Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2497713779 | ||
|
|
79a67e2642 | ||
|
|
d9a2cfe7f9 | ||
|
|
6def232852 | ||
|
|
0df8231334 | ||
|
|
37d4477362 | ||
|
|
611deeda46 | ||
|
|
674aef95b0 |
No files matched your search
+5
-5
@@ -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
|
||||
|
||||
@@ -63,7 +63,7 @@ Ordered by how much each gap blocks someone from switching. Sizes are one-agent
|
||||
tate-chu-yoko), Optical Margin Alignment, the hyphenation and justification options (the Every-line/Single-line
|
||||
composer choice is done), tab leaders, a
|
||||
spell-check dictionary (open licence), Touch Type and Snap to Glyph. Vertical point, area and path type have
|
||||
initial support. 35–48 h across type core and advanced.
|
||||
initial support. 34–47 h across type core and advanced.
|
||||
5. **Brushes, symbols and libraries:** brush options depth; original brush, symbol and graphic-style libraries
|
||||
generated in code (never Adobe's); dynamic symbols; Start Global Edit; brushes driven by pen tilt, bearing and
|
||||
barrel rotation (6D art pens, #372), which needs tablet input beyond pressure on every platform. 20–32 h.
|
||||
@@ -139,7 +139,7 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist
|
||||
- **Geometry and effects:**
|
||||
- Pathfinder (10 exact curve booleans), Offset, Outline Stroke, Simplify, Clean Up, Split Into Grid, Divide Objects Below. Object › Path › Remove Anchor Points (`path.removeAnchors`) removes the direct-selected anchors without opening their paths (the Delete key still deletes them with their segments): the neighbours keep their handle directions and their facing handles are refitted so one cubic follows the two old segments, and straight sides stay straight. The Delete Anchor Point tool uses the same refit. The Control bar, the contextual task bar, the Properties quick actions and the canvas context menu offer it when anchors are selected. With anchors selected, the Control bar and the Properties panel also convert them to corner or smooth (`path.convertAnchors`), connect end points (Join) and cut the path at them (`path.cutAtAnchors`, also on the task bar and the context menu): a closed path opens there and an open one becomes one path per piece, each cut leaving one of its two coincident anchors selected so a drag pulls the path apart.
|
||||
- Live effects with previewing dialogs: Distort & Transform, Path, Convert to Shape, 15 Warp styles, Round Corners, Scribble, Effect → Pathfinder (all 10 operations, live on groups; several loose objects are grouped first, in one undo step), Color Adjustments (Brightness/Contrast, Curves, Levels, Hue/Saturation, Shift to Color, Temperature/Tint, on vectors, live type and embedded images), and raster drop shadow, glows and feather. SVG and PDF export keep live effects (geometry baked; SVG raster effects as filters).
|
||||
- **Type:** Text Wrap, Type on a Path effects (Rainbow/Skew/3D Ribbon/Stair Step/Gravity) and Options (Flip, Align to Path, Spacing; OK keeps the type where it is), type on a path's start, centre and end brackets (Selection and Direct Selection drag them to set where the type runs, slide it along its path and, across the path, flip it: #429), Character and Paragraph Styles (override-preserving redefine), Area Type Options (rows/columns/inset/first baseline, vertical Align Top/Center/Bottom/Justify per row/column, reflowing non-rectangular frames and text wrap), threaded text across any closed shapes, Fit Headline, the Every-line Composer for justified and ragged text (paragraph-wide breaks for an even rag, Single-line per object from the Paragraph panel menu or `text.setFormat {composer}`). Area type resizes like Illustrator's type areas: a bounding-box handle drag (Selection tool) or Area Type Options Width/Height size the frame and the text reflows at its size (threads too); Direct Selection drags a frame corner or edge (`text.reshapeArea`). Point type still scales. The Selection tool shows the type widget beside selected type's bounding box (hollow on point type, filled on area type); double-clicking it converts between them (Type › Convert To Area Type / Convert To Point Type), keeping the text and its styles in place. Variable fonts list every named instance as a style of their family (Figtree Light to Black and their italics, Bahnschrift, Segoe UI Variable), and the instance chosen is shaped, drawn, outlined and measured at its axis settings; PDF and SVG embed it as that instance. Variation axis sliders are not done. Hebrew and Arabic are laid out right to left with the Unicode bidirectional algorithm (embedded Latin and numbers keep their direction, lines put in visual order after wrapping) in point, area and path type, with caret, selection and arrow keys in visual order; each paragraph's direction comes from its first strong character unless Paragraph Direction sets it (Paragraph panel with Show Indic Options, `text.setFormat {direction}`), and new type aligns to the start of its direction. SVG export outlines right-to-left text. Font Size and Leading are combo boxes in the Character and Properties panels (Font Size in the Control bar too, beside the Character link, font family and style): type, step with ↑/↓ or the spinner, scrub the label, or pick a preset (6–72 pt, shown in the type unit; Leading also Auto), each pick one undo step; Kerning and Tracking list -100…200; a size, leading, kerning or tracking the selected text doesn't share shows blank (#458).
|
||||
- **Type:** Text Wrap, Type on a Path effects (Rainbow/Skew/3D Ribbon/Stair Step/Gravity) and Options (Flip, Align to Path, Spacing; OK keeps the type where it is), type on a path's start, centre and end brackets (Selection and Direct Selection drag them to set where the type runs, slide it along its path and, across the path, flip it: #429), Character and Paragraph Styles (override-preserving redefine), Area Type Options (rows/columns/inset/first baseline, vertical Align Top/Center/Bottom/Justify per row/column, reflowing non-rectangular frames and text wrap), threaded text across any closed shapes, Fit Headline, the Every-line Composer for justified and ragged text (paragraph-wide breaks for an even rag, Single-line per object from the Paragraph panel menu or `text.setFormat {composer}`). Area type resizes like Illustrator's type areas: a bounding-box handle drag (Selection tool) or Area Type Options Width/Height size the frame and the text reflows at its size (threads too); Direct Selection drags a frame corner or edge (`text.reshapeArea`). Point type still scales. 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.
|
||||
- **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).
|
||||
@@ -176,7 +176,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, Area Type Options (with Width/Height and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs, OpenType panel, Find Font, installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import, variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel, Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; tab leaders, spell check, vertical type pending | 45–60 |
|
||||
| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | 🟡 Character/Paragraph Styles, 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 |
|
||||
| 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 |
|
||||
@@ -211,7 +211,7 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale)
|
||||
| Live vector effects | 5 | 85% | Outline Object, Pathfinder Hard/Soft Mix and Trap, SVG Filters | 6–10 |
|
||||
| Raster effects (Effect Gallery, Document Raster Effects Settings) | 4 | 20% | ~55 Photoshop-style filters (Artistic, Brush Strokes, Distort, Pixelate, Sketch, Stylize, Texture, Video) and the Effect Gallery; Document Raster Effects Settings and raster effects in PDF are done | 28–42 |
|
||||
| 3D and Materials | 4 | 0% | Extrude & Bevel, Revolve, Inflate, Rotate, lighting, materials (software renderer) | 50–80 |
|
||||
| Type core | 9 | 79% | Middle Eastern features beyond bidi layout and Paragraph Direction (Character Direction, digit types, kashidas, the Middle Eastern composers, editable bidirectional SVG text, a split caret where directions meet); Hyphenation… and Justification… options (Every-line Composer for justified and ragged text, per object, is done; it is tuned by eye, not yet compared side by side with Illustrator; mixed type sizes in a paragraph still break single-line), Optical Margin Alignment, paragraph spacing limit for vertically justified area type, hidden characters, Transform Again after a type-area resize (it scales the type), partial selection of type-area anchors by marquee | 14–19 |
|
||||
| Type 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, 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 |
|
||||
| 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 |
|
||||
|
||||
@@ -34,6 +34,7 @@ mod window;
|
||||
use vectorcraft_engine::Session;
|
||||
use vectorcraft_engine::cmd::fileio;
|
||||
use vectorcraft_ui_egui::graphics::GraphicsLoss;
|
||||
use vectorcraft_ui_egui::picks::PickRequest;
|
||||
use vectorcraft_ui_egui::{ClipboardProbeFactory, FilePick, Services, VectorcraftApp};
|
||||
|
||||
struct App {
|
||||
@@ -185,9 +186,22 @@ fn save_prefs(app: &VectorcraftApp) {
|
||||
}
|
||||
}
|
||||
|
||||
/// A native file dialog showing `pick`'s file types, folder and suggested name.
|
||||
fn file_dialog(pick: &FilePick) -> rfd::FileDialog {
|
||||
let d = pick.filters.iter().fold(rfd::FileDialog::new(), |d, (name, exts)| d.add_filter(*name, exts));
|
||||
/// The window file dialogs belong to.
|
||||
type Parent = Option<std::sync::Arc<winit::window::Window>>;
|
||||
|
||||
/// A native file dialog for `request` over `parent` (Windows and Linux, where the portal then
|
||||
/// shows it over the window and keeps it in front; macOS shows them as before).
|
||||
fn file_dialog(request: &PickRequest, parent: &Parent) -> rfd::FileDialog {
|
||||
let d = match parent {
|
||||
Some(w) if !cfg!(target_os = "macos") => rfd::FileDialog::new().set_parent(&**w),
|
||||
_ => rfd::FileDialog::new(),
|
||||
};
|
||||
let pick = match request {
|
||||
PickRequest::Open(pick) | PickRequest::Save(pick) => pick,
|
||||
PickRequest::OpenMany => return fileio::place_filters().fold(d.set_title("Place"), |d, (name, exts)| d.add_filter(name, exts)),
|
||||
PickRequest::Folder => return d,
|
||||
};
|
||||
let d = pick.filters.iter().fold(d, |d, (name, exts)| d.add_filter(*name, exts));
|
||||
let d = match &pick.folder {
|
||||
Some(folder) => d.set_directory(folder),
|
||||
None => d,
|
||||
@@ -195,6 +209,28 @@ fn file_dialog(pick: &FilePick) -> rfd::FileDialog {
|
||||
if pick.name.is_empty() { d } else { d.set_file_name(&pick.name) }
|
||||
}
|
||||
|
||||
/// Show `dialog` for `request` (on the calling thread, until it closes) → the paths picked.
|
||||
fn show_dialog(dialog: rfd::FileDialog, request: &PickRequest) -> Vec<String> {
|
||||
let paths = match request {
|
||||
PickRequest::Open(_) => dialog.pick_file().into_iter().collect(),
|
||||
PickRequest::OpenMany => dialog.pick_files().unwrap_or_default(),
|
||||
PickRequest::Save(pick) => {
|
||||
// The Templates folder may not exist yet.
|
||||
if let Some(folder) = &pick.folder {
|
||||
let _ = std::fs::create_dir_all(folder);
|
||||
}
|
||||
dialog.save_file().into_iter().collect()
|
||||
}
|
||||
PickRequest::Folder => dialog.pick_folder().into_iter().collect(),
|
||||
};
|
||||
paths.into_iter().map(|p| p.to_string_lossy().to_string()).collect()
|
||||
}
|
||||
|
||||
/// Show the dialog for `request` over `parent` now → the paths picked.
|
||||
fn pick_now(request: PickRequest, parent: &Parent) -> Vec<String> {
|
||||
show_dialog(file_dialog(&request, parent), &request)
|
||||
}
|
||||
|
||||
/// File → Show in Folder: select `path` in Finder / Explorer, or open its folder elsewhere.
|
||||
fn reveal(path: &str) -> Result<(), String> {
|
||||
reveal_command(path).spawn().map(|_| ()).map_err(|e| format!("can't show {path}: {e}"))
|
||||
@@ -230,25 +266,31 @@ fn write_file(path: &str, bytes: &[u8]) -> Result<(), String> {
|
||||
fileio::write_atomic(std::path::Path::new(path), bytes).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
fn services() -> Services {
|
||||
/// Linux: show the dialog for `request` over `parent` on a thread of its own, answering on the
|
||||
/// receiver. Shown on the UI thread, nothing would answer the compositor meanwhile, which then
|
||||
/// offers to kill the window as not responding (#592).
|
||||
fn start_pick(request: PickRequest, parent: &Parent) -> Option<std::sync::mpsc::Receiver<Vec<String>>> {
|
||||
let dialog = file_dialog(&request, parent);
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
std::thread::Builder::new()
|
||||
.name("file-dialog".into())
|
||||
.spawn(move || {
|
||||
// The app gone meanwhile has no use for the answer.
|
||||
let _ = tx.send(show_dialog(dialog, &request));
|
||||
})
|
||||
.ok()?;
|
||||
Some(rx)
|
||||
}
|
||||
|
||||
fn services(parent: Parent) -> Services {
|
||||
let (p1, p2, p3, p4, p5) = (parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent);
|
||||
Services {
|
||||
pick_open: Some(Box::new(|pick: &FilePick| file_dialog(pick).pick_file().map(|p| p.to_string_lossy().to_string()))),
|
||||
pick_open_multi: Some(Box::new(|| {
|
||||
fileio::place_filters()
|
||||
.fold(rfd::FileDialog::new().set_title("Place"), |d, (name, exts)| d.add_filter(name, exts))
|
||||
.pick_files()
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.map(|p| p.to_string_lossy().to_string())
|
||||
.collect()
|
||||
})),
|
||||
pick_save: Some(Box::new(|pick: &FilePick| {
|
||||
// The Templates folder may not exist yet.
|
||||
if let Some(folder) = &pick.folder {
|
||||
let _ = std::fs::create_dir_all(folder);
|
||||
}
|
||||
file_dialog(pick).save_file().map(|p| p.to_string_lossy().to_string())
|
||||
})),
|
||||
pick_open: Some(Box::new(move |pick: &FilePick| pick_now(PickRequest::Open(pick.clone()), &p1).into_iter().next())),
|
||||
pick_open_multi: Some(Box::new(move || pick_now(PickRequest::OpenMany, &p2))),
|
||||
pick_save: Some(Box::new(move |pick: &FilePick| pick_now(PickRequest::Save(pick.clone()), &p3).into_iter().next())),
|
||||
// Windows and macOS dialogs run the window's events while they are open; Linux's don't.
|
||||
start_pick: cfg!(all(unix, not(target_os = "macos")))
|
||||
.then(|| Box::new(move |request: PickRequest| start_pick(request, &p5)) as vectorcraft_ui_egui::picks::StartPick),
|
||||
read: Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))),
|
||||
write: Some(Box::new(write_file)),
|
||||
// Background Save and Export write from a worker thread.
|
||||
@@ -266,7 +308,7 @@ fn services() -> Services {
|
||||
reveal: Some(Box::new(reveal)),
|
||||
// Links panel: Edit Original; Package: Show Package. Relink to Folder and Package pick folders.
|
||||
open_file: Some(Box::new(open_file)),
|
||||
pick_folder: Some(Box::new(|| rfd::FileDialog::new().pick_folder().map(|p| p.to_string_lossy().to_string()))),
|
||||
pick_folder: Some(Box::new(move || pick_now(PickRequest::Folder, &p4).into_iter().next())),
|
||||
// File → Print: the system's printers and print queue.
|
||||
print: Some(Box::new(printing::SystemPrint)),
|
||||
..Default::default()
|
||||
@@ -397,7 +439,7 @@ fn main() -> std::process::ExitCode {
|
||||
"VectorCraft",
|
||||
options,
|
||||
Box::new(move |cc| {
|
||||
let mut app = VectorcraftApp::new(Session::new(), services());
|
||||
let mut app = VectorcraftApp::new(Session::new(), services(cc.winit_window().cloned()));
|
||||
load_prefs(&mut app, saved);
|
||||
// Fit the window to its monitor, or put it back where it was (still hidden).
|
||||
if let Some(w) = cc.winit_window() {
|
||||
|
||||
@@ -82,8 +82,9 @@ pub use setup::{Background, DocSetup, ExportText, GridSize, Quotes};
|
||||
pub use slices::{CellAlign, CellVAlign, Slice, SliceArea, SliceKind, SliceOptions, SliceSource};
|
||||
pub use style_libs::StyleLibrary;
|
||||
pub use text::{
|
||||
AreaOptions, Burasagari, CharAlign, CharPosition, CharStyle, Composer, FirstBaseline, Justify, LeadingModel, Mojikumi, ParaDirection, ParaStyle,
|
||||
PathAlign, PathEffect, ScriptMetrics, TabAlign, TabStop, TextKind, TextObject, TextRun, TextStyleDef, TextWrap, VerticalAlign, WrapShape,
|
||||
AreaFit, AreaOptions, Burasagari, CharAlign, CharPosition, CharStyle, Composer, FirstBaseline, 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;
|
||||
|
||||
@@ -664,6 +664,9 @@ pub struct AreaOptions {
|
||||
pub first_baseline_min: f64,
|
||||
/// Vertical alignment of the lines in each row/column.
|
||||
pub vertical_align: VerticalAlign,
|
||||
/// How the frame and its text fit each other (Auto Size, Shrink Text to Fit).
|
||||
#[serde(skip_serializing_if = "crate::skip::is_default")]
|
||||
pub fit: AreaFit,
|
||||
}
|
||||
|
||||
impl Default for AreaOptions {
|
||||
@@ -676,6 +679,67 @@ impl Default for AreaOptions {
|
||||
first_baseline: FirstBaseline::Ascent,
|
||||
first_baseline_min: 0.0,
|
||||
vertical_align: VerticalAlign::Top,
|
||||
fit: AreaFit::None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How area type and its frame fit each other. Serialized as `"none"`, `"autoHeight"` or
|
||||
/// `{"shrinkText": {"minPercent": 50}}`.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AreaFit {
|
||||
/// The frame keeps its size; text that doesn't fit overflows.
|
||||
#[default]
|
||||
None,
|
||||
/// The frame's height follows the text (Illustrator's Auto Size): resolved by the engine after
|
||||
/// each edit, for rectangular frames of horizontal type in one row.
|
||||
AutoHeight,
|
||||
/// Text that overflows is scaled down (size, leading and baseline shift; not paragraph
|
||||
/// spacing) by the largest factor down to `min_percent` % that makes it fit, at layout time.
|
||||
ShrinkText {
|
||||
#[serde(rename = "minPercent", default = "AreaFit::default_min_percent")]
|
||||
min_percent: f64,
|
||||
},
|
||||
}
|
||||
|
||||
impl AreaFit {
|
||||
/// The smallest Shrink Text to Fit percentage allowed.
|
||||
pub const MIN_PERCENT: f64 = 10.0;
|
||||
/// The Shrink Text to Fit percentage new settings start with.
|
||||
pub const DEFAULT_MIN_PERCENT: f64 = 50.0;
|
||||
fn default_min_percent() -> f64 {
|
||||
Self::DEFAULT_MIN_PERCENT
|
||||
}
|
||||
/// Its id: `none`, `autoHeight` or `shrinkText`.
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
AreaFit::None => "none",
|
||||
AreaFit::AutoHeight => "autoHeight",
|
||||
AreaFit::ShrinkText { .. } => "shrinkText",
|
||||
}
|
||||
}
|
||||
/// The fit an id names (case, spaces, dashes and underscores ignored), with `min_percent`
|
||||
/// for Shrink Text (clamped to 10..100; a non-finite value gives the default).
|
||||
pub fn parse(id: &str, min_percent: Option<f64>) -> Option<Self> {
|
||||
match id.to_ascii_lowercase().replace([' ', '-', '_'], "").as_str() {
|
||||
"none" | "off" => Some(AreaFit::None),
|
||||
"autoheight" | "autosize" => Some(AreaFit::AutoHeight),
|
||||
"shrinktext" | "shrinktexttofit" | "shrink" => {
|
||||
Some(AreaFit::ShrinkText { min_percent: Self::clamp_percent(min_percent.unwrap_or(Self::DEFAULT_MIN_PERCENT)) })
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// A Shrink Text minimum percentage within 10..100 (the default when not finite).
|
||||
pub fn clamp_percent(p: f64) -> f64 {
|
||||
if p.is_finite() { p.clamp(Self::MIN_PERCENT, 100.0) } else { Self::DEFAULT_MIN_PERCENT }
|
||||
}
|
||||
/// Shrink Text's minimum scale factor (0.1..1), if this is Shrink Text.
|
||||
pub fn min_scale(self) -> Option<f64> {
|
||||
match self {
|
||||
AreaFit::ShrinkText { min_percent } => Some(Self::clamp_percent(min_percent) / 100.0),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,7 +50,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Create Text",
|
||||
[],
|
||||
None,
|
||||
"{x, y, text, vertical?: bool = false, size?: pt, font?: family, style?, color?, area?: {width, height}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id}",
|
||||
"{x, y, text, vertical?: bool = false, size?: pt, font?: family, style?, color?, area?: {width, height, fit?: none|autoHeight|shrinkText, fitMinPercent?}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\" (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
|
||||
),
|
||||
@@ -415,10 +415,12 @@ fn text_create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let w = f64_or(a, "width", 200.0);
|
||||
let h = f64_or(a, "height", 100.0);
|
||||
t.kind = vectorcraft_doc::TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, w, h)) };
|
||||
t.area.fit = new_area_fit(s, a, "text.create")?;
|
||||
}
|
||||
if bool_or(p, "placeholder", false) {
|
||||
super::typemenu::fill_with_placeholder(&mut t);
|
||||
} else {
|
||||
// Lays the text out (and sizes an Auto Size frame).
|
||||
super::typecmd::refresh_bounds(&mut t);
|
||||
}
|
||||
add_node(s, "Type", NodeKind::Text(Box::new(t)), Appearance::default(), None)
|
||||
@@ -471,6 +473,13 @@ pub(crate) fn new_type_alignment(s: &mut Session, p: &Value, cmd: &str, t: &mut
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The fit new area type gets: `fit`/`fitMinPercent` from `p` (as `text.areaOptions` takes
|
||||
/// them), else Auto Size when the "Auto Size New Area Type" preference is on.
|
||||
pub(crate) fn new_area_fit(s: &Session, p: &Value, c: &str) -> Result<vectorcraft_doc::AreaFit> {
|
||||
let default = if s.prefs.auto_size_area_type { vectorcraft_doc::AreaFit::AutoHeight } else { vectorcraft_doc::AreaFit::None };
|
||||
Ok(super::typecmd::fit_param(p, default, c)?.unwrap_or(default))
|
||||
}
|
||||
|
||||
/// The character style new type gets: `size`, `font`, `style` and `color` from `p`, else the
|
||||
/// defaults, filled with the current fill unless that is None or white (black then).
|
||||
pub(crate) fn new_type_style(s: &Session, p: &Value) -> CharStyle {
|
||||
|
||||
@@ -45,7 +45,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Area / Path Type",
|
||||
[],
|
||||
None,
|
||||
"{path: id, mode: \"area\"|\"onPath\", text?: \"\", vertical?: bool = false, at?: [x, y] (on-path start: nearest point), size?, font?, placeholder?: bool (placeholder text instead, as text.create), leadingModel?, charAlign? (as text.create)} turn a path into an area-type frame or a type-on-a-path baseline (the path's paint is dropped) → {id}",
|
||||
"{path: id, mode: \"area\"|\"onPath\", text?: \"\", vertical?: bool = false, at?: [x, y] (on-path start: nearest point), size?, font?, fit?: none|autoHeight|shrinkText, fitMinPercent? (area: as text.areaOptions; default autoHeight when the autoSizeAreaType preference is on), placeholder?: bool (placeholder text instead, as text.create), leadingModel?, charAlign? (as text.create)} turn a path into an area-type frame or a type-on-a-path baseline (the path's paint is dropped) → {id}",
|
||||
has_doc,
|
||||
create_in_path
|
||||
),
|
||||
@@ -472,6 +472,9 @@ fn create_in_path(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
cached_baselines: Vec::new(),
|
||||
};
|
||||
super::create::new_type_alignment(s, p, C, &mut t)?;
|
||||
if !on_path {
|
||||
t.area.fit = super::create::new_area_fit(s, p, C)?;
|
||||
}
|
||||
if bool_or(p, "placeholder", false) {
|
||||
super::typemenu::fill_with_placeholder(&mut t);
|
||||
} else {
|
||||
|
||||
@@ -93,6 +93,16 @@ pub(crate) fn reflow(before: &Document, doc: &mut Document) {
|
||||
continue;
|
||||
}
|
||||
vectorcraft_text::edit::normalize(&mut story);
|
||||
if live.len() >= 2 {
|
||||
// Threaded frames keep their size: Auto Size is off for them (as in Illustrator).
|
||||
for id in &live {
|
||||
if text_of(doc, *id).is_some_and(|t| t.area.fit == vectorcraft_doc::AreaFit::AutoHeight)
|
||||
&& let Some(NodeKind::Text(t)) = doc.node_mut(*id).map(|n| &mut n.kind)
|
||||
{
|
||||
t.area.fit = vectorcraft_doc::AreaFit::None;
|
||||
}
|
||||
}
|
||||
}
|
||||
let frames: Vec<TextObject> = live.iter().filter_map(|id| text_of(doc, *id).cloned()).collect();
|
||||
let refs: Vec<&TextObject> = frames.iter().collect();
|
||||
let parts = vectorcraft_text::thread::distribute(vectorcraft_text::FontDb::global(), &refs, &story);
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, Justify, Node, NodeId, NodeKind, TextObject};
|
||||
use vectorcraft_doc::{AreaFit, Document, Justify, Node, NodeId, NodeKind, TextObject};
|
||||
use vectorcraft_geom::{Affine, PathData, Vec2};
|
||||
|
||||
use super::edit::selected_roots;
|
||||
@@ -48,7 +48,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Area Type Options…",
|
||||
["Type"],
|
||||
None,
|
||||
"{ids?, width?: pt, height?: pt, rows?, columns?, gutter?: pt, inset?: pt, firstBaseline?: ascent|capHeight|xHeight|leading|fixed, firstBaselineMin?: pt, verticalAlign?: top|center|bottom|justify} set the selected area type's options; width and height size the type area from its top-left corner, along the type's own axes, and the text reflows at its size (none given: query) → the first object's options",
|
||||
"{ids?, width?: pt, height?: pt, rows?, columns?, gutter?: pt, inset?: pt, firstBaseline?: ascent|capHeight|xHeight|leading|fixed, firstBaselineMin?: pt, verticalAlign?: top|center|bottom|justify, fit?: none|autoHeight|shrinkText, fitMinPercent?: 10..100} set the selected area type's options; width and height size the type area from its top-left corner, along the type's own axes, and the text reflows at its size (with fit autoHeight, Auto Size, the frame's height follows the text after every edit and height is ignored; setting the height by hand turns it off); fit shrinkText scales overflowing text down (size, leading, baseline shift) by the largest factor down to fitMinPercent % (default 50) that makes it fit (none given: query) → the first object's options, plus overflow (the text doesn't fit its frame) and fitScale (Shrink Text's factor, 1 unshrunk)",
|
||||
has_selection,
|
||||
area_options
|
||||
),
|
||||
@@ -97,13 +97,94 @@ fn orientation(s: &mut Session, p: &Value, vertical: bool) -> Result<Value> {
|
||||
Ok(json!({"vertical": vertical, "ids": ids.iter().map(|id| id.0).collect::<Vec<_>>()}))
|
||||
}
|
||||
|
||||
/// Recompute the layout caches (bounds and baselines) after a text edit.
|
||||
/// Recompute the layout caches (bounds and baselines) after a text edit. Every engine text edit ends here (typing
|
||||
/// through `text.editRange` too), inside its `Session::edit`, so this is where Auto Size area type
|
||||
/// ([`vectorcraft_doc::AreaFit::AutoHeight`]) fits its frame to the text: part of the same undo
|
||||
/// step as the edit.
|
||||
pub(crate) fn refresh_bounds(t: &mut TextObject) {
|
||||
auto_height(t);
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
|
||||
t.cached_bounds = Some(lay.bounds);
|
||||
t.cached_baselines = lay.baselines();
|
||||
}
|
||||
|
||||
/// The text-space bounds of area type's frame, when Auto Size can fit it: a rectangle (one
|
||||
/// subpath, as large as its bounds) of horizontal type in one row, with some height.
|
||||
fn auto_height_frame(t: &TextObject) -> Option<vectorcraft_geom::Rect> {
|
||||
use vectorcraft_geom::Shape;
|
||||
let vectorcraft_doc::TextKind::Area { frame } = &t.kind else { return None };
|
||||
if t.area.fit != vectorcraft_doc::AreaFit::AutoHeight || t.vertical || t.area.rows > 1 || frame.subpaths.len() != 1 {
|
||||
return None;
|
||||
}
|
||||
let b = frame.bounds()?;
|
||||
let area = frame.to_bezpath().area().abs();
|
||||
let finite = [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite());
|
||||
(finite && b.height() > 1e-6 && b.width() > 1e-6 && (area - b.area()).abs() <= b.area() * 1e-6).then_some(b)
|
||||
}
|
||||
|
||||
/// Auto Size: move the bottom of a rectangular area type frame to just below its last line (plus
|
||||
/// the inset), so the frame's height follows the text. Text in several columns gets the least
|
||||
/// height (to 0.01 pt) at which it fits. True when the frame changed.
|
||||
fn auto_height(t: &mut TextObject) -> bool {
|
||||
use vectorcraft_geom::Shape;
|
||||
let Some(b) = auto_height_frame(t) else { return false };
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
// Lay out in a frame as tall as the canvas allows: everything the width lets through flows.
|
||||
let tall = (crate::MAX_COORD - b.y0).min(1.0e5);
|
||||
if tall <= 1.0 {
|
||||
return false;
|
||||
}
|
||||
let mut probe = t.clone();
|
||||
let with_size = |probe: &mut TextObject, w: f64, h: f64| {
|
||||
if let vectorcraft_doc::TextKind::Area { frame } = &mut probe.kind {
|
||||
*frame = PathData::from_bezpath(&vectorcraft_geom::Rect::new(b.x0, b.y0, b.x0 + w, b.y0 + h).to_path(0.1));
|
||||
}
|
||||
};
|
||||
// Columns: all the text in one column as wide as each of them is surely tall enough.
|
||||
let cols = t.area.columns.max(1);
|
||||
let col_w = if cols > 1 { ((b.width() - t.area.gutter.max(0.0) * (cols - 1) as f64) / cols as f64).max(1.0) } else { b.width() };
|
||||
with_size(&mut probe, col_w, tall);
|
||||
probe.area.columns = 1;
|
||||
let lay = vectorcraft_text::layout(db, &probe);
|
||||
let inset = t.area.inset.max(0.0);
|
||||
let Some(bottom) = lay.lines.iter().map(|l| l.baseline + l.descent).filter(|y| y.is_finite()).reduce(f64::max) else { return false };
|
||||
// The layout's fit test is `baseline + descent <= bottom + 0.01`: the last line fits exactly.
|
||||
let mut h = (bottom + inset - b.y0).clamp(1.0, tall);
|
||||
if cols > 1 {
|
||||
// The least height (to 0.01 pt) at which the columns hold the text.
|
||||
probe.area.columns = cols;
|
||||
let fits = |probe: &mut TextObject, h: f64| {
|
||||
with_size(probe, b.width(), h);
|
||||
!vectorcraft_text::layout(db, probe).overflow
|
||||
};
|
||||
if !fits(&mut probe, h) {
|
||||
return false;
|
||||
}
|
||||
let (mut lo, mut hi) = (1.0, h);
|
||||
for _ in 0..24 {
|
||||
if hi - lo <= 0.01 {
|
||||
break;
|
||||
}
|
||||
let mid = (lo + hi) * 0.5;
|
||||
if fits(&mut probe, mid) { hi = mid } else { lo = mid }
|
||||
}
|
||||
h = hi;
|
||||
}
|
||||
if (h - b.height()).abs() <= 1e-6 {
|
||||
return false;
|
||||
}
|
||||
// Scale the frame about its top edge, keeping its anchors (and their order) as they are.
|
||||
let a = Affine::translate((0.0, b.y0)) * Affine::scale_non_uniform(1.0, h / b.height()) * Affine::translate((0.0, -b.y0));
|
||||
let vectorcraft_doc::TextKind::Area { frame } = &mut t.kind else { return false };
|
||||
let mut next = frame.clone();
|
||||
next.transform(a);
|
||||
if next.bounds().is_none_or(|nb| ![nb.x0, nb.y0, nb.x1, nb.y1].iter().all(|v| v.is_finite() && v.abs() <= crate::MAX_COORD)) {
|
||||
return false;
|
||||
}
|
||||
*frame = next;
|
||||
true
|
||||
}
|
||||
|
||||
/// Text objects among `ids` and their descendants.
|
||||
fn text_ids(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
|
||||
let mut out = vec![];
|
||||
@@ -292,10 +373,18 @@ pub(crate) fn reshape_area_with(t: &mut TextObject, f: impl FnOnce(&mut TextObje
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
let height = |t: &TextObject| auto_height_frame(t).map(|b| b.height());
|
||||
let was = height(t);
|
||||
if !(f(t) && within(t)) {
|
||||
t.kind = before;
|
||||
return false;
|
||||
}
|
||||
// Setting the height by hand turns Auto Size off (as in Illustrator); a new width keeps it.
|
||||
if let (Some(a), Some(b)) = (was, height(t))
|
||||
&& (a - b).abs() > 1e-6
|
||||
{
|
||||
t.area.fit = vectorcraft_doc::AreaFit::None;
|
||||
}
|
||||
refresh_bounds(t);
|
||||
true
|
||||
}
|
||||
@@ -334,6 +423,60 @@ fn size_area(t: &mut TextObject, w: Option<f64>, h: Option<f64>) -> bool {
|
||||
reshape_area_with(t, |t| t.transform_area(a))
|
||||
}
|
||||
|
||||
/// The fit `p` asks for (`fit`: none|autoHeight|shrinkText or `{"shrinkText": {"minPercent"}}`,
|
||||
/// `fitMinPercent`), starting from `cur`. None when `p` sets neither (or only `fitMinPercent`
|
||||
/// while the fit isn't Shrink Text).
|
||||
pub(crate) fn fit_param(p: &Value, cur: AreaFit, c: &str) -> Result<Option<AreaFit>> {
|
||||
let min = p.get("fitMinPercent").and_then(Value::as_f64);
|
||||
let cur_min = match cur {
|
||||
AreaFit::ShrinkText { min_percent } => Some(min_percent),
|
||||
_ => None,
|
||||
};
|
||||
let fit = match p.get("fit") {
|
||||
None | Some(Value::Null) => match (cur, min) {
|
||||
(AreaFit::ShrinkText { .. }, Some(m)) => AreaFit::ShrinkText { min_percent: m },
|
||||
_ => return Ok(None),
|
||||
},
|
||||
Some(Value::String(id)) => {
|
||||
AreaFit::parse(id, min.or(cur_min)).ok_or_else(|| bad(c, format!("fit must be none|autoHeight|shrinkText, got {id}")))?
|
||||
}
|
||||
Some(v) => match serde_json::from_value::<AreaFit>(v.clone()).map_err(|e| bad(c, format!("bad fit: {e}")))? {
|
||||
AreaFit::ShrinkText { min_percent } => AreaFit::ShrinkText { min_percent: min.unwrap_or(min_percent) },
|
||||
f => f,
|
||||
},
|
||||
};
|
||||
Ok(Some(match fit {
|
||||
AreaFit::ShrinkText { min_percent } => AreaFit::ShrinkText { min_percent: AreaFit::clamp_percent(min_percent) },
|
||||
f => f,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Area type's options as `text.areaOptions` reports them: the Area Type Options with `fit` as
|
||||
/// its id and `fitMinPercent` beside it, the frame's `width` and `height`, and whether the text
|
||||
/// `overflow`s its frame at `fitScale` (Shrink Text to Fit's factor; 1 unshrunk).
|
||||
pub(crate) fn area_options_json(t: &TextObject) -> Result<Value> {
|
||||
let mut v = serde_json::to_value(&t.area).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
|
||||
if let Some(o) = v.as_object_mut() {
|
||||
o.insert("fit".into(), json!(t.area.fit.id()));
|
||||
let min = match t.area.fit {
|
||||
AreaFit::ShrinkText { min_percent } => min_percent,
|
||||
_ => AreaFit::DEFAULT_MIN_PERCENT,
|
||||
};
|
||||
o.insert("fitMinPercent".into(), json!(min));
|
||||
if let Some((w, h, _)) = area_size(t) {
|
||||
o.insert("width".into(), json!(w));
|
||||
o.insert("height".into(), json!(h));
|
||||
}
|
||||
o.insert("overflow".into(), json!(lay.overflow));
|
||||
o.insert("fitScale".into(), json!(lay.fit_scale));
|
||||
}
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// The [`vectorcraft_doc::AreaOptions`] keys `text.areaOptions` merges as they are.
|
||||
const AREA_KEYS: [&str; 7] = ["rows", "columns", "gutter", "inset", "firstBaseline", "firstBaselineMin", "verticalAlign"];
|
||||
|
||||
fn area_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "text.areaOptions";
|
||||
let ids: Vec<NodeId> = {
|
||||
@@ -343,34 +486,35 @@ fn area_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let first = *ids.first().ok_or_else(|| bad(C, "select area type (text in a frame)"))?;
|
||||
let options = |s: &Session| -> Result<Value> {
|
||||
let t = area_text(s.doc()?.doc.node(first)).ok_or_else(|| bad(C, "select area type (text in a frame)"))?;
|
||||
let mut v = serde_json::to_value(&t.area).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
if let (Some(o), Some((w, h, _))) = (v.as_object_mut(), area_size(t)) {
|
||||
o.insert("width".into(), json!(w));
|
||||
o.insert("height".into(), json!(h));
|
||||
}
|
||||
Ok(v)
|
||||
area_options_json(t)
|
||||
};
|
||||
let mut v = options(s)?;
|
||||
let size = |k: &str| p.get(k).and_then(Value::as_f64).map(|x| x.clamp(1.0, 100_000.0));
|
||||
let (w, h) = (size("width"), size("height"));
|
||||
let mut changed = w.is_some() || h.is_some();
|
||||
let cur = area_text(s.doc()?.doc.node(first)).map(|t| t.area.clone()).unwrap_or_default();
|
||||
let fit = fit_param(p, cur.fit, C)?;
|
||||
let mut v = serde_json::to_value(&cur).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
let size = |k: &str| p.get(k).and_then(Value::as_f64).filter(|x| x.is_finite()).map(|x| x.clamp(1.0, 100_000.0));
|
||||
let (w, mut h) = (size("width"), size("height"));
|
||||
let mut changed = w.is_some() || h.is_some() || fit.is_some();
|
||||
if let (Some(o), Some(src)) = (v.as_object_mut(), p.as_object()) {
|
||||
for (k, val) in src {
|
||||
if o.contains_key(k) && !matches!(k.as_str(), "ids" | "width" | "height") {
|
||||
o.insert(k.clone(), val.clone());
|
||||
changed = true;
|
||||
}
|
||||
for (k, val) in src.iter().filter(|(k, _)| AREA_KEYS.contains(&k.as_str())) {
|
||||
o.insert(k.clone(), val.clone());
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if !changed {
|
||||
return Ok(v);
|
||||
return options(s);
|
||||
}
|
||||
let mut opts: vectorcraft_doc::AreaOptions = serde_json::from_value(v).map_err(|e| bad(C, e.to_string()))?;
|
||||
opts.rows = opts.rows.clamp(1, 100);
|
||||
opts.columns = opts.columns.clamp(1, 100);
|
||||
opts.gutter = opts.gutter.clamp(0.0, 10_000.0);
|
||||
opts.inset = opts.inset.clamp(0.0, 10_000.0);
|
||||
opts.first_baseline_min = opts.first_baseline_min.clamp(0.0, 10_000.0);
|
||||
let finite = |x: f64| if x.is_finite() { x } else { 0.0 };
|
||||
opts.gutter = finite(opts.gutter).clamp(0.0, 10_000.0);
|
||||
opts.inset = finite(opts.inset).clamp(0.0, 10_000.0);
|
||||
opts.first_baseline_min = finite(opts.first_baseline_min).clamp(0.0, 10_000.0);
|
||||
opts.fit = fit.unwrap_or(cur.fit);
|
||||
if opts.fit == AreaFit::AutoHeight {
|
||||
// Auto Size sets the height (Illustrator's dialog turns the Height field off).
|
||||
h = None;
|
||||
}
|
||||
s.edit("Area Type Options", |d, _| {
|
||||
for id in &ids {
|
||||
if let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) {
|
||||
|
||||
@@ -80,7 +80,19 @@ pub fn node_summary_opts(n: &Node, opts: SummaryOpts) -> Value {
|
||||
v["anchors"] = json!(path.anchor_count());
|
||||
v["closed"] = json!(path.is_closed());
|
||||
}
|
||||
NodeKind::Text(t) => v["text"] = json!(t.plain_text()),
|
||||
NodeKind::Text(t) => {
|
||||
v["text"] = json!(t.plain_text());
|
||||
// Area type and type on a path: does the text fit (the red overflow "+")? Area type
|
||||
// also reports its fit and Shrink Text's factor (1 unshrunk).
|
||||
if !matches!(t.kind, vectorcraft_doc::TextKind::Point) {
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
|
||||
v["overflow"] = json!(lay.overflow);
|
||||
if matches!(t.kind, vectorcraft_doc::TextKind::Area { .. }) {
|
||||
v["fit"] = json!(t.area.fit.id());
|
||||
v["fitScale"] = json!(lay.fit_scale);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if let Some(ch) = n.children() {
|
||||
|
||||
@@ -1293,6 +1293,8 @@ mod tests_adjust;
|
||||
#[cfg(test)]
|
||||
mod tests_appearance;
|
||||
#[cfg(test)]
|
||||
mod tests_areafit;
|
||||
#[cfg(test)]
|
||||
mod tests_assets;
|
||||
#[cfg(test)]
|
||||
mod tests_attributes;
|
||||
|
||||
@@ -0,0 +1,242 @@
|
||||
//! Area type fitting: Auto Size (the frame's height follows the text), Shrink Text to Fit, and
|
||||
//! overflow reporting.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{AreaFit, NodeKind, TextKind, TextObject};
|
||||
use vectorcraft_geom::Rect;
|
||||
use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey};
|
||||
|
||||
use super::*;
|
||||
|
||||
const STORY: &str = "The quick brown fox jumps over the lazy dog. A second sentence follows the first one here. Then a third one ends it.";
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn area(s: &mut Session, w: f64, h: f64, text: &str, extra: Value) -> NodeId {
|
||||
let mut a = json!({"width": w, "height": h});
|
||||
if let (Some(a), Some(e)) = (a.as_object_mut(), extra.as_object()) {
|
||||
a.extend(e.clone());
|
||||
}
|
||||
let id = s.execute("text.create", &json!({"x": 40, "y": 40, "size": 12, "area": a, "text": text})).unwrap()["id"].as_u64().unwrap();
|
||||
NodeId(id)
|
||||
}
|
||||
|
||||
fn text(s: &Session, id: NodeId) -> TextObject {
|
||||
match &s.doc().unwrap().doc.node(id).unwrap().kind {
|
||||
NodeKind::Text(t) => (**t).clone(),
|
||||
k => panic!("not text: {k:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn frame(s: &Session, id: NodeId) -> Rect {
|
||||
match text(s, id).kind {
|
||||
TextKind::Area { frame } => frame.bounds().unwrap(),
|
||||
k => panic!("not area type: {k:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn overflows(s: &Session, id: NodeId) -> bool {
|
||||
vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &text(s, id)).overflow
|
||||
}
|
||||
|
||||
fn undo_len(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn area_options_set_and_report_the_fit() {
|
||||
let mut s = session();
|
||||
let id = area(&mut s, 120.0, 30.0, STORY, json!({}));
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
let q = s.execute("text.areaOptions", &json!({})).unwrap();
|
||||
assert_eq!((q["fit"].as_str(), q["fitMinPercent"].as_f64()), (Some("none"), Some(50.0)));
|
||||
assert_eq!((q["overflow"].as_bool(), q["fitScale"].as_f64()), (Some(true), Some(1.0)));
|
||||
let n = undo_len(&s);
|
||||
let r = s.execute("text.areaOptions", &json!({"fit": "shrinkText", "fitMinPercent": 20})).unwrap();
|
||||
assert_eq!(undo_len(&s), n + 1);
|
||||
assert_eq!((r["fit"].as_str(), r["fitMinPercent"].as_f64()), (Some("shrinkText"), Some(20.0)));
|
||||
assert_eq!(r["overflow"], false, "{r}");
|
||||
let f = r["fitScale"].as_f64().unwrap();
|
||||
assert!((0.2..1.0).contains(&f), "{f}");
|
||||
assert_eq!(text(&s, id).area.fit, AreaFit::ShrinkText { min_percent: 20.0 });
|
||||
assert_eq!(text(&s, id).runs[0].style.size, 12.0, "the stored size stays");
|
||||
// The minimum alone, clamped; the object form; and bad values.
|
||||
s.execute("text.areaOptions", &json!({"fitMinPercent": 3})).unwrap();
|
||||
assert_eq!(text(&s, id).area.fit, AreaFit::ShrinkText { min_percent: 10.0 });
|
||||
s.execute("text.areaOptions", &json!({"fit": {"shrinkText": {"minPercent": 95}}})).unwrap();
|
||||
assert_eq!(text(&s, id).area.fit, AreaFit::ShrinkText { min_percent: 95.0 });
|
||||
assert_eq!(s.execute("text.areaOptions", &json!({})).unwrap()["overflow"], true, "95 % is not enough");
|
||||
assert!(s.execute("text.areaOptions", &json!({"fit": "squash"})).is_err());
|
||||
assert!(s.execute("text.areaOptions", &json!({"fit": 7})).is_err());
|
||||
// The reply's own keys go back in unchanged (the dialog sends everything).
|
||||
let q = s.execute("text.areaOptions", &json!({})).unwrap();
|
||||
let n = undo_len(&s);
|
||||
let again = s.execute("text.areaOptions", &q).unwrap();
|
||||
assert_eq!(again, q);
|
||||
assert_eq!(undo_len(&s), n + 1);
|
||||
// Undo back to no fit.
|
||||
while text(&s, id).area.fit != AreaFit::None {
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
}
|
||||
assert!(overflows(&s, id));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inspect_reports_overflow_and_fit_scale() {
|
||||
let mut s = session();
|
||||
let id = area(&mut s, 120.0, 30.0, STORY, json!({"fit": "shrinkText", "fitMinPercent": 10}));
|
||||
s.execute("text.create", &json!({"x": 10, "y": 500, "text": "point"})).unwrap();
|
||||
let doc = s.execute("document.inspect", &json!({})).unwrap();
|
||||
let kids = doc["layers"][0]["children"].as_array().unwrap();
|
||||
let node = kids.iter().find(|k| k["id"] == id.0).unwrap();
|
||||
assert_eq!(node["overflow"], false);
|
||||
assert_eq!(node["fit"], "shrinkText");
|
||||
assert!(node["fitScale"].as_f64().unwrap() < 1.0);
|
||||
let point = kids.iter().find(|k| k["id"] != id.0).unwrap();
|
||||
assert!(point.get("overflow").is_none() && point.get("fitScale").is_none(), "point type never overflows");
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("text.areaOptions", &json!({"fit": "none"})).unwrap();
|
||||
let doc = s.execute("document.inspect", &json!({})).unwrap();
|
||||
let node = doc["layers"][0]["children"].as_array().unwrap().iter().find(|k| k["id"] == id.0).unwrap().clone();
|
||||
assert_eq!((node["overflow"].as_bool(), node["fitScale"].as_f64(), node["fit"].as_str()), (Some(true), Some(1.0), Some("none")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_height_follows_edits_in_the_same_undo_step() {
|
||||
let mut s = session();
|
||||
let id = area(&mut s, 200.0, 300.0, "One line", json!({"fit": "autoHeight"}));
|
||||
let one = frame(&s, id);
|
||||
assert!(one.height() < 30.0, "the frame fits one line: {one:?}");
|
||||
assert_eq!((one.x0, one.y0, one.width()), (0.0, 0.0, 200.0), "top and width stay");
|
||||
assert!(!overflows(&s, id));
|
||||
let n = undo_len(&s);
|
||||
s.execute("text.editRange", &json!({"id": id.0, "start": 8, "insert": format!(" {STORY}")})).unwrap();
|
||||
assert_eq!(undo_len(&s), n + 1);
|
||||
let grown = frame(&s, id);
|
||||
assert!(grown.height() > one.height() * 2.0, "{grown:?}");
|
||||
assert!(!overflows(&s, id), "the grown frame holds the text");
|
||||
// Tight: a point less overflows.
|
||||
let mut t = text(&s, id);
|
||||
t.area.fit = AreaFit::None;
|
||||
t.kind = TextKind::Area {
|
||||
frame: vectorcraft_geom::PathData::from_bezpath(&vectorcraft_geom::Shape::to_path(&Rect::new(0.0, 0.0, 200.0, grown.height() - 1.0), 0.1)),
|
||||
};
|
||||
assert!(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).overflow);
|
||||
// Character changes resize it too.
|
||||
s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 0, "end": 3, "size": 40})).unwrap();
|
||||
assert!(frame(&s, id).height() > grown.height());
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(frame(&s, id), grown);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(frame(&s, id), one, "one undo restores the text and the frame");
|
||||
assert_eq!(text(&s, id).plain_text(), "One line");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_height_follows_typing_with_the_type_tool() {
|
||||
let mut s = session();
|
||||
s.prefs.auto_size_area_type = true;
|
||||
// An empty frame (no placeholder text), so its first height is one line.
|
||||
s.prefs.placeholder_text = false;
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool("type", v).unwrap();
|
||||
for (kind, (x, y)) in [(PointerKind::Down, (100.0, 100.0)), (PointerKind::Drag, (300.0, 400.0)), (PointerKind::Up, (300.0, 400.0))] {
|
||||
s.pointer(&PointerEvent::new(kind, x, y), v).unwrap();
|
||||
}
|
||||
let id = s.doc().unwrap().selection.objects[0];
|
||||
assert_eq!(text(&s, id).area.fit, AreaFit::AutoHeight, "the preference gives new area type Auto Size");
|
||||
let empty = frame(&s, id);
|
||||
assert!(empty.height() < 30.0, "{empty:?}");
|
||||
let n = undo_len(&s);
|
||||
for word in STORY.split_inclusive(' ') {
|
||||
s.tool_text(word, v).unwrap();
|
||||
}
|
||||
s.tool_key(ToolKey::Escape, Mods::default(), v).unwrap();
|
||||
assert_eq!(text(&s, id).plain_text(), STORY);
|
||||
assert_eq!(undo_len(&s), n + 1, "one typing step");
|
||||
let typed = frame(&s, id);
|
||||
assert!(typed.height() > empty.height() * 2.0, "{typed:?}");
|
||||
assert!(!overflows(&s, id));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(frame(&s, id), empty);
|
||||
assert_eq!(text(&s, id).plain_text(), "");
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(frame(&s, id), typed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_height_in_columns_and_by_hand() {
|
||||
let mut s = session();
|
||||
let id = area(&mut s, 300.0, 400.0, &STORY.repeat(3), json!({"fit": "autoHeight"}));
|
||||
let one = frame(&s, id).height();
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
// Height is ignored while Auto Size is on.
|
||||
let r = s.execute("text.areaOptions", &json!({"columns": 2, "gutter": 12, "height": 500})).unwrap();
|
||||
let two = r["height"].as_f64().unwrap();
|
||||
assert!(two < 500.0 && two > one * 0.5, "{one} → {two}");
|
||||
assert_eq!(r["overflow"], false);
|
||||
assert_eq!(r["fit"], "autoHeight");
|
||||
// The least height the two columns fit: a point less overflows, and both columns are used.
|
||||
let mut t = text(&s, id);
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t);
|
||||
assert!(lay.glyphs.iter().any(|g| g.origin.x > 160.0), "text flows into the second column");
|
||||
t.area.fit = AreaFit::None;
|
||||
t.kind = TextKind::Area {
|
||||
frame: vectorcraft_geom::PathData::from_bezpath(&vectorcraft_geom::Shape::to_path(&Rect::new(0.0, 0.0, 300.0, two - 1.0), 0.1)),
|
||||
};
|
||||
assert!(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).overflow);
|
||||
// Dragging the bottom edge sets the height by hand: Auto Size goes off.
|
||||
let b = frame(&s, id);
|
||||
s.execute("text.reshapeArea", &json!({"id": id.0, "anchors": [[0, 2], [0, 3]], "dx": 0, "dy": 50})).unwrap();
|
||||
assert_eq!(text(&s, id).area.fit, AreaFit::None);
|
||||
assert!((frame(&s, id).height() - (b.height() + 50.0)).abs() < 1e-6);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
// A new width keeps it: the height follows the reflow.
|
||||
s.execute("text.reshapeArea", &json!({"id": id.0, "anchors": [[0, 1], [0, 2]], "dx": 100, "dy": 0})).unwrap();
|
||||
assert_eq!(text(&s, id).area.fit, AreaFit::AutoHeight);
|
||||
assert!(frame(&s, id).height() < b.height());
|
||||
// Point type has no frame to size.
|
||||
let p = s.execute("text.create", &json!({"x": 10, "y": 10, "text": "x"})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [p]})).unwrap();
|
||||
assert!(s.execute("text.areaOptions", &json!({"fit": "autoHeight"})).is_err(), "point type has no area options");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shrink_text_round_trips_through_the_native_format() {
|
||||
let mut s = session();
|
||||
let id = area(&mut s, 120.0, 30.0, STORY, json!({"fit": "shrinkText", "fitMinPercent": 35}));
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
let bytes = vectorcraft_format::save(&doc, false);
|
||||
let back = vectorcraft_format::load(&bytes).unwrap();
|
||||
let NodeKind::Text(t) = &back.node(id).unwrap().kind else { panic!() };
|
||||
assert_eq!(t.area.fit, AreaFit::ShrinkText { min_percent: 35.0 });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_height_follows_the_leading_model_and_character_alignment() {
|
||||
let mut s = session();
|
||||
let id = area(&mut s, 200.0, 300.0, STORY, json!({"fit": "autoHeight"}));
|
||||
let roman = frame(&s, id);
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
// Top-to-Top leading: the first line moves up to touch the frame, the frame follows.
|
||||
s.execute("text.setFormat", &json!({"leadingModel": "emBoxTop"})).unwrap();
|
||||
let em = frame(&s, id);
|
||||
assert_ne!(em.height(), roman.height());
|
||||
assert!(!overflows(&s, id), "the frame holds the text under emBoxTop");
|
||||
// Mixed sizes aligned on the em box centre still fit exactly.
|
||||
s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 0, "end": 3, "size": 30})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"charAlign": "emBoxCenter"})).unwrap();
|
||||
let mixed = frame(&s, id);
|
||||
assert!(mixed.height() > em.height());
|
||||
assert!(!overflows(&s, id));
|
||||
let mut t = text(&s, id);
|
||||
t.area.fit = AreaFit::None;
|
||||
t.kind = TextKind::Area {
|
||||
frame: vectorcraft_geom::PathData::from_bezpath(&vectorcraft_geom::Shape::to_path(&Rect::new(0.0, 0.0, 200.0, mixed.height() - 1.0), 0.1)),
|
||||
};
|
||||
assert!(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).overflow, "tight");
|
||||
}
|
||||
@@ -205,7 +205,6 @@ impl Session {
|
||||
slices_locked: self.menu.slices_locked,
|
||||
auto_add_delete: !self.prefs.disable_auto_add_delete,
|
||||
selection_tolerance: self.prefs.selection_tolerance,
|
||||
anchor_size: self.prefs.anchor_size,
|
||||
path_only: self.prefs.object_selection_by_path_only,
|
||||
type_path_only: self.prefs.type_selection_by_path_only,
|
||||
double_click_isolate: self.prefs.double_click_to_isolate,
|
||||
|
||||
@@ -311,6 +311,54 @@ fn structured_junk() {
|
||||
assert!(failures.is_empty(), "{} failures:\n{}", failures.len(), failures.join("\n"));
|
||||
}
|
||||
|
||||
/// Area Type Options with junk fit values, on selected area type (the fixtures have none), with
|
||||
/// text that overflows: never a panic, the document stays sound, and editing still works.
|
||||
#[test]
|
||||
fn area_options_fit_junk() {
|
||||
let cases = [
|
||||
json!({"fit": "shrinkText", "fitMinPercent": 1e308}),
|
||||
json!({"fit": "shrinkText", "fitMinPercent": -1e308}),
|
||||
json!({"fit": "shrinkText", "fitMinPercent": "x"}),
|
||||
json!({"fit": {"shrinkText": {"minPercent": -5}}}),
|
||||
json!({"fit": {"shrinkText": {"minPercent": "a"}}}),
|
||||
json!({"fit": {"shrinkText": null}}),
|
||||
json!({"fit": {"autoHeight": 1}}),
|
||||
json!({"fit": {"bogus": {}}}),
|
||||
json!({"fit": [1, 2]}),
|
||||
json!({"fit": ""}),
|
||||
json!({"fit": "AUTO-HEIGHT", "height": 1e308, "width": -1e308}),
|
||||
json!({"fit": "autoHeight", "columns": u64::MAX, "gutter": 1e308, "inset": 1e308}),
|
||||
json!({"fit": "autoHeight", "rows": 5, "inset": -1}),
|
||||
json!({"fit": "shrinkText", "columns": 100, "gutter": 0, "inset": 10000}),
|
||||
json!({"fitMinPercent": 50}),
|
||||
json!({"fit": "none", "fitMinPercent": 1e-308}),
|
||||
];
|
||||
let story = "Words that overflow a small frame. ".repeat(40);
|
||||
let mut failures = vec![];
|
||||
for (size, (w, h)) in [(12.0, (120.0, 40.0)), (0.1, (1.0, 1.0)), (1296.0, (100_000.0, 1.0))] {
|
||||
for p in &cases {
|
||||
let mut s = Fixture::Multi.session();
|
||||
let made = s.execute("text.create", &json!({"x": 10, "y": 10, "size": size, "text": story, "area": {"width": w, "height": h}}));
|
||||
let Ok(made) = made else { continue };
|
||||
let id = made["id"].as_u64().unwrap_or(0);
|
||||
let r = catch_quiet(|| s.execute("text.areaOptions", p));
|
||||
match r {
|
||||
Err(m) => failures.push(format!("PANIC text.areaOptions {p} [{size} pt, {w}×{h}]: {m}")),
|
||||
Ok(_) => {
|
||||
let typed = catch_quiet(|| s.execute("text.editRange", &json!({"id": id, "start": 0, "insert": "More words. "})));
|
||||
if typed.is_err() {
|
||||
failures.push(format!("PANIC typing after text.areaOptions {p}"));
|
||||
}
|
||||
if let Err(e) = check_session(&s) {
|
||||
failures.push(format!("text.areaOptions {p} [{size} pt]: {e}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(failures.is_empty(), "{} failures:\n{}", failures.len(), failures.join("\n"));
|
||||
}
|
||||
|
||||
/// After a successful fuzzed call, the document still round-trips and exports.
|
||||
#[test]
|
||||
fn fuzzed_calls_keep_documents_serializable() {
|
||||
|
||||
@@ -53,8 +53,10 @@ fn area_type_vertical_alignment_round_trips() {
|
||||
let area = |d: &Document| {
|
||||
let mut found = None;
|
||||
d.walk(|n| {
|
||||
// The fixture's centred area type, by its text (the fixture has other area type).
|
||||
if let NodeKind::Text(t) = &n.kind
|
||||
&& matches!(t.kind, vectorcraft_doc::TextKind::Area { .. })
|
||||
&& t.runs.iter().map(|r| r.text.as_str()).collect::<String>() == "Centred area type"
|
||||
{
|
||||
found = Some(t.area.vertical_align);
|
||||
}
|
||||
@@ -63,7 +65,20 @@ fn area_type_vertical_alignment_round_trips() {
|
||||
};
|
||||
assert_eq!(area(&back), vectorcraft_doc::VerticalAlign::Center);
|
||||
// Files from before the option open top-aligned.
|
||||
let old = text.replacen("\"verticalAlign\":\"center\",", "", 1).replacen(",\"verticalAlign\":\"center\"", "", 1);
|
||||
// (Every area type the fixture has writes its options, so the key goes from all of them.)
|
||||
fn strip(v: &mut Value) {
|
||||
match v {
|
||||
Value::Object(m) => {
|
||||
m.remove("verticalAlign");
|
||||
m.values_mut().for_each(strip);
|
||||
}
|
||||
Value::Array(a) => a.iter_mut().for_each(strip),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut v = json_of(text.as_bytes());
|
||||
strip(&mut v);
|
||||
let old = serde_json::to_string(&v).unwrap();
|
||||
assert!(!old.contains("verticalAlign"));
|
||||
assert_eq!(area(&load(old.as_bytes()).unwrap()), vectorcraft_doc::VerticalAlign::Top);
|
||||
}
|
||||
@@ -149,11 +164,12 @@ fn text_composer_round_trips() {
|
||||
});
|
||||
v
|
||||
};
|
||||
// The point type set to Single-line, then the area type left at the default.
|
||||
assert_eq!(composers(&d), [Composer::SingleLine, Composer::EveryLine]);
|
||||
// The point type set to Single-line comes first; the fixture's other type keeps the default.
|
||||
let single_then_default = |c: &[Composer]| c.len() > 1 && c[0] == Composer::SingleLine && c[1..].iter().all(|c| *c == Composer::EveryLine);
|
||||
assert!(single_then_default(&composers(&d)), "{:?}", composers(&d));
|
||||
let bytes = save(&d, false);
|
||||
assert!(String::from_utf8_lossy(&bytes).contains("\"composer\":\"singleLine\""));
|
||||
assert_eq!(composers(&load(&bytes).unwrap()), [Composer::SingleLine, Composer::EveryLine]);
|
||||
assert_eq!(composers(&load(&bytes).unwrap()), composers(&d));
|
||||
// Files without the key (older files, Every-line text) read as Every-line.
|
||||
fn strip(v: &mut Value) {
|
||||
match v {
|
||||
@@ -168,7 +184,7 @@ fn text_composer_round_trips() {
|
||||
let mut v = json_of(&bytes);
|
||||
strip(&mut v);
|
||||
let d2 = load(&serde_json::to_vec(&v).unwrap()).unwrap();
|
||||
assert_eq!(composers(&d2), [Composer::EveryLine, Composer::EveryLine]);
|
||||
assert!(composers(&d2).iter().all(|c| *c == Composer::EveryLine), "{:?}", composers(&d2));
|
||||
assert!(!String::from_utf8_lossy(&save(&d2, false)).contains("composer"));
|
||||
}
|
||||
|
||||
|
||||
@@ -123,6 +123,12 @@ pub fn rich_session() -> Session {
|
||||
));
|
||||
select(&mut s, &[area]);
|
||||
exec(&mut s, "text.areaOptions", json!({"verticalAlign": "center", "inset": 2}));
|
||||
let _ = id_of(&exec(
|
||||
&mut s,
|
||||
"text.create",
|
||||
json!({"x": 300, "y": 330, "size": 14, "text": "Area type shrinks its text to fit the frame.",
|
||||
"area": {"width": 150, "height": 40, "fit": "shrinkText", "fitMinPercent": 40}}),
|
||||
));
|
||||
exec(&mut s, "layer.new", json!({"name": "Top"}));
|
||||
let d = rect(&mut s, 350.0, 200.0, 80.0, 80.0);
|
||||
let e = ellipse(&mut s, 380.0, 230.0, 80.0, 80.0);
|
||||
|
||||
@@ -128,14 +128,88 @@ pub fn layout(db: &FontDb, t: &TextObject) -> TextLayout {
|
||||
first_baseline: a.first_baseline,
|
||||
first_baseline_min: a.first_baseline_min,
|
||||
vertical_align: a.vertical_align,
|
||||
fit: a.fit,
|
||||
..LayoutOptions::default()
|
||||
};
|
||||
layout_with(db, t, &opts)
|
||||
}
|
||||
|
||||
/// Most layout passes Shrink Text to Fit runs past the first (bisection plus the final pass).
|
||||
const SHRINK_PASSES: usize = 11;
|
||||
|
||||
/// Lay out a text object with explicit options (area type rows/columns, inset, first baseline,
|
||||
/// composer, OpenType features).
|
||||
/// fit, composer, OpenType features).
|
||||
pub fn layout_with(db: &FontDb, t: &TextObject, opts: &LayoutOptions) -> TextLayout {
|
||||
let first = layout_once(db, t, opts);
|
||||
match (opts.fit.min_scale(), &t.kind) {
|
||||
(Some(min), TextKind::Area { .. }) if first.overflow => shrink_to_fit(db, t, opts, min).unwrap_or(first),
|
||||
_ => first,
|
||||
}
|
||||
}
|
||||
|
||||
/// Shrink Text to Fit for text that overflows at full size: the largest scale in `min..1` at which
|
||||
/// it fits, searched by bisection over the first run's size in steps of 0.1 pt (so its scaled size
|
||||
/// is a whole number of tenths of a point, the same every time). Down at `min` it lays out there,
|
||||
/// still overflowing. None (keep the full-size layout) when the text has no usable size.
|
||||
fn shrink_to_fit(db: &FontDb, t: &TextObject, opts: &LayoutOptions, min: f64) -> Option<TextLayout> {
|
||||
let size = t.runs.first().map(|r| r.style.size).filter(|s| s.is_finite() && *s >= 0.1)?;
|
||||
if !(min.is_finite() && min < 1.0) {
|
||||
return None;
|
||||
}
|
||||
let tenths = size * 10.0;
|
||||
// Candidate sizes k/10 pt for k in lo..hi: `hi` (full size, rounded down) is known to overflow
|
||||
// unless it is below the full size; `lo` is the smallest allowed.
|
||||
let mut lo = (tenths * min).ceil().max(1.0);
|
||||
let mut hi = tenths.floor();
|
||||
if hi < lo {
|
||||
hi = lo;
|
||||
}
|
||||
let at = |k: f64| -> TextLayout {
|
||||
let f = (k / tenths).clamp(min, 1.0);
|
||||
let mut l = layout_once(db, &scaled(t, f), opts);
|
||||
l.fit_scale = f;
|
||||
l
|
||||
};
|
||||
let mut passes = 0;
|
||||
let mut best: Option<TextLayout> = None;
|
||||
// `hi` itself may fit when the size isn't a whole number of tenths.
|
||||
if hi < tenths && hi > lo {
|
||||
let l = at(hi);
|
||||
passes += 1;
|
||||
if !l.overflow {
|
||||
return Some(l);
|
||||
}
|
||||
}
|
||||
// Invariant: everything at `hi` or above overflows; `lo` fits or is the floor.
|
||||
while hi - lo > 1.0 && passes + 1 < SHRINK_PASSES {
|
||||
let mid = ((lo + hi) * 0.5).floor();
|
||||
let l = at(mid);
|
||||
passes += 1;
|
||||
if l.overflow {
|
||||
hi = mid;
|
||||
} else {
|
||||
lo = mid;
|
||||
best = Some(l);
|
||||
}
|
||||
}
|
||||
// `best` is the layout at `lo` once `lo` has moved; at the floor it still needs laying out.
|
||||
Some(best.unwrap_or_else(|| at(lo)))
|
||||
}
|
||||
|
||||
/// `t` with every run's size, explicit leading and baseline shift scaled by `f` (auto leading
|
||||
/// follows the size; paragraph spacing stays).
|
||||
fn scaled(t: &TextObject, f: f64) -> TextObject {
|
||||
let mut s = t.clone();
|
||||
for r in &mut s.runs {
|
||||
r.style.size *= f;
|
||||
r.style.leading = r.style.leading.map(|l| l * f);
|
||||
r.style.baseline_shift *= f;
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// One layout pass, without fitting.
|
||||
fn layout_once(db: &FontDb, t: &TextObject, opts: &LayoutOptions) -> TextLayout {
|
||||
let text = t.plain_text();
|
||||
let mut runs = Vec::with_capacity(t.runs.len());
|
||||
let mut off = 0;
|
||||
|
||||
+27
-2
@@ -31,7 +31,7 @@ use kurbo::{Affine, BezPath, Point, Rect, Vec2};
|
||||
pub use layout::{layout, layout_with};
|
||||
pub use vectorcraft_doc::TextObject;
|
||||
|
||||
pub use vectorcraft_doc::{FirstBaseline, VerticalAlign};
|
||||
pub use vectorcraft_doc::{AreaFit, FirstBaseline, VerticalAlign};
|
||||
|
||||
/// Paragraph composer; stored per text object in [`vectorcraft_doc::ParaStyle::composer`].
|
||||
pub use vectorcraft_doc::Composer;
|
||||
@@ -52,6 +52,9 @@ pub struct LayoutOptions {
|
||||
pub first_baseline_min: f64,
|
||||
/// Vertical alignment of the lines in each row/column (Area Type Options "Align").
|
||||
pub vertical_align: VerticalAlign,
|
||||
/// Area type only: Shrink Text to Fit scales overflowing text down at layout time (see
|
||||
/// [`TextLayout::fit_scale`]); the other fits are the engine's business and lay out as `None`.
|
||||
pub fit: AreaFit,
|
||||
/// Overrides the object's paragraph composer (`None` = use `ParaStyle::composer`).
|
||||
pub composer: Option<Composer>,
|
||||
pub features: OtFeatures,
|
||||
@@ -67,6 +70,7 @@ impl Default for LayoutOptions {
|
||||
first_baseline: FirstBaseline::Ascent,
|
||||
first_baseline_min: 0.0,
|
||||
vertical_align: VerticalAlign::Top,
|
||||
fit: AreaFit::None,
|
||||
composer: None,
|
||||
features: OtFeatures::default(),
|
||||
}
|
||||
@@ -131,7 +135,7 @@ pub struct LineInfo {
|
||||
pub region: usize,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct TextLayout {
|
||||
/// Lines retain inline/block coordinates; glyph geometry is in physical text space.
|
||||
pub vertical: bool,
|
||||
@@ -149,6 +153,25 @@ pub struct TextLayout {
|
||||
pub on_path: bool,
|
||||
/// Area type: the frame cells text flowed into (one per row/column).
|
||||
pub frames: Vec<Rect>,
|
||||
/// Shrink Text to Fit: the factor the text's sizes, leading and baseline shifts were scaled
|
||||
/// by to fit its frame (1.0 when the text is not shrunk).
|
||||
pub fit_scale: f64,
|
||||
}
|
||||
|
||||
impl Default for TextLayout {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
vertical: false,
|
||||
line_xf: Affine::IDENTITY,
|
||||
glyphs: Vec::new(),
|
||||
lines: Vec::new(),
|
||||
bounds: Rect::ZERO,
|
||||
overflow: false,
|
||||
on_path: false,
|
||||
frames: Vec::new(),
|
||||
fit_scale: 1.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TextLayout {
|
||||
@@ -450,6 +473,8 @@ mod tests_bidi;
|
||||
#[cfg(test)]
|
||||
mod tests_embed;
|
||||
#[cfg(test)]
|
||||
mod tests_fit;
|
||||
#[cfg(test)]
|
||||
mod tests_scripts;
|
||||
#[cfg(test)]
|
||||
mod tests_snap;
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
//! Area type fitting: Shrink Text to Fit.
|
||||
|
||||
use super::*;
|
||||
use kurbo::Shape;
|
||||
use vectorcraft_doc::{AreaFit, CharStyle, TextKind};
|
||||
use vectorcraft_geom::PathData;
|
||||
|
||||
const COPY: &str = "Typography is the craft of arranging type to make written language legible, readable and appealing when displayed. \
|
||||
The arrangement of type involves selecting typefaces, point sizes, line lengths, line spacing and letter spacing, and adjusting the space \
|
||||
between pairs of letters.";
|
||||
|
||||
fn db() -> &'static FontDb {
|
||||
FontDb::global()
|
||||
}
|
||||
|
||||
fn area(text: &str, size: f64, frame: Rect, fit: AreaFit) -> TextObject {
|
||||
let mut t = TextObject::point(Point::ZERO, text, CharStyle { size, ..CharStyle::default() });
|
||||
t.kind = TextKind::Area { frame: PathData::from_bezpath(&frame.to_path(0.1)) };
|
||||
t.xf = Affine::IDENTITY;
|
||||
t.area.fit = fit;
|
||||
t
|
||||
}
|
||||
|
||||
fn shrink(min_percent: f64) -> AreaFit {
|
||||
AreaFit::ShrinkText { min_percent }
|
||||
}
|
||||
|
||||
/// `t` laid out without fitting at `size` (every run).
|
||||
fn at_size(t: &TextObject, size: f64) -> TextLayout {
|
||||
let mut p = t.clone();
|
||||
p.area.fit = AreaFit::None;
|
||||
for r in &mut p.runs {
|
||||
r.style.size = size;
|
||||
}
|
||||
layout(db(), &p)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shrink_text_makes_overflowing_text_fit() {
|
||||
let t = area(COPY, 14.0, Rect::new(0.0, 0.0, 200.0, 90.0), shrink(30.0));
|
||||
assert!(at_size(&t, 14.0).overflow, "the text overflows at full size");
|
||||
let l = layout(db(), &t);
|
||||
assert!(!l.overflow, "shrunk to fit");
|
||||
assert!(l.fit_scale < 1.0 && l.fit_scale >= 0.3, "{}", l.fit_scale);
|
||||
assert!(l.glyphs.len() > 100);
|
||||
// The first run's scaled size is a whole number of tenths of a point.
|
||||
let size = 14.0 * l.fit_scale;
|
||||
assert!((size * 10.0 - (size * 10.0).round()).abs() < 1e-6, "{size}");
|
||||
// Maximal: a tenth of a point larger overflows; and the layout is the one at that size.
|
||||
assert!(at_size(&t, size + 0.1).overflow, "{size} + 0.1 pt still fits");
|
||||
let same = at_size(&t, size);
|
||||
assert_eq!((same.lines.len(), same.glyphs.len(), same.overflow), (l.lines.len(), l.glyphs.len(), false));
|
||||
// Deterministic.
|
||||
assert_eq!(layout(db(), &t).fit_scale, l.fit_scale);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shrink_text_respects_its_minimum() {
|
||||
let t = area(COPY, 14.0, Rect::new(0.0, 0.0, 120.0, 40.0), shrink(90.0));
|
||||
let l = layout(db(), &t);
|
||||
assert!(l.overflow, "still overflows at 90 %");
|
||||
assert!((l.fit_scale - 0.9).abs() < 1e-9, "{}", l.fit_scale);
|
||||
// Out-of-range minimums are clamped (10 %).
|
||||
let l = layout(db(), &area(COPY, 14.0, Rect::new(0.0, 0.0, 120.0, 40.0), shrink(0.0)));
|
||||
assert!(l.fit_scale >= 0.1 - 1e-9, "{}", l.fit_scale);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shrink_text_is_a_no_op_when_the_text_fits() {
|
||||
let t = area("Short text", 14.0, Rect::new(0.0, 0.0, 200.0, 90.0), shrink(50.0));
|
||||
let l = layout(db(), &t);
|
||||
let plain = at_size(&t, 14.0);
|
||||
assert!(!l.overflow);
|
||||
assert_eq!(l.fit_scale, 1.0);
|
||||
let o = |l: &TextLayout| l.glyphs.iter().map(|g| g.origin).collect::<Vec<_>>();
|
||||
assert_eq!(o(&l), o(&plain));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shrink_text_fills_columns() {
|
||||
let mut t = area(COPY, 14.0, Rect::new(0.0, 0.0, 300.0, 70.0), shrink(20.0));
|
||||
t.area.columns = 2;
|
||||
t.area.gutter = 12.0;
|
||||
let l = layout(db(), &t);
|
||||
assert!(!l.overflow);
|
||||
assert!(l.fit_scale < 1.0);
|
||||
assert_eq!(l.frames.len(), 2);
|
||||
let second = l.frames[1];
|
||||
assert!(l.glyphs.iter().any(|g| g.origin.x >= second.x0), "text flows into the second column");
|
||||
let size = 14.0 * l.fit_scale;
|
||||
assert!(at_size(&t, size + 0.1).overflow, "maximal across columns too");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shrink_text_scales_leading_and_baseline_shift_not_paragraph_spacing() {
|
||||
let mut t = area(©.repeat(2), 12.0, Rect::new(0.0, 0.0, 200.0, 200.0), shrink(10.0));
|
||||
for r in &mut t.runs {
|
||||
r.style.leading = Some(20.0);
|
||||
}
|
||||
let l = layout(db(), &t);
|
||||
assert!(!l.overflow && l.fit_scale < 1.0);
|
||||
let gap = l.lines[2].baseline - l.lines[1].baseline;
|
||||
assert!((gap - 20.0 * l.fit_scale).abs() < 1e-6, "{gap} vs {}", 20.0 * l.fit_scale);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn point_type_and_type_on_a_path_ignore_fit() {
|
||||
let mut t = TextObject::point(Point::ZERO, COPY, CharStyle::default());
|
||||
t.area.fit = shrink(10.0);
|
||||
assert_eq!(layout(db(), &t).fit_scale, 1.0);
|
||||
t.kind = TextKind::OnPath { path: PathData::from_bezpath(&kurbo::Line::new((0.0, 0.0), (50.0, 0.0)).to_path(0.1)), start: 0.0, end: None };
|
||||
let l = layout(db(), &t);
|
||||
assert!(l.overflow, "text runs past the path end");
|
||||
assert_eq!(l.fit_scale, 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shrink_text_guards_degenerate_sizes() {
|
||||
for size in [0.0, 0.01, f64::NAN, 1296.0] {
|
||||
let l = layout(db(), &area(COPY, size, Rect::new(0.0, 0.0, 50.0, 20.0), shrink(10.0)));
|
||||
assert!(l.fit_scale.is_finite() && l.fit_scale > 0.0 && l.fit_scale <= 1.0, "{size}: {}", l.fit_scale);
|
||||
}
|
||||
// A zero-height frame.
|
||||
let l = layout(db(), &area(COPY, 12.0, Rect::new(0.0, 0.0, 50.0, 0.0), shrink(10.0)));
|
||||
assert!(l.overflow);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shrink_text_follows_top_to_top_leading_and_character_alignment() {
|
||||
use vectorcraft_doc::{CharAlign, LeadingModel, TextRun};
|
||||
// Mixed sizes aligned on the em box centre, leading measured from em box top to top.
|
||||
let mut t = area(COPY, 14.0, Rect::new(0.0, 0.0, 200.0, 90.0), shrink(20.0));
|
||||
t.para.leading_model = LeadingModel::EmBoxTop;
|
||||
let big = CharStyle { size: 28.0, leading: Some(32.0), char_align: CharAlign::EmBoxCenter, ..CharStyle::default() };
|
||||
t.runs.insert(0, TextRun { text: "Big ".into(), style: big });
|
||||
for r in &mut t.runs {
|
||||
r.style.char_align = CharAlign::EmBoxCenter;
|
||||
}
|
||||
let l = layout(db(), &t);
|
||||
assert!(!l.overflow, "shrunk to fit under the top-to-top model");
|
||||
assert!(l.fit_scale < 1.0);
|
||||
// The shrunk layout is the same text laid out at the scaled sizes and leading.
|
||||
let mut manual = t.clone();
|
||||
manual.area.fit = AreaFit::None;
|
||||
for r in &mut manual.runs {
|
||||
r.style.size *= l.fit_scale;
|
||||
r.style.leading = r.style.leading.map(|v| v * l.fit_scale);
|
||||
}
|
||||
let m = layout(db(), &manual);
|
||||
let o = |l: &TextLayout| l.glyphs.iter().map(|g| (g.origin.x, g.origin.y)).collect::<Vec<_>>();
|
||||
assert_eq!(o(&l), o(&m));
|
||||
// First line still touches the frame top (top-to-top: em box top at y = 0, scaled).
|
||||
let first = l.lines.first().map(|li| li.baseline).unwrap_or(0.0);
|
||||
assert!(first > 0.0 && first <= 28.0 * l.fit_scale + 1e-6, "{first}");
|
||||
// Maximal: the next 0.1 pt step of the first run overflows.
|
||||
let step = 0.1 / 28.0;
|
||||
let mut bigger = manual.clone();
|
||||
for (r, orig) in bigger.runs.iter_mut().zip(&t.runs) {
|
||||
r.style.size = orig.style.size * (l.fit_scale + step);
|
||||
r.style.leading = orig.style.leading.map(|v| v * (l.fit_scale + step));
|
||||
}
|
||||
assert!(layout(db(), &bigger).overflow);
|
||||
}
|
||||
+11
-41
@@ -201,21 +201,15 @@ fn anchor_owners(cx: &ToolContext, f: fn(&Node) -> bool) -> Vec<NodeId> {
|
||||
v
|
||||
}
|
||||
|
||||
/// The anchor within `tol` of `p` nearest to it, of the topmost visible path or area type frame
|
||||
/// that has one: (id, si, ai, where it is).
|
||||
/// Anchor of any visible path or area type frame under `p`, topmost first: (id, si, ai, where it is).
|
||||
fn hit_anchor(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId, usize, usize, Point)> {
|
||||
let owners = anchor_owners(cx, |n| matches!(n.kind, NodeKind::Path { .. }) || is_area_type(n));
|
||||
owners.into_iter().find_map(|id| {
|
||||
let pd = cx.doc.node(id).and_then(editable_path)?;
|
||||
nearest_anchor(&pd, p, tol).map(|(si, ai, a)| (id, si, ai, a))
|
||||
pd.anchors().find(|(_, _, a)| a.p.distance(p) <= tol).map(|(si, ai, a)| (id, si, ai, a.p))
|
||||
})
|
||||
}
|
||||
|
||||
/// The anchor of `pd` within `tol` of `p` nearest to it: (subpath, anchor, where it is).
|
||||
fn nearest_anchor(pd: &PathData, p: Point, tol: f64) -> Option<(usize, usize, Point)> {
|
||||
pd.anchors().map(|(si, ai, a)| (si, ai, a.p)).filter(|(.., a)| a.distance(p) <= tol).min_by(|x, y| x.2.distance(p).total_cmp(&y.2.distance(p)))
|
||||
}
|
||||
|
||||
/// An edge of an area type frame under `p`, topmost first: (text, the edge's two anchors).
|
||||
fn hit_frame_edge(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId, Vec<AnchorRef>)> {
|
||||
anchor_owners(cx, is_area_type).into_iter().find_map(|id| {
|
||||
@@ -296,8 +290,7 @@ impl Tool for DirectSelectionTool {
|
||||
return out;
|
||||
}
|
||||
let p = ev.pos;
|
||||
// Anchors and handle ends are picked from a little further than segments and objects.
|
||||
let (tol, point) = (cx.pick_tol(), cx.point_tol());
|
||||
let tol = cx.pick_tol();
|
||||
match (ev.kind, self.state.clone()) {
|
||||
(PointerKind::Down, _) if self.group => {
|
||||
if let Some(out) = self.guide.press(cx, ev) {
|
||||
@@ -339,7 +332,7 @@ impl Tool for DirectSelectionTool {
|
||||
return vec![];
|
||||
}
|
||||
if let Some(sel) = self.spine.filter(|(id, _)| cx.selection.contains(*id))
|
||||
&& let Some(out) = hit_spine_handle(cx, sel, p, point)
|
||||
&& let Some(out) = hit_spine_handle(cx, sel, p, tol)
|
||||
{
|
||||
self.state = State::SpineHandle { id: sel.0, anchor: sel.1, out };
|
||||
return vec![Action::Begin("Reshape Spine".into())];
|
||||
@@ -350,17 +343,17 @@ impl Tool for DirectSelectionTool {
|
||||
return self.mesh.press(g);
|
||||
}
|
||||
self.mesh.unfocus();
|
||||
if let Some((id, si, ai, out)) = hit_handle(cx, p, point) {
|
||||
if let Some((id, si, ai, out)) = hit_handle(cx, p, tol) {
|
||||
self.state = State::Handle { id, si, ai, out };
|
||||
self.handle_snap = HandleSnap::default();
|
||||
return vec![Action::Begin("Reshape".into())];
|
||||
}
|
||||
if let Some((id, anchor, from)) = hit_spine_point(cx, p, point) {
|
||||
if let Some((id, anchor, from)) = hit_spine_point(cx, p, tol) {
|
||||
self.spine = Some((id, anchor));
|
||||
self.state = State::SpinePoint { id, anchor, from, start: p, began: false };
|
||||
return if cx.selection.contains(id) { vec![] } else { vec![Action::Exec("select.set".into(), json!({"ids": [id.0]}))] };
|
||||
}
|
||||
if let Some((id, si, ai, grab)) = hit_anchor(cx, p, point) {
|
||||
if let Some((id, si, ai, grab)) = hit_anchor(cx, p, tol) {
|
||||
if cx.doc.node(id).is_some_and(is_area_type) {
|
||||
return self.press_type_area(cx, id, vec![(si, ai)], p, ev.mods.shift);
|
||||
}
|
||||
@@ -615,14 +608,14 @@ impl Tool for DirectSelectionTool {
|
||||
}
|
||||
}
|
||||
|
||||
/// The anchor within a press's reach of `p` ([`ToolContext::point_tol`]), of a selected path or the
|
||||
/// path under `p`: what Highlight anchors on mouse over marks (a press there picks it).
|
||||
/// The anchor within the selection tolerance of `p`, of a selected path or the path under `p`:
|
||||
/// what Highlight anchors on mouse over marks (a press there picks it).
|
||||
fn hovered_anchor(cx: &ToolContext, p: Point) -> Option<(NodeId, Point)> {
|
||||
let under = hit_test(cx.doc, p, cx.hit_options()).map(|h| h.leaf);
|
||||
let tol = cx.point_tol();
|
||||
let tol = cx.pick_tol();
|
||||
cx.selection.objects.iter().copied().chain(under).find_map(|id| {
|
||||
let path = cx.doc.node(id).and_then(editable_path)?;
|
||||
nearest_anchor(&path, p, tol).map(|(.., a)| (id, a))
|
||||
path.anchors().find(|(_, _, a)| a.p.distance(p) <= tol).map(|(_, _, a)| (id, a.p))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -692,29 +685,6 @@ mod tests {
|
||||
assert_eq!(down(&mut t, 100.0), vec![Action::Exec("select.anchors".into(), json!({"id": id.0, "anchors": [[0, 0]], "mode": "set"}))]);
|
||||
}
|
||||
|
||||
/// An anchor is picked from 2 px past its drawn square even where its segment is nearer, and
|
||||
/// further with a larger anchor Size or Tolerance (#593); away from it the segment is.
|
||||
#[test]
|
||||
fn anchors_are_picked_before_the_segments_through_them() {
|
||||
let (d, id) = doc_with_rect();
|
||||
let (s, p) = (Selection::default(), paint());
|
||||
let corner = vec![Action::Exec("select.anchors".into(), json!({"id": id.0, "anchors": [[0, 0]], "mode": "set"}))];
|
||||
let press = |cx: &ToolContext, x: f64, y: f64| DirectSelectionTool::new(false).pointer(cx, &PointerEvent::new(PointerKind::Down, x, y));
|
||||
let c = cx(&d, &s, &p);
|
||||
// 4.3 px from the corner, 0.5 px from the top edge.
|
||||
assert_eq!(press(&c, 104.2, 100.5), corner);
|
||||
assert_ne!(press(&c, 110.0, 100.5), corner, "the segment, away from the anchor");
|
||||
assert_ne!(press(&c, 105.0, 100.5), corner, "past the default reach (4.5 px)");
|
||||
let large = ToolContext { anchor_size: 7, ..cx(&d, &s, &p) };
|
||||
assert_eq!(press(&large, 106.0, 100.5), corner, "Size 7 draws them 9 px wide");
|
||||
let loose = ToolContext { selection_tolerance: 8.0, ..cx(&d, &s, &p) };
|
||||
assert_eq!(press(&loose, 107.5, 100.5), corner);
|
||||
// On screen: at 200% the reach is half as far in the document.
|
||||
let zoomed = ToolContext { zoom: 2.0, ..cx(&d, &s, &p) };
|
||||
assert_eq!(press(&zoomed, 102.1, 100.2), corner);
|
||||
assert_ne!(press(&zoomed, 102.6, 100.2), corner);
|
||||
}
|
||||
|
||||
/// A blend of two 20 pt squares centred on (110, 310) and (210, 310), selected.
|
||||
fn blend_doc() -> (vectorcraft_doc::Document, NodeId, NodeId) {
|
||||
let (mut d, _) = doc_with_rect();
|
||||
|
||||
@@ -48,7 +48,7 @@ impl AnchorTool {
|
||||
}
|
||||
|
||||
fn delete(cx: &ToolContext, p: Point) -> Vec<Action> {
|
||||
hit_anchor(cx, p, cx.point_tol()).map(remove_anchor).into_iter().collect()
|
||||
hit_anchor(cx, p, cx.pick_tol()).map(remove_anchor).into_iter().collect()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,8 +61,7 @@ impl Tool for AnchorTool {
|
||||
}
|
||||
fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec<Action> {
|
||||
let p = ev.pos;
|
||||
// Anchors and handle ends are picked from a little further than segments.
|
||||
let (tol, point) = (cx.pick_tol(), cx.point_tol());
|
||||
let tol = cx.pick_tol();
|
||||
match (self.id, ev.kind) {
|
||||
("addAnchor", PointerKind::Down) => {
|
||||
if ev.mods.alt {
|
||||
@@ -79,7 +78,7 @@ impl Tool for AnchorTool {
|
||||
}
|
||||
}
|
||||
("scissors", PointerKind::Down) => {
|
||||
if let Some((id, si, ai)) = hit_anchor(cx, p, point) {
|
||||
if let Some((id, si, ai)) = hit_anchor(cx, p, tol) {
|
||||
return vec![Action::Exec("path.split".into(), json!({"id": id.0, "subpath": si, "anchor": ai}))];
|
||||
}
|
||||
match hit_segment(cx, p, tol) {
|
||||
@@ -88,10 +87,10 @@ impl Tool for AnchorTool {
|
||||
}
|
||||
}
|
||||
("anchorPoint", PointerKind::Down) => {
|
||||
if let Some((id, si, ai, out)) = hit_handle(cx, p, point) {
|
||||
if let Some((id, si, ai, out)) = hit_handle(cx, p, tol) {
|
||||
self.state = State::Handle { id, si, ai, out, began: false };
|
||||
self.snap = HandleSnap::default();
|
||||
} else if let Some((id, si, ai)) = hit_anchor(cx, p, point) {
|
||||
} else if let Some((id, si, ai)) = hit_anchor(cx, p, tol) {
|
||||
self.state = State::Convert { id, si, ai, start: p, began: false };
|
||||
} else if let Some((id, si, seg, t)) = hit_segment(cx, p, tol) {
|
||||
self.state = State::Reshape { id, si, seg, t, start: p, began: false };
|
||||
|
||||
@@ -274,8 +274,6 @@ pub struct ToolContext<'a> {
|
||||
/// Selection & Anchor Display → Tolerance: how near (screen pixels) a click must be to a path
|
||||
/// or an anchor to pick it.
|
||||
pub selection_tolerance: f64,
|
||||
/// Selection & Anchor Display → Size (1–7, default 3): how big anchors and handles are drawn.
|
||||
pub anchor_size: u32,
|
||||
/// Selection & Anchor Display → Object Selection by Path Only: a click inside a filled path
|
||||
/// doesn't pick it, only one on its path does.
|
||||
pub path_only: bool,
|
||||
@@ -364,14 +362,6 @@ impl ToolContext<'_> {
|
||||
pub fn pick_tol(&self) -> f64 {
|
||||
self.tol(self.selection_tolerance)
|
||||
}
|
||||
/// How near (document units) a press picks an anchor or a direction handle's end: the
|
||||
/// selection tolerance, but at least 2 px past the drawn point, so a point is easy to catch
|
||||
/// and wins over the segments through it, which are tested after it (#593).
|
||||
pub fn point_tol(&self) -> f64 {
|
||||
// Anchors are drawn 5 px wide at the default Size 3, a pixel more or less per step.
|
||||
let half = (5.0 + f64::from(self.anchor_size.clamp(1, 7)) - 3.0) / 2.0;
|
||||
self.tol(self.selection_tolerance.max(half + 2.0))
|
||||
}
|
||||
pub fn hit_options(&self) -> vectorcraft_doc::hit::HitOptions {
|
||||
vectorcraft_doc::hit::HitOptions {
|
||||
tol: self.pick_tol(),
|
||||
@@ -676,7 +666,6 @@ pub(crate) mod testutil {
|
||||
slices_locked: false,
|
||||
auto_add_delete: true,
|
||||
selection_tolerance: 3.0,
|
||||
anchor_size: 3,
|
||||
path_only: false,
|
||||
type_path_only: false,
|
||||
double_click_isolate: true,
|
||||
|
||||
@@ -91,11 +91,11 @@ fn last_anchor(cx: &ToolContext, id: NodeId) -> Option<(usize, usize)> {
|
||||
/// Alt held over a handle end, an anchor or a segment of a selected path: the Anchor Point tool's
|
||||
/// gesture, within its tolerance.
|
||||
fn alt_converts(cx: &ToolContext, p: Point, m: Mods) -> bool {
|
||||
let point = cx.point_tol();
|
||||
let tol = cx.pick_tol();
|
||||
m.alt
|
||||
&& (hit_handle(cx, p, point).is_some()
|
||||
|| crate::draw2::anchor_in(cx, editable_paths(cx), p, point).is_some()
|
||||
|| crate::draw2::segment_in(cx, editable_paths(cx), p, cx.pick_tol()).is_some())
|
||||
&& (hit_handle(cx, p, tol).is_some()
|
||||
|| crate::draw2::anchor_in(cx, editable_paths(cx), p, tol).is_some()
|
||||
|| crate::draw2::segment_in(cx, editable_paths(cx), p, tol).is_some())
|
||||
}
|
||||
|
||||
/// The selected paths the pen edits (not guides, nor locked or hidden ones).
|
||||
@@ -123,7 +123,7 @@ impl Tool for PenTool {
|
||||
self.drag.is_some() || self.handle.is_some() || self.convert.is_some()
|
||||
}
|
||||
fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec<Action> {
|
||||
let tol = cx.tol(5.0).max(cx.point_tol());
|
||||
let tol = cx.tol(5.0);
|
||||
// The path a press began is the selected one by the next event.
|
||||
if self.drawing && self.path.is_none() {
|
||||
self.path = active_path(cx).map(|a| a.0);
|
||||
@@ -297,7 +297,7 @@ impl Tool for PenTool {
|
||||
o
|
||||
}
|
||||
fn cursor(&self, cx: &ToolContext, p: Point, m: Mods) -> Cursor {
|
||||
let tol = cx.tol(5.0).max(cx.point_tol());
|
||||
let tol = cx.tol(5.0);
|
||||
if let Some((id, first, last, _)) = self.active(cx) {
|
||||
let one = last_anchor(cx, id).is_some_and(|(_, ai)| ai == 0);
|
||||
if p.distance(first) <= tol && !one {
|
||||
|
||||
@@ -384,6 +384,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);
|
||||
|
||||
@@ -84,6 +84,8 @@ pub fn inspect(app: &VectorcraftApp, ctx: &egui::Context) -> Value {
|
||||
"pinned": app.ui.task_bar_place.pinned,
|
||||
"rect": crate::canvas::task_bar_rect(ctx).map(|r| json!([r.left(), r.top(), r.width(), r.height()])),
|
||||
},
|
||||
// The Free Transform tool's widget, where it shows.
|
||||
"freeTransformWidget": crate::free_transform::rect(ctx).map(|r| json!([r.left(), r.top(), r.width(), r.height()])),
|
||||
"view": app.view().map(|v| serde_json::to_value(v).unwrap_or_default()),
|
||||
"canvasRect": app.canvas_rect.map(|c| json!([c.left(), c.top(), c.width(), c.height()])),
|
||||
"window": [r.width(), r.height()],
|
||||
|
||||
@@ -38,6 +38,7 @@ fn choices(command: &str, key: &str) -> Option<form::Choices> {
|
||||
match (command, key) {
|
||||
("type.pathOptions", "effect") => Some(crate::menus::PATH_EFFECTS),
|
||||
("type.pathOptions", "alignToPath") => Some(PATH_ALIGN),
|
||||
("text.areaOptions", "fit") => Some(AREA_FIT),
|
||||
("text.areaOptions", "firstBaseline") => Some(FIRST_BASELINE),
|
||||
("text.areaOptions", "verticalAlign") => Some(VERTICAL_ALIGN),
|
||||
_ => None,
|
||||
@@ -47,6 +48,9 @@ fn choices(command: &str, key: &str) -> Option<form::Choices> {
|
||||
/// Type on a Path Options › Align to Path.
|
||||
const PATH_ALIGN: form::Choices = &[("Ascender", "ascender"), ("Descender", "descender"), ("Center", "center"), ("Baseline", "baseline")];
|
||||
|
||||
/// Area Type Options › Fit.
|
||||
const AREA_FIT: form::Choices = &[("None", "none"), ("Auto Size", "autoHeight"), ("Shrink Text to Fit", "shrinkText")];
|
||||
|
||||
/// Area Type Options › First Baseline.
|
||||
const FIRST_BASELINE: form::Choices =
|
||||
&[("Ascent", "ascent"), ("Cap Height", "capHeight"), ("x Height", "xHeight"), ("Leading", "leading"), ("Fixed", "fixed")];
|
||||
|
||||
@@ -424,11 +424,8 @@ fn destination(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) {
|
||||
let pick = app.services.pick_folder.is_some();
|
||||
ui.horizontal(|ui| {
|
||||
form::text(ui, d, "folder", if pick { 300.0 } else { 334.0 });
|
||||
if pick
|
||||
&& widgets::icon_button(ui, "folder-open", tl!("Choose a folder"), false, 26.0).clicked()
|
||||
&& let Some(f) = app.services.pick_folder.as_mut().and_then(|pick| pick())
|
||||
{
|
||||
d.fields.insert("folder".into(), json!(f));
|
||||
if pick && widgets::icon_button(ui, "folder-open", tl!("Choose a folder"), false, 26.0).clicked() {
|
||||
crate::picks::folder_field(app, d, "folder");
|
||||
}
|
||||
});
|
||||
form::check(ui, d, "openLocation", tl!("Open Location after Export"));
|
||||
|
||||
@@ -145,10 +145,17 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(a) = act
|
||||
&& let Err(e) = run(app, d, a, &preset.name)
|
||||
{
|
||||
app.status(e);
|
||||
if let Some(a) = act {
|
||||
let r = if matches!(a, Action::Import) {
|
||||
// Its file dialog, shown off the UI thread, imports into the dialog as it is then.
|
||||
let current = preset.name.clone();
|
||||
crate::picks::in_dialog(app, d, move |app, d| run(app, d, Action::Import, ¤t))
|
||||
} else {
|
||||
run(app, d, a, &preset.name)
|
||||
};
|
||||
if let Err(e) = r {
|
||||
app.status(e);
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
@@ -181,7 +188,7 @@ fn run(app: &mut VectorcraftApp, d: &mut Dialog, act: Action, current: &str) ->
|
||||
return Ok(());
|
||||
}
|
||||
let pick = crate::FilePick { filters: vec![("Flattener presets", PRESET_EXTS)], ..Default::default() };
|
||||
let path = app.services.pick_open.as_mut().and_then(|f| f(&pick)).ok_or("cancelled")?;
|
||||
let path = crate::picks::open(app, &pick).ok_or("cancelled")?;
|
||||
let r = app.run("flattener.presets.import", json!({ "path": path }))?;
|
||||
if let Some(first) = r["imported"].get(0).and_then(Value::as_str) {
|
||||
select(d, first);
|
||||
|
||||
@@ -122,7 +122,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
|
||||
p if !p.is_empty() => p,
|
||||
_ => {
|
||||
let pick = crate::FilePick { filters: vectorcraft_engine::cmd::fileio::place_filters().collect(), ..Default::default() };
|
||||
app.services.pick_open.as_mut().and_then(|f| f(&pick)).ok_or("cancelled")?
|
||||
crate::picks::open(app, &pick).ok_or("cancelled")?
|
||||
}
|
||||
};
|
||||
out = app.run("links.relink", json!({ "ids": current["ids"], "path": path }))?;
|
||||
|
||||
@@ -315,7 +315,8 @@ pub fn cancel(app: &mut VectorcraftApp) {
|
||||
/// Apply the open dialog (OK).
|
||||
pub fn confirm(app: &mut VectorcraftApp) -> DialogResult {
|
||||
let Some(d) = app.ui.dialog.clone() else { return Err("no dialog open".into()) };
|
||||
(spec(&d.kind).confirm)(app, &d)
|
||||
// A file dialog it shows off the UI thread confirms the dialog as it is again.
|
||||
crate::picks::as_entry(app, || crate::picks::Entry::Confirm(Box::new(d.clone())), |app| (spec(&d.kind).confirm)(app, &d))
|
||||
}
|
||||
|
||||
pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
|
||||
@@ -70,11 +70,8 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
if !downloads(app) {
|
||||
widgets::label_row(ui, tl!("Location:"), LABEL, |ui| {
|
||||
form::text(ui, d, "folder", 230.0);
|
||||
if let Some(pick) = app.services.pick_folder.as_mut()
|
||||
&& ui.button(tl!("Choose…")).clicked()
|
||||
&& let Some(f) = pick()
|
||||
{
|
||||
d.fields.insert("folder".into(), json!(f));
|
||||
if app.services.pick_folder.is_some() && ui.button(tl!("Choose…")).clicked() {
|
||||
crate::picks::folder_field(app, d, "folder");
|
||||
}
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
|
||||
@@ -102,10 +102,17 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
details(ui, &t, preset, builtin);
|
||||
});
|
||||
});
|
||||
if let Some(a) = act
|
||||
&& let Err(e) = run(app, d, a, &preset.name)
|
||||
{
|
||||
app.status(e);
|
||||
if let Some(a) = act {
|
||||
let r = if matches!(a, Action::Import) {
|
||||
// Its file dialog, shown off the UI thread, imports into the dialog as it is then.
|
||||
let current = preset.name.clone();
|
||||
crate::picks::in_dialog(app, d, move |app, d| run(app, d, Action::Import, ¤t))
|
||||
} else {
|
||||
run(app, d, a, &preset.name)
|
||||
};
|
||||
if let Err(e) = r {
|
||||
app.status(e);
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
@@ -169,7 +176,7 @@ fn run(app: &mut VectorcraftApp, d: &mut Dialog, act: Action, current: &str) ->
|
||||
return Ok(());
|
||||
}
|
||||
let pick = crate::FilePick { filters: vec![("PDF presets", vectorcraft_engine::cmd::pdfcmds::PRESET_EXTS)], ..Default::default() };
|
||||
let path = app.services.pick_open.as_mut().and_then(|f| f(&pick)).ok_or("cancelled")?;
|
||||
let path = crate::picks::open(app, &pick).ok_or("cancelled")?;
|
||||
let r = app.run("pdf.preset.import", json!({ "path": path }))?;
|
||||
if let Some(first) = r["imported"].get(0).and_then(Value::as_str) {
|
||||
select(d, first);
|
||||
|
||||
@@ -150,10 +150,17 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
});
|
||||
});
|
||||
let name = preset.name.clone();
|
||||
if let Some(a) = act
|
||||
&& let Err(e) = run(app, d, a, &name)
|
||||
{
|
||||
app.status(e);
|
||||
if let Some(a) = act {
|
||||
let r = if matches!(a, Action::Import) {
|
||||
// Its file dialog, shown off the UI thread, imports into the dialog as it is then.
|
||||
let current = name.clone();
|
||||
crate::picks::in_dialog(app, d, move |app, d| run(app, d, Action::Import, ¤t))
|
||||
} else {
|
||||
run(app, d, a, &name)
|
||||
};
|
||||
if let Err(e) = r {
|
||||
app.status(e);
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
@@ -187,7 +194,7 @@ pub(super) fn run(app: &mut VectorcraftApp, d: &mut Dialog, act: Action, current
|
||||
return Ok(());
|
||||
}
|
||||
let pick = crate::FilePick { filters: vec![("Perspective grid presets", PRESET_EXTS)], ..Default::default() };
|
||||
let path = app.services.pick_open.as_mut().and_then(|f| f(&pick)).ok_or("cancelled")?;
|
||||
let path = crate::picks::open(app, &pick).ok_or("cancelled")?;
|
||||
let r = app.run("perspective.presets.import", json!({ "path": path }))?;
|
||||
if let Some(first) = r["imported"].get(0).and_then(Value::as_str) {
|
||||
select(d, first);
|
||||
|
||||
@@ -111,10 +111,17 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
}
|
||||
});
|
||||
});
|
||||
if let Some(a) = act
|
||||
&& let Err(e) = run(app, d, a, &name)
|
||||
{
|
||||
app.status(e);
|
||||
if let Some(a) = act {
|
||||
let r = if matches!(a, Action::Import) {
|
||||
// Its file dialog, shown off the UI thread, imports into the dialog as it is then.
|
||||
let current = name.clone();
|
||||
crate::picks::in_dialog(app, d, move |app, d| run(app, d, Action::Import, ¤t))
|
||||
} else {
|
||||
run(app, d, a, &name)
|
||||
};
|
||||
if let Err(e) = r {
|
||||
app.status(e);
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
@@ -149,7 +156,7 @@ pub(super) fn run(app: &mut VectorcraftApp, d: &mut Dialog, act: Action, current
|
||||
return Ok(());
|
||||
}
|
||||
let pick = crate::FilePick { filters: vec![("Print presets", PRESET_EXTS)], ..Default::default() };
|
||||
let path = app.services.pick_open.as_mut().and_then(|f| f(&pick)).ok_or("cancelled")?;
|
||||
let path = crate::picks::open(app, &pick).ok_or("cancelled")?;
|
||||
let r = app.run("print.presets.import", json!({ "path": path }))?;
|
||||
if let Some(first) = r["imported"].get(0).and_then(Value::as_str) {
|
||||
select(d, first);
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -634,3 +634,7 @@
|
||||
Clipboard Handling Práce se schránkou
|
||||
Appearance of Black Vzhled černé
|
||||
Devices Zařízení
|
||||
A file dialog is open: choose there first Je otevřené dialogové okno souboru: nejprve vyberte v něm
|
||||
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.
|
@@ -3598,3 +3598,7 @@ axis Both Ambos
|
||||
Off: an editable copy of its art, embedded in this document. Desactivado: una copia editable de su ilustración, incrustada en este documento.
|
||||
Images: link to the file instead of only embedding it. Imágenes: vincular al archivo en lugar de solo incrustarlo.
|
||||
VectorCraft documents: one locked object, updated when the file changes. Documentos de VectorCraft: un objeto bloqueado que se actualiza cuando cambia el archivo.
|
||||
A file dialog is open: choose there first Hay un cuadro de diálogo de archivos abierto: elija primero en él
|
||||
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.
|
@@ -3598,3 +3598,7 @@ axis Both Entrambi
|
||||
Off: an editable copy of its art, embedded in this document. Disattivato: una copia modificabile della sua grafica, incorporata in questo documento.
|
||||
Images: link to the file instead of only embedding it. Immagini: collega il file invece di incorporarlo soltanto.
|
||||
VectorCraft documents: one locked object, updated when the file changes. Documenti VectorCraft: un unico oggetto bloccato, aggiornato quando il file cambia.
|
||||
A file dialog is open: choose there first È aperta una finestra di dialogo dei file: scegli prima lì
|
||||
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.
|
@@ -3060,3 +3060,7 @@ theme Appearance 外観
|
||||
Off: an editable copy of its art, embedded in this document. オフ:アートの編集可能なコピーをこのドキュメントに埋め込みます。
|
||||
Images: link to the file instead of only embedding it. 画像:埋め込むだけでなく、ファイルにリンクします。
|
||||
VectorCraft documents: one locked object, updated when the file changes. VectorCraft ドキュメント:ロックされた 1 つのオブジェクト。ファイルの変更時に更新されます。
|
||||
A file dialog is open: choose there first ファイルダイアログが開いています。先にそちらで選択してください
|
||||
Constrain 制限
|
||||
Free Transform 自由変形
|
||||
Perspective Distort 遠近変形
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -2648,3 +2648,7 @@
|
||||
Off: an editable copy of its art, embedded in this document. Desativado: uma cópia editável da arte, incorporada neste documento.
|
||||
Images: link to the file instead of only embedding it. Imagens: vincular ao arquivo em vez de apenas incorporá-lo.
|
||||
VectorCraft documents: one locked object, updated when the file changes. Documentos do VectorCraft: um objeto bloqueado, atualizado quando o arquivo muda.
|
||||
A file dialog is open: choose there first Há uma caixa de diálogo de arquivos aberta: escolha nela primeiro
|
||||
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.
|
@@ -3596,3 +3596,7 @@ axis Both Оба
|
||||
Off: an editable copy of its art, embedded in this document. Выкл.: редактируемая копия его рисунка, внедрённая в этот документ.
|
||||
Images: link to the file instead of only embedding it. Изображения: связывать с файлом вместо простого внедрения.
|
||||
VectorCraft documents: one locked object, updated when the file changes. Документы VectorCraft: один заблокированный объект, обновляемый при изменении файла.
|
||||
A file dialog is open: choose there first Открыто окно выбора файла: сначала сделайте выбор в нём
|
||||
Constrain Ограничить
|
||||
Free Transform Свободное трансформирование
|
||||
Perspective Distort Искажение перспективы
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -3315,3 +3315,6 @@ axis Both 两者
|
||||
Off: an editable copy of its art, embedded in this document. 关闭:将其图稿的可编辑副本嵌入此文档。
|
||||
Images: link to the file instead of only embedding it. 图像:链接到文件,而不只是嵌入。
|
||||
VectorCraft documents: one locked object, updated when the file changes. VectorCraft 文档:一个锁定对象,文件更改时随之更新。
|
||||
A file dialog is open: choose there first 文件对话框已打开:请先在其中选择
|
||||
Constrain 约束
|
||||
Perspective Distort 透视扭曲
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -3090,3 +3090,7 @@ axis Both 兩者
|
||||
Off: an editable copy of its art, embedded in this document. 關閉:將其圖稿的可編輯副本內嵌在此文件中。
|
||||
Images: link to the file instead of only embedding it. 影像:連結至檔案,而不只是嵌入。
|
||||
VectorCraft documents: one locked object, updated when the file changes. VectorCraft 文件:單一鎖定物件,檔案變更時隨之更新。
|
||||
A file dialog is open: choose there first 檔案對話方塊已開啟:請先在其中選擇
|
||||
Constrain 強制
|
||||
Free Transform 任意變形
|
||||
Perspective Distort 透視扭曲
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -72,7 +72,7 @@ pub fn open_document(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: O
|
||||
|
||||
/// A path from the open dialog, or "cancelled".
|
||||
fn pick_open(app: &mut VectorcraftApp, pick: &FilePick) -> Result<String, String> {
|
||||
app.services.pick_open.as_mut().and_then(|f| f(pick)).ok_or_else(|| "cancelled".into())
|
||||
crate::picks::open(app, pick).ok_or_else(|| "cancelled".into())
|
||||
}
|
||||
|
||||
/// Object › Plug-ins › Install Plug-in…: installs the `.wasm` at `path`, else a picked one (the
|
||||
@@ -164,7 +164,7 @@ fn pick_path(app: &mut VectorcraftApp, pick: &FilePick) -> Result<String, String
|
||||
if is_web(app) {
|
||||
return Ok(pick.name.clone());
|
||||
}
|
||||
let picked = app.services.pick_save.as_mut().and_then(|f| f(pick)).ok_or("cancelled")?;
|
||||
let picked = crate::picks::save(app, pick).ok_or("cancelled")?;
|
||||
Ok(with_extension(&picked, &fileio::extension(&pick.name), |_| true))
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
@@ -36,6 +37,7 @@ pub mod menus;
|
||||
pub mod native_menu;
|
||||
pub mod palette;
|
||||
pub mod panels;
|
||||
pub mod picks;
|
||||
pub mod place;
|
||||
pub mod prefs_dialog;
|
||||
pub mod print;
|
||||
@@ -95,6 +97,8 @@ mod tests_pathtype;
|
||||
#[cfg(test)]
|
||||
mod tests_pdfoutput;
|
||||
#[cfg(test)]
|
||||
mod tests_picks;
|
||||
#[cfg(test)]
|
||||
mod tests_place;
|
||||
#[cfg(test)]
|
||||
mod tests_plugins;
|
||||
@@ -233,6 +237,10 @@ pub struct Services {
|
||||
pub print: Option<Box<dyn print::PrintService>>,
|
||||
/// The macOS menu bar, when the desktop app installed one: the in-window menus are hidden then.
|
||||
pub native_menu: Option<native_menu::NativeMenu>,
|
||||
/// Show file dialogs off the UI thread (desktop Linux, where a dialog in line holds the window
|
||||
/// and the compositor finds it not answering): what asked runs again with the answer
|
||||
/// ([`picks`]). Without it they are shown in line.
|
||||
pub start_pick: Option<picks::StartPick>,
|
||||
}
|
||||
|
||||
/// Cached canvas raster.
|
||||
@@ -347,6 +355,8 @@ pub struct VectorcraftApp {
|
||||
/// The thread that checks the system clipboard for `system_paste` instead
|
||||
/// ([`Services::clipboard_probe`]).
|
||||
clipboard_probe: Option<clipboard_probe::Probe>,
|
||||
/// File dialogs shown off the UI thread and what runs again with their answers.
|
||||
pub(crate) picks: picks::Picks,
|
||||
/// The look for fonts installed or removed while the app was in the background, running
|
||||
/// ([`Self::refresh_installed_fonts`]): whether they were.
|
||||
font_check: Option<std::sync::mpsc::Receiver<bool>>,
|
||||
@@ -426,6 +436,7 @@ impl VectorcraftApp {
|
||||
system_paste: false,
|
||||
system_paste_at: f64::NEG_INFINITY,
|
||||
clipboard_probe: None,
|
||||
picks: picks::Picks::default(),
|
||||
font_check: None,
|
||||
paste_chord: Default::default(),
|
||||
background: Default::default(),
|
||||
@@ -489,6 +500,16 @@ impl VectorcraftApp {
|
||||
|
||||
/// Run a UI or engine command by id. The single entry point for every frontend path.
|
||||
pub fn run(&mut self, id: &str, params: Value) -> Result<Value, String> {
|
||||
// A file dialog it shows off the UI thread runs it again with the path picked.
|
||||
if self.picks.is_entry_free() {
|
||||
let entry = picks::Entry::Command(id.to_string(), params.clone());
|
||||
return picks::as_entry(self, move || entry, |app| app.run_now(id, params));
|
||||
}
|
||||
self.run_now(id, params)
|
||||
}
|
||||
|
||||
/// [`Self::run`] it, inside what asks for file dialogs.
|
||||
fn run_now(&mut self, id: &str, params: Value) -> Result<Value, String> {
|
||||
self.run_count = self.run_count.wrapping_add(1);
|
||||
if let Some(r) = menus::run_ui_command(self, id, ¶ms) {
|
||||
return r;
|
||||
@@ -790,6 +811,7 @@ impl VectorcraftApp {
|
||||
self.system_paste = wanted && self.system_clipboard_pasteable();
|
||||
}
|
||||
self.poll_font_check(ctx);
|
||||
picks::poll(self, ctx);
|
||||
background::poll(self);
|
||||
if !self.background.jobs.is_empty() {
|
||||
// Keep the status bar's progress moving and pick the result up when it arrives.
|
||||
|
||||
@@ -2848,7 +2848,8 @@ pub fn click_target(label: &str, id: &str, p: &Value) -> (String, Value) {
|
||||
/// are.
|
||||
fn queried_dialog(id: &str) -> Option<(&'static str, &'static [&'static str])> {
|
||||
Some(match id {
|
||||
"text.areaOptions" => ("Area Type Options", &[]),
|
||||
// Whether the text overflows, and Shrink Text's factor, are read-only facts.
|
||||
"text.areaOptions" => ("Area Type Options", &["overflow", "fitScale"]),
|
||||
"type.pathOptions" => ("Type on a Path Options", &["start", "end"]),
|
||||
_ => return None,
|
||||
})
|
||||
|
||||
@@ -185,17 +185,23 @@ fn collect(app: &mut VectorcraftApp, ctx: &egui::Context, ids: Option<Vec<NodeId
|
||||
/// folder picker: the last folder Export for Screens used, else the Desktop); the web downloads
|
||||
/// them, several as one zip.
|
||||
fn export(app: &mut VectorcraftApp, ids: Vec<u64>, files_each: usize) {
|
||||
// The folder picked off the UI thread exports them then.
|
||||
crate::picks::button(app, move |app| export_now(app, ids.clone(), files_each));
|
||||
}
|
||||
|
||||
fn export_now(app: &mut VectorcraftApp, ids: Vec<u64>, files_each: usize) {
|
||||
let mut p = json!({ "assets": ids });
|
||||
if io::is_web(app) {
|
||||
p["zip"] = json!(ids.len() * files_each > 1);
|
||||
} else {
|
||||
let saved = app.session.active().map(|st| st.doc.export_settings.clone()).unwrap_or_default();
|
||||
let folder = match app.services.pick_folder.as_mut() {
|
||||
Some(pick) => match pick() {
|
||||
let folder = if crate::picks::can(app, &crate::picks::PickRequest::Folder) {
|
||||
match crate::picks::folder(app) {
|
||||
Some(f) => f,
|
||||
None => return,
|
||||
},
|
||||
None => match saved
|
||||
}
|
||||
} else {
|
||||
match saved
|
||||
.get("folder")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|f| !f.is_empty())
|
||||
@@ -204,7 +210,7 @@ fn export(app: &mut VectorcraftApp, ids: Vec<u64>, files_each: usize) {
|
||||
{
|
||||
Some(f) => f,
|
||||
None => return app.status("choose a folder to export to".to_string()),
|
||||
},
|
||||
}
|
||||
};
|
||||
p["folder"] = json!(folder);
|
||||
p["openLocation"] = json!(saved.get("openLocation").and_then(Value::as_bool).unwrap_or(true));
|
||||
|
||||
@@ -154,7 +154,7 @@ pub(crate) fn pick_library_file(app: &mut VectorcraftApp, path: Option<String>)
|
||||
}
|
||||
path.or_else(|| {
|
||||
let pick = crate::FilePick { filters: vectorcraft_engine::cmd::fileio::open_filters().collect(), ..Default::default() };
|
||||
app.services.pick_open.as_mut().and_then(|f| f(&pick))
|
||||
crate::picks::open(app, &pick)
|
||||
})
|
||||
.map(Some)
|
||||
.ok_or_else(|| "cancelled".into())
|
||||
|
||||
@@ -116,15 +116,23 @@ fn report(app: &mut VectorcraftApp, r: Result<Value, String>, done: impl FnOnce(
|
||||
|
||||
/// Relink images `ids` to a picked file.
|
||||
pub(crate) fn relink(app: &mut VectorcraftApp, ids: Vec<u64>) {
|
||||
crate::picks::button(app, move |app| relink_picked(app, ids.clone()));
|
||||
}
|
||||
|
||||
fn relink_picked(app: &mut VectorcraftApp, ids: Vec<u64>) {
|
||||
let pick = crate::FilePick { filters: vectorcraft_engine::cmd::fileio::place_filters().collect(), ..Default::default() };
|
||||
let Some(path) = app.services.pick_open.as_mut().and_then(|f| f(&pick)) else { return };
|
||||
let Some(path) = crate::picks::open(app, &pick) else { return };
|
||||
let r = app.run("links.relink", json!({ "ids": ids, "path": path }));
|
||||
report(app, r, |v| format!("Relinked {} image(s)", v["relinked"].as_array().map_or(0, Vec::len)));
|
||||
}
|
||||
|
||||
/// Relink images `ids` (none: every missing one) to the files of their names in a picked folder.
|
||||
fn relink_to_folder(app: &mut VectorcraftApp, ids: Vec<u64>) {
|
||||
let Some(folder) = app.services.pick_folder.as_mut().and_then(|f| f()) else { return };
|
||||
crate::picks::button(app, move |app| relink_to_picked_folder(app, ids.clone()));
|
||||
}
|
||||
|
||||
fn relink_to_picked_folder(app: &mut VectorcraftApp, ids: Vec<u64>) {
|
||||
let Some(folder) = crate::picks::folder(app) else { return };
|
||||
let ids = Some(ids).filter(|i| !i.is_empty());
|
||||
let r = app.run("links.relink", json!({ "ids": ids, "folder": folder }));
|
||||
report(app, r, |v| {
|
||||
@@ -154,9 +162,12 @@ pub(crate) fn unembed(app: &mut VectorcraftApp, id: u64, name: &str) {
|
||||
}
|
||||
return;
|
||||
}
|
||||
let Some(path) = app.services.pick_save.as_mut().and_then(|f| f(&crate::FilePick::named(name))) else { return };
|
||||
let r = app.run("links.unembed", json!({ "id": id, "path": path }));
|
||||
report(app, r, |v| format!("Unembedded to {}", v["path"].as_str().unwrap_or_default()));
|
||||
let name = name.to_string();
|
||||
crate::picks::button(app, move |app| {
|
||||
let Some(path) = crate::picks::save(app, &crate::FilePick::named(&name)) else { return };
|
||||
let r = app.run("links.unembed", json!({ "id": id, "path": path }));
|
||||
report(app, r, |v| format!("Unembedded to {}", v["path"].as_str().unwrap_or_default()));
|
||||
});
|
||||
}
|
||||
|
||||
/// The UI commands `links.editOriginal` (open the linked file in its app) and `links.reveal`
|
||||
|
||||
@@ -0,0 +1,237 @@
|
||||
//! File dialogs that leave the window running (#592).
|
||||
//!
|
||||
//! The app asks for a path where it needs one (Open, Save As, Export, Place, Relink, presets…)
|
||||
//! and goes on with it at once, so a dialog shown on the UI thread holds the window until it
|
||||
//! closes. On Windows and macOS the dialog runs the window's events meanwhile; on Linux nothing
|
||||
//! does, so a Wayland compositor finds the window not answering and offers to kill it. There the
|
||||
//! host shows dialogs on another thread ([`Services::start_pick`]): asking returns no path for now,
|
||||
//! and when the dialog answers, what asked (the command, the dialog's OK, a panel's button: the
|
||||
//! *entry*) runs again and gets the picked path at once.
|
||||
|
||||
use std::rc::Rc;
|
||||
use std::sync::mpsc::{Receiver, TryRecvError};
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::state::Dialog;
|
||||
use crate::{FilePick, VectorcraftApp};
|
||||
|
||||
/// A file dialog to show.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum PickRequest {
|
||||
/// An open dialog for one file.
|
||||
Open(FilePick),
|
||||
/// An open dialog for files to place.
|
||||
OpenMany,
|
||||
/// A save dialog.
|
||||
Save(FilePick),
|
||||
/// A folder picker.
|
||||
Folder,
|
||||
}
|
||||
|
||||
/// The paths a dialog shown off the UI thread picked (none: cancelled).
|
||||
pub type PickAnswer = Vec<String>;
|
||||
|
||||
/// Shows a dialog off the UI thread; its answer arrives on the receiver. `None` when it can't, and
|
||||
/// the dialog is then shown in line.
|
||||
pub type StartPick = Box<dyn FnMut(PickRequest) -> Option<Receiver<PickAnswer>>>;
|
||||
|
||||
/// What runs again with the picked path.
|
||||
#[derive(Clone)]
|
||||
pub(crate) enum Entry {
|
||||
/// A command (`app.run`).
|
||||
Command(String, Value),
|
||||
/// A dialog's OK (`dialogs::confirm`), on the dialog as it was.
|
||||
Confirm(Box<Dialog>),
|
||||
/// A panel's or a dialog's button.
|
||||
Call(Rc<dyn Fn(&mut VectorcraftApp)>),
|
||||
}
|
||||
|
||||
/// A dialog shown off the UI thread, waiting for its answer.
|
||||
struct Waiting {
|
||||
request: PickRequest,
|
||||
answer: Receiver<PickAnswer>,
|
||||
entry: Entry,
|
||||
}
|
||||
|
||||
/// The app's file dialogs ([`VectorcraftApp`]'s `picks`).
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Picks {
|
||||
/// What is running now and asks for a path, the outermost one.
|
||||
entry: Option<Entry>,
|
||||
waiting: Option<Waiting>,
|
||||
/// A picked answer for the entry running again: the dialog it asks for gets it.
|
||||
answer: Option<(PickRequest, PickAnswer)>,
|
||||
}
|
||||
|
||||
impl Picks {
|
||||
/// Nothing asking for file dialogs is running.
|
||||
pub(crate) fn is_entry_free(&self) -> bool {
|
||||
self.entry.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
/// Run `f` as `entry`: a dialog it asks for off the UI thread runs `entry` again when it
|
||||
/// answers. Inside another entry, that one runs again instead.
|
||||
pub(crate) fn as_entry<R>(app: &mut VectorcraftApp, entry: impl FnOnce() -> Entry, f: impl FnOnce(&mut VectorcraftApp) -> R) -> R {
|
||||
if app.picks.entry.is_some() {
|
||||
return f(app);
|
||||
}
|
||||
app.picks.entry = Some(entry());
|
||||
let r = f(app);
|
||||
app.picks.entry = None;
|
||||
r
|
||||
}
|
||||
|
||||
/// [`as_entry`] for a panel's or a dialog's button that `f` handles.
|
||||
pub(crate) fn button(app: &mut VectorcraftApp, f: impl Fn(&mut VectorcraftApp) + 'static) {
|
||||
let f = Rc::new(f);
|
||||
let again = f.clone();
|
||||
as_entry(app, move || Entry::Call(again), |app| f(app));
|
||||
}
|
||||
|
||||
/// A dialog body's action `f` on `d` (the open dialog's copy) that asks for a file dialog: shown
|
||||
/// off the UI thread, its answer runs `f` again on the open dialog, when it is still of that kind.
|
||||
pub(crate) fn in_dialog(
|
||||
app: &mut VectorcraftApp,
|
||||
d: &mut Dialog,
|
||||
f: impl Fn(&mut VectorcraftApp, &mut Dialog) -> Result<(), String> + 'static,
|
||||
) -> Result<(), String> {
|
||||
let f = Rc::new(f);
|
||||
let (again, kind) = (f.clone(), d.kind.clone());
|
||||
let entry = move || {
|
||||
Entry::Call(Rc::new(move |app: &mut VectorcraftApp| {
|
||||
let Some(mut d) = app.ui.dialog.take() else { return };
|
||||
let r = if d.kind == kind { again(app, &mut d) } else { Ok(()) };
|
||||
app.ui.dialog = Some(d);
|
||||
if let Err(e) = r {
|
||||
app.status(e);
|
||||
}
|
||||
}))
|
||||
};
|
||||
as_entry(app, entry, |app| f(app, d))
|
||||
}
|
||||
|
||||
/// A dialog body's folder button: the folder picked into field `key` of `d` ([`in_dialog`]).
|
||||
pub(crate) fn folder_field(app: &mut VectorcraftApp, d: &mut Dialog, key: &'static str) {
|
||||
let r = in_dialog(app, d, move |app, d| {
|
||||
if let Some(f) = folder(app) {
|
||||
d.fields.insert(key.into(), serde_json::json!(f));
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
// Picking a folder doesn't fail.
|
||||
let _ = r;
|
||||
}
|
||||
|
||||
/// A path from an open dialog for `pick` (none: cancelled, or shown off the UI thread for now).
|
||||
pub(crate) fn open(app: &mut VectorcraftApp, pick: &FilePick) -> Option<String> {
|
||||
ask(app, PickRequest::Open(pick.clone()))?.into_iter().next()
|
||||
}
|
||||
|
||||
/// A path from a save dialog for `pick`.
|
||||
pub(crate) fn save(app: &mut VectorcraftApp, pick: &FilePick) -> Option<String> {
|
||||
ask(app, PickRequest::Save(pick.clone()))?.into_iter().next()
|
||||
}
|
||||
|
||||
/// A folder from the folder picker.
|
||||
pub(crate) fn folder(app: &mut VectorcraftApp) -> Option<String> {
|
||||
ask(app, PickRequest::Folder)?.into_iter().next()
|
||||
}
|
||||
|
||||
/// Paths from the open dialog for files to place (none: cancelled).
|
||||
pub(crate) fn open_many(app: &mut VectorcraftApp) -> Vec<String> {
|
||||
ask(app, PickRequest::OpenMany).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Whether the host shows `request`'s kind of dialog at all.
|
||||
pub(crate) fn can(app: &VectorcraftApp, request: &PickRequest) -> bool {
|
||||
let s = &app.services;
|
||||
match request {
|
||||
PickRequest::Open(_) => s.pick_open.is_some(),
|
||||
PickRequest::OpenMany => s.pick_open_multi.is_some() || s.pick_open.is_some(),
|
||||
PickRequest::Save(_) => s.pick_save.is_some(),
|
||||
PickRequest::Folder => s.pick_folder.is_some(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The paths `request`'s dialog picked: the answer kept for it, else shown off the UI thread (no
|
||||
/// paths for now), else shown in line.
|
||||
fn ask(app: &mut VectorcraftApp, request: PickRequest) -> Option<PickAnswer> {
|
||||
// One for another dialog is dropped: the entry took another way this time.
|
||||
if let Some((asked, answer)) = app.picks.answer.take()
|
||||
&& asked == request
|
||||
{
|
||||
return Some(answer);
|
||||
}
|
||||
if !can(app, &request) {
|
||||
return None;
|
||||
}
|
||||
if let (Some(entry), Some(start)) = (app.picks.entry.clone(), app.services.start_pick.as_mut()) {
|
||||
if app.picks.waiting.is_some() {
|
||||
app.status(tl!("A file dialog is open: choose there first"));
|
||||
return None;
|
||||
}
|
||||
if let Some(answer) = start(request.clone()) {
|
||||
app.picks.waiting = Some(Waiting { request, answer, entry });
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let s = &mut app.services;
|
||||
let one = |p: Option<String>| Some(p.into_iter().collect());
|
||||
match &request {
|
||||
PickRequest::Open(pick) => one(s.pick_open.as_mut().and_then(|f| f(pick))),
|
||||
PickRequest::Save(pick) => one(s.pick_save.as_mut().and_then(|f| f(pick))),
|
||||
PickRequest::Folder => one(s.pick_folder.as_mut().and_then(|f| f())),
|
||||
PickRequest::OpenMany => match (s.pick_open_multi.as_mut(), s.pick_open.as_mut()) {
|
||||
(Some(many), _) => Some(many()),
|
||||
(None, Some(f)) => one(f(&FilePick::default())),
|
||||
(None, None) => None,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Each frame: when the dialog shown off the UI thread answers with paths, run its entry again
|
||||
/// with them. While it is open, look again shortly.
|
||||
pub(crate) fn poll(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
let Some(w) = &app.picks.waiting else { return };
|
||||
let answer = match w.answer.try_recv() {
|
||||
Ok(answer) => answer,
|
||||
Err(TryRecvError::Empty) => {
|
||||
// What asked gave up for now: no "cancelled" while the dialog is open.
|
||||
if app.ui.status == "cancelled" {
|
||||
app.ui.status.clear();
|
||||
}
|
||||
ctx.request_repaint_after(std::time::Duration::from_millis(100));
|
||||
return;
|
||||
}
|
||||
// The dialog's thread is gone: as cancelled.
|
||||
Err(TryRecvError::Disconnected) => vec![],
|
||||
};
|
||||
let Some(Waiting { request, entry, .. }) = app.picks.waiting.take() else { return };
|
||||
if answer.is_empty() {
|
||||
return;
|
||||
}
|
||||
app.picks.answer = Some((request, answer));
|
||||
rerun(app, entry);
|
||||
// An entry that took another way this time leaves the answer unused.
|
||||
app.picks.answer = None;
|
||||
}
|
||||
|
||||
/// Run `entry` again.
|
||||
fn rerun(app: &mut VectorcraftApp, entry: Entry) {
|
||||
let r = match entry {
|
||||
Entry::Command(id, params) => app.run(&id, params).map(|_| ()),
|
||||
Entry::Confirm(d) => {
|
||||
app.ui.dialog = Some(*d);
|
||||
crate::dialogs::confirm(app).map(|_| ())
|
||||
}
|
||||
Entry::Call(f) => {
|
||||
f(app);
|
||||
Ok(())
|
||||
}
|
||||
};
|
||||
if let Err(e) = r {
|
||||
app.status(e);
|
||||
}
|
||||
}
|
||||
@@ -135,10 +135,10 @@ fn pick(app: &mut VectorcraftApp) -> Result<(), String> {
|
||||
f();
|
||||
return Ok(());
|
||||
}
|
||||
let paths = match (app.services.pick_open_multi.as_mut(), app.services.pick_open.as_mut()) {
|
||||
(Some(f), _) => f(),
|
||||
(None, Some(f)) => f(&crate::FilePick { filters: fileio::place_filters().collect(), ..Default::default() }).into_iter().collect(),
|
||||
(None, None) => vec![],
|
||||
let paths = if app.services.pick_open_multi.is_some() {
|
||||
crate::picks::open_many(app)
|
||||
} else {
|
||||
crate::picks::open(app, &crate::FilePick { filters: fileio::place_filters().collect(), ..Default::default() }).into_iter().collect()
|
||||
};
|
||||
if paths.is_empty() {
|
||||
return Err("cancelled".into());
|
||||
|
||||
@@ -458,7 +458,7 @@ pub fn run_command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option<Resu
|
||||
"shortcuts.export" => {
|
||||
let v = export_json(&app.ui.shortcut_set, &app.ui.shortcut_overrides);
|
||||
let bytes = serde_json::to_vec_pretty(&v).unwrap_or_default();
|
||||
let path = s("path").or_else(|| app.services.pick_save.as_mut().and_then(|f| f(&crate::FilePick::named("VectorCraft Shortcuts.json"))));
|
||||
let path = s("path").or_else(|| crate::picks::save(app, &crate::FilePick::named("VectorCraft Shortcuts.json")));
|
||||
match path {
|
||||
Some(path) => match app.services.write.as_mut() {
|
||||
Some(w) => w(&path, &bytes).map(|_| json!({"path": path})),
|
||||
@@ -477,7 +477,7 @@ pub fn run_command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option<Resu
|
||||
let data = if let Some(v) = p.get("data") {
|
||||
Ok(v.clone())
|
||||
} else {
|
||||
let path = s("path").or_else(|| app.services.pick_open.as_mut().and_then(|f| f(&crate::FilePick::default())));
|
||||
let path = s("path").or_else(|| crate::picks::open(app, &crate::FilePick::default()));
|
||||
match (path, app.services.read.as_ref()) {
|
||||
(Some(path), Some(r)) => r(&path).and_then(|b| serde_json::from_slice(&b).map_err(|e| e.to_string())),
|
||||
(None, _) => Err("cancelled".into()),
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
//! File dialogs shown off the UI thread (Linux, #592): what asked runs again with the answer.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
use std::sync::mpsc::{Sender, channel};
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_engine::Session;
|
||||
|
||||
use crate::picks::{self, PickRequest};
|
||||
use crate::state::Dialog;
|
||||
use crate::{FilePick, Services, VectorcraftApp};
|
||||
|
||||
const SVG: &[u8] = br#"<svg xmlns="http://www.w3.org/2000/svg" width="40" height="30"><rect width="10" height="10"/></svg>"#;
|
||||
|
||||
/// A dialog asked for, and where its answer goes.
|
||||
type Asked = (PickRequest, Sender<Vec<String>>);
|
||||
|
||||
/// The dialogs showing.
|
||||
#[derive(Clone, Default)]
|
||||
struct Shown(Rc<RefCell<Vec<Asked>>>);
|
||||
|
||||
impl Shown {
|
||||
fn requests(&self) -> Vec<PickRequest> {
|
||||
self.0.borrow().iter().map(|(r, _)| r.clone()).collect()
|
||||
}
|
||||
/// The last dialog shown answers `paths`.
|
||||
fn answer(&self, paths: &[&str]) {
|
||||
let (_, tx) = self.0.borrow_mut().pop().expect("a dialog is showing");
|
||||
tx.send(paths.iter().map(|p| p.to_string()).collect()).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
/// A desktop app whose dialogs show off the UI thread (none in line), reading [`SVG`] from any path
|
||||
/// and writing files to `written`.
|
||||
fn app() -> (VectorcraftApp, Shown, Rc<RefCell<Vec<String>>>) {
|
||||
let (shown, written) = (Shown::default(), Rc::new(RefCell::new(vec![])));
|
||||
let (s, w) = (shown.clone(), written.clone());
|
||||
let in_line = |_: &FilePick| -> Option<String> { panic!("no dialog on the UI thread") };
|
||||
let services = Services {
|
||||
pick_open: Some(Box::new(in_line)),
|
||||
pick_save: Some(Box::new(in_line)),
|
||||
pick_folder: Some(Box::new(|| panic!("no dialog on the UI thread"))),
|
||||
read: Some(Box::new(|_: &str| Ok(SVG.to_vec()))),
|
||||
write: Some(Box::new(move |path: &str, _: &[u8]| {
|
||||
w.borrow_mut().push(path.to_string());
|
||||
Ok(())
|
||||
})),
|
||||
start_pick: Some(Box::new(move |request: PickRequest| {
|
||||
let (tx, rx) = channel();
|
||||
s.0.borrow_mut().push((request, tx));
|
||||
Some(rx)
|
||||
})),
|
||||
..Default::default()
|
||||
};
|
||||
(VectorcraftApp::new(Session::new(), services), shown, written)
|
||||
}
|
||||
|
||||
fn poll(app: &mut VectorcraftApp) {
|
||||
picks::poll(app, &egui::Context::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_open_opens_what_its_dialog_picks_when_it_answers() {
|
||||
let (mut app, shown, _) = app();
|
||||
// The dialog shows; File › Open gives up for now, without a "cancelled".
|
||||
assert!(app.run("file.open", json!({})).is_err());
|
||||
assert!(matches!(shown.requests().as_slice(), [PickRequest::Open(_)]));
|
||||
poll(&mut app);
|
||||
assert!(app.session.documents().is_empty() && app.ui.status.is_empty(), "{}", app.ui.status);
|
||||
// Another dialog waits for this one.
|
||||
assert!(app.run("file.open", json!({})).is_err());
|
||||
assert_eq!(shown.requests().len(), 1);
|
||||
assert!(app.ui.status.contains("file dialog is open"), "{}", app.ui.status);
|
||||
shown.answer(&["/art/a.svg"]);
|
||||
poll(&mut app);
|
||||
assert_eq!(app.session.documents().len(), 1);
|
||||
assert_eq!(app.session.active().and_then(|d| d.path.clone()).as_deref(), Some("/art/a.svg"));
|
||||
// Cancelled: nothing happens, and dialogs show again.
|
||||
assert!(app.run("file.open", json!({})).is_err());
|
||||
shown.answer(&[]);
|
||||
poll(&mut app);
|
||||
assert_eq!(app.session.documents().len(), 1);
|
||||
assert!(app.run("file.open", json!({})).is_err());
|
||||
assert_eq!(shown.requests().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_as_goes_on_with_the_path_picked() {
|
||||
let (mut app, shown, written) = app();
|
||||
app.run("file.new", json!({"width": 100, "height": 80})).unwrap();
|
||||
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap();
|
||||
assert!(app.run("file.saveAs", json!({})).is_err());
|
||||
assert!(matches!(shown.requests().as_slice(), [PickRequest::Save(_)]));
|
||||
shown.answer(&["/art/poster.svg"]);
|
||||
poll(&mut app);
|
||||
// SVG Options asks next, and its OK writes the file there.
|
||||
assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some("svgOptions"));
|
||||
crate::dialogs::confirm(&mut app).unwrap();
|
||||
assert_eq!(*written.borrow(), ["/art/poster.svg"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dialogs_folder_button_fills_its_field_when_the_picker_answers() {
|
||||
let (mut app, shown, _) = app();
|
||||
let mut d = Dialog::new("exportForScreens", json!({"folder": ""}));
|
||||
app.ui.dialog = Some(d.clone());
|
||||
picks::folder_field(&mut app, &mut d, "folder");
|
||||
assert_eq!(shown.requests(), [PickRequest::Folder]);
|
||||
shown.answer(&["/out"]);
|
||||
poll(&mut app);
|
||||
assert_eq!(app.ui.dialog.as_ref().map(|d| d.str("folder")).as_deref(), Some("/out"));
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
+28
@@ -2219,6 +2219,34 @@ again, so SVG, PDF and EPS show the aligned text.
|
||||
{"name":"run_command","arguments":{"command":"text.areaOptions","params":{"verticalAlign":"center"}}}
|
||||
```
|
||||
|
||||
## Fitting area type: Auto Size, Shrink Text to Fit, overflow
|
||||
|
||||
`text.areaOptions` (and `text.create`'s `area`, `text.createInPath` in area mode) take a `fit`:
|
||||
|
||||
- `none` (default): the frame keeps its size; text that doesn't fit overflows (the red "+").
|
||||
- `autoHeight`: Auto Size. After every edit (typing, `text.editRange`, character and paragraph changes, a new
|
||||
width) the frame's bottom moves to just below the last line plus the inset, in the same undo step as the edit.
|
||||
In several columns the frame gets the least height (to 0.01 pt) at which the columns hold the text. It applies
|
||||
to rectangular frames of horizontal type in one row; `height` is ignored while it is on, and setting the height
|
||||
by hand (a handle drag, `text.reshapeArea` moving the bottom) turns it off, as does threading the frame. The
|
||||
`autoSizeAreaType` preference ("Auto Size New Area Type") gives new area type `autoHeight`.
|
||||
- `shrinkText` (beyond the reference app), with `fitMinPercent` (10–100, default 50): when the text overflows,
|
||||
every run's size, leading (explicit leading; auto leading follows the size) and baseline shift are scaled by the
|
||||
largest factor down to `fitMinPercent` % that makes it fit. Paragraph spacing and indents stay. The stored
|
||||
sizes don't change: the scaling happens at layout time, so rendering and every export see it. The factor is
|
||||
found by bisection over the first run's size in steps of 0.1 pt (its scaled size is a whole number of tenths of
|
||||
a point, so the result is deterministic); at `fitMinPercent` the text may still overflow.
|
||||
|
||||
The file stores `"fit": "autoHeight"` or `"fit": {"shrinkText": {"minPercent": 40}}` in the object's `area`; the
|
||||
command also accepts that object form. The query (and every reply) of `text.areaOptions` reports `fit` as its id,
|
||||
`fitMinPercent`, `overflow` (the text doesn't fit its frame) and `fitScale` (Shrink Text's factor, 1 unshrunk).
|
||||
`document.inspect` (and `document.node {summary: true}`) reports `overflow` for area type and type on a path (text past
|
||||
the end of the path), and `fit` and `fitScale` for area type.
|
||||
|
||||
```json
|
||||
{"name":"run_command","arguments":{"command":"text.areaOptions","params":{"fit":"shrinkText","fitMinPercent":60}}}
|
||||
```
|
||||
|
||||
## Converting between point type and area type
|
||||
|
||||
With the Selection tool, a single selected point or area type object shows the type widget: a small circle beside
|
||||
|
||||
Reference in new issue
Block a user