Compare commits

...
Author SHA1 Message Date
bflatasticandClaude Opus 5.5 4099ebf3c9 Fix #787: raster exports keep translucent edges over opaque art opaque
The renderer composited in 8-bit integers, so where a partly transparent
anti-aliased edge crossed opaque art (or a background colour) the result
came out at alpha 254 on some pixels, and PNG, TIFF and WebP files were
written with an alpha channel. Raster exports (and Save for Web) now
composite in floating point (vello_cpu's f32 pipeline, enabled as a
feature), offscreen groups, masks and patterns included; the canvas keeps
the faster 8-bit path.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 11:12:13 +07:00
bflatasticandClaude Opus 5.5 1db82cbc02 Fix #798: the Curvature tool edits any selected path
The Curvature tool only edited the path it was drawing. It now edits any
selected path, whatever drew it, keeping its shape except where edited:
a click on a point makes it the current (direct-selected) point and a
drag moves it, re-curving only its two segments (the neighbours keep
their handle directions); Alt-click or double-click toggles it smooth or
corner and Delete removes it; a click on a segment adds a smooth point
without changing the shape, and a drag moves it in the same undo step.
With an end of an open path current, clicks go on from it (the old
segments keep their shape) and a click on the other end closes it.

The edits go through a new path.curvatureEdit command (move, insert,
extend, close), path.convertAnchor and path.removeAnchor, one undo step
each. The tool now claims Delete/Backspace while it has a point to
remove, so the key no longer deletes the whole path.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 11:12:10 +07:00
bflatasticandClaude Opus 5.5 898c4f7677 Docs: ROADMAP for the 2026-10-10 fixes; Other Library lists color books
The ROADMAP's last-updated line names this batch's fixes and the two
community PRs that didn't add themselves (#792, #765); the platforms
paragraph says Windows starts on Direct3D 12 and loads no Vulkan driver
unless asked (#806); the guides row has ruler guides with Smart Guides
on and the hover labels (#812). Window › Swatch Libraries › Other
Library's description lists .acb color books (#831).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 10:52:27 +07:00
BFlat 6b42a9100c Merge pull request #887 from storytold/fix/812-hover-labels
Part of #812: Smart Guides label an object's centre and anchors on hover
2026-10-10 10:46:53 +07:00
BFlat 1b398978ba Merge pull request #884 from storytold/fix/827-raster-effect-blend
Fix #827: shadows and glows keep their blend modes in PDF
2026-10-10 10:46:45 +07:00
BFlat 449387a62e Merge pull request #883 from storytold/fix/812-guides-snap
Part of #812: ruler guides pull drawn points with Smart Guides on
2026-10-10 10:46:28 +07:00
BFlat 0782972b88 Merge pull request #882 from storytold/fix/785-step-references
Part of #785: run and command_batch steps can use earlier results
2026-10-10 10:46:10 +07:00
BFlat 07708f6cca Merge pull request #881 from storytold/fix/861-open-error-dialog
Part of #861: a file the user can't open is reported in a dialog
2026-10-10 10:46:01 +07:00
BFlat 5b26fd4d01 Merge pull request #879 from storytold/fix/831-acb-color-books
Fix #831: color books (.acb) open as swatch libraries
2026-10-10 10:45:54 +07:00
BFlat a05a6d06bf Merge pull request #878 from storytold/fix/833-isolation-locks-outside
Fix #833: isolation mode locks and dims the art around the group
2026-10-10 10:45:48 +07:00
BFlat fd59778c8f Merge pull request #877 from storytold/fix/775-properties-paragraph
Fix #775: the Properties panel's Paragraph section justifies and hyphenates
2026-10-10 10:45:43 +07:00
BFlat 06d61296f5 Merge pull request #876 from storytold/fix/789-align-to-everywhere
Fix #789: every align button aligns to the Align To choice
2026-10-10 10:45:36 +07:00
BFlat fb4b84c4b9 Merge pull request #875 from storytold/fix/835-gradient-stop-recent
Fix #835: a recent colour recolours the selected gradient stop
2026-10-10 10:45:30 +07:00
BFlat 9c0eccb067 Merge pull request #874 from storytold/fix/862-stop-popover-beside-art
Fix #862: the gradient stop popover opens beside the art
2026-10-10 10:45:22 +07:00
BFlat 2b01ebcc9e Merge pull request #873 from storytold/fix/826-rotated-rulers
Fix #826: rulers cover their length in a rotated view
2026-10-10 10:45:15 +07:00
BFlat 447fe10edf Merge pull request #872 from storytold/fix/839-sfw-pixel-size
Fix #839: Save for Web accepts a typed width or height
2026-10-10 10:45:09 +07:00
BFlat 9cc0ca866d Merge pull request #871 from storytold/fix/824-artboard-label
Fix #824: the Artboard tool names its artboard once
2026-10-10 10:45:03 +07:00
BFlat 56b3119288 Merge pull request #870 from storytold/fix/806-no-vulkan-on-windows
Fix #806: Windows doesn't load Vulkan drivers unless asked
2026-10-10 10:44:58 +07:00
BFlat 0b249c5257 Merge pull request #869 from storytold/fix/758-skip-hopeless-prune
Part of #758: .ai import doesn't weigh text objects when the layers can't be used
2026-10-10 10:44:52 +07:00
BFlat c1bcd0afeb Merge pull request #863 from storytold/fix/755
Fix #755: blurred type no longer shifts as the view moves
2026-10-10 10:44:41 +07:00
BFlat 5d5db434ea Merge pull request #860 from storytold/fix/830-app-quit-pending
Fix #830: the control channel's app.quit says when it asks first
2026-10-10 10:44:34 +07:00
BFlat 84ae8e90c3 Merge pull request #859 from storytold/fix/828-effect-dropdowns
Fix #828: Offset Path's Joins and Zig Zag's Points are dropdowns
2026-10-10 10:44:27 +07:00
BFlat 71d8881186 Merge pull request #753 from storytold/feat/637-type-from-text-document
Part of #637: area type, threaded type and type on a path from the text document
2026-10-10 10:44:20 +07:00
bflatasticandClaude Opus 5.5 fdb7d7a183 Part of #812: Smart Guides label an object's centre and anchors on hover
With Smart Guides on, hovering the Selection tool near an object's centre
or one of its anchors now labels it ("center", "anchor"), as
Illustrator does, and a press there grabs the object by that point, so
the point follows the pointer and snaps.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 10:28:38 +07:00
bflatasticandClaude Opus 5.5 99671cabd8 Fix #827: shadows and glows keep their blend modes in PDF
A raster effect painted below its object (Drop Shadow, Outer Glow) is
written as an image under the object's vector art. The image was
rendered over nothing and placed with Normal blending, so a Screen glow
or a Multiply shadow came out as Normal in the PDF. Each image is now
composited with its effects' blend mode, one image per mode when an
object's shadows and glows use several.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 10:28:04 +07:00
bflatasticandClaude Opus 5.5 522c1dabd6 Part of #812: ruler guides pull drawn points with Smart Guides on
Drawing with Smart Guides on ignored the ruler guides: only with Smart
Guides off did Snap to Point use them (a vertical guide seemed to work
when it lay on the artboard's centre line, which Smart Guides follow).
With Snap to Point on, the ruler guides now pull drawn and dragged
points with Smart Guides on too, also while a point slides along a
construction guide or Shift's angle, as in Illustrator.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 10:28:03 +07:00
bflatasticandClaude Opus 5.5 b767e850ed Part of #785: run and command_batch steps can use earlier results
A run (vectorcraft-cli run, the MCP command_batch tool) had no way to use
an id an earlier step returned. A parameter string that is exactly
$N.path or $last.path now takes that value from step N's result
(0-based), e.g. {"id":"$1.id"}; $$ starts a literal $, and a
reference to nothing fails the step. Objects given to a command are now
used as given: an ids element or id that isn't an object id (or an
unresolved reference) fails instead of the command acting on the
selection. text.setRangeStyle styles the selected type object when no
id is given, as text.setStyle does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 10:28:03 +07:00
bflatasticandClaude Opus 5.5 c19873e220 Part of #861: a file the user can't open is reported in a dialog
Opening a file that fails (File › Open, Open Recent, the Home screen, a
drop, the Finder or the command line) only set the status bar's
message, which is easily missed: it looked as if nothing happened. A
dialog now says "Can't open “name”." with the reason, as well. An
agent's file.open {path} still just answers with the error.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 10:27:59 +07:00
bflatasticandClaude Opus 5.5 9a0183a02d Fix #831: color books (.acb) open as swatch libraries
Color books such as the Pantone books a user owns (.acb) couldn't be
opened. They are now read (never written), from public descriptions of
the format: their RGB, CMYK or Lab colors, named with the book's prefix
and suffix ("PANTONE 185 C"), as spot colors unless the book marks
them as process colors, leaving out the pages' unnamed padding. They
open from Window › Swatch Libraries › Other Library…, File › Open and
the user library folder like .ase files.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 10:27:58 +07:00
bflatasticandClaude Opus 5.5 b426859b15 Fix #833: isolation mode locks and dims the art around the group
While a group or layer was isolated, clicks, hovers and drags still
reached the art outside it, and that art drew as usual. Now only the
isolated container's contents hit: the art around it is locked and
clicks pass through it. On the canvas it draws at half opacity, above
the group as well as below, each run of it as one dimmed layer.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 10:27:57 +07:00
bflatasticandClaude Opus 5.5 61d372bb7f Fix #775: the Properties panel's Paragraph section justifies and hyphenates
With type selected, the Properties panel's Paragraph section had only
Align Left, Center and Right. It now has the Paragraph panel's seven
alignments (the justified ones too), its Hyphenate checkbox and a "…"
button that opens the Paragraph panel, as Illustrator's does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 10:27:56 +07:00
bflatasticandClaude Opus 5.5 82dc5f8182 Fix #789: every align button aligns to the Align To choice
Align to Key Object and Align to Artboard worked only from the Align
panel's own buttons: the Control bar's and the Properties panel's align
buttons always aligned to the selection (one object to the artboard).
They are now one set of buttons that follow Align To (and the key
object), and the Properties panel's Align section gets the "…" button
that opens the Align panel for Distribute and Align To.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 10:27:54 +07:00
bflatasticandClaude Opus 5.5 79c81d754c Fix #835: a recent colour recolours the selected gradient stop
In the gradient stop popover (and the Color panel), clicking a recent
colour replaced the whole gradient with that colour, while the sliders,
spectrum and Black and White chips recoloured the selected stop. The
recent colours now go through the Color panel's target like the chips.
The Swatches panel's recent colours still paint the fill or stroke, as
its swatches do.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 10:27:54 +07:00
bflatasticandClaude Opus 5.5 97318c188b Fix #862: the gradient stop popover opens beside the art
Opened from a stop on the Gradient tool's annotator, the colour popover
appeared just below and right of the stop, over the very art whose
colour it changes. It now opens beside the selected art, on the first
side with room for it (right, left, below, above), and beside the stop
only when there is none.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 10:27:53 +07:00
bflatasticandClaude Opus 5.5 94141eca82 Fix #826: rulers cover their length in a rotated view
With Rotate View, each ruler measured document x (or y) along a line
that crossed both axes: its ticks covered only a short stretch and the
numbers bunched up. Each ruler now measures along its own edge in the
canvas's coordinates turned with the view, so it is ticked over its
whole length at every angle, and reads x and y as before at 0°.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 10:27:53 +07:00
bflatasticandClaude Opus 5.5 5df4ddd4b6 Fix #839: Save for Web accepts a typed width or height
The dialog's W and H fields send decimal numbers (300.0) and the settings
wanted a whole u32, so the preview failed with "invalid type: floating
point". Pixel sizes now take any number and round it to whole pixels;
negative, huge and non-numeric sizes are still refused.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 10:27:52 +07:00
bflatasticandClaude Opus 5.5 021a9474f8 Fix #824: the Artboard tool names its artboard once
With the Artboard tool, the active artboard's name was drawn twice: by
the canvas, as for every artboard, and by the tool, in blue and a little
higher. The canvas now leaves that one to the tool, which draws it where
the canvas names the others.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 10:27:52 +07:00
bflatasticandClaude Opus 5.5 de564bc24f Fix #806: Windows doesn't load Vulkan drivers unless asked
Creating a Vulkan instance loads every installed Vulkan driver into the
process, and a faulty one (Intel's igvk64.dll) crashed VectorCraft
before its window appeared. On Windows the window now starts with
Direct3D 12, falling back to OpenGL, as PdfCraft does; WGPU_BACKEND
(e.g. vulkan) still chooses others.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 10:27:51 +07:00
bflatasticandClaude Opus 5.5 495694e1ac Part of #758: .ai import doesn't weigh text objects when the layers can't be used
Before deciding to use the layers of an Illustrator file, the import
drew them again for each text object made from the file's text
document, to see whether the page draws it. When the layers differ from
the page by more than the check allows even with every such object
gone (taking one out only changes what is drawn in its box), the
layers aren't used whatever is taken out: that weighing is now
skipped.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 10:27:50 +07:00
62 changed files with 2092 additions and 201 deletions

No files matched your search

+1 -1
View File
@@ -54,7 +54,7 @@ wasmi = { version = "2.0.0", default-features = false, features = ["std", "valid
wat = "1.228"
# rendering / formats
vello_cpu = "0.2"
vello_cpu = { version = "0.2", features = ["f32_pipeline"] }
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "webp", "gif", "tiff", "bmp"] }
usvg = "0.48"
krilla = "0.8"
+6 -6
View File
@@ -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-10 (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-10 (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
@@ -42,7 +42,7 @@ since 2026-10-01.
| **Bundled content:** brush, symbol, style and swatch libraries | ~30% | Ours are original and generated in code, and far fewer than Illustrator ships; brush and symbol libraries are still missing |
| **Performance** | unverified | Multithreaded, off-thread rendering and caches are in place. The last budget run (2026-10-01, loaded machine) measured 290 ms for a 50k-path fit against a 16 ms budget. Re-run `vectorcraft-cli perf` on an idle machine |
| **Robustness** | good, new | ~2,840 tests, property tests, no panics in shipped code (lints, the `guard` safety net, import fuzzing), Data Recovery. Missing: a corpus of real-world files, Windows/Linux/browser QA |
| **Platforms and 1.0 polish** | ~60% | The macOS app and the web build work, and Finder opens every readable format with the macOS app (#295, #354); on macOS the menus are in the system menu bar, laid out as a Mac app's, with the in-window menus as a fallback (`--in-window-menus`; verified on Windows and by cross-compilation, not yet by hand on a Mac); hybrid-graphics laptops render on the power-saving GPU by default on Windows and macOS (#306), and Windows renders through DX12 before Vulkan (#545: Vulkan flickered black on an Intel GPU, DX12 and OpenGL didn't; verified by unit tests and the reporter's runs with `WGPU_BACKEND`), and Linux on the GPU the desktop runs on, since a Wayland compositor may refuse frames from the other one; a window that fails on its GPU while starting up starts again on the next one instead of crashing (#502; the dual-GPU Wayland case is verified by unit tests and cross-compilation, not on such hardware); web drops land in the document they were dropped on (#359); desktop drops carry no pointer position (winit 0.30), so a dropped document opens as a tab of its own and a picture or text is placed in the middle of the view, while the web places anything dropped on the canvas and opens what is dropped off it, as Illustrator does (#472); a web page that loses its WebGPU device or WebGL context restarts its graphics with the same documents (#369); on Linux/Wayland the clipboard reads the compositor's own (data-control) and copied image files paste, but files can't be dropped on the window under Wayland until eframe moves to winit 0.31 (#398; the Wayland side is verified by compilation only); on Linux the Paste menu checks the system clipboard on a background thread, so a clipboard owner that never answers no longer freezes the window, while Windows and macOS keep their quick in-line check (#510; the X11 hang verified by the contributor, here by headless tests); on KDE Plasma 6.3+ under Wayland, pens and pen displays reach the app only under XWayland (`WAYLAND_DISPLAY=`) or with KWin's `KWIN_WAYLAND_EMULATE_TABLET=1`, since winit 0.30 has no Wayland tablet input (#491, not verified on hardware); Windows/Linux packaging and accessibility are pending; an experimental, unsupported Windows 7 x64 OpenGL build exists (community-contributed, not verified by maintainers) |
| **Platforms and 1.0 polish** | ~60% | The macOS app and the web build work, and Finder opens every readable format with the macOS app (#295, #354); on macOS the menus are in the system menu bar, laid out as a Mac app's, with the in-window menus as a fallback (`--in-window-menus`; verified on Windows and by cross-compilation, not yet by hand on a Mac); hybrid-graphics laptops render on the power-saving GPU by default on Windows and macOS (#306), and Windows starts on Direct3D 12, falling back to OpenGL, and loads no Vulkan driver unless `WGPU_BACKEND` asks for it (#545: Vulkan flickered black on an Intel GPU, DX12 and OpenGL didn't; #806: a faulty Vulkan driver crashed the app before its window appeared; verified by unit tests and the reporter's runs with `WGPU_BACKEND`), and Linux on the GPU the desktop runs on, since a Wayland compositor may refuse frames from the other one; a window that fails on its GPU while starting up starts again on the next one instead of crashing (#502; the dual-GPU Wayland case is verified by unit tests and cross-compilation, not on such hardware); web drops land in the document they were dropped on (#359); desktop drops carry no pointer position (winit 0.30), so a dropped document opens as a tab of its own and a picture or text is placed in the middle of the view, while the web places anything dropped on the canvas and opens what is dropped off it, as Illustrator does (#472); a web page that loses its WebGPU device or WebGL context restarts its graphics with the same documents (#369); on Linux/Wayland the clipboard reads the compositor's own (data-control) and copied image files paste, but files can't be dropped on the window under Wayland until eframe moves to winit 0.31 (#398; the Wayland side is verified by compilation only); on Linux the Paste menu checks the system clipboard on a background thread, so a clipboard owner that never answers no longer freezes the window, while Windows and macOS keep their quick in-line check (#510; the X11 hang verified by the contributor, here by headless tests); on KDE Plasma 6.3+ under Wayland, pens and pen displays reach the app only under XWayland (`WAYLAND_DISPLAY=`) or with KWin's `KWIN_WAYLAND_EMULATE_TABLET=1`, since winit 0.30 has no Wayland tablet input (#491, not verified on hardware); Windows/Linux packaging and accessibility are pending; an experimental, unsupported Windows 7 x64 OpenGL build exists (community-contributed, not verified by maintainers) |
| **Agent automation** | beyond Illustrator | Every command, gesture and dialog is drivable over MCP, the CLI and the control channel |
| **Scrubby numeric fields** | beyond Illustrator | As in Photoshop, dragging a numeric field's label (`W:`, `Opacity:`, the Character panel's icons) left or right steps its value live; one undo step per drag, Escape cancels (#400) |
@@ -98,7 +98,7 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist
- JSON-lines control channel with real egui pointer and keyboard injection.
- MCP server with 25 tools (drawing, text, effects, Pathfinder, transforms, graphs, text wrap, export, screenshots, any command), attached to the running app or headless. Tool descriptions and replies agree with the engine: format lists come from its format table, `save_file` says it keeps the document's own format, `inspect_document` reports the paint type's characters show, and selection exports report the encoder's warnings.
- MCP protocol: five prompts (`prompts/list` / `prompts/get`: poster, icon set, recolour, trace-and-style, export set), `completion/complete` for prompt arguments and template variables read from the live catalogues (formats, effect ids, command ids, trace presets, swatch and object ids), four resource templates (`vectorcraft://object/{id}`, `//command/{id}`, `//effect/{id}`, `//swatch/{name}`) so an agent reads one thing instead of the whole document, and `logging/setLevel` with `notifications/message`. `window.panel` ids are case-insensitive (display labels work too), `vectorcraft://object/{id}` reads through `document.node {summary: true}` (the same reply bytes from one lookup instead of summarizing the whole document: a leaf read on a 2,000-object document drops from ~20 ms to ~0.06 ms), large containers slice with `document.node {depth?, childLimit?}` (truncated levels report `childCount`), `document.inspect` and the `inspect_document` tool slice the same way so a depth-0 read is the layer skeleton (~9.7 KB instead of ~2 MB on a 2,000-object document), `document.find` locates nodes by name/kind/text with ancestor paths, and the CLI sweeps the protocol surface over stdio against the compiled binary. `docs/mcp.md` has a Protocol section covering the capability table and what is deliberately absent (subscriptions, progress, cancellation, sampling, elicitation, Streamable HTTP — all of which need the transport to interleave reads).
- Headless CLI (`vectorcraft-cli run`, `convert`, `info`, `bench`, `perf`, `mcp`).
- Headless CLI (`vectorcraft-cli run`, `convert`, `info`, `bench`, `perf`, `mcp`). A `run` step, like a `command_batch` step over MCP, can use an earlier step's result (`"$1.id"`, #785).
- Actions panel that records and plays back commands.
- **UI:** Illustrator 2026 layout restyled to measured values:
- Medium Dark theme, categorized and Advanced toolbars (a tool group's flyout opens on a right press, a long press or a press on its corner triangle), 35 pt document tabs, 33 pt panel tabs.
@@ -128,7 +128,7 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist
Agent selection commands validate every object id before changing the selection and report the resulting count and ids (#784).
Clear deletes individual selected compound-path members without deleting their siblings, and explicit object ids work without a selection; Cut still removes the same objects it copies (#786).
- **Saved selections:** Select ▸ Save Selection… asks for a name and keeps the selection in the document (saved with the file, undoable, up to 25); each one is listed at the bottom of the Select menu and a click selects its objects again; Edit Selection… lists them to rename or delete, applied together on OK. A file's saved selections are capped and checked against its objects when it opens. Not yet: Update Selection and the Layers panel's saved-selection menu.
- **Drawing:** Pen, Curvature, anchor tools, Pencil, Paintbrush, Blob Brush, Smooth, Path Eraser, Join. Direction handles dragged with Direct Selection or the Anchor Point tool snap to smart guides, and Shift keeps them at 45° steps from their anchor. The Pen continues any open path from the end clicked, and while drawing, a click on an end of another open path joins the two into one (#776). Every point a drawing tool places snaps to Smart Guides through one snapper (#506): the Pen's and Curvature tool's anchors, the Pencil's ends, the shape tools' start and dragged corner or radius (Rectangle, Rounded Rectangle, Ellipse, Polygon, Star, Line Segment, Arc, Spiral, the grids), the Type tool's click and frame, a new artboard's corners.
- **Drawing:** Pen, Curvature, anchor tools, Pencil, Paintbrush, Blob Brush, Smooth, Path Eraser, Join. Direction handles dragged with Direct Selection or the Anchor Point tool snap to smart guides, and Shift keeps them at 45° steps from their anchor. The Pen continues any open path from the end clicked, and while drawing, a click on an end of another open path joins the two into one (#776). The Curvature tool edits any selected path, whatever drew it, keeping its shape except where edited (#798): a click on a point makes it current and a drag moves it, re-curving only its two segments; Alt-click or double-click toggles it smooth or corner and Delete removes it; a click on a segment adds a point without changing the shape; with an end of an open path current, clicks go on from it and its other end closes it (`path.curvatureEdit`). Every point a drawing tool places snaps to Smart Guides through one snapper (#506): the Pen's and Curvature tool's anchors, the Pencil's ends, the shape tools' start and dragged corner or radius (Rectangle, Rounded Rectangle, Ellipse, Polygon, Star, Line Segment, Arc, Spiral, the grids), the Type tool's click and frame, a new artboard's corners.
- **Shapes:** all shape tools (including Flare) and the line, arc, spiral and grid tools. Space held while dragging out a shape, line, arc, spiral or grid moves it at its current size. While a grid is dragged out, Up/Down change its rows (concentric dividers) and Left/Right its columns (radial dividers). An ellipse's Pie Start and End Angle and Invert Pie (Transform and Properties panels' Ellipse Properties, `object.setLiveShape {pieStart, pieEnd, invertPie}`) cut it as a pie (#812; the on-canvas pie widget is still to come).
- **Cutting:** Eraser, Scissors, Knife, Mirror & Cut, Line Cut and Rectangle Cut (real geometry, compound paths keep their holes).
- **Transform:** Rotate, Reflect, Scale, Shear (click or Alt-click snaps the reference point to anchors and centres; Alt-click opens the tool's dialog, and a drag with Alt down at the release, from the press or pressed mid-drag, transforms a copy), Reshape, Free Transform (free and perspective distort and shear, switched by the keys held during a handle drag).
@@ -153,7 +153,7 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist
- **Image Trace Flat Logo mode:** a fourth mode beside Black and White, Grayscale and Color, for flat-colour logos. Each pixel is read as a blend of the logo's colours (found automatically or named), the blend is interpolated smoothly and every outline is placed where two colours are equally present, so edges are accurate to a fraction of a pixel. Outlines are then cleaned: corners the blur rounded are put back, near-straight runs and near-circular arcs become exact lines and arcs, the rest is fitted with as few Béziers as the tolerance allows, touching colours overlap by a hair so no gap opens, and an outline that strays from the raw contour is fitted plainly instead. Gradients and photos are refused with advice to use Color. *Measured* (a local experiment, not run in CI): a flat-colour logo's vector original was rendered down to a soft 199 × 100 px transparent PNG, traced, and the result compared with the original at 1600 px wide. The built-in colour presets (6 Colors, 16 Colors, High Fidelity Photo, Low Fidelity Photo) had a mean edge error of 2.5 to 3.4 px and region overlap of 0.88 to 0.91; Flat Logo had 0.78 px and 0.966 (0.48 px and 0.975 from a crisp source), in about 0.1 s. Limits: flat-colour art only; needle-thin sharp tips are shortened by about 1.7 source pixels because the blur erases them; it works at no more than 1024 px on the long side (larger images are averaged down first); only one logo family has been scored against a vector original.
- **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 (a crop box on the image, starting on its part over the artboard, dragged by its handles or inside it, the outside dimmed, with X/Y/W/H, Apply and Cancel in the Control bar, Enter and Escape, #734; `object.cropImage {rect}` for agents, `{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`, swatch exchange (`.ase`) or CSS, and loaded from `.vcswatches`, `.gpl` and `.ase` files (`.ase` both ways: RGB, CMYK, Lab and Gray; global, spot and process; groups); `swatch.library.copyToUser` copies a loaded library into the User Defined folder without replacing a file, and a file with the same extension and bytes as a User Defined library opens as that library. Tints of global and spot colours ("Name 40%") stay linked and separate as a percentage of their plate. Spot colours can be defined in Lab (Spot Colors options). A built-in [Registration] swatch prints on every plate.
- **Swatches:** names follow the colour model and are unique; Swatch Options (process/spot, Global, Gray/RGB/HSB/CMYK/Web, live preview); editing a global or spot swatch recolours every linked fill, stroke and text run in one undo step; multi-select and delete with confirmation; New Swatch and New Color Group dialogs (a group from the selected artwork's colours); swatches in colour groups convert, separate and count like any other. The Swatches panel selects ranges and whole groups, has a find field, and drags swatches to reorder, regroup or paint art; Add Used Colors, Select All Unused, Merge, Ungroup and Sort by Kind; a CMYK document keeps applied colours in CMYK. Swatch libraries: nine generated colour libraries and five gradient libraries in a library panel, saved as `.vcswatches`, `.gpl`, swatch exchange (`.ase`) or CSS, and loaded from `.vcswatches`, `.gpl` and `.ase` files (`.ase` both ways: RGB, CMYK, Lab and Gray; global, spot and process; groups) and from color books (`.acb`, read only: the RGB, CMYK or Lab colors of a book such as a Pantone book a user owns, named with its prefix and suffix, spot unless it says process, #831); `swatch.library.copyToUser` copies a loaded library into the User Defined folder without replacing a file, and a file with the same extension and bytes as a User Defined library opens as that library. 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). 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.
@@ -227,7 +227,7 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale)
| Image Trace, graphs, image tools | 3 | 72% | graph Design/Column/Marker, Create Object Mosaic, 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 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; moves snapping to the grid, #740) | 2–4 |
| 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; moves snapping to the grid, #740; ruler guides pulling drawn points with Smart Guides on, and "center" and "anchor" labels while hovering with the Selection tool, #812) | 2–4 |
| File formats | 6 | 85% | Affinity export, and the rest of Affinity import (effects, adjustments, brushes, master pages, live symbol instances), 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 rest of Illustrator's editing data (appearances and live effects, symbols, pattern fills, brushes, placed files: #637), the remaining fidelity polish; EPS, DXF, EMF/WMF, TIFF, BMP, Targa, PSD export, SVGZ, PDF security, PDF/X, PDF layers, presets and Affinity import are done | 6–10 (existing scope; Affinity export unestimated) |
| Export for Screens, Asset Export, slices, Save for Web | 3 | 85% | polish only (all four are done) | 2–4 |
| Print, colour management, separations, flattener | 3 | 80% | print preview fidelity (flattener presets in PDF and print, overprint in PDF and composite print, Print dialog, presets, PostScript, marks, separations, Print Tiling, print overprint/flattener/bitmap options and printer profile are done) | 1–2 |
+8 -2
View File
@@ -269,17 +269,23 @@ fn run(args: &[String]) -> Result<(), String> {
} else if !matches!(steps.first(), Some(Step::Cmd(id, _)) if id == "file.new") {
h.ensure_document();
}
// Each step's result, for later steps to refer to (`"$1.id"`, see `vectorcraft_engine::steps`).
let mut results = vec![];
for step in steps {
match step {
let r = match step {
Step::Cmd(id, params) => {
let params = vectorcraft_engine::steps::resolve(&params, &results).map_err(|e| format!("{id}: {e}"))?;
let r = h.call("engine.execute", json!({"command": id, "params": params})).map_err(|e| format!("{id}: {e}"))?;
emit(json!({"step": "cmd", "command": id, "result": r}))?;
r
}
Step::Export(path) => {
let r = h.call("app.export", json!({"path": path, "scale": scale})).map_err(|e| format!("export {path}: {e}"))?;
emit(json!({"step": "export", "result": r}))?;
r
}
}
};
results.push(r);
}
Ok(())
}
+22 -1
View File
@@ -31,7 +31,7 @@ use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, OnceLock};
use eframe::egui_wgpu::NativeAdapterSelectorMethod;
use eframe::wgpu::{self, Backend, DeviceType, PowerPreference};
use eframe::wgpu::{self, Backend, Backends, DeviceType, PowerPreference};
/// The adapters a restart leaves out, those the window failed on, as comma-separated [`key`]s
/// (`Vulkan:1002:164e`, `Metal:Intel Iris Pro Graphics`). Set by the app itself when it starts
@@ -81,6 +81,15 @@ pub fn preferred_displays(pref: Option<&str>, env: Option<PowerPreference>) -> V
if automatic(pref, env) { display_gpus() } else { Vec::new() }
}
/// The graphics backends the window starts with: on Windows Direct3D 12, falling back to OpenGL,
/// unless `WGPU_BACKEND` names others (`env_set`; `default` then holds them). Creating a Vulkan
/// instance loads every installed Vulkan driver into the process, and a faulty one (Intel's
/// `igvk64.dll`, #806) crashed the app before its window appeared. DX12 is Windows' own backend,
/// as in PdfCraft. Elsewhere, `default`.
pub fn backends(default: Backends, env_set: bool) -> Backends {
if cfg!(windows) && !env_set { Backends::DX12 | Backends::GL } else { default }
}
/// One adapter, as [`adapter_order`] sees it.
#[derive(Clone, Debug)]
pub struct Candidate {
@@ -809,6 +818,18 @@ mod tests {
assert_eq!(adapter_order(&c, PowerPreference::LowPower, &[], None, &[c[1].key.clone()]), [0, 3, 2], "DX12 failed: Vulkan next");
}
#[test]
fn windows_never_loads_vulkan_drivers_unless_asked() {
let all = Backends::all();
let start = backends(all, false);
if cfg!(windows) {
assert_eq!(start, Backends::DX12 | Backends::GL, "#806");
} else {
assert_eq!(start, all);
}
assert_eq!(backends(Backends::VULKAN, true), Backends::VULKAN, "WGPU_BACKEND=vulkan still picks it");
}
#[test]
fn power_preference_follows_the_environment_then_the_preference() {
assert_eq!(power_preference(None, None), AUTOMATIC);
+3 -3
View File
@@ -118,12 +118,11 @@ fn end_before_teardown(frames: u64) {
}
/// Open files handed to the app (command line, macOS Finder and Dock) as documents. A file that
/// can't be opened is reported in the status bar and on stderr; the others still open.
/// can't be opened is reported to the user and on stderr; the others still open.
fn open_files(app: &mut VectorcraftApp, files: Vec<String>) {
for f in files {
if let Err(e) = vectorcraft_ui_egui::io::open_path(app, &f) {
if let Err(e) = vectorcraft_ui_egui::io::open_reporting(app, &f) {
eprintln!("vectorcraft: {f}: {e}");
app.status(format!("Couldn't open {}: {e}", fileio::file_name(&f)));
}
}
}
@@ -467,6 +466,7 @@ fn main() -> std::process::ExitCode {
// Metal on an Iris Pro, #651). `WGPU_VALIDATION_INDIRECT_CALL=1` turns it back on.
create.instance_descriptor.flags =
(eframe::wgpu::InstanceFlags::from_build_config() - eframe::wgpu::InstanceFlags::VALIDATION_INDIRECT_CALL).with_env();
create.instance_descriptor.backends = gpu::backends(create.instance_descriptor.backends, std::env::var_os("WGPU_BACKEND").is_some());
}
options
};
+145 -1
View File
@@ -1,7 +1,8 @@
//! Swatch library files: the native `.vcswatches` JSON (colour models, global, spot, gradients
//! and colour groups exactly), `.gpl` palettes (8-bit RGB; colour groups as `# Group:` comment
//! headers), swatch exchange `.ase` files (binary: solid colors in their own model, global, spot
//! and process colors, color groups) and CSS custom properties (written only).
//! and process colors, color groups), color books `.acb` (read only: the books a user owns, such
//! as a Pantone book) and CSS custom properties (written only).
use std::collections::{HashMap, HashSet};
@@ -79,6 +80,8 @@ const ASE_MAX_ENTRIES: usize = 100_000;
/// The most UTF-16 code units of a name that are kept.
const ASE_MAX_NAME: usize = 1024;
const ASE_CUT_SHORT: &str = "the swatch exchange file is cut short";
const ACB_SIGNATURE: &[u8] = b"8BCB";
const ACB_CUT_SHORT: &str = "the color book is cut short";
/// Write `lib` in `format` → the file's bytes. Pattern swatches (their tiles live in a document)
/// and None are left out; `.gpl` keeps solid colours only, as 8-bit RGB, and `.ase` keeps solid
@@ -326,6 +329,9 @@ pub fn read_bytes(bytes: &[u8], name: &str) -> Result<SwatchLibrary, String> {
if bytes.starts_with(ASE_SIGNATURE) {
return read_ase(bytes, name);
}
if bytes.starts_with(ACB_SIGNATURE) {
return read_acb(bytes, name).map_err(|e| if e == ASE_CUT_SHORT { ACB_CUT_SHORT.into() } else { e });
}
read(&String::from_utf8_lossy(bytes), name)
}
@@ -333,6 +339,7 @@ pub fn read_bytes(bytes: &[u8], name: &str) -> Result<SwatchLibrary, String> {
/// [`read_bytes`] reads it, with the invalid bytes replaced (its first KiB is enough).
pub fn sniff_bytes(bytes: &[u8]) -> bool {
bytes.starts_with(ASE_SIGNATURE)
|| bytes.starts_with(ACB_SIGNATURE)
|| std::str::from_utf8(bytes).is_ok_and(sniff)
|| sniff(&String::from_utf8_lossy(bytes.get(..1024).unwrap_or(bytes)))
}
@@ -427,6 +434,67 @@ fn read_ase(bytes: &[u8], fallback: &str) -> Result<SwatchLibrary, String> {
Ok(lib)
}
/// `.acb` (a color book, read only), from public descriptions of the format: after the signature
/// come, big-endian, a `u16` version (1) and book id, the title, prefix, suffix and description
/// as strings, a `u16` color count, page size and page selector offset, a `u16` color space (0
/// RGB, 2 CMYK, 7 Lab) and the colors: each a name, a six-character catalog code and its
/// components as bytes. RGB runs from 0 to 255, CMYK ink is stored inverted (255 is no ink), Lab
/// lightness is 0 to 255 for 0 to 100 and a and b are offset by 128. A string is a `u32` count of
/// UTF-16 code units, then the units; a `$$$/key=Text` string means `Text`, and `^R`, `^C` stand
/// for ® and ©. An optional `spflspot` or `spflproc` at the end says whether the colors are spot
/// or process colors (a book without it is a spot color book).
///
/// The book's colors are named with its prefix and suffix ("PANTONE 185 C"); colors without a
/// name (the padding of a book's pages) are left out. A version other than 1, a color space other
/// than those three or more than [`ASE_MAX_ENTRIES`] colors is an error.
fn read_acb(bytes: &[u8], fallback: &str) -> Result<SwatchLibrary, String> {
let mut data = AseData(bytes);
data.bytes(ACB_SIGNATURE.len())?;
let version = data.u16()?;
if version != 1 {
return Err(format!("color book version {version} isn't supported (only 1)"));
}
let _book_id = data.u16()?;
let [title, prefix, suffix, _description] = [data.acb_string()?, data.acb_string()?, data.acb_string()?, data.acb_string()?];
let count = usize::from(data.u16()?);
if count > ASE_MAX_ENTRIES {
return Err(format!("the color book holds more than {ASE_MAX_ENTRIES} colors"));
}
let (_page_size, _page_offset) = (data.u16()?, data.u16()?);
let space = data.u16()?;
let mut colors = Vec::with_capacity(count);
for _ in 0..count {
let name = data.acb_string()?;
let _code = data.bytes(6)?;
let color = match space {
0 => {
let [r, g, b] = data.array::<3>()?;
Color::rgb8(r, g, b)
}
2 => {
let ink = |v: u8| f32::from(255 - v) / 255.0;
let [c, m, y, k] = data.array::<4>()?;
Color::cmyk(ink(c), ink(m), ink(y), ink(k))
}
7 => {
let [l, a, b] = data.array::<3>()?;
Color::lab(f32::from(l) * 100.0 / 255.0, f32::from(a) - 128.0, f32::from(b) - 128.0)
}
other => return Err(format!("color books in color space {other} aren't supported (only RGB, CMYK and Lab)")),
};
colors.push((name, color));
}
// Spot colors unless the book says process ones.
let spot = data.0.windows(8).last() != Some(b"spflproc".as_slice());
let mut lib = SwatchLibrary { name: if title.is_empty() { fallback.into() } else { title }, ..Default::default() };
let mut names = UniqueNames::default();
for (name, color) in colors.into_iter().filter(|(n, _)| !n.trim().is_empty()) {
let name = names.unique(format!("{prefix}{name}{suffix}").trim().to_string());
lib.swatches.push(Swatch { name, paint: Paint::solid(color), global: spot, spot });
}
Ok(lib)
}
/// The swatch of an `.ase` color block, `None` for a model other than RGB, CMYK, Lab and Gray.
/// Components are clamped to their ranges.
fn ase_swatch(body: &mut AseData) -> Result<Option<Swatch>, String> {
@@ -503,6 +571,20 @@ impl<'a> AseData<'a> {
let v = f32::from_be_bytes(self.array()?);
Ok(if v.is_finite() { v } else { 0.0 })
}
/// A color book string ([`read_acb`]): a `u32` count of UTF-16 code units, then the units,
/// with `$$$/key=Text` read as `Text` and `^R`, `^C` as ®, ©; at most [`ASE_MAX_NAME`] units
/// are kept.
fn acb_string(&mut self) -> Result<String, String> {
let n = usize::try_from(self.u32()?).unwrap_or(usize::MAX);
let (units, _) = self.bytes(n.checked_mul(2).ok_or(ASE_CUT_SHORT)?)?.as_chunks::<2>();
let units: Vec<u16> = units.iter().take(ASE_MAX_NAME).map(|u| u16::from_be_bytes(*u)).take_while(|&u| u != 0).collect();
let s = String::from_utf16_lossy(&units);
let s = match s.strip_prefix("$$$/") {
Some(key) => key.split_once('=').map_or("", |(_, text)| text).to_string(),
None => s,
};
Ok(s.replace("^R", "®").replace("^C", "©"))
}
/// A name up to its terminating zero, trimmed. A block that ends before it has no name.
fn name(&mut self) -> Result<String, String> {
if self.0.is_empty() {
@@ -553,6 +635,68 @@ mod tests {
use crate::{Gradient, GradientPaint, GradientStop};
use proptest::prelude::*;
/// A color book's string: a `u32` count of UTF-16 code units, then the units.
fn acb_str(out: &mut Vec<u8>, s: &str) {
let units: Vec<u16> = s.encode_utf16().collect();
out.extend((units.len() as u32).to_be_bytes());
units.iter().for_each(|u| out.extend(u.to_be_bytes()));
}
/// A color book in `space` (0 RGB, 2 CMYK, 7 Lab) with `colors` (name, components) and an
/// optional spot/process marker.
fn acb(space: u16, colors: &[(&str, &[u8])], marker: &[u8]) -> Vec<u8> {
let mut b = b"8BCB".to_vec();
b.extend(1u16.to_be_bytes());
b.extend(3000u16.to_be_bytes());
for s in ["$$$/colorbook/Test/title=Test Book^R", "TEST ", " C", "a book"] {
acb_str(&mut b, s);
}
b.extend((colors.len() as u16).to_be_bytes());
b.extend(7u16.to_be_bytes());
b.extend(0u16.to_be_bytes());
b.extend(space.to_be_bytes());
for (name, comps) in colors {
acb_str(&mut b, name);
b.extend(b"TST001");
b.extend(*comps);
}
b.extend(marker);
b
}
/// #831: color books (`.acb`) are read: their colors in RGB, CMYK or Lab, named with the book's
/// prefix and suffix, spot unless the book says process; page padding is left out.
#[test]
fn color_books_are_read() {
let lib = read_bytes(&acb(0, &[("185", &[228, 0, 43]), ("", &[0, 0, 0]), ("Red 032", &[239, 51, 64])], b"spflspot"), "fallback").unwrap();
assert_eq!(lib.name, "Test Book®");
let names: Vec<&str> = lib.swatches.iter().map(|s| s.name.as_str()).collect();
assert_eq!(names, ["TEST 185 C", "TEST Red 032 C"]);
assert!(lib.swatches.iter().all(|s| s.spot && s.global));
assert_eq!(lib.swatches[0].paint.color(), Some(Color::rgb8(228, 0, 43)));
// CMYK ink is stored inverted; a book marked process gives process colors.
let lib = read_bytes(&acb(2, &[("Cyan", &[0, 255, 255, 255])], b"spflproc"), "x").unwrap();
assert_eq!(lib.swatches[0].paint.color(), Some(Color::cmyk(1.0, 0.0, 0.0, 0.0)));
assert!(!lib.swatches[0].spot && !lib.swatches[0].global);
// Lab: lightness 0..255 for 0..100, a and b offset by 128; no marker: spot.
let lib = read_bytes(&acb(7, &[("Grey", &[255, 128, 128])], b""), "x").unwrap();
assert_eq!(lib.swatches[0].paint.color(), Some(Color::lab(100.0, 0.0, 0.0)));
assert!(lib.swatches[0].spot);
assert!(sniff_bytes(&acb(0, &[], b"")));
// Unsupported versions and color spaces, and short files, are errors.
let mut v2 = acb(0, &[], b"");
v2[5] = 2;
assert!(read_bytes(&v2, "x").is_err());
assert!(read_bytes(&acb(1, &[("x", &[1, 2, 3])], b""), "x").is_err());
let full = acb(0, &[("185", &[228, 0, 43])], b"");
for cut in 4..full.len() {
assert!(read_bytes(&full[..cut], "x").is_err(), "{cut} bytes");
}
let mut huge = b"8BCB\0\x01\0\x01".to_vec();
huge.extend(u32::MAX.to_be_bytes());
assert!(read_bytes(&huge, "x").is_err(), "a string longer than the file");
}
fn sample() -> SwatchLibrary {
let grad = Paint::Gradient(Box::new(GradientPaint::new(Gradient {
kind: GradientKind::Linear,
+20 -5
View File
@@ -86,6 +86,19 @@ pub fn objects_at(doc: &Document, p: Point, opt: HitOptions, scope: Option<NodeI
/// [`hit_test`] passing over the nodes `skip` names (and their contents).
fn hit_test_skipping(doc: &Document, p: Point, opt: HitOptions, skip: &dyn Fn(NodeId) -> bool) -> Option<Hit> {
let finish = |mut h: Hit| {
h.contents_of = h.ancestry.iter().rev().copied().find(|a| doc.node(*a).is_some_and(edits_contents));
h.layers = h.ancestry.iter().take_while(|a| doc.node(**a).is_some_and(Node::is_layer)).count();
h
};
// Isolation mode: only what is inside the isolated container hits. The art around it is
// locked, and clicks pass through it (#833).
if let Some(scope) = opt.scope
&& let Some(container) = doc.node(scope).filter(|n| n.is_container())
&& let Some(mut chain) = doc.ancestry(scope)
{
return hit_children(container, p, opt, skip, &mut chain).map(finish);
}
let mut chain = Vec::new();
for layer in doc.layers.iter().rev() {
if !layer.visible || layer.locked {
@@ -100,10 +113,8 @@ fn hit_test_skipping(doc: &Document, p: Point, opt: HitOptions, skip: &dyn Fn(No
}
chain.push(layer.id);
let opt = if matches!(layer.kind, NodeKind::Layer { preview: false, .. }) { HitOptions { outline: true, ..opt } } else { opt };
if let Some(mut h) = hit_children(layer, p, opt, skip, &mut chain) {
h.contents_of = h.ancestry.iter().rev().copied().find(|a| doc.node(*a).is_some_and(edits_contents));
h.layers = h.ancestry.iter().take_while(|a| doc.node(**a).is_some_and(Node::is_layer)).count();
return Some(h);
if let Some(h) = hit_children(layer, p, opt, skip, &mut chain) {
return Some(finish(h));
}
chain.pop();
}
@@ -560,7 +571,11 @@ world",
d.insert(Some(l), 9, far).unwrap();
let at = |x: f64, scope| objects_at(&d, Point::new(x, 25.0), HitOptions::default(), scope);
assert_eq!(at(30.0, None), vec![g, a_id]);
assert_eq!(at(30.0, Some(g))[..2], [c_id, b_id], "isolated: the group's own objects");
assert_eq!(at(30.0, Some(g)), [c_id, b_id], "isolated: the group's own objects");
// Isolated, the art around the group is locked: clicks pass through it (#833).
assert!(at(5.0, Some(g)).is_empty());
assert!(at(130.0, Some(g)).is_empty());
assert!(hit_test(&d, Point::new(5.0, 25.0), HitOptions { scope: Some(g), ..HitOptions::default() }).is_none());
assert_eq!(at(5.0, None), vec![a_id]);
assert!(at(90.0, None).is_empty());
}
+7
View File
@@ -52,6 +52,13 @@ impl RasterFx {
pub fn is_below(&self) -> bool {
matches!(self, RasterFx::DropShadow { .. } | RasterFx::OuterGlow { .. })
}
/// The blend mode it paints with (shadows and glows).
pub fn mode(&self) -> Option<BlendMode> {
match self {
RasterFx::DropShadow { mode, .. } | RasterFx::OuterGlow { mode, .. } | RasterFx::InnerGlow { mode, .. } => Some(*mode),
_ => None,
}
}
/// 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 {
+79
View File
@@ -36,6 +36,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
curvature
),
cmd!(
"path.curvatureEdit",
"Curvature",
[],
None,
"{id, subpath?, op: \"move\"|\"insert\"|\"extend\"|\"close\", anchor?, segment?, t?, end?: \"start\"|\"end\", from?: \"keep\"|\"smooth\"|\"corner\", x?, y?} edit a path as the Curvature tool does, its shape kept elsewhere; the anchor edited becomes the direct-selected one → {anchor}. move: anchor to x, y, re-curving only its two segments; insert: a smooth anchor at t on segment, the shape unchanged (with x, y: then moved there); extend: an open subpath goes on from its end (default) or start to a new end at x, y; close: an open subpath closes from that end. The old end bends into the new segment as from says: keep its curve (default), smooth through its neighbours, or a corner",
has_doc,
curvature_edit
),
cmd!(
"path.removeAnchor",
"Delete Anchor Point",
@@ -593,6 +602,76 @@ fn curvature(s: &mut Session, p: &Value) -> Result<Value> {
add_look(s, "Curvature", path_kind(PathData::single(sp)), look, None)
}
/// An edit `path.curvatureEdit` makes.
enum CurvatureOp {
Move(usize, Point),
Insert(usize, f64, Option<Point>),
Extend(Point),
Close,
}
fn curvature_edit(s: &mut Session, p: &Value) -> Result<Value> {
use vectorcraft_tools::draw2::{EndCurve, curvature_close, curvature_extend, curvature_insert, curvature_move};
const C: &str = "path.curvatureEdit";
let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?;
let si = p.get("subpath").and_then(Value::as_u64).unwrap_or(0) as usize;
let at = match (p.get("x").and_then(Value::as_f64), p.get("y").and_then(Value::as_f64)) {
(Some(x), Some(y)) if x.is_finite() && y.is_finite() => Some(Point::new(x, y)),
(None, None) => None,
_ => return Err(bad(C, "x and y must be finite numbers")),
};
let to = || at.ok_or_else(|| bad(C, "missing x, y"));
let start = match str_param(p, "end") {
None | Some("end") => false,
Some("start") => true,
Some(e) => return Err(bad(C, format!("unknown end {e:?}"))),
};
let how = match str_param(p, "from") {
None => EndCurve::Keep,
Some(f) => EndCurve::parse(f).ok_or_else(|| bad(C, format!("unknown from {f:?}")))?,
};
let op = match str_param(p, "op") {
Some("move") => CurvatureOp::Move(usize_req(p, "anchor", C)?, to()?),
Some("insert") => CurvatureOp::Insert(usize_req(p, "segment", C)?, f64_or(p, "t", 0.5), at),
Some("extend") => CurvatureOp::Extend(to()?),
Some("close") => CurvatureOp::Close,
Some(o) => return Err(bad(C, format!("unknown op {o:?}"))),
None => return Err(bad(C, "missing op")),
};
let anchor = s.edit("Curvature", |d, sel| {
let path = path_mut(d, id)?;
let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?;
if matches!(op, CurvatureOp::Extend(_) | CurvatureOp::Close) && sp.closed {
return Err(EngineError::Other("path is already closed".into()));
}
let ai = match op {
CurvatureOp::Move(ai, q) => curvature_move(sp, ai, q).then_some(ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?,
CurvatureOp::Insert(seg, t, q) => {
let ai = curvature_insert(sp, seg, t).ok_or_else(|| EngineError::Other("no such segment".into()))?;
if let Some(q) = q {
curvature_move(sp, ai, q);
}
ai
}
CurvatureOp::Extend(q) => {
curvature_extend(sp, start, q, how);
if start { 0 } else { sp.anchors.len() - 1 }
}
CurvatureOp::Close => {
if sp.anchors.len() < 3 {
return Err(EngineError::Other("closing needs three anchors".into()));
}
curvature_close(sp, start, how);
if start { sp.anchors.len() - 1 } else { 0 }
}
};
sel.set([id]);
sel.anchors.insert(id, [(si, ai)].into());
Ok(ai)
})?;
Ok(json!({ "anchor": anchor }))
}
// ---------- anchor tools ----------
fn remove_anchor(s: &mut Session, p: &Value) -> Result<Value> {
+15 -5
View File
@@ -366,13 +366,23 @@ pub fn color_value(v: &Value) -> Option<Color> {
/// Objects a command targets: explicit `ids` param or the selection.
pub(crate) fn targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
if let Some(ids) = ids_param(p, "ids") {
return Ok(ids);
// Objects given are used as given: a value that isn't an object id fails rather than the
// command acting on the selection instead (#785).
let object_id = |v: &Value| v.as_u64().map(NodeId).ok_or_else(|| EngineError::Other(format!("object ids are non-negative integers, not {v}")));
match p.get("ids").filter(|v| !v.is_null()) {
Some(Value::Array(a)) => return a.iter().map(object_id).collect(),
Some(v) => return Err(EngineError::Other(format!("`ids` must be an array of object ids, not {v}"))),
None => {}
}
if let Some(id) = id_param(p, "id") {
return Ok(vec![id]);
match p.get("id").filter(|v| !v.is_null()) {
Some(v @ Value::Number(_)) => Ok(vec![object_id(v)?]),
// A step reference a batch couldn't resolve (other strings are other ids, such as an
// effect's).
Some(Value::String(r)) if r.starts_with('$') => {
Err(EngineError::Other(format!("`id` is the step reference {r:?}, which only `run` and `command_batch` resolve")))
}
_ => Ok(s.doc()?.selection.objects.clone()),
}
Ok(s.doc()?.selection.objects.clone())
}
pub(crate) fn ok() -> Result<Value> {
+46 -6
View File
@@ -15,7 +15,7 @@
use std::sync::Arc;
use serde_json::{Map, Value, json};
use vectorcraft_color::Paint;
use vectorcraft_color::{BlendMode, Paint};
use vectorcraft_doc::rastersettings::MAX_ADD_AROUND;
use vectorcraft_doc::{
Appearance, AppearanceItem, ColorMode, Document, Effect, ImageBlob, ImageObject, Node, NodeId, NodeKind, RasterColorModel, StrokeLayer,
@@ -217,18 +217,55 @@ pub(crate) fn raster_fx(n: &Node) -> Vec<RasterFx> {
/// Remove the raster effects of `n` (its own and its fills' and strokes') and, with `members`, of
/// everything inside it.
pub(crate) fn strip_raster(n: &mut Node, members: bool) {
let keep = |e: &Effect| !effects::is_raster(&e.id);
retain_effects(n, members, &|e| !effects::is_raster(&e.id));
}
/// Keep the effects of `n` (its own and its fills' and strokes') that `keep` accepts and, with
/// `members`, of everything inside it.
fn retain_effects(n: &mut Node, members: bool, keep: &dyn Fn(&Effect) -> bool) {
n.appearance.effects.retain(keep);
for it in &mut n.appearance.items {
it.effects_mut().retain(keep);
}
if members {
for c in n.children_mut().into_iter().flatten() {
strip_raster(Arc::make_mut(c), true);
retain_effects(Arc::make_mut(c), true, keep);
}
}
}
/// The blend mode raster effect `e` paints with (`None`: not a raster effect, or one without).
fn effect_mode(e: &Effect) -> Option<BlendMode> {
effects::raster_effects(std::slice::from_ref(e)).first().and_then(RasterFx::mode)
}
/// The images of the shadows and outer glows of `n`, one per blend mode they use (in the order
/// the modes first come), each composited with its mode: rendered alone, over nothing, they can't
/// blend with the art below the object, so the image does.
fn below_images(d: &mut Document, n: &Node) -> Option<Vec<Node>> {
let mut modes: Vec<BlendMode> = vec![];
for mode in raster_fx(n).iter().filter_map(RasterFx::mode) {
if !modes.contains(&mode) {
modes.push(mode);
}
}
if modes.len() < 2 {
let mut image = raster_image(d, n, true, false)?;
image.blend = modes.first().copied().unwrap_or_default();
return Some(vec![image]);
}
modes
.into_iter()
.map(|mode| {
let mut only = n.clone();
retain_effects(&mut only, false, &|e| effect_mode(e).is_none_or(|m| m == mode));
let mut image = raster_image(d, &only, true, false)?;
image.blend = mode;
Some(image)
})
.collect()
}
/// The raster effects of `n` (its own, its fills' and strokes') as an embedded image of `d`
/// rendered at the document's raster effects resolution, without `n`'s transparency (that stays
/// on the object). With `below` (they all paint below it: shadows and outer glows) the image holds
@@ -405,15 +442,18 @@ fn walk(out: &mut Document, n: &Node, which: Which) -> Option<Node> {
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 images = below_images(out, n)?;
let mut m = walk(out, &v, which).unwrap_or(v);
put_below(out, &mut m, image);
// Each goes in first: the last one put is the lowest.
for image in images.into_iter().rev() {
put_below(out, &mut m, image);
}
m
} else {
replace_with_image(v, image)
replace_with_image(v, raster_image(out, n, false, false)?)
};
walk_mask(out, &mut m, which);
Some(m)
+2 -2
View File
@@ -72,7 +72,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Other Library…",
["Window", "Swatch Libraries"],
None,
"{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} load a .vcswatches, .gpl or .ase (swatch exchange) library, or the swatches of any document VectorCraft opens (see document.formats), for the library panel (Window → Swatch Libraries lists it until the app quits; a file of the user library folder, or a file with the same extension and bytes as one there, opens as that User Defined library) → {library: id, name, count}",
"{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} load a .vcswatches, .gpl, .ase (swatch exchange) or .acb (color book, read only) library, or the swatches of any document VectorCraft opens (see document.formats), for the library panel (Window → Swatch Libraries lists it until the app quits; a file of the user library folder, or a file with the same extension and bytes as one there, opens as that User Defined library) → {library: id, name, count}",
always,
load
),
@@ -130,7 +130,7 @@ impl LibraryFile for SwatchLibrary {
}
/// The extensions of library files [`palette_io::read_bytes`] reads.
pub const LIBRARY_EXTS: &[&str] = &["vcswatches", "gpl", "ase"];
pub const LIBRARY_EXTS: &[&str] = &["vcswatches", "gpl", "ase", "acb"];
/// A library file the save commands write ([`Libraries::write`]).
pub(crate) enum FileData {
+9 -2
View File
@@ -27,7 +27,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Character",
[],
None,
"{id, start?: byte, end?: byte (default: all text), font?, style?, size?: pt, leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, fill?: colour|\"none\", stroke?: colour|\"none\", strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", …], charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\"} style a character range (runs are split at the range ends) → {id, runs}",
"{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), font?, style?, size?: pt, leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, fill?: colour|\"none\", stroke?: colour|\"none\", strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", …], charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\"} style a character range (runs are split at the range ends) → {id, runs}",
has_doc,
set_range_style
),
@@ -420,7 +420,14 @@ pub(crate) fn protect_missing_glyphs(before: &[TextRun], runs: &mut Vec<TextRun>
fn set_range_style(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "text.setRangeStyle";
let id = id_param(p, "id").ok_or_else(|| bad(C, "missing `id`"))?;
// The type object given, else the one selected (#785).
let id = match p.get("id").filter(|v| !v.is_null()) {
Some(v) => v.as_u64().map(NodeId).ok_or_else(|| bad(C, format!("`id` must be an object id, not {v}")))?,
None => match super::typecmd::text_targets(s, &json!({}), C)?.as_slice() {
[one] => *one,
_ => return Err(bad(C, "missing `id`: give one, or select one type object")),
},
};
let change = CharChange::parse(p, C, &s.doc()?.doc.setup)?;
if change.is_empty() {
return Err(bad(C, "nothing to change"));
+15 -1
View File
@@ -142,6 +142,17 @@ fn de_key<'de, T: Keyed, D: Deserializer<'de>>(d: D) -> std::result::Result<T, D
T::parse(&s).ok_or_else(|| D::Error::custom(format!("`{s}`: {}", T::KEYS)))
}
/// A size in pixels: a number, rounded to whole pixels (`300.0` is 300).
fn de_pixels<'de, D: Deserializer<'de>>(d: D) -> std::result::Result<Option<u32>, D::Error> {
let Some(v) = Option::<f64>::deserialize(d)? else { return Ok(None) };
let px = v.round();
if !(px.is_finite() && px >= 0.0 && px <= f64::from(u32::MAX)) {
return Err(D::Error::custom(format!("{v} is not a size in pixels")));
}
// In range and whole: the cast is exact.
Ok(Some(px as u32))
}
/// The file format.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
@@ -361,8 +372,10 @@ pub struct WebSettings {
/// JPEG: embed the sRGB profile.
pub embed_profile: bool,
/// The image width in pixels (the height follows).
#[serde(deserialize_with = "de_pixels")]
pub width: Option<u32>,
/// The image height in pixels (the width follows).
#[serde(deserialize_with = "de_pixels")]
pub height: Option<u32>,
/// The image size in percent of the art's size in points.
pub percent: Option<f64>,
@@ -569,7 +582,8 @@ pub fn render(doc: &Document, s: &WebSettings) -> std::result::Result<WebRender,
let doc = doc.without_edit_modes();
let (region, scale) = region(&doc, s)?;
let page = (doc.setup.background == vectorcraft_doc::Background::White).then_some([255; 4]);
let opts = vectorcraft_render::RenderOptions { background: page, skip_templates: true, anti_alias: s.anti_alias, ..Default::default() };
let opts =
vectorcraft_render::RenderOptions { background: page, skip_templates: true, anti_alias: s.anti_alias, precise: true, ..Default::default() };
let img = vectorcraft_render::Renderer::new().render_region_with(&doc, region, scale, &opts);
Ok(WebRender { rgba: img.to_straight(), width: img.width, height: img.height, region, scale })
}
+1
View File
@@ -9,6 +9,7 @@
pub mod cmd;
pub mod guard;
pub mod inspect;
pub mod steps;
mod tooling;
pub mod units;
+138
View File
@@ -0,0 +1,138 @@
//! References between the steps of a batch (`vectorcraft-cli run`, MCP `command_batch`): a
//! parameter string that is exactly `$N` or `$N.path` takes that value from the result of step `N`
//! (0-based, in the order the steps ran), and `$last…` from the step before. A path goes into
//! objects by key and into arrays by index: `$1.id`, `$2.ids.0`, `$last.ids[0]`. `$$` at the start
//! of a string stands for one `$` and is never a reference (text such as `$$1.99`). A string that
//! looks like a reference but names no value is an error, so a step never runs with a reference
//! left in it.
use serde_json::Value;
/// Most nesting [`resolve`] walks into: deeper parameters are left as they are.
const MAX_DEPTH: usize = 64;
/// `params` with every step reference replaced from `results` (the results of the steps run so
/// far, in order); an error names a reference that resolves to nothing.
pub fn resolve(params: &Value, results: &[Value]) -> Result<Value, String> {
resolve_at(params, results, 0)
}
fn resolve_at(v: &Value, results: &[Value], depth: usize) -> Result<Value, String> {
if depth > MAX_DEPTH {
return Ok(v.clone());
}
Ok(match v {
Value::String(s) => match s.strip_prefix("$$") {
Some(rest) => Value::String(format!("${rest}")),
None => match parse(s) {
Some((step, path)) => lookup(s, step, &path, results)?,
None => v.clone(),
},
},
Value::Array(a) => Value::Array(a.iter().map(|x| resolve_at(x, results, depth + 1)).collect::<Result<_, _>>()?),
Value::Object(o) => Value::Object(o.iter().map(|(k, x)| Ok((k.clone(), resolve_at(x, results, depth + 1)?))).collect::<Result<_, String>>()?),
_ => v.clone(),
})
}
/// Which step a reference names.
#[derive(Debug, PartialEq)]
enum Step {
Index(usize),
Last,
}
/// A path segment: an object key or an array index (`.0` is either, as the value decides).
#[derive(Debug, PartialEq)]
enum Seg {
Key(String),
Index(usize),
}
/// `$N…` or `$last…` → the step and the path after it; `None` for any other string.
fn parse(s: &str) -> Option<(Step, Vec<Seg>)> {
let rest = s.strip_prefix('$')?;
let digits = rest.bytes().take_while(u8::is_ascii_digit).count();
let (step, mut rest) = if digits > 0 {
let (n, rest) = rest.split_at_checked(digits)?;
(Step::Index(n.parse().ok()?), rest)
} else {
(Step::Last, rest.strip_prefix("last")?)
};
let mut path = vec![];
while !rest.is_empty() {
if let Some(r) = rest.strip_prefix('.') {
let len = r.bytes().take_while(|b| b.is_ascii_alphanumeric() || *b == b'_').count();
let (key, r) = r.split_at_checked(len)?;
if key.is_empty() {
return None;
}
path.push(Seg::Key(key.to_string()));
rest = r;
} else {
let (n, r) = rest.strip_prefix('[')?.split_once(']')?;
path.push(Seg::Index(n.parse().ok()?));
rest = r;
}
}
Some((step, path))
}
fn lookup(text: &str, step: Step, path: &[Seg], results: &[Value]) -> Result<Value, String> {
let (i, found) = match step {
Step::Index(i) => (i, results.get(i)),
Step::Last => (results.len().saturating_sub(1), results.last()),
};
let mut cur = found.ok_or_else(|| format!("`{text}`: there is no step {i} before this one (steps count from 0; write $$ for a literal $)"))?;
for seg in path {
let next = match (seg, cur) {
(Seg::Key(k), Value::Object(o)) => o.get(k),
(Seg::Key(k), Value::Array(a)) => k.parse::<usize>().ok().and_then(|n| a.get(n)),
(Seg::Index(n), Value::Array(a)) => a.get(*n),
_ => None,
};
cur = next.ok_or_else(|| format!("`{text}`: step {i}'s result has no such value (write $$ for a literal $)"))?;
}
Ok(cur.clone())
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
#[test]
fn references_take_values_from_earlier_results() {
let results = [json!({"index": 0}), json!({"id": 2}), json!({"ids": [5, 6]})];
let p = json!({"id": "$1.id", "ids": ["$2.ids.1", "$last.ids[0]"], "nested": {"all": "$2"}, "n": 3, "flag": true});
assert_eq!(resolve(&p, &results).unwrap(), json!({"id": 2, "ids": [6, 5], "nested": {"all": {"ids": [5, 6]}}, "n": 3, "flag": true}));
}
#[test]
fn plain_strings_and_escapes_are_left_alone() {
let results = [json!({"id": 2})];
let p = json!({"text": "costs $1", "price": "$$1.99", "name": "a$1.id", "dollar": "$", "word": "$lastname"});
assert_eq!(
resolve(&p, &results).unwrap(),
json!({"text": "costs $1", "price": "$1.99", "name": "a$1.id", "dollar": "$", "word": "$lastname"})
);
}
#[test]
fn a_reference_to_nothing_is_an_error() {
let results = [json!({"id": 2})];
for bad in ["$1", "$1.id", "$0.ids", "$0.id.x", "$last.nope", "$7[0]"] {
let e = resolve(&json!({"id": bad}), &results).unwrap_err();
assert!(e.contains(bad), "{bad}: {e}");
}
assert!(resolve(&json!({"id": "$last"}), &[]).is_err(), "no step before the first");
// Huge indexes and deep nesting don't panic.
assert!(resolve(&json!("$99999999999999999999999.id"), &results).is_ok_and(|v| v == json!("$99999999999999999999999.id")));
let mut deep = json!("$0.id");
for _ in 0..200 {
deep = json!([deep]);
}
assert!(resolve(&deep, &results).is_ok());
}
}
+27
View File
@@ -853,3 +853,30 @@ fn new_layers_and_sublayers_are_numbered_together() {
let sub = s.execute("layer.newSublayer", &json!({})).unwrap();
assert_eq!(name(&s, &sub), "Layer 4", "the art doesn't count");
}
/// #785: objects given are used as given (a value that isn't an object id fails, never the
/// selection instead), and `text.setRangeStyle` works on the selected type object without `id`.
#[test]
fn given_targets_are_used_as_given_and_range_style_takes_the_selected_type() {
let mut s = session();
let first = s.execute("text.create", &json!({"x": 10, "y": 60, "text": "first", "size": 30})).unwrap()["id"].clone();
s.execute("text.create", &json!({"x": 10, "y": 140, "text": "second", "size": 30})).unwrap();
for bad in [
json!({"id": "$1.id", "size": 60}),
json!({"id": 2.5, "size": 60}),
json!({"ids": [first.clone(), "$1.id"], "size": 60}),
json!({"ids": 3, "size": 60}),
] {
assert!(s.execute("text.setStyle", &bad).is_err(), "{bad}");
}
// Another kind of id (an effect's) is still not an object id.
let sel = s.doc().unwrap().selection.objects.clone();
assert!(s.execute("effect.apply", &json!({"id": "stylize.dropShadow"})).is_ok());
assert_eq!(s.doc().unwrap().selection.objects, sel);
// The selected type object (the second) is styled when no id is given.
let r = s.execute("text.setRangeStyle", &json!({"start": 0, "end": 3, "style": "Bold"})).unwrap();
assert_ne!(r["id"], first);
s.execute("select.all", &json!({})).unwrap();
assert!(s.execute("text.setRangeStyle", &json!({"start": 0, "end": 3, "size": 40})).is_err(), "two type objects: which one?");
assert!(s.execute("text.setRangeStyle", &json!({"id": "two", "size": 40})).is_err());
}
+62
View File
@@ -197,6 +197,68 @@ fn curvature_click_first_point_closes() {
assert_eq!(p.anchor_count(), 3);
}
/// The Curvature tool edits a path another tool drew (#798), one undo step per edit, keeping its
/// shape except where edited.
#[test]
fn curvature_edits_any_selected_path() {
let mut s = session();
let v = view();
let anchors = json!([
{"x": 100, "y": 300},
{"x": 200, "y": 200, "in": [160, 210], "out": [260, 185]},
{"x": 350, "y": 280, "in": [320, 230], "out": [380, 330]},
{"x": 450, "y": 350, "in": [420, 360], "out": [480, 300]},
{"x": 550, "y": 260, "in": [520, 290]}
]);
let id = NodeId(s.execute("path.create", &json!({ "anchors": anchors })).unwrap()["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.select_tool("curvature", v).unwrap();
let before = path(&s, id).subpaths[0].clone();
// Drag a point: only its two segments change.
assert_eq!(gesture(&mut s, &[(350.0, 280.0), (360.0, 320.0), (370.0, 340.0)], Mods::default()), 1);
let sp = path(&s, id).subpaths[0].clone();
assert_eq!(sp.anchors[2].p, Point::new(370.0, 340.0));
assert_eq!((sp.segment(0), sp.segment(3)), (before.segment(0), before.segment(3)));
assert_eq!(s.doc().unwrap().selection.anchors.get(&id).map(|a| a.len()), Some(1), "the point is current");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(path(&s, id).subpaths[0], before);
// Alt-click toggles it, Delete removes the current point: one step each.
let (alt, steps) = (Mods { alt: true, ..Default::default() }, undo_steps(&s));
assert_eq!(gesture(&mut s, &[(200.0, 200.0)], alt), 1);
assert!(!path(&s, id).subpaths[0].anchors[1].has_out());
s.tool_key(ToolKey::Delete, Mods::default(), v).unwrap();
assert_eq!(path(&s, id).anchor_count(), 4);
assert_eq!(undo_steps(&s), steps + 2);
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(path(&s, id).subpaths[0], before);
// A press on a segment adds a point, the drag moving it: one step.
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
let on = kurbo::ParamCurve::eval(&before.segment(3), 0.5);
assert_eq!(gesture(&mut s, &[(on.x, on.y), (on.x, on.y + 20.0), (on.x, on.y + 30.0)], Mods::default()), 1);
let sp = path(&s, id).subpaths[0].clone();
assert_eq!(sp.anchors.len(), 6);
assert_eq!(sp.anchors[4].p, Point::new(on.x, on.y + 30.0));
assert_eq!((sp.segment(0), sp.segment(1), sp.segment(2)), (before.segment(0), before.segment(1), before.segment(2)));
s.execute("edit.undo", &json!({})).unwrap();
// A click on an end, then two more: the path goes on, its old segments unchanged.
let steps = undo_steps(&s);
for (x, y) in [(550.0, 260.0), (650.0, 300.0), (720.0, 220.0)] {
gesture(&mut s, &[(x, y)], Mods::default());
}
assert_eq!(undo_steps(&s), steps + 2, "selecting the end is no step");
let sp = path(&s, id).subpaths[0].clone();
assert_eq!(sp.anchors.len(), 7);
assert!((0..4).all(|i| sp.segment(i) == before.segment(i)));
assert_eq!(sp.anchors[6].p, Point::new(720.0, 220.0));
// The other end closes it; Esc and a click away start a new path.
gesture(&mut s, &[(100.0, 300.0)], Mods::default());
assert!(path(&s, id).is_closed());
s.tool_key(ToolKey::Escape, Mods::default(), v).unwrap();
gesture(&mut s, &[(700.0, 550.0)], Mods::default());
assert_eq!(paths(&s).len(), 2);
}
#[test]
fn add_and_delete_anchor_tools() {
let mut s = session();
+32
View File
@@ -150,3 +150,35 @@ fn live_objects_and_single_fills_and_strokes_keep_their_raster_effects() {
assert_eq!(pieces, 2, "item {item}: one piece per fill and stroke");
}
}
#[test]
fn shadows_and_glows_keep_their_blend_modes() {
// #827: a red Screen glow over grey can't darken it, as Normal would.
let glow = Effect {
id: "stylize.outerGlow".into(),
params: json!({"mode": "screen", "color": "#ff0000", "opacity": 100.0, "blur": 20.0}),
visible: true,
};
let mut d = Document::new(200.0, 200.0);
let back = rect(&mut d, Rect::new(0.0, 0.0, 200.0, 200.0), Color::rgb(0.5, 0.5, 0.5));
add(&mut d, back);
let dot = rect(&mut d, Rect::new(70.0, 70.0, 130.0, 130.0), Color::rgb(0.12, 0.12, 0.12));
add(&mut d, with(dot, glow.clone()));
assert_written("screen glow", &d);
let r = crate::cmd::rasterfx::export_pdf_with_report(&d, &Default::default()).unwrap();
let back = render(&vectorcraft_pdf::import(&r.bytes).unwrap());
for x in [133, 138, 145] {
let i = (100 * back.width as usize + x) * 4;
let (red, green, blue) = (back.pixels[i], back.pixels[i + 1], back.pixels[i + 2]);
assert!(red > green && green >= 124 && blue >= 124, "x {x}: {:?}", (red, green, blue));
}
// A Multiply shadow and the Screen glow: an image each, composited with its mode.
let mut d = Document::new(200.0, 200.0);
let dot = rect(&mut d, Rect::new(70.0, 70.0, 130.0, 130.0), Color::rgb(0.12, 0.12, 0.12));
add(&mut d, with(with(dot, shadow()), glow));
let flat = crate::flatten_raster_effects(&d).unwrap();
let modes: Vec<_> =
flat.layers[0].children().unwrap()[0].children().unwrap().iter().filter(|c| matches!(c.kind, NodeKind::Image(_))).map(|c| c.blend).collect();
assert_eq!(modes, [vectorcraft_color::BlendMode::Multiply, vectorcraft_color::BlendMode::Screen]);
}
+7
View File
@@ -285,9 +285,16 @@ fn image_size_region_and_metadata() {
assert_eq!(size(&mut s, json!({"width": 80})), (80, 60));
assert_eq!(size(&mut s, json!({"height": 15})), (20, 15));
assert_eq!(size(&mut s, json!({"percent": 150})), (60, 45));
// The dialog's fields send decimal numbers: rounded to whole pixels.
assert_eq!(size(&mut s, json!({"width": 80.0})), (80, 60));
assert_eq!(size(&mut s, json!({"height": 14.6})), (20, 15));
for bad in [
json!({"percent": 0}),
json!({"width": 0}),
json!({"width": 0.2}),
json!({"width": -5}),
json!({"height": 1e300}),
json!({"height": "tall"}),
json!({"format": "bmp"}),
json!({"colors": "many"}),
json!({"matte": "plaid"}),
+5
View File
@@ -215,6 +215,11 @@ fn structured_junk() {
("path.freehand", json!({"points": [[0, 0], [0, 0], [0, 0], [0, 0]]})),
("path.freehand", json!({"points": [[1e308, 1e308], [-1e308, 0]], "fidelity": 0})),
("path.curvature", json!({"points": [{"x": 0, "y": 0}]})),
("path.curvatureEdit", json!({"id": 2, "op": "move", "anchor": 1000, "x": 0, "y": 0})),
("path.curvatureEdit", json!({"id": 2, "op": "move", "anchor": 0, "x": 1e308, "y": -1e308})),
("path.curvatureEdit", json!({"id": 2, "subpath": 7, "op": "extend", "x": 1e308, "y": -1e308, "from": "smooth"})),
("path.curvatureEdit", json!({"id": 2, "op": "insert", "segment": 99, "t": -5, "x": 1})),
("path.curvatureEdit", json!({"id": 2, "op": "close", "end": "start", "from": "corner"})),
("path.knife", json!({"points": [[0, 0], [1e9, 1e9]]})),
("path.eraseRegion", json!({"points": [[100, 80]], "size": 0})),
("path.eraseRegion", json!({"points": [[100, 80], [101, 80]], "size": 1e9})),
+8
View File
@@ -936,6 +936,14 @@ fn prune_unseen(frame: &Frame<'_>, view: &mut PageView, doc: &mut Document) -> u
return 0;
}
let mut with = view.difference(doc, rect).any;
// Taking a text object out changes only what is drawn in its box. When the art would still
// differ from the page by more than `compare` allows with every candidate gone, the layers
// aren't used whatever is pruned: don't draw them again for each one (#758).
let margin = OUTLINE_REACH + 1.0;
let boxes: f64 = found.iter().filter_map(|(_, b)| *b).map(|b| b.inflate(margin, margin).intersect(rect).area().max(0.0)).sum();
if with - boxes / rect.area().max(1e-9) > MAX_DIFFERENCE {
return 0;
}
let mut removed = 0;
for (id, bounds) in found {
if bounds.is_none_or(|b| b.intersect(rect).is_zero_area()) {
+18
View File
@@ -129,3 +129,21 @@ fn conventions_resources_and_versioned_results() {
rpc(&mut s, "initialize", json!({"protocolVersion":"2025-06-18"}));
assert!(rpc(&mut s, "tools/list", json!({}))["result"].get("resultType").is_none());
}
/// #785: a batch step can use an earlier step's result (`"$N.path"`); a reference to nothing
/// fails that step.
#[test]
fn batch_steps_refer_to_earlier_results() {
let mut s = Server::new(Box::new(Headless::with_document()));
let steps = json!([
{"id":"text.create","params":{"x":10,"y":60,"text":"plain and bold words","size":30}},
{"id":"shape.rectangle","params":{"x":0,"y":0,"width":20,"height":20}},
{"id":"text.setRangeStyle","params":{"id":"$0.id","start":10,"end":14,"style":"Bold"}},
{"id":"text.setRangeStyle","params":{"id":"$9.id","start":0,"end":1,"style":"Bold"}}
]);
let r = call(&mut s, "command_batch", json!({"steps":steps,"stop_on_error":false}));
let p = payload(&r);
assert_eq!((p["completed"].clone(), p["failed"].clone()), (json!(3), json!(1)), "{p}");
assert_eq!(p["results"][2]["result"]["id"], p["results"][0]["result"]["id"], "the text, not the selected rectangle");
assert!(p["results"][3]["error"].as_str().unwrap().contains("$9.id"), "{p}");
}
+6 -2
View File
@@ -96,7 +96,7 @@ pub fn tool_definitions() -> Vec<Value> {
tool(
"command_batch",
"Run several commands",
"Run steps in order; each edit is its own undo step. Returns completed, failed and results. Stops on the first error by default.",
"Run steps in order; each edit is its own undo step. A param string that is exactly \"$N.path\" (N: 0-based step index) or \"$last.path\" takes that value from an earlier step's result, e.g. {\"id\":\"$1.id\"}; \"$$\" starts a literal \"$\". Returns completed, failed and results. Stops on the first error by default.",
obj(
json!({"steps": {"type":"array", "items":obj(json!({"id":string("Command id"),"params":{"type":"object"}}), &["id"])}, "stop_on_error":{"type":"boolean", "default":true}}),
&["steps"],
@@ -899,6 +899,8 @@ fn command_batch(b: &mut dyn Backend, a: &Args) -> Result<ToolResult, String> {
Some(v) => v.as_bool().ok_or("`stop_on_error` must be a boolean")?,
};
let (mut completed, mut failed, mut results) = (0, 0, Vec::new());
// Each step's result (null for a failed one), for later steps' `"$N.path"` references.
let mut values: Vec<Value> = vec![];
for step in steps {
let result = vectorcraft_engine::guard::catch_panic(|| {
let args = step.as_object().ok_or("each step must be an object")?;
@@ -908,7 +910,7 @@ fn command_batch(b: &mut dyn Backend, a: &Args) -> Result<ToolResult, String> {
let id = req_str(args, "id")?;
let params = match args.get("params") {
None | Some(Value::Null) => json!({}),
Some(v @ Value::Object(_)) => v.clone(),
Some(v @ Value::Object(_)) => vectorcraft_engine::steps::resolve(v, &values)?,
Some(_) => return Err("`params` must be an object".into()),
};
b.call("engine.execute", json!({"command":id,"params":params}))
@@ -917,10 +919,12 @@ fn command_batch(b: &mut dyn Backend, a: &Args) -> Result<ToolResult, String> {
match result {
Ok(v) => {
completed += 1;
values.push(v.clone());
results.push(json!({"ok":true,"result":v}));
}
Err(e) => {
failed += 1;
values.push(Value::Null);
results.push(json!({"ok":false,"error":e}));
if stop {
break;
+3 -1
View File
@@ -87,7 +87,7 @@ impl RasterExportOptions {
}
/// What the renderer draws for `format`: template layers and guides left out, over the background
/// (white for a JPEG or a flat PSD without one).
/// (white for a JPEG or a flat PSD without one), composited in floating point.
pub fn render_options(&self, format: RasterFormat) -> RenderOptions {
let flat = format == RasterFormat::Jpeg || (format == RasterFormat::Psd && !self.psd.layers);
let background = self.background.or(flat.then_some([255; 3]));
@@ -95,6 +95,8 @@ impl RasterExportOptions {
background: background.map(|[r, g, b]| [r, g, b, 255]),
skip_templates: true,
anti_alias: self.anti_alias,
// Opaque art stays exactly opaque where translucent edges cross it (#787).
precise: true,
..Default::default()
}
}
+38
View File
@@ -110,6 +110,44 @@ fn backgrounds_are_opaque_or_transparent() {
assert_eq!(webp.get_pixel(0, 0).0, [0, 0, 0, 255]);
}
/// #787: translucent art over opaque art (or a background) stays exactly opaque, its anti-aliased
/// edges too, so the file is written as RGB.
#[test]
fn translucent_edges_over_opaque_art_stay_opaque() {
let mut d = Document::new(100.0, 100.0);
let l = d.layers[0].id;
let under = Node::path(
d.alloc_id(),
shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)),
Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0),
);
let mut over =
Node::path(d.alloc_id(), shapes::ellipse(Rect::new(10.0, 10.0, 90.0, 90.0)), Appearance::basic(Paint::solid(Color::WHITE), Paint::None, 0.0));
over.opacity = 0.5;
let only_over = {
let mut d = d.clone();
d.insert(Some(l), 0, over.clone()).unwrap();
d
};
d.insert(Some(l), 0, under).unwrap();
d.insert(Some(l), 1, over).unwrap();
// Over a black background at 72 ppi, and over an opaque rectangle at a scale that puts the
// edges on fractions of a pixel.
for (doc, o) in [
(&only_over, RasterExportOptions { background: Some([0, 0, 0]), ..Default::default() }),
(&d, RasterExportOptions { ppi: 72.0 * 0.3515625, ..Default::default() }),
] {
let png = Renderer::new().export_region(doc, doc.artboards[0].rect, RasterFormat::Png, &o).unwrap();
let img = image::load_from_memory(&png).unwrap().to_rgba8();
let below: Vec<_> = img.pixels().filter(|p| p[3] < 255).collect();
assert!(below.is_empty(), "ppi {}: {} pixels below alpha 255, e.g. {:?}", o.ppi, below.len(), below.first());
assert_eq!(png[25], 2, "IHDR colour type: RGB");
}
// The inside is half white over black.
let img = export(&only_over, RasterFormat::Png, &RasterExportOptions { background: Some([0, 0, 0]), ..Default::default() });
assert!(img.get_pixel(50, 50).0[..3].iter().all(|c| (127..=128).contains(c)), "{:?}", img.get_pixel(50, 50));
}
#[test]
fn interlaced_export_decodes_to_the_same_pixels() {
let d = circle_doc();
+2 -2
View File
@@ -137,7 +137,7 @@ impl Renderer {
fn flatten(&mut self, ctx: &mut RenderContext, r: Region) -> Arc<Pixmap> {
ctx.flush();
let mut all = Pixmap::new(ctx.width(), ctx.height());
ctx.render(&mut all, &mut self.resources);
ctx.render_with(&mut all, &mut self.resources, self.raster);
ctx.reset();
let crop = if (r.x, r.y, r.w, r.h) == (0, 0, all.width(), all.height()) {
None
@@ -171,7 +171,7 @@ impl Renderer {
(self.nested, self.backdrop, self.clip_paths) = outer;
ctx.flush();
let mut pm = Pixmap::new(r.w, r.h);
ctx.render(&mut pm, &mut self.resources);
ctx.render_with(&mut pm, &mut self.resources, self.raster);
pm
}
+83 -2
View File
@@ -107,8 +107,18 @@ pub struct RenderOptions {
/// Images are sampled smoothly when scaled or rotated; off, each pixel takes its nearest image
/// pixel (Pixel Preview with File Handling › Display Bitmaps as Anti-aliased Images off).
pub smooth_images: bool,
/// Screen view in isolation mode: the isolated group or layer. Everything around it draws
/// dimmed ([`ISOLATION_DIM`]).
pub isolated: Option<NodeId>,
/// Composite in floating point (exports): translucent art over opaque art comes out exactly
/// opaque, where 8-bit compositing leaves alpha 254 on some anti-aliased edges (#787). Off,
/// the faster 8-bit pipeline (the canvas).
pub precise: bool,
}
/// The opacity of the art around an isolated group or layer.
pub const ISOLATION_DIM: f32 = 0.5;
/// How edges are rasterized (raster export option).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum AntiAlias {
@@ -174,6 +184,8 @@ impl Default for RenderOptions {
progressive_placed: false,
trace_views: false,
smooth_images: true,
isolated: None,
precise: false,
}
}
}
@@ -355,6 +367,14 @@ pub struct Renderer {
/// Inline graphics being drawn inside inline graphics (a symbol whose art holds text showing
/// it): drawing stops at [`MAX_INLINE_DEPTH`].
inline_depth: u32,
/// How the frame being drawn is rasterized ([`RenderOptions::precise`]): its offscreen groups,
/// masks and patterns too.
raster: vello_cpu::RasterizerSettings,
/// [`RenderOptions::isolated`]'s layers and groups, from the top layer down to it, for the
/// frame (`stamp`) and document they were found in.
isolation: Option<(u64, usize, NodeId, Vec<NodeId>)>,
/// Drawing inside the isolated container or a dimmed object: nothing further dims.
isolation_settled: bool,
}
/// How deep inline graphics nest (text in a symbol shown inline in text…) before they draw nothing.
@@ -441,6 +461,9 @@ impl Renderer {
adjusted: Default::default(),
dim_images: None,
inline_depth: 0,
raster: vello_cpu::RasterizerSettings::default(),
isolation: None,
isolation_settled: false,
}
}
@@ -518,6 +541,8 @@ impl Renderer {
};
// `reset` keeps the threshold of the previous render: set it every time.
ctx.set_aliasing_threshold(opts.anti_alias.threshold());
let render_mode = if opts.precise { vello_cpu::RenderMode::OptimizeQuality } else { vello_cpu::RenderMode::OptimizeSpeed };
self.raster = vello_cpu::RasterizerSettings { render_mode, ..Default::default() };
if let Some(bg) = opts.background {
ctx.set_transform(Affine::IDENTITY);
ctx.set_paint(f.ink.fixed(bg));
@@ -546,7 +571,7 @@ impl Renderer {
}
ctx.flush();
let mut pm = Pixmap::new(w, h);
ctx.render(&mut pm, &mut self.resources);
ctx.render_with(&mut pm, &mut self.resources, self.raster);
if threads == 0 {
self.ctx_st = Some(ctx);
} else {
@@ -781,7 +806,7 @@ impl Renderer {
(self.knockout, self.nested, self.backdrop, self.clip_paths) = outer;
mctx.flush();
let mut pm = Pixmap::new(w, h);
mctx.render(&mut pm, &mut self.resources);
mctx.render_with(&mut pm, &mut self.resources, self.raster);
pm.data().iter().map(|p| mask_value(p.r, p.g, p.b, p.a, m.clip, m.invert)).collect()
}
@@ -876,6 +901,46 @@ impl Renderer {
/// [`Self::draw_node`] after culling and Layer Options.
fn draw_layer_node(&mut self, ctx: &mut RenderContext, f: &Frame, n: &Node) {
// Isolation mode: the art around the isolated container draws dimmed (#833).
if let Some((isolated, path)) = self.isolation_path(f) {
// A container on the way down to it draws as usual: its members decide.
if path.contains(&n.id) && n.id != isolated {
return self.draw_layer_node_now(ctx, f, n);
}
self.isolation_settled = true;
if n.id == isolated {
self.draw_layer_node_now(ctx, f, n);
} else {
self.dimmed(ctx, f, &mut |r, c, fr| r.draw_layer_node_now(c, fr, n));
}
self.isolation_settled = false;
return;
}
self.draw_layer_node_now(ctx, f, n);
}
/// In isolation mode, while drawing outside the isolated container and the art dimmed around
/// it: the isolated container and its layers and groups, from the top layer down to it.
fn isolation_path(&mut self, f: &Frame) -> Option<(NodeId, Vec<NodeId>)> {
let isolated = f.opts.isolated.filter(|_| !self.isolation_settled)?;
let doc = std::ptr::from_ref(f.doc) as usize;
if !self.isolation.as_ref().is_some_and(|(stamp, d, id, _)| (*stamp, *d, *id) == (self.stamp, doc, isolated)) {
self.isolation = Some((self.stamp, doc, isolated, f.doc.ancestry(isolated).unwrap_or_default()));
}
let path = self.isolation.as_ref().map(|(.., path)| path.clone()).filter(|p| !p.is_empty())?;
Some((isolated, path))
}
/// `draw` at [`ISOLATION_DIM`], with nothing inside dimmed again.
fn dimmed(&mut self, ctx: &mut RenderContext, f: &Frame, draw: &mut group::Content) {
let settled = std::mem::replace(&mut self.isolation_settled, true);
let comp = Composite { opacity: ISOLATION_DIM, ..Default::default() };
self.group(ctx, f, comp, draw);
self.isolation_settled = settled;
}
/// [`Self::draw_layer_node`] past isolation mode's dimming.
fn draw_layer_node_now(&mut self, ctx: &mut RenderContext, f: &Frame, n: &Node) {
if fx::has_object_fx(n) {
return self.draw_object_fx(ctx, f, &Arc::new(n.clone()), false);
}
@@ -998,6 +1063,22 @@ impl Renderer {
fn draw_children(&mut self, ctx: &mut RenderContext, f: &Frame, children: &[Arc<Node>], knockout: bool) {
if knockout {
self.draw_knockout(ctx, f, children);
} else if let Some((_, path)) = self.isolation_path(f) {
// Isolation mode, in a container on the way down to the isolated one: each run of
// members around it draws dimmed as one (#833).
let mut rest = children;
while let Some(i) = rest.iter().position(|c| path.contains(&c.id)) {
let (around, from) = rest.split_at(i);
if !around.is_empty() {
self.dimmed(ctx, f, &mut |r, c, fr| around.iter().for_each(|n| r.draw_arc(c, fr, n)));
}
let Some((on_path, after)) = from.split_first() else { break };
self.draw_arc(ctx, f, on_path);
rest = after;
}
if !rest.is_empty() {
self.dimmed(ctx, f, &mut |r, c, fr| rest.iter().for_each(|n| r.draw_arc(c, fr, n)));
}
} else {
for c in children {
self.draw_arc(ctx, f, c);
+1 -1
View File
@@ -88,7 +88,7 @@ fn rasterize(r: &mut Renderer, doc: &Document, def: &PatternDef, region: Rect, w
}
ctx.flush();
let mut pm = Pixmap::new(w, h);
ctx.render(&mut pm, &mut r.resources);
ctx.render_with(&mut pm, &mut r.resources, r.raster);
pm
}
+27
View File
@@ -218,3 +218,30 @@ fn copying_the_backdrop_changes_nothing_without_blending() {
let worst = a.iter().zip(&b).map(|(x, y)| (*x as i32 - *y as i32).abs()).max().unwrap();
assert!(worst <= 1, "differs by {worst}/255");
}
/// Isolation mode (#833): the art around the isolated group draws at half opacity, above it as
/// well as below; the group's own art as usual.
#[test]
fn isolation_mode_dims_the_art_around_the_isolated_group() {
let mut d = Document::new(100.0, 100.0);
let l = d.layers[0].id;
let below = rect(&mut d, Rect::new(0.0, 0.0, 40.0, 40.0), [0.0, 0.0, 0.0]);
let inside = rect(&mut d, Rect::new(60.0, 60.0, 100.0, 100.0), [0.0, 0.0, 0.0]);
let above = rect(&mut d, Rect::new(60.0, 0.0, 100.0, 40.0), [0.0, 0.0, 0.0]);
let g = group(&mut d, vec![inside], 1.0, Blend::Normal, false);
let gid = g.id;
for n in [below, g, above] {
d.insert(Some(l), usize::MAX, n).unwrap();
}
let alpha = |img: &Rendered, x: usize, y: usize| img.pixels[(y * 100 + x) * 4 + 3];
let plain = render(&d);
let isolated = |id| render_with(&mut Renderer::new(), &d, &RenderOptions { isolated: Some(id), ..Default::default() });
let dimmed = isolated(gid);
assert_eq!(alpha(&dimmed, 80, 80), 255, "the isolated group's art");
for (x, y) in [(20, 20), (80, 20)] {
assert_eq!(alpha(&plain, x, y), 255);
assert!((120..=135).contains(&alpha(&dimmed, x, y)), "({x}, {y}): {}", alpha(&dimmed, x, y));
}
// An object that isn't in the document dims nothing.
assert_eq!(isolated(NodeId(u64::MAX)).pixels, plain.pixels);
}
+10 -1
View File
@@ -15,7 +15,7 @@ use vectorcraft_geom::{Anchor, AnchorKind, BezPath, Point, SubPath};
use crate::{Action, Tool, ToolContext};
pub use anchor::AnchorTool;
pub use curvature::CurvatureTool;
pub use curvature::{CurvatureTool, EndCurve, curvature_close, curvature_extend, curvature_insert, curvature_move};
pub use family::FamilyTool;
pub use gesture::GestureTool;
@@ -94,6 +94,15 @@ fn candidate_paths(cx: &ToolContext) -> Vec<NodeId> {
v
}
/// The selected paths the Pen and the Curvature tool edit (not guides, nor locked or hidden ones).
pub(crate) fn editable_paths<'a>(cx: &'a ToolContext) -> impl Iterator<Item = NodeId> + 'a {
cx.selection
.objects
.iter()
.copied()
.filter(|&id| cx.doc.is_editable(id) && cx.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: false, .. })))
}
/// Nearest anchor within `tol`: (path, subpath, anchor).
pub(crate) fn hit_anchor(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId, usize, usize)> {
anchor_in(cx, candidate_paths(cx), p, tol)
+685 -30
View File
@@ -5,28 +5,293 @@
//! first point to close; Backspace/Delete removes the last touched point; Esc/Enter ends the path.
//! A rubber band shows the curve to the cursor (Enable Rubber Band for Curvature Tool). Each point
//! placed or dragged snaps to Smart Guides ([`DrawSnap`]), as the Pen's anchors do.
//!
//! It edits any selected path too, whatever drew it, keeping its shape except where edited
//! (#798). A click on one of its points makes that the current point (direct-selected); a drag
//! moves it, re-curving only the two segments at it ([`curvature_move`]); Alt-click or
//! double-click toggles it between smooth and corner and Backspace/Delete removes it. A click on
//! a segment adds a smooth point there without changing the shape ([`curvature_insert`]), and a
//! drag moves the new point at once. While the current point is an end of an open path, clicks go
//! on from it ([`curvature_extend`]): the old segments keep their shape, the new ones curve
//! through the new points, and a click on the path's other end closes it. Each edit is one
//! `path.curvatureEdit`, `path.convertAnchor` or `path.removeAnchor` (one undo step).
use serde_json::{Value, json};
use vectorcraft_doc::{NodeId, Selection};
use vectorcraft_geom::Point;
use vectorcraft_geom::{Anchor, AnchorKind, BezPath, Point, SubPath, Vec2};
use super::{FEEDBACK, catmull_rom};
use super::{FEEDBACK, anchor_in, catmull_rom, editable_paths, remove_anchor, segment_in};
use crate::guides::{DrawSnap, Leave, Targets};
use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey};
/// The command that edits a selected path.
const EDIT: &str = "path.curvatureEdit";
#[derive(Default)]
pub struct CurvatureTool {
pts: Vec<(Point, bool)>,
closed: bool,
id: Option<NodeId>,
/// Point being dragged: (index, began).
drag: Option<(usize, Point, bool)>,
/// Last touched point (Backspace removes it).
/// The point being dragged, the pointer at the press, and whether the drag began.
drag: Option<(Grab, Point, bool)>,
/// Last touched point of the path being drawn (Backspace removes it).
current: Option<usize>,
hover: Option<Point>,
/// The end the last click on a selected path placed.
placed: Option<Placed>,
snap: DrawSnap,
}
/// What a press grabbed for a drag.
#[derive(Clone, Copy, Debug, PartialEq)]
enum Grab {
/// A point of the path being drawn.
Drawn(usize),
/// An anchor of a selected path: (path, subpath, anchor).
Anchor(NodeId, usize, usize),
/// The anchor the press added on a segment of a selected path: (path, subpath, segment, t).
Inserted(NodeId, usize, usize, f64),
}
/// The end a click on a selected path placed, while it still is that end (its subpath has as many
/// anchors as then): going on from it, it curves through its neighbours, or stays a corner when it
/// was Alt-clicked. Any other end keeps its curve.
#[derive(Clone, Copy, Debug, PartialEq)]
struct Placed {
id: NodeId,
si: usize,
start: bool,
anchors: usize,
corner: bool,
}
/// The current point of a selected path while it is an end of an open subpath: where clicks go on
/// from (its start with `start`), and the other end, which a click closes the subpath on.
#[derive(Clone, Copy)]
struct End {
id: NodeId,
si: usize,
start: bool,
anchors: usize,
p: Point,
other: Point,
}
impl End {
/// `end` for `path.curvatureEdit`.
fn name(&self) -> &'static str {
if self.start { "start" } else { "end" }
}
}
/// How the end a path goes on from bends into the new segment ([`curvature_extend`],
/// [`curvature_close`]).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum EndCurve {
/// The segment it ends keeps its shape: the new handle goes on along its handle, or along the
/// curve where it has none, and with both it is smooth.
#[default]
Keep,
/// Smooth through its neighbours, as [`catmull_rom`] curves a point (a point the Curvature tool
/// placed: its segment re-curves).
Smooth,
/// A corner, without handles.
Corner,
}
impl EndCurve {
pub fn parse(s: &str) -> Option<Self> {
Some(match s {
"keep" => Self::Keep,
"smooth" => Self::Smooth,
"corner" => Self::Corner,
_ => return None,
})
}
pub fn name(self) -> &'static str {
match self {
Self::Keep => "keep",
Self::Smooth => "smooth",
Self::Corner => "corner",
}
}
}
/// The anchors before and after anchor `i` of `sp` (round the start of a closed one).
fn neighbours(sp: &SubPath, i: usize) -> [Option<usize>; 2] {
let n = sp.anchors.len();
let wrap = sp.closed && n > 1;
let prev = if i > 0 { Some(i - 1) } else { wrap.then(|| n - 1) };
let next = if i + 1 < n { Some(i + 1) } else { wrap.then_some(0) };
[prev, next]
}
/// Move anchor `i` of `sp` to `q` as the Curvature tool drags a point: only the two segments at it
/// change. A smooth anchor turns along the line through its neighbours; the neighbours' handles on
/// those segments, and a corner's own handles, keep their directions, their lengths scaling with
/// their segment's chord, so the segments beyond don't move and a corner without handles keeps
/// none. False when there is no anchor `i`.
pub fn curvature_move(sp: &mut SubPath, i: usize, q: Point) -> bool {
let Some(&a) = sp.anchors.get(i) else { return false };
let mut own = [a.h_in - a.p, a.h_out - a.p];
let mut ends = [None; 2];
for (side, j) in neighbours(sp, i).into_iter().enumerate() {
let Some(b) = j.and_then(|j| sp.anchors.get_mut(j)) else { continue };
let old = a.p.distance(b.p);
let s = if old > 1e-9 { q.distance(b.p) / old } else { 1.0 };
let h = if side == 0 { &mut b.h_out } else { &mut b.h_in };
*h = b.p + (*h - b.p) * s;
own[side] *= s;
ends[side] = Some(b.p);
}
let mut m = Anchor { p: q, h_in: q + own[0], h_out: q + own[1], kind: a.kind };
if let (AnchorKind::Smooth, [Some(prev), Some(next)]) = (a.kind, ends) {
let d = next - prev;
let l = d.hypot();
if l > 1e-9 {
// A handle it lacks comes out a third of the way to that side's neighbour.
let len = |h: Vec2, to: Point| if h.hypot() > 1e-9 { h.hypot() } else { q.distance(to) / 3.0 };
m.h_in = q - d * (len(own[0], prev) / l);
m.h_out = q + d * (len(own[1], next) / l);
}
}
if let Some(x) = sp.anchors.get_mut(i) {
*x = m;
}
true
}
/// Add a smooth anchor at `t` on segment `seg` of `sp` without changing its shape (on a straight
/// segment its handles lie along it, so a drag curves it): the new anchor's index. None when there
/// is no such segment.
pub fn curvature_insert(sp: &mut SubPath, seg: usize, t: f64) -> Option<usize> {
if seg >= sp.segment_count() {
return None;
}
let line = sp.segment_is_line(seg);
let i = sp.insert_anchor(seg, if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.5 });
if line {
sp.smooth_anchor(i);
}
Some(i)
}
/// Go on from an end of the open subpath `sp` (its start with `start`) to a new end at `p`, which
/// has no handles; the old end bends into the new segment as `how` says.
pub fn curvature_extend(sp: &mut SubPath, start: bool, p: Point, how: EndCurve) {
if start {
sp.reverse();
}
bend_last(sp, p, how);
sp.anchors.push(Anchor::corner(p));
if start {
sp.reverse();
}
}
/// Close the open subpath `sp` from its end (its start with `start`): that end bends into the
/// closing segment as `how` says, and the other keeps its curve.
pub fn curvature_close(sp: &mut SubPath, start: bool, how: EndCurve) {
if start {
sp.reverse();
}
if let (Some(first), Some(last)) = (sp.anchors.first().map(|a| a.p), sp.anchors.last().map(|a| a.p)) {
bend_last(sp, first, how);
sp.reverse();
bend_last(sp, last, EndCurve::Keep);
sp.reverse();
sp.closed = true;
}
if start {
sp.reverse();
}
}
/// Bend the last anchor of `sp` into a new segment on to `to`, as `how` says.
fn bend_last(sp: &mut SubPath, to: Point, how: EndCurve) {
let prev = sp.anchors.len().checked_sub(2).and_then(|j| sp.anchors.get(j)).copied();
let Some(e) = sp.anchors.last_mut() else { return };
match how {
EndCurve::Corner => e.retract(),
EndCurve::Smooth => {
let t = prev.map_or(Vec2::ZERO, |b| (to - b.p) / 6.0);
if t.hypot() > 1e-9 {
*e = Anchor { p: e.p, h_in: e.p - t, h_out: e.p + t, kind: AnchorKind::Smooth };
} else {
e.retract();
}
}
EndCurve::Keep => {
// The way the curve comes in: from its handle, or else the segment's tangent there.
let back = if e.has_in() { Some(e.h_in) } else { prev.map(|b| if b.h_out.distance(e.p) > 1e-9 { b.h_out } else { b.p }) };
let d = back.map_or(Vec2::ZERO, |b| e.p - b);
let l = d.hypot();
e.h_out = if l > 1e-9 { e.p + d * (e.p.distance(to) / 3.0 / l) } else { e.p };
if e.has_in() && e.has_out() {
e.kind = AnchorKind::Smooth;
}
}
}
}
/// Subpath `si` of `id`, a selected path the tool edits.
fn subpath<'a>(cx: &ToolContext<'a>, id: NodeId, si: usize) -> Option<&'a SubPath> {
if !editable_paths(cx).any(|e| e == id) {
return None;
}
cx.doc.node(id)?.path_data()?.subpaths.get(si)
}
/// The current point of a selected path: its one direct-selected anchor (path, subpath, anchor).
fn current_point(cx: &ToolContext) -> Option<(NodeId, usize, usize)> {
let mut sets = cx.selection.anchors.iter().filter(|(_, set)| !set.is_empty());
let (&id, set) = sets.next()?;
if set.len() != 1 || sets.next().is_some() {
return None;
}
let &(si, ai) = set.first()?;
subpath(cx, id, si).filter(|sp| ai < sp.anchors.len()).map(|_| (id, si, ai))
}
/// The current point while it is an end of an open subpath.
fn current_end(cx: &ToolContext) -> Option<End> {
let (id, si, ai) = current_point(cx)?;
let sp = subpath(cx, id, si)?;
let n = sp.anchors.len();
let (first, last) = (sp.anchors.first()?.p, sp.anchors.last()?.p);
if sp.closed || (ai > 0 && ai + 1 < n) {
return None;
}
// A one-anchor subpath goes on from its end.
let start = ai == 0 && n > 1;
let (p, other) = if start { (first, last) } else { (last, first) };
Some(End { id, si, start, anchors: n, p, other })
}
/// Make anchor `(id, si, ai)` the current point.
fn select_point((id, si, ai): (NodeId, usize, usize)) -> Action {
Action::Exec("select.anchors".into(), json!({"id": id.0, "anchors": [[si, ai]], "mode": "set"}))
}
/// Toggle anchor `(id, si, ai)` of a selected path between smooth and corner.
fn toggle(cx: &ToolContext, (id, si, ai): (NodeId, usize, usize)) -> Option<Action> {
let a = subpath(cx, id, si)?.anchors.get(ai)?;
let to = if a.kind == AnchorKind::Smooth { "corner" } else { "smooth" };
Some(Action::Exec("path.convertAnchor".into(), json!({"id": id.0, "subpath": si, "anchor": ai, "to": to})))
}
/// Snap targets for dragging anchors `anchors` of subpath `si` of `id` (the rest of the path
/// pulls).
fn hold_targets(snap: &mut DrawSnap, cx: &ToolContext, id: NodeId, si: usize, anchors: &[usize]) {
let sel = Selection { objects: vec![id], anchors: [(id, anchors.iter().map(|&ai| (si, ai)).collect())].into(), ..Selection::default() };
snap.hold(cx, || Targets::for_anchor_drag(cx.doc, &sel));
}
/// How near a press picks a point.
fn point_tol(cx: &ToolContext) -> f64 {
cx.tol(5.0).max(cx.point_tol())
}
impl CurvatureTool {
/// The path being drawn, if it is still the single selected object and matches our points.
fn active(&self, cx: &ToolContext) -> Option<NodeId> {
@@ -58,12 +323,70 @@ impl CurvatureTool {
self.id = None;
self.drag = None;
self.current = None;
self.placed = None;
self.snap.clear();
}
/// The segment to the next point leaves the last one.
fn leave(&self, cx: &ToolContext) -> Option<Leave> {
self.pts.last().map(|(p, _)| Leave::segment(cx, *p, false))
/// The path the next click goes on (left out of the snap targets, its anchors still pulling)
/// and the segment to it: the path being drawn, or the selected one whose end is current.
fn leave(&self, cx: &ToolContext) -> Option<(NodeId, Leave)> {
match self.active(cx) {
Some(id) => self.pts.last().map(|(p, _)| (id, Leave::segment(cx, *p, false))),
None => current_end(cx).map(|e| (e.id, Leave::segment(cx, e.p, false))),
}
}
/// How end `e` bends into the next segment: as [`Placed`] says for the end the last click
/// placed, else it keeps its curve.
fn how(&self, e: &End) -> EndCurve {
match self.placed {
Some(pl) if (pl.id, pl.si, pl.start, pl.anchors) == (e.id, e.si, e.start, e.anchors) => {
if pl.corner {
EndCurve::Corner
} else {
EndCurve::Smooth
}
}
_ => EndCurve::Keep,
}
}
/// A press on a selected path the tool isn't drawing: on the other end of the open path going
/// on (it closes), on a point, anywhere while an end is current (the path goes on), or on a
/// segment. None elsewhere: a new path starts.
fn press_selected(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Option<Vec<Action>> {
let (p, tol) = (ev.pos, point_tol(cx));
let end = current_end(cx);
if let Some(e) = end.filter(|e| e.anchors >= 3 && p.distance(e.other) <= tol) {
let how = self.how(&e);
self.placed = None;
let v = json!({"id": e.id.0, "subpath": e.si, "op": "close", "end": e.name(), "from": how.name()});
return Some(vec![Action::Exec(EDIT.into(), v)]);
}
if let Some(hit) = anchor_in(cx, editable_paths(cx), p, tol) {
let mut out = vec![select_point(hit)];
if ev.mods.alt {
out.extend(toggle(cx, hit));
return Some(out);
}
let (id, si, ai) = hit;
hold_targets(&mut self.snap, cx, id, si, &[ai]);
self.drag = Some((Grab::Anchor(id, si, ai), p, false));
return Some(out);
}
if let Some(e) = end {
let q = self.snap.press(cx, p, &[e.id], Some(&Leave::segment(cx, e.p, false)));
let how = self.how(&e);
self.placed = Some(Placed { id: e.id, si: e.si, start: e.start, anchors: e.anchors + 1, corner: ev.mods.alt });
let v = json!({"id": e.id.0, "subpath": e.si, "op": "extend", "end": e.name(), "x": q.x, "y": q.y, "from": how.name()});
return Some(vec![Action::Exec(EDIT.into(), v)]);
}
let (id, si, seg, t) = segment_in(cx, editable_paths(cx), p, tol)?;
let n = subpath(cx, id, si)?.anchors.len().max(1);
hold_targets(&mut self.snap, cx, id, si, &[seg, (seg + 1) % n]);
self.drag = Some((Grab::Inserted(id, si, seg, t), p, true));
let v = json!({"id": id.0, "subpath": si, "op": "insert", "segment": seg, "t": t});
Some(vec![Action::Begin("Curvature".into()), Action::Preview(EDIT.into(), v)])
}
}
@@ -82,8 +405,8 @@ impl Tool for CurvatureTool {
}
match ev.kind {
PointerKind::Move => {
let from = active.and_then(|_| self.leave(cx));
self.hover = Some(self.snap.hover(cx, p, active.as_slice(), from.as_ref()));
let (on, from) = self.leave(cx).unzip();
self.hover = Some(self.snap.hover(cx, p, on.as_slice(), from.as_ref()));
vec![]
}
PointerKind::Down => {
@@ -99,19 +422,21 @@ impl Tool for CurvatureTool {
return vec![Action::Exec("path.curvature".into(), self.params())];
}
// The point dragged and the curve through it move: the rest pull.
let sel = Selection { objects: vec![id], anchors: [(id, [(0, i)].into())].into(), ..Selection::default() };
self.snap.hold(cx, || Targets::for_anchor_drag(cx.doc, &sel));
self.drag = Some((i, p, false));
hold_targets(&mut self.snap, cx, id, 0, &[i]);
self.drag = Some((Grab::Drawn(i), p, false));
return vec![];
}
if !self.closed {
let from = self.leave(cx);
let from = self.leave(cx).map(|l| l.1);
let p = self.snap.press(cx, p, &[id], from.as_ref());
self.pts.push((p, ev.mods.alt));
self.current = Some(self.pts.len() - 1);
return vec![Action::Exec("path.curvature".into(), self.params())];
}
}
if let Some(out) = self.press_selected(cx, ev) {
return out;
}
// Start a new path.
self.reset();
let p = self.snap.press(cx, p, &[], None);
@@ -120,20 +445,30 @@ impl Tool for CurvatureTool {
vec![Action::Exec("path.curvature".into(), self.params()), Action::Notify("created".into())]
}
PointerKind::Drag => {
let Some((i, start, began)) = self.drag else { return vec![] };
let Some((grab, start, began)) = self.drag else { return vec![] };
let mut out = vec![];
if !began {
if p.distance(start) < cx.tol(3.0) {
return out;
}
out.push(Action::Begin("Curvature".into()));
self.drag = Some((i, start, true));
self.drag = Some((grab, start, true));
}
let p = self.snap.drag(cx, p, None);
if let Some(pt) = self.pts.get_mut(i) {
pt.0 = p;
}
out.push(Action::Preview("path.curvature".into(), self.params()));
out.push(match grab {
Grab::Drawn(i) => {
if let Some(pt) = self.pts.get_mut(i) {
pt.0 = p;
}
Action::Preview("path.curvature".into(), self.params())
}
Grab::Anchor(id, si, ai) => {
Action::Preview(EDIT.into(), json!({"id": id.0, "subpath": si, "op": "move", "anchor": ai, "x": p.x, "y": p.y}))
}
Grab::Inserted(id, si, seg, t) => {
Action::Preview(EDIT.into(), json!({"id": id.0, "subpath": si, "op": "insert", "segment": seg, "t": t, "x": p.x, "y": p.y}))
}
});
out
}
PointerKind::Up => {
@@ -145,7 +480,7 @@ impl Tool for CurvatureTool {
}
PointerKind::DoubleClick => {
if active.is_none() {
return vec![];
return anchor_in(cx, editable_paths(cx), p, point_tol(cx)).and_then(|hit| toggle(cx, hit)).into_iter().collect();
}
let Some(i) = self.hit_point(cx, p) else { return vec![] };
self.pts[i].1 = !self.pts[i].1;
@@ -158,14 +493,30 @@ impl Tool for CurvatureTool {
self.id = Some(cx.selection.objects[0]);
}
}
fn claims_key(&self, cx: &ToolContext, key: ToolKey) -> bool {
matches!(key, ToolKey::Backspace | ToolKey::Delete)
&& self.drag.is_none()
&& if self.active(cx).is_some() { self.pts.len() > 1 } else { current_point(cx).is_some() }
}
fn key(&mut self, cx: &ToolContext, key: ToolKey, _m: Mods) -> Vec<Action> {
match key {
ToolKey::Escape | ToolKey::Enter => {
let dragging = self.drag.is_some_and(|d| d.2);
let drawing = self.active(cx).is_some();
self.reset();
if dragging { vec![Action::Cancel] } else { vec![] }
if dragging {
return vec![Action::Cancel];
}
// A selected path's current point goes: clicks no longer go on from it.
if drawing || current_point(cx).is_none() {
return vec![];
}
vec![Action::Exec("select.set".into(), json!({"ids": crate::json_ids(&cx.selection.objects)}))]
}
ToolKey::Backspace | ToolKey::Delete if self.active(cx).is_some() && self.pts.len() > 1 && self.drag.is_none() => {
ToolKey::Backspace | ToolKey::Delete if self.claims_key(cx, key) => {
if self.active(cx).is_none() {
return current_point(cx).map(remove_anchor).into_iter().collect();
}
let i = self.current.unwrap_or(self.pts.len() - 1).min(self.pts.len() - 1);
self.pts.remove(i);
if self.pts.len() < 3 {
@@ -184,19 +535,34 @@ impl Tool for CurvatureTool {
}
fn overlays(&self, cx: &ToolContext) -> Vec<Overlay> {
let mut o = self.snap.guides().to_vec();
let band = cx.curvature_rubber_band && self.drag.is_none();
let mut bp = BezPath::new();
if self.active(cx).is_none() {
// The curve on from the current end of a selected path: its last segment and the next.
if band
&& let (Some(e), Some(h)) = (current_end(cx), self.hover)
&& let Some(sp) = subpath(cx, e.id, e.si)
{
let n = sp.anchors.len();
let near = if e.start {
sp.anchors.iter().take(2).rev().map(Anchor::reversed).collect()
} else {
sp.anchors.iter().skip(n.saturating_sub(2)).copied().collect()
};
let mut tail = SubPath::new(near, false);
curvature_extend(&mut tail, false, h, self.how(&e));
tail.to_bezpath_into(&mut bp);
o.push(Overlay::Path { path: bp, color: FEEDBACK, width: 1.0, dashed: false });
}
return o;
}
if cx.curvature_rubber_band
if band
&& !self.closed
&& self.drag.is_none()
&& let Some(h) = self.hover
{
let mut pts = self.pts.clone();
pts.push((h, false));
let sp = catmull_rom(&pts, false);
let mut bp = vectorcraft_geom::BezPath::new();
sp.to_bezpath_into(&mut bp);
catmull_rom(&pts, false).to_bezpath_into(&mut bp);
o.push(Overlay::Path { path: bp, color: FEEDBACK, width: 1.0, dashed: false });
}
for (i, (p, _)) in self.pts.iter().enumerate() {
@@ -204,7 +570,33 @@ impl Tool for CurvatureTool {
}
o
}
fn cursor(&self, _cx: &ToolContext, _p: Point, _m: Mods) -> Cursor {
fn cursor(&self, cx: &ToolContext, p: Point, m: Mods) -> Cursor {
if self.active(cx).is_some() {
return match self.hit_point(cx, p) {
Some(0) if !self.closed && self.pts.len() >= 3 => Cursor::PenClose,
Some(_) if m.alt => Cursor::PenConvert,
Some(_) => Cursor::Move,
None => Cursor::Pen,
};
}
let tol = point_tol(cx);
let end = current_end(cx);
if end.is_some_and(|e| e.anchors >= 3 && p.distance(e.other) <= tol) {
return Cursor::PenClose;
}
if let Some((id, si, ai)) = anchor_in(cx, editable_paths(cx), p, tol) {
let open_end = subpath(cx, id, si).is_some_and(|sp| !sp.closed && (ai == 0 || ai + 1 == sp.anchors.len()));
return if m.alt {
Cursor::PenConvert
} else if open_end {
Cursor::PenContinue
} else {
Cursor::Move
};
}
if end.is_none() && segment_in(cx, editable_paths(cx), p, tol).is_some() {
return Cursor::PenAdd;
}
Cursor::Pen
}
}
@@ -213,7 +605,8 @@ impl Tool for CurvatureTool {
mod tests {
use super::*;
use crate::testutil::*;
use vectorcraft_doc::Selection;
use vectorcraft_doc::{Appearance, Document, Node, Selection};
use vectorcraft_geom::{ParamCurve, PathData};
#[test]
fn first_click_creates_then_notify_tracks_path() {
@@ -252,4 +645,266 @@ mod tests {
t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 202.0, 99.0));
assert!(t.overlays(&cx).is_empty());
}
fn pt(x: f64, y: f64) -> Point {
Point::new(x, y)
}
/// An open pen-style path: a corner start, two smooth anchors with uneven handles, a cusp and
/// an end with only an incoming handle.
fn wave() -> SubPath {
SubPath::new(
vec![
Anchor::corner(pt(0.0, 100.0)),
Anchor::with_handles(pt(100.0, 0.0), pt(60.0, 10.0), pt(160.0, -15.0)),
Anchor::with_handles(pt(250.0, 80.0), pt(220.0, 30.0), pt(280.0, 130.0)),
Anchor::with_handles(pt(350.0, 150.0), pt(320.0, 160.0), pt(380.0, 100.0)),
Anchor::with_handles(pt(450.0, 60.0), pt(420.0, 90.0), pt(450.0, 60.0)),
],
false,
)
}
/// Every point of `a` lies on `b` (within 1e-6), sampled.
fn lies_on(a: &SubPath, b: &SubPath) -> bool {
let b = PathData::single(b.clone());
(0..a.segment_count()).all(|i| (0..=20).all(|k| b.nearest(a.segment(i).eval(k as f64 / 20.0)).is_some_and(|n| n.4 < 1e-6)))
}
fn collinear(a: Vec2, b: Vec2) -> bool {
a.cross(b).abs() < 1e-6 * a.hypot().max(1.0) * b.hypot().max(1.0)
}
#[test]
fn moving_a_point_recurves_only_its_two_segments() {
let before = wave();
let mut sp = before.clone();
assert_eq!(sp.anchors[2].kind, AnchorKind::Smooth);
assert!(curvature_move(&mut sp, 2, pt(260.0, 140.0)));
assert_eq!(sp.anchors[2].p, pt(260.0, 140.0));
// The segments beyond its neighbours are bit-identical.
assert_eq!(sp.segment(0), before.segment(0));
assert_eq!(sp.segment(3), before.segment(3));
// The neighbours keep their handle directions on its segments, and their other handles.
assert!(collinear(sp.anchors[1].h_out - sp.anchors[1].p, before.anchors[1].h_out - before.anchors[1].p));
assert!(collinear(sp.anchors[3].h_in - sp.anchors[3].p, before.anchors[3].h_in - before.anchors[3].p));
assert_eq!((sp.anchors[1].h_in, sp.anchors[3].h_out), (before.anchors[1].h_in, before.anchors[3].h_out));
// The moved smooth point turns along the line through its neighbours.
let a = sp.anchors[2];
assert_eq!(a.kind, AnchorKind::Smooth);
assert!(collinear(a.h_out - a.p, sp.anchors[3].p - sp.anchors[1].p) && collinear(a.h_in - a.p, a.h_out - a.p));
assert!((a.h_out - a.p).dot(sp.anchors[3].p - sp.anchors[1].p) > 0.0);
// A cusp keeps its handle directions; a moved end changes its one segment only.
assert_eq!(sp.anchors[3].kind, AnchorKind::Corner);
assert!(curvature_move(&mut sp, 3, pt(360.0, 170.0)));
assert!(collinear(sp.anchors[3].h_out - sp.anchors[3].p, before.anchors[3].h_out - before.anchors[3].p));
let mut end = before.clone();
assert!(curvature_move(&mut end, 4, pt(470.0, 20.0)));
assert_eq!(end.segment(2), before.segment(2));
assert!(!curvature_move(&mut end, 5, pt(0.0, 0.0)));
}
#[test]
fn moving_a_corner_without_handles_keeps_its_sides_straight() {
let (d, id) = doc_with_rect();
let mut sp = d.node(id).unwrap().path_data().unwrap().subpaths[0].clone();
assert!(curvature_move(&mut sp, 0, pt(80.0, 70.0)));
assert!((0..sp.segment_count()).all(|i| sp.segment_is_line(i)));
assert_eq!(sp.anchors[0], Anchor::corner(pt(80.0, 70.0)));
}
#[test]
fn going_on_from_an_end_keeps_the_old_segments() {
let before = wave();
let mut sp = before.clone();
curvature_extend(&mut sp, false, pt(550.0, 120.0), EndCurve::Keep);
assert_eq!(sp.anchors.len(), 6);
assert!((0..4).all(|i| sp.segment(i) == before.segment(i)));
// The old end turns smooth, going on along its incoming handle, a third of the chord out.
let e = sp.anchors[4];
assert_eq!(e.kind, AnchorKind::Smooth);
assert!(collinear(e.h_out - e.p, e.p - e.h_in) && (e.h_out - e.p).dot(e.p - e.h_in) > 0.0);
assert!((e.h_out.distance(e.p) - e.p.distance(pt(550.0, 120.0)) / 3.0).abs() < 1e-9);
assert_eq!(sp.anchors[5], Anchor::corner(pt(550.0, 120.0)));
// The point placed then curves through its neighbours as a drawn path's points do.
curvature_extend(&mut sp, false, pt(650.0, 60.0), EndCurve::Smooth);
let drawn = catmull_rom(&[(pt(450.0, 60.0), false), (pt(550.0, 120.0), false), (pt(650.0, 60.0), false)], false);
assert_eq!((sp.anchors[5].h_in, sp.anchors[5].h_out), (drawn.anchors[1].h_in, drawn.anchors[1].h_out));
assert!((0..4).all(|i| sp.segment(i) == before.segment(i)));
// A corner stays one.
curvature_extend(&mut sp, false, pt(700.0, 100.0), EndCurve::Corner);
assert!(!sp.anchors[6].has_in() && !sp.anchors[6].has_out());
// From the start: the old segments come one later, and the new end is the first anchor.
let mut sp = before.clone();
curvature_extend(&mut sp, true, pt(-100.0, 50.0), EndCurve::Keep);
assert_eq!(sp.anchors[0], Anchor::corner(pt(-100.0, 50.0)));
assert!((0..4).all(|i| sp.segment(i + 1) == before.segment(i)));
// A corner end without handles goes on along its segment's tangent.
let old = sp.anchors[1];
assert!(old.has_in() && !old.has_out());
assert!(collinear(old.h_in - old.p, old.p - before.anchors[1].h_in) && (old.h_in - old.p).dot(old.p - before.anchors[1].h_in) > 0.0);
}
#[test]
fn closing_keeps_the_old_segments() {
let before = wave();
let mut sp = before.clone();
curvature_close(&mut sp, false, EndCurve::Keep);
assert!(sp.closed && sp.anchors.len() == 5);
assert!((0..4).all(|i| sp.segment(i) == before.segment(i)));
// The first anchor gains an incoming handle along its tangent: no kink there.
let f = sp.anchors[0];
assert!(f.has_in() && collinear(f.p - f.h_in, before.anchors[1].h_in - f.p));
}
#[test]
fn inserting_a_point_keeps_the_shape() {
let before = wave();
let mut sp = before.clone();
assert_eq!(curvature_insert(&mut sp, 1, 0.3), Some(2));
assert_eq!(sp.anchors.len(), 6);
assert_eq!(sp.anchors[2].kind, AnchorKind::Smooth);
assert!(lies_on(&sp, &before) && lies_on(&before, &sp));
// On a straight side the point is smooth too, its handles along the side.
let (d, id) = doc_with_rect();
let rect = d.node(id).unwrap().path_data().unwrap().subpaths[0].clone();
let mut sp = rect.clone();
let i = curvature_insert(&mut sp, 0, 0.5).unwrap();
assert_eq!(sp.anchors[i].kind, AnchorKind::Smooth);
assert!(sp.anchors[i].has_in() && sp.anchors[i].has_out());
assert!(lies_on(&sp, &rect) && lies_on(&rect, &sp));
assert_eq!(curvature_insert(&mut sp, 99, 0.5), None);
}
/// A document with one path, `sp`.
fn doc_with(sp: SubPath) -> (Document, NodeId) {
let mut d = Document::new(800.0, 600.0);
let l = d.layers[0].id;
let id = d.alloc_id();
d.insert(Some(l), 0, Node::path(id, PathData::single(sp), Appearance::default_art())).unwrap();
(d, id)
}
/// Path `id` selected, anchor `current` of its first subpath direct-selected (or none).
fn selected(id: NodeId, current: Option<usize>) -> Selection {
let mut s = Selection::default();
s.set([id]);
if let Some(ai) = current {
s.anchors.insert(id, [(0, ai)].into());
}
s
}
/// A context without snapping.
fn quiet<'a>(d: &'a Document, s: &'a Selection, p: &'a crate::PaintDefaults) -> ToolContext<'a> {
ToolContext { smart_guides: false, snap_to_point: false, ..cx(d, s, p) }
}
fn press(t: &mut CurvatureTool, cx: &ToolContext, x: f64, y: f64, alt: bool) -> Vec<Action> {
let ev = PointerEvent::new(PointerKind::Down, x, y).with_mods(Mods { alt, ..Mods::default() });
let mut a = t.pointer(cx, &ev);
a.extend(t.pointer(cx, &PointerEvent::new(PointerKind::Up, x, y)));
a
}
/// The op and params of a `path.curvatureEdit` action.
fn edit_op(a: &Action) -> Option<(&str, &Value)> {
match a {
Action::Exec(c, v) | Action::Preview(c, v) if c == EDIT => Some((v["op"].as_str()?, v)),
_ => None,
}
}
#[test]
fn a_press_on_a_point_selects_it_and_a_drag_moves_it() {
let (d, id) = doc_with(wave());
let (s, p) = (selected(id, None), paint());
let cx = quiet(&d, &s, &p);
let mut t = CurvatureTool::default();
assert_eq!(t.cursor(&cx, pt(250.0, 81.0), Mods::default()), Cursor::Move);
assert_eq!(t.cursor(&cx, pt(450.0, 61.0), Mods::default()), Cursor::PenContinue);
let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 251.0, 81.0));
assert_eq!(a, vec![Action::Exec("select.anchors".into(), json!({"id": id.0, "anchors": [[0, 2]], "mode": "set"}))]);
let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 260.0, 140.0));
assert_eq!(a[0], Action::Begin("Curvature".into()));
let moved = edit_op(&a[1]).map(|(op, v)| (op, v["anchor"].clone(), v["x"].clone(), v["y"].clone()));
assert_eq!(moved, Some(("move", json!(2), json!(260.0), json!(140.0))));
assert!(t.busy());
assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 260.0, 140.0)), vec![Action::Commit]);
// A press without a drag only selects.
assert_eq!(press(&mut t, &cx, 100.0, 0.0, false).len(), 1);
}
#[test]
fn alt_click_or_double_click_toggles_and_delete_removes() {
let (d, id) = doc_with(wave());
let p = paint();
let s = selected(id, None);
let cx = quiet(&d, &s, &p);
let mut t = CurvatureTool::default();
let to = |a: &[Action]| a.iter().find(|a| matches!(a, Action::Exec(c, _) if c == "path.convertAnchor")).cloned();
let a = press(&mut t, &cx, 100.0, 0.0, true);
assert!(matches!(to(&a), Some(Action::Exec(_, v)) if v["anchor"] == 1 && v["to"] == "corner"), "{a:?}");
assert_eq!(t.cursor(&cx, pt(100.0, 0.0), Mods { alt: true, ..Mods::default() }), Cursor::PenConvert);
let a = t.pointer(&cx, &PointerEvent::new(PointerKind::DoubleClick, 0.0, 100.0));
assert!(matches!(to(&a), Some(Action::Exec(_, v)) if v["anchor"] == 0 && v["to"] == "smooth"), "{a:?}");
// Delete is the tool's while a point is current, and removes it.
assert!(!t.claims_key(&cx, ToolKey::Delete));
let s = selected(id, Some(2));
let cx = quiet(&d, &s, &p);
assert!(t.claims_key(&cx, ToolKey::Backspace));
assert_eq!(t.key(&cx, ToolKey::Delete, Mods::default()), vec![remove_anchor((id, 0, 2))]);
// Esc lets go of the point.
assert_eq!(t.key(&cx, ToolKey::Escape, Mods::default()), vec![Action::Exec("select.set".into(), json!({"ids": [id.0]}))]);
}
#[test]
fn a_press_on_a_segment_adds_a_point_and_a_drag_moves_it_in_one_step() {
let (d, id) = doc_with(wave());
let (s, p) = (selected(id, None), paint());
let cx = quiet(&d, &s, &p);
let mut t = CurvatureTool::default();
let on = wave().segment(1).eval(0.5);
assert_eq!(t.cursor(&cx, on, Mods::default()), Cursor::PenAdd);
let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, on.x, on.y));
assert_eq!(a[0], Action::Begin("Curvature".into()));
assert!(
matches!(edit_op(&a[1]), Some(("insert", v)) if v["segment"] == 1 && (v["t"].as_f64().unwrap() - 0.5).abs() < 1e-3 && v.get("x").is_none())
);
let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, on.x + 1.0, on.y + 40.0));
assert!(matches!(edit_op(&a[0]), Some(("insert", v)) if v["segment"] == 1 && v["y"] == on.y + 40.0), "{a:?}");
assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, on.x, on.y + 40.0)), vec![Action::Commit]);
}
#[test]
fn clicks_go_on_from_a_current_end_and_the_other_end_closes() {
let p = paint();
let mut sp = wave();
let mut t = CurvatureTool::default();
let (d, id) = doc_with(sp.clone());
let s = selected(id, Some(4));
let a = press(&mut t, &quiet(&d, &s, &p), 550.0, 120.0, false);
assert!(matches!(edit_op(&a[0]), Some(("extend", v)) if v["end"] == "end" && v["from"] == "keep" && v["x"] == 550.0), "{a:?}");
// As the engine does it: the new end is current, and the next click curves through it.
curvature_extend(&mut sp, false, pt(550.0, 120.0), EndCurve::Keep);
let (d, id) = doc_with(sp.clone());
let s = selected(id, Some(5));
let cx = quiet(&d, &s, &p);
t.pointer(&cx, &PointerEvent::new(PointerKind::Move, 650.0, 60.0));
assert!(t.overlays(&cx).iter().any(|o| matches!(o, Overlay::Path { .. })), "the rubber band shows");
let a = press(&mut t, &cx, 650.0, 60.0, true);
assert!(matches!(edit_op(&a[0]), Some(("extend", v)) if v["from"] == "smooth"), "{a:?}");
curvature_extend(&mut sp, false, pt(650.0, 60.0), EndCurve::Smooth);
let (d, id) = doc_with(sp.clone());
let s = selected(id, Some(6));
let cx = quiet(&d, &s, &p);
// The Alt-clicked point stays a corner; a click on the first point closes.
assert_eq!(t.cursor(&cx, pt(0.0, 100.0), Mods::default()), Cursor::PenClose);
let a = press(&mut t, &cx, 0.0, 100.0, false);
assert!(matches!(edit_op(&a[0]), Some(("close", v)) if v["from"] == "corner" && v["end"] == "end"), "{a:?}");
// Any other end keeps its curve; the start goes on from the start.
let s = selected(id, Some(0));
let a = press(&mut t, &quiet(&d, &s, &p), -50.0, 150.0, false);
assert!(matches!(edit_op(&a[0]), Some(("extend", v)) if v["end"] == "start" && v["from"] == "keep"), "{a:?}");
}
}
+35 -5
View File
@@ -365,11 +365,16 @@ impl Targets {
/// View → Snap to Point: only these targets' anchors pull, and the ruler guides (shown and
/// unlocked, as the selection tools pick them) pull the pointer into line where they run.
fn for_snap_to_point(self, cx: &ToolContext) -> Self {
let mut t = self.anchors_only();
self.anchors_only().with_rulers(cx)
}
/// These targets and the ruler guides, when they are shown (and so unlocked to the selection
/// tools): they pull a point into line where they run.
fn with_rulers(mut self, cx: &ToolContext) -> Self {
if cx.guides {
t.rulers = cx.doc.guides.iter().map(|g| Ruler { vertical: g.vertical, pos: g.pos, span: cx.doc.guide_span(g) }).collect();
self.rulers = cx.doc.guides.iter().map(|g| Ruler { vertical: g.vertical, pos: g.pos, span: cx.doc.guide_span(g) }).collect();
}
t
self
}
/// What a dragged selection's grabbed point snaps to with View → Snap to Point and Smart
@@ -486,8 +491,10 @@ impl Targets {
if d.abs() <= 1e-9 {
continue;
}
// The ruler guides that way count as lines too (#812).
let rulers: Vec<(f64, Point, Kind)> = self.rulers.iter().filter(|r| r.vertical == vertical).filter_map(|r| r.line_at(q, reach)).collect();
// A line that far across the way crosses it at least that far along.
for (t, from, _) in lines_near(lines, v, reach) {
for (t, from, _) in lines_near(lines, v, reach).iter().chain(&rulers) {
let s = (t - a) / d;
// Exactly on the line, whatever the rounding along the way.
let hit = if vertical { Point::new(*t, at.y + dir.y * s) } else { Point::new(at.x + dir.x * s, *t) };
@@ -827,7 +834,9 @@ impl PointSnap {
let targets = if cx.snap_to_pixel || cx.snap_to_grid {
None
} else if cx.smart_guides {
Some((targets().styled(cx), cx.snapping_tolerance))
// Snap to Point keeps pulling points onto the ruler guides with Smart Guides on (#812).
let t = targets().styled(cx);
Some((if cx.snap_to_point { t.with_rulers(cx) } else { t }, cx.snapping_tolerance))
} else if cx.snap_to_point {
Some((targets().for_snap_to_point(cx), cx.snap_tolerance))
} else {
@@ -1397,6 +1406,27 @@ mod tests {
}
}
/// #812: with Smart Guides on, ruler guides pull a drawn point too (Snap to Point), horizontal
/// and vertical alike, also while it slides along a construction guide or Shift's angle.
#[test]
fn drawn_points_snap_to_ruler_guides_with_smart_guides_on() {
let (mut d, _) = doc_with_rect();
d.guides.push(vectorcraft_doc::Guide::new(false, 313.0));
d.guides.push(vectorcraft_doc::Guide::new(true, 331.0));
let (s, p) = (Selection::default(), paint());
let c = cx(&d, &s, &p);
let mut snap = DrawSnap::default();
assert_eq!(snap.press(&c, Point::new(260.0, 315.0), &[], None), Point::new(260.0, 313.0), "the horizontal guide");
assert_eq!(snap.press(&c, Point::new(329.0, 260.0), &[], None), Point::new(331.0, 260.0), "the vertical guide");
// On the 45° construction guide from (210, 210), where the horizontal guide crosses it.
let from = Leave::segment(&c, Point::new(210.0, 210.0), false);
let q = snap.press(&c, Point::new(312.0, 311.0), &[], Some(&from));
assert!((q - Point::new(313.0, 313.0)).hypot() < 1e-9, "{q:?}");
// Snap to Point off: Smart Guides alone don't use the ruler guides.
let off = ToolContext { snap_to_point: false, ..cx(&d, &s, &p) };
assert_eq!(snap.press(&off, Point::new(260.0, 315.0), &[], None), Point::new(260.0, 315.0));
}
/// A drawing tool's snapper reuses its targets while hovering over the same document state, and
/// gathers them again when it changes, and on every press.
#[test]
+1 -10
View File
@@ -27,7 +27,7 @@ use vectorcraft_doc::{NodeId, NodeKind};
use vectorcraft_geom::{BezPath, Point};
use crate::direct::hit_handle;
use crate::draw2::AnchorTool;
use crate::draw2::{AnchorTool, editable_paths};
use crate::guides::{DrawSnap, Leave};
use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey};
@@ -122,15 +122,6 @@ fn alt_converts(cx: &ToolContext, p: Point, m: Mods) -> bool {
|| crate::draw2::segment_in(cx, editable_paths(cx), p, cx.pick_tol()).is_some())
}
/// The selected paths the pen edits (not guides, nor locked or hidden ones).
fn editable_paths<'a>(cx: &'a ToolContext) -> impl Iterator<Item = NodeId> + 'a {
cx.selection
.objects
.iter()
.copied()
.filter(|&id| cx.doc.is_editable(id) && cx.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: false, .. })))
}
/// Preview the outgoing handle of anchor `ai` of subpath `si` at `h`, the incoming one left alone.
fn set_out_handle(id: NodeId, si: usize, ai: usize, h: Point) -> Action {
Action::Preview(
+73 -1
View File
@@ -71,6 +71,8 @@ pub struct SelectionTool {
targets: Option<Targets>,
moving: Option<MoveSnap>,
guide: GuideEdit,
/// Smart Guides: the centre or anchor under the pointer, and its label ([`Self::hover_point`]).
hover: Option<(Point, &'static str)>,
}
/// Snapping for the selection moved as a whole, its targets gathered when the move begins: View →
@@ -163,10 +165,36 @@ fn box_hit(cx: &ToolContext, b: &OrientedBox, p: Point) -> Option<BoxHit> {
in_rotate_zone(b.rect, lp, tol, cx.tol(18.0)).map(|_| BoxHit::Rotate)
}
/// How near (screen points) the pointer must come to an object's centre or anchor for Smart Guides
/// to label it while hovering.
const HOVER_REACH: f64 = 6.0;
impl SelectionTool {
fn drag_threshold(cx: &ToolContext) -> f64 {
cx.tol(3.0)
}
/// With Smart Guides on, the anchor or the centre of an object near `p` (the one under the
/// pointer, else a selected one) and its label, "anchor" or "center", as Illustrator shows
/// them while hovering (#812). A press there grabs the object by that point.
fn hover_point(cx: &ToolContext, p: Point) -> Option<(Point, &'static str)> {
if !cx.smart_guides {
return None;
}
let reach = cx.tol(HOVER_REACH);
let under = hit_test(cx.doc, p, cx.hit_options()).map(|h| h.top_object(cx.isolation));
let nearest = |points: &mut dyn Iterator<Item = Point>| {
points.filter(|q| q.distance(p) <= reach).min_by(|a, b| a.distance(p).total_cmp(&b.distance(p)))
};
under.into_iter().chain(cx.selection.objects.iter().copied()).find_map(|id| {
let n = cx.doc.node(id)?;
let anchor = n.path_data().and_then(|pd| nearest(&mut pd.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p))));
anchor.map(|q| (q, "anchor")).or_else(|| {
let c = cx.doc.bounds_of(&[id], cx.preview_bounds)?.center();
(c.distance(p) <= reach).then_some((c, "center"))
})
})
}
}
impl Tool for SelectionTool {
@@ -188,6 +216,11 @@ impl Tool for SelectionTool {
}
let p = ev.pos;
let m = ev.mods;
// A press near the hovered centre or anchor grabs the object by it.
let grab = self.hover.take().map(|(q, _)| q).filter(|q| q.distance(p) <= cx.tol(HOVER_REACH)).unwrap_or(p);
if matches!(ev.kind, PointerKind::Move) && matches!(self.state, State::Idle) {
self.hover = Self::hover_point(cx, p);
}
match (ev.kind, self.state.clone()) {
(PointerKind::DoubleClick, _) => {
self.state = State::Idle;
@@ -278,7 +311,7 @@ impl Tool for SelectionTool {
} else if cx.selection.objects.len() > 1 && !m.cmd && !m.alt {
key = Some(top);
}
self.state = State::Moving { start: p, began: false, deselect, key };
self.state = State::Moving { start: grab, began: false, deselect, key };
out
}
None => {
@@ -397,6 +430,12 @@ impl Tool for SelectionTool {
}
o.extend(self.guides.iter().cloned());
o.extend(self.guide.overlays(cx));
if let (Some((q, label)), State::Idle) = (self.hover, &self.state) {
let style = crate::guides::GuideStyle::of(cx);
if style.labels {
o.push(Overlay::Label { p: q, text: label.into(), color: style.color });
}
}
if let Some((p, t)) = &self.measure {
o.push(Overlay::Measure { p: *p, text: t.clone() });
}
@@ -483,6 +522,39 @@ mod tests {
PointerEvent::new(kind, x, y)
}
/// #812: with Smart Guides on, hovering near an object's centre or an anchor labels it, and a
/// press there grabs the object by that point.
#[test]
fn hovering_labels_the_centre_and_anchors_and_a_press_grabs_by_them() {
let (d, _) = doc_with_rect();
let s = Selection::default();
let p = paint();
let cx = cx(&d, &s, &p);
let label = |t: &SelectionTool| {
t.overlays(&cx).iter().find_map(|o| match o {
Overlay::Label { p, text, .. } => Some((*p, text.clone())),
_ => None,
})
};
let mut t = SelectionTool::default();
t.pointer(&cx, &ev(PointerKind::Move, 152.0, 151.0));
assert_eq!(label(&t), Some((Point::new(150.0, 150.0), "center".to_string())));
t.pointer(&cx, &ev(PointerKind::Move, 102.0, 101.0));
assert_eq!(label(&t), Some((Point::new(100.0, 100.0), "anchor".to_string())));
t.pointer(&cx, &ev(PointerKind::Move, 130.0, 170.0));
assert_eq!(label(&t), None, "away from both");
// Grabbed by its centre, the object's centre follows the pointer.
t.pointer(&cx, &ev(PointerKind::Move, 152.0, 151.0));
t.pointer(&cx, &ev(PointerKind::Down, 152.0, 151.0));
let a = t.pointer(&cx, &ev(PointerKind::Drag, 250.0, 250.0));
assert!(a.iter().any(|a| matches!(a, Action::Preview(_, v) if v["matrix"][4] == 100.0 && v["matrix"][5] == 100.0)), "{a:?}");
// With Smart Guides off, nothing is labelled.
let off = ToolContext { smart_guides: false, ..cx };
let mut t = SelectionTool::default();
t.pointer(&off, &ev(PointerKind::Move, 152.0, 151.0));
assert!(!t.overlays(&off).iter().any(|o| matches!(o, Overlay::Label { .. })));
}
#[test]
fn click_selects_object() {
let (d, id) = doc_with_rect();
+4 -1
View File
@@ -346,7 +346,10 @@ impl Tool for ArtboardTool {
for h in Handle::ALL {
o.push(Overlay::Anchor { p: h.pos(r), color: BLUE, filled: false, size: 7.0 });
}
o.push(Overlay::Label { p: Point::new(r.x0, r.y0 - cx.tol(14.0)), text: format!("{:02} - {}", self.active + 1, ab.name), color: BLUE });
// Where the canvas names the other artboards: on the top edge, flush with the left one
// (labels are drawn 8 px right of and 14 px above their point).
let at = Point::new(r.x0 - cx.tol(8.0), r.y0 - cx.tol(4.0));
o.push(Overlay::Label { p: at, text: format!("{:02} - {}", self.active + 1, ab.name), color: BLUE });
if let (Some(Drag::Resize { began: true, .. }), true) = (self.drag, cx.measurement_labels) {
o.push(Overlay::Measure {
p: Point::new(r.x1, r.y1) + Vec2::new(cx.tol(12.0), cx.tol(12.0)),
+85 -41
View File
@@ -249,6 +249,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
placed: vectorcraft_render::placed_document::generation(),
pixel,
smooth_images,
isolated: st.isolation.map(|id| id.0),
};
// Placed documents' bitmaps are being made: draw again when they are ready.
if vectorcraft_render::placed_document::busy() {
@@ -298,6 +299,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
progressive_placed: true,
trace_views: true,
smooth_images,
// Isolation mode: the art around the isolated group or layer is dimmed (#833).
isolated: key.isolated.map(vectorcraft_doc::NodeId),
..opts
};
// Light documents render synchronously (no lag vs overlays); heavy ones go to the worker.
@@ -349,8 +352,11 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
if app.ui.view.pixel_preview && v.zoom >= PIXEL_GRID_ZOOM && app.session.prefs.show_pixel_grid {
grid(&painter, &xf, 1.0, 1, LineLook { color: PIXEL_GRID, dots: false });
}
// Artboard edges and names.
// Artboard edges and names. The Artboard tool labels its active artboard itself (following
// a move or resize): that one isn't named twice.
let active_ab = 0;
let artboard_tool = app.session.tool_id() == "artboard";
let tool_labelled = artboard_tool.then(|| app.session.tool_options()["active"].as_u64()).flatten();
for (i, ab) in doc.artboards.iter().enumerate() {
let r = xf.rect_to_screen(ab.rect);
let c = if i == active_ab { Color32::from_gray(0) } else { Color32::from_gray(120) };
@@ -359,7 +365,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
if doc.setup.has_bleed() {
painter.add(Shape::closed_line(xf.quad(doc.setup.bleed_rect(ab.rect)), Stroke::new(1.0, t.bleed)));
}
if app.session.tool_id() == "artboard" || doc.artboards.len() > 1 {
if (artboard_tool || doc.artboards.len() > 1) && tool_labelled != u64::try_from(i).ok() {
painter.text(
r.left_top() - vec2(0.0, 4.0),
egui::Align2::LEFT_BOTTOM,
@@ -1078,47 +1084,46 @@ fn rulers(ui: &Ui, full: egui::Rect, xf: &Xf, hover: Option<Point>, unit: Unit,
let step = unit.ruler_step(xf.zoom);
let minor = step / 10.0;
let font = egui::FontId::proportional(9.5);
let a = xf.to_doc(top.left_top());
let b = xf.to_doc(top.right_top());
let clip_top = p.with_clip_rect(top);
let mut x = (a.x / per / minor).floor() * minor;
while x * per <= b.x {
let sx = xf.to_screen(Point::new(x * per, 0.0)).x;
let is_major = ((x / step).round() * step - x).abs() < minor * 0.01;
let is_mid = ((x / (step / 2.0)).round() * (step / 2.0) - x).abs() < minor * 0.01;
let len = if is_major {
let near = |v: f64, every: f64| ((v / every).round() * every - v).abs() < minor * 0.01;
// A tick's length: the labelled ones longest, the halves between them shorter.
let tick = |v: f64| {
if near(v, step) {
RULER
} else if is_mid {
} else if near(v, step / 2.0) {
7.0
} else {
4.0
};
clip_top.line_segment([pos2(sx, top.bottom() - len), pos2(sx, top.bottom())], Stroke::new(1.0, t.ruler_tick));
if is_major {
}
};
// Each ruler measures along its own edge, in the canvas's coordinates turned with the view
// (#826): at 0° the top one reads x and the left one y. `draw` gets each tick's distance
// (screen points) from `from` along the ruler, and its value in `unit`.
let ticks = |from: Pos2, to: Pos2, axis: vectorcraft_geom::Vec2, draw: &mut dyn FnMut(f32, f64)| {
let along = |s: Pos2| xf.to_doc(s).to_vec2().dot(axis);
let (a, b) = (along(from), along(to));
let mut v = (a / per / minor).floor() * minor;
while v * per <= b {
draw(((v * per - a) * xf.zoom) as f32, v);
v += minor;
}
};
// The canvas's directions along the screen's x and y.
let (sn, cs) = xf.rot.sin_cos();
let clip_top = p.with_clip_rect(top);
ticks(top.left_top(), top.right_top(), vectorcraft_geom::Vec2::new(cs, -sn), &mut |d, x| {
let sx = top.left() + d;
clip_top.line_segment([pos2(sx, top.bottom() - tick(x)), pos2(sx, top.bottom())], Stroke::new(1.0, t.ruler_tick));
if near(x, step) {
clip_top.text(pos2(sx + 2.0, top.top() + 1.0), egui::Align2::LEFT_TOP, ruler_label(x, step), font.clone(), t.ruler_tick);
}
x += minor;
}
let a = xf.to_doc(left.left_top());
let b = xf.to_doc(left.left_bottom());
});
let clip_left = p.with_clip_rect(left);
let mut y = (a.y / per / minor).floor() * minor;
while y * per <= b.y {
let sy = xf.to_screen(Point::new(0.0, y * per)).y;
let is_major = ((y / step).round() * step - y).abs() < minor * 0.01;
let is_mid = ((y / (step / 2.0)).round() * (step / 2.0) - y).abs() < minor * 0.01;
let len = if is_major {
RULER
} else if is_mid {
7.0
} else {
4.0
};
clip_left.line_segment([pos2(left.right() - len, sy), pos2(left.right(), sy)], Stroke::new(1.0, t.ruler_tick));
if is_major {
ticks(left.left_top(), left.left_bottom(), vectorcraft_geom::Vec2::new(sn, cs), &mut |d, y| {
let sy = left.top() + d;
clip_left.line_segment([pos2(left.right() - tick(y), sy), pos2(left.right(), sy)], Stroke::new(1.0, t.ruler_tick));
if near(y, step) {
// Vertical labels read top-to-bottom, one digit per line like Illustrator.
let s = ruler_label(y, step);
for (k, ch) in s.chars().enumerate() {
for (k, ch) in ruler_label(y, step).chars().enumerate() {
clip_left.text(
pos2(left.left() + 4.0, sy + 2.0 + k as f32 * 8.5),
egui::Align2::LEFT_TOP,
@@ -1128,8 +1133,7 @@ fn rulers(ui: &Ui, full: egui::Rect, xf: &Xf, hover: Option<Point>, unit: Unit,
);
}
}
y += minor;
}
});
if let Some(h) = hover {
let s = xf.to_screen(h);
clip_top.line_segment([pos2(s.x, top.top()), pos2(s.x, top.bottom())], Stroke::new(1.0, t.text));
@@ -1846,10 +1850,9 @@ fn recent(app: &mut VectorcraftApp, ui: &mut Ui) {
crate::icons::icon(ui, "history", 16.0, t.icon);
let r = ui.add(egui::Button::new(egui::RichText::new(&name).color(t.accent).size(13.0)).frame(false)).on_hover_text(&path);
ui.add(egui::Label::new(egui::RichText::new(&folder).size(12.0).color(t.text_dim)).truncate());
if r.clicked()
&& let Err(e) = crate::io::open_path(app, &path)
{
app.status(e);
if r.clicked() {
// A failure is reported to the user there.
let _ = crate::io::open_reporting(app, &path);
}
});
}
@@ -2050,6 +2053,47 @@ mod tests {
use vectorcraft_engine::Session;
use vectorcraft_geom::Shape as _;
/// #826: in a turned view each ruler still has ticks along its whole length; at 0° the top one
/// reads x where the canvas has it.
#[test]
fn rulers_cover_their_length_at_any_rotation() {
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
let full = egui::Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0));
let [top, left, _] = ruler_rects(full);
for deg in [0.0_f64, 30.0, 90.0, 135.0, 200.0] {
let xf = Xf { rect: full, zoom: 1.0, center: Point::new(300.0, 200.0), rot: deg.to_radians() };
let mut out = ctx.run_ui(Default::default(), |ui| rulers(ui, full, &xf, None, Unit::Points, &Tokens::get(ui.ctx())));
out.textures_delta.clear();
// The ticks' positions along each ruler.
let along = |ruler: egui::Rect, x: bool| -> Vec<f32> {
let mut at: Vec<f32> = out
.shapes
.iter()
.filter(|c| c.clip_rect == ruler)
.filter_map(|c| match &c.shape {
Shape::LineSegment { points: [a, b], .. } if x && a.x == b.x => Some(a.x),
Shape::LineSegment { points: [a, b], .. } if !x && a.y == b.y => Some(a.y),
_ => None,
})
.collect();
at.sort_by(f32::total_cmp);
at
};
for (ruler, x) in [(top, true), (left, false)] {
let at = along(ruler, x);
let (start, end) = if x { (ruler.left(), ruler.right()) } else { (ruler.top(), ruler.bottom()) };
let (Some(first), Some(last)) = (at.first(), at.last()) else { panic!("{deg}°: no ticks") };
assert!(first - start < 20.0 && end - last < 20.0, "{deg}°: ticks from {first} to {last} on {start}..{end}");
assert!(at.windows(2).all(|w| w[1] - w[0] < 20.0), "{deg}°: a gap in the ticks");
}
if deg == 0.0 {
let origin = xf.to_screen(Point::ZERO).x;
assert!(along(top, true).iter().any(|x| (x - origin).abs() < 0.01), "a tick at x = 0");
}
}
}
#[test]
fn shaper_selection_highlights_only_the_visible_result() {
let mut s = Session::new();
+1 -17
View File
@@ -265,23 +265,7 @@ pub fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) {
}
return;
}
// Align buttons.
for (icon, tip, p) in [
("align-start-vertical", "Horizontal Align Left", json!({"horizontal": "left"})),
("align-center-vertical", "Horizontal Align Center", json!({"horizontal": "center"})),
("align-end-vertical", "Horizontal Align Right", json!({"horizontal": "right"})),
("align-start-horizontal", "Vertical Align Top", json!({"vertical": "top"})),
("align-center-horizontal", "Vertical Align Center", json!({"vertical": "center"})),
("align-end-horizontal", "Vertical Align Bottom", json!({"vertical": "bottom"})),
] {
if widgets::icon_button(ui, icon, tl!(tip), false, 24.0).clicked() {
let mut p = p;
if sel.len() == 1 {
p["to"] = json!("artboard");
}
app.run("object.align", p).ok();
}
}
crate::panels::align::align_buttons(app, ui, 24.0);
ui.separator();
// The Transform link opens the whole Transform panel (reference point, rotate,
// shear, options) in a popover; X/Y/W/H follow inline while the bar has room.
+11
View File
@@ -36,6 +36,17 @@ pub fn ask(app: &mut VectorcraftApp, message: &str, detail: &str, command: &str,
app.ui.dialog = Some(Dialog::new(KIND, fields));
}
/// The dialog kind of a message with a Close button only ([`tell`]).
pub const MESSAGE: &str = "message";
pub(super) const MESSAGE_SPEC: DialogSpec = DialogSpec { ok: None, ..SPEC };
/// Tell the user `message` (with an optional `detail` line), both in the UI language, in a dialog
/// they close.
pub fn tell(app: &mut VectorcraftApp, message: &str, detail: &str) {
app.ui.dialog = Some(Dialog::new(MESSAGE, json!({"message": message, "detail": detail})));
}
/// Closes before running, so a dialog the command opens stays open.
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
let params = d.fields.get("__params").cloned().unwrap_or_else(|| json!({}));
+60 -3
View File
@@ -90,12 +90,19 @@ fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
let screen =
d.fields.get("screen").and_then(Value::as_array).and_then(|a| Some(egui::pos2(a.first()?.as_f64()? as f32, a.get(1)?.as_f64()? as f32)));
let chip = Point::new(d.f64("x", 0.0), d.f64("y", 0.0));
let pos = screen.unwrap_or_else(|| {
app.canvas_rect.zip(app.view().copied()).map_or(ctx.content_rect().center(), |(r, v)| Xf::new(r, &v).to_screen(chip) + vec2(14.0, 14.0))
let area = egui::Id::new("gradient-stop-popover");
let size = ctx.memory(|m| m.area_rect(area)).map_or(POPOVER_SIZE, |r| r.size());
let pos = screen.unwrap_or_else(|| match app.canvas_rect.zip(app.view().copied()) {
Some((canvas, v)) => {
let xf = Xf::new(canvas, &v);
let at = xf.to_screen(chip);
selection_on_screen(app, &xf).map_or(at + vec2(14.0, 14.0), |art| beside_art(at, art, size, canvas))
}
None => ctx.content_rect().center(),
});
let swatches = d.str("tab") == "swatches";
let mut tab = None;
let resp = egui::Area::new(egui::Id::new("gradient-stop-popover"))
let resp = egui::Area::new(area)
.order(egui::Order::Foreground)
.fixed_pos(pos)
.constrain(true)
@@ -150,6 +157,34 @@ fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
}
}
/// The popover's size before it has been drawn.
const POPOVER_SIZE: egui::Vec2 = vec2(272.0, 360.0);
/// The selected art's box on the screen.
fn selection_on_screen(app: &VectorcraftApp, xf: &Xf) -> Option<egui::Rect> {
let st = app.session.active()?;
let b = st.doc.bounds_of(&st.selection.objects, false)?;
Some(egui::Rect::from_points(&xf.quad(b)))
}
/// Where the popover opened from a stop's chip at `chip` goes: beside the selected `art` on the
/// first side of it with room for a popover of `size` in `room` (right, left, below, above), so
/// the art it recolours stays in view (#862); else beside the chip.
fn beside_art(chip: egui::Pos2, art: egui::Rect, size: egui::Vec2, room: egui::Rect) -> egui::Pos2 {
const GAP: f32 = 12.0;
let x = (chip.x - size.x / 2.0).clamp(room.left(), (room.right() - size.x).max(room.left()));
let y = (chip.y - size.y / 2.0).clamp(room.top(), (room.bottom() - size.y).max(room.top()));
[
egui::pos2(art.right() + GAP, y),
egui::pos2(art.left() - GAP - size.x, y),
egui::pos2(x, art.bottom() + GAP),
egui::pos2(x, art.top() - GAP - size.y),
]
.into_iter()
.find(|p| room.contains_rect(egui::Rect::from_min_size(*p, size)))
.unwrap_or(chip + vec2(14.0, 14.0))
}
/// Document swatches as tiles: a click gives the stop (or point) that colour.
fn swatch_grid(app: &mut VectorcraftApp, ui: &mut egui::Ui, target: &Target) {
let colors = swatch_colors(app);
@@ -248,6 +283,28 @@ mod tests {
app
}
/// #862: the popover goes beside the art, on the first side with room, not over it.
#[test]
fn the_popover_goes_beside_the_art_it_edits() {
let room = egui::Rect::from_min_size(egui::pos2(0.0, 0.0), egui::vec2(1200.0, 800.0));
let size = egui::vec2(272.0, 360.0);
let place = |art: egui::Rect| egui::Rect::from_min_size(beside_art(art.center(), art, size, room), size);
// Room on the right.
let art = egui::Rect::from_min_max(egui::pos2(300.0, 300.0), egui::pos2(500.0, 450.0));
assert!(place(art).left() > art.right() && room.contains_rect(place(art)));
// Against the right edge: on the left.
let art = egui::Rect::from_min_max(egui::pos2(900.0, 300.0), egui::pos2(1150.0, 450.0));
assert!(place(art).right() < art.left());
// As wide as the room: below it, or above it near the bottom.
let art = egui::Rect::from_min_max(egui::pos2(100.0, 20.0), egui::pos2(1100.0, 300.0));
assert!(place(art).top() > art.bottom());
let art = egui::Rect::from_min_max(egui::pos2(100.0, 420.0), egui::pos2(1100.0, 780.0));
assert!(place(art).bottom() < art.top());
// Nowhere to go: beside the chip, as before.
let art = room.shrink(10.0);
assert_eq!(beside_art(art.center(), art, size, room), art.center() + egui::vec2(14.0, 14.0));
}
fn stops(app: &VectorcraftApp) -> Vec<GradientStop> {
match selected(app) {
Some(Target::Stop(stops, _)) => stops,
+1
View File
@@ -216,6 +216,7 @@ registry! {
FindFont: ["findFont"] => DialogSpec::window(crate::find_font::show, |app, _| crate::find_font::confirm(app)),
SwatchOptions: [swatch_options::KIND] => swatch_options::SPEC,
Confirm: [confirm::KIND] => confirm::SPEC,
Message: [confirm::MESSAGE] => confirm::MESSAGE_SPEC,
NewSwatch: [new_swatch::KIND] => new_swatch::SPEC,
NewColorGroup: [new_color_group::KIND] => new_color_group::SPEC,
GradientStop: ["gradientStop"] => gradient_stop::SPEC,
+9
View File
@@ -686,6 +686,7 @@
Divide Vertically Into Dividir verticalmente en
Do Not Move No mover
Do you want to save the changes you made to “{name}”? ¿Quieres guardar los cambios hechos en “{name}”?
Can't open “{name}”. No se puede abrir «{name}».
Document Documento
Document Color Mode Modo de color del documento
Document Info Información del documento
@@ -1497,6 +1498,8 @@
Monospaced Monoespaciada
More Más
More Pathfinder options Más opciones de Buscatrazos
More Align options Más opciones de alineación
More Paragraph options Más opciones de párrafo
More Settings Más ajustes
Move Mover
Move All Objects Mover todos los objetos
@@ -3352,6 +3355,7 @@ axis Both Ambos
@msg cannot distort a zero-size bounding box no se puede distorsionar un cuadro delimitador de tamaño cero
@msg cannot read PDF: {0} no se puede leer el PDF: {0}
@msg cannot split an open path at its end point no se puede dividir un trazado abierto en su punto final
@msg closing needs three anchors cerrar necesita tres puntos de ancla
@msg check an asset to export marca un recurso para exportar
@msg choice must be "merge" or "add", not `{choice}` choice debe ser "merge" o "add", no `{choice}`
@msg choose a direction to divide in elige una dirección en la que dividir
@@ -3779,3 +3783,8 @@ axis Both Ambos
Constrain Restringir
Free Transform Transformación libre
Perspective Distort Distorsión de perspectiva
@msg `id` is the step reference {r}, which only `run` and `command_batch` resolve `id` es la referencia a un paso {r}, que solo `run` y `command_batch` resuelven
@msg `ids` must be an array of object ids, not {v} `ids` debe ser una lista de identificadores de objeto, no {v}
@msg `{text}`: step {i}'s result has no such value (write $$ for a literal $) `{text}`: el resultado del paso {i} no tiene ese valor (escriba $$ para un $ literal)
@msg `{text}`: there is no step {i} before this one (steps count from 0; write $$ for a literal $) `{text}`: no hay ningún paso {i} antes de este (los pasos se cuentan desde 0; escriba $$ para un $ literal)
@msg object ids are non-negative integers, not {v} los identificadores de objeto son enteros no negativos, no {v}
Can't render this file because it contains an unexpected character in line 2 and column 73.
+9
View File
@@ -688,6 +688,7 @@
Divide Vertically Into Diviser verticalement en
Do Not Move Ne pas déplacer
Do you want to save the changes you made to “{name}”? Voulez-vous enregistrer les modifications apportées à « {name} » ?
Can't open “{name}”. Impossible d’ouvrir « {name} ».
Document Document
Document Color Mode Mode colorimétrique du document
Document Info Informations sur le document
@@ -1496,6 +1497,8 @@
Monospaced À chasse fixe
More Plus
More Pathfinder options Plus d’options Pathfinder
More Align options Plus d’options d’alignement
More Paragraph options Plus d’options de paragraphe
More Settings Plus de réglages
Move Déplacer
Move All Objects Déplacer tous les objets
@@ -3349,6 +3352,7 @@ axis Both Les deux
@msg cannot distort a zero-size bounding box impossible de déformer un cadre de sélection de taille nulle
@msg cannot read PDF: {0} impossible de lire le PDF : {0}
@msg cannot split an open path at its end point impossible de scinder un tracé ouvert à son extrémité
@msg closing needs three anchors la fermeture nécessite trois points d’ancrage
@msg check an asset to export cochez une ressource à exporter
@msg choice must be "merge" or "add", not `{choice}` choice doit valoir "merge" ou "add", pas `{choice}`
@msg choose a direction to divide in choisissez une direction de division
@@ -3790,3 +3794,8 @@ axis Both Les deux
Insert Inline Symbol Insérer un symbole dans le texte
ICF Top/Right ICF haut/droite
ICF Bottom/Left ICF bas/gauche
@msg `id` is the step reference {r}, which only `run` and `command_batch` resolve `id` est la référence d’étape {r}, que seuls `run` et `command_batch` résolvent
@msg `ids` must be an array of object ids, not {v} `ids` doit être une liste d’identifiants d’objet, pas {v}
@msg `{text}`: step {i}'s result has no such value (write $$ for a literal $) `{text}` : le résultat de l’étape {i} n’a pas cette valeur (écrivez $$ pour un $ littéral)
@msg `{text}`: there is no step {i} before this one (steps count from 0; write $$ for a literal $) `{text}` : il n’y a pas d’étape {i} avant celle-ci (les étapes sont comptées à partir de 0 ; écrivez $$ pour un $ littéral)
@msg object ids are non-negative integers, not {v} les identifiants d’objet sont des entiers positifs ou nuls, pas {v}
Can't render this file because it contains an unexpected character in line 2 and column 73.
+9
View File
@@ -686,6 +686,7 @@
Divide Vertically Into Dividi verticalmente in
Do Not Move Non spostare
Do you want to save the changes you made to “{name}”? Vuoi salvare le modifiche apportate a “{name}”?
Can't open “{name}”. Impossibile aprire «{name}».
Document Documento
Document Color Mode Metodo colore documento
Document Info Informazioni documento
@@ -1497,6 +1498,8 @@
Monospaced Monospaziato
More Altro
More Pathfinder options Altre opzioni di Elaborazione tracciati
More Align options Altre opzioni di allineamento
More Paragraph options Altre opzioni di paragrafo
More Settings Altre impostazioni
Move Sposta
Move All Objects Sposta tutti gli oggetti
@@ -3352,6 +3355,7 @@ axis Both Entrambi
@msg cannot distort a zero-size bounding box impossibile distorcere un riquadro di delimitazione di dimensione zero
@msg cannot read PDF: {0} impossibile leggere il PDF: {0}
@msg cannot split an open path at its end point impossibile dividere un tracciato aperto nel suo punto finale
@msg closing needs three anchors per chiudere servono tre punti di ancoraggio
@msg check an asset to export spunta una risorsa da esportare
@msg choice must be "merge" or "add", not `{choice}` choice deve essere "merge" o "add", non `{choice}`
@msg choose a direction to divide in scegli una direzione in cui dividere
@@ -3779,3 +3783,8 @@ axis Both Entrambi
Constrain Vincola
Free Transform Trasformazione libera
Perspective Distort Distorsione prospettica
@msg `id` is the step reference {r}, which only `run` and `command_batch` resolve `id` è il riferimento al passaggio {r}, che solo `run` e `command_batch` risolvono
@msg `ids` must be an array of object ids, not {v} `ids` deve essere un elenco di ID oggetto, non {v}
@msg `{text}`: step {i}'s result has no such value (write $$ for a literal $) `{text}`: il risultato del passaggio {i} non ha questo valore (scrivi $$ per un $ letterale)
@msg `{text}`: there is no step {i} before this one (steps count from 0; write $$ for a literal $) `{text}`: non c’è un passaggio {i} prima di questo (i passaggi si contano da 0; scrivi $$ per un $ letterale)
@msg object ids are non-negative integers, not {v} gli ID oggetto sono interi non negativi, non {v}
Can't render this file because it contains an unexpected character in line 2 and column 73.
+9
View File
@@ -1122,6 +1122,7 @@
Divide Slices スライスを分割
Divide Vertically Into 垂直方向に分割
Do you want to save the changes you made to “{name}”? 「{name}」への変更を保存しますか?
Can't open “{name}”. 「{name}」を開けません。
Document ドキュメント
Document Ink Options ドキュメントのインキオプション
Document JSON ドキュメント JSON
@@ -1639,6 +1640,8 @@
Monochrome images モノクロイメージ
More 多く
More Pathfinder options その他のパスファインダーオプション
More Align options その他の整列オプション
More Paragraph options その他の段落オプション
More Settings その他の設定
Move 移動
Move Anchors アンカーポイントを移動
@@ -3276,6 +3279,7 @@ theme Appearance 外観
@msg no saved selections 保存した選択範囲はありません
@msg no such artboard 指定されたアートボードが見つかりません
@msg cannot split an open path at its end point オープンパスは端点で分割できません
@msg closing needs three anchors 閉じるには 3 つのアンカーポイントが必要です
@msg empty brush stroke ブラシストロークが空です
@msg no such anchor 指定されたアンカーポイントが見つかりません
@msg no such segment 指定されたセグメントが見つかりません
@@ -3771,3 +3775,8 @@ theme Appearance 外観
@msg larger than 256 MB 256 MB を超えています
@msg the files come to more than 1 GB: add fewer at a time ファイルの合計が 1 GB を超えています: 一度に追加するファイルを減らしてください
@msg every numbered name for it is taken in the Fonts folder Fonts フォルダーでは、このファイルの番号付きの名前がすべて使われています
@msg `id` is the step reference {r}, which only `run` and `command_batch` resolve `id` はステップ参照 {r} です。ステップ参照を解決できるのは `run` と `command_batch` だけです
@msg `ids` must be an array of object ids, not {v} `ids` はオブジェクト ID の配列にしてください ({v} は使えません)
@msg `{text}`: step {i}'s result has no such value (write $$ for a literal $) `{text}`: ステップ {i} の結果にその値はありません ($ そのものを書くには $$ と入力してください)
@msg `{text}`: there is no step {i} before this one (steps count from 0; write $$ for a literal $) `{text}`: この前にステップ {i} はありません (ステップは 0 から数えます。$ そのものを書くには $$ と入力してください)
@msg object ids are non-negative integers, not {v} オブジェクト ID は 0 以上の整数です ({v} は使えません)
Can't render this file because it contains an unexpected character in line 2 and column 73.
+3
View File
@@ -636,6 +636,7 @@
Divide Slices… Dividir Fatias…
Divide Vertically Into Dividir Verticalmente Em
Do you want to save the changes you made to “{name}”? Deseja salvar as alterações feitas em “{name}”?
Can't open “{name}”. Não é possível abrir “{name}”.
Document Documento
Document Color Mode Modo de Cor do Documento
Document Info Informações do Documento
@@ -1313,6 +1314,8 @@
Monochrome images Imagens monocromáticas
More Mais
More Pathfinder options Mais opções de Localizador de Caminhos
More Align options Mais opções de alinhamento
More Paragraph options Mais opções de parágrafo
More Settings Mais Configurações
Move Mover
Move Anchors Mover Âncoras
Can't render this file because it contains an unexpected character in line 6 and column 47.
+9
View File
@@ -684,6 +684,7 @@
Divide Vertically Into Разделить по вертикали на
Do Not Move Не перемещать
Do you want to save the changes you made to “{name}”? Сохранить изменения, внесённые в «{name}»?
Can't open “{name}”. Не удаётся открыть «{name}».
Document Документ
Document Color Mode Цветовой режим документа
Document Info Сведения о документе
@@ -1495,6 +1496,8 @@
Monospaced Моноширинный
More Больше
More Pathfinder options Дополнительные параметры обработки контуров
More Align options Дополнительные параметры выравнивания
More Paragraph options Дополнительные параметры абзаца
More Settings Дополнительные настройки
Move Переместить
Move All Objects Переместить все объекты
@@ -3348,6 +3351,7 @@ axis Both Оба
@msg cannot distort a zero-size bounding box нельзя исказить ограничительную рамку нулевого размера
@msg cannot read PDF: {0} не удалось прочитать PDF: {0}
@msg cannot split an open path at its end point нельзя разделить открытый контур в его конечной точке
@msg closing needs three anchors для замыкания нужны три опорные точки
@msg check an asset to export отметьте ресурс для экспорта
@msg choice must be "merge" or "add", not `{choice}` choice должно быть "merge" или "add", а не `{choice}`
@msg choose a direction to divide in выберите направление для разделения
@@ -3777,3 +3781,8 @@ axis Both Оба
Perspective Distort Искажение перспективы
Artboard Монтажная область
Exit Выйти
@msg `id` is the step reference {r}, which only `run` and `command_batch` resolve `id` — это ссылка на шаг {r}, которую разрешают только `run` и `command_batch`
@msg `ids` must be an array of object ids, not {v} `ids` должен быть массивом идентификаторов объектов, а не {v}
@msg `{text}`: step {i}'s result has no such value (write $$ for a literal $) `{text}`: в результате шага {i} нет такого значения (чтобы написать сам $, введите $$)
@msg `{text}`: there is no step {i} before this one (steps count from 0; write $$ for a literal $) `{text}`: перед этим шагом нет шага {i} (шаги считаются с 0; чтобы написать сам $, введите $$)
@msg object ids are non-negative integers, not {v} идентификаторы объектов — неотрицательные целые числа, а не {v}
Can't render this file because it contains an unexpected character in line 2 and column 73.
+9
View File
@@ -680,6 +680,7 @@
Divide Vertically Into Розділити по вертикалі на
Do Not Move Не переміщати
Do you want to save the changes you made to “{name}”? Зберегти зміни, внесені до «{name}»?
Can't open “{name}”. Не вдається відкрити «{name}».
Document Документ
Document Color Mode Колірний режим документа
Document Info Відомості про документ
@@ -1491,6 +1492,8 @@
Monospaced Моноширинний
More Більше
More Pathfinder options Додаткові параметри обробки контурів
More Align options Додаткові параметри вирівнювання
More Paragraph options Додаткові параметри абзацу
More Settings Додаткові налаштування
Move Перемістити
Move All Objects Перемістити всі об’єкти
@@ -3335,6 +3338,7 @@ axis Both Обидві
@msg cannot distort a zero-size bounding box не можна спотворити обмежувальну рамку нульового розміру
@msg cannot read PDF: {0} не вдалося прочитати PDF: {0}
@msg cannot split an open path at its end point не можна розділити відкритий контур у його кінцевій точці
@msg closing needs three anchors для замикання потрібні три опорні точки
@msg check an asset to export позначте ресурс для експорту
@msg choice must be "merge" or "add", not `{choice}` choice має бути "merge" або "add", а не `{choice}`
@msg choose a direction to divide in виберіть напрямок для поділу
@@ -3762,3 +3766,8 @@ axis Both Обидві
Perspective Distort Спотворення перспективи
Artboard Монтажна область
Exit Вийти
@msg `id` is the step reference {r}, which only `run` and `command_batch` resolve `id` — це посилання на крок {r}, яке розв’язують лише `run` і `command_batch`
@msg `ids` must be an array of object ids, not {v} `ids` має бути масивом ідентифікаторів об’єктів, а не {v}
@msg `{text}`: step {i}'s result has no such value (write $$ for a literal $) `{text}`: у результаті кроку {i} немає такого значення (щоб написати сам $, введіть $$)
@msg `{text}`: there is no step {i} before this one (steps count from 0; write $$ for a literal $) `{text}`: перед цим кроком немає кроку {i} (кроки рахуються з 0; щоб написати сам $, введіть $$)
@msg object ids are non-negative integers, not {v} ідентифікатори об’єктів — невід’ємні цілі числа, а не {v}
Can't render this file because it contains an unexpected character in line 632 and column 40.
+3
View File
@@ -666,6 +666,7 @@
Divide Vertically Into 垂直分割为
Do Not Move 不移动
Do you want to save the changes you made to “{name}”? 要存储对“{name}”所做的更改吗?
Can't open “{name}”. 无法打开“{name}”。
Document 文档
Document Color Mode 文档颜色模式
Document Info 文档信息
@@ -1455,6 +1456,8 @@
Monochrome images 单色图像
More 较多
More Pathfinder options 更多路径查找器选项
More Align options 更多对齐选项
More Paragraph options 更多段落选项
More Settings 更多设置
Move 移动
Move All Objects 移动所有对象
Can't render this file because it contains an unexpected character in line 2 and column 73.
+3
View File
@@ -684,6 +684,7 @@
Divide Vertically Into 垂直分割為
Do Not Move 不移動
Do you want to save the changes you made to “{name}”? 要儲存對「{name}」所做的變更嗎?
Can't open “{name}”. 無法開啟「{name}」。
Document 文件
Document Color Mode 文件色彩模式
Document Info 文件資訊
@@ -1497,6 +1498,8 @@
Monospaced 等寬
More 更多
More Pathfinder options 更多路徑管理員選項
More Align options 更多對齊選項
More Paragraph options 更多段落選項
More Settings 更多設定
Move 移動
Move All Objects 移動所有物件
Can't render this file because it contains an unexpected character in line 6 and column 47.
+36 -1
View File
@@ -97,7 +97,24 @@ pub fn open_dialog(app: &mut VectorcraftApp) -> Result<(), String> {
return Ok(());
}
let path = pick_open(app, &FilePick { filters: fileio::open_filters().collect(), ..Default::default() })?;
open_path(app, &path).map(|_| ())
open_reporting(app, &path).map(|_| ())
}
/// A file the user asked to open (File › Open, Open Recent, the Home screen, a drop, the Finder)
/// couldn't be: say so in a dialog as well as the status bar, which is easily missed (#861).
pub fn report_open_error(app: &mut VectorcraftApp, name: &str, e: &str) {
app.status(format!("Couldn't open {name}: {e}"));
let message = crate::i18n::fmt(tl!("Can't open “{name}”."), &[("name", name)]);
dialogs::confirm::tell(app, &message, &crate::i18n::message(crate::i18n::current(), e));
}
/// [`open_path`] for a file the user asked for, a failure reported ([`report_open_error`]).
pub fn open_reporting(app: &mut VectorcraftApp, path: &str) -> Result<Value, String> {
let r = open_path(app, path);
if let Err(e) = &r {
report_open_error(app, &fileio::file_name(path), e);
}
r
}
fn read(app: &VectorcraftApp, path: &str) -> Result<Vec<u8>, String> {
@@ -699,6 +716,24 @@ mod tests {
(VectorcraftApp::new(Session::new(), services), written)
}
/// #861: a file the user opens that can't be opened is reported in a dialog they close, not
/// only in the status bar; a file an agent opens by path only answers with the error.
#[test]
fn a_file_the_user_cant_open_is_reported_in_a_dialog() {
let (mut app, _) = app();
app.services.read = Some(Box::new(|_: &str| Err("no such file".into())));
assert!(open_reporting(&mut app, "/docs/gone.ai").is_err());
let d = app.ui.dialog.take().expect("a dialog says so");
assert_eq!(
(d.kind.as_str(), d.str("message"), d.str("detail")),
(dialogs::confirm::MESSAGE, "Can't open “gone.ai”.".to_string(), "no such file".to_string())
);
assert!(app.ui.status.contains("gone.ai"));
// An agent's `file.open {path}` gets the error back and no dialog.
assert!(app.run("file.open", json!({"path": "/docs/gone.ai"})).is_err());
assert!(app.ui.dialog.is_none());
}
fn bytes_of(app: &mut VectorcraftApp, cmd: &str, p: Value) -> Vec<u8> {
let v = app.session.execute(cmd, &p).unwrap();
vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap()
+3 -1
View File
@@ -293,6 +293,8 @@ pub struct CacheKey {
pub pixel: Option<[i64; 4]>,
/// Images sampled smoothly ([`vectorcraft_render::RenderOptions::smooth_images`]).
pub smooth_images: bool,
/// Isolation mode's group or layer ([`vectorcraft_render::RenderOptions::isolated`]).
pub isolated: Option<u64>,
}
#[derive(Clone, Copy, Debug, Default)]
@@ -704,7 +706,7 @@ impl VectorcraftApp {
self.services.inbox.as_ref().map(|q| std::mem::take(&mut *q.lock().unwrap_or_else(|e| e.into_inner()))).unwrap_or_default();
for (name, bytes) in arrived {
if let Err(e) = io::open_bytes(self, &name, &bytes, None) {
self.status(format!("Couldn't open {name}: {e}"));
io::report_open_error(self, &name, &e);
}
}
place::drain(self);
+2 -2
View File
@@ -377,7 +377,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"window.swatchLibrary.other",
"Other Library…",
"",
"{path?} (default: pick a file) load a .vcswatches, .gpl or .ase library, or another document's swatches (engine: swatch.library.load), and open it in the library panel",
"{path?} (default: pick a file) load a .vcswatches, .gpl, .ase or .acb (color book) library, or another document's swatches (engine: swatch.library.load), and open it in the library panel",
),
(
"ui.saveSwatchLibrary",
@@ -884,7 +884,7 @@ pub fn run_ui_command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option<R
"file.revert" if p.get("confirmed").and_then(Value::as_bool) != Some(true) => io::ask_revert(app),
"file.reveal" => io::reveal(app),
id if id.starts_with("file.openRecent") => match recent_slot(app, id).cloned() {
Some(path) => io::open_path(app, &path),
Some(path) => io::open_reporting(app, &path),
None => Err("no such recent file".into()),
},
"type.findFont" => {
+51
View File
@@ -52,6 +52,26 @@ pub const DISTRIBUTE: [(&str, &str, &str, &str); 6] = [
("dc-dist-right", "Horizontal Distribute Right", "horizontal", "right"),
];
/// The six align buttons of the Control bar and the Properties panel, `size` points square.
/// They align to what the Align panel's Align To says (the key object while there is one), as
/// its own buttons do (#789).
pub fn align_buttons(app: &mut VectorcraftApp, ui: &mut Ui, size: f32) {
let n = selection_len(app);
let to = align_to(app, ui.ctx());
for (icon, tip, axis, v) in [
("align-start-vertical", "Horizontal Align Left", "horizontal", "left"),
("align-center-vertical", "Horizontal Align Center", "horizontal", "center"),
("align-end-vertical", "Horizontal Align Right", "horizontal", "right"),
("align-start-horizontal", "Vertical Align Top", "vertical", "top"),
("align-center-horizontal", "Vertical Align Center", "vertical", "center"),
("align-end-horizontal", "Vertical Align Bottom", "vertical", "bottom"),
] {
if widgets::icon_button(ui, icon, tl!(tip), false, size).clicked() {
app.run("object.align", align_params(json!({axis: v}), to, n)).ok();
}
}
}
/// Whether the selection has a key object.
fn has_key(app: &VectorcraftApp) -> bool {
app.session.active().is_some_and(|st| st.selection.key.is_some())
@@ -183,4 +203,35 @@ mod tests {
app.run("select.key", json!({})).unwrap();
assert_eq!(align_to(&app, &ctx), AlignTo::Selection, "no key: the choice again");
}
/// #789: the Control bar's and the Properties panel's align buttons follow Align To too.
#[test]
fn the_other_align_buttons_align_to_the_align_to_choice() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
let a = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap()["id"].clone();
let b = app.run("shape.rectangle", json!({"x": 80, "y": 50, "width": 30, "height": 30})).unwrap()["id"].clone();
app.run("select.set", json!({"ids": [a, b]})).unwrap();
let ctx = egui::Context::default();
set_pstate(&ctx, "align-to", AlignTo::Artboard);
// One frame finds the first button (Horizontal Align Right is third); the next clicks it.
let at = std::cell::Cell::new(egui::Pos2::ZERO);
let frame = |app: &mut VectorcraftApp, events: Vec<egui::Event>| {
let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| {
ui.horizontal(|ui| {
at.set(ui.cursor().min);
align_buttons(app, ui, 24.0);
});
});
out.textures_delta.clear();
};
frame(&mut app, vec![]);
let right = at.get() + egui::vec2(2.0 * (24.0 + ctx.global_style().spacing.item_spacing.x) + 12.0, 12.0);
let press = |pressed| egui::Event::PointerButton { pos: right, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
frame(&mut app, vec![egui::Event::PointerMoved(right), press(true)]);
frame(&mut app, vec![press(false)]);
let st = app.session.active().unwrap();
let x1 = |id: &serde_json::Value| st.doc.bounds_of(&[vectorcraft_doc::NodeId(id.as_u64().unwrap())], false).unwrap().x1;
assert_eq!((x1(&a), x1(&b)), (200.0, 200.0), "both to the artboard's right edge");
}
}
+38 -2
View File
@@ -496,7 +496,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
(Some(c), _) => components(mode, &c),
(None, _) => vec![0.0; mode.labels().len()],
};
super::recent_colors_row(app, ui);
let recent = super::recent_colors_row(app, ui);
widgets::divider(ui);
// An edit of the active colour with its displayed components (`new`), or a colour clicked with
// Alt held for the inactive proxy (`behind`).
@@ -585,6 +585,10 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
*new = Some((c, phase, components(mode, &c)));
}
};
// A recent colour, like the chips, recolours the selected gradient stop (or point).
if let Some(c) = recent {
pick(c, Live::Released, &mut new);
}
// None / Black / White chips and the hex field.
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 0.0;
@@ -691,12 +695,23 @@ mod tests {
/// Run the panel for one frame with `events` and `modifiers`; returns the spectrum's rect (when
/// the options are shown) and the panel's height.
fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec<egui::Event>, modifiers: egui::Modifiers) -> (Option<Rect>, f32) {
frame_with(app, ctx, events, modifiers, "color-spectrum")
}
/// [`frame`] returning the rect of the panel's widget `id` instead of the spectrum's.
fn frame_with(
app: &mut VectorcraftApp,
ctx: &egui::Context,
events: Vec<egui::Event>,
modifiers: egui::Modifiers,
id: impl std::hash::Hash + std::fmt::Debug,
) -> (Option<Rect>, f32) {
let mut out = (None, 0.0);
let events = std::iter::once(egui::Event::ModifiersChanged(modifiers)).chain(events).collect();
let input = egui::RawInput { events, ..Default::default() };
let mut full = ctx.run_ui(input, |ui| {
show(app, ui);
out = (ctx.read_response(ui.id().with("color-spectrum")).map(|r| r.rect), ui.min_rect().height());
out = (ctx.read_response(ui.id().with(&id)).map(|r| r.rect), ui.min_rect().height());
});
full.textures_delta.clear();
out
@@ -712,6 +727,27 @@ mod tests {
frame(app, ctx, vec![], egui::Modifiers::NONE);
}
#[test]
fn a_recent_colour_recolours_the_selected_gradient_stop() {
// #835: it replaced the whole gradient with the colour.
let mut app = app();
app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap();
let stops = json!([{"offset": 0, "color": "#ffffff"}, {"offset": 1, "color": "#000000"}]);
app.run("paint.setFill", json!({"gradient": {"stops": stops, "start": [10, 35], "end": [60, 35]}})).unwrap();
app.select_tool("gradient");
app.run("gradient.selectStop", json!({"index": 1})).unwrap();
let red = app.session.recent_colors.iter().position(|c| c.to_hex() == "#ff0000").expect("red is a recent colour");
let ctx = egui::Context::default();
let none = egui::Modifiers::NONE;
let chip = frame_with(&mut app, &ctx, vec![], none, ("recent", red)).0.expect("the chip is drawn").center();
let button = |pressed| egui::Event::PointerButton { pos: chip, button: egui::PointerButton::Primary, pressed, modifiers: none };
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(chip), button(true)], none);
frame(&mut app, &ctx, vec![button(false)], none);
let Paint::Gradient(g) = crate::panels::current_paints(&app).0 else { panic!("still a gradient") };
let hex: Vec<String> = g.gradient.stops.iter().map(|s| s.color.to_hex()).collect();
assert_eq!(hex, ["#ffffff", "#ff0000"]);
}
fn paints_hex(app: &VectorcraftApp) -> (String, String) {
let (f, s) = crate::panels::current_paints(app);
(f.color().map(|c| c.to_hex()).unwrap_or_default(), s.color().map(|c| c.to_hex()).unwrap_or_default())
+3 -5
View File
@@ -412,8 +412,8 @@ pub(crate) fn label_or_name(s: &str, built_in: bool) -> &str {
}
/// "Recent Colors" header + a row of chips (the Session's recent colours, which every paint
/// command feeds); clicking one applies it to the active proxy (Alt: the inactive one).
pub(crate) fn recent_colors_row(app: &mut VectorcraftApp, ui: &mut Ui) {
/// command feeds); returns the one clicked, for the caller to apply.
pub(crate) fn recent_colors_row(app: &VectorcraftApp, ui: &mut Ui) -> Option<Color> {
let t = Tokens::get(ui.ctx());
crate::widgets::subheader(ui, "Recent Colors");
let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::hover());
@@ -430,9 +430,7 @@ pub(crate) fn recent_colors_row(app: &mut VectorcraftApp, ui: &mut Ui) {
chosen = Some(*c);
}
}
if let Some(c) = chosen {
apply_click(app, ui, json!({"color": color_json(&c)}));
}
chosen
}
/// A colour as command JSON, keeping its model.
+20 -9
View File
@@ -60,6 +60,24 @@ fn shown_alignment(justify: Justify, rtl: bool) -> Justify {
}
}
/// The seven alignment buttons, `size` points square, the one of `para`'s alignment on (the
/// Paragraph panel's and the Properties panel's).
pub fn alignment_buttons(app: &mut VectorcraftApp, ui: &mut Ui, para: &ParaStyle, size: f32) {
let shown = shown_alignment(para.justify, resolved_rtl(app, para));
for (j, icon, tip, id) in ALIGNMENTS {
if widgets::icon_button(ui, icon, tip, shown == j, size).clicked() {
para_cmd(app, "text.setStyle", json!({"justify": id}));
}
}
}
/// The Hyphenate checkbox of `para`'s paragraphs.
pub fn hyphenate_check(app: &mut VectorcraftApp, ui: &mut Ui, para: &ParaStyle) {
if widgets::check(ui, tl!("Hyphenate"), para.hyphenate, true) {
format(app, json!({"hyphenate": !para.hyphenate}));
}
}
pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
let t = Tokens::get(ui.ctx());
let Some((_, para)) = text_style(app) else {
@@ -67,14 +85,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
return;
};
let rtl = resolved_rtl(app, &para);
let shown = shown_alignment(para.justify, rtl);
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 3.0;
for (j, icon, tip, id) in ALIGNMENTS {
if widgets::icon_button(ui, icon, tip, shown == j, 28.0).clicked() {
para_cmd(app, "text.setStyle", json!({"justify": id}));
}
}
alignment_buttons(app, ui, &para, 28.0);
// Paragraph direction, with the Middle Eastern (Indic) options.
if app.session.prefs.show_indic_options {
ui.add_space(6.0);
@@ -127,9 +140,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
if pstate::<bool>(ui.ctx(), "pa-hide-options") {
return;
}
if widgets::check(ui, tl!("Hyphenate"), para.hyphenate, true) {
format(app, json!({"hyphenate": !para.hyphenate}));
}
hyphenate_check(app, ui, &para);
// Japanese composition: how punctuation is spaced (JLREQ 3.1), with the East Asian options.
if app.session.prefs.show_east_asian_options {
ui.horizontal(|ui| {
+28 -21
View File
@@ -57,21 +57,10 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
divider(ui);
section_header(ui, tl!("Align"));
ui.horizontal(|ui| {
for (icon, tip, p) in [
("align-start-vertical", tl!("Horizontal Align Left"), json!({"horizontal": "left"})),
("align-center-vertical", tl!("Horizontal Align Center"), json!({"horizontal": "center"})),
("align-end-vertical", tl!("Horizontal Align Right"), json!({"horizontal": "right"})),
("align-start-horizontal", tl!("Vertical Align Top"), json!({"vertical": "top"})),
("align-center-horizontal", tl!("Vertical Align Center"), json!({"vertical": "center"})),
("align-end-horizontal", tl!("Vertical Align Bottom"), json!({"vertical": "bottom"})),
] {
if widgets::icon_button(ui, icon, tip, false, 26.0).clicked() {
let mut p = p;
if n_sel == 1 {
p["to"] = json!("artboard");
}
app.run("object.align", p).ok();
}
super::align::align_buttons(app, ui, 26.0);
// The rest (Distribute Objects, Distribute Spacing, Align To) is the Align panel's.
if widgets::icon_button(ui, "ellipsis", tl!("More Align options"), false, 26.0).clicked() {
app.ui.open_panel = Some("align".into());
}
});
if n_sel > 1 {
@@ -534,13 +523,17 @@ pub fn type_sections(app: &mut VectorcraftApp, ui: &mut Ui) {
super::character::font_pickers(app, ui, &s, ("font", "font-style"), (w - 4.0, w - 4.0));
super::character::metrics_grid(app, ui, "props-char", &s, w, false);
section_header(ui, tl!("Paragraph"));
ui.horizontal(|ui| {
for (icon, j) in [("align-start-vertical", "left"), ("align-center-vertical", "center"), ("align-end-vertical", "right")] {
if widgets::icon_button(ui, icon, j, false, 24.0).clicked() {
app.run("text.setStyle", json!({"justify": j})).ok();
// As in the Paragraph panel: the seven alignments and Hyphenate (#775); the rest is there.
if let Some((_, para)) = super::character::text_style(app) {
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 3.0;
super::paragraph::alignment_buttons(app, ui, &para, 24.0);
if widgets::icon_button(ui, "ellipsis", tl!("More Paragraph options"), false, 24.0).clicked() {
app.ui.open_panel = Some("paragraph".into());
}
}
});
});
super::paragraph::hyphenate_check(app, ui, &para);
}
}
#[cfg(test)]
@@ -603,6 +596,20 @@ mod tests {
}
/// #530: Edit Artboards shows the active artboard, with New Artboard, Delete Artboard and Exit.
/// #775: type's Paragraph section has Hyphenate, and its checkbox turns it on.
#[test]
fn type_paragraph_section_hyphenates() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 200, "height": 100})).unwrap();
app.run("text.create", json!({"x": 10, "y": 50, "text": "Paragraph"})).unwrap();
let ctx = egui::Context::default();
frame(&mut app, &ctx, vec![]);
let texts = frame(&mut app, &ctx, vec![]);
click(&mut app, &ctx, &texts, "Hyphenate");
let hyphenate = |app: &VectorcraftApp| crate::panels::character::text_style(app).unwrap().1.hyphenate;
assert!(hyphenate(&app));
}
#[test]
fn edit_artboards_adds_artboards_and_exits() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
+4 -1
View File
@@ -642,7 +642,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, salt: &'static str) {
}
});
ui.add_space(4.0);
super::recent_colors_row(app, ui);
// A recent colour paints the active proxy (Alt: the inactive one), as a swatch does.
if let Some(c) = super::recent_colors_row(app, ui) {
super::apply_click(app, ui, json!({"color": super::color_json(&c)}));
}
widgets::divider(ui);
widgets::subheader(ui, tl!("Swatch Tiles"));
let query = if pstate(ui.ctx(), "swatch-show-find") { widgets::search_field(ui, find_id(), tl!("Find")) } else { String::new() };
+4 -2
View File
@@ -357,8 +357,10 @@ pub fn drop_files(app: &mut VectorcraftApp, mut files: Vec<(DropTarget, DropFile
}),
},
};
if let Err(e) = r {
app.status(if target == DropTarget::Open { format!("Couldn't open {name}: {e}") } else { format!("Couldn't place {name}: {e}") });
match r {
Err(e) if target == DropTarget::Open => io::report_open_error(app, &name, &e),
Err(e) => app.status(format!("Couldn't place {name}: {e}")),
Ok(()) => {}
}
}
}
+2 -1
View File
@@ -45,7 +45,8 @@ How the web shell (`apps/vectorcraft-web/src/web.rs`) differs from desktop:
The canvas is rasterized on the CPU (`vectorcraft-render`, vello_cpu); the GPU (wgpu, through eframe) only composites the canvas texture and draws the UI, so any GPU that can show the window will do. The desktop app picks the window's adapter itself (`apps/vectorcraft/src/gpu.rs`, eframe's `native_adapter_selector`) and logs every adapter it found and the one it uses.
- **Order:** adapters that report they can't present to the window are never tried; then the one `WGPU_ADAPTER_NAME` names; hardware before software (llvmpipe, WARP); the native backends (Vulkan, Metal, DX12) before OpenGL; with Automatic, the GPU that drives a display, and among those the one that drives the primary display; then the power preference; then, on Windows, where each GPU is listed under both, a GPU's DX12 adapter before its Vulkan one (Intel's Vulkan driver made the whole window flicker black, #545), keeping the system's order among equals. `WGPU_BACKEND=vulkan` still picks Vulkan.
- **Order:** adapters that report they can't present to the window are never tried; then the one `WGPU_ADAPTER_NAME` names; hardware before software (llvmpipe, WARP); the native backends (Vulkan, Metal, DX12) before OpenGL; with Automatic, the GPU that drives a display, and among those the one that drives the primary display; then the power preference; then a GPU's DX12 adapter before its Vulkan one (Intel's Vulkan driver made the whole window flicker black, #545), keeping the system's order among equals.
- **Windows backends:** Direct3D 12, falling back to OpenGL. Vulkan isn't started at all unless `WGPU_BACKEND` asks for it (`WGPU_BACKEND=vulkan`): creating a Vulkan instance loads every installed Vulkan driver into the process, and a faulty one (Intel's `igvk64.dll`, #806) crashed the app before its window appeared.
- **The GPU that drives the display.** A GPU without a monitor is the wrong one even when it says it can show the window: on a desktop with a Ryzen's integrated GPU (no monitor) and an NVIDIA card driving both monitors, power saving picked the integrated GPU, Windows had to present every frame across adapters, and the integrated GPU's driver reset under that: the graphics device was lost, or the desktop's compositor went down and every monitor stayed black for minutes (pdfcraft#378). So Automatic asks the system which GPU drives which display and puts that GPU first; the power preference only orders the rest, and decides alone where the system can't say.
- **Windows:** `EnumDisplayDevices` (the display devices attached to the desktop, and the primary one), through the `winsafe` crate; the PCI ids in each device id are matched against wgpu's adapters. The registry doesn't tell a user which adapter drives a display, and WMI reports a resolution for a GPU without a monitor, so neither is used.
- **Linux:** the connected connectors in `/sys/class/drm` and their cards' PCI ids; a built-in panel (`eDP`, `LVDS`, `DSI`) counts as the primary display.
+36 -4
View File
@@ -167,7 +167,7 @@ The older names below remain listed because existing workflows use them.
|---|---|
| `command_list` | Optional `filter`, `enabled_only`; returns the command array |
| `command_run` | `id`, optional `params`; runs the command through the existing backend |
| `command_batch` | `steps: [{id, params?}]`, optional `stop_on_error` (default true); returns `completed`, `failed`, `results: [{ok, result\|error}]`. Each edit has its own undo step; failures set `isError` |
| `command_batch` | `steps: [{id, params?}]`, optional `stop_on_error` (default true); returns `completed`, `failed`, `results: [{ok, result\|error}]`. Each edit has its own undo step; failures set `isError`. A param string `"$N.path"` or `"$last.path"` takes a value from an earlier step's result (see `run` below) |
| `doc_inspect` | Optional `depth`, `childLimit`; same summary as `inspect_document` |
| `render_preview` | Optional `max_side` (1–4096, default 1024); inline PNG of the first artboard without editing it. Artboards too large to render within the allocation bound return a tool error |
| `ui_inspect`, `ui_screenshot` | Connected desktop state/window capture; tool errors in headless mode |
@@ -573,6 +573,16 @@ applies to the `--cmd` just before it. `run` also accepts the host commands `fil
`file.exportForScreens` and `tool.select`. `run --in`, `convert` and `info` read every format `document.open` reads
(`vectorcraft-cli --help` lists them).
A step can use an earlier step's result, in `run` as in the `command_batch` tool. A parameter string that is exactly
`$N` or `$N.path` takes that value from the result of step `N` (counting from 0, in the order they ran; `run --in`'s
open isn't a step), and `$last…` from the step before. A path goes into objects by key and arrays by index:
`"$1.id"`, `"$2.ids.0"`, `"$last.ids[0]"`. A string starting with `$$` stands for one `$` (`"$$1.99"` is `$1.99`). A
reference that names no value fails the step, so a command never runs with one left in it:
```sh
vectorcraft-cli run --cmd file.new --params '{"width":600,"height":200}' --cmd text.create --params '{"x":10,"y":60,"text":"plain and bold words","size":30}' --cmd text.setRangeStyle --params '{"id":"$1.id","start":10,"end":14,"style":"Bold"}'
```
## Transparency and opacity masks
Transparency and opacity-mask commands take `ids` (or `id`), so they need no selection. Opacity is a percentage
@@ -819,9 +829,11 @@ groups; `.gpl` is 8-bit RGB; a swatch exchange `.ase` file keeps solid colors in
as the color it shows and leaves gradients out; CSS writes custom properties); without `path`
it returns `{data}`, or `{dataBase64}` for `.ase`, and `user: true` saves into the user library
folder of the desktop app (listed as category `user`, User Defined). `swatch.library.load {path? | data? |
dataBase64?, name?}` loads a `.vcswatches`, `.gpl` or swatch exchange (`.ase`) file, or another document's swatches,
as a library to add from. From an `.ase` file it reads RGB, CMYK, Lab and Gray colors as global, spot or process
swatches and keeps their color groups. A file in the user library folder, or a file with the
dataBase64?, name?}` loads a `.vcswatches`, `.gpl`, swatch exchange (`.ase`) or color book (`.acb`) file, or another
document's swatches, as a library to add from. From an `.ase` file it reads RGB, CMYK, Lab and Gray colors as global,
spot or process swatches and keeps their color groups. A color book (such as a Pantone book you own) gives its RGB,
CMYK or Lab colors named with the book's prefix and suffix ("PANTONE 185 C"), as spot colors unless the book marks
them as process colors; `.acb` files are read, never written. A file in the user library folder, or a file with the
same extension and bytes as one there, loads as that User Defined library (category `user`).
`swatch.library.copyToUser {library}` copies a loaded library into the user library folder of the desktop
app (a library file as it is; a document's swatches or a library loaded from `data` or `dataBase64`
@@ -1218,6 +1230,26 @@ the path it had begun while that stays selected. Its reply's `tool` is the tool
{"name":"run_command","arguments":{"command":"path.moveAnchors","params":{"dx":0,"dy":40}}}
```
## Editing a path with the Curvature tool
The Curvature tool edits any selected path, whatever drew it, keeping its shape except where edited (#798). Each edit
is one undo step and leaves the anchor it edited direct-selected (the tool's current point):
`path.curvatureEdit {id, subpath?, op, …}` answers `{anchor}`. `op: "move"` with `anchor`, `x`, `y` moves a point and
re-curves only its two segments: a smooth point turns along the line through its neighbours, and the neighbours'
handles keep their directions (their lengths scale with the chord), so the segments beyond don't change.
`op: "insert"` with `segment`, `t` adds a smooth point there without changing the shape (with `x`, `y` it is then
moved there: the tool's click-and-drag on a segment). `op: "extend"` with `x`, `y` goes on from the `end` (default)
or the `start` of an open subpath, and `op: "close"` closes it from that end; `from` says how the old end bends into
the new segment: `"keep"` (default) keeps its curve, `"smooth"` curves it through its neighbours (a point the tool
placed), `"corner"` leaves it without handles. Alt-click or double-click toggles a point with `path.convertAnchor`, and
Backspace/Delete removes the current point with `path.removeAnchor`.
```json
{"name":"run_command","arguments":{"command":"path.curvatureEdit","params":{"id":12,"op":"move","anchor":2,"x":260,"y":140}}}
{"name":"run_command","arguments":{"command":"path.curvatureEdit","params":{"id":12,"op":"extend","end":"end","x":550,"y":120}}}
{"name":"run_command","arguments":{"command":"path.curvatureEdit","params":{"id":12,"op":"extend","x":650,"y":60,"from":"smooth"}}}
```
## Registration and trim marks
Every document has the built-in `[Registration]` swatch (listed after None by `swatch.list`): a colour that prints on