Compare commits
21
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
37d4477362 | ||
|
|
8d0cede84a | ||
|
|
030d407f61 | ||
|
|
465ec07445 | ||
|
|
5854346053 | ||
|
|
f4b4312cc9 | ||
|
|
0869f51360 | ||
|
|
d2aad22dac | ||
|
|
2e64786e8c | ||
|
|
367117ba26 | ||
|
|
5a09d1aef8 | ||
|
|
e1d560a727 | ||
|
|
07654ff45d | ||
|
|
53297259d2 | ||
|
|
b771a74361 | ||
|
|
04827da657 | ||
|
|
d066e0ddc0 | ||
|
|
89b10cce52 | ||
|
|
c7094320b3 | ||
|
|
2a35c4a82f | ||
|
|
0d68c1283a |
No files matched your search
Generated
+2
@@ -4312,8 +4312,10 @@ dependencies = [
|
||||
"rfd",
|
||||
"serde_json",
|
||||
"vectorcraft-engine",
|
||||
"vectorcraft-text",
|
||||
"vectorcraft-ui-egui",
|
||||
"webbrowser",
|
||||
"windows",
|
||||
"winit",
|
||||
"winresource",
|
||||
]
|
||||
|
||||
@@ -194,7 +194,7 @@ milestones, and honest time-to-parity estimates.
|
||||
"a power user can't tell the difference". Everyday vector illustration is close to usable: drawing and path tools,
|
||||
Pathfinder and Shape Builder, paint, gradients, appearance and transparency, type with styles, threading and Hebrew/Arabic bidirectional layout, and
|
||||
files (SVG, PDF and PDF-compatible `.ai` with PDF/X, EPS, DXF, EMF/WMF, raster formats and PSD, Print, Package). The interface
|
||||
speaks English, Japanese, Traditional and Simplified Chinese, Spanish and Italian (and Czech and Brazilian Portuguese in the menus).
|
||||
speaks English, Japanese, Traditional and Simplified Chinese, Spanish, Italian and Russian (and Czech and Brazilian Portuguese in the menus).
|
||||
The scores are
|
||||
self-assessed, so the [honest assessment](ROADMAP.md#honest-assessment-2026-10-05) explains how far to trust them.
|
||||
|
||||
|
||||
+9
-8
@@ -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
|
||||
|
||||
@@ -60,7 +60,8 @@ Ordered by how much each gap blocks someone from switching. Sizes are one-agent
|
||||
renderer in its own crate (layering allows it below L6), with output in SVG/PDF as rasters or projected vectors.
|
||||
The largest single gap. 50–80 h.
|
||||
4. **Advanced type:** CJK composition for vertical type (ruby, mojikumi, proportional vertical metrics, manual
|
||||
tate-chu-yoko), Optical Margin Alignment, the composer/hyphenation options, tab leaders, a
|
||||
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.
|
||||
5. **Brushes, symbols and libraries:** brush options depth; original brush, symbol and graphic-style libraries
|
||||
@@ -101,7 +102,7 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist
|
||||
- Tool flyouts tear off: dragging or clicking the tear-off bar on a flyout's right side (or releasing the long press over it) floats its group as a strip of tool buttons, moved by the same bar and put back in the toolbar by the × at its top (`window.floatTools`). While a group floats, the presses that would open its flyout raise the strip instead. Floating strips are kept with the preferences and in user workspaces. Not done: turning a strip vertical, docking it.
|
||||
- Panels undock (#495): a dock tab, a panel icon or a popped-out panel's title dragged out of the dock floats that panel inside the window, and the strip right of the dock's tabs floats the whole tabbed group. A floating group moves by its title bar, a tab dragged out of it floats on its own, and dropped on another group's title bar or tabs it stacks with that group; dropped on the dock, which lights up under the pointer, its panels go back where they live (the tabbed group or the icon column), as its × and the panel menus' Float Panel / Dock Panel do (`window.panel.float`, `window.panel.dock`). The Tools panel floats by its title bar and docks again on the window's left edge. Floating panels and the Tools panel's position are kept with the preferences and in user workspaces, and clamped into a smaller window. Not done: panels in separate OS windows, docking a panel into a dock group it doesn't belong to, reordering tabs by dragging, collapsing a floating group to icons, resizing floating panels.
|
||||
- The dock's double arrow collapses Properties, Layers and Libraries to icons at the top of the icon column, popping out like the other icon panels, and expands them again (`window.collapseDock`, kept with the preferences and in saved workspaces). The icon column's own arrow (expanding the icon panels into a full column) is not done.
|
||||
- Localised UI: menus (in-window and native), panels, dialogs, toolbar and Preferences read from per-language catalogs (`crates/ui-egui/src/i18n`, see `docs/development.md`); Traditional Chinese (Taiwan), Simplified Chinese (mainland), Japanese, Spanish and Italian ship complete, and Czech and Brazilian Portuguese cover every menu label (and more), with system-locale detection on macOS, Windows, Linux and the web (the browser's languages, or `?lang=`), a VectorCraft ▸ Language menu and a Language preference. Names are never translated (fonts and their styles, layers, artboards, saved presets, user libraries, custom workspaces, recent files, plug-ins).
|
||||
- Localised UI: menus (in-window and native), panels, dialogs, toolbar and Preferences read from per-language catalogs (`crates/ui-egui/src/i18n`, see `docs/development.md`); Traditional Chinese (Taiwan), Simplified Chinese (mainland), Japanese, Spanish, Italian and Russian ship complete, and Czech and Brazilian Portuguese cover every menu label (and more), with system-locale detection on macOS, Windows, Linux and the web (the browser's languages, or `?lang=`), a VectorCraft ▸ Language menu and a Language preference. Names are never translated (fonts and their styles, layers, artboards, saved presets, user libraries, custom workspaces, recent files, plug-ins).
|
||||
- Native macOS menu bar, vector tool cursors, a ⌘K command palette, middle-button panning with any tool. Native menus explicitly end tracking on command selection, outside window presses and Escape; menu updates wait until tracking ends, and a dismissing press never starts a canvas gesture (M14.8).
|
||||
- The macOS menu bar is built from the in-window menus (one model, `native_menu`) and laid out as a Mac app's: the VectorCraft menu holds About, Settings ▸ (each Preferences page, General… ⌘K), Language ▸, Appearance ▸ (UI brightness), Services, Hide VectorCraft ⌃⌘H (⌘H stays Hide Edges), Hide Others, Show All and Quit; Window gains Minimize ⌃⌘M, Zoom and Bring All to Front, and Help the system's search field. Its key equivalents go back to egui as key presses, so user shortcuts, focused text fields and the Type tool's input method behave as in the window, and nothing fires twice; enabled, check marks and labels update in place. `--in-window-menus` or `VECTORCRAFT_IN_WINDOW_MENUS=1` keeps the menus in the window; `ui.inspect` reports `nativeMenuBar`.
|
||||
- macOS: Finder opens every format File › Open reads with VectorCraft (double-click, Open With, a drop on the Dock icon, `open -a`), at launch or while it runs; the release and `cargo xtask bundle` apps share one `Info.plist` that declares those document types, owning only VectorCraft's own formats. The DMG opens on a designed Finder window, VectorCraft.app beside the `Applications` link over a background with the app icon (#493).
|
||||
@@ -138,8 +139,8 @@ 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), threaded text across any closed shapes, Fit Headline. Area type resizes like Illustrator's type areas: a bounding-box handle drag (Selection tool) or Area Type Options Width/Height size the frame and the text reflows at its size (threads too); Direct Selection drags a frame corner or edge (`text.reshapeArea`). Point type still scales. The Selection tool shows the type widget beside selected type's bounding box (hollow on point type, filled on area type); double-clicking it converts between them (Type › Convert To Area Type / Convert To Point Type), keeping the text and its styles in place. Variable fonts list every named instance as a style of their family (Figtree Light to Black and their italics, Bahnschrift, Segoe UI Variable), and the instance chosen is shaped, drawn, outlined and measured at its axis settings; PDF and SVG embed it as that instance. Variation axis sliders are not done. Hebrew and Arabic are laid out right to left with the Unicode bidirectional algorithm (embedded Latin and numbers keep their direction, lines put in visual order after wrapping) in point, area and path type, with caret, selection and arrow keys in visual order; each paragraph's direction comes from its first strong character unless Paragraph Direction sets it (Paragraph panel with Show Indic Options, `text.setFormat {direction}`), and new type aligns to the start of its direction. SVG export outlines right-to-left text. Font Size and Leading are combo boxes in the Character and Properties panels (Font Size in the Control bar too, beside the Character link, font family and style): type, step with ↑/↓ or the spinner, scrub the label, or pick a preset (6–72 pt, shown in the type unit; Leading also Auto), each pick one undo step; Kerning and Tracking list -100…200; a size, leading, kerning or tracking the selected text doesn't share shows blank (#458).
|
||||
- **Interface languages, vertical type:** VectorCraft ▸ Language (or Preferences ▸ User Interface) picks Automatic (the system locale) or a registered language, persisted as `interfaceLanguage`. Translations come from per-language catalogs (`i18n/*.tsv`): Traditional and Simplified Chinese, Japanese, Spanish (neutral international Spanish, for every `es-*` locale) and Italian (every `it-*` locale) cover the whole interface, Czech and Brazilian Portuguese every menu label, Brazilian Portuguese the shell's `tl!` literals too (tested); Spanish and Italian 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 and Italian ones from the bundled UI fonts. The web app follows the browser's languages (or `?lang=`). The Basic toolbar's Type button holds Vertical Type in its flyout. Vertical Type, Vertical Area Type and Vertical Type on a Path create vertical text (columns right to left, upright CJK glyphs and marks with `vert` alternates, Latin and longer numbers on their side, two- and three-digit numbers set as tate-chu-yoko in one em of the column (kept whole when justified), upright glyphs centred on the column (tracked or justified too), point type's anchor on the first column's centre line); kinsoku (the strict set) applies to horizontal and vertical Japanese, and justified Japanese lines spread their room between characters (not inside Latin words); Paragraph panel › Mojikumi Set (shown with Preferences › Type › Show East Asian Options, `text.setFormat {mojikumi}`): None or Line-end Punctuation Half Width (new type's default, as in Illustrator; older documents and imported text keep None) shares one half-em space between consecutive punctuation, sets a closing mark ending a line half width and an opening bracket starting a wrapped line flush with its start, and puts a quarter em between Japanese and Latin letters or digits; Paragraph panel menu › Top-to-Top / Bottom-to-Bottom Leading measures leading from em box top to top (area type's first line touches the frame) or from baseline to baseline (new type in a Japanese interface starts top to top, with em box centre character alignment, #432); Paragraph panel menu › Burasagari None / Regular / Force (`text.setFormat {burasagari: "none"|"standard"|"forced"}`) hangs an East Asian comma or full stop (、。,.、。) ending an area type line outside it, Regular (new type's default) when it doesn't fit and Force always (the rest of the line then fills the measure; closing brackets and Latin punctuation don't hang); Character panel menu › Character Alignment (with the East Asian options; `text.setFormat` or `text.setRangeStyle {charAlign}`) lines characters smaller than the largest on their line up on the Roman baseline or the em box top/right, centre or bottom/left (ICF top and bottom not yet); Type ▸ Type Orientation switches existing text; caret, selection, hit testing and arrow keys follow the writing direction. Vertical text exports to PDF as real text and to SVG as outlines.
|
||||
- **Type:** Text Wrap, Type on a Path effects (Rainbow/Skew/3D Ribbon/Stair Step/Gravity) and Options (Flip, Align to Path, Spacing; OK keeps the type where it is), type on a path's start, centre and end brackets (Selection and Direct Selection drag them to set where the type runs, slide it along its path and, across the path, flip it: #429), Character and Paragraph Styles (override-preserving redefine), Area Type Options (rows/columns/inset/first baseline), threaded text across any closed shapes, Fit Headline, the Every-line Composer for justified and ragged text (paragraph-wide breaks for an even rag, Single-line per object from the Paragraph panel menu or `text.setFormat {composer}`). Area type resizes like Illustrator's type areas: a bounding-box handle drag (Selection tool) or Area Type Options Width/Height size the frame and the text reflows at its size (threads too); Direct Selection drags a frame corner or edge (`text.reshapeArea`). Point type still scales. The Selection tool shows the type widget beside selected type's bounding box (hollow on point type, filled on area type); double-clicking it converts between them (Type › Convert To Area Type / Convert To Point Type), keeping the text and its styles in place. Variable fonts list every named instance as a style of their family (Figtree Light to Black and their italics, Bahnschrift, Segoe UI Variable), and the instance chosen is shaped, drawn, outlined and measured at its axis settings; PDF and SVG embed it as that instance. Variation axis sliders are not done. Hebrew and Arabic are laid out right to left with the Unicode bidirectional algorithm (embedded Latin and numbers keep their direction, lines put in visual order after wrapping) in point, area and path type, with caret, selection and arrow keys in visual order; each paragraph's direction comes from its first strong character unless Paragraph Direction sets it (Paragraph panel with Show Indic Options, `text.setFormat {direction}`), and new type aligns to the start of its direction. SVG export outlines right-to-left text. Font Size and Leading are combo boxes in the Character and Properties panels (Font Size in the Control bar too, beside the Character link, font family and style): type, step with ↑/↓ or the spinner, scrub the label, or pick a preset (6–72 pt, shown in the type unit; Leading also Auto), each pick one undo step; Kerning and Tracking list -100…200; a size, leading, kerning or tracking the selected text doesn't share shows blank (#458).
|
||||
- **Interface languages, vertical type:** VectorCraft ▸ Language (or Preferences ▸ User Interface) picks Automatic (the system locale) or a registered language, persisted as `interfaceLanguage`. Translations come from per-language catalogs (`i18n/*.tsv`): Traditional and Simplified Chinese, Japanese, Spanish (neutral international Spanish, for every `es-*` locale), Italian (every `it-*` locale) and Russian (every `ru-*` locale) cover the whole interface, Czech and Brazilian Portuguese every menu label, Brazilian Portuguese the shell's `tl!` literals too (tested); Spanish, Italian and Russian also translate status-bar and error messages as they are shown (`@msg` templates, every message literal tested; the messages themselves stay English for agents); untranslated text stays English. Japanese and Chinese glyphs come from the craft-fonts build input (release builds) or the installed fonts, Czech, Spanish, Italian and Russian ones from the bundled UI fonts. The web app follows the browser's languages (or `?lang=`). The Basic toolbar's Type button holds Vertical Type in its flyout. Vertical Type, Vertical Area Type and Vertical Type on a Path create vertical text (columns right to left, upright CJK glyphs and marks with `vert` alternates, Latin and longer numbers on their side, two- and three-digit numbers set as tate-chu-yoko in one em of the column (kept whole when justified), upright glyphs centred on the column (tracked or justified too), point type's anchor on the first column's centre line); kinsoku (the strict set) applies to horizontal and vertical Japanese, and justified Japanese lines spread their room between characters (not inside Latin words); Paragraph panel › Mojikumi Set (shown with Preferences › Type › Show East Asian Options, `text.setFormat {mojikumi}`): None or Line-end Punctuation Half Width (new type's default, as in Illustrator; older documents and imported text keep None) shares one half-em space between consecutive punctuation, sets a closing mark ending a line half width and an opening bracket starting a wrapped line flush with its start, and puts a quarter em between Japanese and Latin letters or digits; Paragraph panel menu › Top-to-Top / Bottom-to-Bottom Leading measures leading from em box top to top (area type's first line touches the frame) or from baseline to baseline (new type in a Japanese interface starts top to top, with em box centre character alignment, #432); Paragraph panel menu › Burasagari None / Regular / Force (`text.setFormat {burasagari: "none"|"standard"|"forced"}`) hangs an East Asian comma or full stop (、。,.、。) ending an area type line outside it, Regular (new type's default) when it doesn't fit and Force always (the rest of the line then fills the measure; closing brackets and Latin punctuation don't hang); Character panel menu › Character Alignment (with the East Asian options; `text.setFormat` or `text.setRangeStyle {charAlign}`) lines characters smaller than the largest on their line up on the Roman baseline or the em box top/right, centre or bottom/left (ICF top and bottom not yet); Type ▸ Type Orientation switches existing text; caret, selection, hit testing and arrow keys follow the writing direction. Vertical text exports to PDF as real text and to SVG as outlines.
|
||||
- **Transparency:** opacity masks (clip/invert/disable/link), exported as SVG `<mask>` and PDF soft masks.
|
||||
- **Advanced art:** live Blends (steps/distance/smooth colour, editable spine, anchor-targeted Blend tool, faithful interpolation, knockout), Envelope Distort (warp/mesh/top object, Reset, full Envelope Options, mesh handles, Edit Contents; type, images, symbols, gradients, patterns and appearance distorted everywhere), Liquify tools with options and pen pressure, Puppet Warp with rotating pins, Perspective Grid with presets, movable planes and projected type (choosing a perspective tool shows the grid; Hide Grid hides it with the tool still chosen), Gradient Mesh, Shape Builder (stroke-only open paths and lines cut the regions they cross and enclose regions of their own; filled open paths count as closed; erase mode while Alt/Option is held: a minus pointer, red highlights of what will go, a click or drag deletes the regions touched, the pieces of open lines and the edges (outline pieces between the points where paths meet, opening their paths there) it passes over, one undo step, `shapeBuilder.merge {erase}` and `shapeBuilder.regions` edges over MCP), Live Paint (every path an edge, open lines included), Image Trace (12 presets, colour layers traced in parallel; a trace past two million anchor points or an image over 64 megapixels is refused with advice rather than running out of memory, and a selection too large to outline shows its bounds (#525); Object › Image Trace › Make and Make and Expand trace at once with the Default preset, #543; with an image selected the Control bar and the Properties panel show Image Trace, whose arrow traces with any preset, Mask (`object.maskImage`: a clipping path on the image's outline, selected so its handles crop), Crop Image and Embed or Unembed in place of Fill and Stroke; with an Image Trace object selected, its Preset (choosing another traces again), the Image Trace panel and Expand, plus Release in Properties; the View modes are not done), pattern swatches with pattern editing mode, live Repeat (radial/grid/mirror).
|
||||
- **Paint and appearance (M3):**
|
||||
@@ -156,7 +157,7 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist
|
||||
- **Fonts:** a font is found by any of its names (family and style in every language of its name table, legacy family/style pairs, PostScript name), so documents from other apps open with the font they name; Find Font and `text.fonts` say for each font whether it was found exactly, by another name, substituted or missing, and how many glyphs are missing. PDF and `.ai` import brings Japanese text back as live type: CID fonts without a ToUnicode map read through the standard CMaps, vertical columns (WMode 1) as vertical type, letter spacing as tracking; a glyph is live type only when the installed font (in the closest style of its family) draws the same glyph, and text in a font that isn't installed comes in as live type shown in the fallback font until the font is installed (exports that draw it — PDF, EPS, EMF/WMF, raster, SVG outlines or embedded fonts — warn that they wrote the fallback font; `textAs: outlines` keeps the PDF's embedded glyphs).
|
||||
- **Files (M4):**
|
||||
- `.vectorcraft` (lossless JSON, compressed, atomic saves, save down to v1), Save As with a format chooser, Save a Copy, Revert, templates, Data Recovery after a crash (browser tabs hold their copies with Web Locks too, so a background tab's copies are never taken for a crash's, and a tab repairs copies another removed when it resumes: #367), background save and export. The desktop app writes its warnings and errors (graphics adapter, a lost graphics device, panics the guard recovered from) to standard error and to `logs/vectorcraft.log` next to the preferences, the two previous runs kept and each file capped at 16 MiB, so a launch without a terminal still leaves something to attach to a bug report (#465).
|
||||
- SVG/SVGZ in and out with SVG Options, Preserve Editing, symbols, filters, rich text and physical units (SVG type under a transform or `viewBox` scale opens at the size it draws at, the scale moved into its size, leading, baseline shift and strokes, a stretch, skew or rotation kept as its transform: #396; a top-level group with a clip path, such as a clipped Inkscape layer, opens as a layer with a clipping mask, its name kept: #420); PDF and PDF-compatible `.ai` in and out (layers, with hidden ones kept hidden with their art and nested ones as sublayers, on pages of up to 64 million operators, art whose layer can't be told going to a hidden, non-printing layer rather than showing or printing: #419; strokes kept live, a fill and a stroke of one outline as one object; a type object's stroke written as each glyph's outline stroked back on the type, so it stays one editable object; lines wrapped in a frame (each wrapped line ending in a space, one left edge, leading and font) back as one area type object, left aligned or justified with its paragraph spacing, where laying it out breaks the lines where the file does; glyphs set apart by gaps wider than a space (a barcode's digit groups) keeping their places; layers stacked as the pages mark them even when one first paints on a later page, art ending a layer's marked content or a clip closing in a later layer kept in its own layer, and layers with no art kept empty: #508; masks, editable text with type set along a curve coming back as type on a path, each artboard's art on its own page only, an `.ai`'s white page under its layers left out rather than coming in as art, spot colours, presets, security, marks and bleed, ICC output intents, raster effects, subset fonts, PDF/X, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3). CMYK images keep their ink amounts from PDF import (and from placed CMYK TIFFs) to PDF export: a CMYK JPEG passes through unchanged, others stay CMYK (DeviceCMYK, or ICC-based CMYK in PDF/X-3/X-4) unless the Output settings convert them; the canvas shows them through the working CMYK profile (#320).
|
||||
- SVG/SVGZ in and out with SVG Options, Preserve Editing, symbols, filters, rich text and physical units (SVG type under a transform or `viewBox` scale opens at the size it draws at, the scale moved into its size, leading, baseline shift and strokes, a stretch, skew or rotation kept as its transform: #396; a top-level group with a clip path, such as a clipped Inkscape layer, opens as a layer with a clipping mask, its name kept: #420; hidden objects written hidden on Save and `convert`, and `data-*` attributes kept as the objects' own data: #522); PDF and PDF-compatible `.ai` in and out (layers, with hidden ones kept hidden with their art and nested ones as sublayers, on pages of up to 64 million operators, art whose layer can't be told going to a hidden, non-printing layer rather than showing or printing: #419; strokes kept live, a fill and a stroke of one outline as one object; a type object's stroke written as each glyph's outline stroked back on the type, so it stays one editable object; lines wrapped in a frame (each wrapped line ending in a space, one left edge, leading and font) back as one area type object, left aligned or justified with its paragraph spacing, where laying it out breaks the lines where the file does; glyphs set apart by gaps wider than a space (a barcode's digit groups) keeping their places; layers stacked as the pages mark them even when one first paints on a later page, art ending a layer's marked content or a clip closing in a later layer kept in its own layer, and layers with no art kept empty: #508; masks, editable text with type set along a curve coming back as type on a path, each artboard's art on its own page only, an `.ai`'s white page under its layers left out rather than coming in as art, spot colours, presets, security, marks and bleed, ICC output intents, raster effects, subset fonts, PDF/X, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3). CMYK images keep their ink amounts from PDF import (and from placed CMYK TIFFs) to PDF export: a CMYK JPEG passes through unchanged, others stay CMYK (DeviceCMYK, or ICC-based CMYK in PDF/X-3/X-4) unless the Output settings convert them; the canvas shows them through the working CMYK profile (#320).
|
||||
- EPS and DXF in and out, EMF/WMF in and out; PNG (with PNG-8), JPEG, WebP, GIF, TIFF, BMP, Targa and layered PSD export. EPS import runs a PostScript Level 3 interpreter written from the PostScript Language Reference: resource categories and `resourceforall`, local and global VM (`currentglobal`/`setglobal`/`gcheck`), `clipsave`/`cliprestore`, subarrays and substrings that share storage, the standard dictionaries in `systemdict`, `dictstack`, `internaldict`, executable filters and strings, `load` by any key, `//name` immediate names, `token`, `execform`, user paths, `cshow`, `rootfont`, `cachestatus`, colour rendering and halftone queries, file `status` and data read with `flushfile`, and `pdfmark` marks dropped (Discord feedback, #466, #469, #474). Masked images (`ImageType 3` in its three interleavings) and reusable streams are read, and an image's several data sources are read in turn, as the reference defines (procedures that read one file get their own rows: such images came in banded, #498). `restore` puts dictionaries back as they were at the `save`, so programs that count their saves in a dictionary read to their end (part of #505). Tiling patterns come in as pattern swatches, uncoloured ones too; Type 3 fonts' glyphs as their outlines, spaced by `ashow`/`widthshow`/`xshow`/`kshow`; mesh and function-based shadings (types 1, 4–7) as gradient meshes; sampled functions (type 0) and Flate/LZW predictors are read. It is tested with programs written from the specification in the ways common generators use these features; Inkscape/cairo EPS files open as vectors. When a file's PostScript still can't be read, it opens as its TIFF preview, its Windows metafile preview (as vectors) or its EPSI preview, and the warning (in the status bar, `document.open`/`app.open`/MCP `open_file` replies and `vectorcraft-cli info`) names the error, the operator that raised it and the procedures it ran in. Legacy PostScript `.ai` files (Illustrator 3–8, written with the prolog that defines their operators) keep their groups and nested groups (`u` … `U`), between and inside clipping groups; EPS and EMF/WMF import nest clips (and groups) at most 128 deep, so a hostile file can't exhaust the stack. DXF TEXT justified Fit or Aligned spans its two points (stretched, or scaled as a whole).
|
||||
- Placed documents: File › Place of a `.vectorcraft` file links to it by default (`file.place`'s `link`): one locked object showing an artboard of the document (or its art's bounds), read the way placing it without Link reads it, its symbols, patterns and images kept apart from the document's; without Link (or from bytes, not a file) it is an editable copy as before. It stays vectors in every output (SVG, PDF, EPS, EMF, DXF), and so do placed documents inside it, read from their own files up to 8 levels deep (documents that place each other stop there). On screen they draw from bitmaps cached per file and zoom step, shared by every copy and made in the background (a placeholder until ready), so a sheet of them redraws in about a millisecond; exports and prints draw them exactly. Like linked images, a save keeps only a preview of each (JPEG when opaque) unless Include Linked Files; output, and zooming past the preview, read the file again, falling back to the preview with a warning when it is gone or changed. Saves for older versions write them as plain art. Links check, update, relink, Update Links on open, Link Info (the artboard's size), Placement Options, Break Link (also Embed, Object › Expand: the editable copy placing without Link gives, its resources joining the document), Edit Original (the document in a new tab) and the Links panel cover them; saving a document updates the open documents that place it. The native format (v4) keeps data of 8 KB or more after the JSON instead of base64 in it.
|
||||
- Place and the Links panel, Package, File Info, Print with print presets, PostScript output and print tiling, slices and Save for Web, Export for Screens and Asset Export, CSS Properties, PNG/PDF/SVG/text clipboard flavours; files copied in a file manager paste as art (SVG, PDF, EMF/WMF, bitmaps) on every desktop platform, and Linux/Wayland reads the compositor's clipboard (#398); on Linux the Paste menu checks the clipboard off the UI thread, so an X11 owner that never answers can't freeze the window (#510); screenshots and other copied pictures paste as embedded images at the view centre everywhere, the web included (#457).
|
||||
@@ -175,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), 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 and Paragraph Direction 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), 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 |
|
||||
@@ -210,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); composer/hyphenation options, Optical Margin Alignment, hidden characters, Transform Again after a type-area resize (it scales the type), partial selection of type-area anchors by marquee | 15–20 |
|
||||
| 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, 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 |
|
||||
|
||||
@@ -69,7 +69,8 @@ USAGE:
|
||||
Open IN (any readable format) and export OUT in the format its extension picks (see Writable
|
||||
formats). --artboard is 0-based, --range 1-based (\"1-3,5\"); a PDF gets every artboard
|
||||
unless one of them is given, EPS the bounds of the art, the other formats the first artboard.
|
||||
Live effects are kept; --outline-text writes SVG text as paths.
|
||||
Live effects are kept, and hidden layers and objects (written hidden in SVG and PSD), with
|
||||
SVG's data-* attributes; --outline-text writes SVG text as paths.
|
||||
|
||||
vectorcraft-cli info FILE
|
||||
Print a JSON summary: the import warnings (what didn't come in as it was, such as an EPS
|
||||
@@ -177,12 +178,10 @@ fn convert(args: &[String]) -> Result<(), String> {
|
||||
let [input, output] = <[String; 2]>::try_from(files).map_err(|_| "convert needs IN and OUT")?;
|
||||
let mut h = Headless::new();
|
||||
h.call("app.open", json!({"path": input})).map_err(|e| format!("open {input}: {e}"))?;
|
||||
let r = h
|
||||
.call(
|
||||
"engine.execute",
|
||||
json!({"command": "document.export", "params": {"path": output, "scale": scale, "artboard": artboard, "range": range, "outlineText": outline_text}}),
|
||||
)
|
||||
.map_err(|e| format!("export {output}: {e}"))?;
|
||||
// A conversion keeps hidden layers and objects, written hidden, where the format can (SVG,
|
||||
// PSD).
|
||||
let params = json!({"path": output, "scale": scale, "artboard": artboard, "range": range, "outlineText": outline_text, "hiddenLayers": true});
|
||||
let r = h.call("engine.execute", json!({"command": "document.export", "params": params})).map_err(|e| format!("export {output}: {e}"))?;
|
||||
outln!("{r}");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ windows7 = ["eframe/glow"]
|
||||
[dependencies]
|
||||
vectorcraft-engine = { workspace = true }
|
||||
vectorcraft-ui-egui = { workspace = true }
|
||||
vectorcraft-text = { workspace = true }
|
||||
eframe = { workspace = true, features = ["default_fonts", "wayland", "x11"] }
|
||||
egui = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
@@ -36,6 +37,11 @@ winit = { version = "0.30", default-features = false }
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
clipboard-win = { workspace = true }
|
||||
|
||||
# DirectWrite's system font collection (src/system_fonts.rs): fonts that font services such as
|
||||
# Adobe Fonts load in place (#579). MIT OR Apache-2.0, already in the build through accesskit.
|
||||
[target.'cfg(all(windows, not(target_vendor = "win7")))'.dependencies]
|
||||
windows = { version = "0.62", features = ["Win32_Graphics_DirectWrite"] }
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
# The macOS menu bar (src/mac_menu.rs): Tauri's menu crate, AppKit menus behind a safe API (no GTK
|
||||
# with default features off). Pinned exactly: review the diff before bumping.
|
||||
|
||||
@@ -27,11 +27,14 @@ mod mac_menu;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod open_documents;
|
||||
mod printing;
|
||||
#[cfg(all(windows, not(target_vendor = "win7")))]
|
||||
mod system_fonts;
|
||||
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 {
|
||||
@@ -183,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,
|
||||
@@ -193,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}"))
|
||||
@@ -228,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.
|
||||
@@ -264,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()
|
||||
@@ -314,6 +358,9 @@ fn main() -> std::process::ExitCode {
|
||||
// First, so every start-up warning is recorded (`logging`).
|
||||
let logger = logging::install();
|
||||
vectorcraft_ui_egui::i18n::detect_system_lang_in_background();
|
||||
// Before the first font scan (the app's start): the fonts font services load (#579).
|
||||
#[cfg(all(windows, not(target_vendor = "win7")))]
|
||||
system_fonts::install();
|
||||
let mut control_port: Option<u16> = std::env::var("VECTORCRAFT_CONTROL_PORT").ok().and_then(|p| p.parse().ok());
|
||||
let mut files = Vec::new();
|
||||
let mut in_window_menus = std::env::var_os("VECTORCRAFT_IN_WINDOW_MENUS").is_some_and(|v| !v.is_empty() && v != "0");
|
||||
@@ -392,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() {
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
//! Windows: the font files in DirectWrite's system font collection, scanned with the font folders
|
||||
//! (`vectorcraft_text::set_platform_font_files`).
|
||||
//!
|
||||
//! Font services such as Adobe Fonts load their fonts with GDI at run time, from files in their
|
||||
//! own folders, without installing them: the font folders and the registry don't list them. Since
|
||||
//! Windows 10 (version 1607) DirectWrite's system font collection holds them too
|
||||
//! (<https://learn.microsoft.com/windows/win32/directwrite/what-s-new-in-directwrite-for-windows-8-consumer-preview>,
|
||||
//! "Support for Adobe Typekit and other font-service clients"), so VectorCraft lists them as other
|
||||
//! apps do, reading the files in place (#579).
|
||||
//!
|
||||
//! DirectWrite is COM, which has no safe API, hence the scoped `unsafe_code` allowance.
|
||||
#![allow(unsafe_code)]
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use windows::Win32::Graphics::DirectWrite::{
|
||||
DWRITE_FACTORY_TYPE_SHARED, DWriteCreateFactory, IDWriteFactory3, IDWriteFontSet, IDWriteLocalFontFileLoader,
|
||||
};
|
||||
use windows::core::Interface;
|
||||
|
||||
/// The most fonts read from the collection (a system has a few thousand).
|
||||
const MAX_FONTS: u32 = 1 << 16;
|
||||
/// The longest file path taken, in UTF-16 units (Windows' own limit).
|
||||
const MAX_PATH: u32 = 32_767;
|
||||
|
||||
/// Have the font scans read the font files DirectWrite lists.
|
||||
pub fn install() {
|
||||
vectorcraft_text::set_platform_font_files(font_files);
|
||||
}
|
||||
|
||||
/// The local files of the fonts in DirectWrite's system font collection as it is now (fonts
|
||||
/// loaded since the last call included). None before Windows 10, or when DirectWrite fails: the
|
||||
/// font folders and the registry still list the installed fonts.
|
||||
fn font_files() -> Vec<String> {
|
||||
match collection_files() {
|
||||
Ok(files) => files.into_iter().collect(),
|
||||
Err(e) => {
|
||||
log::debug!("DirectWrite's system fonts aren't listed: {e}");
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn collection_files() -> windows::core::Result<BTreeSet<String>> {
|
||||
// SAFETY: plain DirectWrite calls on interfaces it returned, each checked for failure; the
|
||||
// collection is asked to check for fonts loaded since the factory last looked.
|
||||
let set = unsafe {
|
||||
let factory: IDWriteFactory3 = DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED)?;
|
||||
let mut collection = None;
|
||||
factory.GetSystemFontCollection(false, &mut collection, true)?;
|
||||
let Some(collection) = collection else { return Ok(BTreeSet::new()) };
|
||||
collection.GetFontSet()?
|
||||
};
|
||||
// SAFETY: a count of the set's fonts.
|
||||
let count = unsafe { set.GetFontCount() }.min(MAX_FONTS);
|
||||
// Faces of one file (a collection's, a variable font's instances) name it once.
|
||||
Ok((0..count).filter_map(|i| local_path(&set, i)).collect())
|
||||
}
|
||||
|
||||
/// The path of the file holding font `i` of `set`, when it is a local file (not a downloadable
|
||||
/// font, nor one in memory).
|
||||
fn local_path(set: &IDWriteFontSet, i: u32) -> Option<String> {
|
||||
// SAFETY: `i` is below the set's count; the key DirectWrite hands back stays valid while
|
||||
// `file` (which owns it) lives, and is passed back with its own size; the path buffer is
|
||||
// sized from DirectWrite's answer plus the terminating NUL.
|
||||
unsafe {
|
||||
let file = set.GetFontFaceReference(i).ok()?.GetFontFile().ok()?;
|
||||
let loader: IDWriteLocalFontFileLoader = file.GetLoader().ok()?.cast().ok()?;
|
||||
let (mut key, mut size) = (std::ptr::null_mut(), 0u32);
|
||||
file.GetReferenceKey(&mut key, &mut size).ok()?;
|
||||
let len = loader.GetFilePathLengthFromKey(key, size).ok()?;
|
||||
if len == 0 || len > MAX_PATH {
|
||||
return None;
|
||||
}
|
||||
let mut path = vec![0u16; len as usize + 1];
|
||||
loader.GetFilePathFromKey(key, size, &mut path).ok()?;
|
||||
Some(String::from_utf16_lossy(path.get(..len as usize)?))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
/// DirectWrite lists the installed fonts, by their files' full paths.
|
||||
#[test]
|
||||
fn directwrite_lists_the_installed_font_files() {
|
||||
let files = super::font_files();
|
||||
assert!(files.iter().all(|f| std::path::Path::new(f).is_absolute()), "{:?}", files.first());
|
||||
let fonts = std::path::Path::new(&std::env::var("WINDIR").unwrap()).join("Fonts").to_string_lossy().to_lowercase();
|
||||
assert!(files.iter().any(|f| f.to_lowercase().starts_with(&fonts)), "{} files, {:?}", files.len(), files.first());
|
||||
}
|
||||
}
|
||||
@@ -82,8 +82,8 @@ 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, FirstBaseline, Justify, LeadingModel, Mojikumi, ParaDirection, ParaStyle, PathAlign,
|
||||
PathEffect, ScriptMetrics, TabAlign, TabStop, TextKind, TextObject, TextRun, TextStyleDef, TextWrap, WrapShape,
|
||||
AreaOptions, Burasagari, CharAlign, CharPosition, CharStyle, Composer, FirstBaseline, Justify, LeadingModel, Mojikumi, ParaDirection, ParaStyle,
|
||||
PathAlign, PathEffect, ScriptMetrics, TabAlign, TabStop, TextKind, TextObject, TextRun, TextStyleDef, TextWrap, WrapShape,
|
||||
};
|
||||
pub use vectorcraft_color as color;
|
||||
pub use vectorcraft_geom as geom;
|
||||
|
||||
@@ -1214,6 +1214,10 @@ pub struct ObjectAttributes {
|
||||
/// The note shown in the Attributes panel.
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
pub note: String,
|
||||
/// The object's own data, in order: SVG's `data-*` attributes (`data-pivot="100,180"` is
|
||||
/// `("pivot", "100,180")`), kept from import to export (`object.setProps {data}`).
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub data: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
/// The Attributes panel's Image Map shapes.
|
||||
|
||||
@@ -285,6 +285,24 @@ fn default_align_on() -> char {
|
||||
/// Distance between default tab stops when no explicit stop applies (½ inch).
|
||||
pub const DEFAULT_TAB_INTERVAL: f64 = 36.0;
|
||||
|
||||
/// Paragraph composer (Paragraph panel menu): how lines are broken.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Composer {
|
||||
/// Break each line as soon as it is full.
|
||||
SingleLine,
|
||||
/// Total fit over the whole paragraph (Illustrator's default): justified lines get even word
|
||||
/// spacing, ragged lines an even rag.
|
||||
#[default]
|
||||
EveryLine,
|
||||
}
|
||||
|
||||
impl Composer {
|
||||
fn is_default(&self) -> bool {
|
||||
*self == Self::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Paragraph attributes (the Paragraph panel).
|
||||
///
|
||||
/// Saved through [`ParaStyleFile`], which keeps files with text openable by builds from before
|
||||
@@ -299,6 +317,8 @@ pub struct ParaStyle {
|
||||
pub space_before: f64,
|
||||
pub space_after: f64,
|
||||
pub hyphenate: bool,
|
||||
/// Line breaking: Single-line or Every-line Composer.
|
||||
pub composer: Composer,
|
||||
/// Tab stops (Tabs panel), sorted by position.
|
||||
pub tabs: Vec<TabStop>,
|
||||
/// Paragraph style (Paragraph Styles panel) these attributes come from; None = Normal.
|
||||
@@ -341,6 +361,8 @@ struct ParaStyleFile {
|
||||
space_after: f64,
|
||||
#[serde(default)]
|
||||
hyphenate: bool,
|
||||
#[serde(default, skip_serializing_if = "Composer::is_default")]
|
||||
composer: Composer,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
tabs: Vec<TabStop>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
@@ -370,6 +392,7 @@ impl From<ParaStyle> for ParaStyleFile {
|
||||
space_before,
|
||||
space_after,
|
||||
hyphenate,
|
||||
composer,
|
||||
tabs,
|
||||
style_name,
|
||||
mojikumi,
|
||||
@@ -387,6 +410,7 @@ impl From<ParaStyle> for ParaStyleFile {
|
||||
space_before,
|
||||
space_after,
|
||||
hyphenate,
|
||||
composer,
|
||||
tabs,
|
||||
style_name,
|
||||
mojikumi,
|
||||
@@ -407,6 +431,7 @@ impl From<ParaStyleFile> for ParaStyle {
|
||||
space_before,
|
||||
space_after,
|
||||
hyphenate,
|
||||
composer,
|
||||
tabs,
|
||||
style_name,
|
||||
mojikumi,
|
||||
@@ -423,6 +448,7 @@ impl From<ParaStyleFile> for ParaStyle {
|
||||
space_before,
|
||||
space_after,
|
||||
hyphenate,
|
||||
composer,
|
||||
tabs,
|
||||
style_name,
|
||||
mojikumi,
|
||||
|
||||
@@ -70,7 +70,7 @@ pub const OPTIONS: &[FormatOption] = &[
|
||||
name: "hiddenLayers",
|
||||
ty: "boolean",
|
||||
default: "false",
|
||||
description: "keep hidden layers, not displayed (display:none); document.save sets it unless given",
|
||||
description: "keep hidden layers and objects, not displayed (display=\"none\"); document.save sets it unless given",
|
||||
},
|
||||
FormatOption {
|
||||
name: "encoding",
|
||||
|
||||
@@ -150,7 +150,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Object Properties",
|
||||
[],
|
||||
None,
|
||||
"{ids?|id?, name?, visible?, locked?, opacity?: 0..100, blend?: \"Multiply\"…, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool}",
|
||||
"{ids?|id?, name?, visible?, locked?, opacity?: 0..100, blend?: \"Multiply\"…, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, data?: {key: \"value\" | null (removes it)} (the object's own data, SVG data-* attributes: {pivot: \"100,180\"} is data-pivot; document.node → attrs.data)}",
|
||||
has_doc,
|
||||
set_props
|
||||
),
|
||||
@@ -738,6 +738,32 @@ fn exit_isolation(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
ok()
|
||||
}
|
||||
|
||||
/// The most data entries `object.setProps` takes at once.
|
||||
const MAX_DATA: usize = 256;
|
||||
|
||||
/// `object.setProps`'s `data`: each key (a data-* attribute's name: letters, digits, `-`, `_`,
|
||||
/// `.`) with its value, or `None` to remove it.
|
||||
fn data_param(m: &serde_json::Map<String, Value>) -> Result<Vec<(String, Option<String>)>> {
|
||||
const C: &str = "object.setProps";
|
||||
if m.len() > MAX_DATA {
|
||||
return Err(bad(C, format!("data takes at most {MAX_DATA} keys at once")));
|
||||
}
|
||||
m.iter()
|
||||
.map(|(k, v)| {
|
||||
let k = k.strip_prefix("data-").unwrap_or(k);
|
||||
if k.is_empty() || !k.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.')) || k == "name" || k.starts_with("vc-") {
|
||||
return Err(bad(C, format!("data key `{k}`: letters, digits, -, _ and . (not name or vc-…)")));
|
||||
}
|
||||
let v = match v {
|
||||
Value::Null => None,
|
||||
Value::String(s) => Some(s.clone()),
|
||||
other => Some(other.to_string()),
|
||||
};
|
||||
Ok((k.to_string(), v))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn set_props(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = targets(s, p)?;
|
||||
let opacity = p.get("opacity").and_then(Value::as_f64).map(percent);
|
||||
@@ -745,6 +771,11 @@ fn set_props(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(b) => Some(BlendMode::parse(b).ok_or_else(|| bad("object.setProps", format!("unknown blend mode `{b}`")))?),
|
||||
None => None,
|
||||
};
|
||||
let data = match p.get("data") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(Value::Object(m)) => Some(data_param(m)?),
|
||||
Some(v) => return Err(bad("object.setProps", format!("data must be an object of key: value, not {v}"))),
|
||||
};
|
||||
let knockout = match p.get("knockout") {
|
||||
Some(v) => Some(
|
||||
Knockout::from_value(v)
|
||||
@@ -779,6 +810,24 @@ fn set_props(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(v) = p.get("knockoutShape").and_then(Value::as_bool) {
|
||||
n.knockout_shape = v;
|
||||
}
|
||||
if let Some(changes) = &data {
|
||||
n.edit_attrs(|a| {
|
||||
for (k, v) in changes {
|
||||
match (a.data.iter().position(|(key, _)| key == k), v) {
|
||||
(Some(i), Some(v)) => {
|
||||
if let Some(e) = a.data.get_mut(i) {
|
||||
e.1 = v.clone();
|
||||
}
|
||||
}
|
||||
(Some(i), None) => {
|
||||
a.data.remove(i);
|
||||
}
|
||||
(None, Some(v)) => a.data.push((k.clone(), v.clone())),
|
||||
(None, None) => {}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! Character/Paragraph attributes.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::NodeKind;
|
||||
use vectorcraft_doc::{Composer, NodeKind};
|
||||
use vectorcraft_geom::{Rect, Vec2};
|
||||
|
||||
use super::*;
|
||||
@@ -43,7 +43,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Character / Paragraph",
|
||||
[],
|
||||
None,
|
||||
"{ids?|id?, kerning?: 1/1000 em|\"auto\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt, hyphenate?: bool, mojikumi?: \"none\"|\"lineEndHalf\" (Japanese punctuation spacing), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\" (where characters smaller than the largest on their line line up with it), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\")}",
|
||||
"{ids?|id?, kerning?: 1/1000 em|\"auto\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt, hyphenate?: bool, mojikumi?: \"none\"|\"lineEndHalf\" (Japanese punctuation spacing), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\" (where characters smaller than the largest on their line line up with it), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), composer?: \"singleLine\"|\"everyLine\" (line breaking, Every-line by default)}",
|
||||
has_doc,
|
||||
set_format
|
||||
),
|
||||
@@ -219,10 +219,19 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"leadingModel",
|
||||
"charAlign",
|
||||
"burasagari",
|
||||
"composer",
|
||||
];
|
||||
if !keys.iter().any(|k| p.get(*k).is_some()) {
|
||||
return Err(bad(C, "nothing to change"));
|
||||
}
|
||||
let composer = match p.get("composer") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(v) => Some(match v.as_str() {
|
||||
Some("singleLine") => Composer::SingleLine,
|
||||
Some("everyLine") => Composer::EveryLine,
|
||||
_ => return Err(bad(C, "composer must be \"singleLine\" or \"everyLine\"")),
|
||||
}),
|
||||
};
|
||||
let (position, small_caps) = super::docsetup::script_params(p, &s.doc()?.doc.setup, C)?;
|
||||
let char_align = super::textedit::char_align_param(p, C)?;
|
||||
let mojikumi = match p.get("mojikumi") {
|
||||
@@ -329,6 +338,9 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(v) = burasagari {
|
||||
para.burasagari = v;
|
||||
}
|
||||
if let Some(v) = composer {
|
||||
para.composer = v;
|
||||
}
|
||||
super::typecmd::refresh_bounds(t);
|
||||
}
|
||||
Ok(())
|
||||
|
||||
@@ -190,3 +190,27 @@ fn svg_export_links_objects_and_import_reads_the_links_back() {
|
||||
});
|
||||
assert_eq!(urls, [Some("https://example.com/?a=1&b=2".to_string()), None], "the link wraps the path alone");
|
||||
}
|
||||
|
||||
/// #522: an object's own data (SVG `data-*` attributes) is set with `object.setProps {data}`,
|
||||
/// undone in one step, written to SVG and kept by the native format.
|
||||
#[test]
|
||||
fn object_data_is_set_saved_and_written_to_svg() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 10.0);
|
||||
let data = |s: &Session| s.doc().unwrap().doc.node(a).unwrap().attrs.as_deref().map(|x| x.data.clone()).unwrap_or_default();
|
||||
let pair = |k: &str, v: &str| (k.to_string(), v.to_string());
|
||||
run(&mut s, "object.setProps", json!({"data": {"pivot": "60,100", "z": 3}}));
|
||||
assert_eq!(data(&s), [pair("pivot", "60,100"), pair("z", "3")], "values are text");
|
||||
run(&mut s, "object.setProps", json!({"data": {"data-pivot": "1,2", "z": null}}));
|
||||
assert_eq!(data(&s), [pair("pivot", "1,2")], "a data- prefix is optional; null removes a key");
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(data(&s).len(), 2, "one step");
|
||||
for bad in [json!({"data": {"vc-x": "1"}}), json!({"data": {"name": "x"}}), json!({"data": {"a b": "1"}}), json!({"data": "pivot"})] {
|
||||
assert!(s.execute("object.setProps", &bad).is_err(), "{bad}");
|
||||
}
|
||||
let svg = run(&mut s, "document.serialize", json!({"format": "svg"}))["text"].as_str().unwrap().to_string();
|
||||
assert!(svg.contains("data-pivot=\"60,100\" data-z=\"3\""), "{svg}");
|
||||
let native = vectorcraft_format::save(&s.doc().unwrap().doc, false);
|
||||
let back = vectorcraft_format::load(&native).unwrap();
|
||||
assert_eq!(back.node(a).unwrap().attrs, s.doc().unwrap().doc.node(a).unwrap().attrs);
|
||||
}
|
||||
@@ -248,6 +248,16 @@ fn text_set_format() {
|
||||
let NodeKind::Text(t) = node(&s, id).kind else { panic!() };
|
||||
assert_eq!(t.first_style().kerning, None);
|
||||
assert!(s.execute("text.setFormat", &json!({"ids": [id.0]})).is_err());
|
||||
// Paragraph composer: Every-line by default, undoable.
|
||||
assert_eq!(t.para.composer, vectorcraft_doc::Composer::EveryLine);
|
||||
s.execute("text.setFormat", &json!({"ids": [id.0], "composer": "singleLine"})).unwrap();
|
||||
let NodeKind::Text(t) = node(&s, id).kind else { panic!() };
|
||||
assert_eq!(t.para.composer, vectorcraft_doc::Composer::SingleLine);
|
||||
assert!(s.execute("text.setFormat", &json!({"ids": [id.0], "composer": "best"})).is_err());
|
||||
assert!(s.execute("text.setFormat", &json!({"ids": [id.0], "composer": 1})).is_err());
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let NodeKind::Text(t) = node(&s, id).kind else { panic!() };
|
||||
assert_eq!(t.para.composer, vectorcraft_doc::Composer::EveryLine);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -7,7 +7,7 @@ use std::io::Write as _;
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{ColorProfiles, Document, ImageBlob, ImageObject, Node, NodeKind, OpacityMask, Symbol};
|
||||
use vectorcraft_doc::{ColorProfiles, Composer, Document, ImageBlob, ImageObject, Node, NodeKind, OpacityMask, Symbol};
|
||||
use vectorcraft_format::{FormatError, SaveOptions, VERSION, is_compressed, load, preview, save, save_with, sniff};
|
||||
use vectorcraft_geom::Affine;
|
||||
use vectorcraft_testkit::fixtures;
|
||||
@@ -111,6 +111,41 @@ fn keys_from_newer_versions_round_trip() {
|
||||
check_native_roundtrip(&d).unwrap();
|
||||
}
|
||||
|
||||
/// The paragraph composer is saved only when it isn't the default (Every-line) and reads back.
|
||||
#[test]
|
||||
fn text_composer_round_trips() {
|
||||
let d = rich_doc();
|
||||
let composers = |d: &Document| {
|
||||
let mut v = vec![];
|
||||
d.walk(|n| {
|
||||
if let NodeKind::Text(t) = &n.kind {
|
||||
v.push(t.para.composer);
|
||||
}
|
||||
});
|
||||
v
|
||||
};
|
||||
assert_eq!(composers(&d), [Composer::SingleLine]);
|
||||
let bytes = save(&d, false);
|
||||
assert!(String::from_utf8_lossy(&bytes).contains("\"composer\":\"singleLine\""));
|
||||
assert_eq!(composers(&load(&bytes).unwrap()), [Composer::SingleLine]);
|
||||
// Files without the key (older files, Every-line text) read as Every-line.
|
||||
fn strip(v: &mut Value) {
|
||||
match v {
|
||||
Value::Object(m) => {
|
||||
m.remove("composer");
|
||||
m.values_mut().for_each(strip);
|
||||
}
|
||||
Value::Array(a) => a.iter_mut().for_each(strip),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
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]);
|
||||
assert!(!String::from_utf8_lossy(&save(&d2, false)).contains("composer"));
|
||||
}
|
||||
|
||||
/// A document as the first version wrote it (format name `drawcraft`, anchors as maps).
|
||||
const V1_FILE: &str = r#"{"format":"drawcraft","version":1,"generator":"DrawCraft 0.1.0","document":{"version":1,"title":"Old","artboards":[{"id":1,"name":"Artboard 1","rect":{"x0":0.0,"y0":0.0,"x1":100.0,"y1":80.0}}],
|
||||
"layers":[{"id":1,"name":"Layer 1","visible":true,"locked":false,"opacity":1.0,"kind":{"type":"layer","children":[
|
||||
|
||||
@@ -50,9 +50,13 @@ pub(crate) fn blend_css(b: BlendMode) -> &'static str {
|
||||
}
|
||||
}
|
||||
|
||||
/// An object's opacity, blend mode and isolation.
|
||||
/// An object's opacity, blend mode and isolation, and `display: none` when it is hidden (written
|
||||
/// only when hidden objects are kept).
|
||||
pub(crate) fn transparency(n: &Node) -> Props {
|
||||
let mut p = Props::new();
|
||||
if !n.visible {
|
||||
p.push(("display", "none".into()));
|
||||
}
|
||||
if n.opacity < 1.0 {
|
||||
p.push(("opacity", fmt_num(n.opacity as f64, 3)));
|
||||
}
|
||||
|
||||
+18
-11
@@ -545,15 +545,25 @@ impl Writer<'_> {
|
||||
}
|
||||
/// ` id="…"` for a named object, plus ` data-name="…"` with the name itself when the id had to
|
||||
/// differ from it (spaces, punctuation, duplicates, the unique prefix).
|
||||
/// The id of `n`'s element (with its name when the id isn't it), then the object's own data
|
||||
/// as `data-*` attributes.
|
||||
fn id_attr(&self, n: &Node) -> String {
|
||||
if self.anonymous {
|
||||
return String::new();
|
||||
}
|
||||
let Some(id) = self.names.get(&n.id) else { return String::new() };
|
||||
match n.name.as_deref() {
|
||||
Some(name) if name != id => format!(" id=\"{}\" data-name=\"{}\"", xml_escape(id), xml_escape(name)),
|
||||
_ => format!(" id=\"{}\"", xml_escape(id)),
|
||||
let mut out = match (self.names.get(&n.id), n.name.as_deref()) {
|
||||
(Some(id), Some(name)) if name != id => format!(" id=\"{}\" data-name=\"{}\"", xml_escape(id), xml_escape(name)),
|
||||
(Some(id), _) => format!(" id=\"{}\"", xml_escape(id)),
|
||||
(None, _) => String::new(),
|
||||
};
|
||||
for (k, v) in n.attrs.as_deref().map_or(&[][..], |a| a.data.as_slice()) {
|
||||
// Names as XML takes them; ours (`name`, `vc-…`) are written by the export itself.
|
||||
let valid = k.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.')) && k != "name" && !k.starts_with("vc-");
|
||||
if valid && !k.is_empty() {
|
||||
out.push_str(&format!(" data-{k}=\"{}\"", xml_escape(v)));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
fn matrix(&self, m: Affine) -> String {
|
||||
let c = m.as_coeffs();
|
||||
@@ -1130,15 +1140,12 @@ impl Writer<'_> {
|
||||
std::mem::replace(&mut self.body, body)
|
||||
}
|
||||
|
||||
/// Props of a group (or layer): a knockout group is isolated, a hidden layer not displayed.
|
||||
/// Props of a group (or layer): a knockout group is isolated, a hidden one not displayed.
|
||||
fn group_props(&self, n: &Node) -> Props {
|
||||
let mut p = css::transparency(n);
|
||||
if !n.isolate && n.knocks_out(self.knockout) {
|
||||
p.push(("isolation", "isolate".into()));
|
||||
}
|
||||
if !n.visible {
|
||||
p.push(("display", "none".into()));
|
||||
}
|
||||
p
|
||||
}
|
||||
|
||||
@@ -1221,9 +1228,9 @@ impl Writer<'_> {
|
||||
}
|
||||
|
||||
fn node_body(&mut self, n: &Node) {
|
||||
// Hidden objects are left out; hidden layers too, unless the options keep them (hidden).
|
||||
let kept = self.opts.hidden_layers && matches!(n.kind, NodeKind::Layer { template: false, .. });
|
||||
if !(n.visible || kept) {
|
||||
// Hidden layers and objects are left out, unless the options keep them (hidden). Template
|
||||
// layers never print.
|
||||
if !(n.visible || self.opts.hidden_layers) {
|
||||
return;
|
||||
}
|
||||
if has_raster(&n.appearance.effects) {
|
||||
|
||||
@@ -64,6 +64,7 @@ pub(crate) fn import(svg: &str, opts: &ImportOptions) -> Result<(Document, Vec<S
|
||||
blends: fx::blends(&xml),
|
||||
files,
|
||||
non_scaling: found.non_scaling,
|
||||
data: found.data,
|
||||
screen: (kx * ky).sqrt(),
|
||||
};
|
||||
if im.files.nested_text() {
|
||||
@@ -124,6 +125,7 @@ pub(crate) fn import(svg: &str, opts: &ImportOptions) -> Result<(Document, Vec<S
|
||||
}
|
||||
im.add_unclipped(&mut l, 0, std::mem::take(&mut loose));
|
||||
l.visible = !im.hidden.contains(g.id());
|
||||
im.keep_data(g.id(), &mut l);
|
||||
im.doc.layers.push(Arc::new(l));
|
||||
}
|
||||
} else {
|
||||
@@ -210,6 +212,8 @@ struct Importer {
|
||||
files: files::Files,
|
||||
/// Ids of the shapes whose strokes don't scale ([`vector_effect`]).
|
||||
non_scaling: HashSet<String>,
|
||||
/// The `data-*` attributes of elements, by id ([`user_data`]).
|
||||
data: HashMap<String, Vec<(String, String)>>,
|
||||
/// Points per screen pixel (the root's user unit before its `viewBox`): what a non-scaling
|
||||
/// stroke's width is measured in.
|
||||
screen: f64,
|
||||
@@ -320,6 +324,8 @@ struct Found {
|
||||
files: files::Files,
|
||||
/// Ids of the shapes whose strokes don't scale ([`vector_effect`]).
|
||||
non_scaling: HashSet<String>,
|
||||
/// The `data-*` attributes of elements, by id ([`user_data`]).
|
||||
data: HashMap<String, Vec<(String, String)>>,
|
||||
warnings: Vec<String>,
|
||||
}
|
||||
|
||||
@@ -390,7 +396,7 @@ impl Edits {
|
||||
fn prepass<'s>(svg: &'s str, opts: &ImportOptions) -> (Cow<'s, str>, Found) {
|
||||
let mut found = Found::default();
|
||||
// (`:` for prefixed elements such as `<svg:image>`.)
|
||||
if !["<a", "display", "<use", ":use", "<image", ":image", vector_effect::NON_SCALING].iter().any(|t| svg.contains(t)) {
|
||||
if !["<a", "display", "<use", ":use", "<image", ":image", vector_effect::NON_SCALING, "data-"].iter().any(|t| svg.contains(t)) {
|
||||
return (svg.into(), found);
|
||||
}
|
||||
let Ok(xml) = roxmltree::Document::parse_with_options(svg, roxmltree::ParsingOptions { allow_dtd: true, ..Default::default() }) else {
|
||||
@@ -403,6 +409,14 @@ fn prepass<'s>(svg: &'s str, opts: &ImportOptions) -> (Cow<'s, str>, Found) {
|
||||
found.links.insert(edits.id(svg, a), url.to_string());
|
||||
}
|
||||
}
|
||||
if svg.contains("data-") {
|
||||
for e in elements().filter(|e| OBJECT_ELEMENTS.contains(&e.tag_name().name())) {
|
||||
let data = user_data(e);
|
||||
if !data.is_empty() {
|
||||
found.data.insert(edits.id(svg, e), data);
|
||||
}
|
||||
}
|
||||
}
|
||||
let symbols: HashSet<&str> = elements().filter(|n| n.tag_name().name() == "symbol").filter_map(|n| n.attribute("id")).collect();
|
||||
for u in elements().filter(|n| n.tag_name().name() == "use") {
|
||||
if let Some(sym) = href(u).and_then(|h| h.strip_prefix('#')).filter(|s| symbols.contains(s)) {
|
||||
@@ -456,6 +470,24 @@ fn tag_name_end(svg: &str, n: XNode) -> usize {
|
||||
svg.get(start + 1..).and_then(|s| s.find(|c: char| c.is_whitespace() || c == '/' || c == '>')).map_or(start + 2, |i| start + 1 + i)
|
||||
}
|
||||
|
||||
/// The elements that become objects, whose `data-*` attributes are kept.
|
||||
const OBJECT_ELEMENTS: &[&str] = &["g", "a", "use", "path", "rect", "circle", "ellipse", "line", "polyline", "polygon", "image"];
|
||||
|
||||
/// The most `data-*` attributes kept per element (the file is untrusted).
|
||||
const MAX_DATA: usize = 64;
|
||||
|
||||
/// The `data-*` attributes of element `e`, in order, without the `data-` (ours, `data-name` and
|
||||
/// `data-vc-*`, aside).
|
||||
fn user_data(e: XNode) -> Vec<(String, String)> {
|
||||
e.attributes()
|
||||
.filter(|a| a.namespace().is_none())
|
||||
.filter_map(|a| Some((a.name().strip_prefix("data-")?, a.value())))
|
||||
.filter(|(k, _)| !k.is_empty() && *k != "name" && !k.starts_with("vc-"))
|
||||
.take(MAX_DATA)
|
||||
.map(|(k, v)| (k.to_string(), v.to_string()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Make `n` link to `url`, unless it links somewhere already (an inner link wins).
|
||||
fn link(n: &mut Node, url: &str) {
|
||||
if n.url().is_none() {
|
||||
@@ -592,9 +624,18 @@ impl Importer {
|
||||
if self.hidden.contains(n.id()) {
|
||||
out.visible = false;
|
||||
}
|
||||
self.keep_data(n.id(), &mut out);
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// Give `n` the `data-*` attributes of element `id`, unless it has data already (what an
|
||||
/// inner element made of it keeps).
|
||||
fn keep_data(&self, id: &str, n: &mut Node) {
|
||||
if let Some(data) = self.data.get(id).filter(|_| n.attrs.as_ref().is_none_or(|a| a.data.is_empty())) {
|
||||
n.edit_attrs(|a| a.data = data.clone());
|
||||
}
|
||||
}
|
||||
|
||||
/// A gradient's stops, midpoints restored.
|
||||
fn stops(&self, g: &usvg::BaseGradient) -> Vec<GradientStop> {
|
||||
gradient_stops(g, self.midpoints.get(g.id()).map(Vec::as_slice))
|
||||
@@ -1114,9 +1155,10 @@ impl Importer {
|
||||
std::mem::take(&mut self.uses),
|
||||
std::mem::take(&mut self.labels),
|
||||
std::mem::take(&mut self.non_scaling),
|
||||
std::mem::take(&mut self.data),
|
||||
);
|
||||
let art = self.group_node(tree.root(), acc);
|
||||
(self.links, self.hidden, self.uses, self.labels, self.non_scaling) = outer;
|
||||
(self.links, self.hidden, self.uses, self.labels, self.non_scaling, self.data) = outer;
|
||||
art
|
||||
}
|
||||
}
|
||||
@@ -208,7 +208,8 @@ pub struct ExportOptions {
|
||||
/// One positioned `<tspan>` per line of type instead of one per style run, tab stop and
|
||||
/// justified word (smaller; viewers then space the line with their own font metrics).
|
||||
pub fewer_tspans: bool,
|
||||
/// Keep hidden layers, written hidden (`display:none`), as Save does; exports leave them out.
|
||||
/// Keep hidden layers and objects, written hidden (`display="none"`), as Save does; exports
|
||||
/// leave them out unless asked.
|
||||
pub hidden_layers: bool,
|
||||
/// The file's character encoding (see [`Output::bytes`]).
|
||||
pub encoding: Encoding,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Symbols export as one `<symbol>` def and a `<use>` per instance (instances the def can't stand
|
||||
//! for get their own art), hidden layers are kept hidden when asked and come back hidden, clipped
|
||||
//! layers come in as clipping layers, and the editing data notices edits made elsewhere.
|
||||
//! for get their own art), hidden layers and objects are kept hidden when asked and come back
|
||||
//! hidden with their `data-*` attributes, clipped layers come in as clipping layers, and the
|
||||
//! editing data notices edits made elsewhere.
|
||||
// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness).
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
@@ -205,6 +206,61 @@ fn hidden_layers_are_kept_hidden_when_asked() {
|
||||
}
|
||||
}
|
||||
|
||||
/// An animation rig (#522): hidden alternates (a group and a lone path) and rotation pivots kept as
|
||||
/// `data-*` attributes.
|
||||
const RIG: &str = r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200" width="200" height="200">
|
||||
<g id="character" data-pivot="100,180">
|
||||
<g id="arm" data-pivot="60,100" data-z-order="2"><path d="M40 100 L60 90 L80 110 Z" fill="#b5835a"/></g>
|
||||
<g id="arm-raised" data-pivot="60,100" display="none"><path d="M40 100 L50 60 L70 70 Z" fill="#b5835a"/></g>
|
||||
<path id="eye-closed" d="M90 80 L110 80 L100 95 Z" fill="#000" style="display:none" data-blink="1"/>
|
||||
</g>
|
||||
</svg>"##;
|
||||
|
||||
/// The `data-*` attributes of the object named `name`.
|
||||
fn data_of(d: &Document, name: &str) -> Vec<(String, String)> {
|
||||
let mut found = vec![];
|
||||
d.walk(|n| {
|
||||
if n.name.as_deref() == Some(name) {
|
||||
found = n.attrs.as_deref().map(|a| a.data.clone()).unwrap_or_default();
|
||||
}
|
||||
});
|
||||
found
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hidden_objects_and_data_attributes_round_trip() {
|
||||
let d = import(RIG).unwrap();
|
||||
let pivot = |v: &str| vec![("pivot".to_string(), v.to_string())];
|
||||
assert_eq!(data_of(&d, "character"), pivot("100,180"));
|
||||
assert_eq!(data_of(&d, "arm"), [("pivot".to_string(), "60,100".to_string()), ("z-order".to_string(), "2".to_string())]);
|
||||
assert_eq!(data_of(&d, "arm-raised"), pivot("60,100"));
|
||||
let hidden = |d: &Document| {
|
||||
let mut v = vec![];
|
||||
d.walk(|n| {
|
||||
if !n.visible {
|
||||
v.push(n.name.clone().unwrap_or_default());
|
||||
}
|
||||
});
|
||||
v
|
||||
};
|
||||
assert_eq!(hidden(&d), ["arm-raised", "eye-closed"]);
|
||||
// An export leaves the hidden objects out, their data with them; the others keep theirs.
|
||||
let plain = export(&d, &ExportOptions::default());
|
||||
assert!(!plain.contains("arm-raised") && !plain.contains("eye-closed") && plain.contains("data-pivot=\"60,100\""), "{plain}");
|
||||
let styles = [vectorcraft_svg::Styling::PresentationAttributes, vectorcraft_svg::Styling::InlineStyle, vectorcraft_svg::Styling::InternalCss];
|
||||
for styling in styles {
|
||||
// Kept (Save, or asked), they are written hidden and come back hidden, with every attribute.
|
||||
let kept = export(&d, &ExportOptions { hidden_layers: true, styling, ..Default::default() });
|
||||
assert!(kept.contains("data-pivot=\"100,180\"") && kept.contains("data-z-order=\"2\"") && kept.contains("data-blink=\"1\""), "{kept}");
|
||||
assert_eq!(resvg_render(&kept, 200, 200).pixel(100, 85), [255, 255, 255, 255], "hidden, not drawn: {kept}");
|
||||
let back = import(&kept).unwrap();
|
||||
assert_eq!(hidden(&back), ["arm-raised", "eye-closed"], "{kept}");
|
||||
for name in ["character", "arm", "arm-raised", "eye-closed"] {
|
||||
assert_eq!(data_of(&back, name), data_of(&d, name), "{name}: {kept}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Each layer's art: clipping layer or not, and the kinds of its children.
|
||||
fn layer_art(d: &Document) -> Vec<(String, bool, Vec<&'static str>)> {
|
||||
d.layers.iter().map(|l| (l.name.clone().unwrap_or_default(), l.clips(), l.children().unwrap().iter().map(|c| c.kind_label()).collect())).collect()
|
||||
|
||||
@@ -112,7 +112,9 @@ pub fn rich_session() -> Session {
|
||||
exec(&mut s, "effect.apply", json!({"effect": "distort.roughen", "params": {"size": 3, "detail": 5, "seed": 7}}));
|
||||
let l = id_of(&exec(&mut s, "shape.line", json!({"x1": 20, "y1": 300, "x2": 200, "y2": 350})));
|
||||
exec(&mut s, "stroke.set", json!({"weight": 3, "endArrow": "Arrow"}));
|
||||
let _ = id_of(&exec(&mut s, "text.create", json!({"x": 250, "y": 300, "text": "VectorCraft", "size": 30})));
|
||||
let tx = id_of(&exec(&mut s, "text.create", json!({"x": 250, "y": 300, "text": "VectorCraft", "size": 30})));
|
||||
// A non-default paragraph composer, so format round trips cover it.
|
||||
exec(&mut s, "text.setFormat", json!({"ids": [tx.0], "composer": "singleLine"}));
|
||||
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);
|
||||
|
||||
+122
-38
@@ -1,9 +1,17 @@
|
||||
//! Every-line composer: a Knuth–Plass style total-fit line breaker for justified paragraphs.
|
||||
//! Every-line composer: a Knuth–Plass style total-fit line breaker.
|
||||
//!
|
||||
//! Boxes are the paragraph's glyphs, glue is its spaces (word spacing may stretch to 150% and
|
||||
//! shrink to 80%), and penalties are break opportunities after hyphens/dashes/CJK and at
|
||||
//! hyphenation points. The breaks minimise the sum of squared (badness + penalty) demerits over
|
||||
//! the whole paragraph, so loose lines are traded for evenly spaced ones.
|
||||
//! Boxes are the paragraph's glyphs, glue is its spaces, and penalties are break opportunities
|
||||
//! after hyphens/dashes/CJK and at hyphenation points. The breaks minimise the sum of squared
|
||||
//! (badness + penalty) demerits over the whole paragraph, plus a demerit when neighbouring lines
|
||||
//! fall in fitness classes more than one apart (a tight line next to a loose one).
|
||||
//!
|
||||
//! - **Justified** lines: word spacing may stretch to 150% and shrink to 80%; the badness comes
|
||||
//! from the stretch/shrink ratio, so loose lines are traded for evenly spaced ones.
|
||||
//! - **Ragged** lines (left/centre/right aligned): spaces keep their width, so a line never
|
||||
//! shrinks (it must fit). The badness comes from the line's leftover space measured against a
|
||||
//! rag zone of a sixth of the line width, so the rag is even rather than full lines followed by
|
||||
//! a short one, and hyphenating costs less. The last line costs nothing unless it is shorter
|
||||
//! than a third of the width (a word or two left dangling).
|
||||
|
||||
use crate::shape::SGlyph;
|
||||
|
||||
@@ -12,6 +20,21 @@ const SHRINK: f64 = 0.2;
|
||||
const HYPHEN_PENALTY: f64 = 50.0;
|
||||
const DOUBLE_HYPHEN_DEMERITS: f64 = 3000.0;
|
||||
const LINE_PENALTY: f64 = 10.0;
|
||||
/// Demerits for adjacent lines whose fitness classes differ by more than one.
|
||||
const ADJ_DEMERITS_JUSTIFIED: f64 = 10_000.0;
|
||||
const ADJ_DEMERITS_RAGGED: f64 = 1_000.0;
|
||||
/// Ragged lines only gain from hyphenation by filling the rag, so it costs less than in
|
||||
/// justified text (where it also evens the word spacing).
|
||||
const HYPHEN_PENALTY_RAGGED: f64 = 25.0;
|
||||
/// Ragged text: leftover space is measured in units of this fraction of the line width.
|
||||
const RAG_ZONE: f64 = 1.0 / 6.0;
|
||||
/// Ragged text: a last line shorter than this fraction of the width is penalised, by how much
|
||||
/// shorter it is in units of `SHORT_LAST_ZONE` of the width.
|
||||
const SHORT_LAST: f64 = 1.0 / 3.0;
|
||||
const SHORT_LAST_ZONE: f64 = 1.0 / 3.0;
|
||||
/// Give up (fall back to the single-line composer) beyond this many active breakpoints.
|
||||
const MAX_ACTIVE: usize = 4096;
|
||||
const EPS: f64 = 1e-6;
|
||||
|
||||
/// A place a line may end: glyph index `end` (exclusive), plus the width of the hyphen that is
|
||||
/// added when breaking there (0 = no hyphen).
|
||||
@@ -21,24 +44,56 @@ pub(crate) struct Breakpoint {
|
||||
pub hyphen: f64,
|
||||
}
|
||||
|
||||
/// How a paragraph is composed.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) struct Params {
|
||||
/// The last line is justified too (Justify All).
|
||||
pub justify_last: bool,
|
||||
/// Left/centre/right aligned text: spaces keep their width and lines are scored by their rag.
|
||||
pub ragged: bool,
|
||||
/// Maximum stretch ratio (justified) or leftover space in rag zones (ragged) of a line.
|
||||
pub tolerance: f64,
|
||||
/// Lines from this index on all have the same width, so their line numbers are interchangeable
|
||||
/// (keeps the number of active breakpoints small).
|
||||
pub uniform_from: usize,
|
||||
}
|
||||
|
||||
struct Node {
|
||||
pos: usize,
|
||||
/// Line number of the next line, clamped to `uniform_from`.
|
||||
line: usize,
|
||||
fitness: u8,
|
||||
demerits: f64,
|
||||
hyphenated: bool,
|
||||
prev: Option<usize>,
|
||||
}
|
||||
|
||||
/// Fitness class 0 (tight) … 3 (very loose) of a line with adjustment ratio `r`.
|
||||
fn fitness(r: f64, ragged: bool) -> u8 {
|
||||
let bounds = if ragged { [0.15, 0.4, 0.75] } else { [-0.5, 0.5, 1.0] };
|
||||
if r < bounds[0] {
|
||||
0
|
||||
} else if r <= bounds[1] {
|
||||
1
|
||||
} else if r <= bounds[2] {
|
||||
2
|
||||
} else {
|
||||
3
|
||||
}
|
||||
}
|
||||
|
||||
/// Compose the paragraph `g` into lines. `width(k)` is the available width of line `k`;
|
||||
/// `cands` are the break opportunities in increasing order (the paragraph end is added).
|
||||
/// `justify_last`: the last line is justified too (Justify All). Returns `(end, hyphen)` per line,
|
||||
/// or `None` if no set of breaks fits within `tolerance` (maximum stretch ratio).
|
||||
/// `start_credit(i)` is the width a wrapped line starting at glyph `i` gives back (Mojikumi sets
|
||||
/// an opening bracket there flush with the line's start); `cands` are the break opportunities
|
||||
/// in increasing order (the paragraph end is added).
|
||||
/// Returns `(end, hyphen)` per line, or `None` if no set of breaks fits within the tolerance
|
||||
/// (the caller then falls back to single-line breaking).
|
||||
pub(crate) fn compose(
|
||||
g: &[SGlyph],
|
||||
width: &dyn Fn(usize) -> f64,
|
||||
start_credit: &dyn Fn(usize) -> f64,
|
||||
cands: &[Breakpoint],
|
||||
justify_last: bool,
|
||||
tolerance: f64,
|
||||
p: &Params,
|
||||
) -> Option<Vec<(usize, bool)>> {
|
||||
let n = g.len();
|
||||
if n == 0 {
|
||||
@@ -51,68 +106,93 @@ pub(crate) fn compose(
|
||||
w[i + 1] = w[i] + gl.adv;
|
||||
sp[i + 1] = sp[i] + if gl.is_space() { gl.adv } else { 0.0 };
|
||||
}
|
||||
if !w[n].is_finite() {
|
||||
return None;
|
||||
}
|
||||
// Trailing spaces are dropped at a break.
|
||||
let trim = |mut b: usize, a: usize| {
|
||||
while b > a && g[b - 1].is_space() {
|
||||
while b > a && g.get(b - 1).is_some_and(SGlyph::is_space) {
|
||||
b -= 1;
|
||||
}
|
||||
b
|
||||
};
|
||||
let mut all: Vec<Breakpoint> = cands.iter().copied().filter(|c| c.end > 0 && c.end < n).collect();
|
||||
all.push(Breakpoint { end: n, hyphen: 0.0 });
|
||||
let mut nodes = vec![Node { pos: 0, line: 0, demerits: 0.0, hyphenated: false, prev: None }];
|
||||
let (adj_demerits, hyphen_penalty) =
|
||||
if p.ragged { (ADJ_DEMERITS_RAGGED, HYPHEN_PENALTY_RAGGED) } else { (ADJ_DEMERITS_JUSTIFIED, HYPHEN_PENALTY) };
|
||||
let mut nodes = vec![Node { pos: 0, line: 0, fitness: 1, demerits: 0.0, hyphenated: false, prev: None }];
|
||||
let mut active: Vec<usize> = vec![0];
|
||||
for bp in &all {
|
||||
let last = bp.end == n;
|
||||
let mut best: Vec<(usize, f64, usize)> = vec![]; // (line, demerits, from)
|
||||
let mut best: Vec<(usize, u8, f64, usize)> = vec![]; // (line, fitness, demerits, from)
|
||||
let mut keep = Vec::with_capacity(active.len());
|
||||
for &ai in &active {
|
||||
let a = &nodes[ai];
|
||||
let Some(a) = nodes.get(ai) else { continue };
|
||||
let t = trim(bp.end, a.pos);
|
||||
let natural = w[t] - w[a.pos] + bp.hyphen;
|
||||
let spaces = sp[t] - sp[a.pos];
|
||||
let credit = if a.pos > 0 { start_credit(a.pos) } else { 0.0 };
|
||||
let natural = w[t] - w[a.pos] - credit + bp.hyphen;
|
||||
let lw = width(a.line);
|
||||
let ratio = if natural < lw {
|
||||
if last && !justify_last {
|
||||
0.0
|
||||
} else if spaces > 0.0 {
|
||||
(lw - natural) / (spaces * STRETCH)
|
||||
// Adjustment ratio, badness and whether the line ends the active node's reach.
|
||||
let ratio = if p.ragged {
|
||||
if natural > lw + EPS {
|
||||
// Ragged lines never shrink; longer lines from this node only get worse.
|
||||
continue;
|
||||
}
|
||||
if last && !p.justify_last {
|
||||
((lw * SHORT_LAST - natural) / (lw * SHORT_LAST_ZONE).max(1.0)).max(0.0)
|
||||
} else {
|
||||
f64::INFINITY
|
||||
(lw - natural).max(0.0) / (lw * RAG_ZONE).max(1.0)
|
||||
}
|
||||
} else if natural > lw {
|
||||
if spaces > 0.0 { (lw - natural) / (spaces * SHRINK) } else { f64::NEG_INFINITY }
|
||||
} else {
|
||||
0.0
|
||||
let spaces = sp[t] - sp[a.pos];
|
||||
if natural < lw {
|
||||
if last && !p.justify_last {
|
||||
0.0
|
||||
} else if spaces > 0.0 {
|
||||
(lw - natural) / (spaces * STRETCH)
|
||||
} else {
|
||||
f64::INFINITY
|
||||
}
|
||||
} else if natural > lw {
|
||||
if spaces > 0.0 { (lw - natural) / (spaces * SHRINK) } else { f64::NEG_INFINITY }
|
||||
} else {
|
||||
0.0
|
||||
}
|
||||
};
|
||||
if ratio < -1.0 {
|
||||
// Too long already; longer lines from this node only get worse.
|
||||
continue;
|
||||
}
|
||||
keep.push(ai);
|
||||
if ratio > tolerance && !(last && ratio.is_infinite() && justify_last) {
|
||||
let free_last = last && (p.ragged || !p.justify_last);
|
||||
if ratio > p.tolerance && !(last && (p.ragged || (ratio.is_infinite() && p.justify_last))) {
|
||||
continue;
|
||||
}
|
||||
let badness = if ratio.is_finite() { (100.0 * ratio.abs().powi(3)).min(10_000.0) } else { 10_000.0 };
|
||||
let penalty = if bp.hyphen > 0.0 { HYPHEN_PENALTY } else { 0.0 };
|
||||
let penalty = if bp.hyphen > 0.0 { hyphen_penalty } else { 0.0 };
|
||||
let mut d = (LINE_PENALTY + badness).powi(2) + penalty * penalty;
|
||||
if bp.hyphen > 0.0 && a.hyphenated {
|
||||
d += DOUBLE_HYPHEN_DEMERITS;
|
||||
}
|
||||
// A ragged last line's length says nothing about the rag: it keeps its neighbour's class.
|
||||
let fit = if p.ragged && free_last { a.fitness } else { fitness(ratio, p.ragged) };
|
||||
if a.prev.is_some() && fit.abs_diff(a.fitness) > 1 {
|
||||
d += adj_demerits;
|
||||
}
|
||||
let total = a.demerits + d;
|
||||
let line = a.line + 1;
|
||||
match best.iter_mut().find(|b| b.0 == line) {
|
||||
Some(b) if b.1 <= total => {}
|
||||
Some(b) => *b = (line, total, ai),
|
||||
None => best.push((line, total, ai)),
|
||||
let line = (a.line + 1).min(p.uniform_from);
|
||||
match best.iter_mut().find(|b| b.0 == line && b.1 == fit) {
|
||||
Some(b) if b.2 <= total => {}
|
||||
Some(b) => *b = (line, fit, total, ai),
|
||||
None => best.push((line, fit, total, ai)),
|
||||
}
|
||||
}
|
||||
active = keep;
|
||||
for (line, demerits, from) in best {
|
||||
nodes.push(Node { pos: bp.end, line, demerits, hyphenated: bp.hyphen > 0.0, prev: Some(from) });
|
||||
for (line, fitness, demerits, from) in best {
|
||||
nodes.push(Node { pos: bp.end, line, fitness, demerits, hyphenated: bp.hyphen > 0.0, prev: Some(from) });
|
||||
active.push(nodes.len() - 1);
|
||||
}
|
||||
if active.is_empty() {
|
||||
if active.is_empty() || active.len() > MAX_ACTIVE {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
@@ -120,10 +200,14 @@ pub(crate) fn compose(
|
||||
let mut out = vec![];
|
||||
let mut cur = Some(end);
|
||||
while let Some(i) = cur {
|
||||
if nodes[i].prev.is_some() {
|
||||
out.push((nodes[i].pos, nodes[i].hyphenated));
|
||||
let nd = nodes.get(i)?;
|
||||
if nd.prev.is_some() {
|
||||
out.push((nd.pos, nd.hyphenated));
|
||||
}
|
||||
cur = nd.prev;
|
||||
if out.len() > n {
|
||||
return None;
|
||||
}
|
||||
cur = nodes[i].prev;
|
||||
}
|
||||
out.reverse();
|
||||
Some(out)
|
||||
|
||||
@@ -3,13 +3,27 @@
|
||||
use harfrust::{Feature, Tag};
|
||||
use vectorcraft_doc::CharStyle;
|
||||
|
||||
/// Tracking (in 1/1000 em) outside which standard ligatures are dropped automatically: tighter
|
||||
/// than the first, looser than the second.
|
||||
///
|
||||
/// Letterspaced type should not ligate: an `fi` glyph keeps its letters tight while everything
|
||||
/// around it opens up (or stays open while it closes up), which reads as a blot. Small tracking
|
||||
/// adjustments made to fit a line are not letterspacing and keep the ligatures. The limits are
|
||||
/// about −8% and +22% of a typical word space (250/1000 em), the thresholds Adobe's composers are
|
||||
/// described as using (John Hudson, www-style, 2012-07): condensing shows the fixed ligature
|
||||
/// sooner than expanding. An explicit `liga` / `clig` in the character's own features always wins.
|
||||
pub const LIGATURE_TRACKING_LIMITS: (f64, f64) = (-20.0, 55.0);
|
||||
|
||||
/// OpenType features applied during shaping. Kerning, `case` and ligature suppression are driven
|
||||
/// by the character style (`kerning`, `all_caps`, `tracking`); the rest are layout-wide options.
|
||||
/// Standard ligatures are dropped when tracking is outside [`LIGATURE_TRACKING_LIMITS`], unless
|
||||
/// the character's features turn `liga` (or `clig`) on explicitly.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct OtFeatures {
|
||||
/// Vertical glyph alternates (`vert`), set by the writing direction.
|
||||
pub vertical: bool,
|
||||
/// Standard ligatures (`liga`, `clig`). Suppressed automatically when tracking is non-zero.
|
||||
/// Standard ligatures (`liga`, `clig`). Suppressed automatically when tracking is outside
|
||||
/// [`LIGATURE_TRACKING_LIMITS`], unless the character turns them on explicitly.
|
||||
pub ligatures: bool,
|
||||
/// Contextual alternates (`calt`).
|
||||
pub contextual: bool,
|
||||
@@ -117,7 +131,7 @@ impl OtFeatures {
|
||||
if st.kerning.is_some() {
|
||||
v.push(f(b"kern", false));
|
||||
}
|
||||
let liga = s.ligatures && st.tracking.abs() < 1e-9;
|
||||
let liga = s.ligatures && (!ligatures_suppressed_by(st.tracking) || explicit_ligatures(&st.features));
|
||||
if !liga {
|
||||
v.push(f(b"liga", false));
|
||||
v.push(f(b"clig", false));
|
||||
@@ -150,6 +164,28 @@ impl OtFeatures {
|
||||
}
|
||||
}
|
||||
|
||||
/// Does `tracking` (1/1000 em) count as letterspacing that drops standard ligatures?
|
||||
pub fn ligatures_suppressed_by(tracking: f64) -> bool {
|
||||
// A non-finite value is not a real letterspacing request; keep the default.
|
||||
let (tight, loose) = LIGATURE_TRACKING_LIMITS;
|
||||
tracking.is_finite() && (tracking < tight || tracking > loose)
|
||||
}
|
||||
|
||||
/// Do `features` turn standard ligatures on explicitly (`liga`, `+liga`, `clig`, `+clig`)? The last
|
||||
/// ligature tag wins, matching [`OtFeatures::with_tags`]. Absence of a tag means "default", which
|
||||
/// [`OtFeatures::to_tags`] never writes, so this is distinguishable from an explicit request.
|
||||
pub fn explicit_ligatures<S: AsRef<str>>(features: &[S]) -> bool {
|
||||
features
|
||||
.iter()
|
||||
.rev()
|
||||
.find_map(|t| match t.as_ref() {
|
||||
"liga" | "+liga" | "clig" | "+clig" => Some(true),
|
||||
"-liga" | "-clig" => Some(false),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -782,8 +782,29 @@ pub(crate) fn sfnt_of(tables: &[(&[u8; 4], &[u8])]) -> Option<Vec<u8>> {
|
||||
Some(font)
|
||||
}
|
||||
|
||||
/// The platform's font folders (the system's and the user's) and, on Windows, the font files
|
||||
/// registered with it outside them, scanned by [`FontDb::global`].
|
||||
/// Lists the font files the platform's font service knows, for [`set_platform_font_files`].
|
||||
pub type PlatformFontFiles = fn() -> Vec<String>;
|
||||
|
||||
/// What lists the platform's font files, set by the app ([`set_platform_font_files`]).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
static PLATFORM_FONT_FILES: std::sync::OnceLock<PlatformFontFiles> = std::sync::OnceLock::new();
|
||||
|
||||
/// Have [`system_font_dirs`] add the font files `list` gives (full paths) outside the font
|
||||
/// folders, asked again by each scan and each check for installed fonts
|
||||
/// ([`FontDb::installed_fonts_changed`]). The desktop app lists DirectWrite's system font
|
||||
/// collection on Windows: fonts a font service such as Adobe Fonts loads in place, from files
|
||||
/// outside the font folders and unknown to the registry (#579). Only the first call counts.
|
||||
pub fn set_platform_font_files(list: PlatformFontFiles) {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
// A second call keeps the first lister, as documented.
|
||||
let _ = PLATFORM_FONT_FILES.set(list);
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let _ = list;
|
||||
}
|
||||
|
||||
/// The platform's font folders (the system's and the user's) and the font files known to it
|
||||
/// outside them (on Windows those registered with it, and those [`set_platform_font_files`]
|
||||
/// lists), scanned by [`FontDb::global`].
|
||||
pub fn system_font_dirs() -> Vec<PathBuf> {
|
||||
let mut dirs: Vec<PathBuf> = Vec::new();
|
||||
if cfg!(target_arch = "wasm32") {
|
||||
@@ -824,6 +845,11 @@ pub fn system_font_dirs() -> Vec<PathBuf> {
|
||||
// In a Flatpak sandbox, the host's fonts (system, local and the user's).
|
||||
dirs.extend(["/run/host/fonts", "/run/host/local-fonts", "/run/host/user-fonts"].map(Into::into));
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Some(list) = PLATFORM_FONT_FILES.get() {
|
||||
let files = fonts_outside(list(), &dirs);
|
||||
dirs.extend(files);
|
||||
}
|
||||
dirs
|
||||
}
|
||||
|
||||
@@ -848,7 +874,7 @@ fn registered_font_files(font_dirs: &[PathBuf]) -> Vec<PathBuf> {
|
||||
/// The full paths among `registered` (font registrations' data) that aren't in `font_dirs`
|
||||
/// (ignoring case, as Windows paths do), sorted and deduplicated. File names alone are files in
|
||||
/// the Windows font folder, which is scanned anyway. The count is capped.
|
||||
#[cfg(any(windows, test))]
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn fonts_outside(registered: impl IntoIterator<Item = String>, font_dirs: &[PathBuf]) -> Vec<PathBuf> {
|
||||
const MAX_REGISTERED: usize = 1 << 16;
|
||||
let lower = |p: &Path| PathBuf::from(p.to_string_lossy().to_lowercase());
|
||||
@@ -1154,6 +1180,7 @@ impl FontDb {
|
||||
let mut n = 0;
|
||||
let paths = self.font_paths.get();
|
||||
let mut modified_at = Vec::new();
|
||||
// Each file with whether it was named by itself rather than found in a folder.
|
||||
let mut files = Vec::new();
|
||||
let mut stack = paths.clone();
|
||||
// Each folder once, however links lead back to it.
|
||||
@@ -1166,7 +1193,7 @@ impl FontDb {
|
||||
modified_at.push((d.clone(), modified(&d)));
|
||||
// Not a folder: a font file named by itself (or nothing, yet).
|
||||
let Ok(rd) = std::fs::read_dir(&d) else {
|
||||
files.push(d);
|
||||
files.push((d, true));
|
||||
continue;
|
||||
};
|
||||
for e in rd.flatten() {
|
||||
@@ -1174,13 +1201,15 @@ impl FontDb {
|
||||
if p.is_dir() {
|
||||
stack.push(p);
|
||||
} else {
|
||||
files.push(p);
|
||||
files.push((p, false));
|
||||
}
|
||||
}
|
||||
}
|
||||
for p in files {
|
||||
for (p, named) in files {
|
||||
// A file named by itself is a font whatever its name (font services keep fonts in
|
||||
// files without an extension); one of a folder's only with a font's extension.
|
||||
let ext = p.extension().and_then(|e| e.to_str()).map(|e| e.to_ascii_lowercase());
|
||||
if !matches!(ext.as_deref(), Some("ttf" | "otf" | "ttc" | "otc")) {
|
||||
if !named && !matches!(ext.as_deref(), Some("ttf" | "otf" | "ttc" | "otc")) {
|
||||
continue;
|
||||
}
|
||||
for FaceStyle { family, style, keys, weight, italic, traits, .. } in file_face_names(&p) {
|
||||
|
||||
@@ -9,7 +9,7 @@ use vectorcraft_doc::{
|
||||
};
|
||||
use vectorcraft_geom::{ArcPath, PathData};
|
||||
|
||||
use crate::composer::{Breakpoint, compose};
|
||||
use crate::composer::{Breakpoint, Params, compose};
|
||||
use crate::fontdb::FontDb;
|
||||
use crate::hyphen::hyphen_points;
|
||||
use crate::shape::{Punct, SGlyph, Tcy, cap_x_heights, hyphen_glyph, is_cjk, no_line_end, no_line_start, punct, shape_range, style_metrics};
|
||||
@@ -914,14 +914,18 @@ fn candidates(text: &str, g: &[SGlyph], hyphenate: bool) -> Vec<Breakpoint> {
|
||||
v
|
||||
}
|
||||
|
||||
/// Every-line composition of paragraph glyphs `sg` if applicable (justified area text with uniform
|
||||
/// line metrics); `None` falls back to the greedy single-line composer.
|
||||
fn compose_para(cx: &Ctx<'_>, sg: &[SGlyph], para: &ParaStyle, pen: &Pen<'_>) -> Option<Vec<(usize, bool)>> {
|
||||
let justified = !matches!(para.justify, Justify::Auto | Justify::Left | Justify::Center | Justify::Right);
|
||||
/// Paragraphs longer than this (glyphs) are always broken line by line.
|
||||
const MAX_COMPOSE_GLYPHS: usize = 200_000;
|
||||
|
||||
/// Every-line composition of paragraph glyphs `sg` if applicable (area text with uniform line
|
||||
/// metrics, justified or ragged); `None` falls back to the greedy single-line composer.
|
||||
fn compose_para(cx: &Ctx<'_>, sg: &[SGlyph], para: &ParaStyle, pen: &Pen<'_>, rtl: bool) -> Option<Vec<(usize, bool)>> {
|
||||
let ragged = matches!(para.justify, Justify::Auto | Justify::Left | Justify::Center | Justify::Right);
|
||||
let composer = cx.opts.composer.unwrap_or(para.composer);
|
||||
// A paragraph whose commas or full stops may hang is composed line by line (as the Japanese
|
||||
// single-line composer does).
|
||||
let may_hang = para.burasagari != Burasagari::None && sg.iter().any(hangs);
|
||||
if cx.opts.composer != Composer::EveryLine || !justified || pen.regions.is_none() || sg.len() < 2 || may_hang {
|
||||
if composer != Composer::EveryLine || pen.regions.is_none() || sg.len() < 2 || sg.len() > MAX_COMPOSE_GLYPHS || may_hang {
|
||||
return None;
|
||||
}
|
||||
let m = Metrics::of(&sg[0]);
|
||||
@@ -948,9 +952,21 @@ fn compose_para(cx: &Ctx<'_>, sg: &[SGlyph], para: &ParaStyle, pen: &Pen<'_>) ->
|
||||
}
|
||||
let last = *widths.last()?;
|
||||
let width = |k: usize| widths.get(k).copied().unwrap_or(last);
|
||||
// Lines from `uniform_from` on are interchangeable (same width).
|
||||
let uniform_from = widths.iter().rposition(|&w| (w - last).abs() > EPS).map_or(0, |k| k + 1);
|
||||
let cands = candidates(cx.text, sg, para.hyphenate);
|
||||
let justify_last = para.justify == Justify::JustifyAll;
|
||||
compose(sg, &width, &cands, justify_last, 1.0).or_else(|| compose(sg, &width, &cands, justify_last, 4.0))
|
||||
let params = |tolerance| Params { justify_last, ragged, tolerance, uniform_from };
|
||||
// Ragged: first look for breaks that leave at most one rag zone (a sixth of the width) on
|
||||
// each line, then accept any lines that fit.
|
||||
let (strict, loose) = if ragged { (1.0, f64::INFINITY) } else { (1.0, 4.0) };
|
||||
// The same rule as the line loop below: an opening bracket starting a wrapped line gives up
|
||||
// the space before it.
|
||||
let start_credit = |i: usize| {
|
||||
let flush = !rtl && para.mojikumi == Mojikumi::LineEndHalf;
|
||||
sg.get(i).filter(|g| flush && g.lead <= 0.0).and_then(|g| punct_half(g, Punct::Opening)).unwrap_or(0.0)
|
||||
};
|
||||
compose(sg, &width, &start_credit, &cands, ¶ms(strict)).or_else(|| compose(sg, &width, &start_credit, &cands, ¶ms(loose)))
|
||||
}
|
||||
|
||||
fn flow(cx: &mut Ctx<'_>, paras: &[Range<usize>], para: &ParaStyle, regions: Option<&[Region]>) {
|
||||
@@ -985,7 +1001,7 @@ fn flow(cx: &mut Ctx<'_>, paras: &[Range<usize>], para: &ParaStyle, regions: Opt
|
||||
pen.pending += para.space_before;
|
||||
}
|
||||
let n = sg.len();
|
||||
let composed = compose_para(cx, &sg, para, &pen);
|
||||
let composed = compose_para(cx, &sg, para, &pen, rtl);
|
||||
let mut li_para = 0;
|
||||
let mut i = 0;
|
||||
loop {
|
||||
|
||||
+9
-13
@@ -23,23 +23,18 @@ pub mod test_fonts;
|
||||
pub mod thread;
|
||||
|
||||
pub use craft_fonts::{CRAFT_FONTS, CraftFont};
|
||||
pub use features::OtFeatures;
|
||||
pub use fontdb::{FALLBACK_FAMILY, FontClass, FontDb, FontFace, FontMatch, FontTraits, style_weight, system_font_dirs};
|
||||
pub use features::{LIGATURE_TRACKING_LIMITS, OtFeatures, explicit_ligatures, ligatures_suppressed_by};
|
||||
pub use fontdb::{
|
||||
FALLBACK_FAMILY, FontClass, FontDb, FontFace, FontMatch, FontTraits, PlatformFontFiles, set_platform_font_files, style_weight, system_font_dirs,
|
||||
};
|
||||
use kurbo::{Affine, BezPath, Point, Rect, Vec2};
|
||||
pub use layout::{layout, layout_with};
|
||||
pub use vectorcraft_doc::TextObject;
|
||||
|
||||
pub use vectorcraft_doc::FirstBaseline;
|
||||
|
||||
/// Paragraph composer (Paragraph panel menu).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum Composer {
|
||||
/// Break each line as soon as it is full.
|
||||
SingleLine,
|
||||
/// Knuth–Plass total fit over the paragraph (justified area text only).
|
||||
#[default]
|
||||
EveryLine,
|
||||
}
|
||||
/// Paragraph composer; stored per text object in [`vectorcraft_doc::ParaStyle::composer`].
|
||||
pub use vectorcraft_doc::Composer;
|
||||
|
||||
/// Layout parameters that the document model doesn't store per object (Area Type Options,
|
||||
/// composer, OpenType features). [`layout`] takes rows/columns/inset/first baseline from the object.
|
||||
@@ -55,7 +50,8 @@ pub struct LayoutOptions {
|
||||
pub first_baseline: FirstBaseline,
|
||||
/// Minimum first-baseline offset in points.
|
||||
pub first_baseline_min: f64,
|
||||
pub composer: Composer,
|
||||
/// Overrides the object's paragraph composer (`None` = use `ParaStyle::composer`).
|
||||
pub composer: Option<Composer>,
|
||||
pub features: OtFeatures,
|
||||
}
|
||||
|
||||
@@ -68,7 +64,7 @@ impl Default for LayoutOptions {
|
||||
inset: 0.0,
|
||||
first_baseline: FirstBaseline::Ascent,
|
||||
first_baseline_min: 0.0,
|
||||
composer: Composer::EveryLine,
|
||||
composer: None,
|
||||
features: OtFeatures::default(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -237,3 +237,29 @@ fn the_database_tells_when_fonts_were_installed_or_removed_since_its_scan() {
|
||||
assert_eq!(db.load_system_fonts(), 2);
|
||||
assert_eq!(db.styles(FAMILY), ["Bold"]);
|
||||
}
|
||||
|
||||
/// A font a font service loads from a file without an extension, outside the font folders.
|
||||
fn service_font() -> PathBuf {
|
||||
std::env::temp_dir().join(format!("vc-sysfonts-{}-service", std::process::id())).join(".29457")
|
||||
}
|
||||
|
||||
/// The fonts a font service (Adobe Fonts on Windows, through DirectWrite) loads in place are
|
||||
/// cataloged: named by the platform's lister, read whatever their file is called (#579).
|
||||
#[test]
|
||||
fn fonts_the_platform_lists_outside_the_font_folders_are_cataloged() {
|
||||
let file = service_font();
|
||||
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
|
||||
std::fs::write(&file, renamed_to("SourceSans3-Regular.ttf", "Service Sans3")).unwrap();
|
||||
// The lister's files outside the font folders are scanned with them, each once (a collection
|
||||
// lists its file once per face).
|
||||
fn lister() -> Vec<String> {
|
||||
vec![service_font().to_string_lossy().into_owned(); 2]
|
||||
}
|
||||
set_platform_font_files(lister);
|
||||
let dirs = system_font_dirs();
|
||||
assert_eq!(dirs.iter().filter(|d| **d == file).count(), 1, "{dirs:?}");
|
||||
// A file named by itself is read without a font's extension, one in a folder isn't.
|
||||
let db = FontDb::with_font_dirs(vec![file.clone()]);
|
||||
assert_eq!(db.styles("Service Sans3"), ["Regular"]);
|
||||
assert!(!FontDb::with_font_dirs(vec![file.parent().unwrap().to_path_buf()]).has_family("Service Sans3"));
|
||||
}
|
||||
+134
-18
@@ -227,7 +227,7 @@ fn composer_lines_never_exceed_frame() {
|
||||
for (hy, composer) in [(false, Composer::EveryLine), (true, Composer::EveryLine), (false, Composer::SingleLine), (true, Composer::SingleLine)] {
|
||||
let mut t = area(©.repeat(2), style(12.0), Rect::new(0.0, 0.0, 180.0, 2000.0), Justify::JustifyLeft);
|
||||
t.para.hyphenate = hy;
|
||||
let l = layout_with(db(), &t, &LayoutOptions { composer, ..Default::default() });
|
||||
let l = layout_with(db(), &t, &LayoutOptions { composer: Some(composer), ..Default::default() });
|
||||
assert!(l.lines.len() > 10);
|
||||
for (i, li) in l.lines.iter().enumerate() {
|
||||
assert!(li.x1 - li.x0 <= 180.0 + 1e-6, "{composer:?} hy={hy} line {i} too wide: {li:?}");
|
||||
@@ -246,7 +246,7 @@ fn composer_lines_never_exceed_frame() {
|
||||
fn every_line_composer_is_more_even() {
|
||||
let t = area(©.repeat(2), style(12.0), Rect::new(0.0, 0.0, 190.0, 2000.0), Justify::JustifyLeft);
|
||||
let spread = |c: Composer| {
|
||||
let l = layout_with(db(), &t, &LayoutOptions { composer: c, ..Default::default() });
|
||||
let l = layout_with(db(), &t, &LayoutOptions { composer: Some(c), ..Default::default() });
|
||||
// Worst word-space stretch (space glyph advance) over all justified lines.
|
||||
let mut worst: f64 = 0.0;
|
||||
for li in &l.lines[..l.lines.len() - 1] {
|
||||
@@ -269,7 +269,7 @@ fn burasagari_keeps_the_every_line_composer_for_latin_text() {
|
||||
// A measure where the two composers break the copy differently.
|
||||
let mut t = area(©.repeat(2), style(12.0), Rect::new(0.0, 0.0, 300.0, 4000.0), Justify::JustifyLeft);
|
||||
let ends = |t: &TextObject, c: Composer| {
|
||||
let l = layout_with(db(), t, &LayoutOptions { composer: c, ..Default::default() });
|
||||
let l = layout_with(db(), t, &LayoutOptions { composer: Some(c), ..Default::default() });
|
||||
l.lines.iter().map(|li| li.glyph_end).collect::<Vec<_>>()
|
||||
};
|
||||
let every_line = ends(&t, Composer::EveryLine);
|
||||
@@ -278,6 +278,102 @@ fn burasagari_keeps_the_every_line_composer_for_latin_text() {
|
||||
assert_eq!(ends(&t, Composer::EveryLine), every_line);
|
||||
}
|
||||
|
||||
/// Width of `s` set on one line.
|
||||
fn natural_width(s: &str, size: f64) -> f64 {
|
||||
let l = layout(db(), &TextObject::point(Point::ZERO, s, style(size)));
|
||||
l.lines[0].x1 - l.lines[0].x0
|
||||
}
|
||||
|
||||
/// The text of each line.
|
||||
fn line_texts(t: &TextObject, l: &TextLayout) -> Vec<String> {
|
||||
let text = t.plain_text();
|
||||
l.lines.iter().map(|li| text[li.start..li.end].trim_end().to_string()).collect()
|
||||
}
|
||||
|
||||
/// Ragged text: Every-line breaks before a word that would fit, to avoid leaving a lone short
|
||||
/// word on the last line (single-line keeps filling the first line). Auto alignment is ragged
|
||||
/// too, in either paragraph direction: set right to left, the lines break the same and stay
|
||||
/// flush right.
|
||||
#[test]
|
||||
fn every_line_composer_balances_ragged_lines() {
|
||||
use vectorcraft_doc::ParaDirection;
|
||||
const S: &str = "Destroy all creatures with toughness X or less.";
|
||||
let w = natural_width("Destroy all creatures with toughness X or", 12.0) + 2.0;
|
||||
assert!(w < natural_width(S, 12.0), "the sentence needs two lines");
|
||||
let cases = [
|
||||
(Justify::Left, None),
|
||||
(Justify::Center, None),
|
||||
(Justify::Right, None),
|
||||
(Justify::Auto, None),
|
||||
(Justify::Auto, Some(ParaDirection::RightToLeft)),
|
||||
(Justify::Left, Some(ParaDirection::RightToLeft)),
|
||||
];
|
||||
for (justify, direction) in cases {
|
||||
let mut t = area(S, style(12.0), Rect::new(0.0, 0.0, w, 400.0), justify);
|
||||
t.para.direction = direction;
|
||||
t.para.composer = Composer::SingleLine;
|
||||
let greedy = line_texts(&t, &layout(db(), &t));
|
||||
assert_eq!(greedy, ["Destroy all creatures with toughness X or", "less."], "{justify:?} {direction:?}");
|
||||
t.para.composer = Composer::EveryLine;
|
||||
let every = line_texts(&t, &layout(db(), &t));
|
||||
assert_eq!(every, ["Destroy all creatures with toughness X", "or less."], "{justify:?} {direction:?}");
|
||||
// Burasagari (new type's Standard) leaves Latin text to the every-line composer.
|
||||
t.para.burasagari = vectorcraft_doc::Burasagari::Standard;
|
||||
assert_eq!(line_texts(&t, &layout(db(), &t)), every, "{justify:?} {direction:?} with burasagari");
|
||||
if (justify, direction) == (Justify::Auto, Some(ParaDirection::RightToLeft)) {
|
||||
let l = layout(db(), &t);
|
||||
assert!(l.lines.iter().all(|li| li.rtl && (li.x1 - w).abs() < 1e-6), "right to left Auto is flush right: {:?}", l.lines);
|
||||
}
|
||||
// The options override wins over the object's setting.
|
||||
let forced = layout_with(db(), &t, &LayoutOptions { composer: Some(Composer::SingleLine), ..Default::default() });
|
||||
assert_eq!(line_texts(&t, &forced), greedy);
|
||||
}
|
||||
}
|
||||
|
||||
/// Every-line evens the rag of a long ragged paragraph: the spread of the line ends is no worse
|
||||
/// than greedy breaking, every line fits, and nothing is lost.
|
||||
#[test]
|
||||
fn every_line_composer_evens_the_rag() {
|
||||
for (width, hy) in [(150.0, false), (190.0, false), (240.0, true), (310.0, false)] {
|
||||
let mut t = area(©.repeat(2), style(12.0), Rect::new(0.0, 0.0, width, 4000.0), Justify::Left);
|
||||
t.para.hyphenate = hy;
|
||||
let rag = |c: Composer| {
|
||||
let mut t = t.clone();
|
||||
t.para.composer = c;
|
||||
let l = layout(db(), &t);
|
||||
assert!(!l.overflow);
|
||||
for li in &l.lines {
|
||||
assert!(li.x1 - li.x0 <= width + 1e-6, "{c:?} {width}: line too wide {li:?}");
|
||||
}
|
||||
let clusters: std::collections::BTreeSet<(usize, usize)> = l.glyphs.iter().filter(|g| g.len > 0).map(|g| (g.byte, g.len)).collect();
|
||||
assert_eq!(clusters.iter().map(|c| c.1).sum::<usize>(), COPY.len() * 2, "every character placed");
|
||||
// Leftover space of all lines but the last: its sum of squares (how ragged) and the
|
||||
// sum of squared differences between neighbours (how jagged).
|
||||
let slack: Vec<f64> = l.lines[..l.lines.len() - 1].iter().map(|li| width - (li.x1 - li.x0)).collect();
|
||||
let jag: f64 = slack.windows(2).map(|p| (p[0] - p[1]).powi(2)).sum();
|
||||
(slack.iter().map(|s| s * s).sum::<f64>(), jag, l.lines.len())
|
||||
};
|
||||
let ((kp, kp_jag, kp_lines), (greedy, greedy_jag, greedy_lines)) = (rag(Composer::EveryLine), rag(Composer::SingleLine));
|
||||
assert!(kp <= greedy + 1e-6, "{width}: every-line rag {kp} vs greedy {greedy}");
|
||||
assert!(kp_jag <= greedy_jag + 1e-6, "{width}: every-line jag {kp_jag} vs greedy {greedy_jag}");
|
||||
assert!(kp_lines <= greedy_lines + 1, "{width}: {kp_lines} lines vs {greedy_lines}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Single-line breaking is the greedy breaker: each line takes as many words as fit.
|
||||
#[test]
|
||||
fn single_line_composer_is_greedy() {
|
||||
let width = 190.0;
|
||||
let mut t = area(COPY, style(12.0), Rect::new(0.0, 0.0, width, 2000.0), Justify::Left);
|
||||
t.para.composer = Composer::SingleLine;
|
||||
let l = layout(db(), &t);
|
||||
let lines = line_texts(&t, &l);
|
||||
for pair in lines.windows(2) {
|
||||
let next_word = pair[1].split(' ').next().unwrap();
|
||||
assert!(natural_width(&format!("{} {next_word}", pair[0]), 12.0) > width - 1e-6, "{pair:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hyphenation_rules() {
|
||||
assert_eq!(hyphen::hyphenate_word("typography"), "typo-gra-phy");
|
||||
@@ -370,9 +466,24 @@ fn opentype_ligature_switches() {
|
||||
assert_eq!(layout(db(), &t).glyphs.len(), 1, "fi ligature by default");
|
||||
let off = LayoutOptions { features: OtFeatures { ligatures: false, ..Default::default() }, ..Default::default() };
|
||||
assert_eq!(layout_with(db(), &t, &off).glyphs.len(), 2);
|
||||
// Tracking suppresses ligatures (as letterspaced type should).
|
||||
let tracked = TextObject::point(Point::ZERO, "fi", CharStyle { tracking: 100.0, ..serif });
|
||||
assert_eq!(layout(db(), &tracked).glyphs.len(), 2);
|
||||
let fi = |tracking: f64, features: &[&str]| {
|
||||
let st = CharStyle { tracking, features: features.iter().map(|s| s.to_string()).collect(), ..serif.clone() };
|
||||
layout(db(), &TextObject::point(Point::ZERO, "fi", st)).glyphs.len()
|
||||
};
|
||||
// Small tracking adjustments (fitting a line) keep the ligature.
|
||||
assert_eq!(fi(-5.0, &[]), 1, "tracking -5 keeps fi");
|
||||
assert_eq!(fi(20.0, &[]), 1, "tracking +20 keeps fi");
|
||||
let (tight, loose) = LIGATURE_TRACKING_LIMITS;
|
||||
assert_eq!((fi(tight, &[]), fi(loose, &[])), (1, 1), "the limits themselves keep fi");
|
||||
// Real letterspacing suppresses ligatures (as letterspaced type should), condensing sooner...
|
||||
assert_eq!(fi(100.0, &[]), 2, "tracking 100 drops fi");
|
||||
assert_eq!(fi(-30.0, &[]), 2, "tracking -30 drops fi");
|
||||
assert_eq!(fi(-100.0, &[]), 2, "tracking -100 drops fi");
|
||||
// ...unless the character turns them on explicitly.
|
||||
assert_eq!(fi(100.0, &["liga"]), 1, "explicit liga wins over tracking");
|
||||
assert_eq!(fi(100.0, &["+liga"]), 1);
|
||||
assert_eq!(fi(100.0, &["liga", "-liga"]), 2, "the last tag wins");
|
||||
assert_eq!(fi(0.0, &["-liga"]), 2, "explicit off still turns it off");
|
||||
let f = OtFeatures::from_tags(["dlig", "-liga", "smcp", "onum", "bogus"]);
|
||||
assert!(f.discretionary_ligatures && !f.ligatures && f.small_caps && f.oldstyle_figures && !f.fractions);
|
||||
}
|
||||
@@ -404,17 +515,22 @@ fn uncovered_characters_do_not_break_layout() {
|
||||
#[test]
|
||||
fn layout_10k_area_text_is_fast() {
|
||||
let text: String = COPY.chars().cycle().take(10_000).collect();
|
||||
let mut t = area(&text, style(10.0), Rect::new(0.0, 0.0, 400.0, 20_000.0), Justify::JustifyLeft);
|
||||
t.para.hyphenate = true;
|
||||
let _ = layout(db(), &t);
|
||||
let n = 5;
|
||||
let start = std::time::Instant::now();
|
||||
for _ in 0..n {
|
||||
let l = layout(db(), &t);
|
||||
assert!(!l.overflow);
|
||||
for (justify, composer) in
|
||||
[(Justify::JustifyLeft, Composer::EveryLine), (Justify::Left, Composer::EveryLine), (Justify::Left, Composer::SingleLine)]
|
||||
{
|
||||
let mut t = area(&text, style(10.0), Rect::new(0.0, 0.0, 400.0, 20_000.0), justify);
|
||||
t.para.hyphenate = true;
|
||||
t.para.composer = composer;
|
||||
let _ = layout(db(), &t);
|
||||
let n = 5;
|
||||
let start = std::time::Instant::now();
|
||||
for _ in 0..n {
|
||||
let l = layout(db(), &t);
|
||||
assert!(!l.overflow);
|
||||
}
|
||||
let per = start.elapsed().as_secs_f64() * 1000.0 / n as f64;
|
||||
eprintln!("layout of 10k chars ({justify:?}, {composer:?}, hyphenated): {per:.3} ms");
|
||||
let budget = if cfg!(debug_assertions) { 400.0 } else { 10.0 };
|
||||
assert!(per < budget, "{justify:?} {composer:?}: {per} ms");
|
||||
}
|
||||
let per = start.elapsed().as_secs_f64() * 1000.0 / n as f64;
|
||||
eprintln!("layout of 10k chars (justified, hyphenated): {per:.3} ms");
|
||||
let budget = if cfg!(debug_assertions) { 400.0 } else { 10.0 };
|
||||
assert!(per < budget, "{per} ms");
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -634,3 +634,4 @@
|
||||
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
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -3598,3 +3598,4 @@ 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
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -3598,3 +3598,4 @@ 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ì
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -3060,3 +3060,4 @@ 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 ファイルダイアログが開いています。先にそちらで選択してください
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -63,8 +63,20 @@ fn plural_czech(n: u64) -> usize {
|
||||
}
|
||||
}
|
||||
|
||||
/// Russian: 1 (but not 11) is `one`, 2–4 (but not 12–14) `few`, everything else `many`.
|
||||
fn plural_russian(n: u64) -> usize {
|
||||
match n % 100 {
|
||||
11..=14 => 2,
|
||||
_ => match n % 10 {
|
||||
1 => 0,
|
||||
2..=4 => 1,
|
||||
_ => 2,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// The registry. English first: it is the fallback and the source language.
|
||||
pub static LANGUAGES: [LangInfo; 8] = [
|
||||
pub static LANGUAGES: [LangInfo; 9] = [
|
||||
LangInfo { code: "en", name: "English", source: "", plural: plural_one_other, complete_menus: false, catalog: OnceLock::new() },
|
||||
// Japanese: the whole interface (every menu string and `tl!` literal), keeping the product,
|
||||
// workspace and perspective preset names in English (`MENU_KEEP_AS_IS`).
|
||||
@@ -91,6 +103,11 @@ pub static LANGUAGES: [LangInfo; 8] = [
|
||||
complete_menus: true,
|
||||
catalog: OnceLock::new(),
|
||||
},
|
||||
// Russian: the whole interface and the status and error messages, keeping the same names in
|
||||
// English as Spanish; every `ru-*` locale (`ru-RU`, `ru-BY`, `ru-KZ` …) resolves here.
|
||||
LangInfo {
|
||||
code: "ru", name: "Русский", source: include_str!("ru.tsv"), plural: plural_russian, complete_menus: true, catalog: OnceLock::new()
|
||||
},
|
||||
// Brazilian Portuguese: every menu label (`menu_catalogs_translate_every_menu_label`), every
|
||||
// `tl!` literal and the plural messages; left English on purpose are the `MENU_KEEP_AS_IS`
|
||||
// strings (product name, language names, workspace names, perspective grid presets).
|
||||
|
||||
@@ -2648,3 +2648,4 @@
|
||||
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
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
File diff suppressed because it is too large.
Load diff
@@ -418,7 +418,7 @@ fn cs() -> Lang {
|
||||
}
|
||||
|
||||
/// Languages whose catalogs leave [`MENU_KEEP_AS_IS`] in English.
|
||||
const KEEPS_MENU_NAMES: [&str; 5] = ["cs", "es", "it", "ja", "pt-br"];
|
||||
const KEEPS_MENU_NAMES: [&str; 6] = ["cs", "es", "it", "ja", "pt-br", "ru"];
|
||||
|
||||
/// Menu labels the menu-complete catalogs (Czech, Spanish, Italian, Japanese, Brazilian Portuguese) show as they are: the product name, a format name, the built-in workspace
|
||||
/// names and the perspective grid presets (names, shown untranslated wherever else they appear).
|
||||
@@ -555,6 +555,10 @@ fn it() -> Lang {
|
||||
Lang::from_code("it").expect("it registered")
|
||||
}
|
||||
|
||||
fn ru() -> Lang {
|
||||
Lang::from_code("ru").expect("ru registered")
|
||||
}
|
||||
|
||||
/// Spanish uses the vector-illustration vocabulary its users know, has two plural forms like
|
||||
/// English, and reads the same in the menus and in the panels.
|
||||
#[test]
|
||||
@@ -597,6 +601,30 @@ fn italian_reads_as_italian() {
|
||||
assert_eq!(trn(it(), 3, "{n} Layer", "{n} Layers"), "3 livelli");
|
||||
}
|
||||
|
||||
/// Russian uses the vector-illustration vocabulary its users know, has the three plural forms
|
||||
/// (one/few/many), and reads the same in the menus and in the panels.
|
||||
#[test]
|
||||
fn russian_reads_as_russian() {
|
||||
for (en, want) in [
|
||||
("Artboard Tool", "Инструмент «Монтажная область»"),
|
||||
("Swatches", "Образцы"),
|
||||
("Pathfinder", "Обработка контуров"),
|
||||
("Stroke", "Обводка"),
|
||||
("Fill", "Заливка"),
|
||||
("Direct Selection Tool", "Инструмент «Прямое выделение»"),
|
||||
("Save As…", "Сохранить как…"),
|
||||
("Undo", "Отменить"),
|
||||
] {
|
||||
assert_eq!(tr(ru(), en), want);
|
||||
}
|
||||
assert_eq!(trn(ru(), 1, "{n} Layer", "{n} Layers"), "1 слой");
|
||||
assert_eq!(trn(ru(), 2, "{n} Layer", "{n} Layers"), "2 слоя");
|
||||
assert_eq!(trn(ru(), 5, "{n} Layer", "{n} Layers"), "5 слоёв");
|
||||
assert_eq!(trn(ru(), 11, "{n} Layer", "{n} Layers"), "11 слоёв");
|
||||
assert_eq!(trn(ru(), 21, "{n} Layer", "{n} Layers"), "21 слой");
|
||||
assert_eq!(trn(ru(), 22, "{n} Layer", "{n} Layers"), "22 слоя");
|
||||
}
|
||||
|
||||
/// Catalogs written with spaces between words keep a fragment's leading and trailing spaces: the
|
||||
/// hint bar and a few labels are joined from pieces (" to finish", "Press ").
|
||||
#[test]
|
||||
@@ -615,6 +643,12 @@ fn czech_plurals_have_three_forms() {
|
||||
assert_eq!(forms, [2, 0, 1, 1, 2, 2, 2]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn russian_plurals_have_three_forms() {
|
||||
let forms: Vec<usize> = [0, 1, 2, 4, 5, 11, 21, 22, 25, 111, 121].into_iter().map(plural_russian).collect();
|
||||
assert_eq!(forms, [2, 0, 1, 1, 2, 2, 0, 1, 2, 2, 0]);
|
||||
}
|
||||
|
||||
/// Czech, Spanish and Italian letters (and the punctuation their text uses) come from each family's own first font, not
|
||||
/// from a fallback further down the stack. (`has_glyph` can't tell: it counts characters of the
|
||||
/// face that draws missing glyphs, the first one, as missing.)
|
||||
@@ -638,6 +672,28 @@ fn czech_spanish_and_italian_glyphs_are_available_without_system_fonts() {
|
||||
});
|
||||
}
|
||||
|
||||
/// Russian letters (and the punctuation the catalog uses) come from each family's own first font, not
|
||||
/// from a fallback further down the stack.
|
||||
#[test]
|
||||
fn russian_glyphs_are_available_without_system_fonts() {
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
let mut output = ctx.run_ui(egui::RawInput::default(), |_| {});
|
||||
output.textures_delta.clear();
|
||||
ctx.fonts_mut(|fonts| {
|
||||
let families: Vec<_> = fonts.definitions().families.iter().map(|(f, stack)| (f.clone(), stack.first().cloned())).collect();
|
||||
for (family, first) in families {
|
||||
let first = first.unwrap();
|
||||
let mut font = fonts.fonts.font(&family);
|
||||
let chars = font.characters();
|
||||
for ch in "абвгдеёжзийклмнопрстуфхцчшщъыьэюяАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ«»„“…–’".chars()
|
||||
{
|
||||
assert!(chars.get(&ch).is_some_and(|fonts| fonts.contains(&first)), "{first} ({family:?}) has no {ch}");
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// A language chosen in an older version (saved with the UI state as `"language"`) carries over to
|
||||
/// the `interfaceLanguage` preference, and isn't written back.
|
||||
#[test]
|
||||
@@ -708,7 +764,7 @@ fn complete_languages_translate_every_message() {
|
||||
}
|
||||
|
||||
/// Languages whose catalogs cover every status and error message.
|
||||
const COMPLETE_MESSAGES: &[&str] = &["es", "it"];
|
||||
const COMPLETE_MESSAGES: &[&str] = &["es", "it", "ru"];
|
||||
|
||||
/// Crates whose error and status messages reach the status bar.
|
||||
const MESSAGE_CRATES: &[&str] = &["ui-egui", "engine", "doc", "format", "svg", "pdf", "eps", "text", "plugins", "metafile", "cad", "trace"];
|
||||
|
||||
@@ -3315,3 +3315,4 @@ 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 文件对话框已打开:请先在其中选择
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -3090,3 +3090,4 @@ 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 檔案對話方塊已開啟:請先在其中選擇
|
||||
|
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))
|
||||
}
|
||||
|
||||
|
||||
@@ -36,6 +36,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 +96,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 +236,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 +354,11 @@ 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>>,
|
||||
/// Keyboard pastes of something other than text (see [`shortcuts::PasteChord`]).
|
||||
pub(crate) paste_chord: shortcuts::PasteChord,
|
||||
/// Saves and exports running in the background (Preferences → File Handling).
|
||||
@@ -423,6 +435,8 @@ 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(),
|
||||
recovery: Default::default(),
|
||||
@@ -485,6 +499,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;
|
||||
@@ -785,6 +809,8 @@ impl VectorcraftApp {
|
||||
self.system_paste_at = now;
|
||||
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.
|
||||
@@ -858,10 +884,38 @@ impl VectorcraftApp {
|
||||
|
||||
/// Fonts installed or removed while the app was in the background are listed when it comes
|
||||
/// back (Refresh Font List by itself): a look at the font folders, a scan only when they changed.
|
||||
/// The look runs on another thread (asking DirectWrite for the fonts font services loaded
|
||||
/// meanwhile takes tens of milliseconds on Windows, #579), [`Self::poll_font_check`] scans.
|
||||
fn refresh_installed_fonts(&mut self) {
|
||||
if vectorcraft_text::FontDb::global().installed_fonts_changed() {
|
||||
// A failure shows in the status bar, as the menu item's does.
|
||||
let _ = self.run("text.rescanFonts", json!({}));
|
||||
if self.font_check.is_some() {
|
||||
return;
|
||||
}
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let look = move || {
|
||||
// The UI gone meanwhile has nothing to refresh.
|
||||
let _ = tx.send(vectorcraft_text::FontDb::global().installed_fonts_changed());
|
||||
};
|
||||
let spawned =
|
||||
if cfg!(target_arch = "wasm32") { None } else { std::thread::Builder::new().name("font-check".into()).spawn(look.clone()).ok() };
|
||||
if spawned.is_none() {
|
||||
look();
|
||||
}
|
||||
self.font_check = Some(rx);
|
||||
}
|
||||
|
||||
/// Rescan the fonts once [`Self::refresh_installed_fonts`]'s look says they changed.
|
||||
fn poll_font_check(&mut self, ctx: &egui::Context) {
|
||||
let Some(check) = &self.font_check else { return };
|
||||
match check.try_recv() {
|
||||
Ok(changed) => {
|
||||
self.font_check = None;
|
||||
if changed {
|
||||
// A failure shows in the status bar, as the menu item's does.
|
||||
let _ = self.run("text.rescanFonts", json!({}));
|
||||
}
|
||||
}
|
||||
Err(std::sync::mpsc::TryRecvError::Empty) => ctx.request_repaint_after(std::time::Duration::from_millis(50)),
|
||||
Err(std::sync::mpsc::TryRecvError::Disconnected) => self.font_check = 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));
|
||||
|
||||
@@ -503,21 +503,33 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let mut new: Option<(Color, Live, Vec<f32>)> = None;
|
||||
let mut behind: Option<(Color, Live)> = None;
|
||||
let mut tinted: Option<(f32, Live)> = None;
|
||||
let gamut = color.filter(|_| matches!(mode, Mode::Rgb | Mode::Hsb)).and_then(|c| gamut_fix(app, ui.ctx(), "color-gamut", &c));
|
||||
// The warnings the mode shows: out of gamut in RGB and HSB, out of web colours but in Web Safe
|
||||
// RGB and Grayscale.
|
||||
let (shows_gamut, shows_web) = (matches!(mode, Mode::Rgb | Mode::Hsb), !matches!(mode, Mode::WebSafe | Mode::Grayscale));
|
||||
let gamut = color.filter(|_| shows_gamut).and_then(|c| gamut_fix(app, ui.ctx(), "color-gamut", &c));
|
||||
ui.horizontal(|ui| {
|
||||
// Left column: proxy, out-of-gamut and out-of-web warnings.
|
||||
ui.vertical(|ui| {
|
||||
ui.set_width(44.0);
|
||||
super::proxy(app, ui, 40.0);
|
||||
let web = color.filter(|c| !matches!(mode, Mode::WebSafe | Mode::Grayscale) && !is_web_safe(c)).map(|c| web_safe(&c));
|
||||
for (warning, fix) in [(GAMUT_WARNING, gamut), (WEB_WARNING, web)] {
|
||||
if let Some(fix) = fix {
|
||||
ui.add_space(6.0);
|
||||
if warning_chip(ui, warning, &fix) {
|
||||
new = Some((fix, Live::Released, components(mode, &fix)));
|
||||
}
|
||||
let web = color.filter(|c| shows_web && !is_web_safe(c)).map(|c| web_safe(&c));
|
||||
let warnings: Vec<_> = [(GAMUT_WARNING, gamut), (WEB_WARNING, web)].into_iter().filter_map(|(w, fix)| Some((w, fix?))).collect();
|
||||
for (warning, fix) in &warnings {
|
||||
ui.add_space(6.0);
|
||||
if warning_chip(ui, *warning, fix) {
|
||||
new = Some((*fix, Live::Released, components(mode, fix)));
|
||||
}
|
||||
}
|
||||
// Room for the mode's other warnings: the panel keeps its height as the colour changes,
|
||||
// else the spectrum below moves under a dragging pointer and the colour flips every
|
||||
// frame, e.g. between a pale colour out of gamut and white above the spectrum (#578).
|
||||
for _ in warnings.len()..usize::from(shows_gamut) + usize::from(shows_web) {
|
||||
ui.add_space(6.0);
|
||||
ui.scope(|ui| {
|
||||
ui.set_invisible();
|
||||
warning_chip(ui, WEB_WARNING, &Color::WHITE)
|
||||
});
|
||||
}
|
||||
});
|
||||
// Sliders (Shift-drag moves them in tandem).
|
||||
ui.vertical(|ui| {
|
||||
@@ -705,6 +717,40 @@ mod tests {
|
||||
(f.color().map(|c| c.to_hex()).unwrap_or_default(), s.color().map(|c| c.to_hex()).unwrap_or_default())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_drag_on_the_spectrum_holds_still_near_white() {
|
||||
let mut app = app();
|
||||
let ctx = egui::Context::default();
|
||||
let none = egui::Modifiers::NONE;
|
||||
// White needs no warning, #fefefe the web one, a pale violet both: one panel height.
|
||||
let heights: Vec<f32> = ["#ffffff", "#fefefe", "#ded3ff"]
|
||||
.iter()
|
||||
.map(|c| {
|
||||
app.run("paint.setFill", json!({"color": c})).unwrap();
|
||||
frame(&mut app, &ctx, vec![], none);
|
||||
frame(&mut app, &ctx, vec![], none).1
|
||||
})
|
||||
.collect();
|
||||
assert!(heights.windows(2).all(|w| w[0] == w[1]), "{heights:?}");
|
||||
// Drag along the spectrum's top edge (pale colours, some out of gamut), stopping at each
|
||||
// point: the colour holds while the pointer does.
|
||||
let r = frame(&mut app, &ctx, vec![], none).0.expect("the spectrum is drawn");
|
||||
let at = |x: f32| egui::pos2(r.left() + x * r.width(), r.top() + 2.0);
|
||||
let button = |pressed| egui::Event::PointerButton { pos: at(0.02), button: egui::PointerButton::Primary, pressed, modifiers: none };
|
||||
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at(0.02)), button(true)], none);
|
||||
for i in 1..20 {
|
||||
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at(i as f32 * 0.05))], none);
|
||||
let fills: Vec<String> = (0..3)
|
||||
.map(|_| {
|
||||
frame(&mut app, &ctx, vec![], none);
|
||||
paints_hex(&app).0
|
||||
})
|
||||
.collect();
|
||||
assert!(fills.windows(2).all(|w| w[0] == w[1]), "at {}: {fills:?}", i as f32 * 0.05);
|
||||
}
|
||||
frame(&mut app, &ctx, vec![button(false)], none);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tandem_keeps_ratios() {
|
||||
let t = tandem(Mode::Rgb, &[100.0, 50.0, 25.0], 0, 200.0);
|
||||
|
||||
@@ -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`
|
||||
|
||||
@@ -63,7 +63,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
*field(&mut next) = !on;
|
||||
}
|
||||
}
|
||||
if st.tracking.abs() > 1e-9 && cur.ligatures {
|
||||
if cur.ligatures && vectorcraft_text::ligatures_suppressed_by(st.tracking) && !vectorcraft_text::explicit_ligatures(&st.features) {
|
||||
widgets::dim_label(ui, tl!("Ligatures are off while the text is tracked."));
|
||||
}
|
||||
if next != cur {
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
//! Paragraph panel: seven alignment buttons, Paragraph Direction (with the Indic options), indents,
|
||||
//! space before/after, Hyphenate and Mojikumi Set (with the East Asian options).
|
||||
//! space before/after, Hyphenate and Mojikumi Set (with the East Asian options); the panel menu
|
||||
//! picks the Single-line or Every-line Composer.
|
||||
|
||||
use egui::{Ui, vec2};
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Justify, NodeKind, ParaDirection, ParaStyle};
|
||||
use vectorcraft_doc::{Composer, Justify, NodeKind, ParaDirection, ParaStyle};
|
||||
|
||||
use super::character::text_style;
|
||||
use super::{pstate, set_pstate};
|
||||
@@ -181,14 +182,20 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
});
|
||||
}
|
||||
ui.separator();
|
||||
menu_item(ui, tl!("Single-line Composer"), false, false);
|
||||
menu_item(ui, tl!("Every-line Composer"), false, true);
|
||||
let composer = style.as_ref().map(|(_, p)| p.composer);
|
||||
for (c, label, id) in
|
||||
[(Composer::SingleLine, tl!("Single-line Composer"), "singleLine"), (Composer::EveryLine, tl!("Every-line Composer"), "everyLine")]
|
||||
{
|
||||
if menu_item(ui, label, has, composer == Some(c)) {
|
||||
format(app, json!({ "composer": id }));
|
||||
}
|
||||
}
|
||||
ui.separator();
|
||||
if menu_item(ui, tl!("Reset Panel"), has, false) {
|
||||
para_cmd(app, "text.setStyle", json!({"justify": "auto"}));
|
||||
format(
|
||||
app,
|
||||
json!({"leftIndent": 0, "rightIndent": 0, "firstLineIndent": 0, "spaceBefore": 0, "spaceAfter": 0, "hyphenate": false, "direction": "auto", "leadingModel": "romanBaseline", "burasagari": "standard"}),
|
||||
json!({"leftIndent": 0, "rightIndent": 0, "firstLineIndent": 0, "spaceBefore": 0, "spaceAfter": 0, "hyphenate": false, "direction": "auto", "leadingModel": "romanBaseline", "burasagari": "standard", "composer": "everyLine"}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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"));
|
||||
}
|
||||
+5
-4
@@ -135,7 +135,8 @@ in Taiwan; `zh-TW`, `zh-HK`, `zh-MO` and `zh-Hant-*` locales all resolve to it),
|
||||
complete, in the vocabulary used in mainland China; `zh-CN`, `zh-SG`, `zh-Hans-*` and a bare `zh` resolve to it,
|
||||
so the two scripts never mix), Japanese (`ja`, complete), Spanish (`es`, complete, in neutral
|
||||
international Spanish; every `es-*` locale such as `es-ES`, `es-MX`, `es-AR` or `es-419` resolves to it), Italian (`it`,
|
||||
complete; `it-IT`, `it-CH` and every other `it-*` locale resolve to it), Czech (`cs`, every menu label) and Brazilian Portuguese
|
||||
complete; `it-IT`, `it-CH` and every other `it-*` locale resolve to it), Russian (`ru`, complete; every `ru-*`
|
||||
locale such as `ru-RU`, `ru-BY` or `ru-KZ` resolves to it), Czech (`cs`, every menu label) and Brazilian Portuguese
|
||||
(`pt-br`, every menu label and every `tl!` literal). Untranslated text falls back to English until its rows are added.
|
||||
|
||||
- `tl!("…")` translates a literal into the language the UI is drawn in; `i18n::t(s)` is the same for a
|
||||
@@ -163,10 +164,10 @@ complete; `it-IT`, `it-CH` and every other `it-*` locale resolve to it), Czech (
|
||||
control channel, MCP and tests read them) and are translated only where the status bar draws them
|
||||
(`i18n::msg`). `@msg` catalog rows hold a whole message or a template such as
|
||||
`Couldn't open {name}: {e}`; `{_1}`, `{_2}` … stand for the format string's `{}`, and the values in the
|
||||
placeholders are translated in turn (the reason after `: {e}` is often a message too). Spanish and Italian cover every
|
||||
placeholders are translated in turn (the reason after `: {e}` is often a message too). Spanish, Italian and Russian cover every
|
||||
message literal the test scan finds (`complete_languages_translate_every_message`, languages listed in
|
||||
`COMPLETE_MESSAGES`): a new `Err("…")`, `Other(…)`, `#[error(…)]` or `status(…)` message needs an `es.tsv`
|
||||
and an `it.tsv` row (`VECTORCRAFT_I18N_DUMP_MESSAGES=messages.txt cargo test -p vectorcraft-ui-egui
|
||||
`COMPLETE_MESSAGES`): a new `Err("…")`, `Other(…)`, `#[error(…)]` or `status(…)` message needs an `es.tsv`,
|
||||
an `it.tsv` and a `ru.tsv` row (`VECTORCRAFT_I18N_DUMP_MESSAGES=messages.txt cargo test -p vectorcraft-ui-egui
|
||||
complete_languages_translate_every_message` lists them all). Other languages show messages in English
|
||||
until they add `@msg` rows.
|
||||
- Not translated on purpose: names that are user data (layers, swatches, fonts, documents), the tab
|
||||
|
||||
+20
-4
@@ -266,9 +266,10 @@ place and paste). `run_command document.save {path: "x.svg", svg: {…}}` saves
|
||||
Symbols export as one `<symbol>` with a `<use>` per instance. An instance the def can't stand for is written as its
|
||||
own art: one stained by its fill; one scaled while the symbol has strokes (their weight doesn't scale), or rotated or
|
||||
scaled while it has effects, brushes or live objects; and every instance of a symbol with pattern paints or unlinked
|
||||
opacity masks (those stay on the page). `hiddenLayers: true` keeps hidden layers as groups that aren't displayed
|
||||
(`display:none`); `document.save` keeps them unless told otherwise, exports leave them out, and they reopen as
|
||||
hidden layers. A `preserveEditing` SVG carries the native document (CDATA in `<metadata>`) and a hash of the
|
||||
opacity masks (those stay on the page). `hiddenLayers: true` keeps hidden layers and objects, not displayed
|
||||
(`display="none"`); `document.save` and the CLI's `convert` keep them unless told otherwise, other exports leave
|
||||
them out, and they reopen hidden. An object's own data (`object.setProps {data: {pivot: "100,180"}}`) is written as
|
||||
`data-*` attributes (`data-pivot="100,180"`), and an SVG's `data-*` attributes come in as it. A `preserveEditing` SVG carries the native document (CDATA in `<metadata>`) and a hash of the
|
||||
markup around it: if another app changed the SVG since, `document.open` reads it as plain SVG and says so in
|
||||
`warnings`.
|
||||
|
||||
@@ -2309,7 +2310,8 @@ tone (mono, or CMYK screens multiplied over each other), clipped to the art's ou
|
||||
|
||||
Type can use the bundled fonts, fonts added to the session and the fonts installed on the system (none on the web):
|
||||
the system's and the user's font folders (Windows: `Fonts` and `%LOCALAPPDATA%\Microsoft\Windows\Fonts`, plus fonts
|
||||
registered outside them, such as fonts installed as shortcuts; macOS: `/System/Library/Fonts`, `/Library/Fonts`,
|
||||
registered outside them, such as fonts installed as shortcuts, and in the desktop app the fonts in DirectWrite's system
|
||||
font collection, such as those Adobe Fonts activates while Creative Cloud runs; macOS: `/System/Library/Fonts`, `/Library/Fonts`,
|
||||
`/Network/Library/Fonts`, `~/Library/Fonts` and downloaded system fonts; Linux and BSD: `/usr/share/fonts`,
|
||||
`/usr/local/share/fonts`, `~/.fonts` and the XDG data folders' `fonts`, `~/.local/share/fonts` among them, and in a
|
||||
Flatpak sandbox the host's fonts). The installed fonts are cataloged once per session (in the background when the app starts, else on the first lookup
|
||||
@@ -2548,6 +2550,20 @@ canvas as they export. `object.blend.expand` and `object.blend.release` keep the
|
||||
opacity mask and appearance (Release on a group around the keys and spine when the blend has any), and
|
||||
`object.expand` with `object: true` expands the blends in the selection.
|
||||
|
||||
## Paragraph composer
|
||||
|
||||
`text.setFormat {ids?, composer: "singleLine"|"everyLine"}` sets how a text object's lines are broken (the Paragraph
|
||||
panel menu's Single-line and Every-line Composer; stored in the paragraph attributes as `para.composer`, saved only
|
||||
when it is Single-line). Every-line, the default, picks the breaks of the whole paragraph together in area type:
|
||||
justified text gets even word spacing, ragged text (left, centre or right aligned) an even rag, so it may move a word
|
||||
that fits to the next line to avoid a lone short word on the last line or a full line next to a short one.
|
||||
Single-line fills each line as far as it goes. Point type and type on a path have no line width, so both composers
|
||||
give the same result there; paragraphs that mix type sizes fall back to Single-line.
|
||||
|
||||
```json
|
||||
{"name":"run_command","arguments":{"command":"text.setFormat","params":{"ids":[7],"composer":"singleLine"}}}
|
||||
```
|
||||
|
||||
## Editing envelopes
|
||||
|
||||
`object.envelope.editContents {editing}` switches between editing the envelope and its contents (the menu item reads
|
||||
|
||||
Reference in new issue
Block a user