Compare commits
26
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1e7f5084d8 | ||
|
|
256702bab0 | ||
|
|
498a2d1e6b | ||
|
|
4ab13dabfb | ||
|
|
f1157456a1 | ||
|
|
55cc14e4a8 | ||
|
|
dce0f8a48d | ||
|
|
6a39ee0a1c | ||
|
|
01df2c730b | ||
|
|
dcc0de7487 | ||
|
|
0924bc16ae | ||
|
|
f18cd1c99b | ||
|
|
e92bbdbdac | ||
|
|
b61089e5c6 | ||
|
|
7bd496b1e2 | ||
|
|
2b91d7effd | ||
|
|
b062d625cf | ||
|
|
ee7be83ee0 | ||
|
|
50bb3b2693 | ||
|
|
2f81b4437b | ||
|
|
23b7c68d90 | ||
|
|
f767403673 | ||
|
|
2cdf4e3de0 | ||
|
|
088495ee17 | ||
|
|
43db1cdbbf | ||
|
|
ed17166343 |
No files matched your search
+15
-12
@@ -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
|
||||
|
||||
@@ -35,7 +35,7 @@ since 2026-10-01.
|
||||
|---|---|---|
|
||||
| **Breadth:** menus, tools and panels exist | ~90% | 13 menu items still stubbed; every tool implemented except Touch Type; 51 panel modules |
|
||||
| **Depth:** each feature behaves like Illustrator | ~69–75% | Strong: paint, appearance and colour (M3), Pathfinder and booleans, selection, drawing, files (M4). Weak: advanced type (~45%; inline symbols in text are beyond parity and don't raise it), brushes and symbols (in progress), raster effects (~20%) |
|
||||
| **Large missing subsystems** | 0–20% | 3D & Materials (0%), Photoshop-style raster effects and the Effect Gallery (~1 of ~56 filters), SVG Filters, CJK composition (vertical type with kinsoku, tate-chu-yoko and the font's vertical metrics; ruby, mojikumi and proportional vertical metrics open), Variables (data merge), scripting |
|
||||
| **Large missing subsystems** | 0–20% | 3D & Materials (0%), Photoshop-style raster effects and the Effect Gallery (~4 of ~56 filters), SVG Filters, CJK composition (vertical type with kinsoku, tate-chu-yoko and the font's vertical metrics; ruby, mojikumi and proportional vertical metrics open), Variables (data merge), scripting |
|
||||
| **Interaction fidelity:** modifiers, cursors, small behaviours | ~30–40% | The dedicated pass hasn't started, and there has been no side-by-side session with Illustrator yet. A power user notices this first |
|
||||
| **Look & feel** | ~75–80% | Measured against Illustrator 2026 screenshots (2026-10-02); the panels added since haven't been re-measured |
|
||||
| **File interop** | ~85% | SVG/SVGZ, PDF and PDF-compatible `.ai`, EPS, DXF, EMF/WMF, raster formats, PSD export, Place and Links, Package, Print, clipboard flavours. Native `.ai` private data is out of scope by design; DWG has no open spec |
|
||||
@@ -53,9 +53,12 @@ Ordered by how much each gap blocks someone from switching. Sizes are one-agent
|
||||
1. **Interaction fidelity:** go tool by tool and panel by panel against `plan/illustrator/05-tools.md`,
|
||||
`06-panels.md` and `09-shortcuts.md`, covering modifier keys, cursors, the Properties panel per context and
|
||||
isolation mode. The Shaper’s rough-square recognition and shape orientation steps are corrected; Shaper Groups now retain editable originals for region merges/punches and separate fill/stroke edits; their construction-mode widget and gesture refinements remain. 60–90 h.
|
||||
2. **Photoshop-style raster effects and the Effect Gallery:** about 55 filters (Artistic, Brush Strokes, Distort,
|
||||
Pixelate, Sketch, Stylize, Texture, Video) on the raster pipeline that drop shadows already use, applied at
|
||||
Document Raster Effects Settings resolution. Parallelizes well across agents. 28–42 h.
|
||||
2. **Photoshop-style raster effects and the Effect Gallery:** about 52 filters (Artistic, Brush Strokes, Distort,
|
||||
Pixelate, Sketch, Stylize, Texture, Video) and the Effect Gallery. The pixel-filter pipeline is in place
|
||||
(`vectorcraft_effects::pixel`: the object rendered offscreen, filtered in stack order with Gaussian Blur and
|
||||
Feather, cached while panning, images in PDF/SVG/Expand Appearance) with Blur › Radial Blur and Smart Blur
|
||||
(Normal mode only) and Sharpen › Unsharp Mask; each new filter is now one function, a catalogue row, menu and
|
||||
translations. Parallelizes well across agents. 26–40 h.
|
||||
3. **3D and Materials:** Extrude & Bevel, Revolve, Inflate and Rotate with lighting and materials, using a software
|
||||
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.
|
||||
@@ -129,7 +132,7 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist
|
||||
- **Pen:** Alt pressed in the middle of dragging out an anchor splits its handles and keeps the curve already shaped into it (only the outgoing handle follows the pointer); Space held while dragging out an anchor moves it, handles and all. A press on the first anchor of the path being drawn closes it whatever the drag then does: the drag shapes the closing curve (symmetric handles, Alt breaks them) and the release closes the path wherever it ends (#501). Clicking the last anchor of the path being drawn retracts its outgoing handle (convert cursor), and dragging from it pulls out a new one on its own. Auto Add/Delete: over a selected path, a click on a segment adds an anchor and a click on an anchor deletes it (add and delete cursors); Shift held, or Preferences › General › Disable Auto Add/Delete, starts a new path instead. Alt held over a handle end or an anchor of a selected path (the one being drawn too) works as the Anchor Point tool, with its convert cursor: dragging a handle moves it alone, clicking a smooth anchor makes it a corner, dragging an anchor pulls out new symmetric handles, dragging a segment reshapes it; drawing then goes on. Cmd (Ctrl) held drags with the selection tool chosen last, Direct Selection until one is (handles, anchors and segments of the path being drawn or another), and the Pen then goes on drawing its path while that stays selected; the pointer shows that tool's while Cmd is held. The same holds for agents (`pointer_gesture` with `mods.cmd`), as the borrowing now lives in the engine (#494).
|
||||
- **Path editing (#494):** the handles shown are the handles that drag: Direct Selection drags those of a path selected as a whole (as the Pen leaves it), the Anchor Point tool and Pen+Alt no longer grab handles that Show handles when multiple anchors are selected hides, a handle shorter than the tolerance leaves its anchor to be picked, and the anchor tools pick within Selection & Anchor Display › Tolerance. A dragged segment keeps a smooth anchor at either end smooth. With Direct Selection, the Pen, the Curvature and the anchor tools, a path selected as a whole shows all its anchors selected, and the Control bar and the Properties panel offer Convert (corner, smooth) for them too; Remove and Cut wait for anchors direct-selected (#504). A handle drag gathers its snap targets once per drag (it took 21 ms per pointer move on a 20,000-path document, now 1 ms; `vectorcraft-cli perf` measures handle and segment drags on a 5,000-anchor path).
|
||||
- **Graphs:** Column, Stacked Column, Bar, Stacked Bar, Line, Area, Scatter, Pie and Radar graph tools with Graph Data and Graph Type.
|
||||
- **Other:** Eyedropper, Gradient annotator, Artboard (Alt-drag duplicates an artboard, and its art with Move/Copy Artwork with Artboard on; Copy, Cut and Paste take the artboard with its art, Paste right of the last artboard, Paste in Place where it was, into this or another document, #446), Measure, Type, Hand, Zoom, Rotate View.
|
||||
- **Other:** Eyedropper, Gradient annotator, Artboard (Alt-drag duplicates an artboard, and its art with Move/Copy Artwork with Artboard on; Copy, Cut and Paste take the artboard with its art, Paste right of the last artboard, Paste in Place where it was, into this or another document, #446; Object › Artboards › Rearrange All Artboards lays them out in a grid by row or by column, in one row or one column, left to right or right to left, from the menu, the Artboards panel or Properties' Rearrange All, #681), Measure, Type, Hand, Zoom, Rotate View.
|
||||
- **Editing type:** double-clicking type with a selection tool switches to the Type tool with the caret where it was clicked.
|
||||
- **Temporary tools:** Cmd with any other tool drags with the selection tool used last (Selection, Direct Selection or Group Selection). Held Space pans and Cmd+Space zooms (Cmd+Alt+Space out) whatever the tool.
|
||||
- **Panel drag and drop:** art dragged off the canvas onto the Symbols panel becomes a symbol, onto the Swatches panel a pattern swatch and onto the Brushes panel an Art brush; a symbol dragged onto the canvas places an instance where it is dropped, and a brush dragged onto a path is applied to it.
|
||||
@@ -143,10 +146,10 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist
|
||||
- **Type:** Text Wrap, Type on a Path effects (Rainbow/Skew/3D Ribbon/Stair Step/Gravity) and Options (Flip, Align to Path, Spacing; OK keeps the type where it is), type on a path's start, centre and end brackets (Selection and Direct Selection drag them to set where the type runs, slide it along its path and, across the path, flip it: #429), Character and Paragraph Styles (override-preserving redefine), paragraph attributes per paragraph (alignment, indents, spacing, hyphenation, hanging punctuation, tab stops, paragraph style, direction, mojikumi and leading model; the Paragraph, Tabs and Paragraph Styles panels act on the paragraphs the Type tool's selection or caret touches, Return continues the paragraph's style, threads and SVG keep them), Area Type Options (rows/columns/inset/first baseline, vertical Align Top/Center/Bottom/Justify per row/column, reflowing non-rectangular frames and text wrap), threaded text across any closed shapes, Fit Headline, the Every-line Composer for justified and ragged text (paragraph-wide breaks for an even rag, Single-line per object from the Paragraph panel menu or `text.setFormat {composer}`). Area type resizes like Illustrator's type areas: a bounding-box handle drag (Selection tool) or Area Type Options Width/Height size the frame and the text reflows at its size (threads too); Direct Selection drags a frame corner or edge (`text.reshapeArea`). Point type still scales. Auto Size: the frame height follows the text after every edit, in the same undo step (rectangular frames of horizontal type in one row; columns get the least height that holds them; a height set by hand or threading turns it off), and the "Auto Size New Area Type" preference gives it to new area type. Shrink Text to Fit (beyond Illustrator): overflowing area type scales its sizes, leading and baseline shifts down by the largest factor (in 0.1 pt steps of the first run, down to a minimum percentage) that fits, at layout time so every export sees it. `text.areaOptions` and `document.inspect` report overflow and the shrink factor. The Selection tool shows the type widget beside selected type's bounding box (hollow on point type, filled on area type); double-clicking it converts between them (Type › Convert To Area Type / Convert To Point Type), keeping the text and its styles in place. Variable fonts list every named instance as a style of their family (Figtree Light to Black and their italics, Bahnschrift, Segoe UI Variable), and the instance chosen is shaped, drawn, outlined and measured at its axis settings; PDF and SVG embed it as that instance. Variation axis sliders are not done. Beyond Illustrator: inline graphics (`text.insertInline`, Type ▸ Insert Inline Symbol) set a document symbol in a run of type as one character that flows, wraps and justifies like a glyph (InDesign-style inline objects, e.g. mana symbols in card rules text): sized to a multiple of the font size, centred on the cap height, opening up tall lines, following Redefine Symbol; a character of its run's size for Character Alignment and Top-to-Top leading, placed by the bidi reordering in right-to-left text (a neutral U+FFFC); drawn on the canvas, kept as live text plus a `<use>` in SVG and as vector art in PDF; Backspace removes it whole. Hebrew and Arabic are laid out right to left with the Unicode bidirectional algorithm (embedded Latin and numbers keep their direction, lines put in visual order after wrapping) in point, area and path type, with caret, selection and arrow keys in visual order; each paragraph's direction comes from its first strong character unless Paragraph Direction sets it (Paragraph panel with Show Indic Options, `text.setFormat {direction}`), and new type aligns to the start of its direction. SVG export outlines right-to-left text. Font Size and Leading are combo boxes in the Character and Properties panels (Font Size in the Control bar too, beside the Character link, font family and style): type, step with ↑/↓ or the spinner, scrub the label, or pick a preset (6–72 pt, shown in the type unit; Leading also Auto), each pick one undo step; Kerning and Tracking list -100…200; a size, leading, kerning or tracking the selected text doesn't share shows blank (#458).
|
||||
- **Interface languages, vertical type:** VectorCraft ▸ Language (or Preferences ▸ User Interface) picks Automatic (the system locale) or a registered language, persisted as `interfaceLanguage`. Translations come from per-language catalogs (`i18n/*.tsv`): Traditional and Simplified Chinese, Japanese, Spanish (neutral international Spanish, for every `es-*` locale), French (every `fr-*` locale), Italian (every `it-*` locale) and Russian (every `ru-*` locale) cover the whole interface, Czech and Brazilian Portuguese every menu label, Brazilian Portuguese the shell's `tl!` literals too (tested); Spanish, French, Italian and Russian also translate status-bar and error messages as they are shown (`@msg` templates, every message literal tested; the messages themselves stay English for agents); untranslated text stays English. Japanese and Chinese glyphs come from the craft-fonts build input (release builds) or the installed fonts, Czech, Spanish, French, Italian and Russian ones from the bundled UI fonts. The web app follows the browser's languages (or `?lang=`). The Basic toolbar's Type button holds Vertical Type in its flyout. Vertical Type, Vertical Area Type and Vertical Type on a Path create vertical text (columns right to left, upright CJK glyphs and marks with `vert` alternates, Latin and longer numbers on their side, two- and three-digit numbers set as tate-chu-yoko in one em of the column (kept whole when justified), upright glyphs centred on the column (tracked or justified too), point type's anchor on the first column's centre line); kinsoku (the strict set) applies to horizontal and vertical Japanese, and justified Japanese lines spread their room between characters (not inside Latin words); Paragraph panel › Mojikumi Set (shown with Preferences › Type › Show East Asian Options, `text.setFormat {mojikumi}`): None or Line-end Punctuation Half Width (new type's default, as in Illustrator; older documents and imported text keep None) shares one half-em space between consecutive punctuation, sets a closing mark ending a line half width and an opening bracket starting a wrapped line flush with its start, and puts a quarter em between Japanese and Latin letters or digits; Paragraph panel menu › Top-to-Top / Bottom-to-Bottom Leading measures leading from em box top to top (area type's first line touches the frame) or from baseline to baseline (new type in a Japanese interface starts top to top, with em box centre character alignment, #432); Paragraph panel menu › Burasagari None / Regular / Force (`text.setFormat {burasagari: "none"|"standard"|"forced"}`) hangs an East Asian comma or full stop (、。,.、。) ending an area type line outside it, Regular (new type's default) when it doesn't fit and Force always (the rest of the line then fills the measure; closing brackets and Latin punctuation don't hang); Character panel menu › Character Alignment (with the East Asian options; `text.setFormat` or `text.setRangeStyle {charAlign}`) lines characters smaller than the largest on their line up on the Roman baseline, the em box top/right, centre or bottom/left, or the ICF (ideographic character face) top/right or bottom/left, from the font's BASE table or, without one, the average ink box of some ideographs and kana; Type ▸ Type Orientation switches existing text; caret, selection, hit testing and arrow keys follow the writing direction. Vertical text exports to PDF as real text and to SVG as outlines.
|
||||
- **Transparency:** opacity masks (clip/invert/disable/link), exported as SVG `<mask>` and PDF soft masks.
|
||||
- **Advanced art:** live Blends (steps/distance/smooth colour, editable spine, anchor-targeted Blend tool, faithful interpolation, knockout), Envelope Distort (warp/mesh/top object, Reset, full Envelope Options, mesh handles, Edit Contents; type, images, symbols, gradients, patterns and appearance distorted everywhere), Liquify tools with options and pen pressure, Puppet Warp with rotating pins, Perspective Grid with presets, movable planes and projected type (choosing a perspective tool shows the grid; Hide Grid hides it with the tool still chosen), Gradient Mesh, Shape Builder (stroke-only open paths and lines cut the regions they cross and enclose regions of their own; filled open paths count as closed; erase mode while Alt/Option is held: a minus pointer, red highlights of what will go, a click or drag deletes the regions touched, the pieces of open lines and the edges (outline pieces between the points where paths meet, opening their paths there) it passes over, one undo step, `shapeBuilder.merge {erase}` and `shapeBuilder.regions` edges over MCP), Live Paint (every path an edge, open lines included), Image Trace (12 presets, colour layers traced in parallel; a trace past two million anchor points or an image over 64 megapixels is refused with advice rather than running out of memory, and a selection too large to outline shows its bounds (#525); Object › Image Trace › Make and Make and Expand trace at once with the Default preset, #543; with an image selected the Control bar and the Properties panel show Image Trace, whose arrow traces with any preset, Mask (`object.maskImage`: a clipping path on the image's outline, selected so its handles crop), Crop Image and Embed or Unembed in place of Fill and Stroke; with an Image Trace object selected, its Preset (choosing another traces again), View, the Image Trace panel and Expand, plus Release in Properties; the five View modes (Tracing Result, with Outlines, Outlines, Outlines with Source Image, Source Image) redraw a trace on screen without tracing again, are saved with it and `imageTrace.setView` sets them, while exports and Expand keep the result; the panel's Advanced section is a header that stays open or closed as it was left (part of #641); Color mode's Palette: Limited, Full Tone (as many colours as the tones need, Less … More), Automatic (flat art with its own colours, else Full Tone; a heuristic) and Document Library (the most used colours of the document's swatches or a swatch library, filled with the swatch colours as they are), part of #641; Advanced › Create: Fills and/or Strokes, where lines up to the Stroke width trace as stroked centre lines (distance transform, thinning, a skeleton graph with spurs pruned, curve fitting; one width per line; without Fills, wider areas become stroked outlines), part of #641), pattern swatches with pattern editing mode, live Repeat (radial/grid/mirror).
|
||||
- **Advanced art:** live Blends (steps/distance/smooth colour, editable spine, anchor-targeted Blend tool, faithful interpolation, knockout), Envelope Distort (warp/mesh/top object, Reset, full Envelope Options, mesh handles, Edit Contents; type, images, symbols, gradients, patterns and appearance distorted everywhere), Liquify tools with options and pen pressure, Puppet Warp with rotating pins, Perspective Grid with presets, movable planes and projected type (choosing a perspective tool shows the grid; Hide Grid hides it with the tool still chosen), Gradient Mesh, Shape Builder (stroke-only open paths and lines cut the regions they cross and enclose regions of their own; filled open paths count as closed; erase mode while Alt/Option is held: a minus pointer, red highlights of what will go, a click or drag deletes the regions touched, the pieces of open lines and the edges (outline pieces between the points where paths meet, opening their paths there) it passes over, one undo step, `shapeBuilder.merge {erase}` and `shapeBuilder.regions` edges over MCP), Live Paint (every path an edge, open lines included), Image Trace (12 presets, colour layers traced in parallel; a trace past two million anchor points or an image over 64 megapixels is refused with advice rather than running out of memory, and a selection too large to outline shows its bounds (#525); Object › Image Trace › Make and Make and Expand trace at once with the Default preset, #543; with an image selected the Control bar and the Properties panel show Image Trace, whose arrow traces with any preset, Mask (`object.maskImage`: a clipping path on the image's outline, selected so its handles crop), Crop Image (`object.cropImage {trim: true}` cuts an image to its pixels that aren't fully transparent, pixel for pixel) and Embed or Unembed in place of Fill and Stroke; with an Image Trace object selected, its Preset (choosing another traces again), View, the Image Trace panel and Expand, plus Release in Properties; the five View modes (Tracing Result, with Outlines, Outlines, Outlines with Source Image, Source Image) redraw a trace on screen without tracing again, are saved with it and `imageTrace.setView` sets them, while exports and Expand keep the result; the panel's Advanced section is a header that stays open or closed as it was left (part of #641); Color mode's Palette: Limited, Full Tone (as many colours as the tones need, Less … More), Automatic (flat art with its own colours, else Full Tone; a heuristic) and Document Library (the most used colours of the document's swatches or a swatch library, filled with the swatch colours as they are), part of #641; Advanced › Create: Fills and/or Strokes, where lines up to the Stroke width trace as stroked centre lines (distance transform, thinning, a skeleton graph with spurs pruned, curve fitting; one width per line; without Fills, wider areas become stroked outlines), part of #641), pattern swatches with pattern editing mode, live Repeat (radial/grid/mirror).
|
||||
- **Paint and appearance (M3):**
|
||||
- **Swatches:** names follow the colour model and are unique; Swatch Options (process/spot, Global, Gray/RGB/HSB/CMYK/Web, live preview); editing a global or spot swatch recolours every linked fill, stroke and text run in one undo step; multi-select and delete with confirmation; New Swatch and New Color Group dialogs (a group from the selected artwork's colours); swatches in colour groups convert, separate and count like any other. The Swatches panel selects ranges and whole groups, has a find field, and drags swatches to reorder, regroup or paint art; Add Used Colors, Select All Unused, Merge, Ungroup and Sort by Kind; a CMYK document keeps applied colours in CMYK. Swatch libraries: nine generated colour libraries and five gradient libraries in a library panel, saved as `.vcswatches`, `.gpl` or CSS, and loaded from `.vcswatches`, `.gpl` and swatch exchange (`.ase`) files (RGB, CMYK, Lab and Gray; global, spot and process; groups). Tints of global and spot colours ("Name 40%") stay linked and separate as a percentage of their plate. Spot colours can be defined in Lab (Spot Colors options). A built-in [Registration] swatch prints on every plate.
|
||||
- **Colour:** a Color Picker (colour field, H/S/B/R/G/B channel slider, HSB/RGB/Lab/CMYK fields, hex, web-only snapping, out-of-gamut correction); the Color panel follows each colour's own model and Alt-click paints the other proxy; proxies look through groups and show "?" for mixed paint; Invert, Complement, Apply Last Color (`,`) and Apply Last Gradient (`.`) keep the colour model; every paint command feeds the recent colours. The Color Guide has 21 harmony rules, Steps and Variation options and Limit to Library. Adjust Color Balance (its Global mode shifts tints) and Saturate preview live; Edit Colors and Recolor also reach meshes, images and patterns. Recolor Artwork has colour reduction, five recolour methods, presets, Limit to Library, a colour-wheel Edit tab and Edit Color Group; a local Color Themes panel saves five-colour themes. Fill/Stroke chips open swatch and mixer popovers (the Properties panel has the Control bar's Fill and Stroke chips, Stroke link and weight spinner, with nothing selected too), panels have Illustrator's Window menu keys (Align Shift+F7, Transform Shift+F8, Pathfinder Cmd+Shift+F9, Layers F7, Character Cmd+T…; every panel can be given one in Edit › Keyboard Shortcuts), and Eyedropper Options pick up and apply chosen attributes (Alt and Shift+Alt, image pixels). Fills and strokes can overprint (Attributes panel, Overprint Black options), and CMYK documents blend in inks on screen, in PDF and when flattening. Document Color Mode converts the art, symbols, pattern tiles and swatches through the colour settings: Gray stays Gray, RGB greys separate into four-colour greys and a rich black as Illustrator does, or go on the black plate only with `grays: "black"` (also for `document.open {colorMode}`).
|
||||
- **Colour:** a Color Picker (colour field, H/S/B/R/G/B channel slider, HSB/RGB/Lab/CMYK fields, hex, web-only snapping, out-of-gamut correction); the Color panel follows each colour's own model and Alt-click paints the other proxy; proxies look through groups and show "?" for mixed paint; Invert, Complement, Apply Last Color (`,`) and Apply Last Gradient (`.`) keep the colour model; every paint command feeds the recent colours. The Color Guide has 21 harmony rules, Steps and Variation options and Limit to Library. Adjust Color Balance (its Global mode shifts tints) and Saturate preview live; Edit Colors and Recolor also reach meshes, images and patterns. Recolor Artwork has colour reduction, five recolour methods, presets, Limit to Library, a colour-wheel Edit tab and Edit Color Group; a local Color Themes panel saves five-colour themes. Fill/Stroke chips open swatch and mixer popovers (the Properties panel has the Control bar's Fill and Stroke chips, Stroke link and weight spinner, with nothing selected too), panels have Illustrator's Window menu keys (Align Shift+F7, Transform Shift+F8, Pathfinder Cmd+Shift+F9, Layers F7, Character Cmd+T…; every panel can be given one in Edit › Keyboard Shortcuts), and Eyedropper Options pick up and apply chosen attributes (Alt and Shift+Alt, image pixels). An ICC CMYK profile converts straight into the RGB working space (not through sRGB, so a wider space such as Wide Gamut RGB keeps colours sRGB can't hold) with the colour settings' black-point compensation, on the canvas and in RGB exports alike. Fills and strokes can overprint (Attributes panel, Overprint Black options), and CMYK documents blend in inks on screen, in PDF and when flattening. Document Color Mode converts the art, symbols, pattern tiles and swatches through the colour settings: Gray stays Gray, RGB greys separate into four-colour greys and a rich black as Illustrator does, or go on the black plate only with `grays: "black"` (also for `document.open {colorMode}`).
|
||||
- **Gradients:** lossless, validated gradient params; gradients follow rotate, reflect, shear, non-uniform scale and distortions; the Gradient tool edits the fill or stroke of the active proxy, type included; an interactive on-canvas annotator (move, length/angle, rotate, add/move/delete/duplicate stops, midpoints, a stop popover, Delete and arrow keys). The Gradient panel has the Fill/Stroke proxy, a gradient-swatch dropdown with Save to Swatches, midpoint locations, Alt-drag to copy or swap stops, swatch drops on the ramp and a stop eyedropper; copied appearances and graphic styles place gradients on each target's own bounds; gradient handles snap and honour Constrain Angle. Gradient stops stay linked to global and spot swatches. Freeform gradients (points and lines) are edited on the canvas; radial gradients have an extent ellipse, an aspect handle and an off-centre focal point (SVG `fx`/`fy`, PDF two-point radials). A stroke's gradient runs within, along or across it. Object ▸ Expand turns gradients into N objects or a gradient mesh.
|
||||
- **Strokes:** one stroke-geometry module shared by the canvas, SVG, PDF and Outline Stroke; dotted lines (zero-length dashes draw dots or squares); arrowheads with hollow outlines, tip-on-end or extend-past-end alignment and one opacity for line and head. SVG and PDF export arrowheads, width profiles, brushes and aligned strokes exactly as the canvas draws them; Outline Stroke and the live Outline Stroke effect outline every stroke item as drawn (dashes, heads, profiles, alignment); dashes can be fitted to corners and path ends; width profiles carry through dashes, and their corners take the join. The Stroke panel edits type's character strokes, follows the stroke units (its weight presets are round values in that unit: `0.25 mm`, `0.0625 in`, `1 px`, #426; fields show four decimals in mm, cm and inches, three in points), shows mixed values blank and opens from the Control bar. A width profile library, thirty more arrowheads, and Width Point Edit with multi-select and discontinuous points. Visual bounds and clicks cover the whole painted stroke. Scale Strokes & Effects, Scale Corners and Use Preview Bounds work everywhere, and new art inherits stroke options, a graphic style or the whole last appearance.
|
||||
- **Appearance:** the Appearance panel's selected row drives every paint, stroke, gradient and transparency edit (`item` on the commands); effects apply to one fill or stroke; per-item Opacity popups, whose blend-mode list and opacity slider stay open inside them (#430; the Control bar's Stroke popover too); Mixed Appearances, Layers target dots and basic-appearance rules. Effects can be reordered, moved between items and copied by dragging; Show All Hidden Attributes; clicking an effect edits it in place; the object thumbnail drags onto art; effects render on type, images, symbols, blends, envelopes, meshes and repeats, and per-item raster effects export. Groups, layers and type have their own fills, strokes and effects (Contents and Characters rows); the Layers panel's target circles target layers, groups and objects; Expand Appearance turns fills, strokes, effects and brushes into objects.
|
||||
@@ -158,7 +161,7 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist
|
||||
- **Fonts:** a font is found by any of its names (family and style in every language of its name table, legacy family/style pairs, PostScript name), so documents from other apps open with the font they name; Find Font and `text.fonts` say for each font whether it was found exactly, by another name, substituted or missing, and how many glyphs are missing. PDF and `.ai` import brings Japanese text back as live type: CID fonts without a ToUnicode map read through the standard CMaps, vertical columns (WMode 1) as vertical type, letter spacing as tracking; a glyph is live type only when the installed font (in the closest style of its family) draws the same glyph, and text in a font that isn't installed comes in as live type shown in the fallback font until the font is installed (exports that draw it — PDF, EPS, EMF/WMF, raster, SVG outlines or embedded fonts — warn that they wrote the fallback font; `textAs: outlines` keeps the PDF's embedded glyphs).
|
||||
- **Files (M4):**
|
||||
- `.vectorcraft` (lossless JSON, compressed, atomic saves, save down to v1), Save As with a format chooser, Save a Copy, Revert, templates, Data Recovery after a crash (browser tabs hold their copies with Web Locks too, so a background tab's copies are never taken for a crash's, and a tab repairs copies another removed when it resumes: #367), background save and export. The desktop app writes its warnings and errors (graphics adapter, a lost graphics device, panics the guard recovered from) to standard error and to `logs/vectorcraft.log` next to the preferences, the two previous runs kept and each file capped at 16 MiB, so a launch without a terminal still leaves something to attach to a bug report (#465).
|
||||
- SVG/SVGZ in and out with SVG Options, Preserve Editing, symbols, filters, rich text and physical units (SVG type under a transform or `viewBox` scale opens at the size it draws at, the scale moved into its size, leading, baseline shift and strokes, a stretch, skew or rotation kept as its transform: #396; a top-level group with a clip path, such as a clipped Inkscape layer, opens as a layer with a clipping mask, its name kept: #420; hidden objects written hidden on Save and `convert`, and `data-*` attributes kept as the objects' own data: #522; top-level groups open as layers named from `data-name`, else the id, also when one more group (a transform on all the art, a `<switch>`) wraps them, hidden ones hidden, and a file whose art sits loose under a root `<svg>` with an id (or `data-name`), as one-layer exports write it, opens with its one layer named from it; nested groups stay groups, except the sublayers VectorCraft writes, marked `data-vc-layer`, and Inkscape sublayers, which open as sublayers in their layer's colour: #372); PDF and PDF-compatible `.ai` in and out (layers, with hidden ones kept hidden with their art and nested ones as sublayers, on pages of up to 64 million operators, art whose layer can't be told going to a hidden, non-printing layer rather than showing or printing: #419; strokes kept live, a fill and a stroke of one outline as one object; a type object's stroke written as each glyph's outline stroked back on the type, so it stays one editable object; lines wrapped in a frame (each wrapped line ending in a space, one left edge, leading and font) back as one area type object, left aligned or justified with its paragraph spacing, where laying it out breaks the lines where the file does; glyphs set apart by gaps wider than a space (a barcode's digit groups) keeping their places; layers stacked as the pages mark them even when one first paints on a later page, art ending a layer's marked content or a clip closing in a later layer kept in its own layer, and layers with no art kept empty: #508; masks, editable text with type set along a curve coming back as type on a path, each artboard's art on its own page only, an `.ai`'s white page under its layers left out rather than coming in as art, spot colours, presets, security, marks and bleed, ICC output intents, raster effects, subset fonts, PDF/X, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3). CMYK images keep their ink amounts from PDF import (and from placed CMYK TIFFs) to PDF export: a CMYK JPEG passes through unchanged, others stay CMYK (DeviceCMYK, or ICC-based CMYK in PDF/X-3/X-4) unless the Output settings convert them; the canvas shows them through the working CMYK profile (#320).
|
||||
- SVG/SVGZ in and out with SVG Options, Preserve Editing, symbols, filters, rich text and physical units (SVG type under a transform or `viewBox` scale opens at the size it draws at, the scale moved into its size, leading, baseline shift and strokes, a stretch, skew or rotation kept as its transform: #396; a top-level group with a clip path, such as a clipped Inkscape layer, opens as a layer with a clipping mask, its name kept: #420; hidden objects written hidden on Save and `convert`, and `data-*` attributes kept as the objects' own data: #522; top-level groups open as layers named from `data-name`, else the id, also when one more group (a transform on all the art, a `<switch>`) wraps them, hidden ones hidden, and a file whose art sits loose under a root `<svg>` with an id (or `data-name`), as one-layer exports write it, opens with its one layer named from it; nested groups stay groups, except the sublayers VectorCraft writes, marked `data-vc-layer`, and Inkscape sublayers, which open as sublayers in their layer's colour: #372); PDF and PDF-compatible `.ai` in and out (layers, with hidden ones kept hidden with their art and nested ones as sublayers, on pages of up to 64 million operators, art whose layer can't be told going to a hidden, non-printing layer rather than showing or printing: #419; strokes kept live, a fill and a stroke of one outline as one object; a type object's stroke written as each glyph's outline stroked back on the type, so it stays one editable object; lines wrapped in a frame (each wrapped line ending in a space, one left edge, leading and font) back as one area type object, left aligned or justified with its paragraph spacing, where laying it out breaks the lines where the file does; glyphs set apart by gaps wider than a space (a barcode's digit groups) keeping their places; layers stacked as the pages mark them even when one first paints on a later page, art ending a layer's marked content or a clip closing in a later layer kept in its own layer, and layers with no art kept empty: #508; masks, editable text with type set along a curve coming back as type on a path, each artboard's art on its own page only, an `.ai`'s white page under its layers left out rather than coming in as art, spot colours, presets, security, marks and bleed, ICC output intents, raster effects, subset fonts, PDF/X, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3). CMYK images keep their ink amounts from PDF import (and from placed CMYK TIFFs) to PDF export: a CMYK JPEG passes through unchanged, others stay CMYK (DeviceCMYK, or ICC-based CMYK in PDF/X-3/X-4) unless the Output settings convert them; the canvas shows them through the working CMYK profile (#320). A masked CMYK image (`/SMask`, `/Mask` or a colour key) keeps its inks too, its alpha coming in as a greyscale opacity mask.
|
||||
- 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).
|
||||
@@ -210,13 +213,13 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale)
|
||||
| Strokes, brushes, width profiles | 5 | 88% | brush options depth, brush libraries (generated in code), brushes driven by pen tilt, bearing and barrel rotation (6D art pens) | 12–20 |
|
||||
| Appearance, transparency, graphic styles, masks | 5 | 98% | raster effect reach in preview bounds (flattener presets apply in PDF, EPS and print) | 1–2 |
|
||||
| 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 |
|
||||
| Raster effects (Effect Gallery, Document Raster Effects Settings) | 4 | 24% | ~52 Photoshop-style filters (Artistic, Brush Strokes, Distort, Pixelate, Sketch, Stylize, Texture, Video), Smart Blur's Edge Only / Overlay Edge modes and the Effect Gallery; Document Raster Effects Settings, raster effects in PDF, the pixel-filter pipeline, Radial Blur, Smart Blur and Unsharp Mask are done | 26–40 |
|
||||
| 3D and Materials | 4 | 0% | Extrude & Bevel, Revolve, Inflate, Rotate, lighting, materials (software renderer) | 50–80 |
|
||||
| Type core | 9 | 80% | Middle Eastern features beyond bidi layout and Paragraph Direction (Character Direction, digit types, kashidas, the Middle Eastern composers, editable bidirectional SVG text, a split caret where directions meet); Hyphenation… and Justification… options (Every-line Composer for justified and ragged text, per object, is done; it is tuned by eye, not yet compared side by side with Illustrator; mixed type sizes in a paragraph still break single-line), Optical Margin Alignment, paragraph spacing limit for vertically justified area type, hidden characters, paragraph attributes in the Type tool's copy and paste (the characters keep their styles, the paragraphs take the destination's), mixed-value display in the Paragraph panel for a selection across differing paragraphs, Transform Again after a type-area resize (it scales the type), partial selection of type-area anchors by marquee | 14–19 |
|
||||
| Type advanced | 4 | 50% | CJK composition for vertical type (ruby, mojikumi beyond Line-end Punctuation Half Width — the other sets (and their paragraph-start bracket and indent rules), kinsoku sets and the Mojikumi Settings dialog —, proportional vertical metrics, manual tate-chu-yoko), variable font axis sliders (named instances are styles), tab leaders, spell check (open dictionary), Touch Type, Retype; vertical point/area/path type and Type Orientation have initial support (beyond parity, not scored: inline symbols in text) | 20–28 |
|
||||
| Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | symbol libraries (original), dynamic symbols, envelope Anti-Alias/Preserve Shape output and warp point editing, brush interpolation in blends (M8 fidelity pass done) | 5–8 |
|
||||
| Image Trace, graphs, image tools | 3 | 70% | graph Design/Column/Marker, Create Object Mosaic, Crop Image polish (an on-canvas crop box), per-feature stroke/fill choice and varying widths in Image Trace's Create Strokes (Vector Halftone and the Image Trace View modes, Palette and Create Strokes are done) | 6–10 |
|
||||
| Layers, artboards, document setup | 5 | 82% | Layers panel: a confirmation before deleting layers that hold art, Collect for Export, row context menus, the Layer Options dialog for several rows with mixed values, Paste Remembers Layers for sublayers, drag-scrolling a long panel while dragging rows; artboard presets/rearrange polish (Document Setup, New Document and the rest of the Layers panel are done) | 4–7 |
|
||||
| Layers, artboards, document setup | 5 | 82% | Layers panel: a confirmation before deleting layers that hold art, Collect for Export, row context menus, the Layer Options dialog for several rows with mixed values, Paste Remembers Layers for sublayers, drag-scrolling a long panel while dragging rows; artboard preset polish (Rearrange All Artboards, Document Setup, New Document and the rest of the Layers panel are done) | 4–7 |
|
||||
| View & navigation | 3 | 70% | New View/Edit Views, multiple windows/arrange, Snap to Pixel/Glyph (print tiling is done) | 9–14 |
|
||||
| Guides, grids, smart guides, snapping, rulers | 3 | 85% | global/video rulers, Spacing Guides' distance readouts and spacing for resized or drawn art, Smart Guides' angle and distance readouts while drawing, Alt swapping a ruler guide's orientation, ruler guides selected together with art (marquee, Shift-click), ruler guides as Layers rows with their own lock and hide (#451: Lock Guides locks them all; Make Guides paths are Layers rows already) (dragging existing guides is done, #414; new guides snapping to side midpoints and artboards, and artboard guides, #451; the drawing tools snapping, with Construction Guides, #506; Spacing Guides for moves, #394) | 2–4 |
|
||||
| File formats | 6 | 85% | DWG (no open spec: DXF instead), PSD placement as layers, EPS checked against more real files users send (Inkscape files open as vectors; other generators' constructs are tested with programs written from the PostScript Language Reference only; CID-keyed CJK type and `CCITTFaxDecode` images not read), legacy `.ai` files saved without the prolog that defines their operators (their own operator set isn't read yet), the remaining fidelity polish; EPS, DXF, EMF/WMF, TIFF, BMP, Targa, PSD export, SVGZ, PDF security, PDF/X, PDF layers and presets are done | 6–10 |
|
||||
@@ -236,7 +239,7 @@ With 4–6 agents working on disjoint crates (as the layering allows) the wall-c
|
||||
|
||||
_Inventories (2026-10-07):_ 13 menu items still stubbed (`todo(…)` in `crates/ui-egui/src/menus.rs`); every tool
|
||||
implemented except Touch Type; 51 panel modules; Illustrator-style live
|
||||
effects ~44/54, Photoshop-style raster effects ~1/56, 3D 0/5; ~2,840 tests; ~221k lines of Rust.
|
||||
effects ~44/54, Photoshop-style raster effects ~4/56, 3D 0/5; ~2,840 tests; ~221k lines of Rust.
|
||||
|
||||
_Where we already beat Illustrator:_ exact curve booleans, off-thread multithreaded rendering, undo that never runs out,
|
||||
lossless SVG/PDF export of live effects with SVG filters, a documented JSON format, the same app on the web, and every
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! ICC profiles through `moxcms` (pure Rust): built-in RGB spaces and user-supplied `.icc` files,
|
||||
//! and the profiles exports embed ([`encode_builtin`]), written in code from the CMS.
|
||||
|
||||
use std::sync::{Arc, OnceLock};
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
|
||||
use moxcms::{
|
||||
ColorProfile, DataColorSpace, Layout, LocalizableString, LutMultidimensionalType, LutStore, LutWarehouse, Matrix3d, ProfileClass, ProfileText,
|
||||
@@ -27,6 +27,9 @@ fn intent_index(i: Intent) -> usize {
|
||||
|
||||
type Xf = Option<Arc<TransformF32Executor>>;
|
||||
|
||||
/// A direct transform's cache key: destination name, intent index, black-point compensation.
|
||||
type DirectKey = (String, usize, bool);
|
||||
|
||||
/// A parsed ICC profile plus lazily-built transforms to/from sRGB.
|
||||
pub struct IccProfile {
|
||||
pub name: String,
|
||||
@@ -37,6 +40,21 @@ pub struct IccProfile {
|
||||
srgb: ColorProfile,
|
||||
to_srgb: [OnceLock<Xf>; 4],
|
||||
from_srgb: [OnceLock<Xf>; 4],
|
||||
/// Direct transforms into other RGB profiles ([`Self::to_rgb_of`]), by destination, intent
|
||||
/// and black-point compensation.
|
||||
direct: Mutex<Vec<(DirectKey, Option<Arc<Direct>>)>>,
|
||||
}
|
||||
|
||||
/// A transform from one profile into an RGB profile without passing through sRGB: into the
|
||||
/// destination's primaries with linear tone curves, where black-point compensation is a linear
|
||||
/// remap, then onto its own curves.
|
||||
struct Direct {
|
||||
to_linear: Arc<TransformF32Executor>,
|
||||
/// Linear → the destination's curves; `None` when the destination isn't a matrix profile
|
||||
/// (the first transform goes straight into it, without compensation).
|
||||
to_dest: Option<Arc<TransformF32Executor>>,
|
||||
/// The source black's luminance in the linear destination (0: no compensation).
|
||||
black: f32,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for IccProfile {
|
||||
@@ -72,6 +90,7 @@ impl IccProfile {
|
||||
srgb: ColorProfile::new_srgb(),
|
||||
to_srgb: Default::default(),
|
||||
from_srgb: Default::default(),
|
||||
direct: Mutex::new(Vec::new()),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -135,6 +154,72 @@ impl IccProfile {
|
||||
Some(dst.into_iter().map(|x| x.clamp(0.0, 1.0)).collect())
|
||||
}
|
||||
|
||||
/// Device values (RGB / CMYK / Gray, 0..1) → `dest`'s RGB, converted directly with `intent`:
|
||||
/// not through sRGB, so colours outside sRGB keep their place in a wider space. With `bpc`
|
||||
/// (and an intent other than absolute), this profile's black maps onto the destination's
|
||||
/// black (black-point compensation, the darkest ink the profile prints becoming RGB 0 rather
|
||||
/// than a dark grey). `None` when `dest` isn't RGB or no transform can be built.
|
||||
pub fn to_rgb_of(&self, dest: &IccProfile, v: &[f32], intent: Intent, bpc: bool) -> Option<[f32; 3]> {
|
||||
let t = self.direct_xf(dest, intent, bpc && intent != Intent::AbsoluteColorimetric)?;
|
||||
let mut src = v.to_vec();
|
||||
src.resize(self.channels(), 0.0);
|
||||
let mut lin = [0.0f32; 3];
|
||||
t.to_linear.transform(&src, &mut lin).ok()?;
|
||||
let Some(to_dest) = &t.to_dest else { return Some(lin.map(|x| x.clamp(0.0, 1.0))) };
|
||||
if t.black > 0.0 {
|
||||
lin = lin.map(|x| (x - t.black) / (1.0 - t.black));
|
||||
}
|
||||
let lin = lin.map(|x| x.clamp(0.0, 1.0));
|
||||
let mut out = [0.0f32; 3];
|
||||
to_dest.transform(&lin, &mut out).ok()?;
|
||||
Some(out.map(|x| x.clamp(0.0, 1.0)))
|
||||
}
|
||||
|
||||
fn direct_xf(&self, dest: &IccProfile, intent: Intent, bpc: bool) -> Option<Arc<Direct>> {
|
||||
if dest.kind != ProfileKind::Rgb {
|
||||
return None;
|
||||
}
|
||||
let key = (dest.name.clone(), intent_index(intent), bpc);
|
||||
let mut cache = self.direct.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some((_, t)) = cache.iter().find(|(k, _)| *k == key) {
|
||||
return t.clone();
|
||||
}
|
||||
let t = self.build_direct(dest, intent, bpc).map(Arc::new);
|
||||
cache.push((key, t.clone()));
|
||||
t
|
||||
}
|
||||
|
||||
fn build_direct(&self, dest: &IccProfile, intent: Intent, bpc: bool) -> Option<Direct> {
|
||||
let d = &dest.profile;
|
||||
let matrix = d.red_trc.is_some() && d.green_trc.is_some() && d.blue_trc.is_some();
|
||||
if !matrix {
|
||||
let xf = self.profile.create_transform_f32(self.layout(), d, Layout::Rgb, Self::opts(intent)).ok()?;
|
||||
return Some(Direct { to_linear: xf, to_dest: None, black: 0.0 });
|
||||
}
|
||||
let mut linear = d.clone();
|
||||
for trc in [&mut linear.red_trc, &mut linear.green_trc, &mut linear.blue_trc] {
|
||||
*trc = Some(ToneReprCurve::Parametric(vec![1.0]));
|
||||
}
|
||||
// A coding-independent code point names the transfer curve outright (moxcms's sRGB has
|
||||
// one) and would override the linear curves.
|
||||
linear.cicp = None;
|
||||
let to_linear = self.profile.create_transform_f32(self.layout(), &linear, Layout::Rgb, Self::opts(intent)).ok()?;
|
||||
let to_dest = linear.create_transform_f32(Layout::Rgb, d, Layout::Rgb, Self::opts(Intent::RelativeColorimetric)).ok()?;
|
||||
// The source black: the darkest colour the profile reproduces, found as lcms does for an
|
||||
// output profile (black sent into the profile and read back), made neutral.
|
||||
let black = if bpc && self.kind == ProfileKind::Cmyk {
|
||||
let inks = self.from_srgb([0.0; 3], Intent::RelativeColorimetric)?;
|
||||
let mut lin = [0.0f32; 3];
|
||||
to_linear.transform(&inks, &mut lin).ok()?;
|
||||
let y = |c: &moxcms::Xyzd| c.y as f32;
|
||||
let lum = lin[0] * y(&d.red_colorant) + lin[1] * y(&d.green_colorant) + lin[2] * y(&d.blue_colorant);
|
||||
lum.clamp(0.0, 0.5)
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
Some(Direct { to_linear, to_dest: Some(to_dest), black })
|
||||
}
|
||||
|
||||
/// Whether transforms can be built for this profile (checked at registration).
|
||||
pub fn usable(&self) -> bool {
|
||||
self.to_xf(Intent::RelativeColorimetric).is_some() && self.inverse_xf(Intent::RelativeColorimetric).is_some()
|
||||
|
||||
@@ -356,10 +356,37 @@ impl Cms {
|
||||
}
|
||||
}
|
||||
|
||||
/// CMYK in the working space → display sRGB (`absolute` simulates the paper colour).
|
||||
/// CMYK in the working space → display sRGB (`absolute` simulates the paper colour). An ICC
|
||||
/// CMYK profile converts as [`Self::cmyk_to_rgb`] does into sRGB (with the settings'
|
||||
/// black-point compensation), so what shows is what an RGB export writes.
|
||||
pub fn cmyk_to_srgb(&self, cmyk: [f32; 4], absolute: bool) -> [f32; 3] {
|
||||
if let (false, CmykSpace::Icc(p)) = (absolute, &self.cmyk)
|
||||
&& let Some(srgb) = builtin_rgb_cache(SRGB)
|
||||
&& let Some(v) = p.to_rgb_of(&srgb, &cmyk.map(|v| v.clamp(0.0, 1.0)), Intent::RelativeColorimetric, self.settings.bpc)
|
||||
{
|
||||
return v;
|
||||
}
|
||||
Self::cmyk_to_srgb_in(&self.cmyk, cmyk, absolute)
|
||||
}
|
||||
/// CMYK in the working space → working RGB with `intent`. An ICC CMYK profile converts
|
||||
/// directly into the RGB profile: not through display sRGB, which would clip colours a wider
|
||||
/// RGB space holds (Wide Gamut RGB keeps CMYK cyan that sRGB can't show), and with the
|
||||
/// settings' black-point compensation. The built-in CMYK spaces go through sRGB as before
|
||||
/// (Generic CMYK compensates in its own model).
|
||||
pub fn cmyk_to_rgb(&self, cmyk: [f32; 4], intent: Intent) -> [f32; 3] {
|
||||
let cmyk = cmyk.map(|v| v.clamp(0.0, 1.0));
|
||||
let src = match &self.cmyk {
|
||||
CmykSpace::Icc(p) => Some(p.clone()),
|
||||
CmykSpace::Generic(_) | CmykSpace::Device => None,
|
||||
};
|
||||
let dest = match &self.rgb {
|
||||
RgbSpace::Icc(p) => Some(p.clone()),
|
||||
RgbSpace::Srgb => builtin_rgb_cache(SRGB),
|
||||
};
|
||||
src.zip(dest)
|
||||
.and_then(|(s, d)| s.to_rgb_of(&d, &cmyk, intent, self.settings.bpc))
|
||||
.unwrap_or_else(|| self.srgb_to_rgb(self.cmyk_to_srgb(cmyk, false)))
|
||||
}
|
||||
/// Display sRGB → working CMYK with `intent`.
|
||||
pub fn srgb_to_cmyk(&self, srgb: [f32; 3], intent: Intent) -> [f32; 4] {
|
||||
Self::srgb_to_cmyk_in(&self.cmyk, srgb, intent, self.settings.bpc)
|
||||
@@ -424,6 +451,10 @@ impl Cms {
|
||||
let [c, m, y, k] = self.to_cmyk(c, intent);
|
||||
Color::Cmyk { c, m, y, k }
|
||||
}
|
||||
(Color::Cmyk { c, m, y, k }, Model::Rgb) => {
|
||||
let [r, g, b] = self.cmyk_to_rgb([*c, *m, *y, *k], intent);
|
||||
Color::Rgb { r, g, b }
|
||||
}
|
||||
(_, Model::Rgb) => {
|
||||
let [r, g, b] = self.srgb_to_rgb(self.display_rgb(c));
|
||||
Color::Rgb { r, g, b }
|
||||
|
||||
@@ -60,3 +60,54 @@ fn a_loaded_profile_is_embedded_as_loaded() {
|
||||
register_icc(&bytes, Some("Embedded As Loaded RGB".into())).unwrap();
|
||||
assert_eq!(&*icc_bytes("Embedded As Loaded RGB").unwrap(), &bytes[..]);
|
||||
}
|
||||
|
||||
/// Settings with an ICC CMYK profile (Generic CMYK's, loaded as a file is) and Wide Gamut RGB.
|
||||
fn icc_cmyk(bpc: bool) -> Cms {
|
||||
let name = register_icc(&icc_bytes(GENERIC_CMYK).unwrap(), Some("Test ICC CMYK".into())).unwrap().name;
|
||||
Cms::new(&ColorSettings { rgb: WIDE_GAMUT_RGB.into(), cmyk: name, bpc, ..ColorSettings::default() }).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn icc_cmyk_converts_into_a_wide_rgb_space_directly_without_clipping_to_srgb() {
|
||||
let wide = icc_cmyk(true);
|
||||
let cyan = [1.0, 0.0, 0.0, 0.0];
|
||||
let direct = wide.cmyk_to_rgb(cyan, Intent::RelativeColorimetric);
|
||||
// Through sRGB, cyan clips to sRGB's gamut first: in the wider space that reads as a red
|
||||
// channel well above zero.
|
||||
let hub = wide.srgb_to_rgb(wide.cmyk_to_srgb(cyan, false));
|
||||
assert!(direct[0] + 0.15 < hub[0], "direct {direct:?}, through sRGB {hub:?}");
|
||||
// Same colour either way where sRGB holds it: a mid grey and paper white.
|
||||
for inks in [[0.0, 0.0, 0.0, 0.5], [0.0; 4]] {
|
||||
let (d, h) = (wide.cmyk_to_rgb(inks, Intent::RelativeColorimetric), wide.srgb_to_rgb(wide.cmyk_to_srgb(inks, false)));
|
||||
assert!(d.iter().zip(h).all(|(a, b)| (a - b).abs() < 0.02), "{inks:?}: direct {d:?}, through sRGB {h:?}");
|
||||
}
|
||||
// Cms::convert takes the direct route for CMYK.
|
||||
let Color::Rgb { r, .. } = wide.convert(&Color::Cmyk { c: 1.0, m: 0.0, y: 0.0, k: 0.0 }, Model::Rgb, Intent::RelativeColorimetric) else {
|
||||
panic!("RGB")
|
||||
};
|
||||
assert!((r - direct[0]).abs() < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn black_point_compensation_maps_the_darkest_ink_to_rgb_black() {
|
||||
let rich = [0.75, 0.68, 0.67, 0.9];
|
||||
let (on, off) = (icc_cmyk(true).cmyk_to_rgb(rich, Intent::RelativeColorimetric), icc_cmyk(false).cmyk_to_rgb(rich, Intent::RelativeColorimetric));
|
||||
// Without compensation the profile's black is a dark grey; with it, rich black goes most of
|
||||
// the way to RGB black (not all: it isn't quite the darkest ink the profile prints).
|
||||
assert!(off.iter().all(|v| *v > 0.1), "without: {off:?}");
|
||||
assert!(on.iter().zip(off).all(|(a, b)| *a < 0.08 && *a < b * 0.5), "with: {on:?}, without: {off:?}");
|
||||
// The screen shows what an sRGB conversion writes, compensated alike.
|
||||
let srgb = |bpc| {
|
||||
let c = icc_cmyk(bpc);
|
||||
Cms::new(&ColorSettings { rgb: SRGB.into(), ..c.settings().clone() }).unwrap()
|
||||
};
|
||||
for bpc in [true, false] {
|
||||
let c = srgb(bpc);
|
||||
assert_eq!(c.cmyk_to_srgb(rich, false), c.cmyk_to_rgb(rich, Intent::RelativeColorimetric), "bpc {bpc}");
|
||||
}
|
||||
// White is untouched, and absolute colorimetric never compensates.
|
||||
let white = icc_cmyk(true).cmyk_to_rgb([0.0; 4], Intent::RelativeColorimetric);
|
||||
assert!(white.iter().all(|v| *v > 0.99), "{white:?}");
|
||||
let abs = |bpc| icc_cmyk(bpc).cmyk_to_rgb(rich, Intent::AbsoluteColorimetric);
|
||||
assert_eq!(abs(true), abs(false));
|
||||
}
|
||||
@@ -136,10 +136,65 @@ fn tiff_inks(bytes: &[u8]) -> Option<Inks> {
|
||||
Inks::new(w, h, data)
|
||||
}
|
||||
|
||||
/// A CMYK TIFF with an alpha channel (5 samples) as RGBA pixels, each colour converted by `rgb`
|
||||
/// (ink amounts 0..1 → sRGB 0..1) and associated (premultiplied) alpha divided back out; `None`
|
||||
/// for other images, planar ones and ones larger than [`MAX_CMYK_PIXELS`]. The image decoder
|
||||
/// doesn't read these at all; the inks can't be kept with the transparency, so they show as RGB.
|
||||
pub fn cmyka_tiff_rgba(bytes: &[u8], rgb: impl Fn([f32; 4]) -> [f32; 3]) -> Option<image::RgbaImage> {
|
||||
let (kind, mut d) = tiff(bytes)?;
|
||||
let (w, h) = d.dimensions().ok()?;
|
||||
let planar = d.find_tag_unsigned::<u16>(tiff::tags::Tag::PlanarConfiguration).ok().flatten().is_some_and(|p| p != 1);
|
||||
if !matches!(kind, tiff::ColorType::CMYKA(8 | 16)) || planar {
|
||||
return None;
|
||||
}
|
||||
let n = usize::try_from(pixels(w, h)?).ok()?;
|
||||
// ExtraSamples 1: associated alpha (premultiplied colour); 2 (or none stated): unassociated.
|
||||
let associated = d.find_tag_unsigned_vec::<u16>(tiff::tags::Tag::ExtraSamples).ok().flatten().is_some_and(|v| v.first() == Some(&1));
|
||||
let data: Vec<u8> = match d.read_image().ok()? {
|
||||
tiff::decoder::DecodingResult::U8(v) => v,
|
||||
tiff::decoder::DecodingResult::U16(v) => v.iter().map(|s| (s >> 8) as u8).collect(),
|
||||
_ => return None,
|
||||
};
|
||||
if data.len() != n * 5 {
|
||||
return None;
|
||||
}
|
||||
let mut out = Vec::with_capacity(n * 4);
|
||||
for p in data.as_chunks::<5>().0 {
|
||||
let a = f32::from(p[4]) / 255.0;
|
||||
let ink = |v: u8| {
|
||||
let v = f32::from(v) / 255.0;
|
||||
if associated && a > 0.0 { (v / a).min(1.0) } else { v }
|
||||
};
|
||||
let [r, g, b] = rgb([ink(p[0]), ink(p[1]), ink(p[2]), ink(p[3])]);
|
||||
out.extend([r, g, b].map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8));
|
||||
out.push(p[4]);
|
||||
}
|
||||
image::RgbaImage::from_raw(w, h, out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_cmyk_tiff_with_alpha_reads_as_rgba() {
|
||||
use tiff::encoder::{TiffEncoder, colortype::CMYKA8};
|
||||
// 2 × 1: full cyan opaque, then 100% K at half alpha (premultiplied: K 128, alpha 128).
|
||||
let mut file = Cursor::new(Vec::new());
|
||||
let mut enc = TiffEncoder::new(&mut file).unwrap();
|
||||
let mut img = enc.new_image::<CMYKA8>(2, 1).unwrap();
|
||||
img.encoder().write_tag(tiff::tags::Tag::ExtraSamples, &[1u16][..]).unwrap();
|
||||
img.write_data(&[255, 0, 0, 0, 255, 0, 0, 0, 128, 128]).unwrap();
|
||||
let bytes = file.into_inner();
|
||||
let naive = |[c, m, y, k]: [f32; 4]| [(1.0 - c) * (1.0 - k), (1.0 - m) * (1.0 - k), (1.0 - y) * (1.0 - k)];
|
||||
let px = cmyka_tiff_rgba(&bytes, naive).expect("CMYKA reads");
|
||||
assert_eq!(px.dimensions(), (2, 1));
|
||||
assert_eq!(px.get_pixel(0, 0).0, [0, 255, 255, 255], "cyan, opaque");
|
||||
assert_eq!(px.get_pixel(1, 0).0, [0, 0, 0, 128], "the premultiplied K divided back out: black at half alpha");
|
||||
// Not CMYKA: not this reader's.
|
||||
assert!(cmyka_tiff_rgba(&ImageBlob::cmyk_tiff(&inks()).unwrap().bytes, naive).is_none());
|
||||
}
|
||||
|
||||
fn inks() -> Inks {
|
||||
Inks::new(3, 2, vec![0, 40, 100, 0, 255, 0, 0, 0, 0, 255, 0, 0, 0, 0, 255, 0, 0, 0, 0, 255, 12, 34, 56, 78]).unwrap()
|
||||
}
|
||||
|
||||
@@ -5,7 +5,8 @@
|
||||
//!
|
||||
//! - **Geometry effects** (Distort & Transform, Path, Convert to Shape, Round Corners, Scribble,
|
||||
//! Warp) rewrite a path: [`apply_geometry`] evaluates them in stack order.
|
||||
//! - **Raster effects** (Drop Shadow, Inner/Outer Glow, Feather, Gaussian Blur) are described by
|
||||
//! - **Raster effects** (Drop Shadow, Inner/Outer Glow, Feather, Gaussian Blur, and the
|
||||
//! Photoshop-style filters of [`pixel`]: Radial Blur, Smart Blur, Unsharp Mask) are described by
|
||||
//! [`raster_effects`] and painted by the renderer; [`outset`] says how far they reach beyond
|
||||
//! the geometry.
|
||||
//! - **Stroke geometry** ([`stroke`]): arrowheads, dash patterns and width profiles, shared by the
|
||||
@@ -36,6 +37,7 @@ mod distort;
|
||||
mod group;
|
||||
mod live;
|
||||
mod marks;
|
||||
pub mod pixel;
|
||||
mod raster;
|
||||
mod reshape;
|
||||
pub mod stroke;
|
||||
@@ -61,6 +63,7 @@ pub use group::{
|
||||
};
|
||||
pub use live::{expand_live, expand_live_deep, expanded_live_group, text_outliner};
|
||||
pub use marks::{CROP_MARKS, crop_marks_art, has_crop_marks};
|
||||
pub use pixel::{PIXEL_EFFECTS, PixelFx, PixelSpace};
|
||||
pub use raster::{RasterFx, outset, raster_effects};
|
||||
pub use reshape::{expand_outlined, needs_outline, outline_art, outline_text, reshape};
|
||||
pub use warp::{WarpStyle, warp_point};
|
||||
@@ -118,7 +121,7 @@ fn lengths_of(id: &str) -> Lengths {
|
||||
"distort.transform" => always(&["moveH", "moveV"]),
|
||||
"path.offsetPath" => always(&["offset"]),
|
||||
"path.outlineStroke" => always(&["width"]),
|
||||
"stylize.roundCorners" | "stylize.feather" | "blur.gaussian" => always(&["radius"]),
|
||||
"stylize.roundCorners" | "stylize.feather" | "blur.gaussian" | "blur.smart" | "sharpen.unsharpMask" => always(&["radius"]),
|
||||
"stylize.scribble" => always(&["overlap", "strokeWidth", "spacing", "variation"]),
|
||||
"stylize.dropShadow" => always(&["x", "y", "blur"]),
|
||||
"stylize.innerGlow" | "stylize.outerGlow" => always(&["blur"]),
|
||||
@@ -134,6 +137,7 @@ const SHAPE: &[&str] = &["Effect", "Convert to Shape"];
|
||||
const STYLIZE: &[&str] = &["Effect", "Stylize"];
|
||||
const WARP: &[&str] = &["Effect", "Warp"];
|
||||
const BLUR: &[&str] = &["Effect", "Blur"];
|
||||
const SHARPEN: &[&str] = &["Effect", "Sharpen"];
|
||||
const PATHFINDER: &[&str] = &["Effect", "Pathfinder"];
|
||||
const PLUGINS: &[&str] = &["Effect", "Plug-ins"];
|
||||
const ADJUST: &[&str] = &["Effect", "Color Adjustments"];
|
||||
@@ -265,6 +269,27 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
|
||||
),
|
||||
r("stylize.feather", "Feather…", STYLIZE, "{radius: pt (5)}", json!({"radius": 5.0})),
|
||||
r("blur.gaussian", "Gaussian Blur…", BLUR, "{radius: pt (5)}", json!({"radius": 5.0})),
|
||||
r(
|
||||
"blur.radial",
|
||||
"Radial Blur…",
|
||||
BLUR,
|
||||
"{amount: 1..100 (10; spin: an arc of `amount`°, zoom: the content scaled by up to about ±amount/2 %), method: \"spin\"|\"zoom\" (\"spin\"), quality: \"draft\"|\"good\"|\"best\" (\"good\"; 16, 64 or 256 samples)} blurs around the object's centre",
|
||||
json!({"amount": 10.0, "method": "spin", "quality": "good"}),
|
||||
),
|
||||
r(
|
||||
"blur.smart",
|
||||
"Smart Blur…",
|
||||
BLUR,
|
||||
"{radius: pt 0.1..100 (3), threshold: levels 0.1..100 (25; only colours closer than this blur together, so edges stay sharp), quality: \"low\"|\"medium\"|\"high\" (\"medium\"; 5, 7 or 9 samples across)} (Normal mode)",
|
||||
json!({"radius": 3.0, "threshold": 25.0, "quality": "medium"}),
|
||||
),
|
||||
r(
|
||||
"sharpen.unsharpMask",
|
||||
"Unsharp Mask…",
|
||||
SHARPEN,
|
||||
"{amount: % 1..500 (50), radius: pt 0.1..250 (1; σ of the blur edges are found against), threshold: levels 0..255 (0; smaller differences are left alone)}",
|
||||
json!({"amount": 50.0, "radius": 1.0, "threshold": 0.0}),
|
||||
),
|
||||
];
|
||||
v.extend([
|
||||
g(
|
||||
@@ -428,6 +453,7 @@ pub fn scale_effect(e: &mut Effect, s: f64) {
|
||||
/// Is `id` a raster (painted) effect?
|
||||
pub fn is_raster(id: &str) -> bool {
|
||||
matches!(id, "stylize.dropShadow" | "stylize.innerGlow" | "stylize.outerGlow" | "stylize.feather" | "blur.gaussian")
|
||||
|| PIXEL_EFFECTS.contains(&id)
|
||||
}
|
||||
|
||||
/// Does `id` change geometry? (Crop Marks adds art of its own instead, [`crop_marks_art`]; colour
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
//! Blur › Radial Blur and Smart Blur.
|
||||
|
||||
use vectorcraft_geom::{Affine, Point, Vec2};
|
||||
|
||||
use super::{PixelSpace, Px16, box_blur, to8, to16};
|
||||
|
||||
/// Zoom's total spread, in log scale: `amount` 100 scales the content between 1/√2 and √2.
|
||||
pub(super) fn zoom_extent(amount: f64) -> f64 {
|
||||
(1.0 + amount / 100.0).ln()
|
||||
}
|
||||
|
||||
/// `buf` (`w` × `h`) sampled bilinearly at pixel index position (`x`, `y`) (pixel centres at
|
||||
/// whole coordinates); transparent outside.
|
||||
fn bilinear(buf: &[Px16], w: usize, h: usize, x: f64, y: f64) -> [f32; 4] {
|
||||
if !(x > -1.0 && y > -1.0 && x < w as f64 && y < h as f64) {
|
||||
return [0.0; 4];
|
||||
}
|
||||
let (x0, y0) = (x.floor(), y.floor());
|
||||
let (fx, fy) = ((x - x0) as f32, (y - y0) as f32);
|
||||
let (xi, yi) = (x0 as isize, y0 as isize);
|
||||
let at = |cx: isize, cy: isize| -> [f32; 4] {
|
||||
if cx < 0 || cy < 0 || cx as usize >= w || cy as usize >= h {
|
||||
return [0.0; 4];
|
||||
}
|
||||
buf.get(cy as usize * w + cx as usize).map_or([0.0; 4], |p| p.map(f32::from))
|
||||
};
|
||||
let (a, b, c, d) = (at(xi, yi), at(xi + 1, yi), at(xi, yi + 1), at(xi + 1, yi + 1));
|
||||
let (wa, wb, wc, wd) = ((1.0 - fx) * (1.0 - fy), fx * (1.0 - fy), (1.0 - fx) * fy, fx * fy);
|
||||
std::array::from_fn(|i| a[i] * wa + b[i] * wb + c[i] * wc + d[i] * wd)
|
||||
}
|
||||
|
||||
/// Radial Blur: the average of the content turned (spin) or scaled (zoom) about the centre over
|
||||
/// evenly spaced steps spanning `amount`. Each pass averages the previous result with itself
|
||||
/// turned both ways by half the last step, so `passes` passes average 2^`passes` samples at two
|
||||
/// lookups a pixel each.
|
||||
pub(super) fn radial(px: &mut [[u8; 4]], w: usize, h: usize, space: &PixelSpace, amount: f64, zoom: bool, passes: u32) {
|
||||
// The centre in pixel index coordinates (pixel centres at whole numbers).
|
||||
let c = space.to_doc.inverse() * space.center - Vec2::new(0.5, 0.5);
|
||||
if !(c.x.is_finite() && c.y.is_finite()) {
|
||||
return;
|
||||
}
|
||||
let total = if zoom { zoom_extent(amount) } else { amount.to_radians() };
|
||||
let about = |m: Affine| Affine::translate(c.to_vec2()) * m * Affine::translate(-c.to_vec2());
|
||||
// A pixel's reflection in the view (one axis flipped) only turns the spin the other way,
|
||||
// which a symmetric blur doesn't notice.
|
||||
let step = |d: f64| if zoom { about(Affine::scale(d.exp())) } else { about(Affine::rotate(d)) };
|
||||
let mut cur = to16(px);
|
||||
let mut next = vec![[0u16; 4]; cur.len()];
|
||||
for j in 1..=passes.min(12) {
|
||||
let d = total / f64::powi(2.0, j as i32 + 1);
|
||||
let (fwd, back) = (step(d), step(-d));
|
||||
// Where a pixel's two samples lie moves by a fixed step along a row.
|
||||
let (df, db) = (fwd * Point::new(1.0, 0.0) - fwd * Point::ZERO, back * Point::new(1.0, 0.0) - back * Point::ZERO);
|
||||
for (y, row) in next.chunks_exact_mut(w).enumerate().take(h) {
|
||||
let (mut f, mut b) = (fwd * Point::new(0.0, y as f64), back * Point::new(0.0, y as f64));
|
||||
for out in row.iter_mut() {
|
||||
let (s, t) = (bilinear(&cur, w, h, f.x, f.y), bilinear(&cur, w, h, b.x, b.y));
|
||||
*out = std::array::from_fn(|i| ((s[i] + t[i]) * 0.5).round().clamp(0.0, 65535.0) as u16);
|
||||
(f, b) = (f + df, b + db);
|
||||
}
|
||||
}
|
||||
std::mem::swap(&mut cur, &mut next);
|
||||
}
|
||||
for (p, q) in px.iter_mut().zip(&cur) {
|
||||
*p = q.map(to8);
|
||||
}
|
||||
}
|
||||
|
||||
/// The largest radius (pixels) Smart Blur looks over: farther neighbours are as good as gone.
|
||||
const MAX_SMART: f64 = 4096.0;
|
||||
|
||||
/// Smart Blur (Normal mode): each pixel averaged with itself and the neighbours within `radius`
|
||||
/// pixels whose premultiplied channels all lie within `threshold` levels of its own. Wide radii
|
||||
/// look at `samples` × `samples` neighbours spread over the disc, read from a copy box-blurred
|
||||
/// over the gaps between them so the blur stays smooth (a neighbour counts when both it and its
|
||||
/// blurred surroundings are within the threshold, so at most a fringe under the threshold crosses
|
||||
/// an edge).
|
||||
pub(super) fn smart(px: &mut [[u8; 4]], w: usize, h: usize, radius: f64, threshold: f64, samples: u32) {
|
||||
if radius.is_nan() || radius < 0.5 {
|
||||
return;
|
||||
}
|
||||
let r = radius.min(MAX_SMART);
|
||||
let n = samples.clamp(3, 15) as f64;
|
||||
let k = r.round();
|
||||
let (offsets, prefilter): (Vec<Vec2>, usize) = if 2.0 * k < n {
|
||||
let k = k as i32;
|
||||
((-k..=k).flat_map(|dy| (-k..=k).map(move |dx| Vec2::new(dx as f64, dy as f64))).collect(), 0)
|
||||
} else {
|
||||
let gap = 2.0 * r / (n - 1.0);
|
||||
let grid = (0..n as i32).map(|i| -r + gap * i as f64);
|
||||
(grid.clone().flat_map(|dy| grid.clone().map(move |dx| Vec2::new(dx.round(), dy.round()))).collect(), (gap / 2.0).floor() as usize)
|
||||
};
|
||||
let offsets: Vec<(isize, isize)> =
|
||||
offsets.into_iter().filter(|o| o.hypot() <= r + 0.5 && *o != Vec2::ZERO).map(|o| (o.x as isize, o.y as isize)).collect();
|
||||
let src = to16(px);
|
||||
let blurred;
|
||||
let near: &[Px16] = if prefilter > 0 {
|
||||
let mut b = src.clone();
|
||||
box_blur(&mut b, w, prefilter);
|
||||
blurred = b;
|
||||
&blurred
|
||||
} else {
|
||||
&src
|
||||
};
|
||||
let t = (threshold.clamp(0.0, 255.0) * 257.0) as i32;
|
||||
for (y, (row, out)) in src.chunks_exact(w).zip(px.chunks_exact_mut(w)).enumerate().take(h) {
|
||||
for (x, (c, o)) in row.iter().zip(out.iter_mut()).enumerate() {
|
||||
let mut acc = c.map(u64::from);
|
||||
let mut count = 1u64;
|
||||
for (dx, dy) in &offsets {
|
||||
let (sx, sy) = (x as isize + dx, y as isize + dy);
|
||||
if sx < 0 || sy < 0 || sx as usize >= w || sy as usize >= h {
|
||||
continue;
|
||||
}
|
||||
let i = sy as usize * w + sx as usize;
|
||||
let (Some(s), Some(own)) = (near.get(i), src.get(i)) else { continue };
|
||||
// The neighbour itself and its surroundings both close enough: edges stay sharp.
|
||||
let close = |p: &Px16| p.iter().zip(c).all(|(a, b)| (*a as i32 - *b as i32).abs() <= t);
|
||||
if close(own) && close(s) {
|
||||
for (a, v) in acc.iter_mut().zip(s) {
|
||||
*a += *v as u64;
|
||||
}
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
*o = acc.map(|a| to8(((a + count / 2) / count).min(65535) as u16));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,297 @@
|
||||
//! Photoshop-style raster effects (Effect › Blur › Radial Blur and Smart Blur, Sharpen › Unsharp
|
||||
//! Mask): filters over the pixels of an object rendered alone, premultiplied RGBA8.
|
||||
//!
|
||||
//! - Every distance is in document units (points) and becomes pixels through the raster's
|
||||
//! [`PixelSpace::px`], so an effect looks the same at any zoom and at any Document Raster Effects
|
||||
//! Settings resolution (as Gaussian Blur's radius does).
|
||||
//! - The work per pixel is bounded whatever the parameters: blurs are box approximations whose
|
||||
//! cost doesn't grow with the radius, and sample counts come from the effect's quality.
|
||||
//! - Beyond the raster's edges is transparency.
|
||||
|
||||
mod blur;
|
||||
mod sharpen;
|
||||
|
||||
use serde_json::Value;
|
||||
use vectorcraft_geom::{Affine, Point, Rect};
|
||||
|
||||
use crate::util::{num, text};
|
||||
|
||||
/// The Photoshop-style effect ids (all raster effects, see [`crate::is_raster`]).
|
||||
pub const PIXEL_EFFECTS: [&str; 3] = ["blur.radial", "blur.smart", "sharpen.unsharpMask"];
|
||||
|
||||
/// A Photoshop-style raster effect with its parameters read and clamped to their ranges. Lengths
|
||||
/// are in document units.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum PixelFx {
|
||||
/// Blur › Radial Blur around the object's centre: along arcs (spin, an arc of `amount`°) or
|
||||
/// along rays (zoom, the content scaled by up to about ±`amount`/2 %), averaging 2^`passes` samples.
|
||||
RadialBlur { amount: f64, zoom: bool, passes: u32 },
|
||||
/// Blur › Smart Blur (Normal mode): each pixel averaged with the neighbours within `radius`
|
||||
/// whose colour differs from its own by no more than `threshold` levels, over a grid of
|
||||
/// `samples` × `samples` neighbours at most.
|
||||
SmartBlur { radius: f64, threshold: f64, samples: u32 },
|
||||
/// Sharpen › Unsharp Mask: colours pushed away from a Gaussian blur of σ = `radius` by `amount`
|
||||
/// (1 = 100 %), where they differ from it by at least `threshold` levels.
|
||||
UnsharpMask { amount: f64, radius: f64, threshold: f64 },
|
||||
}
|
||||
|
||||
/// Where a raster's pixels lie in the document.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct PixelSpace {
|
||||
/// Pixel coordinates (x right, y down, (0, 0) the top-left corner of the first pixel) →
|
||||
/// document coordinates.
|
||||
pub to_doc: Affine,
|
||||
/// The size of a pixel in document units.
|
||||
pub px: f64,
|
||||
/// The object's centre (document coordinates): where Radial Blur blurs around.
|
||||
pub center: Point,
|
||||
}
|
||||
|
||||
/// Effect `id`'s parameters `p` (defaults merged in) as a [`PixelFx`]; `None` for other effects.
|
||||
pub(crate) fn parse(id: &str, p: &Value) -> Option<PixelFx> {
|
||||
let quality = |levels: [(&str, u32); 3], default: u32| {
|
||||
let q = text(p, "quality", "");
|
||||
levels.iter().find(|(name, _)| name.eq_ignore_ascii_case(q)).map_or(default, |(_, v)| *v)
|
||||
};
|
||||
Some(match id {
|
||||
"blur.radial" => PixelFx::RadialBlur {
|
||||
amount: num(p, "amount", 10.0).clamp(1.0, 100.0),
|
||||
zoom: text(p, "method", "spin").eq_ignore_ascii_case("zoom"),
|
||||
passes: quality([("draft", 4), ("good", 6), ("best", 8)], 6),
|
||||
},
|
||||
"blur.smart" => PixelFx::SmartBlur {
|
||||
radius: num(p, "radius", 3.0).clamp(0.1, 100.0),
|
||||
threshold: num(p, "threshold", 25.0).clamp(0.1, 100.0),
|
||||
samples: quality([("low", 5), ("medium", 7), ("high", 9)], 7),
|
||||
},
|
||||
"sharpen.unsharpMask" => PixelFx::UnsharpMask {
|
||||
amount: num(p, "amount", 50.0).clamp(1.0, 500.0) / 100.0,
|
||||
radius: num(p, "radius", 1.0).clamp(0.1, 250.0),
|
||||
threshold: num(p, "threshold", 0.0).clamp(0.0, 255.0),
|
||||
},
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
impl PixelFx {
|
||||
/// How far beyond `bounds` (the content's, document units) the effect can paint.
|
||||
pub fn outset(&self, bounds: Rect) -> f64 {
|
||||
// From the centre to the farthest corner, and to the nearest side.
|
||||
let far = 0.5 * bounds.width().hypot(bounds.height());
|
||||
let near = 0.5 * bounds.width().min(bounds.height());
|
||||
match *self {
|
||||
// A rotated corner reaches the circle through the corners.
|
||||
PixelFx::RadialBlur { zoom: false, .. } => (far - near).max(0.0),
|
||||
PixelFx::RadialBlur { amount, zoom: true, .. } => far * (blur::zoom_extent(amount).exp() - 1.0),
|
||||
PixelFx::SmartBlur { radius, .. } => radius,
|
||||
PixelFx::UnsharpMask { .. } => 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// How far (document units) from a pixel the content that decides it lies; `None` when that
|
||||
/// is anywhere in the object (Radial Blur).
|
||||
pub fn reach(&self) -> Option<f64> {
|
||||
match *self {
|
||||
PixelFx::RadialBlur { .. } => None,
|
||||
PixelFx::SmartBlur { radius, .. } => Some(radius),
|
||||
PixelFx::UnsharpMask { radius, .. } => Some(3.0 * radius),
|
||||
}
|
||||
}
|
||||
|
||||
/// Run the effect on `data`, `w` × `h` premultiplied RGBA8 pixels lying in the document as
|
||||
/// `space` says. Does nothing when the sizes don't match.
|
||||
pub fn apply(&self, data: &mut [u8], w: usize, h: usize, space: &PixelSpace) {
|
||||
let Some(px) = pixels(data, w, h) else { return };
|
||||
let to_px = |len: f64| len / space.px.max(1e-9);
|
||||
match *self {
|
||||
PixelFx::RadialBlur { amount, zoom, passes } => blur::radial(px, w, h, space, amount, zoom, passes),
|
||||
PixelFx::SmartBlur { radius, threshold, samples } => blur::smart(px, w, h, to_px(radius), threshold, samples),
|
||||
PixelFx::UnsharpMask { amount, radius, threshold } => sharpen::unsharp(px, w, h, amount, to_px(radius), threshold),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `data` as `w` × `h` RGBA pixels, `None` when it isn't that size (or is empty).
|
||||
fn pixels(data: &mut [u8], w: usize, h: usize) -> Option<&mut [[u8; 4]]> {
|
||||
let (px, rest) = data.as_chunks_mut::<4>();
|
||||
(w > 0 && h > 0 && rest.is_empty() && w.checked_mul(h) == Some(px.len())).then_some(px)
|
||||
}
|
||||
|
||||
/// The largest box radius the blurs use: wider boxes look the same on any raster we make.
|
||||
const MAX_BOX: usize = 1 << 17;
|
||||
|
||||
/// Radii of three box blurs approximating a Gaussian of `sigma` pixels.
|
||||
pub fn gauss_boxes(sigma: f64) -> [usize; 3] {
|
||||
let sigma = if sigma.is_finite() { sigma.clamp(0.0, MAX_BOX as f64 / 2.0) } else { 0.0 };
|
||||
let n = 3.0;
|
||||
let w_ideal = (12.0 * sigma * sigma / n + 1.0).sqrt();
|
||||
let mut wl = w_ideal.floor() as i64;
|
||||
if wl % 2 == 0 {
|
||||
wl -= 1;
|
||||
}
|
||||
let wu = wl + 2;
|
||||
let m_ideal = (12.0 * sigma * sigma - n * (wl * wl) as f64 - 4.0 * n * wl as f64 - 3.0 * n) / (-4.0 * wl as f64 - 4.0);
|
||||
let m = m_ideal.round() as i64;
|
||||
let r = |i: i64| ((((if i < m { wl } else { wu }) - 1) / 2).max(0) as usize).min(MAX_BOX);
|
||||
[r(0), r(1), r(2)]
|
||||
}
|
||||
|
||||
/// One horizontal box blur of radius `r` over the rows of `w` values of a plane (running sum,
|
||||
/// zero past the ends).
|
||||
fn box_plane(src: &[f32], dst: &mut [f32], w: usize, r: usize) {
|
||||
if r == 0 {
|
||||
dst.copy_from_slice(src);
|
||||
return;
|
||||
}
|
||||
let norm = 1.0 / (2 * r + 1) as f32;
|
||||
for (row, out) in src.chunks_exact(w).zip(dst.chunks_exact_mut(w)) {
|
||||
let mut acc: f32 = row.iter().take(r + 1).sum();
|
||||
for (x, o) in out.iter_mut().enumerate() {
|
||||
*o = acc * norm;
|
||||
if let Some(v) = row.get(x + r + 1) {
|
||||
acc += v;
|
||||
}
|
||||
if let Some(v) = x.checked_sub(r).and_then(|i| row.get(i)) {
|
||||
acc -= v;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn transpose<T: Copy>(src: &[T], dst: &mut [T], w: usize, h: usize) {
|
||||
for (y, row) in src.chunks_exact(w).enumerate().take(h) {
|
||||
for (x, v) in row.iter().enumerate() {
|
||||
if let Some(d) = dst.get_mut(x * h + y) {
|
||||
*d = *v;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Gaussian-blur a `w` × `h` plane of values in place (three box passes per axis, zero past the
|
||||
/// edges). Does nothing when the sizes don't match.
|
||||
pub fn blur_plane(a: &mut Vec<f32>, w: usize, h: usize, sigma: f64) {
|
||||
if sigma < 0.2 || w == 0 || h == 0 || w.checked_mul(h) != Some(a.len()) {
|
||||
return;
|
||||
}
|
||||
let boxes = gauss_boxes(sigma);
|
||||
let mut tmp = vec![0.0; a.len()];
|
||||
for (len, other) in [(w, h), (h, w)] {
|
||||
for r in boxes {
|
||||
box_plane(a, &mut tmp, len, r);
|
||||
std::mem::swap(a, &mut tmp);
|
||||
}
|
||||
transpose(a, &mut tmp, len, other);
|
||||
std::mem::swap(a, &mut tmp);
|
||||
}
|
||||
}
|
||||
|
||||
/// Premultiplied RGBA at 16 bits (×257): blurs and averages that keep their tones.
|
||||
pub(super) type Px16 = [u16; 4];
|
||||
|
||||
pub(super) fn to16(px: &[[u8; 4]]) -> Vec<Px16> {
|
||||
px.iter().map(|p| p.map(|v| v as u16 * 257)).collect()
|
||||
}
|
||||
|
||||
pub(super) fn to8(v: u16) -> u8 {
|
||||
((v as u32 + 128) / 257).min(255) as u8
|
||||
}
|
||||
|
||||
fn add(acc: &mut [u64; 4], p: &Px16) {
|
||||
for (a, v) in acc.iter_mut().zip(p) {
|
||||
*a += *v as u64;
|
||||
}
|
||||
}
|
||||
|
||||
fn sub(acc: &mut [u64; 4], p: &Px16) {
|
||||
for (a, v) in acc.iter_mut().zip(p) {
|
||||
*a = a.saturating_sub(*v as u64);
|
||||
}
|
||||
}
|
||||
|
||||
fn mean(acc: &[u64; 4], n: u64) -> Px16 {
|
||||
acc.map(|a| ((a + n / 2) / n.max(1)).min(65535) as u16)
|
||||
}
|
||||
|
||||
/// One box blur of radius `r` along the rows of `w` pixels (transparent past the ends).
|
||||
fn box_rows(src: &[Px16], dst: &mut [Px16], w: usize, r: usize) {
|
||||
let n = 2 * r as u64 + 1;
|
||||
for (row, out) in src.chunks_exact(w).zip(dst.chunks_exact_mut(w)) {
|
||||
let mut acc = [0u64; 4];
|
||||
row.iter().take(r + 1).for_each(|p| add(&mut acc, p));
|
||||
for (x, o) in out.iter_mut().enumerate() {
|
||||
*o = mean(&acc, n);
|
||||
if let Some(p) = row.get(x + r + 1) {
|
||||
add(&mut acc, p);
|
||||
}
|
||||
if let Some(p) = x.checked_sub(r).and_then(|i| row.get(i)) {
|
||||
sub(&mut acc, p);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One box blur of radius `r` down the columns of `w`-wide rows (transparent past the ends), row
|
||||
/// by row with a running sum per column.
|
||||
fn box_cols(src: &[Px16], dst: &mut [Px16], w: usize, r: usize) {
|
||||
let n = 2 * r as u64 + 1;
|
||||
let rows: Vec<&[Px16]> = src.chunks_exact(w).collect();
|
||||
let mut acc = vec![[0u64; 4]; w];
|
||||
let add_row = |acc: &mut [[u64; 4]], row: &[Px16]| acc.iter_mut().zip(row).for_each(|(a, p)| add(a, p));
|
||||
rows.iter().take(r + 1).for_each(|row| add_row(&mut acc, row));
|
||||
for (y, out) in dst.chunks_exact_mut(w).enumerate() {
|
||||
for (o, a) in out.iter_mut().zip(&acc) {
|
||||
*o = mean(a, n);
|
||||
}
|
||||
if let Some(row) = rows.get(y + r + 1) {
|
||||
add_row(&mut acc, row);
|
||||
}
|
||||
if let Some(row) = y.checked_sub(r).and_then(|i| rows.get(i)) {
|
||||
acc.iter_mut().zip(*row).for_each(|(a, p)| sub(a, p));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Box-blur `w`-wide rows of pixels in place with radius `r` along both axes.
|
||||
pub(super) fn box_blur(px: &mut [Px16], w: usize, r: usize) {
|
||||
if r == 0 || w == 0 {
|
||||
return;
|
||||
}
|
||||
let mut tmp = vec![[0u16; 4]; px.len()];
|
||||
box_rows(px, &mut tmp, w, r);
|
||||
box_cols(&tmp, px, w, r);
|
||||
}
|
||||
|
||||
/// Gaussian-blur `w`-wide rows of premultiplied pixels in place (σ = `sigma` pixels, three box
|
||||
/// passes per axis, transparent past the edges).
|
||||
pub(super) fn gaussian(px: &mut [Px16], w: usize, sigma: f64) {
|
||||
if sigma < 0.2 || w == 0 {
|
||||
return;
|
||||
}
|
||||
let mut tmp = vec![[0u16; 4]; px.len()];
|
||||
for r in gauss_boxes(sigma) {
|
||||
box_rows(px, &mut tmp, w, r);
|
||||
px.copy_from_slice(&tmp);
|
||||
}
|
||||
for r in gauss_boxes(sigma) {
|
||||
box_cols(px, &mut tmp, w, r);
|
||||
px.copy_from_slice(&tmp);
|
||||
}
|
||||
}
|
||||
|
||||
/// Gaussian-blur `data`, `w` × `h` premultiplied RGBA8 pixels, in place (σ = `sigma` pixels). Does
|
||||
/// nothing when the sizes don't match.
|
||||
pub fn gaussian_rgba(data: &mut [u8], w: usize, h: usize, sigma: f64) {
|
||||
if let Some(px) = pixels(data, w, h)
|
||||
&& sigma >= 0.2
|
||||
{
|
||||
let mut wide = to16(px);
|
||||
gaussian(&mut wide, w, sigma);
|
||||
for (p, q) in px.iter_mut().zip(&wide) {
|
||||
*p = q.map(to8);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,31 @@
|
||||
//! Sharpen › Unsharp Mask.
|
||||
|
||||
use super::{gaussian, to16};
|
||||
|
||||
/// Unsharp Mask: each colour channel pushed away from a Gaussian blur of the pixels (σ = `sigma`
|
||||
/// pixels) by `amount` times their difference, where that difference reaches `threshold` levels.
|
||||
/// The blur is premultiplied, so edges against transparency don't darken; coverage stays as it is.
|
||||
pub(super) fn unsharp(px: &mut [[u8; 4]], w: usize, h: usize, amount: f64, sigma: f64, threshold: f64) {
|
||||
if sigma.is_nan() || sigma < 0.2 || amount.is_nan() || amount <= 0.0 || h == 0 {
|
||||
return;
|
||||
}
|
||||
let mut blurred = to16(px);
|
||||
gaussian(&mut blurred, w, sigma);
|
||||
let (amount, threshold) = (amount as f32, threshold as f32);
|
||||
for (p, b) in px.iter_mut().zip(&blurred) {
|
||||
let a = p[3] as f32;
|
||||
if a == 0.0 {
|
||||
continue;
|
||||
}
|
||||
for i in 0..3 {
|
||||
let own = p[i] as f32 * 255.0 / a;
|
||||
let around = if b[3] > 0 { b[i] as f32 * 255.0 / b[3] as f32 } else { own };
|
||||
let diff = own - around;
|
||||
if diff.abs() < threshold || diff == 0.0 {
|
||||
continue;
|
||||
}
|
||||
let v = (own + amount * diff).clamp(0.0, 255.0);
|
||||
p[i] = (v * a / 255.0).round().clamp(0.0, 255.0) as u8;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
use serde_json::json;
|
||||
use vectorcraft_doc::Effect;
|
||||
use vectorcraft_geom::{Affine, Point, Rect};
|
||||
|
||||
use super::*;
|
||||
use crate::{RasterFx, raster_effects};
|
||||
|
||||
/// A `w` × `h` raster whose pixels are document points (origin top-left).
|
||||
fn space(w: usize, h: usize) -> PixelSpace {
|
||||
PixelSpace { to_doc: Affine::IDENTITY, px: 1.0, center: Point::new(w as f64 / 2.0, h as f64 / 2.0) }
|
||||
}
|
||||
|
||||
fn image(w: usize, h: usize, f: impl Fn(usize, usize) -> [u8; 4]) -> Vec<u8> {
|
||||
let mut out = Vec::with_capacity(w * h * 4);
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
out.extend(f(x, y));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn at(d: &[u8], w: usize, x: usize, y: usize) -> [u8; 4] {
|
||||
let i = (y * w + x) * 4;
|
||||
[d[i], d[i + 1], d[i + 2], d[i + 3]]
|
||||
}
|
||||
|
||||
fn fx(id: &str, p: serde_json::Value) -> PixelFx {
|
||||
let e = Effect { id: id.into(), params: p, visible: true };
|
||||
match raster_effects(&[e]).first() {
|
||||
Some(RasterFx::Pixel(p)) => *p,
|
||||
other => panic!("{id}: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn grey(v: u8) -> [u8; 4] {
|
||||
[v, v, v, 255]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn params_take_defaults_and_stay_in_range() {
|
||||
assert_eq!(fx("blur.radial", json!({})), PixelFx::RadialBlur { amount: 10.0, zoom: false, passes: 6 });
|
||||
assert_eq!(
|
||||
fx("blur.radial", json!({"amount": 1e308, "method": "ZOOM", "quality": "best"})),
|
||||
PixelFx::RadialBlur { amount: 100.0, zoom: true, passes: 8 }
|
||||
);
|
||||
assert_eq!(fx("blur.radial", json!({"amount": -5, "quality": "nonsense"})), PixelFx::RadialBlur { amount: 1.0, zoom: false, passes: 6 });
|
||||
assert_eq!(fx("blur.smart", json!({})), PixelFx::SmartBlur { radius: 3.0, threshold: 25.0, samples: 7 });
|
||||
assert_eq!(
|
||||
fx("blur.smart", json!({"radius": "1e999", "threshold": -1, "quality": "low"})),
|
||||
PixelFx::SmartBlur { radius: 3.0, threshold: 0.1, samples: 5 }
|
||||
);
|
||||
assert_eq!(fx("sharpen.unsharpMask", json!({})), PixelFx::UnsharpMask { amount: 0.5, radius: 1.0, threshold: 0.0 });
|
||||
assert_eq!(
|
||||
fx("sharpen.unsharpMask", json!({"amount": 1e9, "radius": 0, "threshold": 1e9})),
|
||||
PixelFx::UnsharpMask { amount: 5.0, radius: 0.1, threshold: 255.0 }
|
||||
);
|
||||
for id in PIXEL_EFFECTS {
|
||||
assert!(crate::is_raster(id) && crate::effect_info(id).is_some_and(|e| e.raster), "{id}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outsets_follow_the_object() {
|
||||
let b = Rect::new(0.0, 0.0, 100.0, 50.0);
|
||||
let spin = fx("blur.radial", json!({}));
|
||||
let far = 0.5 * 100f64.hypot(50.0);
|
||||
assert!((spin.outset(b) - (far - 25.0)).abs() < 1e-9);
|
||||
assert!(fx("blur.radial", json!({"method": "zoom", "amount": 100})).outset(b) > 0.4 * far);
|
||||
assert_eq!(fx("blur.smart", json!({"radius": 4})).outset(b), 4.0);
|
||||
assert_eq!(fx("sharpen.unsharpMask", json!({})).outset(b), 0.0);
|
||||
assert_eq!(spin.reach(), None);
|
||||
assert_eq!(fx("sharpen.unsharpMask", json!({"radius": 2})).reach(), Some(6.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrong_sizes_and_empty_rasters_are_left_alone() {
|
||||
for id in PIXEL_EFFECTS {
|
||||
let f = fx(id, json!({}));
|
||||
let mut d = vec![200u8; 4 * 10];
|
||||
f.apply(&mut d, 3, 3, &space(3, 3));
|
||||
f.apply(&mut d, 0, 10, &space(0, 10));
|
||||
f.apply(&mut [], 0, 0, &space(0, 0));
|
||||
assert!(d.iter().all(|v| *v == 200), "{id}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extreme_parameters_finish() {
|
||||
let (w, h) = (40, 30);
|
||||
let src = image(w, h, |x, y| if (x / 5 + y / 5) % 2 == 0 { grey(250) } else { [0, 0, 0, 0] });
|
||||
let tiny = PixelSpace { px: 1e-9, ..space(w, h) };
|
||||
let huge = PixelSpace { px: 1e9, center: Point::new(f64::MAX, -1e300), ..space(w, h) };
|
||||
for id in PIXEL_EFFECTS {
|
||||
for p in [json!({"amount": 1e308, "radius": 1e308, "threshold": 1e308, "quality": "best"}), json!({"amount": 0, "radius": 0})] {
|
||||
for s in [tiny, huge, space(w, h)] {
|
||||
let mut d = src.clone();
|
||||
fx(id, p.clone()).apply(&mut d, w, h, &s);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_effect_is_deterministic() {
|
||||
let (w, h) = (32, 24);
|
||||
let src = image(w, h, |x, y| {
|
||||
let a = if x > 4 { 255 } else { 128 };
|
||||
[((x * 8) as u8).min(a), ((y * 10) as u8).min(a), ((x * y % 256) as u8).min(a), a]
|
||||
});
|
||||
for id in PIXEL_EFFECTS {
|
||||
let f = fx(id, json!({"amount": 40, "radius": 3, "threshold": 40}));
|
||||
let (mut a, mut b) = (src.clone(), src.clone());
|
||||
f.apply(&mut a, w, h, &space(w, h));
|
||||
f.apply(&mut b, w, h, &space(w, h));
|
||||
assert_eq!(a, b, "{id}");
|
||||
assert_ne!(a, src, "{id} changes the image");
|
||||
// Premultiplied stays premultiplied.
|
||||
assert!(a.chunks_exact(4).all(|p| p[0] <= p[3] && p[1] <= p[3] && p[2] <= p[3]), "{id}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spin_blur_smears_along_arcs_and_keeps_the_centre() {
|
||||
let (w, h) = (41, 41);
|
||||
// A white dot 12 px right of the centre (20.5, 20.5), and one on the centre.
|
||||
let src = image(w, h, |x, y| if (x == 32 || x == 20) && y == 20 { grey(255) } else { [0, 0, 0, 0] });
|
||||
let mut d = src.clone();
|
||||
fx("blur.radial", json!({"amount": 60, "quality": "best"})).apply(&mut d, w, h, &space(w, h));
|
||||
// 60° of arc around the centre: up to 30° either way, 12 px out: (20.5 + 12 cos 20°, 20.5 ± 12 sin 20°).
|
||||
assert!(at(&d, w, 31, 16)[3] > 0 && at(&d, w, 31, 24)[3] > 0, "the dot spreads along its circle");
|
||||
assert_eq!(at(&d, w, 32, 10)[3], 0, "not beyond the arc");
|
||||
assert_eq!(at(&d, w, 26, 20)[3], 0, "not towards the centre");
|
||||
assert!(at(&d, w, 20, 20)[3] > 100, "the centre barely moves: {:?}", at(&d, w, 20, 20));
|
||||
// Zoom smears along the ray instead.
|
||||
let mut z = src.clone();
|
||||
fx("blur.radial", json!({"amount": 60, "method": "zoom", "quality": "best"})).apply(&mut z, w, h, &space(w, h));
|
||||
assert!(at(&z, w, 35, 20)[3] > 0 && at(&z, w, 29, 20)[3] > 0, "the dot streaks along the ray");
|
||||
assert_eq!(at(&z, w, 32, 16)[3], 0, "not across it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn smart_blur_smooths_noise_and_keeps_edges() {
|
||||
let (w, h) = (40, 20);
|
||||
// Left: grey 100 with ±6 noise; right: white.
|
||||
let src = image(w, h, |x, y| if x < 20 { grey(if (x + y) % 2 == 0 { 94 } else { 106 }) } else { grey(255) });
|
||||
let mut d = src.clone();
|
||||
fx("blur.smart", json!({"radius": 3, "threshold": 25})).apply(&mut d, w, h, &space(w, h));
|
||||
let v = at(&d, w, 8, 10)[0];
|
||||
assert!((97..=103).contains(&v), "noise smoothed: {v}");
|
||||
assert!(at(&d, w, 19, 10)[0] < 120, "the edge's dark side doesn't take the white");
|
||||
assert_eq!(at(&d, w, 20, 10)[0], 255, "the edge's white side stays white");
|
||||
// A threshold above the step blurs across it.
|
||||
let mut all = src.clone();
|
||||
fx("blur.smart", json!({"radius": 3, "threshold": 100})).apply(&mut all, w, h, &space(w, h));
|
||||
assert_eq!(at(&all, w, 20, 10)[0], 255, "a 155-level step is still past 100");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsharp_mask_overshoots_at_edges() {
|
||||
let (w, h) = (40, 10);
|
||||
let src = image(w, h, |x, _| grey(if x < 20 { 100 } else { 150 }));
|
||||
let mut d = src.clone();
|
||||
fx("sharpen.unsharpMask", json!({"amount": 100, "radius": 2})).apply(&mut d, w, h, &space(w, h));
|
||||
assert!(at(&d, w, 19, 5)[0] < 95, "dark side darker: {:?}", at(&d, w, 19, 5));
|
||||
assert!(at(&d, w, 20, 5)[0] > 155, "light side lighter: {:?}", at(&d, w, 20, 5));
|
||||
assert_eq!(at(&d, w, 5, 5), grey(100), "flat areas stay");
|
||||
assert_eq!(at(&d, w, 35, 5), grey(150));
|
||||
// Differences under the threshold are left alone.
|
||||
let mut t = src.clone();
|
||||
fx("sharpen.unsharpMask", json!({"amount": 100, "radius": 2, "threshold": 60})).apply(&mut t, w, h, &space(w, h));
|
||||
assert_eq!(t, src);
|
||||
// Coverage stays, and a shape's edge against transparency doesn't darken.
|
||||
let shape = image(w, h, |x, _| if x < 20 { [200, 0, 0, 255] } else { [0, 0, 0, 0] });
|
||||
let mut s = shape.clone();
|
||||
fx("sharpen.unsharpMask", json!({"amount": 300, "radius": 3})).apply(&mut s, w, h, &space(w, h));
|
||||
assert_eq!(s, shape);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lengths_are_document_units() {
|
||||
// The same art at twice the resolution, sharpened with the same radius in points: the
|
||||
// overshoot spans twice the pixels, the same distance.
|
||||
let edge = |scale: usize| image(40 * scale, 4, move |x, _| grey(if x < 20 * scale { 100 } else { 150 }));
|
||||
let run = |scale: usize| {
|
||||
let mut d = edge(scale);
|
||||
let s = PixelSpace { to_doc: Affine::scale(1.0 / scale as f64), px: 1.0 / scale as f64, center: Point::ZERO };
|
||||
fx("sharpen.unsharpMask", json!({"amount": 100, "radius": 2})).apply(&mut d, 40 * scale, 4, &s);
|
||||
(0..40 * scale).filter(|x| at(&d, 40 * scale, *x, 2)[0] < 99).count()
|
||||
};
|
||||
let (one, two) = (run(1), run(2));
|
||||
assert!(one > 1 && (two as f64 / one as f64 - 2.0).abs() < 0.5, "{one} px at 1×, {two} px at 2×");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gaussian_and_plane_blurs_keep_their_mass() {
|
||||
let (w, h) = (30, 30);
|
||||
let mut d = image(w, h, |x, y| if (10..20).contains(&x) && (10..20).contains(&y) { grey(255) } else { [0, 0, 0, 0] });
|
||||
let before: u32 = d.chunks_exact(4).map(|p| p[3] as u32).sum();
|
||||
gaussian_rgba(&mut d, w, h, 2.0);
|
||||
let after: u32 = d.chunks_exact(4).map(|p| p[3] as u32).sum();
|
||||
assert!((before as f64 - after as f64).abs() / (before as f64) < 0.02, "{before} → {after}");
|
||||
assert!(at(&d, w, 9, 15)[3] > 0 && at(&d, w, 10, 15)[3] < 255);
|
||||
let mut plane: Vec<f32> = (0..w * h).map(|i| if i == 15 * w + 15 { 100.0 } else { 0.0 }).collect();
|
||||
blur_plane(&mut plane, w, h, 2.0);
|
||||
assert!((plane.iter().sum::<f32>() - 100.0).abs() < 0.5 && plane[15 * w + 13] > 0.0 && plane[13 * w + 15] > 0.0);
|
||||
}
|
||||
|
||||
/// Timings on a 2000 × 2000 raster (`cargo test -p vectorcraft-effects --release -- --ignored
|
||||
/// --nocapture pixel_timings`).
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn pixel_timings() {
|
||||
let (w, h) = (2000, 2000);
|
||||
let src = image(w, h, |x, y| [(x % 256) as u8, (y % 256) as u8, ((x ^ y) % 256) as u8, 255]);
|
||||
let s = PixelSpace { to_doc: Affine::IDENTITY, px: 1.0, center: Point::new(1000.0, 1000.0) };
|
||||
let cases = [
|
||||
("blur.radial", json!({"quality": "draft"})),
|
||||
("blur.radial", json!({"quality": "good"})),
|
||||
("blur.radial", json!({"quality": "best", "method": "zoom"})),
|
||||
("blur.smart", json!({"quality": "low"})),
|
||||
("blur.smart", json!({"quality": "high", "radius": 30})),
|
||||
("sharpen.unsharpMask", json!({"radius": 20})),
|
||||
];
|
||||
for (id, p) in cases {
|
||||
let mut d = src.clone();
|
||||
let t = std::time::Instant::now();
|
||||
fx(id, p.clone()).apply(&mut d, w, h, &s);
|
||||
println!("{id} {p}: {:?}", t.elapsed());
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,10 @@ use serde_json::Value;
|
||||
use vectorcraft_doc::Effect;
|
||||
use vectorcraft_doc::color::{BlendMode, Color};
|
||||
|
||||
use vectorcraft_geom::Rect;
|
||||
|
||||
use crate::merged_params;
|
||||
use crate::pixel::{self, PixelFx};
|
||||
use crate::util::*;
|
||||
|
||||
/// A painted effect, in document units. `blur` is Illustrator's blur distance; the renderer uses
|
||||
@@ -40,6 +43,8 @@ pub enum RasterFx {
|
||||
GaussianBlur {
|
||||
radius: f64,
|
||||
},
|
||||
/// A Photoshop-style filter over the object's pixels (Radial Blur, Unsharp Mask…).
|
||||
Pixel(PixelFx),
|
||||
}
|
||||
|
||||
impl RasterFx {
|
||||
@@ -47,13 +52,15 @@ impl RasterFx {
|
||||
pub fn is_below(&self) -> bool {
|
||||
matches!(self, RasterFx::DropShadow { .. } | RasterFx::OuterGlow { .. })
|
||||
}
|
||||
/// How far this effect reaches beyond the geometry.
|
||||
pub fn outset(&self) -> f64 {
|
||||
/// How far this effect reaches beyond `bounds`, what it paints around (Radial Blur reaches
|
||||
/// further around larger objects).
|
||||
pub fn outset(&self, bounds: Rect) -> f64 {
|
||||
match self {
|
||||
RasterFx::DropShadow { dx, dy, blur, .. } => dx.abs().max(dy.abs()) + 1.5 * blur,
|
||||
RasterFx::OuterGlow { blur, .. } => 1.5 * blur,
|
||||
RasterFx::InnerGlow { .. } | RasterFx::Feather { .. } => 0.0,
|
||||
RasterFx::GaussianBlur { radius } => 1.5 * radius,
|
||||
RasterFx::Pixel(p) => p.outset(bounds),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -113,14 +120,14 @@ pub fn raster_effects(effects: &[Effect]) -> Vec<RasterFx> {
|
||||
},
|
||||
"stylize.feather" => RasterFx::Feather { radius: num(&p, "radius", 5.0).clamp(0.0, 1000.0) },
|
||||
"blur.gaussian" => RasterFx::GaussianBlur { radius: num(&p, "radius", 5.0).clamp(0.0, 1000.0) },
|
||||
_ => return None,
|
||||
id => RasterFx::Pixel(pixel::parse(id, &p)?),
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// How far the visible raster effects of `effects` paint beyond the (effected) geometry, in
|
||||
/// document units. Geometry effects are accounted for by evaluating them.
|
||||
pub fn outset(effects: &[Effect]) -> f64 {
|
||||
raster_effects(effects).iter().map(RasterFx::outset).fold(0.0, f64::max)
|
||||
/// How far the visible raster effects of `effects` paint beyond `bounds`, the (effected)
|
||||
/// geometry's, in document units. Geometry effects are accounted for by evaluating them.
|
||||
pub fn outset(effects: &[Effect], bounds: Rect) -> f64 {
|
||||
raster_effects(effects).iter().map(|fx| fx.outset(bounds)).fold(0.0, f64::max)
|
||||
}
|
||||
@@ -301,8 +301,8 @@ fn raster_effects_parse_and_outset() {
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
assert!(matches!(r[2], RasterFx::InnerGlow { center: true, .. }));
|
||||
assert!(close(outset(&list), 10.0 + 9.0, 1e-9));
|
||||
assert_eq!(outset(&[]), 0.0);
|
||||
assert!(close(outset(&list, vectorcraft_geom::Rect::ZERO), 10.0 + 9.0, 1e-9));
|
||||
assert_eq!(outset(&[], vectorcraft_geom::Rect::ZERO), 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -170,8 +170,10 @@ impl Session {
|
||||
return None;
|
||||
}
|
||||
let d = self.clipboard.to_document();
|
||||
// SVG has no filters for the Photoshop-style effects: their objects go in as images.
|
||||
let flat = super::rasterfx::flatten_pixel_effects(&d);
|
||||
Some(vectorcraft_svg::export(
|
||||
&d,
|
||||
flat.as_ref().unwrap_or(&d),
|
||||
&vectorcraft_svg::ExportOptions { artboard: None, object_ids: vectorcraft_svg::ObjectIds::Minimal, ..Default::default() },
|
||||
))
|
||||
}
|
||||
|
||||
@@ -282,10 +282,19 @@ pub(super) fn new_from_template(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
open_template(s, src.name, &src.bytes, src.path)
|
||||
}
|
||||
|
||||
/// The most memory decoding one image may take: a 60 in print sheet at 300 ppi (18000 × 6600 px)
|
||||
/// is ~475 MB as RGBA, past the decoder's 512 MB default once it is converted. The web app keeps
|
||||
/// that default: wasm32 has 4 GB to address and aborts when an allocation fails.
|
||||
const MAX_RASTER_ALLOC: u64 = if cfg!(target_arch = "wasm32") { 512 << 20 } else { 2 << 30 };
|
||||
|
||||
/// Decode an image's header (and, for formats stored as PNG, its pixels). CMYK TIFFs are kept as
|
||||
/// they are, with their ink amounts ([`ImageBlob::cmyk`]).
|
||||
/// they are, with their ink amounts ([`ImageBlob::cmyk`]); CMYK TIFFs with an alpha channel, which
|
||||
/// the decoder can't read, become RGBA in the active colour settings' CMYK.
|
||||
pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> {
|
||||
let reader = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().map_err(err)?;
|
||||
let mut reader = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().map_err(err)?;
|
||||
let mut limits = image::Limits::default();
|
||||
limits.max_alloc = Some(MAX_RASTER_ALLOC);
|
||||
reader.limits(limits);
|
||||
let kind = reader.format().ok_or_else(|| err("not an image VectorCraft reads (see document.formats)"))?;
|
||||
let f = image_format(kind).ok_or_else(|| err(format!("{kind:?} images can't be opened (see document.formats)")))?;
|
||||
let ppi = super::ppi::resolution(bytes);
|
||||
@@ -293,7 +302,14 @@ pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> {
|
||||
let (bytes, mime, (width, height)) = if matches!(f.id, "png" | "jpg" | "gif" | "webp") || (f.id == "tiff" && cmyk()) {
|
||||
(bytes.to_vec(), f.mime, reader.into_dimensions().map_err(err)?)
|
||||
} else {
|
||||
let img = reader.decode().map_err(err)?.to_rgba8();
|
||||
let cmyka = || {
|
||||
let cms = vectorcraft_color::cms::active();
|
||||
vectorcraft_doc::cmyk::cmyka_tiff_rgba(bytes, |c| cms.cmyk_to_srgb(c, false))
|
||||
};
|
||||
let img = match (f.id == "tiff").then(cmyka).flatten() {
|
||||
Some(img) => img,
|
||||
None => reader.decode().map_err(err)?.to_rgba8(),
|
||||
};
|
||||
let size = img.dimensions();
|
||||
let mut png = Vec::new();
|
||||
img.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).map_err(err)?;
|
||||
@@ -311,16 +327,16 @@ pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> {
|
||||
Ok(RasterImage { key: blob.content_key(), blob, width, height, ppi })
|
||||
}
|
||||
|
||||
/// An image as a document of its pixel size (1 px = 1 pt), the image named after the file.
|
||||
/// An image as a document of its physical size at the resolution it declares (as Place sizes it;
|
||||
/// 72 ppi, 1 px = 1 pt, when it declares none), the image named after the file.
|
||||
fn raster_doc(name: &str, bytes: &[u8]) -> Result<Document> {
|
||||
let RasterImage { key, blob, width, height, .. } = raster_image(bytes)?;
|
||||
let mut d = Document::new(width as f64, height as f64);
|
||||
let RasterImage { key, blob, width, height, ppi } = raster_image(bytes)?;
|
||||
let (sx, sy) = crate::cmd::place::pt_per_px(ppi);
|
||||
let mut d = Document::new(width as f64 * sx, height as f64 * sy);
|
||||
let layer = d.layers[0].id;
|
||||
let id = d.alloc_id();
|
||||
let mut n = Node::new(
|
||||
id,
|
||||
NodeKind::Image(ImageObject { key: key.clone(), width, height, xf: Affine::IDENTITY, link: None, placement: Default::default() }),
|
||||
);
|
||||
let xf = Affine::scale_non_uniform(sx, sy);
|
||||
let mut n = Node::new(id, NodeKind::Image(ImageObject { key: key.clone(), width, height, xf, link: None, placement: Default::default() }));
|
||||
n.name = Some(name.to_string());
|
||||
d.images.insert(key, blob);
|
||||
d.insert(Some(layer), 0, n).map_err(err)?;
|
||||
|
||||
@@ -78,7 +78,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Open Document",
|
||||
[],
|
||||
None,
|
||||
"{path} or {name, dataBase64}, PDF/.ai: pages?: \"2-3, 5\" (1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page) | false (one layer per page, without the art that is off; Save then asks for a name), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), DXF: dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its pixel size), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again). Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's <image> files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks)",
|
||||
"{path} or {name, dataBase64}, PDF/.ai: pages?: \"2-3, 5\" (1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page) | false (one layer per page, without the art that is off; Save then asks for a name), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), DXF: dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again). Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's <image> files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks)",
|
||||
always,
|
||||
load::open
|
||||
),
|
||||
|
||||
@@ -153,6 +153,9 @@ pub(super) fn encode(doc: &Document, p: &Value, compressed: bool) -> Result<Enco
|
||||
let (opts, boards, chosen) = plan(doc, p)?;
|
||||
// Preserve editing embeds the native document (once, shared by every file).
|
||||
let native = opts.preserve_editing.then(|| vectorcraft_format::save(doc, false));
|
||||
// SVG has no filters for the Photoshop-style effects: their objects go in as images.
|
||||
let flat = crate::cmd::rasterfx::flatten_pixel_effects(doc);
|
||||
let doc = flat.as_ref().unwrap_or(doc);
|
||||
let mut enc = Encoded::default();
|
||||
for artboard in boards {
|
||||
// A chosen artboard's file holds the art over it (#550).
|
||||
|
||||
@@ -147,3 +147,19 @@ fn the_document_background_is_the_default_export_background() {
|
||||
assert_eq!(png(&mut s, json!({"format": "png", "background": "transparent"})).get_pixel(0, 0)[3], 0, "the option wins");
|
||||
assert_eq!(png(&mut s, json!({"format": "webp", "background": "black"})).get_pixel(0, 0).0, [0, 0, 0, 255]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_image_opens_at_the_size_its_resolution_declares() {
|
||||
let mut s = session(72.0, 36.0, 1);
|
||||
let hi = b64(&s.execute("document.export", &json!({"format": "png", "ppi": 300, "background": "white"})).unwrap());
|
||||
let lo = b64(&s.execute("document.export", &json!({"format": "png", "background": "white"})).unwrap());
|
||||
let lo = super::ppi::with_png_resolution(&lo, (72.0, 72.0));
|
||||
for (png, w, h, what) in [(hi, 72.0, 36.0, "300 ppi: 300 x 150 px is 1 x 0.5 in"), (lo, 72.0, 36.0, "72 ppi: 1 px = 1 pt")] {
|
||||
s.execute("document.open", &json!({"name": "art.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap();
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let ab = doc.artboards[0].rect;
|
||||
assert!((ab.width() - w).abs() < 1e-6 && (ab.height() - h).abs() < 1e-6, "{what}: artboard {ab:?}");
|
||||
let art = doc.art_bounds().expect("the image");
|
||||
assert!((art.width() - w).abs() < 1e-6 && (art.height() - h).abs() < 1e-6, "{what}: the image fills it, {art:?}");
|
||||
}
|
||||
}
|
||||
@@ -1265,11 +1265,11 @@ fn reach(n: &Node) -> Option<Rect> {
|
||||
if !n.visible {
|
||||
return None;
|
||||
}
|
||||
let fx = n.appearance.items.iter().map(|i| effects::outset(i.effects())).fold(effects::outset(&n.appearance.effects), f64::max);
|
||||
let b = match n.children() {
|
||||
Some(ch) if !n.clips() && !matches!(n.kind, NodeKind::Compound { .. }) => ch.iter().filter_map(|c| reach(c)).reduce(|a, b| a.union(b))?,
|
||||
_ => n.visual_bounds()?,
|
||||
};
|
||||
let fx = n.appearance.items.iter().map(|i| effects::outset(i.effects(), b)).fold(effects::outset(&n.appearance.effects, b), f64::max);
|
||||
Some(b.inflate(fx + 1.0, fx + 1.0))
|
||||
}
|
||||
|
||||
|
||||
@@ -247,7 +247,7 @@ fn font_list(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
|
||||
fn rescan(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
pub(crate) fn rescan(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let faces = db.load_system_fonts();
|
||||
@@ -283,6 +283,21 @@ fn rescan(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Type › Options › Additional Fonts Folder (#683) adds its folder to the system font scan,
|
||||
/// trimmed; clearing it takes the folder out again.
|
||||
#[test]
|
||||
fn the_additional_fonts_folder_joins_the_font_scan() {
|
||||
let mut s = Session::new();
|
||||
let dir = std::env::temp_dir().join("vectorcraft-fonts-folder-pref");
|
||||
s.execute("prefs.set", &json!({"key": "fontsFolder", "value": format!(" {} ", dir.display())})).unwrap();
|
||||
assert_eq!(vectorcraft_text::user_font_dirs(), std::slice::from_ref(&dir));
|
||||
if !cfg!(target_arch = "wasm32") {
|
||||
assert!(vectorcraft_text::system_font_dirs().contains(&dir));
|
||||
}
|
||||
s.execute("prefs.set", &json!({"key": "fontsFolder", "value": ""})).unwrap();
|
||||
assert!(vectorcraft_text::user_font_dirs().is_empty() && !vectorcraft_text::system_font_dirs().contains(&dir));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn list_flag_missing_replace_and_select() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -111,7 +111,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Crop Image",
|
||||
["Object"],
|
||||
None,
|
||||
"{rect?: [x, y, width, height]} crop the selected image (default: to the artboard it sits on) → {id, width, height}",
|
||||
"{rect?: [x, y, width, height] | trim?: true (to the pixels that aren't fully transparent, pixel for pixel; an image with none to cut is left as it is, trimmed: false)} crop the selected image (default: to the artboard it sits on) → {id, width, height, trimmed? (with trim)}",
|
||||
has_image,
|
||||
crop_image
|
||||
),
|
||||
@@ -156,7 +156,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Rearrange All Artboards…",
|
||||
["Object", "Artboards"],
|
||||
None,
|
||||
"{columns?: n (2), spacing?: pt (20), byColumn?: false, moveArtwork?: true (locked and hidden art only with prefs moveLockedWithArtboard)} lay artboards out in a grid",
|
||||
"{layout?: gridByRow|gridByColumn|row|column (gridByRow; byColumn?: true is gridByColumn), order?: leftToRight|rightToLeft (leftToRight: right-to-left mirrors the order along the rows), columns?: n (2; the rows for gridByColumn; row and column ignore it), spacing?: pt (20), moveArtwork?: true (locked and hidden art only with prefs moveLockedWithArtboard)} lay the artboards out in their order, the grid's top-left at the first artboard's → {artboards, rows, columns}",
|
||||
has_doc,
|
||||
rearrange_artboards
|
||||
),
|
||||
@@ -541,6 +541,9 @@ fn crop_image(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.ok_or_else(|| bad(C, "select an image"))?;
|
||||
let node = st.doc.node(id).cloned().ok_or(EngineError::NoNode(id))?;
|
||||
let NodeKind::Image(im) = &node.kind else { return Err(bad(C, "select an image")) };
|
||||
if p.get("trim").and_then(Value::as_bool) == Some(true) {
|
||||
return trim_image(s, id, im.clone());
|
||||
}
|
||||
let ib = node.geometric_bounds().ok_or_else(|| bad(C, "image has no bounds"))?;
|
||||
let rect = match p.get("rect").and_then(Value::as_array) {
|
||||
Some(a) if a.len() == 4 => {
|
||||
@@ -594,6 +597,49 @@ fn crop_image(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "id": id.0, "width": w, "height": h }))
|
||||
}
|
||||
|
||||
/// Crop Image's trim: the image cut to the box of its pixels that aren't fully transparent, the
|
||||
/// pixels copied as they are (no resampling) and placed where they were.
|
||||
fn trim_image(s: &mut Session, id: NodeId, im: ImageObject) -> Result<Value> {
|
||||
const C: &str = "object.cropImage";
|
||||
let st = s.doc()?;
|
||||
let blob = st.doc.images.get(&im.key).ok_or_else(|| bad(C, "the image's pixels are missing"))?;
|
||||
let px = image::load_from_memory(&blob.bytes).map_err(|_| bad(C, "the image's pixels can't be read"))?.to_rgba8();
|
||||
let (w, h) = px.dimensions();
|
||||
let (mut x0, mut y0, mut x1, mut y1) = (w, h, 0, 0);
|
||||
for (x, y, p) in px.enumerate_pixels() {
|
||||
if p[3] > 0 {
|
||||
(x0, y0, x1, y1) = (x0.min(x), y0.min(y), x1.max(x + 1), y1.max(y + 1));
|
||||
}
|
||||
}
|
||||
if x1 <= x0 || y1 <= y0 {
|
||||
return Err(bad(C, "the image is fully transparent"));
|
||||
}
|
||||
if (x0, y0, x1, y1) == (0, 0, w, h) {
|
||||
// Already trimmed: not an error, so a script can trim every image it opens.
|
||||
return Ok(json!({ "id": id.0, "width": w, "height": h, "trimmed": false }));
|
||||
}
|
||||
let cut = image::imageops::crop_imm(&px, x0, y0, x1 - x0, y1 - y0).to_image();
|
||||
let mut png = Vec::new();
|
||||
cut.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).map_err(|e| bad(C, e.to_string()))?;
|
||||
let (cw, ch) = (x1 - x0, y1 - y0);
|
||||
s.edit("Crop Image", |d, _| {
|
||||
let key = unique_key(d, "crop");
|
||||
d.images.insert(key.clone(), vectorcraft_doc::ImageBlob::new("image/png", png));
|
||||
if let Some(n) = d.node_mut(id) {
|
||||
n.kind = NodeKind::Image(ImageObject {
|
||||
key,
|
||||
width: cw,
|
||||
height: ch,
|
||||
xf: im.xf * Affine::translate((f64::from(x0), f64::from(y0))),
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "id": id.0, "width": cw, "height": ch, "trimmed": true }))
|
||||
}
|
||||
|
||||
/// The Control bar's Mask for an image: a clip group of the image and a clipping path on its
|
||||
/// outline, with that path selected so dragging its handles crops the image.
|
||||
fn mask_image(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
@@ -777,10 +823,32 @@ fn convert_to_artboards(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn rearrange_artboards(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let n_ab = s.doc()?.doc.artboards.len().max(1);
|
||||
let cols = (f64_or(p, "columns", 2.0).clamp(1.0, n_ab as f64)) as usize;
|
||||
const CMD: &str = "artboard.rearrange";
|
||||
use super::newdoc::ArtboardLayout as L;
|
||||
// A value given (not null) must be one of the names.
|
||||
let named = |key: &str| p.get(key).filter(|v| !v.is_null()).map(|v| v.as_str().unwrap_or_default());
|
||||
let layout = match named("layout") {
|
||||
Some(l) => L::parse(l).ok_or_else(|| bad(CMD, "layout must be gridByRow, gridByColumn, row or column"))?,
|
||||
None if bool_or(p, "byColumn", false) => L::GridByColumn,
|
||||
None => L::GridByRow,
|
||||
};
|
||||
let rtl = match named("order") {
|
||||
None => false,
|
||||
Some(o) if o.eq_ignore_ascii_case("leftToRight") => false,
|
||||
Some(o) if o.eq_ignore_ascii_case("rightToLeft") => true,
|
||||
Some(_) => return Err(bad(CMD, "order must be leftToRight or rightToLeft")),
|
||||
};
|
||||
let count = s.doc()?.doc.artboards.len();
|
||||
let n_ab = count.max(1);
|
||||
// Columns of a grid by row, rows of a grid by column (NaN casts to 0).
|
||||
let lines = (f64_or(p, "columns", 2.0).clamp(1.0, n_ab as f64) as usize).max(1);
|
||||
let (rows, cols) = match layout {
|
||||
L::GridByRow => (n_ab.div_ceil(lines), lines),
|
||||
L::GridByColumn => (lines, n_ab.div_ceil(lines)),
|
||||
L::Row => (1, n_ab),
|
||||
L::Column => (n_ab, 1),
|
||||
};
|
||||
let spacing = f64_or(p, "spacing", 20.0).clamp(-1.0e5, 1.0e5);
|
||||
let by_col = bool_or(p, "byColumn", false);
|
||||
let move_art = bool_or(p, "moveArtwork", true);
|
||||
let locked_and_hidden = s.prefs.move_locked_with_artboard;
|
||||
let scale_strokes = false;
|
||||
@@ -788,7 +856,7 @@ fn rearrange_artboards(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let rects: Vec<Rect> = d.artboards.iter().map(|a| a.rect).collect();
|
||||
let Some(first) = rects.first().copied() else { return Ok(()) };
|
||||
let sizes: Vec<(f64, f64)> = rects.iter().map(|r| (r.width(), r.height())).collect();
|
||||
let origins = super::newdoc::grid_origins(&sizes, first.origin(), cols, spacing, by_col, false);
|
||||
let origins = super::newdoc::grid_origins_rc(&sizes, first.origin(), (rows, cols), spacing, layout == L::GridByColumn, rtl);
|
||||
let deltas: Vec<Vec2> = rects.iter().zip(origins).map(|(r, o)| o - r.origin()).collect();
|
||||
if move_art {
|
||||
let tops: Vec<(NodeId, Point)> = d
|
||||
@@ -800,11 +868,11 @@ fn rearrange_artboards(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.filter_map(|n| Some((n.id, n.geometric_bounds()?.center())))
|
||||
.collect();
|
||||
for (id, c) in tops {
|
||||
if let Some(i) = rects.iter().position(|r| r.contains(c))
|
||||
&& deltas[i] != Vec2::ZERO
|
||||
if let Some(&dl) = rects.iter().position(|r| r.contains(c)).and_then(|i| deltas.get(i))
|
||||
&& dl != Vec2::ZERO
|
||||
&& let Some(n) = d.node_mut(id)
|
||||
{
|
||||
n.transform(Affine::translate(deltas[i]), scale_strokes);
|
||||
n.transform(Affine::translate(dl), scale_strokes);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -818,5 +886,5 @@ fn rearrange_artboards(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
ok()
|
||||
Ok(json!({ "artboards": count, "rows": rows, "columns": cols }))
|
||||
}
|
||||
@@ -345,9 +345,22 @@ pub fn color_mode_id(m: ColorMode) -> &'static str {
|
||||
/// each column as wide and each row as tall as its largest artboard; `by_column` fills columns
|
||||
/// top to bottom first, `rtl` puts the first column at the right.
|
||||
pub(crate) fn grid_origins(sizes: &[(f64, f64)], origin: Point, columns: usize, spacing: f64, by_column: bool, rtl: bool) -> Vec<Point> {
|
||||
let n = sizes.len();
|
||||
let cols = columns.clamp(1, n.max(1));
|
||||
let rows = n.div_ceil(cols).max(1);
|
||||
let n = sizes.len().max(1);
|
||||
let cols = columns.clamp(1, n);
|
||||
grid_origins_rc(sizes, origin, (n.div_ceil(cols), cols), spacing, by_column, rtl)
|
||||
}
|
||||
|
||||
/// [`grid_origins`] on a grid of `rows` × `cols` cells (at least enough for every artboard when
|
||||
/// filled the `by_column` way).
|
||||
pub(crate) fn grid_origins_rc(
|
||||
sizes: &[(f64, f64)],
|
||||
origin: Point,
|
||||
(rows, cols): (usize, usize),
|
||||
spacing: f64,
|
||||
by_column: bool,
|
||||
rtl: bool,
|
||||
) -> Vec<Point> {
|
||||
let (rows, cols) = (rows.max(1), cols.max(1));
|
||||
// Grid cell (row, column) of artboard i.
|
||||
let cell = |i: usize| {
|
||||
let (r, c) = if by_column { (i % rows, i / rows) } else { (i / cols, i % cols) };
|
||||
@@ -362,7 +375,7 @@ pub(crate) fn grid_origins(sizes: &[(f64, f64)], origin: Point, columns: usize,
|
||||
}
|
||||
}
|
||||
let offset = |spans: &[f64], k: usize| spans.iter().take(k).map(|s| s + spacing).sum::<f64>();
|
||||
(0..n)
|
||||
(0..sizes.len())
|
||||
.map(|i| {
|
||||
let (r, c) = cell(i);
|
||||
Point::new(origin.x + offset(&col_w, c), origin.y + offset(&row_h, r))
|
||||
|
||||
@@ -187,6 +187,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[
|
||||
p!("missingGlyphProtection", "Type", "Options", "Enable Missing Glyph Protection", bool),
|
||||
p!("highlightAlternateGlyphs", "Type", "Options", "Highlight Alternate Glyphs", bool),
|
||||
p!("placeholderText", "Type", "Options", "Fill New Type Objects With Placeholder Text", bool),
|
||||
p!("fontsFolder", "Type", "Options", "Additional Fonts Folder", text),
|
||||
// Units
|
||||
p!("unitsGeneral", "Units", "", "General", choice(UNITS)),
|
||||
p!("unitsStroke", "Units", "", "Stroke", choice(UNITS)),
|
||||
@@ -260,8 +261,21 @@ pub const PREF_SPECS: &[PrefSpec] = &[
|
||||
"Brightness",
|
||||
choice(&[("dark", "Dark"), ("mediumDark", "Medium Dark"), ("mediumLight", "Medium Light"), ("light", "Light")])
|
||||
),
|
||||
p!("canvasColor", "User Interface", "", "Canvas Color", choice(&[("matchUi", "Match User Interface Brightness"), ("white", "White")])),
|
||||
p!(
|
||||
"canvasColor",
|
||||
"User Interface",
|
||||
"",
|
||||
"Canvas Color",
|
||||
choice(&[
|
||||
("matchUi", "Match User Interface Brightness"),
|
||||
("white", "White"),
|
||||
("lightGray", "Light Gray"),
|
||||
("mediumGray", "Medium Gray"),
|
||||
("darkGray", "Dark Gray")
|
||||
])
|
||||
),
|
||||
p!("autoCollapseIconPanels", "User Interface", "", "Auto-Collapse Iconic Panels", bool),
|
||||
p!("toolGroupLabels", "User Interface", "", "Show Tool Group Labels", bool),
|
||||
p!("openDocumentsAsTabs", "User Interface", "", "Open Documents As Tabs", bool),
|
||||
p!("largeTabs", "User Interface", "", "Large Tabs", bool),
|
||||
p!("uiScaling", "User Interface", "UI Scaling", "Scale", num(0.75, 2.0, "×")),
|
||||
@@ -460,7 +474,18 @@ impl Session {
|
||||
let grid_changed = p.gridline_every != self.prefs.gridline_every || p.grid_subdivisions != self.prefs.grid_subdivisions;
|
||||
let history_changed = p.history_states != self.prefs.history_states;
|
||||
let tile_edge_changed = p.pattern_tile_edge_color != self.prefs.pattern_tile_edge_color;
|
||||
let fonts_folder_changed = p.fonts_folder != self.prefs.fonts_folder;
|
||||
self.prefs = p;
|
||||
if fonts_folder_changed {
|
||||
let folder = self.prefs.fonts_folder.trim();
|
||||
vectorcraft_text::set_user_font_dirs(if folder.is_empty() { vec![] } else { vec![folder.into()] });
|
||||
// Once the fonts were scanned, scan again now: the folder's fonts appear (or go) in the
|
||||
// font menus, and type in them lays out again. The first scan reads it anyway.
|
||||
if vectorcraft_text::FontDb::global().installed_fonts_changed() {
|
||||
// Its result only counts the faces cataloged.
|
||||
let _ = super::fonts::rescan(self, &serde_json::Value::Null);
|
||||
}
|
||||
}
|
||||
vectorcraft_render::set_default_threads(u16::try_from(self.prefs.render_threads).ok());
|
||||
for st in &mut self.docs {
|
||||
if history_changed {
|
||||
|
||||
@@ -7,6 +7,10 @@
|
||||
//! effect: the image (with the object's own area knocked out) goes under the untouched vector
|
||||
//! object. Effects that change the object itself (inner glow, feather, Gaussian blur) replace it
|
||||
//! with the image. Expand Appearance makes its images with the same helpers.
|
||||
//!
|
||||
//! SVG has filters for shadows, glows, blurs and feathers but none for the Photoshop-style
|
||||
//! effects (Radial Blur, Unsharp Mask…): SVG export turns only the objects carrying one of those
|
||||
//! into images the same way ([`flatten_pixel_effects`]).
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -167,7 +171,7 @@ pub(crate) fn effect_image(out: &mut Document, whole: &Node, knockout: Option<&N
|
||||
// effects reach beyond that.
|
||||
let b = vectorcraft_render::painted_bounds(whole)?;
|
||||
let look = out.raster_effects.clone();
|
||||
let reach = whole.appearance.items.iter().map(|i| effects::outset(i.effects())).fold(0.0, f64::max) + 2.0 + look.add_around;
|
||||
let reach = whole.appearance.items.iter().map(|i| effects::outset(i.effects(), b)).fold(0.0, f64::max) + 2.0 + look.add_around;
|
||||
let b = b.inflate(reach, reach);
|
||||
// Whole pixels, and no larger than 64 Mpx.
|
||||
let scale = scale.min((64.0e6 / (b.width() * b.height()).max(1.0)).sqrt());
|
||||
@@ -337,20 +341,39 @@ fn placed_symbol(d: &Document, n: &Node) -> Option<Node> {
|
||||
Some(Node { kind: NodeKind::Group { children: vec![Arc::new(art)], clip: false }, ..n.clone() })
|
||||
}
|
||||
|
||||
/// Does `n` hold raster effects PDF export draws: its own, its fills' and strokes', its opacity
|
||||
/// mask's or (groups and layers) its members'? Hidden objects and template layers aren't drawn.
|
||||
fn needs(n: &Node) -> bool {
|
||||
/// Which objects' raster effects become images.
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum Which {
|
||||
/// Every raster effect (PDF).
|
||||
All,
|
||||
/// Objects with a Photoshop-style effect, which SVG can't draw (with all their raster effects).
|
||||
Pixel,
|
||||
}
|
||||
|
||||
/// Has `n` (its own, its fills' or strokes') raster effects `which` turns into an image?
|
||||
fn imaged(n: &Node, which: Which) -> bool {
|
||||
let fx = raster_fx(n);
|
||||
match which {
|
||||
Which::All => !fx.is_empty(),
|
||||
Which::Pixel => fx.iter().any(|f| matches!(f, RasterFx::Pixel(_))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Does `n` hold raster effects that `which` turns into images: its own, its fills' and strokes',
|
||||
/// its opacity mask's or (groups and layers) its members'? Hidden objects and template layers
|
||||
/// aren't drawn.
|
||||
fn needs(n: &Node, which: Which) -> bool {
|
||||
n.visible
|
||||
&& !matches!(n.kind, NodeKind::Layer { template: true, .. })
|
||||
&& (!raster_fx(n).is_empty()
|
||||
|| n.mask.as_ref().is_some_and(|m| needs(&m.art))
|
||||
|| (is_container(n) && n.children().is_some_and(|ch| ch.iter().any(|c| needs(c)))))
|
||||
&& (imaged(n, which)
|
||||
|| n.mask.as_ref().is_some_and(|m| needs(&m.art, which))
|
||||
|| (is_container(n) && n.children().is_some_and(|ch| ch.iter().any(|c| needs(c, which)))))
|
||||
}
|
||||
|
||||
/// The art of `n`'s opacity mask with its raster effects as images.
|
||||
fn walk_mask(out: &mut Document, n: &mut Node) {
|
||||
fn walk_mask(out: &mut Document, n: &mut Node, which: Which) {
|
||||
if let Some(m) = n.mask.as_mut()
|
||||
&& let Some(art) = walk(out, &m.art)
|
||||
&& let Some(art) = walk(out, &m.art, which)
|
||||
{
|
||||
m.art = Arc::new(art);
|
||||
}
|
||||
@@ -359,15 +382,15 @@ fn walk_mask(out: &mut Document, n: &mut Node) {
|
||||
/// `n` with its raster effects (and its members' and its opacity mask's) as images, `None` when it
|
||||
/// has none. An object whose effects all paint below it keeps its vector art over an image of
|
||||
/// them; one whose effects change it (blur, feather, inner glow) becomes the image.
|
||||
fn walk(out: &mut Document, n: &Node) -> Option<Node> {
|
||||
if !needs(n) {
|
||||
fn walk(out: &mut Document, n: &Node, which: Which) -> Option<Node> {
|
||||
if !needs(n, which) {
|
||||
return None;
|
||||
}
|
||||
if raster_fx(n).is_empty() {
|
||||
if !imaged(n, which) {
|
||||
let mut m = n.clone();
|
||||
walk_mask(out, &mut m);
|
||||
walk_mask(out, &mut m, which);
|
||||
if is_container(&m)
|
||||
&& let Some(ch) = walk_all(out, n.children()?)
|
||||
&& let Some(ch) = walk_all(out, n.children()?, which)
|
||||
&& let Some(slot) = m.children_mut()
|
||||
{
|
||||
*slot = ch;
|
||||
@@ -375,30 +398,30 @@ fn walk(out: &mut Document, n: &Node) -> Option<Node> {
|
||||
return Some(m);
|
||||
}
|
||||
if let Some(g) = placed_symbol(out, n) {
|
||||
return Some(walk(out, &g).unwrap_or(g));
|
||||
return Some(walk(out, &g, which).unwrap_or(g));
|
||||
}
|
||||
let below = below_only(n);
|
||||
if !below && let Some(g) = split_items(out, n) {
|
||||
return Some(walk(out, &g).unwrap_or(g));
|
||||
return Some(walk(out, &g, which).unwrap_or(g));
|
||||
}
|
||||
// An image that can't be made leaves the object as it is (the writer reports its effects).
|
||||
let image = raster_image(out, n, below, false)?;
|
||||
let mut v = n.clone();
|
||||
strip_raster(&mut v, false);
|
||||
let mut m = if below {
|
||||
let mut m = walk(out, &v).unwrap_or(v);
|
||||
let mut m = walk(out, &v, which).unwrap_or(v);
|
||||
put_below(out, &mut m, image);
|
||||
m
|
||||
} else {
|
||||
replace_with_image(v, image)
|
||||
};
|
||||
walk_mask(out, &mut m);
|
||||
walk_mask(out, &mut m, which);
|
||||
Some(m)
|
||||
}
|
||||
|
||||
/// `nodes` with their raster effects as images, `None` when none has any.
|
||||
fn walk_all(out: &mut Document, nodes: &[Arc<Node>]) -> Option<Vec<Arc<Node>>> {
|
||||
nodes.iter().any(|n| needs(n)).then(|| nodes.iter().map(|n| walk(out, n).map(Arc::new).unwrap_or_else(|| n.clone())).collect())
|
||||
fn walk_all(out: &mut Document, nodes: &[Arc<Node>], which: Which) -> Option<Vec<Arc<Node>>> {
|
||||
nodes.iter().any(|n| needs(n, which)).then(|| nodes.iter().map(|n| walk(out, n, which).map(Arc::new).unwrap_or_else(|| n.clone())).collect())
|
||||
}
|
||||
|
||||
/// A copy of `doc` with raster effects turned into images at the document's raster effects
|
||||
@@ -406,26 +429,37 @@ fn walk_all(out: &mut Document, nodes: &[Arc<Node>]) -> Option<Vec<Arc<Node>>> {
|
||||
/// type, images, symbol instances, live objects) and on single fills and strokes, in the layers,
|
||||
/// opacity masks, symbol definitions and pattern tiles.
|
||||
pub fn flatten_raster_effects(doc: &Document) -> Option<Document> {
|
||||
let any = |nodes: &[Arc<Node>]| nodes.iter().any(|n| needs(n));
|
||||
if !any(&doc.layers) && !doc.symbols.iter().any(|s| needs(&s.art)) && !doc.patterns.iter().any(|p| any(&p.art)) {
|
||||
flatten(doc, Which::All)
|
||||
}
|
||||
|
||||
/// A copy of `doc` in which the objects with Photoshop-style raster effects (Radial Blur, Unsharp
|
||||
/// Mask…) are images as [`flatten_raster_effects`] makes them (SVG export: its filters draw the
|
||||
/// other raster effects live), or `None` when there are none.
|
||||
pub fn flatten_pixel_effects(doc: &Document) -> Option<Document> {
|
||||
flatten(doc, Which::Pixel)
|
||||
}
|
||||
|
||||
fn flatten(doc: &Document, which: Which) -> Option<Document> {
|
||||
let any = |nodes: &[Arc<Node>]| nodes.iter().any(|n| needs(n, which));
|
||||
if !any(&doc.layers) && !doc.symbols.iter().any(|s| needs(&s.art, which)) && !doc.patterns.iter().any(|p| any(&p.art)) {
|
||||
return None;
|
||||
}
|
||||
// Geometry effects first, so the vector objects kept above shadows are final.
|
||||
let baked = effects::bake_document(doc);
|
||||
let src = baked.as_ref().unwrap_or(doc);
|
||||
let mut out = src.clone();
|
||||
if let Some(layers) = walk_all(&mut out, &src.layers) {
|
||||
if let Some(layers) = walk_all(&mut out, &src.layers, which) {
|
||||
out.layers = layers;
|
||||
}
|
||||
for i in 0..out.symbols.len() {
|
||||
if let Some(art) = out.symbols.get(i).map(|s| s.art.clone()).and_then(|a| walk(&mut out, &a))
|
||||
if let Some(art) = out.symbols.get(i).map(|s| s.art.clone()).and_then(|a| walk(&mut out, &a, which))
|
||||
&& let Some(s) = out.symbols.get_mut(i)
|
||||
{
|
||||
s.art = Arc::new(art);
|
||||
}
|
||||
}
|
||||
for i in 0..out.patterns.len() {
|
||||
if let Some(art) = out.patterns.get(i).map(|p| p.art.clone()).and_then(|a| walk_all(&mut out, &a))
|
||||
if let Some(art) = out.patterns.get(i).map(|p| p.art.clone()).and_then(|a| walk_all(&mut out, &a, which))
|
||||
&& let Some(p) = out.patterns.get_mut(i)
|
||||
{
|
||||
p.art = art;
|
||||
|
||||
@@ -480,6 +480,9 @@ pub struct Prefs {
|
||||
// Hyphenation
|
||||
pub hyphenation_language: String,
|
||||
pub hyphenation_exceptions: String,
|
||||
/// Type › Options › Additional Fonts Folder: a folder (read with its subfolders) whose fonts
|
||||
/// are listed and used as if installed (#683); empty for none.
|
||||
pub fonts_folder: String,
|
||||
// Performance & Storage (Plug-ins & Scratch Disks)
|
||||
pub plugins_folder: String,
|
||||
pub scratch_primary: String,
|
||||
@@ -488,6 +491,9 @@ pub struct Prefs {
|
||||
pub ui_brightness: String,
|
||||
pub canvas_color: String,
|
||||
pub auto_collapse_icon_panels: bool,
|
||||
/// User Interface › Show Tool Group Labels: the toolbar's group names (Select, Shapes, Draw…);
|
||||
/// off, a faint dash separates the groups instead (#663).
|
||||
pub tool_group_labels: bool,
|
||||
pub open_documents_as_tabs: bool,
|
||||
pub large_tabs: bool,
|
||||
pub ui_scaling: f64,
|
||||
@@ -696,12 +702,14 @@ impl Default for Prefs {
|
||||
slice_line_color: s("#ff3f3f"),
|
||||
hyphenation_language: s("English: USA"),
|
||||
hyphenation_exceptions: String::new(),
|
||||
fonts_folder: String::new(),
|
||||
plugins_folder: String::new(),
|
||||
scratch_primary: s("Startup"),
|
||||
scratch_secondary: s("None"),
|
||||
ui_brightness: s("mediumDark"),
|
||||
canvas_color: s("matchUi"),
|
||||
auto_collapse_icon_panels: false,
|
||||
tool_group_labels: true,
|
||||
open_documents_as_tabs: true,
|
||||
large_tabs: false,
|
||||
ui_scaling: 1.0,
|
||||
@@ -1544,6 +1552,8 @@ mod tests_proxyitems;
|
||||
#[cfg(test)]
|
||||
mod tests_puppetwarp;
|
||||
#[cfg(test)]
|
||||
mod tests_rasterfilters;
|
||||
#[cfg(test)]
|
||||
mod tests_rastersettings;
|
||||
#[cfg(test)]
|
||||
mod tests_recolor;
|
||||
|
||||
@@ -1159,3 +1159,35 @@ fn saved_selection_names_are_trimmed_and_capped() {
|
||||
let list = s.execute("select.savedList", &json!({})).unwrap();
|
||||
assert_eq!(list[0].as_str().map(|n| n.chars().count()), Some(vectorcraft_doc::SavedSelection::MAX_NAME));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crop_image_trim_cuts_to_the_opaque_pixels_as_they_are() {
|
||||
// 100 × 80 px, transparent but for a block at (20, 10)–(50, 40) px; placed at 2 pt a pixel.
|
||||
let mut px = image::RgbaImage::new(100, 80);
|
||||
for y in 10..40 {
|
||||
for x in 20..50 {
|
||||
px.put_pixel(x, y, image::Rgba([x as u8, y as u8, 7, if x == 20 { 1 } else { 255 }]));
|
||||
}
|
||||
}
|
||||
let mut png = Vec::new();
|
||||
px.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
|
||||
let mut s = Session::new();
|
||||
s.execute("document.open", &json!({"name": "art.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap();
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
let img = selected(&s)[0];
|
||||
s.execute("object.scale", &json!({"sx": 200, "origin": [0, 0]})).unwrap();
|
||||
let r = s.execute("object.cropImage", &json!({"trim": true})).unwrap();
|
||||
assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (30, 30), "{r}");
|
||||
// Placed where those pixels were: (40, 20) pt, 60 × 60 pt at 2 pt a pixel.
|
||||
let b = bounds(&s, img);
|
||||
assert!(close(b.x0, 40.0) && close(b.y0, 20.0) && close(b.width(), 60.0) && close(b.height(), 60.0), "{b:?}");
|
||||
// Pixel for pixel, a barely visible (alpha 1) edge included.
|
||||
let NodeKind::Image(im) = &node(&s, img).kind else { panic!("an image") };
|
||||
let out = image::load_from_memory(&s.doc().unwrap().doc.images[&im.key].bytes).unwrap().to_rgba8();
|
||||
assert_eq!(out, image::imageops::crop_imm(&px, 20, 10, 30, 30).to_image());
|
||||
assert_eq!(r["trimmed"], true);
|
||||
// Nothing transparent left to cut: left as it is, and not an error (scripts trim every image).
|
||||
let r = s.execute("object.cropImage", &json!({"trim": true})).unwrap();
|
||||
assert_eq!((r["trimmed"].as_bool(), r["width"].as_u64()), (Some(false), Some(30)), "{r}");
|
||||
assert_eq!(bounds(&s, img), b);
|
||||
}
|
||||
@@ -223,3 +223,63 @@ fn rearrange_keeps_its_grid() {
|
||||
s.execute("artboard.rearrange", &json!({"columns": 2, "spacing": 5})).unwrap();
|
||||
assert_eq!(boards(&s).iter().map(|r| (r.x0, r.y0)).collect::<Vec<_>>(), [(0.0, 0.0), (105.0, 0.0), (0.0, 55.0)]);
|
||||
}
|
||||
|
||||
/// #681: every layout and order of Rearrange All Artboards, five 100 × 50 artboards 10 pt apart
|
||||
/// with Columns (the rows of a grid by column) 2: each artboard lands in its (row, column) cell, the
|
||||
/// art on it rides along, and it all undoes in one step.
|
||||
#[test]
|
||||
fn rearrange_lays_out_by_layout_and_order() {
|
||||
type Cells = [(u32, u32); 5];
|
||||
let cells: [(&str, &str, Cells); 8] = [
|
||||
("gridByRow", "leftToRight", [(0, 0), (0, 1), (1, 0), (1, 1), (2, 0)]),
|
||||
("gridByRow", "rightToLeft", [(0, 1), (0, 0), (1, 1), (1, 0), (2, 1)]),
|
||||
("gridByColumn", "leftToRight", [(0, 0), (1, 0), (0, 1), (1, 1), (0, 2)]),
|
||||
("gridByColumn", "rightToLeft", [(0, 2), (1, 2), (0, 1), (1, 1), (0, 0)]),
|
||||
("row", "leftToRight", [(0, 0), (0, 1), (0, 2), (0, 3), (0, 4)]),
|
||||
("row", "rightToLeft", [(0, 4), (0, 3), (0, 2), (0, 1), (0, 0)]),
|
||||
("column", "leftToRight", [(0, 0), (1, 0), (2, 0), (3, 0), (4, 0)]),
|
||||
("column", "rightToLeft", [(0, 0), (1, 0), (2, 0), (3, 0), (4, 0)]),
|
||||
];
|
||||
for (layout, order, want) in cells {
|
||||
// One row, 20 pt apart; a 10 pt square 10 pt into each artboard.
|
||||
let mut s = new_doc(json!({"width": 100, "height": 50, "artboards": 5}));
|
||||
let art: Vec<u64> = boards(&s)
|
||||
.iter()
|
||||
.map(|r| {
|
||||
s.execute("shape.rectangle", &json!({"x": r.x0 + 10.0, "y": r.y0 + 10.0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap()
|
||||
})
|
||||
.collect();
|
||||
let before = boards(&s);
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let p = json!({"layout": layout, "order": order, "columns": 2, "spacing": 10});
|
||||
let r = s.execute("artboard.rearrange", &p).unwrap();
|
||||
let (rows, cols) = want.iter().fold((0, 0), |(r, c), (wr, wc)| (r.max(wr + 1), c.max(wc + 1)));
|
||||
assert_eq!(r, json!({"artboards": 5, "rows": rows, "columns": cols}), "{layout} {order}");
|
||||
let got: Vec<(f64, f64)> = boards(&s).iter().map(|r| (r.x0, r.y0)).collect();
|
||||
let cells: Vec<(f64, f64)> = want.iter().map(|&(r, c)| (f64::from(c) * 110.0, f64::from(r) * 60.0)).collect();
|
||||
assert_eq!(got, cells, "{layout} {order}");
|
||||
assert!(boards(&s).iter().all(|r| r.width() == 100.0 && r.height() == 50.0));
|
||||
for (id, (x, y)) in art.iter().zip(&got) {
|
||||
let b = s.doc().unwrap().doc.node(NodeId(*id)).unwrap().geometric_bounds().unwrap();
|
||||
assert_eq!((b.x0, b.y0), (x + 10.0, y + 10.0), "{layout} {order}: the art moves with its artboard");
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(boards(&s), before);
|
||||
}
|
||||
}
|
||||
|
||||
/// `byColumn: true` is Grid by Column; without `moveArtwork` the art stays; bad values are errors.
|
||||
#[test]
|
||||
fn rearrange_aliases_and_rejects_bad_values() {
|
||||
let mut s = new_doc(json!({"width": 100, "height": 50, "artboards": 3}));
|
||||
let id = s.execute("shape.rectangle", &json!({"x": 130, "y": 10, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("artboard.rearrange", &json!({"byColumn": true, "columns": 2, "spacing": 0, "moveArtwork": false})).unwrap();
|
||||
assert_eq!(boards(&s).iter().map(|r| (r.x0, r.y0)).collect::<Vec<_>>(), [(0.0, 0.0), (0.0, 50.0), (100.0, 0.0)]);
|
||||
assert_eq!(s.doc().unwrap().doc.node(NodeId(id)).unwrap().geometric_bounds().unwrap().x0, 130.0, "the art stays");
|
||||
let before = boards(&s);
|
||||
for p in [json!({"layout": "diagonal"}), json!({"order": "upward"}), json!({"layout": 3}), json!({"order": true})] {
|
||||
assert!(s.execute("artboard.rearrange", &p).is_err(), "{p}");
|
||||
}
|
||||
assert_eq!(boards(&s), before, "nothing moved");
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
//! The Photoshop-style raster effects (Effect › Blur › Radial Blur and Smart Blur, Sharpen ›
|
||||
//! Unsharp Mask): applied and edited as commands, listed in the catalogue, drawn on the canvas,
|
||||
//! and written to PDF and SVG as images of the effected object.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::NodeKind;
|
||||
use vectorcraft_geom::Rect;
|
||||
use vectorcraft_render::{Rendered, Renderer};
|
||||
|
||||
use super::*;
|
||||
|
||||
/// The new effects with parameters that change a striped square visibly.
|
||||
const EFFECTS: [(&str, &str); 3] = [
|
||||
("blur.radial", r#"{"amount": 30, "quality": "draft"}"#),
|
||||
("blur.smart", r#"{"radius": 8, "threshold": 100}"#),
|
||||
("sharpen.unsharpMask", r#"{"amount": 300, "radius": 3}"#),
|
||||
];
|
||||
|
||||
/// A group of a red square and a darker red stripe across it; returns the group's id.
|
||||
fn striped() -> (Session, u64) {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
|
||||
let id = s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#e03020", "ids": [id]})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true, "ids": [id]})).unwrap();
|
||||
let stripe = s.execute("shape.rectangle", &json!({"x": 90, "y": 50, "width": 20, "height": 100})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#b04848", "ids": [stripe]})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true, "ids": [stripe]})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id, stripe]})).unwrap();
|
||||
let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
(s, g)
|
||||
}
|
||||
|
||||
fn render(s: &Session) -> Rendered {
|
||||
Renderer::new().render_region(&s.doc().unwrap().doc, Rect::new(0.0, 0.0, 200.0, 200.0), 1.0, true)
|
||||
}
|
||||
|
||||
fn mean_diff(a: &Rendered, b: &Rendered) -> f64 {
|
||||
let sum: u64 = a.pixels.iter().zip(&b.pixels).map(|(x, y)| x.abs_diff(*y) as u64).sum();
|
||||
sum as f64 / a.pixels.len() as f64 / 255.0
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn listed_applied_edited_and_undone() {
|
||||
let (mut s, g) = striped();
|
||||
let list = s.execute("effect.list", &json!({})).unwrap();
|
||||
for (id, _) in EFFECTS {
|
||||
let e = list["catalog"].as_array().unwrap().iter().find(|e| e["id"] == id).unwrap_or_else(|| panic!("{id} listed"));
|
||||
assert_eq!(e["raster"], json!(true), "{id}");
|
||||
assert!(e["params"].as_str().unwrap().contains("radius") || id == "blur.radial", "{id}");
|
||||
}
|
||||
let menus: Vec<Value> =
|
||||
EFFECTS.iter().map(|(id, _)| list["catalog"].as_array().unwrap().iter().find(|e| e["id"] == *id).unwrap()["menu"].clone()).collect();
|
||||
assert_eq!(menus, [json!(["Effect", "Blur"]), json!(["Effect", "Blur"]), json!(["Effect", "Sharpen"])]);
|
||||
// Junk parameters are stored as given and read clamped; the canvas still draws.
|
||||
for (id, _) in EFFECTS {
|
||||
s.execute("effect.apply", &json!({"effect": id, "ids": [g], "params": {"amount": 1e308, "radius": -1e308, "threshold": "x", "quality": 7}}))
|
||||
.unwrap();
|
||||
}
|
||||
let _ = render(&s);
|
||||
let n = s.doc().unwrap().doc.node(NodeId(g)).unwrap().clone();
|
||||
assert_eq!(n.appearance.effects.len(), 3);
|
||||
assert_eq!(n.appearance.effects[0].params["method"], json!("spin"), "defaults fill the rest");
|
||||
s.execute("effect.setParams", &json!({"index": 0, "ids": [g], "params": {"method": "zoom"}})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.node(NodeId(g)).unwrap().appearance.effects[0].params["method"], json!("zoom"));
|
||||
for _ in 0..4 {
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
}
|
||||
assert!(s.doc().unwrap().doc.node(NodeId(g)).unwrap().appearance.effects.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_effect_changes_the_canvas_and_draws_the_same_twice() {
|
||||
for (id, params) in EFFECTS {
|
||||
let (mut s, g) = striped();
|
||||
let plain = render(&s);
|
||||
let params: Value = serde_json::from_str(params).unwrap();
|
||||
s.execute("effect.apply", &json!({"effect": id, "ids": [g], "params": params})).unwrap();
|
||||
let a = render(&s);
|
||||
assert!(mean_diff(&plain, &a) > 0.0005, "{id} shows: {}", mean_diff(&plain, &a));
|
||||
assert_eq!(a.pixels, render(&s).pixels, "{id} is deterministic");
|
||||
// The multithreaded pipeline draws the same.
|
||||
let mut mt = Renderer::new();
|
||||
mt.threads = 4;
|
||||
let b = mt.render_region(&s.doc().unwrap().doc, Rect::new(0.0, 0.0, 200.0, 200.0), 1.0, true);
|
||||
assert!(mean_diff(&a, &b) < 0.002, "{id}: multithreaded differs by {}", mean_diff(&a, &b));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spin_blur_reaches_past_the_corners() {
|
||||
let (mut s, g) = striped();
|
||||
s.execute("effect.apply", &json!({"effect": "blur.radial", "ids": [g], "params": {"amount": 60, "quality": "good"}})).unwrap();
|
||||
let img = render(&s);
|
||||
// Turned corners sweep beyond the square's sides (centre 100, 100; corner 70.7 pt out).
|
||||
let p = img.pixel(100, 46);
|
||||
assert!(p[1] < 250, "the arc of the corners reaches above the square: {p:?}");
|
||||
assert!(img.pixel(100, 20)[1] > 250, "but not beyond the corners' circle");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pdf_and_svg_write_the_effected_object_as_an_image() {
|
||||
for (id, params) in EFFECTS {
|
||||
let (mut s, g) = striped();
|
||||
let params: Value = serde_json::from_str(params).unwrap();
|
||||
s.execute("effect.apply", &json!({"effect": id, "ids": [g], "params": params})).unwrap();
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
// PDF: an image that reads back as the canvas shows it.
|
||||
let r = crate::cmd::rasterfx::export_pdf_with_report(&doc, &Default::default()).unwrap();
|
||||
assert!(r.warnings.is_empty(), "{id}: {:?}", r.warnings);
|
||||
let back = vectorcraft_pdf::import(&r.bytes).unwrap();
|
||||
let diff = mean_diff(&render(&s), &Renderer::new().render_region(&back, Rect::new(0.0, 0.0, 200.0, 200.0), 1.0, true));
|
||||
assert!(diff < 0.03, "{id}: PDF reads back {:.2}% off", diff * 100.0);
|
||||
// SVG: the object becomes an image; a Gaussian Blur alone stays a live filter.
|
||||
let svg = s.execute("document.serialize", &json!({"format": "svg"})).unwrap()["text"].as_str().unwrap().to_string();
|
||||
assert!(svg.contains("<image") && !svg.contains("<filter"), "{id}: {svg}");
|
||||
let flat = crate::cmd::rasterfx::flatten_pixel_effects(&doc).unwrap();
|
||||
assert!(matches!(flat.layers[0].children().unwrap()[0].kind, NodeKind::Image(_)), "{id}");
|
||||
}
|
||||
let (mut s, g) = striped();
|
||||
s.execute("effect.apply", &json!({"effect": "blur.gaussian", "ids": [g]})).unwrap();
|
||||
assert!(crate::cmd::rasterfx::flatten_pixel_effects(&s.doc().unwrap().doc).is_none());
|
||||
let svg = s.execute("document.serialize", &json!({"format": "svg"})).unwrap()["text"].as_str().unwrap().to_string();
|
||||
assert!(svg.contains("feGaussianBlur") && !svg.contains("<image"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expand_appearance_makes_an_image() {
|
||||
let (mut s, g) = striped();
|
||||
s.execute("effect.apply", &json!({"effect": "sharpen.unsharpMask", "ids": [g]})).unwrap();
|
||||
s.execute("effect.expandAppearance", &json!({"ids": [g]})).unwrap();
|
||||
assert!(matches!(s.doc().unwrap().doc.node(NodeId(g)).unwrap().kind, NodeKind::Image(_)));
|
||||
}
|
||||
@@ -98,13 +98,19 @@ fn known_bug(id: &str, p: &Value) -> bool {
|
||||
KNOWN_BUGS.iter().any(|(c, k)| *c == id && p.get(*k).is_some())
|
||||
}
|
||||
|
||||
/// Regression: huge column counts used to panic with `capacity overflow`.
|
||||
/// Regression: huge column counts used to panic with `capacity overflow`; in every layout and
|
||||
/// order (#681), with huge and negative spacing too.
|
||||
#[test]
|
||||
fn artboard_rearrange_huge_columns() {
|
||||
for fx in Fixture::ALL {
|
||||
for cols in [json!(u64::MAX), json!(1e308)] {
|
||||
let p = json!({ "columns": cols });
|
||||
assert_eq!(probe(fx, "artboard.rearrange", &p), None);
|
||||
for layout in ["gridByRow", "gridByColumn", "row", "column"] {
|
||||
for order in ["leftToRight", "rightToLeft"] {
|
||||
for (cols, spacing) in [(json!(u64::MAX), json!(1e308)), (json!(1e308), json!(-1e308)), (json!(0), json!(0)), (json!(-5), json!(20))]
|
||||
{
|
||||
let p = json!({ "layout": layout, "order": order, "columns": cols, "spacing": spacing });
|
||||
assert_eq!(probe(fx, "artboard.rearrange", &p), None);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -251,6 +257,9 @@ fn structured_junk() {
|
||||
("effect.apply", json!({"effect": "distort.zigZag", "params": {"size": 1e308, "ridges": 100}})),
|
||||
("effect.apply", json!({"effect": "distort.transform", "params": {"copies": 1e308}})),
|
||||
("effect.apply", json!({"effect": "stylize.dropShadow", "params": {"blur": 1e308, "opacity": -1}})),
|
||||
("effect.apply", json!({"effect": "blur.radial", "params": {"amount": 1e308, "method": 5, "quality": "best"}})),
|
||||
("effect.apply", json!({"effect": "blur.smart", "params": {"radius": 1e308, "threshold": -1e308, "quality": null}})),
|
||||
("effect.apply", json!({"effect": "sharpen.unsharpMask", "params": {"amount": -1, "radius": "1e999", "threshold": 1e308}})),
|
||||
("effect.apply", json!({"effect": "no.such.effect"})),
|
||||
("effect.remove", json!({"index": 99})),
|
||||
("effect.setParams", json!({"index": 0, "params": null})),
|
||||
|
||||
@@ -592,6 +592,8 @@ struct Builder<'p> {
|
||||
image_keys: HashMap<u128, (String, u32, u32)>,
|
||||
/// The images kept with their CMYK samples ([`crate::import_image`]).
|
||||
cmyk_keys: HashSet<u128>,
|
||||
/// Mask keys of CMYK images whose mask turned out to hide nothing.
|
||||
opaque: HashSet<u128>,
|
||||
warnings: Vec<String>,
|
||||
/// Fonts by cache key → base font name (from [`scan_page`]).
|
||||
fonts: HashMap<u128, String>,
|
||||
@@ -743,6 +745,7 @@ impl<'p> Builder<'p> {
|
||||
images: HashMap::new(),
|
||||
image_keys: HashMap::new(),
|
||||
cmyk_keys: HashSet::new(),
|
||||
opaque: HashSet::new(),
|
||||
warnings: vec![],
|
||||
fonts: HashMap::new(),
|
||||
font_names: HashMap::new(),
|
||||
@@ -1146,6 +1149,40 @@ impl<'p> Builder<'p> {
|
||||
}
|
||||
|
||||
fn add_image(&mut self, key: u128, make: impl FnOnce() -> Option<(ImageBlob, u32, u32)>, xf: Affine) {
|
||||
self.add_image_masked(key, make, xf, None);
|
||||
}
|
||||
|
||||
/// An image's alpha (its soft mask, stencil mask or colour key, at its own resolution) as a
|
||||
/// greyscale image over the image's `w` × `h` pixels (`transform`): its opacity mask. `None`
|
||||
/// when it masks nothing.
|
||||
fn alpha_mask(&mut self, key: u128, r: &hayro_interpret::RasterImage<'_>, w: u32, h: u32, transform: Affine) -> Option<OpacityMask> {
|
||||
let mkey = key ^ 0x5_3a5c;
|
||||
if self.opaque.contains(&mkey) {
|
||||
return None;
|
||||
}
|
||||
let (k, mw, mh) = if let Some(v) = self.image_keys.get(&mkey).cloned() {
|
||||
v
|
||||
} else {
|
||||
let mut alpha = None;
|
||||
r.with_rgba(|_, a| alpha = a, None);
|
||||
let Some(a) = alpha.filter(|a| a.data.iter().any(|v| *v < 255)) else {
|
||||
self.opaque.insert(mkey);
|
||||
return None;
|
||||
};
|
||||
let mut png = Vec::new();
|
||||
image::GrayImage::from_raw(a.width, a.height, a.data)?.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).ok()?;
|
||||
let blob = ImageBlob::new("image/png", png);
|
||||
let k = blob.content_key();
|
||||
self.images.insert(k.clone(), blob);
|
||||
self.image_keys.insert(mkey, (k.clone(), a.width, a.height));
|
||||
(k, a.width, a.height)
|
||||
};
|
||||
let xf = transform * Affine::scale_non_uniform(f64::from(w) / f64::from(mw.max(1)), f64::from(h) / f64::from(mh.max(1)));
|
||||
let art = Node::new(self.id(), NodeKind::Image(ImageObject { key: k, width: mw, height: mh, xf, link: None, placement: Default::default() }));
|
||||
Some(OpacityMask::new(art, true))
|
||||
}
|
||||
|
||||
fn add_image_masked(&mut self, key: u128, make: impl FnOnce() -> Option<(ImageBlob, u32, u32)>, xf: Affine, mask: Option<OpacityMask>) {
|
||||
let (k, w, h) = if let Some(v) = self.image_keys.get(&key).cloned() {
|
||||
v
|
||||
} else {
|
||||
@@ -1160,7 +1197,9 @@ impl<'p> Builder<'p> {
|
||||
(k, w, h)
|
||||
};
|
||||
let id = self.id();
|
||||
self.push_node(Node::new(id, NodeKind::Image(ImageObject { key: k, width: w, height: h, xf, link: None, placement: Default::default() })));
|
||||
let mut n = Node::new(id, NodeKind::Image(ImageObject { key: k, width: w, height: h, xf, link: None, placement: Default::default() }));
|
||||
n.mask = mask.map(Box::new);
|
||||
self.push_node(n);
|
||||
}
|
||||
|
||||
/// Mesh shadings filling `region` (document space): gradient meshes, clipped to the region
|
||||
@@ -1542,7 +1581,10 @@ impl<'a> Device<'a> for Builder<'_> {
|
||||
};
|
||||
if known || cmyk.is_some() {
|
||||
self.cmyk_keys.insert(key);
|
||||
return self.add_image(key, || cmyk.map(|blob| (blob, w, h)), transform);
|
||||
// Its mask (read by the interpreter, whatever its kind) becomes an opacity
|
||||
// mask, so the inks stay as they are.
|
||||
let mask = if crate::import_image::has_mask(st) { self.alpha_mask(key, &r, w, h, transform) } else { None };
|
||||
return self.add_image_masked(key, || cmyk.map(|blob| (blob, w, h)), transform, mask);
|
||||
}
|
||||
// JPEG passthrough for plain DeviceRGB/DeviceGray DCT images.
|
||||
let dict = st.dict();
|
||||
|
||||
@@ -2,7 +2,9 @@
|
||||
//! four components. A JPEG whose Decode array inverts its samples (Adobe's CMYK JPEGs, the
|
||||
//! convention JPEG readers and the PDF writer take a CMYK JPEG to follow) is kept as it is; any
|
||||
//! other is decoded, its Decode array applied, and stored as a CMYK TIFF
|
||||
//! ([`ImageBlob::cmyk_tiff`]). Every other image is read as RGB by the interpreter.
|
||||
//! ([`ImageBlob::cmyk_tiff`]). A mask (`/SMask`, `/Mask`) doesn't change that: the importer
|
||||
//! carries it as the image's opacity mask ([`has_mask`]). Every other image is read as RGB by the
|
||||
//! interpreter.
|
||||
|
||||
use hayro_syntax::Filter;
|
||||
use hayro_syntax::object::stream::ImageDecodeParams;
|
||||
@@ -11,7 +13,6 @@ use vectorcraft_doc::ImageBlob;
|
||||
use vectorcraft_doc::cmyk::{Inks, MAX_CMYK_PIXELS, jpeg_components};
|
||||
|
||||
/// A CMYK image read as RGB: why.
|
||||
pub(crate) const MASKED: &str = "CMYK images with a mask were imported in RGB";
|
||||
pub(crate) const UNREAD: &str = "CMYK images whose samples couldn't be read in CMYK were imported in RGB";
|
||||
|
||||
/// The Decode array of a JPEG kept as it is.
|
||||
@@ -57,9 +58,6 @@ pub(crate) fn cmyk(st: &Stream<'_>, width: u32, height: u32) -> Result<Option<Im
|
||||
if !cmyk_space(d) {
|
||||
return Ok(None);
|
||||
}
|
||||
if d.contains_key(b"SMask") || d.contains_key(b"Mask") {
|
||||
return Err(MASKED);
|
||||
}
|
||||
let ranges = decode_ranges(d);
|
||||
let filters = st.filters();
|
||||
if ranges == INVERTED && matches!(filters.as_slice(), [Filter::DctDecode]) {
|
||||
@@ -91,3 +89,9 @@ pub(crate) fn cmyk(st: &Stream<'_>, width: u32, height: u32) -> Result<Option<Im
|
||||
.collect();
|
||||
Inks::new(width, height, inks).and_then(|i| ImageBlob::cmyk_tiff(&i)).map(Some).ok_or(UNREAD)
|
||||
}
|
||||
|
||||
/// Does the image carry its own transparency (a soft mask, a stencil mask or a colour key)?
|
||||
pub(crate) fn has_mask(st: &Stream<'_>) -> bool {
|
||||
let d = st.dict();
|
||||
d.contains_key(b"SMask") || d.contains_key(b"Mask") || d.get::<u8>(b"SMaskInData").is_some_and(|v| v != 0)
|
||||
}
|
||||
@@ -375,6 +375,11 @@ impl Dest {
|
||||
};
|
||||
Color::Cmyk { c, m, y, k }
|
||||
}
|
||||
// CMYK straight into the destination RGB (the destination shares the source's CMYK).
|
||||
(_, Color::Cmyk { c, m, y, k }) => {
|
||||
let [r, g, b] = self.cms.cmyk_to_rgb([*c, *m, *y, *k], intent);
|
||||
Color::Rgb { r, g, b }
|
||||
}
|
||||
_ => {
|
||||
let [r, g, b] = self.cms.srgb_to_rgb(source.display_rgb(c));
|
||||
Color::Rgb { r, g, b }
|
||||
|
||||
@@ -212,19 +212,96 @@ fn other_cmyk_images_keep_their_ink_amounts() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmyk_images_with_a_mask_or_odd_samples_open_in_rgb_with_a_warning() {
|
||||
let inks = flat([0, 102, 255, 0], 4);
|
||||
let mask = stream("/Type /XObject /Subtype /Image /Width 2 /Height 2 /ColorSpace /DeviceGray /BitsPerComponent 8", &[255, 128, 255, 128]);
|
||||
let source = pdf_with_images(&[(cmyk_dict(2, 2, "/SMask 6 0 R /Filter /FlateDecode"), crate::output::deflate(&inks).unwrap())], &[mask]);
|
||||
let r = import_with_report(&source, &ImportOptions::default()).unwrap();
|
||||
assert_eq!(blobs(&r.document)[0].mime, "image/png");
|
||||
assert!(r.warnings.iter().any(|w| w == crate::import_image::MASKED), "{:?}", r.warnings);
|
||||
fn cmyk_images_with_odd_samples_open_in_rgb_with_a_warning() {
|
||||
let four_bits = cmyk_dict(2, 2, "").replace("/BitsPerComponent 8", "/BitsPerComponent 4");
|
||||
let r = import_with_report(&pdf_with_images(&[(four_bits, vec![0x0F; 8])], &[]), &ImportOptions::default()).unwrap();
|
||||
assert_eq!(blobs(&r.document)[0].mime, "image/png");
|
||||
assert!(r.warnings.iter().any(|w| w == crate::import_image::UNREAD), "{:?}", r.warnings);
|
||||
}
|
||||
|
||||
/// An opacity mask's image: its blob and pixel size.
|
||||
type MaskImage<'d> = (&'d ImageBlob, u32, u32);
|
||||
|
||||
/// The image nodes on the first layer: each one's blob and its opacity mask's image, if it has one.
|
||||
fn masked(d: &Document) -> Vec<(&ImageBlob, Option<MaskImage<'_>>)> {
|
||||
let NodeKind::Layer { children, .. } = &d.layers[0].kind else { panic!() };
|
||||
children
|
||||
.iter()
|
||||
.filter_map(|n| {
|
||||
let NodeKind::Image(im) = &n.kind else { return None };
|
||||
let mask = n.mask.as_ref().map(|m| match &m.art.kind {
|
||||
NodeKind::Image(a) => (&d.images[&a.key], a.width, a.height),
|
||||
other => panic!("mask art is an image: {other:?}"),
|
||||
});
|
||||
Some((&d.images[&im.key], mask))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn masked_cmyk_images_keep_their_inks_and_carry_the_mask_as_an_opacity_mask() {
|
||||
let inks = flat([0, 102, 255, 0], 4);
|
||||
let z = |data: &[u8]| crate::output::deflate(data).unwrap();
|
||||
// Object 6 (the first after the two images): a soft mask; image 2 a colour key masking its
|
||||
// first two pixels.
|
||||
let smask = stream("/Type /XObject /Subtype /Image /Width 2 /Height 2 /ColorSpace /DeviceGray /BitsPerComponent 8", &[255, 128, 255, 128]);
|
||||
let keyed: Vec<u8> = [[10, 20, 30, 40], [10, 20, 30, 40], [0, 102, 255, 0], [0, 102, 255, 0]].concat();
|
||||
let images = [
|
||||
(cmyk_dict(2, 2, "/SMask 7 0 R /Filter /FlateDecode"), z(&inks)),
|
||||
(cmyk_dict(2, 2, "/Mask [10 10 20 20 30 30 40 40] /Filter /FlateDecode"), z(&keyed)),
|
||||
];
|
||||
let source = pdf_with_images(&images, &[smask]);
|
||||
let r = import_with_report(&source, &ImportOptions::default()).unwrap();
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let m = masked(&r.document);
|
||||
assert_eq!(m.len(), 2);
|
||||
for ((blob, mask), (want, alpha)) in m.iter().zip([(&inks, [255, 128, 255, 128]), (&keyed, [0, 0, 255, 255])]) {
|
||||
assert_eq!(blob.mime, "image/tiff");
|
||||
assert!(close(&blob.cmyk().unwrap().data, want, 0), "the inks as they were");
|
||||
let (mblob, mw, mh) = mask.expect("an opacity mask");
|
||||
assert_eq!((mw, mh), (2, 2));
|
||||
let grey = image::load_from_memory(&mblob.bytes).unwrap().to_luma8();
|
||||
assert_eq!(grey.into_raw(), alpha, "the mask's values");
|
||||
}
|
||||
// The mask art covers the image exactly.
|
||||
let NodeKind::Layer { children, .. } = &r.document.layers[0].kind else { panic!() };
|
||||
let img = children.iter().find(|n| matches!(n.kind, NodeKind::Image(_))).unwrap();
|
||||
assert_eq!(img.geometric_bounds(), img.mask.as_ref().unwrap().art.geometric_bounds());
|
||||
// Written as CMYK with the mask in grey; it opens with the same inks.
|
||||
let out = export_with_report(&r.document, &opts(json!({}))).unwrap();
|
||||
let w = written(&out.bytes);
|
||||
assert!(w.iter().filter(|w| w.space == "DeviceCMYK").count() == 2 && w.iter().any(|w| w.space == "DeviceGray"), "{w:?}");
|
||||
let back = import_with_report(&out.bytes, &ImportOptions::default()).unwrap();
|
||||
let inked: Vec<Vec<u8>> = all_images(&back.document).iter().filter_map(|b| b.cmyk()).map(|i| i.data).collect();
|
||||
assert!(inked.iter().any(|d| close(d, &inks, 3)) && inked.iter().any(|d| close(d, &keyed, 3)), "{:?}", back.warnings);
|
||||
// A mask that hides nothing adds none.
|
||||
let opaque = stream("/Type /XObject /Subtype /Image /Width 2 /Height 2 /ColorSpace /DeviceGray /BitsPerComponent 8", &[255; 4]);
|
||||
let r = import_with_report(
|
||||
&pdf_with_images(&[(cmyk_dict(2, 2, "/SMask 6 0 R /Filter /FlateDecode"), z(&inks))], &[opaque]),
|
||||
&ImportOptions::default(),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(masked(&r.document)[0].1.is_none());
|
||||
}
|
||||
|
||||
/// Every image blob a document's art uses (mask art included).
|
||||
fn all_images(d: &Document) -> Vec<&ImageBlob> {
|
||||
let mut keys = vec![];
|
||||
d.walk(|n| {
|
||||
if let NodeKind::Image(im) = &n.kind {
|
||||
keys.push(im.key.clone());
|
||||
}
|
||||
if let Some(m) = &n.mask {
|
||||
m.art.walk(&mut |a| {
|
||||
if let NodeKind::Image(im) = &a.kind {
|
||||
keys.push(im.key.clone());
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
keys.iter().filter_map(|k| d.images.get(k)).collect()
|
||||
}
|
||||
|
||||
/// A document with CMYK image `blob` of `w` × `h` pixels placed 40 pt wide.
|
||||
fn image_doc(blob: ImageBlob, w: u32, h: u32) -> Document {
|
||||
let mut d = Document::new_with_mode(100.0, 100.0, ColorMode::Cmyk);
|
||||
|
||||
+203
-77
@@ -11,7 +11,12 @@
|
||||
//! - Gaussian Blur: the object painted inside a Gaussian filter layer;
|
||||
//! - Feather: like Gaussian Blur but clipped to the shape, so the edge fades inward;
|
||||
//! - Inner Glow: a blurred inverse silhouette (Edge) or the blurred silhouette (Center), clipped
|
||||
//! to the shape and painted above it.
|
||||
//! to the shape and painted above it;
|
||||
//! - Photoshop-style filters (Radial Blur, Smart Blur, Unsharp Mask…): the content is rendered
|
||||
//! offscreen and its pixels run through the content-changing effects in stack order (those
|
||||
//! filters, Gaussian Blur and Feather, see [`effects::pixel`]), then drawn back
|
||||
//! ([`Renderer::pixel_content`]). The result is cached per object while it and the zoom don't
|
||||
//! change.
|
||||
//!
|
||||
//! The same applies to one fill or stroke's own raster effects (around that item alone) and to
|
||||
//! type, images, symbol instances and live objects ([`Renderer::draw_object_fx`]): their art is
|
||||
@@ -132,8 +137,12 @@ pub(crate) fn visual_bounds(n: &Node) -> Option<Rect> {
|
||||
}
|
||||
}
|
||||
}
|
||||
let o = n.appearance.outset() + effects::outset(&n.appearance.effects);
|
||||
r.map(|r| r.inflate(o, o))
|
||||
let s = n.appearance.outset();
|
||||
r.map(|r| {
|
||||
let r = r.inflate(s, s);
|
||||
let o = effects::outset(&n.appearance.effects, r);
|
||||
r.inflate(o, o)
|
||||
})
|
||||
}
|
||||
|
||||
/// Bounds used for culling: like `Node::visual_bounds`, but aware of live effects anywhere in
|
||||
@@ -151,7 +160,7 @@ pub(crate) fn cull_bounds(n: &Node) -> Option<Rect> {
|
||||
} else {
|
||||
art.children()?.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, cull_bounds(c)))
|
||||
}?;
|
||||
let o = effects::outset(&n.appearance.effects);
|
||||
let o = effects::outset(&n.appearance.effects, b);
|
||||
Some(b.inflate(o, o))
|
||||
}
|
||||
NodeKind::Layer { children, clip: false, .. } | NodeKind::Group { children, clip: false } => {
|
||||
@@ -161,7 +170,7 @@ pub(crate) fn cull_bounds(n: &Node) -> Option<Rect> {
|
||||
// The reshaped art (a symbol's art needs the document: its instance box stands in).
|
||||
_ if has_object_fx(n) => {
|
||||
let b = effects::reshape(n, None).and_then(|r| r.visual_bounds()).or_else(|| n.visual_bounds())?;
|
||||
let o = effects::outset(&n.appearance.effects);
|
||||
let o = effects::outset(&n.appearance.effects, b);
|
||||
Some(b.inflate(o, o))
|
||||
}
|
||||
_ => n.visual_bounds(),
|
||||
@@ -187,6 +196,56 @@ fn pcolor(ink: Ink, c: &vectorcraft_doc::color::Color) -> peniko::Color {
|
||||
peniko::Color::new([r, g, b, 1.0])
|
||||
}
|
||||
|
||||
/// Most pixels the raster of [`Renderer::pixel_content`] holds (a 4K screen's): larger content is
|
||||
/// cropped to the view when its effects only look nearby, else rendered at a lower resolution.
|
||||
const PIXEL_BUDGET: f64 = 8.4e6;
|
||||
|
||||
/// The effects [`Renderer::pixel_content`] runs on the content's pixels (those changing the
|
||||
/// content itself), in stack order.
|
||||
fn content_changing(fx: &&RasterFx) -> bool {
|
||||
matches!(fx, RasterFx::Feather { .. } | RasterFx::GaussianBlur { .. } | RasterFx::Pixel(_))
|
||||
}
|
||||
|
||||
/// How far (document units) from a pixel the content deciding it after `fx` lies; `None` when
|
||||
/// anywhere in the object.
|
||||
fn looks_around(fx: &RasterFx) -> Option<f64> {
|
||||
match fx {
|
||||
RasterFx::Feather { radius } | RasterFx::GaussianBlur { radius } => Some(1.5 * radius),
|
||||
RasterFx::Pixel(p) => p.reach(),
|
||||
_ => Some(0.0),
|
||||
}
|
||||
}
|
||||
|
||||
/// The content of an object with Photoshop-style effects as filtered pixels, drawn at
|
||||
/// (`anchor`'s view position + `rel`) scaled by 1 / `k` (see [`Renderer::pixel_content`]).
|
||||
pub(crate) struct PixelEntry {
|
||||
node: Node,
|
||||
linear: [u64; 4],
|
||||
anchor: vectorcraft_geom::Point,
|
||||
rel: (f64, f64),
|
||||
k: f64,
|
||||
image: std::sync::Arc<vello_cpu::Pixmap>,
|
||||
pub(crate) stamp: u64,
|
||||
}
|
||||
|
||||
/// The four linear coefficients of `view` (zoom and rotation, not the pan), as cache keys.
|
||||
fn linear_key(view: Affine) -> [u64; 4] {
|
||||
let c = view.as_coeffs();
|
||||
[c[0].to_bits(), c[1].to_bits(), c[2].to_bits(), c[3].to_bits()]
|
||||
}
|
||||
|
||||
/// Draw `image` with its top-left at (`x`, `y`) device pixels, `1 / k` device pixels a pixel.
|
||||
fn draw_scaled(ctx: &mut RenderContext, image: std::sync::Arc<vello_cpu::Pixmap>, (x, y): (f64, f64), k: f64) {
|
||||
let (w, h) = (image.width() as f64, image.height() as f64);
|
||||
ctx.set_transform(Affine::translate((x, y)) * Affine::scale(1.0 / k));
|
||||
// On whole pixels at full size the cheapest sampler is exact.
|
||||
let quality = if k < 1.0 { peniko::ImageQuality::Medium } else { peniko::ImageQuality::Low };
|
||||
let sampler = peniko::ImageSampler { quality, ..Default::default() };
|
||||
ctx.set_paint(vello_cpu::Image { image: vello_cpu::ImageSource::Pixmap(image), sampler });
|
||||
ctx.fill_rect(&Rect::new(0.0, 0.0, w, h));
|
||||
ctx.set_transform(Affine::IDENTITY);
|
||||
}
|
||||
|
||||
/// A cached shadow / glow raster: premultiplied, already tinted and faded, positioned relative to
|
||||
/// the view-space position of `anchor` (a document point).
|
||||
pub(crate) struct ShadowEntry {
|
||||
@@ -199,73 +258,6 @@ pub(crate) struct ShadowEntry {
|
||||
pub(crate) stamp: u64,
|
||||
}
|
||||
|
||||
/// Box sizes approximating a Gaussian of `sigma` with three box blurs.
|
||||
fn gauss_boxes(sigma: f64) -> [usize; 3] {
|
||||
let n = 3.0;
|
||||
let w_ideal = (12.0 * sigma * sigma / n + 1.0).sqrt();
|
||||
let mut wl = w_ideal.floor() as i64;
|
||||
if wl % 2 == 0 {
|
||||
wl -= 1;
|
||||
}
|
||||
let wu = wl + 2;
|
||||
let m_ideal = (12.0 * sigma * sigma - n * (wl * wl) as f64 - 4.0 * n * wl as f64 - 3.0 * n) / (-4.0 * wl as f64 - 4.0);
|
||||
let m = m_ideal.round() as i64;
|
||||
let r = |i: i64| (((if i < m { wl } else { wu }) - 1) / 2).max(0) as usize;
|
||||
[r(0), r(1), r(2)]
|
||||
}
|
||||
|
||||
/// One horizontal box-blur pass of radius `r` over rows of `w` (running sum, edges as zero).
|
||||
fn box_blur_h(src: &[f32], dst: &mut [f32], w: usize, h: usize, r: usize) {
|
||||
if r == 0 {
|
||||
dst.copy_from_slice(src);
|
||||
return;
|
||||
}
|
||||
let norm = 1.0 / (2 * r + 1) as f32;
|
||||
for y in 0..h {
|
||||
let row = &src[y * w..(y + 1) * w];
|
||||
let out = &mut dst[y * w..(y + 1) * w];
|
||||
let mut acc: f32 = row.iter().take(r + 1).sum();
|
||||
for x in 0..w {
|
||||
out[x] = acc * norm;
|
||||
if x + r + 1 < w {
|
||||
acc += row[x + r + 1];
|
||||
}
|
||||
if x >= r {
|
||||
acc -= row[x - r];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn transpose(src: &[f32], dst: &mut [f32], w: usize, h: usize) {
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
dst[x * h + y] = src[y * w + x];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Gaussian-blur an alpha plane in place (three box passes per axis).
|
||||
fn blur_alpha(a: &mut Vec<f32>, w: usize, h: usize, sigma: f64) {
|
||||
if sigma < 0.2 {
|
||||
return;
|
||||
}
|
||||
let boxes = gauss_boxes(sigma);
|
||||
let mut tmp = vec![0.0; a.len()];
|
||||
for r in boxes {
|
||||
box_blur_h(a, &mut tmp, w, h, r);
|
||||
std::mem::swap(a, &mut tmp);
|
||||
}
|
||||
transpose(a, &mut tmp, w, h);
|
||||
std::mem::swap(a, &mut tmp);
|
||||
for r in boxes {
|
||||
box_blur_h(a, &mut tmp, h, w, r);
|
||||
std::mem::swap(a, &mut tmp);
|
||||
}
|
||||
transpose(a, &mut tmp, h, w);
|
||||
std::mem::swap(a, &mut tmp);
|
||||
}
|
||||
|
||||
impl Renderer {
|
||||
/// Drop shadow / outer glow `fx` (shadow-cache slot `i` of `n`) from a cached raster:
|
||||
/// the silhouette is rendered once into a small crop, blurred and tinted on the CPU, and reused
|
||||
@@ -287,8 +279,7 @@ impl Renderer {
|
||||
RasterFx::OuterGlow { mode, opacity, blur, color } => (*mode, *opacity, 0.0, 0.0, *blur, *color),
|
||||
_ => return false,
|
||||
};
|
||||
let c = f.view.as_coeffs();
|
||||
let linear = [c[0].to_bits(), c[1].to_bits(), c[2].to_bits(), c[3].to_bits()];
|
||||
let linear = linear_key(f.view);
|
||||
let key = (n as *const Node as usize, i, f.ink);
|
||||
let stamp = self.stamp;
|
||||
let hit = self.shadows.get_mut(&key).filter(|e| e.linear == linear && e.node == *n);
|
||||
@@ -317,7 +308,7 @@ impl Renderer {
|
||||
off.render(&mut pm, &mut self.resources);
|
||||
let (wu, hu) = (w as usize, h as usize);
|
||||
let mut a: Vec<f32> = pm.data().iter().map(|p| p.a as f32).collect();
|
||||
blur_alpha(&mut a, wu, hu, blur / 2.0 / f.px);
|
||||
effects::pixel::blur_plane(&mut a, wu, hu, blur / 2.0 / f.px);
|
||||
let [cr, cg, cb] = f.ink.rgb(&color);
|
||||
let tint = |v: f32, ch: f32| (v * ch).round().clamp(0.0, 255.0) as u8;
|
||||
for (px, av) in pm.data_mut().iter_mut().zip(&a) {
|
||||
@@ -504,7 +495,7 @@ impl Renderer {
|
||||
c.pop_layer();
|
||||
});
|
||||
}
|
||||
// The content itself (blurred / feathered).
|
||||
// The content itself (blurred / feathered / filtered).
|
||||
let blur: f64 = rfx
|
||||
.iter()
|
||||
.map(|fx| match fx {
|
||||
@@ -512,7 +503,9 @@ impl Renderer {
|
||||
_ => 0.0,
|
||||
})
|
||||
.sum();
|
||||
if blur > 0.0 {
|
||||
if rfx.iter().any(|fx| matches!(fx, RasterFx::Pixel(_))) {
|
||||
self.pixel_content(ctx, f, content, rfx, paint);
|
||||
} else if blur > 0.0 {
|
||||
self.with_filters(ctx, f, reach, blur, None, |r, c, fr, _| {
|
||||
let mut layers = 0;
|
||||
for fx in rfx {
|
||||
@@ -580,6 +573,105 @@ impl Renderer {
|
||||
}
|
||||
}
|
||||
|
||||
/// Paint `content` through the content-changing effects of `rfx` (Gaussian Blur, Feather and the
|
||||
/// Photoshop-style filters) in stack order on its pixels: rendered offscreen over all it can
|
||||
/// reach, filtered on the CPU and drawn back. The raster holds at most [`PIXEL_BUDGET`] pixels:
|
||||
/// larger content is cropped to the view when every effect only looks nearby, else rendered
|
||||
/// at a lower resolution. A whole raster at full resolution is cached while the object and the
|
||||
/// zoom stay the same (panning only moves it).
|
||||
fn pixel_content(
|
||||
&mut self,
|
||||
ctx: &mut RenderContext,
|
||||
f: &Frame,
|
||||
content: &Content,
|
||||
rfx: &[RasterFx],
|
||||
paint: &mut dyn FnMut(&mut Self, &mut RenderContext, &Frame),
|
||||
) {
|
||||
let chain: Vec<&RasterFx> = rfx.iter().filter(content_changing).collect();
|
||||
// Where the result can paint: each effect spreads what the ones before it painted.
|
||||
let reach = chain.iter().fold(content.reach, |r, fx| {
|
||||
let o = fx.outset(r);
|
||||
r.inflate(o, o)
|
||||
});
|
||||
let full = f.view.transform_rect_bbox(reach).inflate(2.0, 2.0);
|
||||
let (sw, sh) = (ctx.width() as f64, ctx.height() as f64);
|
||||
if !(full.area().is_finite() && full.x1 > 0.0 && full.y1 > 0.0 && full.x0 < sw && full.y0 < sh) {
|
||||
return;
|
||||
}
|
||||
let fits = full.area() <= PIXEL_BUDGET;
|
||||
// Device pixels from a pixel to the content deciding it (`None`: anywhere).
|
||||
let margin = chain.iter().try_fold(2.0, |m, fx| looks_around(fx).map(|d| m + d / f.px));
|
||||
let region = match margin {
|
||||
Some(m) if !fits => full.intersect(Rect::new(0.0, 0.0, sw, sh).inflate(m, m)),
|
||||
_ => full,
|
||||
};
|
||||
let (x0, y0) = (region.x0.floor(), region.y0.floor());
|
||||
let (rw, rh) = ((region.x1 - x0).max(1.0), (region.y1 - y0).max(1.0));
|
||||
let side = u16::MAX as f64;
|
||||
let k = (PIXEL_BUDGET / (rw * rh)).sqrt().min(side / rw).min(side / rh).min(1.0);
|
||||
let (w, h) = ((rw * k).ceil().clamp(1.0, side), (rh * k).ceil().clamp(1.0, side));
|
||||
// The cached raster, when the whole content was rendered at full size at this zoom.
|
||||
let linear = linear_key(f.view);
|
||||
let key = content.cache.filter(|_| fits && k >= 1.0).map(|slot| (content.node as *const Node as usize, slot, f.ink));
|
||||
let stamp = self.stamp;
|
||||
if let Some(e) = key.and_then(|key| self.pixel_fx.get_mut(&key)).filter(|e| e.linear == linear && e.node == *content.node) {
|
||||
e.stamp = stamp;
|
||||
let p = f.view * e.anchor;
|
||||
let (image, at, k) = (e.image.clone(), ((p.x + e.rel.0).round(), (p.y + e.rel.1).round()), e.k);
|
||||
draw_scaled(ctx, image, at, k);
|
||||
return;
|
||||
}
|
||||
let (wu, hu) = (w as u16, h as u16);
|
||||
let view = Affine::scale(k) * Affine::translate((-x0, -y0)) * f.view;
|
||||
let to_doc = view.inverse();
|
||||
let px = f.px / k;
|
||||
let frame = Frame { mt: false, view, visible: to_doc.transform_rect_bbox(Rect::new(0.0, 0.0, w, h)), px, ..*f };
|
||||
let mut off = f.offscreen_context(wu, hu);
|
||||
self.inside_layer(|r| paint(r, &mut off, &frame));
|
||||
off.flush();
|
||||
let mut pm = vello_cpu::Pixmap::new(wu, hu);
|
||||
off.render(&mut pm, &mut self.resources);
|
||||
let space = effects::PixelSpace { to_doc, px, center: content.reach.center() };
|
||||
let (wz, hz) = (wu as usize, hu as usize);
|
||||
for fx in chain {
|
||||
match fx {
|
||||
RasterFx::GaussianBlur { radius } => effects::pixel::gaussian_rgba(pm.data_as_u8_slice_mut(), wz, hz, radius / 2.0 / px),
|
||||
RasterFx::Feather { radius } => {
|
||||
effects::pixel::gaussian_rgba(pm.data_as_u8_slice_mut(), wz, hz, radius / 2.0 / px);
|
||||
if let Some((g, rule)) = content.outline {
|
||||
self.clip_pixels(&mut pm, &frame, g, rule);
|
||||
}
|
||||
}
|
||||
RasterFx::Pixel(p) => p.apply(pm.data_as_u8_slice_mut(), wz, hz, &space),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let image = std::sync::Arc::new(pm);
|
||||
if let Some(key) = key {
|
||||
let anchor = content.reach.origin();
|
||||
let p = f.view * anchor;
|
||||
let rel = (x0 - p.x, y0 - p.y);
|
||||
self.pixel_fx.insert(key, PixelEntry { node: content.node.clone(), linear, anchor, rel, k, image: image.clone(), stamp });
|
||||
}
|
||||
draw_scaled(ctx, image, (x0, y0), k);
|
||||
}
|
||||
|
||||
/// Keep `pm`'s pixels only inside `g` filled by `rule` as `frame` draws it (Feather's clip).
|
||||
fn clip_pixels(&mut self, pm: &mut vello_cpu::Pixmap, frame: &Frame, g: &BezPath, rule: FillRule) {
|
||||
let mut m = frame.offscreen_context(pm.width(), pm.height());
|
||||
m.set_transform(frame.view);
|
||||
m.set_fill_rule(fill_rule(rule));
|
||||
m.set_paint(peniko::Color::BLACK);
|
||||
m.fill_path(g);
|
||||
m.flush();
|
||||
let mut mask = vello_cpu::Pixmap::new(pm.width(), pm.height());
|
||||
m.render(&mut mask, &mut self.resources);
|
||||
for (p, c) in pm.data_mut().iter_mut().zip(mask.data()) {
|
||||
let keep = |v: u8| ((v as u32 * c.a as u32 + 127) / 255) as u8;
|
||||
*p = vello_cpu::color::PremulRgba8 { r: keep(p.r), g: keep(p.g), b: keep(p.b), a: keep(p.a) };
|
||||
}
|
||||
}
|
||||
|
||||
/// Run `draw`, which pushes filter layers. Single-threaded contexts draw directly and `draw`
|
||||
/// applies `composite` (blend mode, opacity) on its filter layer. On a multithreaded context
|
||||
/// the layer is drawn into an offscreen single-threaded context covering `reach` (document
|
||||
@@ -885,4 +977,38 @@ mod tests {
|
||||
assert!(worst <= 4, "{name}: max channel difference {worst}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn photoshop_filters_draw_and_follow_a_pan_from_the_cache() {
|
||||
let d = doc_with(Rect::new(30.0, 30.0, 70.0, 70.0), Color::BLACK, vec![("blur.radial", json!({"amount": 40, "quality": "draft"}))]);
|
||||
let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() };
|
||||
let mut r = Renderer::new();
|
||||
let a = r.render(&d, 100, 100, Affine::IDENTITY, &opts);
|
||||
assert!(lum(a.pixel(31, 31)) > 60, "the spin softens the corners: {:?}", a.pixel(31, 31));
|
||||
assert_eq!(lum(a.pixel(50, 50)), 0, "the centre stays");
|
||||
assert!(lum(a.pixel(50, 28)) < WHITE, "turned corners reach past the sides");
|
||||
// Panned: the cached raster moves with the view.
|
||||
let b = r.render(&d, 100, 100, Affine::translate((10.0, 3.0)), &opts);
|
||||
for (x, y) in [(31, 31), (50, 28), (69, 50), (40, 66)] {
|
||||
assert_eq!(a.pixel(x, y), b.pixel(x + 10, y + 3), "({x}, {y})");
|
||||
}
|
||||
// A fresh renderer draws the panned view the same.
|
||||
let c = Renderer::new().render(&d, 100, 100, Affine::translate((10.0, 3.0)), &opts);
|
||||
assert_eq!(b.pixels, c.pixels);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn photoshop_filters_on_content_larger_than_the_budget() {
|
||||
// Zoomed in 200×: the 40 pt square covers 8000 × 8000 px around a 200 × 200 view.
|
||||
let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() };
|
||||
let view = Affine::translate((100.0, 100.0)) * Affine::scale(200.0) * Affine::translate((-70.0, -50.0));
|
||||
for (id, p) in [("sharpen.unsharpMask", json!({"amount": 200})), ("blur.smart", json!({})), ("blur.radial", json!({"quality": "draft"}))] {
|
||||
let d = doc_with(Rect::new(30.0, 30.0, 70.0, 70.0), Color::rgb(0.2, 0.4, 0.8), vec![(id, p)]);
|
||||
let img = Renderer::new().render(&d, 200, 200, view, &opts);
|
||||
// The view shows the square's right side half way down: inside left, outside right.
|
||||
assert!(lum(img.pixel(40, 100)) < 600, "{id}: inside {:?}", img.pixel(40, 100));
|
||||
// (Smart Blur's wide samples read a blurred copy: a faint fringe under its threshold.)
|
||||
assert!(lum(img.pixel(190, 100)) >= WHITE - 3 * 25, "{id}: outside {:?}", img.pixel(190, 100));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -316,6 +316,9 @@ pub struct Renderer {
|
||||
live: live::LiveCache,
|
||||
/// Blurred, tinted drop shadow / outer glow rasters per object and effect (see `fx`).
|
||||
shadows: PtrMap<(usize, usize, Ink), fx::ShadowEntry>,
|
||||
/// Objects' content run through Photoshop-style effects, per object and content slot (see
|
||||
/// `fx`): kept only while drawn.
|
||||
pixel_fx: PtrMap<(usize, usize, Ink), fx::PixelEntry>,
|
||||
/// Whether the group being drawn is a knockout group (what its neutral children inherit).
|
||||
knockout: bool,
|
||||
/// Address of the knockout-group element being drawn as its knockout shape: at full object
|
||||
@@ -421,6 +424,7 @@ impl Renderer {
|
||||
stats: FrameStats::default(),
|
||||
brushes: Default::default(),
|
||||
shadows: PtrMap::default(),
|
||||
pixel_fx: PtrMap::default(),
|
||||
live: live::LiveCache::default(),
|
||||
knockout: false,
|
||||
shape_of: 0,
|
||||
@@ -491,6 +495,8 @@ impl Renderer {
|
||||
if self.shadows.len() > 256 {
|
||||
self.shadows.retain(|_, e| g - e.stamp <= 3);
|
||||
}
|
||||
// Filtered rasters are large: only those of the last frame stay.
|
||||
self.pixel_fx.retain(|_, e| e.stamp == g);
|
||||
if !inks {
|
||||
proof::post(&mut pixels, opts);
|
||||
}
|
||||
|
||||
@@ -584,6 +584,7 @@ impl Rules<'_> {
|
||||
}
|
||||
RasterFx::GaussianBlur { radius } => filter = Some(format!("blur({})", self.len(radius / 2.0))),
|
||||
RasterFx::InnerGlow { .. } | RasterFx::Feather { .. } => art.unsupported("inner glows or feathering"),
|
||||
RasterFx::Pixel(_) => art.unsupported("Photoshop-style raster effects"),
|
||||
}
|
||||
}
|
||||
if !shadows.is_empty() {
|
||||
|
||||
@@ -1486,7 +1486,9 @@ impl Writer<'_> {
|
||||
}
|
||||
|
||||
/// Raster effects (drop shadow, glows, Gaussian blur, feather) as SVG filters: one `<g filter>`
|
||||
/// per effect, the first effect innermost (the reference app's stacking order).
|
||||
/// per effect, the first effect innermost (the reference app's stacking order). Photoshop-style
|
||||
/// filters have no SVG equivalent: they are left out with a warning (exports from the app turn
|
||||
/// such objects into images first).
|
||||
fn filtered(&mut self, n: &Node) {
|
||||
let mut inner = n.clone();
|
||||
inner.appearance.effects.retain(|e| !vectorcraft_effects::is_raster(&e.id));
|
||||
@@ -1506,9 +1508,15 @@ impl Writer<'_> {
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
let reach: f64 = fx.iter().map(RasterFx::outset).sum::<f64>() + 2.0;
|
||||
let region = n.visual_bounds().map(|b| self.xf.transform_rect_bbox(b).inflate(reach, reach));
|
||||
let bounds = n.visual_bounds();
|
||||
let reach: f64 = fx.iter().map(|f| f.outset(bounds.unwrap_or_default())).sum::<f64>() + 2.0;
|
||||
let region = bounds.map(|b| self.xf.transform_rect_bbox(b).inflate(reach, reach));
|
||||
let mut opened = 0;
|
||||
for f in fx.iter().rev() {
|
||||
if matches!(f, RasterFx::Pixel(_)) {
|
||||
self.warn("SVG has no Photoshop-style raster effects (Radial Blur, Smart Blur, Unsharp Mask…): they are left out");
|
||||
continue;
|
||||
}
|
||||
let fid = self.fresh_id("filter");
|
||||
let region_attr = match region {
|
||||
Some(r) => format!(
|
||||
@@ -1557,6 +1565,7 @@ impl Writer<'_> {
|
||||
sd(*radius)
|
||||
),
|
||||
RasterFx::GaussianBlur { radius } => format!("<feGaussianBlur in=\"SourceGraphic\" stdDeviation=\"{}\"/>", sd(*radius)),
|
||||
RasterFx::Pixel(_) => continue,
|
||||
};
|
||||
// Filters composite normally: a shadow's or glow's other blend mode is recorded for import.
|
||||
let mode = match f {
|
||||
@@ -1570,8 +1579,9 @@ impl Writer<'_> {
|
||||
self.def(1, &format!("<filter id=\"{fid}\"{region_attr}{mode} color-interpolation-filters=\"sRGB\">{body}</filter>"));
|
||||
self.line(&format!("<g filter=\"url(#{fid})\">"));
|
||||
self.depth += 1;
|
||||
opened += 1;
|
||||
}
|
||||
fx.len()
|
||||
opened
|
||||
}
|
||||
|
||||
fn close_filters(&mut self, opened: usize) {
|
||||
|
||||
@@ -878,6 +878,31 @@ pub fn set_platform_font_files(list: PlatformFontFiles) {
|
||||
let _ = list;
|
||||
}
|
||||
|
||||
/// Folders the user adds to the font scan (Preferences › Type › Additional Fonts Folder, #683),
|
||||
/// read with their subfolders after the platform's.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
static USER_FONT_DIRS: std::sync::RwLock<Vec<PathBuf>> = std::sync::RwLock::new(Vec::new());
|
||||
|
||||
/// Have [`system_font_dirs`] also read `dirs` (#683), so the fonts in them are listed and used as
|
||||
/// if installed. The next check for installed fonts ([`FontDb::installed_fonts_changed`]) then
|
||||
/// reports the change, and a scan catalogs them.
|
||||
pub fn set_user_font_dirs(dirs: Vec<PathBuf>) {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
*USER_FONT_DIRS.write().unwrap_or_else(std::sync::PoisonError::into_inner) = dirs;
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let _ = dirs;
|
||||
}
|
||||
|
||||
/// The folders [`set_user_font_dirs`] added (none on wasm).
|
||||
pub fn user_font_dirs() -> Vec<PathBuf> {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
return USER_FONT_DIRS.read().unwrap_or_else(std::sync::PoisonError::into_inner).clone();
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
/// 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`].
|
||||
@@ -926,6 +951,7 @@ pub fn system_font_dirs() -> Vec<PathBuf> {
|
||||
let files = fonts_outside(list(), &dirs);
|
||||
dirs.extend(files);
|
||||
}
|
||||
dirs.extend(user_font_dirs());
|
||||
dirs
|
||||
}
|
||||
|
||||
|
||||
@@ -25,8 +25,8 @@ pub mod thread;
|
||||
pub use craft_fonts::{CRAFT_FONTS, CraftFont};
|
||||
pub use features::{LIGATURE_TRACKING_LIMITS, OtFeatures, explicit_ligatures, ligatures_suppressed_by};
|
||||
pub use fontdb::{
|
||||
FALLBACK_FAMILY, FontClass, FontDb, FontFace, FontMatch, FontTraits, IcfMargins, PlatformFontFiles, set_platform_font_files, style_weight,
|
||||
system_font_dirs,
|
||||
FALLBACK_FAMILY, FontClass, FontDb, FontFace, FontMatch, FontTraits, IcfMargins, PlatformFontFiles, set_platform_font_files, set_user_font_dirs,
|
||||
style_weight, system_font_dirs, user_font_dirs,
|
||||
};
|
||||
use kurbo::{Affine, BezPath, Point, Rect, Vec2};
|
||||
pub use layout::{layout, layout_with};
|
||||
|
||||
@@ -319,6 +319,10 @@ fn tab_title(d: &vectorcraft_engine::DocState, zoom: f64, outline: bool) -> Stri
|
||||
format!("{}{} @ {} ({mode})", d.title(), if d.is_dirty() { "*" } else { "" }, zoom_label(zoom).replace('%', " %"))
|
||||
}
|
||||
|
||||
/// Whether a document tab's × comes before its title (macOS) rather than after it (Windows,
|
||||
/// Linux and the web).
|
||||
const CLOSE_BEFORE_TITLE: bool = cfg!(target_os = "macos");
|
||||
|
||||
/// Document tab strip: "Name* @ 66.67% (RGB/Preview)". User Interface › Large Tabs makes the tabs
|
||||
/// taller, with larger titles.
|
||||
pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
@@ -346,11 +350,13 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
ui.painter().rect_filled(r, 0.0, t.hover.gamma_multiply(0.4));
|
||||
}
|
||||
ui.painter().line_segment([r.right_top(), r.right_bottom()], Stroke::new(1.5, t.border));
|
||||
// × at the left like Illustrator.
|
||||
let xr = egui::Rect::from_center_size(egui::pos2(r.left() + 16.0, r.center().y), vec2(12.0, 12.0));
|
||||
// The × where each platform puts a tab's: before the title on macOS, after it elsewhere
|
||||
// (#673).
|
||||
let (x_center, title_left) = if CLOSE_BEFORE_TITLE { (r.left() + 16.0, r.left() + 32.0) } else { (r.right() - 16.0, r.left() + 14.0) };
|
||||
let xr = egui::Rect::from_center_size(egui::pos2(x_center, r.center().y), vec2(12.0, 12.0));
|
||||
let xresp = ui.interact(xr.expand(3.0), ui.id().with(("tabx", i)), Sense::click());
|
||||
icons::paint(ui, "x", xr, if xresp.hovered() { t.text_strong } else { t.text });
|
||||
ui.painter().galley(egui::pos2(r.left() + 32.0, r.center().y - galley.size().y / 2.0), galley, t.text);
|
||||
ui.painter().galley(egui::pos2(title_left, r.center().y - galley.size().y / 2.0), galley, t.text);
|
||||
if xresp.clicked() {
|
||||
close = Some(i);
|
||||
} else if resp.clicked() {
|
||||
@@ -782,6 +788,44 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A document tab's × sits where the platform puts it (#673): after the title on Windows,
|
||||
/// Linux and the web, before it on macOS; clicking it closes that document.
|
||||
#[test]
|
||||
fn a_tabs_close_box_sits_where_the_platform_puts_it() {
|
||||
let mut app = crate::VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 200.0));
|
||||
let frame = |app: &mut crate::VectorcraftApp, events: Vec<egui::Event>| {
|
||||
let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }, |ui| super::doc_tabs(app, ui));
|
||||
out.textures_delta.clear();
|
||||
let mut titles = vec![];
|
||||
for c in &out.shapes {
|
||||
// The titles, not the × icons.
|
||||
if let egui::Shape::Text(t) = &c.shape
|
||||
&& t.visual_bounding_rect().width() > 30.0
|
||||
{
|
||||
titles.push(t.visual_bounding_rect());
|
||||
}
|
||||
}
|
||||
titles.sort_by(|a, b| a.left().total_cmp(&b.left()));
|
||||
titles
|
||||
};
|
||||
let titles = frame(&mut app, vec![]);
|
||||
assert_eq!(titles.len(), 2, "{titles:?}");
|
||||
// The first tab's ×: 20 pt past its title's end, or 16 pt before its start.
|
||||
let first = titles[0];
|
||||
let x = if super::CLOSE_BEFORE_TITLE { first.left() - 16.0 } else { first.right() + 20.0 };
|
||||
let at = egui::pos2(x, first.center().y);
|
||||
let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
|
||||
frame(&mut app, vec![egui::Event::PointerMoved(at), press(true)]);
|
||||
frame(&mut app, vec![press(false)]);
|
||||
assert_eq!(app.session.documents().len(), 1, "the × closed the first document");
|
||||
assert!(super::CLOSE_BEFORE_TITLE == cfg!(target_os = "macos"));
|
||||
}
|
||||
|
||||
/// One headless frame of the status bar; returns the artboard navigator's buttons, left to
|
||||
/// right: first, previous, next, last.
|
||||
fn navigator(app: &mut crate::VectorcraftApp, ctx: &egui::Context, events: Vec<egui::Event>) -> Vec<egui::Rect> {
|
||||
|
||||
@@ -12,7 +12,7 @@ pub(super) const SPEC: DialogSpec = DialogSpec {
|
||||
body: |app, ui, d| {
|
||||
let command = d.str("__command");
|
||||
let lengths = lengths(&command);
|
||||
form::param_fields(ui, d, &|k| lengths.contains(&k), &|k| choices(&command, k), app.session.general_unit());
|
||||
form::param_fields(ui, d, &|k| lengths.contains(&k), &|k| choices(&command, k), &|_| 0, app.session.general_unit());
|
||||
false
|
||||
},
|
||||
confirm,
|
||||
@@ -24,7 +24,6 @@ fn lengths(command: &str) -> &'static [&'static str] {
|
||||
match command {
|
||||
"graph.create" => &["width", "height"],
|
||||
"shape.flare" => &["diameter", "pathLength"],
|
||||
"artboard.rearrange" => &["spacing"],
|
||||
"perspective.grid.set" => &["cell", "distance"],
|
||||
"object.repeat.options" => &["radius", "hSpacing", "vSpacing"],
|
||||
"text.areaOptions" => &["width", "height", "gutter", "inset", "firstBaselineMin"],
|
||||
|
||||
@@ -131,7 +131,11 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
let changed = match vectorcraft_plugins::effect::installed(&id) {
|
||||
Some(plugin) => form::schema_fields(ui, d, &plugin.manifest().params),
|
||||
None if vectorcraft_effects::is_adjustment(&id) => adjust_fields(ui, d),
|
||||
None => form::param_fields(ui, d, &|k| vectorcraft_effects::is_length(&id, k, relative), &|_| None, app.session.general_unit()),
|
||||
None => {
|
||||
let doc = vectorcraft_effects::effect_info(&id).map(|e| e.params).unwrap_or_default();
|
||||
let unit = app.session.general_unit();
|
||||
form::param_fields(ui, d, &|k| vectorcraft_effects::is_length(&id, k, relative), &|k| choices(&id, k), &|k| doc_rank(doc, k), unit)
|
||||
}
|
||||
};
|
||||
ui.add_space(6.0);
|
||||
let mut pv = d.bool("preview");
|
||||
@@ -148,6 +152,26 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// The parameters of the effect dialogs that pick one of some values, as (label, value).
|
||||
fn choices(effect: &str, key: &str) -> Option<form::Choices> {
|
||||
match (effect, key) {
|
||||
("blur.radial", "method") => Some(&[("Spin", "spin"), ("Zoom", "zoom")]),
|
||||
("blur.radial", "quality") => Some(&[("Draft", "draft"), ("Good", "good"), ("Best", "best")]),
|
||||
("blur.smart", "quality") => Some(&[("Low", "low"), ("Medium", "medium"), ("High", "high")]),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Where parameter `key` comes in the effect's parameter documentation `doc` (`{radius: …,
|
||||
/// threshold: …}`), which lists them in its dialog's order; the end when it isn't there.
|
||||
pub(super) fn doc_rank(doc: &str, key: &str) -> usize {
|
||||
let starts = |at: usize| doc.get(..at).and_then(|s| s.chars().last()).is_some_and(|c| c == '{' || c == ' ');
|
||||
doc.match_indices(key)
|
||||
.map(|(at, _)| at)
|
||||
.find(|at| starts(*at) && doc.get(at + key.len()..).is_some_and(|rest| rest.starts_with(':') || rest.starts_with("?:")))
|
||||
.unwrap_or(usize::MAX)
|
||||
}
|
||||
|
||||
/// A slider of a colour adjustment dialog: (effect, field, label, range, rail colour at 0..1).
|
||||
type Slider = (&'static str, &'static str, &'static str, (f64, f64), fn(f32) -> egui::Color32);
|
||||
|
||||
|
||||
@@ -197,19 +197,22 @@ pub(super) type Choices = &'static [(&'static str, &'static str)];
|
||||
|
||||
/// Generic editor for command/effect parameters: numbers, booleans, strings and colours; the
|
||||
/// parameters `is_length` names are distances shown and typed in `unit`, those `choices` gives
|
||||
/// choices for are dropdowns. Returns true when a value changed.
|
||||
/// choices for are dropdowns. Fields come in `rank` order (by name among equals). Returns true when
|
||||
/// a value changed.
|
||||
pub(super) fn param_fields(
|
||||
ui: &mut egui::Ui,
|
||||
d: &mut Dialog,
|
||||
is_length: &dyn Fn(&str) -> bool,
|
||||
choices: &dyn Fn(&str) -> Option<Choices>,
|
||||
rank: &dyn Fn(&str) -> usize,
|
||||
unit: Unit,
|
||||
) -> bool {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let mut changed = false;
|
||||
egui::Grid::new("fxgrid").num_columns(2).spacing([12.0, 8.0]).show(ui, |ui| {
|
||||
let keys: Vec<(String, Value)> =
|
||||
let mut keys: Vec<(String, Value)> =
|
||||
d.fields.iter().filter(|(k, _)| !k.starts_with("__") && k.as_str() != "preview").map(|(k, v)| (k.clone(), v.clone())).collect();
|
||||
keys.sort_by_key(|(k, _)| rank(k));
|
||||
for (k, v) in keys {
|
||||
ui.label(egui::RichText::new(humanized(&k)).color(t.text));
|
||||
if let Some(cur) = crate::widgets::blend_param(&k, &v) {
|
||||
|
||||
@@ -60,6 +60,7 @@ pub mod print;
|
||||
pub mod print_presets;
|
||||
mod psd_options;
|
||||
pub mod raster_effects;
|
||||
pub mod rearrange_artboards;
|
||||
pub mod recolor;
|
||||
mod recovery;
|
||||
pub mod saturate;
|
||||
@@ -278,6 +279,7 @@ registry! {
|
||||
PerspectivePlane: [perspective_plane::KIND] => perspective_plane::SPEC,
|
||||
LayerOptions: [layer_options::KIND] => layer_options::SPEC,
|
||||
LayersPanelOptions: [layers_panel_options::KIND] => layers_panel_options::SPEC,
|
||||
RearrangeArtboards: [rearrange_artboards::KIND] => rearrange_artboards::SPEC,
|
||||
}
|
||||
|
||||
/// The button labels the shared dialog frame can show (OK, discard and the fixed Cancel/Close),
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
//! Object → Artboards → Rearrange All Artboards (also the Artboards panel's button and menu, and
|
||||
//! the Properties panel's Rearrange All): Layout (a grid by row or by column, one row or one
|
||||
//! column), Layout Order (left to right or right to left), Columns (Rows for a grid by column),
|
||||
//! Spacing and Move Artwork with Artboard, with the document's artboard count. OK runs
|
||||
//! `artboard.rearrange` as one undo step (#681).
|
||||
//!
|
||||
//! Fields: `layout` (`gridByRow` | `gridByColumn` | `row` | `column`), `order` (`leftToRight` |
|
||||
//! `rightToLeft`), `columns` (the rows of a grid by column), `spacing` (pt) and `moveArtwork`.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_engine::cmd::newdoc::ArtboardLayout;
|
||||
|
||||
use super::{DialogSpec, form, run_and_close};
|
||||
use crate::state::Dialog;
|
||||
use crate::{VectorcraftApp, widgets};
|
||||
|
||||
/// The dialog kind of Rearrange All Artboards.
|
||||
pub const KIND: &str = "rearrangeArtboards";
|
||||
|
||||
const CMD: &str = "artboard.rearrange";
|
||||
|
||||
/// Width of the label column.
|
||||
const LABEL_W: f32 = 96.0;
|
||||
|
||||
pub(super) const SPEC: DialogSpec =
|
||||
DialogSpec { heading: |_| tl!("Rearrange All Artboards").into(), body, confirm, min_width: 320.0, ..DialogSpec::FORM };
|
||||
|
||||
/// The fields a fresh dialog starts with.
|
||||
pub fn fields() -> Value {
|
||||
json!({"layout": "gridByRow", "order": "leftToRight", "columns": 2, "spacing": 20, "moveArtwork": true})
|
||||
}
|
||||
|
||||
/// A layout's toggle: its tooltip and its artboards' cells (column, row) in their order, left to
|
||||
/// right.
|
||||
fn layout_glyph(l: ArtboardLayout) -> (&'static str, &'static [(u8, u8)]) {
|
||||
match l {
|
||||
ArtboardLayout::GridByRow => (tl!("Grid by Row"), &[(0, 0), (1, 0), (0, 1), (1, 1)]),
|
||||
ArtboardLayout::GridByColumn => (tl!("Grid by Column"), &[(0, 0), (0, 1), (1, 0), (1, 1)]),
|
||||
ArtboardLayout::Row => (tl!("Arrange by Row"), &[(0, 0), (1, 0), (2, 0)]),
|
||||
ArtboardLayout::Column => (tl!("Arrange by Column"), &[(0, 0), (0, 1), (0, 2)]),
|
||||
}
|
||||
}
|
||||
|
||||
/// `cells` mirrored left to right when `rtl` (the order the layout toggles preview).
|
||||
fn mirrored(cells: &[(u8, u8)], rtl: bool) -> Vec<(u8, u8)> {
|
||||
let last = cells.iter().map(|c| c.0).max().unwrap_or(0);
|
||||
cells.iter().map(|&(x, y)| (if rtl { last - x } else { x }, y)).collect()
|
||||
}
|
||||
|
||||
/// `artboard.rearrange` parameters from the fields.
|
||||
fn params(d: &Dialog) -> Value {
|
||||
json!({
|
||||
"layout": d.str("layout"), "order": d.str("order"), "columns": d.f64("columns", 2.0),
|
||||
"spacing": d.f64("spacing", 20.0), "moveArtwork": d.bool("moveArtwork"),
|
||||
})
|
||||
}
|
||||
|
||||
fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
let unit = app.session.general_unit();
|
||||
let n = app.session.active().map_or(0, |doc| doc.doc.artboards.len());
|
||||
let layout = ArtboardLayout::parse(&d.str("layout")).unwrap_or_default();
|
||||
let rtl = d.str("order") == "rightToLeft";
|
||||
widgets::label_row(ui, tl!("Layout:"), LABEL_W, |ui| {
|
||||
ui.spacing_mut().item_spacing.x = 2.0;
|
||||
for l in ArtboardLayout::ALL {
|
||||
let (tip, cells) = layout_glyph(l);
|
||||
if widgets::layout_button(ui, &mirrored(cells, rtl), layout == l, tip) {
|
||||
d.fields.insert("layout".into(), json!(l.id()));
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
widgets::label_row(ui, tl!("Layout Order:"), LABEL_W, |ui| {
|
||||
ui.spacing_mut().item_spacing.x = 2.0;
|
||||
// One column reads the same either way.
|
||||
ui.add_enabled_ui(layout != ArtboardLayout::Column, |ui| {
|
||||
for (value, cells, tip) in [
|
||||
("leftToRight", [(0, 0), (1, 0)], tl!("Change to Left-to-Right Layout")),
|
||||
("rightToLeft", [(1, 0), (0, 0)], tl!("Change to Right-to-Left Layout")),
|
||||
] {
|
||||
if widgets::layout_button(ui, &cells, (value == "rightToLeft") == rtl, tip) {
|
||||
d.fields.insert("order".into(), json!(value));
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
// The rows of a grid by column; one row or column has no count to set.
|
||||
let label = if layout == ArtboardLayout::GridByColumn { tl!("Rows:") } else { tl!("Columns:") };
|
||||
widgets::label_row(ui, label, LABEL_W, |ui| {
|
||||
let grid = matches!(layout, ArtboardLayout::GridByRow | ArtboardLayout::GridByColumn);
|
||||
ui.add_enabled_ui(grid, |ui| {
|
||||
let most = n.max(1) as f64;
|
||||
if let Some(v) = widgets::spin_plain(ui, "rearrange-columns", d.f64("columns", 2.0), "", 0, 76.0, 1.0, 1.0, &[]) {
|
||||
d.fields.insert("columns".into(), json!(v.round().clamp(1.0, most)));
|
||||
}
|
||||
});
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
widgets::label_row(ui, tl!("Spacing:"), LABEL_W, |ui| {
|
||||
form::length(ui, d, "spacing", unit, 100.0);
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
widgets::label_row(ui, tl!("Options:"), LABEL_W, |ui| {
|
||||
form::check(ui, d, "moveArtwork", tl!("Move Artwork with Artboard"));
|
||||
});
|
||||
ui.add_space(8.0);
|
||||
widgets::dim_label(ui, &crate::i18n::fmt(tl!("Artboards: {n}"), &[("n", &n.to_string())]));
|
||||
false
|
||||
}
|
||||
|
||||
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
|
||||
run_and_close(app, CMD, params(d))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use vectorcraft_engine::Session;
|
||||
|
||||
/// A frame of the open dialog with `events` → the texts painted. The dialog measures itself on
|
||||
/// its first frame, so a fresh context needs two.
|
||||
fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec<egui::Event>) -> Vec<String> {
|
||||
let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| super::super::show(app, ui.ctx()));
|
||||
out.textures_delta.clear();
|
||||
out.shapes.iter().filter_map(|s| if let egui::epaint::Shape::Text(t) = &s.shape { Some(t.galley.text().to_string()) } else { None }).collect()
|
||||
}
|
||||
|
||||
fn context() -> egui::Context {
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
ctx
|
||||
}
|
||||
|
||||
fn origins(app: &VectorcraftApp) -> Vec<(f64, f64)> {
|
||||
app.session.active().unwrap().doc.artboards.iter().map(|a| (a.rect.x0, a.rect.y0)).collect()
|
||||
}
|
||||
|
||||
/// #681: the menu item opens the dialog with the artboard count; Columns reads Rows for a grid
|
||||
/// by column; OK lays the artboards out right to left, as one undo step.
|
||||
#[test]
|
||||
fn opens_from_the_menu_and_rearranges_by_layout_and_order() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 100, "height": 50, "artboards": 3})).unwrap();
|
||||
// The menu item has no params of its own: it opens this dialog, not the generic one.
|
||||
let (id, p) = crate::menus::click_target("Rearrange All Artboards…", CMD, &Value::Null);
|
||||
crate::menus::invoke(&mut app, &id, p);
|
||||
assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(KIND));
|
||||
let ctx = context();
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
let texts = frame(&mut app, &ctx, vec![]);
|
||||
for want in ["Rearrange All Artboards", "Layout:", "Layout Order:", "Columns:", "Spacing:", "Move Artwork with Artboard", "Artboards: 3"] {
|
||||
assert!(texts.iter().any(|t| t == want), "{want:?} in {texts:?}");
|
||||
}
|
||||
let d = app.ui.dialog.as_mut().unwrap();
|
||||
d.fields.insert("layout".into(), json!("gridByColumn"));
|
||||
let texts = frame(&mut app, &ctx, vec![]);
|
||||
assert!(texts.iter().any(|t| t == "Rows:") && !texts.iter().any(|t| t == "Columns:"), "{texts:?}");
|
||||
// One row, right to left, 10 pt apart.
|
||||
let d = app.ui.dialog.as_mut().unwrap();
|
||||
d.fields.insert("layout".into(), json!("row"));
|
||||
d.fields.insert("order".into(), json!("rightToLeft"));
|
||||
d.fields.insert("spacing".into(), json!(10));
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
let undo = app.session.doc().unwrap().history.undo.len();
|
||||
crate::dialogs::confirm(&mut app).unwrap();
|
||||
assert!(app.ui.dialog.is_none());
|
||||
assert_eq!(origins(&app), [(220.0, 0.0), (110.0, 0.0), (0.0, 0.0)]);
|
||||
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1);
|
||||
}
|
||||
|
||||
/// Clicking the layout and order toggles sets the fields (the toggles' rects from the frame).
|
||||
#[test]
|
||||
fn the_toggles_set_layout_and_order() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 100, "height": 50, "artboards": 4})).unwrap();
|
||||
app.run("ui.menuDialog", json!({ "command": CMD })).unwrap();
|
||||
let ctx = context();
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
// The 26-point toggles, left to right then top to bottom: four layouts, then two orders.
|
||||
let toggles: Vec<egui::Rect> = ctx.viewport(|vp| {
|
||||
let mut r: Vec<egui::Rect> = vp
|
||||
.prev_pass
|
||||
.widgets
|
||||
.layers()
|
||||
.flat_map(|(_, w)| w.iter())
|
||||
.filter(|w| w.sense.senses_click() && w.rect.width() == 26.0 && w.rect.height() == 26.0)
|
||||
.map(|w| w.rect)
|
||||
.collect();
|
||||
r.sort_by(|a, b| a.top().total_cmp(&b.top()).then(a.left().total_cmp(&b.left())));
|
||||
r
|
||||
});
|
||||
assert_eq!(toggles.len(), 6, "{toggles:?}");
|
||||
for (i, key, want) in [(3, "layout", "column"), (1, "layout", "gridByColumn"), (5, "order", "rightToLeft")] {
|
||||
let at = toggles[i].center();
|
||||
let b = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
|
||||
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at), b(true)]);
|
||||
frame(&mut app, &ctx, vec![b(false)]);
|
||||
assert_eq!(app.ui.dialog.as_ref().unwrap().str(key), want);
|
||||
// A frame for the order toggles to follow the layout (one column greys them).
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
}
|
||||
crate::dialogs::confirm(&mut app).unwrap();
|
||||
// Two rows (Columns 2 reads Rows for a grid by column), the first column at the right.
|
||||
assert_eq!(origins(&app), [(120.0, 0.0), (120.0, 70.0), (0.0, 0.0), (0.0, 70.0)]);
|
||||
}
|
||||
}
|
||||
@@ -166,6 +166,30 @@ fn effect_preview_is_kept_as_one_undo_step() {
|
||||
assert_eq!(app.session.doc().unwrap().doc, before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn raster_filter_dialogs_preview_and_apply() {
|
||||
for (effect, key, value) in [("blur.radial", "method", "zoom"), ("blur.smart", "quality", "high"), ("sharpen.unsharpMask", "amount", "120")] {
|
||||
let mut app = app();
|
||||
let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap();
|
||||
app.run("select.all", json!({})).unwrap();
|
||||
app.run("effect.dialog", json!({"effect": effect})).unwrap();
|
||||
let d = app.ui.dialog.as_mut().unwrap();
|
||||
let v: serde_json::Value = value.parse::<f64>().map_or_else(|_| json!(value), |n| json!(n));
|
||||
d.fields.insert(key.into(), v.clone());
|
||||
frame(&mut app, Default::default());
|
||||
assert!(app.session.in_interaction(), "{effect}: previews");
|
||||
confirm(&mut app).unwrap();
|
||||
let n = app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().clone();
|
||||
assert_eq!(n.appearance.effects.len(), 1, "{effect}");
|
||||
assert_eq!(n.appearance.effects[0].params[key], v, "{effect}");
|
||||
}
|
||||
// Fields follow the effect's documented order (its dialog's), not the alphabet.
|
||||
let doc = vectorcraft_effects::effect_info("blur.smart").unwrap().params;
|
||||
let ranks: Vec<usize> = ["radius", "threshold", "quality"].iter().map(|k| super::effect::doc_rank(doc, k)).collect();
|
||||
assert!(ranks.windows(2).all(|w| w[0] < w[1]), "{ranks:?}");
|
||||
assert_eq!(super::effect::doc_rank(doc, "nope"), usize::MAX);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn effect_dialog_applies_to_its_appearance_item() {
|
||||
let mut app = app();
|
||||
|
||||
@@ -643,3 +643,9 @@
|
||||
Constrain Omezit
|
||||
Free Transform Volná transformace
|
||||
Perspective Distort Perspektivní deformace
|
||||
|
||||
# Photoshop-style raster effects (Effect menu, their dialogs).
|
||||
Radial Blur… Radiální rozostření…
|
||||
Smart Blur… Chytré rozostření…
|
||||
Sharpen Zostření
|
||||
Unsharp Mask… Maska rozostření…
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -11,6 +11,23 @@
|
||||
# Coverage: the whole interface — every menu string and every `tl!` literal (`complete_menus`,
|
||||
# tested). Left in English on purpose (`MENU_KEEP_AS_IS` in the tests): the product name, language
|
||||
# names, OpenType, the built-in workspace names and the bracketed perspective grid preset names.
|
||||
# Photoshop-style raster effects (Effect menu, their dialogs).
|
||||
Radial Blur… Desenfoque radial…
|
||||
Smart Blur… Desenfoque inteligente…
|
||||
Sharpen Enfocar
|
||||
Unsharp Mask… Máscara de enfoque…
|
||||
Radial Blur Desenfoque radial
|
||||
Smart Blur Desenfoque inteligente
|
||||
Unsharp Mask Máscara de enfoque
|
||||
Gaussian Blur Desenfoque gaussiano
|
||||
Method Método
|
||||
Quality Calidad
|
||||
Radius Radio
|
||||
Spin Giro
|
||||
Draft Borrador
|
||||
Good Buena
|
||||
Best Óptima
|
||||
|
||||
# Status and error messages too (`@msg` rows at the end, `COMPLETE_MESSAGES` in the tests).
|
||||
# A native speaker's review is welcome: keep the placeholders ({name}), the trailing "…" and the
|
||||
# leading/trailing spaces of fragments exactly as they are.
|
||||
@@ -76,6 +93,7 @@
|
||||
Add to Swatches Agregar a muestras
|
||||
Add Used Colors Agregar colores usados
|
||||
Additional Plug-ins Folder Carpeta de plugins adicionales
|
||||
Additional Fonts Folder Carpeta de fuentes adicionales
|
||||
Adjust Adjoining Width Points Ajustar puntos de anchura contiguos
|
||||
Adjust Color Balance… Ajustar equilibrio de color…
|
||||
Adjust Colors Ajustar colores
|
||||
@@ -202,6 +220,7 @@
|
||||
Auto Size New Area Type Ajustar automáticamente el tamaño del nuevo texto de área
|
||||
Auto Spell Check Revisión ortográfica automática
|
||||
Auto-Collapse Iconic Panels Contraer automáticamente los paneles de iconos
|
||||
Show Tool Group Labels Mostrar etiquetas de grupos de herramientas
|
||||
Auto-Rotate (turn the paper to each artboard) Rotar automáticamente (girar el papel según cada mesa de trabajo)
|
||||
Automatic flatness Lisura automática
|
||||
Automatically Automáticamente
|
||||
@@ -1399,6 +1418,9 @@
|
||||
Marks and Bleed Marcas y sangrado
|
||||
Marks and Bleeds Marcas y sangrados
|
||||
Match User Interface Brightness Igualar brillo de la interfaz de usuario
|
||||
Light Gray Gris claro
|
||||
Medium Gray Gris medio
|
||||
Dark Gray Gris oscuro
|
||||
Materials… Materiales…
|
||||
Matte Mate
|
||||
Matte: Mate:
|
||||
@@ -1954,7 +1976,16 @@
|
||||
Rating: Clasificación:
|
||||
Real World: Mundo real:
|
||||
Real-time Drawing and Editing Dibujo y edición en tiempo real
|
||||
Rearrange All Artboards (on the roadmap) Reorganizar todas las mesas de trabajo (en la hoja de ruta)
|
||||
Rearrange All Artboards Reorganizar todas las mesas de trabajo
|
||||
Rearrange All Reorganizar todo
|
||||
Layout Order: Orden de diseño:
|
||||
Change to Left-to-Right Layout Cambiar a diseño de izquierda a derecha
|
||||
Grid by Row Cuadrícula por filas
|
||||
Grid by Column Cuadrícula por columnas
|
||||
Arrange by Row Organizar en una fila
|
||||
Arrange by Column Organizar en una columna
|
||||
Move Artwork with Artboard Mover la ilustración con la mesa de trabajo
|
||||
Artboards: {n} Mesas de trabajo: {n}
|
||||
Rearrange All Artboards… Reorganizar todas las mesas de trabajo…
|
||||
Recall Selection Recuperar selección
|
||||
RECENT RECIENTES
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -12,6 +12,23 @@
|
||||
# Coverage: the whole interface — every menu string and every `tl!` literal (`complete_menus`,
|
||||
# tested). Left in English on purpose (`MENU_KEEP_AS_IS` in the tests): the product name, language
|
||||
# names, OpenType, the built-in workspace names and the bracketed perspective grid preset names.
|
||||
# Photoshop-style raster effects (Effect menu, their dialogs).
|
||||
Radial Blur… Flou radial…
|
||||
Smart Blur… Flou intelligent…
|
||||
Sharpen Netteté
|
||||
Unsharp Mask… Masque de netteté…
|
||||
Radial Blur Flou radial
|
||||
Smart Blur Flou intelligent
|
||||
Unsharp Mask Masque de netteté
|
||||
Gaussian Blur Flou gaussien
|
||||
Method Méthode
|
||||
Quality Qualité
|
||||
Radius Rayon
|
||||
Spin Rotation
|
||||
Draft Brouillon
|
||||
Good Bonne
|
||||
Best Optimale
|
||||
|
||||
# Status and error messages too (`@msg` rows at the end, `COMPLETE_MESSAGES` in the tests).
|
||||
# A native speaker's review is welcome: keep the placeholders ({name}), the trailing "…" and the
|
||||
# leading/trailing spaces of fragments exactly as they are.
|
||||
@@ -77,6 +94,7 @@
|
||||
Add to Swatches Ajouter au nuancier
|
||||
Add Used Colors Ajouter les couleurs utilisées
|
||||
Additional Plug-ins Folder Dossier de modules externes supplémentaires
|
||||
Additional Fonts Folder Dossier de polices supplémentaires
|
||||
Adjust Adjoining Width Points Ajuster les points de largeur adjacents
|
||||
Adjust Color Balance… Régler la balance des couleurs…
|
||||
Adjust Colors Régler les couleurs
|
||||
@@ -203,6 +221,7 @@
|
||||
Auto Size New Area Type Taille automatique du nouveau texte captif
|
||||
Auto Spell Check Vérification orthographique automatique
|
||||
Auto-Collapse Iconic Panels Réduire automatiquement les panneaux en icônes
|
||||
Show Tool Group Labels Afficher les libellés des groupes d'outils
|
||||
Auto-Rotate (turn the paper to each artboard) Rotation automatique (orienter le papier selon chaque plan de travail)
|
||||
Automatic flatness Planéité automatique
|
||||
Automatically Automatiquement
|
||||
@@ -1398,6 +1417,9 @@
|
||||
Marks and Bleed Marques et fond perdu
|
||||
Marks and Bleeds Marques et fonds perdus
|
||||
Match User Interface Brightness Adapter à la luminosité de l’interface
|
||||
Light Gray Gris clair
|
||||
Medium Gray Gris moyen
|
||||
Dark Gray Gris foncé
|
||||
Materials… Matériaux…
|
||||
Matte Détourage
|
||||
Matte: Détourage :
|
||||
@@ -1951,7 +1973,16 @@
|
||||
Rating: Classement :
|
||||
Real World: Monde réel :
|
||||
Real-time Drawing and Editing Dessin et édition en temps réel
|
||||
Rearrange All Artboards (on the roadmap) Réorganiser tous les plans de travail (prévu)
|
||||
Rearrange All Artboards Réorganiser tous les plans de travail
|
||||
Rearrange All Tout réorganiser
|
||||
Layout Order: Ordre de disposition :
|
||||
Change to Left-to-Right Layout Passer à la disposition de gauche à droite
|
||||
Grid by Row Grille par ligne
|
||||
Grid by Column Grille par colonne
|
||||
Arrange by Row Disposer en ligne
|
||||
Arrange by Column Disposer en colonne
|
||||
Move Artwork with Artboard Déplacer l’illustration avec le plan de travail
|
||||
Artboards: {n} Plans de travail : {n}
|
||||
Rearrange All Artboards… Réorganiser tous les plans de travail…
|
||||
Recall Selection Rappeler la sélection
|
||||
RECENT RÉCENTS
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -11,6 +11,23 @@
|
||||
# Coverage: the whole interface — every menu string and every `tl!` literal (`complete_menus`,
|
||||
# tested). Left in English on purpose (`MENU_KEEP_AS_IS` in the tests): the product name, language
|
||||
# names, OpenType, the built-in workspace names and the bracketed perspective grid preset names.
|
||||
# Photoshop-style raster effects (Effect menu, their dialogs).
|
||||
Radial Blur… Sfocatura radiale…
|
||||
Smart Blur… Sfocatura intelligente…
|
||||
Sharpen Nitidezza
|
||||
Unsharp Mask… Maschera di contrasto…
|
||||
Radial Blur Sfocatura radiale
|
||||
Smart Blur Sfocatura intelligente
|
||||
Unsharp Mask Maschera di contrasto
|
||||
Gaussian Blur Sfocatura gaussiana
|
||||
Method Metodo
|
||||
Quality Qualità
|
||||
Radius Raggio
|
||||
Spin Rotazione
|
||||
Draft Bozza
|
||||
Good Buona
|
||||
Best Ottima
|
||||
|
||||
# Status and error messages too (`@msg` rows at the end, `COMPLETE_MESSAGES` in the tests).
|
||||
# A native speaker's review is welcome: keep the placeholders ({name}), the trailing "…" and the
|
||||
# leading/trailing spaces of fragments exactly as they are.
|
||||
@@ -76,6 +93,7 @@
|
||||
Add to Swatches Aggiungi ai campioni
|
||||
Add Used Colors Aggiungi colori usati
|
||||
Additional Plug-ins Folder Cartella plug-in aggiuntivi
|
||||
Additional Fonts Folder Cartella font aggiuntivi
|
||||
Adjust Adjoining Width Points Regola punti di larghezza adiacenti
|
||||
Adjust Color Balance… Regola bilanciamento colore…
|
||||
Adjust Colors Regola colori
|
||||
@@ -202,6 +220,7 @@
|
||||
Auto Size New Area Type Dimensionamento automatico del nuovo testo in area
|
||||
Auto Spell Check Controllo ortografico automatico
|
||||
Auto-Collapse Iconic Panels Comprimi automaticamente i pannelli a icona
|
||||
Show Tool Group Labels Mostra etichette dei gruppi di strumenti
|
||||
Auto-Rotate (turn the paper to each artboard) Rotazione automatica (orienta la carta in base a ogni tavola da disegno)
|
||||
Automatic flatness Planarità automatica
|
||||
Automatically Automaticamente
|
||||
@@ -1399,6 +1418,9 @@
|
||||
Marks and Bleed Segni e abbondanza
|
||||
Marks and Bleeds Segni e abbondanze
|
||||
Match User Interface Brightness Adatta alla luminosità dell'interfaccia utente
|
||||
Light Gray Grigio chiaro
|
||||
Medium Gray Grigio medio
|
||||
Dark Gray Grigio scuro
|
||||
Materials… Materiali…
|
||||
Matte Colore alone
|
||||
Matte: Colore alone:
|
||||
@@ -1954,7 +1976,16 @@
|
||||
Rating: Valutazione:
|
||||
Real World: Mondo reale:
|
||||
Real-time Drawing and Editing Disegno e modifica in tempo reale
|
||||
Rearrange All Artboards (on the roadmap) Ridisponi tutte le tavole da disegno (in programma)
|
||||
Rearrange All Artboards Ridisponi tutte le tavole da disegno
|
||||
Rearrange All Ridisponi tutto
|
||||
Layout Order: Ordine del layout:
|
||||
Change to Left-to-Right Layout Passa al layout da sinistra a destra
|
||||
Grid by Row Griglia per righe
|
||||
Grid by Column Griglia per colonne
|
||||
Arrange by Row Disponi in una riga
|
||||
Arrange by Column Disponi in una colonna
|
||||
Move Artwork with Artboard Sposta la grafica con la tavola da disegno
|
||||
Artboards: {n} Tavole da disegno: {n}
|
||||
Rearrange All Artboards… Ridisponi tutte le tavole da disegno…
|
||||
Recall Selection Richiama selezione
|
||||
RECENT RECENTI
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -724,6 +724,7 @@
|
||||
Add to Selection 選択範囲に追加
|
||||
Add to Swatches スウォッチに追加
|
||||
Additional Plug-ins Folder 追加プラグインフォルダー
|
||||
Additional Fonts Folder 追加フォントフォルダー
|
||||
Adjust Adjoining Width Points 隣接する幅ポイントを調整
|
||||
Adjust Colors カラーを調整
|
||||
Adjust Options: 調整オプション:
|
||||
@@ -809,6 +810,7 @@
|
||||
Auto 自動
|
||||
Auto Size New Area Type 新規エリア内文字を自動サイズ調整
|
||||
Auto-Collapse Iconic Panels アイコンパネルを自動的に折りたたむ
|
||||
Show Tool Group Labels ツールグループのラベルを表示
|
||||
Auto-Rotate (turn the paper to each artboard) 自動回転 (アートボードごとに用紙を回転)
|
||||
Automatic flatness フラットネスを自動設定
|
||||
Automatically 自動
|
||||
@@ -1576,6 +1578,9 @@
|
||||
Mark as trapped トラップ済みとしてマーク
|
||||
Marks トンボ
|
||||
Match User Interface Brightness ユーザーインターフェイスの明るさに合わせる
|
||||
Light Gray ライトグレー
|
||||
Medium Gray ミディアムグレー
|
||||
Dark Gray ダークグレー
|
||||
Matte: マット:
|
||||
Maximize 最大化
|
||||
Maximum Editability 編集機能を最大限に保持
|
||||
@@ -1984,7 +1989,16 @@
|
||||
Rating: 評価:
|
||||
Real World: 実寸:
|
||||
Real-time Drawing and Editing リアルタイム描画および編集
|
||||
Rearrange All Artboards (on the roadmap) すべてのアートボードを再配置 (今後対応予定)
|
||||
Rearrange All Artboards すべてのアートボードを再配置
|
||||
Rearrange All すべて再配置
|
||||
Layout Order: レイアウト順序:
|
||||
Change to Left-to-Right Layout 左から右のレイアウトに変更
|
||||
Grid by Row 行ごとのグリッド
|
||||
Grid by Column 列ごとのグリッド
|
||||
Arrange by Row 1 行に配置
|
||||
Arrange by Column 1 列に配置
|
||||
Move Artwork with Artboard アートボードと一緒にアートワークを移動
|
||||
Artboards: {n} アートボード: {n}
|
||||
Recall Selection 選択範囲を呼び出し
|
||||
Recent Colors 最近使用したカラー
|
||||
Recent Files 最近使ったファイル
|
||||
@@ -3091,3 +3105,20 @@ theme Appearance 外観
|
||||
Constrain 制限
|
||||
Free Transform 自由変形
|
||||
Perspective Distort 遠近変形
|
||||
|
||||
# Photoshop-style raster effects (Effect menu, their dialogs).
|
||||
Radial Blur… ぼかし (放射状)…
|
||||
Smart Blur… ぼかし (詳細)…
|
||||
Sharpen シャープ
|
||||
Unsharp Mask… アンシャープマスク…
|
||||
Radial Blur ぼかし (放射状)
|
||||
Smart Blur ぼかし (詳細)
|
||||
Unsharp Mask アンシャープマスク
|
||||
Gaussian Blur ぼかし (ガウス)
|
||||
Method 方法
|
||||
Quality 画質
|
||||
Radius 半径
|
||||
Spin 回転
|
||||
Draft ドラフト
|
||||
Good 標準
|
||||
Best 高品質
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -138,6 +138,7 @@
|
||||
Add to Selection Adicionar à Seleção
|
||||
Add to Swatches Adicionar às Amostras
|
||||
Additional Plug-ins Folder Pasta Adicional de Plug-ins
|
||||
Additional Fonts Folder Pasta Adicional de Fontes
|
||||
Adjust Adjoining Width Points Ajustar Pontos de Largura Adjacentes
|
||||
Adjust Color Balance… Ajustar Equilíbrio de Cores…
|
||||
Adjust Colors Ajustar Cores
|
||||
@@ -251,6 +252,7 @@
|
||||
Auto Size New Area Type Dimensionar Automaticamente Novo Texto de Área
|
||||
Auto Spell Check Verificação Ortográfica Automática
|
||||
Auto-Collapse Iconic Panels Recolher Automaticamente Painéis Icônicos
|
||||
Show Tool Group Labels Mostrar Rótulos dos Grupos de Ferramentas
|
||||
Auto-Rotate (turn the paper to each artboard) Girar Automaticamente (gire o papel para cada mesa de trabalho)
|
||||
Automatic Automático
|
||||
Automatic flatness Achatamento automático
|
||||
@@ -1261,6 +1263,9 @@
|
||||
Marker… Marcador…
|
||||
Marks Marcas
|
||||
Match User Interface Brightness Corresponder ao Brilho da Interface do Usuário
|
||||
Light Gray Cinza Claro
|
||||
Medium Gray Cinza Médio
|
||||
Dark Gray Cinza Escuro
|
||||
Materials… Materiais…
|
||||
Matte: Fosco:
|
||||
Maximize Maximizar
|
||||
@@ -1746,7 +1751,16 @@
|
||||
Rating: Avaliação:
|
||||
Real World: Mundo Real:
|
||||
Real-time Drawing and Editing Desenho e Edição em Tempo Real
|
||||
Rearrange All Artboards (on the roadmap) Reorganizar Todas as Mesas de Trabalho (no roadmap)
|
||||
Rearrange All Artboards Reorganizar Todas as Mesas de Trabalho
|
||||
Rearrange All Reorganizar Tudo
|
||||
Layout Order: Ordem do Layout:
|
||||
Change to Left-to-Right Layout Mudar para Layout da Esquerda para a Direita
|
||||
Grid by Row Grade por Linha
|
||||
Grid by Column Grade por Coluna
|
||||
Arrange by Row Organizar em Linha
|
||||
Arrange by Column Organizar em Coluna
|
||||
Move Artwork with Artboard Mover Arte com a Mesa de Trabalho
|
||||
Artboards: {n} Mesas de Trabalho: {n}
|
||||
Rearrange All Artboards… Reorganizar Todas as Mesas de Trabalho…
|
||||
Recall Selection Relembrar Seleção
|
||||
Recent Colors Cores Recentes
|
||||
@@ -2662,3 +2676,9 @@
|
||||
Constrain Restringir
|
||||
Free Transform Transformação Livre
|
||||
Perspective Distort Distorção de Perspectiva
|
||||
|
||||
# Photoshop-style raster effects (Effect menu, their dialogs).
|
||||
Radial Blur… Desfoque Radial…
|
||||
Smart Blur… Desfoque Inteligente…
|
||||
Sharpen Nitidez
|
||||
Unsharp Mask… Máscara de Nitidez…
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -9,6 +9,23 @@
|
||||
# Coverage: the whole interface — every menu string and every `tl!` literal (`complete_menus`,
|
||||
# tested). Left in English on purpose (`MENU_KEEP_AS_IS` in the tests): the product name, language
|
||||
# names, OpenType, the built-in workspace names and the bracketed perspective grid preset names.
|
||||
# Photoshop-style raster effects (Effect menu, their dialogs).
|
||||
Radial Blur… Радиальное размытие…
|
||||
Smart Blur… Умное размытие…
|
||||
Sharpen Резкость
|
||||
Unsharp Mask… Нерезкая маска…
|
||||
Radial Blur Радиальное размытие
|
||||
Smart Blur Умное размытие
|
||||
Unsharp Mask Нерезкая маска
|
||||
Gaussian Blur Размытие по Гауссу
|
||||
Method Метод
|
||||
Quality Качество
|
||||
Radius Радиус
|
||||
Spin Вращение
|
||||
Draft Черновое
|
||||
Good Хорошее
|
||||
Best Наилучшее
|
||||
|
||||
# Status and error messages too (`@msg` rows at the end, `COMPLETE_MESSAGES` in the tests).
|
||||
# A native speaker's review is welcome: keep the placeholders ({name}), the trailing "…" and the
|
||||
# leading/trailing spaces of fragments exactly as they are.
|
||||
@@ -74,6 +91,7 @@
|
||||
Add to Swatches Добавить в образцы
|
||||
Add Used Colors Добавить использованные цвета
|
||||
Additional Plug-ins Folder Папка дополнительных модулей
|
||||
Additional Fonts Folder Папка дополнительных шрифтов
|
||||
Adjust Adjoining Width Points Настроить смежные точки ширины
|
||||
Adjust Color Balance… Настроить цветовой баланс…
|
||||
Adjust Colors Настроить цвета
|
||||
@@ -200,6 +218,7 @@
|
||||
Auto Size New Area Type Автоматически подгонять размер нового текста в области
|
||||
Auto Spell Check Автоматическая проверка орфографии
|
||||
Auto-Collapse Iconic Panels Автоматически сворачивать значки панелей
|
||||
Show Tool Group Labels Показывать названия групп инструментов
|
||||
Auto-Rotate (turn the paper to each artboard) Автоповорот (поворачивать лист по каждой монтажной области)
|
||||
Automatic flatness Автоматическая плоскостность
|
||||
Automatically Автоматически
|
||||
@@ -1397,6 +1416,9 @@
|
||||
Marks and Bleed Метки и вылет
|
||||
Marks and Bleeds Метки и вылеты
|
||||
Match User Interface Brightness Согласовать с яркостью интерфейса
|
||||
Light Gray Светло-серый
|
||||
Medium Gray Средне-серый
|
||||
Dark Gray Тёмно-серый
|
||||
Materials… Материалы…
|
||||
Matte Мат
|
||||
Matte: Мат:
|
||||
@@ -1950,7 +1972,16 @@
|
||||
Rating: Рейтинг:
|
||||
Real World: Реальный мир:
|
||||
Real-time Drawing and Editing Рисование и редактирование в реальном времени
|
||||
Rearrange All Artboards (on the roadmap) Переставить все монтажные области (в плане развития)
|
||||
Rearrange All Artboards Переставить все монтажные области
|
||||
Rearrange All Переставить все
|
||||
Layout Order: Порядок макета:
|
||||
Change to Left-to-Right Layout Переключить на макет слева направо
|
||||
Grid by Row Сетка по строкам
|
||||
Grid by Column Сетка по столбцам
|
||||
Arrange by Row Расположить в строку
|
||||
Arrange by Column Расположить в столбец
|
||||
Move Artwork with Artboard Перемещать иллюстрацию вместе с монтажной областью
|
||||
Artboards: {n} Монтажные области: {n}
|
||||
Rearrange All Artboards… Переставить все монтажные области…
|
||||
Recall Selection Восстановить выделение
|
||||
RECENT ПОСЛЕДНИЕ
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -79,6 +79,7 @@
|
||||
Add to Swatches 添加到色板
|
||||
Add Used Colors 添加已用颜色
|
||||
Additional Plug-ins Folder 附加增效工具文件夹
|
||||
Additional Fonts Folder 附加字体文件夹
|
||||
Adjust Adjoining Width Points 调整相邻宽度点
|
||||
Adjust Color Balance… 调整色彩平衡…
|
||||
Adjust Colors 调整颜色
|
||||
@@ -202,6 +203,7 @@
|
||||
Auto Size New Area Type 自动调整新区域文字大小
|
||||
Auto Spell Check 自动拼写检查
|
||||
Auto-Collapse Iconic Panels 自动折叠图标面板
|
||||
Show Tool Group Labels 显示工具组标签
|
||||
Auto-Rotate (turn the paper to each artboard) 自动旋转 (为每个画板转动纸张)
|
||||
Automatic flatness 自动平滑度
|
||||
Automatically 自动
|
||||
@@ -1381,6 +1383,9 @@
|
||||
Marks and Bleed 标记和出血
|
||||
Marks and Bleeds 标记和出血
|
||||
Match User Interface Brightness 匹配用户界面亮度
|
||||
Light Gray 浅灰色
|
||||
Medium Gray 中灰色
|
||||
Dark Gray 深灰色
|
||||
Materials… 材质…
|
||||
Matte 杂边
|
||||
Matte: 杂边:
|
||||
@@ -1928,7 +1933,16 @@
|
||||
Rating: 等级:
|
||||
Real World: 真实世界:
|
||||
Real-time Drawing and Editing 实时绘图和编辑
|
||||
Rearrange All Artboards (on the roadmap) 重新排列所有画板 (规划中)
|
||||
Rearrange All Artboards 重新排列所有画板
|
||||
Rearrange All 全部重新排列
|
||||
Layout Order: 布局顺序:
|
||||
Change to Left-to-Right Layout 更改为由左至右版面配置
|
||||
Grid by Row 按行网格排列
|
||||
Grid by Column 按列网格排列
|
||||
Arrange by Row 排成一行
|
||||
Arrange by Column 排成一列
|
||||
Move Artwork with Artboard 随画板移动图稿
|
||||
Artboards: {n} 画板:{n}
|
||||
Rearrange All Artboards… 重新排列所有画板…
|
||||
Recall Selection 召回选区
|
||||
RECENT 最近使用
|
||||
@@ -3343,3 +3357,20 @@ axis Both 两者
|
||||
Select Shaper Face 选择 Shaper 区域
|
||||
Constrain 约束
|
||||
Perspective Distort 透视扭曲
|
||||
|
||||
# Photoshop-style raster effects (Effect menu, their dialogs).
|
||||
Radial Blur… 径向模糊…
|
||||
Smart Blur… 智能模糊…
|
||||
Sharpen 锐化
|
||||
Unsharp Mask… 反锐化遮罩…
|
||||
Radial Blur 径向模糊
|
||||
Smart Blur 智能模糊
|
||||
Unsharp Mask 反锐化遮罩
|
||||
Gaussian Blur 高斯模糊
|
||||
Method 方法
|
||||
Quality 质量
|
||||
Radius 半径
|
||||
Spin 旋转
|
||||
Draft 草稿
|
||||
Good 良好
|
||||
Best 最佳
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -87,6 +87,7 @@
|
||||
Add to Swatches 新增至色票
|
||||
Add Used Colors 新增使用中的顏色
|
||||
Additional Plug-ins Folder 額外的增效模組資料夾
|
||||
Additional Fonts Folder 額外的字體資料夾
|
||||
Adjust Adjoining Width Points 調整相鄰寬度點
|
||||
Adjust Color Balance… 調整色彩平衡…
|
||||
Adjust Colors 調整顏色
|
||||
@@ -213,6 +214,7 @@
|
||||
Auto Size New Area Type 自動調整新區域文字大小
|
||||
Auto Spell Check 自動拼字檢查
|
||||
Auto-Collapse Iconic Panels 自動收合圖示面板
|
||||
Show Tool Group Labels 顯示工具組標籤
|
||||
Auto-Rotate (turn the paper to each artboard) 自動旋轉 (將紙張轉向各工作區域)
|
||||
Automatic flatness 自動平滑度
|
||||
Automatically 自動
|
||||
@@ -1417,6 +1419,9 @@
|
||||
Marks and Bleed 標記與出血
|
||||
Marks and Bleeds 標記與出血
|
||||
Match User Interface Brightness 符合使用者介面亮度
|
||||
Light Gray 淺灰色
|
||||
Medium Gray 中灰色
|
||||
Dark Gray 深灰色
|
||||
Materials… 材質…
|
||||
Matte 邊緣色
|
||||
Matte: 遮色:
|
||||
@@ -1974,7 +1979,16 @@
|
||||
Rating: 評等:
|
||||
Real World: 真實世界:
|
||||
Real-time Drawing and Editing 即時繪圖與編輯
|
||||
Rearrange All Artboards (on the roadmap) 重新排列所有工作區域 (規劃中)
|
||||
Rearrange All Artboards 重新排列所有工作區域
|
||||
Rearrange All 全部重新排列
|
||||
Layout Order: 版面配置順序:
|
||||
Change to Left-to-Right Layout 變更為由左至右版面配置
|
||||
Grid by Row 依列格狀排列
|
||||
Grid by Column 依欄格狀排列
|
||||
Arrange by Row 排成一列
|
||||
Arrange by Column 排成一欄
|
||||
Move Artwork with Artboard 隨工作區域移動圖稿
|
||||
Artboards: {n} 工作區域:{n}
|
||||
Rearrange All Artboards… 重新排列所有工作區域…
|
||||
Recall Selection 叫出選取範圍
|
||||
RECENT 最近使用
|
||||
@@ -3121,3 +3135,20 @@ axis Both 兩者
|
||||
Constrain 強制
|
||||
Free Transform 任意變形
|
||||
Perspective Distort 透視扭曲
|
||||
|
||||
# Photoshop-style raster effects (Effect menu, their dialogs).
|
||||
Radial Blur… 放射狀模糊…
|
||||
Smart Blur… 智慧型模糊…
|
||||
Sharpen 銳利化
|
||||
Unsharp Mask… 反銳利化遮罩…
|
||||
Radial Blur 放射狀模糊
|
||||
Smart Blur 智慧型模糊
|
||||
Unsharp Mask 反銳利化遮罩
|
||||
Gaussian Blur 高斯模糊
|
||||
Method 方法
|
||||
Quality 品質
|
||||
Radius 半徑
|
||||
Spin 旋轉
|
||||
Draft 草稿
|
||||
Good 良好
|
||||
Best 最佳
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
+35
-21
@@ -473,7 +473,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.menuDialog",
|
||||
"Menu Dialog",
|
||||
"",
|
||||
"{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|object.path.offsetPath|object.path.simplify|object.path.splitIntoGrid|object.vectorHalftone|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options} open the dialog that command's menu item opens (dialog kind: move, rotate, scale, reflect, shear, transformEach, …, vectorHalftone, envelopeWarp, envelopeMesh, envelopeOptions; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected)",
|
||||
"{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|object.path.offsetPath|object.path.simplify|object.path.splitIntoGrid|object.vectorHalftone|artboard.rearrange|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options} open the dialog that command's menu item opens (dialog kind: move, rotate, scale, reflect, shear, transformEach, …, vectorHalftone, rearrangeArtboards, envelopeWarp, envelopeMesh, envelopeOptions; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected)",
|
||||
),
|
||||
(
|
||||
"ui.widthPointEdit",
|
||||
@@ -2196,7 +2196,7 @@ pub fn menu_tree() -> Vec<(&'static str, Vec<Item>)> {
|
||||
"Artboards",
|
||||
vec![
|
||||
c("Convert to Artboards", "artboard.convertToArtboards"),
|
||||
cp("Rearrange All Artboards…", "artboard.rearrange", json!({"columns": 2, "spacing": 20, "moveArtwork": true})),
|
||||
c("Rearrange All Artboards…", "artboard.rearrange"),
|
||||
Sep,
|
||||
c("Fit to Artwork Bounds", "artboard.fitToArt"),
|
||||
c("Fit to Selected Art", "artboard.fitToSelection"),
|
||||
@@ -2870,6 +2870,7 @@ fn menu_dialog(id: &str) -> Option<(&'static str, Value)> {
|
||||
"object.path.simplify" => ("simplify", json!({"tolerance": "1 pt"})),
|
||||
"object.path.splitIntoGrid" => ("splitIntoGrid", json!({"rows": 2, "columns": 2, "gutter": "12 pt"})),
|
||||
"object.vectorHalftone" => (crate::dialogs::halftone::KIND, crate::dialogs::halftone::fields()),
|
||||
"artboard.rearrange" => (crate::dialogs::rearrange_artboards::KIND, crate::dialogs::rearrange_artboards::fields()),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -3222,6 +3223,10 @@ fn font_items() -> Vec<Item> {
|
||||
items.1.clone()
|
||||
}
|
||||
|
||||
/// The raster effects' submenus of the Effect menu (the Photoshop-style effects, below the
|
||||
/// vector effects): (submenu, the catalogue's menu path of its effects).
|
||||
const RASTER_MENUS: [(&str, &[&str]); 2] = [("Blur", &["Effect", "Blur"]), ("Sharpen", &["Effect", "Sharpen"])];
|
||||
|
||||
/// The Effect menu, built from the effects catalogue (vector effects), plus raster effects.
|
||||
fn effect_menu() -> Vec<Item> {
|
||||
let cat = vectorcraft_effects::effect_catalog();
|
||||
@@ -3245,33 +3250,25 @@ fn effect_menu() -> Vec<Item> {
|
||||
"Stylize",
|
||||
"SVG Filters",
|
||||
"Warp",
|
||||
"Blur",
|
||||
];
|
||||
let top_level = |e: &vectorcraft_effects::EffectInfo| e.menu == ["Effect"] && order.contains(&e.label);
|
||||
for sub_name in order {
|
||||
if let Some(e) = cat.iter().find(|e| top_level(e) && e.label == sub_name) {
|
||||
out.push(Item::Cmd(e.label, "effect.apply", json!({ "effect": e.id })));
|
||||
continue;
|
||||
}
|
||||
let items: Vec<Item> = cat
|
||||
.iter()
|
||||
.filter(|e| e.menu.last().copied() == Some(sub_name))
|
||||
// The effects whose catalogue menu path is `path`.
|
||||
let items_at = |path: &[&str]| -> Vec<Item> {
|
||||
cat.iter()
|
||||
.filter(|e| e.menu == path)
|
||||
.map(|e| match e.defaults.as_object().is_some_and(|o| o.is_empty()) {
|
||||
// No options (Effect → Pathfinder): apply directly, like Illustrator.
|
||||
true => Item::Cmd(e.label, "effect.apply", json!({ "effect": e.id })),
|
||||
false => Item::Cmd(e.label, "effect.dialog", json!({ "effect": e.id })),
|
||||
})
|
||||
.collect();
|
||||
if sub_name == "Blur" {
|
||||
// Live-effect plug-ins close the vector effects.
|
||||
out.extend(crate::dialogs::plugin::effect_menu());
|
||||
if !items.is_empty() {
|
||||
out.push(Sep);
|
||||
out.push(Item::Header("Raster Effects"));
|
||||
out.push(sub(sub_name, items));
|
||||
}
|
||||
.collect()
|
||||
};
|
||||
for sub_name in order {
|
||||
if let Some(e) = cat.iter().find(|e| top_level(e) && e.label == sub_name) {
|
||||
out.push(Item::Cmd(e.label, "effect.apply", json!({ "effect": e.id })));
|
||||
continue;
|
||||
}
|
||||
let items = items_at(&["Effect", sub_name]);
|
||||
if items.is_empty() {
|
||||
let placeholder = match sub_name {
|
||||
"3D and Materials" => vec![todo("Extrude & Bevel…"), todo("Revolve…"), todo("Inflate…"), todo("Rotate…"), todo("Materials…")],
|
||||
@@ -3283,8 +3280,25 @@ fn effect_menu() -> Vec<Item> {
|
||||
out.push(sub(sub_name, items));
|
||||
}
|
||||
}
|
||||
// Live-effect plug-ins close the vector effects.
|
||||
out.extend(crate::dialogs::plugin::effect_menu());
|
||||
let raster: Vec<Item> = RASTER_MENUS
|
||||
.iter()
|
||||
.filter_map(|(name, path)| {
|
||||
let items = items_at(path);
|
||||
(!items.is_empty()).then(|| sub(name, items))
|
||||
})
|
||||
.collect();
|
||||
if !raster.is_empty() {
|
||||
out.push(Sep);
|
||||
out.push(Item::Header("Raster Effects"));
|
||||
out.extend(raster);
|
||||
}
|
||||
// Anything not placed above (future effects) still shows up.
|
||||
for e in cat.iter().filter(|e| !top_level(e) && !e.menu.last().is_some_and(|m| order.contains(m))) {
|
||||
let placed = |e: &vectorcraft_effects::EffectInfo| {
|
||||
top_level(e) || order.iter().any(|s| e.menu == ["Effect", *s]) || RASTER_MENUS.iter().any(|(_, path)| e.menu == *path)
|
||||
};
|
||||
for e in cat.iter().filter(|e| !placed(e)) {
|
||||
out.push(Item::Cmd(e.label, "effect.dialog", json!({ "effect": e.id })));
|
||||
}
|
||||
out
|
||||
|
||||
@@ -113,7 +113,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
});
|
||||
let n = abs.len();
|
||||
widgets::bottom_bar(ui, |ui| {
|
||||
widgets::icon_button_enabled(ui, "dc-rearrange", tl!("Rearrange All Artboards (on the roadmap)"), false, false, 24.0);
|
||||
if widgets::icon_button_enabled(ui, "dc-rearrange", tl!("Rearrange All Artboards"), false, n > 1, 24.0).clicked() {
|
||||
open_rearrange(app);
|
||||
}
|
||||
ui.add_space((ui.available_width() - 4.0 * 28.0).max(0.0));
|
||||
if widgets::icon_button_enabled(ui, "dc-arrow-up", tl!("Move Up"), false, sel > 0, 24.0).clicked()
|
||||
&& app.run("artboard.reorder", json!({"index": sel, "to": sel - 1})).is_ok()
|
||||
@@ -140,6 +142,11 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
});
|
||||
}
|
||||
|
||||
/// Open Rearrange All Artboards (#681).
|
||||
pub(crate) fn open_rearrange(app: &mut VectorcraftApp) {
|
||||
app.run("ui.menuDialog", json!({ "command": "artboard.rearrange" })).ok();
|
||||
}
|
||||
|
||||
pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let n = app.session.active().map(|d| d.doc.artboards.len()).unwrap_or(0);
|
||||
let sel = selected(app, n);
|
||||
@@ -161,7 +168,9 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
if menu_item(ui, tl!("Artboard Options…"), n > 0, false) {
|
||||
app.select_tool("artboard");
|
||||
}
|
||||
menu_item(ui, tl!("Rearrange All Artboards…"), false, false);
|
||||
if menu_item(ui, tl!("Rearrange All Artboards…"), n > 1, false) {
|
||||
open_rearrange(app);
|
||||
}
|
||||
ui.separator();
|
||||
if menu_item(ui, tl!("Fit to Artwork Bounds"), n > 0, false) {
|
||||
app.run("artboard.fitToArt", json!({"index": sel})).ok();
|
||||
|
||||
@@ -198,7 +198,8 @@ fn multi_color(app: &mut VectorcraftApp, ctx: &egui::Context) -> bool {
|
||||
}
|
||||
|
||||
/// Edit Artboards (the Artboard tool): the active artboard's name, position and size, its preset and
|
||||
/// orientation (#671), New Artboard and Delete Artboard, and Exit back to the Selection tool (#530).
|
||||
/// orientation (#671), New Artboard and Delete Artboard, and Quick Actions: Rearrange All (#681) and
|
||||
/// Exit back to the Selection tool (#530).
|
||||
fn artboard_sections(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let units = app.session.general_unit();
|
||||
let n = app.session.active().map_or(0, |d| d.doc.artboards.len());
|
||||
@@ -235,8 +236,18 @@ fn artboard_sections(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
});
|
||||
divider(ui);
|
||||
section_header(ui, tl!("Quick Actions"));
|
||||
if widgets::flat_button(ui, tl!("Exit"), w).clicked() {
|
||||
app.select_tool("selection");
|
||||
ui.horizontal(|ui| {
|
||||
rearrange_button(app, ui, n, w);
|
||||
if widgets::flat_button(ui, tl!("Exit"), w).clicked() {
|
||||
app.select_tool("selection");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Rearrange All (#681): opens Rearrange All Artboards; disabled with fewer than two artboards.
|
||||
fn rearrange_button(app: &mut VectorcraftApp, ui: &mut Ui, artboards: usize, w: f32) {
|
||||
if ui.add_enabled_ui(artboards > 1, |ui| widgets::flat_button(ui, tl!("Rearrange All"), w)).inner.clicked() {
|
||||
super::artboards::open_rearrange(app);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -308,6 +319,10 @@ fn document_sections(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
app.select_tool("artboard");
|
||||
}
|
||||
});
|
||||
let artboards = app.session.active().map_or(0, |d| d.doc.artboards.len());
|
||||
if artboards > 1 {
|
||||
rearrange_button(app, ui, artboards, w);
|
||||
}
|
||||
divider(ui);
|
||||
section_header(ui, tl!("Appearance"));
|
||||
fill_stroke_rows(app, ui);
|
||||
@@ -572,6 +587,26 @@ mod tests {
|
||||
assert_eq!(app.session.tool_id(), "selection");
|
||||
}
|
||||
|
||||
/// #681: Rearrange All opens Rearrange All Artboards in one click, from the Document section
|
||||
/// (only with several artboards) and from Edit Artboards' Quick Actions.
|
||||
#[test]
|
||||
fn rearrange_all_opens_the_dialog() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 200, "height": 100})).unwrap();
|
||||
let ctx = egui::Context::default();
|
||||
assert!(!frame(&mut app, &ctx, vec![]).iter().any(|(t, _)| t == "Rearrange All"), "one artboard: nothing to rearrange");
|
||||
app.run("artboard.new", json!({})).unwrap();
|
||||
let texts = frame(&mut app, &ctx, vec![]);
|
||||
click(&mut app, &ctx, &texts, "Rearrange All");
|
||||
let kind = |app: &VectorcraftApp| app.ui.dialog.as_ref().map(|d| d.kind.clone());
|
||||
assert_eq!(kind(&app).as_deref(), Some(crate::dialogs::rearrange_artboards::KIND));
|
||||
app.ui.dialog = None;
|
||||
app.select_tool("artboard");
|
||||
let texts = frame(&mut app, &ctx, vec![]);
|
||||
click(&mut app, &ctx, &texts, "Rearrange All");
|
||||
assert_eq!(kind(&app).as_deref(), Some(crate::dialogs::rearrange_artboards::KIND));
|
||||
}
|
||||
|
||||
/// #671: Edit Artboards shows the artboard's preset (Custom when it matches none) and its
|
||||
/// orientation; the other orientation swaps its width and height, its corner staying put.
|
||||
#[test]
|
||||
|
||||
@@ -80,13 +80,26 @@ pub fn restore(app: &mut VectorcraftApp) {
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
struct Applied {
|
||||
brightness: Brightness,
|
||||
white_canvas: bool,
|
||||
/// User Interface › Canvas Color, unless it matches the interface brightness.
|
||||
canvas: Option<egui::Color32>,
|
||||
threads: i32,
|
||||
tool_tips: bool,
|
||||
scrub: bool,
|
||||
bare_points: bool,
|
||||
}
|
||||
|
||||
/// User Interface › Canvas Color: the canvas around the artboards, or `None` to match the
|
||||
/// interface brightness. The greys keep the white page's edge in view (#663).
|
||||
fn canvas_color(key: &str) -> Option<egui::Color32> {
|
||||
match key {
|
||||
"white" => Some(egui::Color32::WHITE),
|
||||
"lightGray" => Some(egui::Color32::from_gray(0xc8)),
|
||||
"mediumGray" => Some(egui::Color32::from_gray(0x96)),
|
||||
"darkGray" => Some(egui::Color32::from_gray(0x5a)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Per frame: push UI-side preferences into egui / the renderer when they change.
|
||||
pub fn apply_runtime(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
let p = &app.session.prefs;
|
||||
@@ -97,7 +110,7 @@ pub fn apply_runtime(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
}
|
||||
let want = Applied {
|
||||
brightness: app.ui.brightness,
|
||||
white_canvas: p.canvas_color == "white",
|
||||
canvas: canvas_color(&p.canvas_color),
|
||||
threads: p.render_threads,
|
||||
tool_tips: p.show_tool_tips,
|
||||
scrub: p.scrub_numeric_fields,
|
||||
@@ -113,9 +126,9 @@ pub fn apply_runtime(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
ctx.global_style_mut(|s| s.interaction.tooltip_delay = delay);
|
||||
crate::scrub::set_enabled(ctx, want.scrub);
|
||||
crate::widgets::set_bare_numbers_are_points(ctx, want.bare_points);
|
||||
if want.white_canvas {
|
||||
if let Some(c) = want.canvas {
|
||||
let mut t = Tokens::get(ctx);
|
||||
t.pasteboard = egui::Color32::WHITE;
|
||||
t.pasteboard = c;
|
||||
ctx.data_mut(|d| d.insert_temp(egui::Id::NULL, t));
|
||||
}
|
||||
if prev.is_some_and(|pr| pr.threads != want.threads) {
|
||||
@@ -365,6 +378,28 @@ mod tests {
|
||||
use crate::Services;
|
||||
use vectorcraft_engine::Session;
|
||||
|
||||
/// User Interface › Canvas Color (#663): White and the three greys paint the canvas around the
|
||||
/// artboards; Match User Interface Brightness keeps the theme's.
|
||||
#[test]
|
||||
fn canvas_color_choices_paint_the_pasteboard() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Services::default());
|
||||
let ctx = egui::Context::default();
|
||||
apply_runtime(&mut app, &ctx);
|
||||
let themed = Tokens::get(&ctx).pasteboard;
|
||||
for (key, want) in [
|
||||
("white", egui::Color32::WHITE),
|
||||
("lightGray", egui::Color32::from_gray(0xc8)),
|
||||
("mediumGray", egui::Color32::from_gray(0x96)),
|
||||
("darkGray", egui::Color32::from_gray(0x5a)),
|
||||
("matchUi", themed),
|
||||
] {
|
||||
app.run("prefs.set", serde_json::json!({"key": "canvasColor", "value": key})).unwrap();
|
||||
apply_runtime(&mut app, &ctx);
|
||||
assert_eq!(Tokens::get(&ctx).pasteboard, want, "{key}");
|
||||
}
|
||||
assert!(app.run("prefs.set", serde_json::json!({"key": "canvasColor", "value": "pink"})).is_err());
|
||||
}
|
||||
|
||||
fn app() -> VectorcraftApp {
|
||||
VectorcraftApp::new(Session::new(), Services::default())
|
||||
}
|
||||
|
||||
@@ -73,6 +73,7 @@ pub(crate) fn all_shortcuts() -> Vec<(KeyboardShortcut, &'static str, serde_json
|
||||
v.push((sc, "window.panel", json!({ "panel": panel })));
|
||||
}
|
||||
}
|
||||
settings_chord(&mut v, cfg!(target_os = "macos"));
|
||||
// Most specific (most modifiers) first so Cmd+Shift+Z isn't eaten by Cmd+Z.
|
||||
v.sort_by_key(|(sc, ..)| {
|
||||
std::cmp::Reverse(sc.modifiers.shift as u8 + sc.modifiers.alt as u8 + sc.modifiers.command as u8 + sc.modifiers.ctrl as u8)
|
||||
@@ -80,6 +81,14 @@ pub(crate) fn all_shortcuts() -> Vec<(KeyboardShortcut, &'static str, serde_json
|
||||
v
|
||||
}
|
||||
|
||||
/// On a Mac, Cmd+, opens Settings as in every Mac app (#663), beside Preferences' own shortcut,
|
||||
/// unless a command or a user's shortcut already took it.
|
||||
fn settings_chord(v: &mut Vec<(KeyboardShortcut, &'static str, serde_json::Value)>, mac: bool) {
|
||||
if let Some(sc) = parse("Cmd+,").filter(|sc| mac && !v.iter().any(|(s, ..)| s == sc)) {
|
||||
v.push((sc, "edit.preferences", json!({})));
|
||||
}
|
||||
}
|
||||
|
||||
/// Consume a press of `sc`. A `=` chord also takes [`Key::Plus`], which is how `+` arrives from
|
||||
/// the numpad and from layouts where it has its own key (Shift+`=` arrives as either; extra Shift
|
||||
/// is ignored).
|
||||
@@ -687,6 +696,24 @@ mod tests {
|
||||
assert_eq!(digit_of(Key::A), None);
|
||||
}
|
||||
|
||||
/// Cmd+, opens Settings on a Mac only, and never takes a chord a command already has.
|
||||
#[test]
|
||||
fn cmd_comma_opens_settings_on_a_mac() {
|
||||
let comma = parse("Cmd+,").unwrap();
|
||||
let mut v = vec![];
|
||||
super::settings_chord(&mut v, false);
|
||||
assert!(v.is_empty(), "not elsewhere");
|
||||
super::settings_chord(&mut v, true);
|
||||
assert_eq!(v.len(), 1);
|
||||
assert_eq!((v[0].0, v[0].1), (comma, "edit.preferences"));
|
||||
let mut taken = vec![(comma, "view.zoomIn", json!({}))];
|
||||
super::settings_chord(&mut taken, true);
|
||||
assert_eq!(taken.len(), 1, "a command that has it keeps it");
|
||||
if cfg!(target_os = "macos") {
|
||||
assert!(super::all_shortcuts().iter().any(|(sc, id, _)| *sc == comma && *id == "edit.preferences"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses() {
|
||||
let s = parse("Cmd+Shift+]").unwrap();
|
||||
|
||||
@@ -169,7 +169,11 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, cols: usize, floating: Option<egu
|
||||
let mut raise: Option<&'static str> = None;
|
||||
let mut i = 0;
|
||||
while i < all.len() {
|
||||
if let Some(cat) = all[i].0 {
|
||||
if all[i].0.is_some() && !app.session.prefs.tool_group_labels {
|
||||
// User Interface › Show Tool Group Labels off: a faint dash between the groups.
|
||||
let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), 9.0), Sense::hover());
|
||||
ui.painter().line_segment([r.center() - vec2(6.0, 0.0), r.center() + vec2(6.0, 0.0)], egui::Stroke::new(1.0, t.divider));
|
||||
} else if let Some(cat) = all[i].0 {
|
||||
let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), 18.0), Sense::hover());
|
||||
// A long name is cut to its first four characters in the single column.
|
||||
let cat = tl!(cat);
|
||||
@@ -1205,6 +1209,35 @@ pub(crate) mod tests {
|
||||
assert!(r.min.x.is_finite() && r.min.y.is_finite() && r.left() >= 0.0, "on screen: {r:?}");
|
||||
}
|
||||
|
||||
/// User Interface › Show Tool Group Labels (#663): on, the toolbar names its groups; off, it
|
||||
/// shows none of the names, a faint dash between the groups instead.
|
||||
#[test]
|
||||
fn tool_group_labels_can_be_hidden() {
|
||||
fn texts(s: &egui::Shape, out: &mut Vec<String>) {
|
||||
match s {
|
||||
egui::Shape::Text(t) => out.push(t.galley.text().to_string()),
|
||||
egui::Shape::Vec(v) => v.iter().for_each(|s| texts(s, out)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
let draw = |app: &mut VectorcraftApp| {
|
||||
let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(400.0, 1600.0))), ..Default::default() };
|
||||
let mut out = ctx.run_ui(raw, |ui| show(app, ui));
|
||||
out.textures_delta.clear();
|
||||
let mut shown = vec![];
|
||||
out.shapes.iter().for_each(|c| texts(&c.shape, &mut shown));
|
||||
shown
|
||||
};
|
||||
let with = draw(&mut app);
|
||||
assert!(with.iter().any(|t| t == "Shapes") && with.iter().any(|t| t == "Draw"), "{with:?}");
|
||||
app.run("prefs.set", json!({"key": "toolGroupLabels", "value": false})).unwrap();
|
||||
let without = draw(&mut app);
|
||||
assert!(!without.iter().any(|t| ["Select", "Shapes", "Draw", "Modify", "Type"].contains(&t.as_str())), "{without:?}");
|
||||
}
|
||||
|
||||
/// Hover `at` for two seconds, coming from elsewhere: the texts painted meanwhile.
|
||||
fn hovered_texts(app: &mut VectorcraftApp, ctx: &egui::Context, t0: f64, at: Pos2) -> Vec<String> {
|
||||
fn texts(s: &egui::Shape, out: &mut Vec<String>) {
|
||||
|
||||
@@ -1694,6 +1694,51 @@ pub fn orientation_button(ui: &mut Ui, landscape: bool, selected: bool, tip: &st
|
||||
resp.on_hover_text(tl!(tip)).clicked()
|
||||
}
|
||||
|
||||
/// An artboard-layout toggle drawn in code (Rearrange All Artboards): small artboards in the grid
|
||||
/// cells `tiles` (column, row), tinted, and over them their order as a line from a dot on the first
|
||||
/// to an arrowhead on the last; accent-drawn in a pressed well when `selected`, greyed in a disabled
|
||||
/// `ui`. `tip` is shown as it is (the caller translates it). Returns clicked.
|
||||
pub fn layout_button(ui: &mut Ui, tiles: &[(u8, u8)], selected: bool, tip: &str) -> bool {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let (rect, resp) = ui.allocate_exact_size(Vec2::splat(26.0), Sense::click());
|
||||
let enabled = ui.is_enabled();
|
||||
let bg = if selected {
|
||||
t.tool_active
|
||||
} else if resp.hovered() && enabled {
|
||||
t.hover
|
||||
} else {
|
||||
Color32::TRANSPARENT
|
||||
};
|
||||
ui.painter().rect_filled(rect, CornerRadius::same(3), bg);
|
||||
let color = if !enabled {
|
||||
t.text_disabled
|
||||
} else if selected {
|
||||
t.accent
|
||||
} else {
|
||||
t.icon
|
||||
};
|
||||
// Cells at most 10 points a side in a 20-point square: a row's artboards stand tall, a
|
||||
// column's lie flat.
|
||||
let (cols, rows) = tiles.iter().fold((1u8, 1u8), |(c, r), &(x, y)| (c.max(x.saturating_add(1)), r.max(y.saturating_add(1))));
|
||||
let cell = vec2((20.0 / f32::from(cols)).min(10.0), (20.0 / f32::from(rows)).min(10.0));
|
||||
let origin = rect.center() - vec2(f32::from(cols) * cell.x, f32::from(rows) * cell.y) / 2.0;
|
||||
let centre = |&(x, y): &(u8, u8)| origin + vec2((f32::from(x) + 0.5) * cell.x, (f32::from(y) + 0.5) * cell.y);
|
||||
for tile in tiles {
|
||||
ui.painter().rect_filled(Rect::from_center_size(centre(tile), cell - vec2(2.0, 2.0)), 1.0, color.gamma_multiply(0.35));
|
||||
}
|
||||
let path: Vec<Pos2> = tiles.iter().map(centre).collect();
|
||||
if let ([first, ..], [.., from, to]) = (path.as_slice(), path.as_slice()) {
|
||||
let (first, from, to) = (*first, *from, *to);
|
||||
let dir = (to - from).normalized();
|
||||
let side = dir.rot90() * 2.5;
|
||||
let head = vec![to + dir * 1.5, to - dir * 2.5 + side, to - dir * 2.5 - side];
|
||||
ui.painter().circle_filled(first, 1.6, color);
|
||||
ui.painter().add(egui::Shape::line(path, Stroke::new(1.2, color)));
|
||||
ui.painter().add(egui::Shape::convex_polygon(head, color, Stroke::NONE));
|
||||
}
|
||||
resp.on_hover_text(tip).clicked()
|
||||
}
|
||||
|
||||
/// `region` of `doc` rendered on white, its longest side `px` pixels, as a texture named `name`
|
||||
/// (artboard and page thumbnails).
|
||||
pub fn region_texture(
|
||||
|
||||
Reference in new issue
Block a user