Compare commits

...
Author SHA1 Message Date
bflatastic 9dfa7bf931 Docs: ROADMAP 2026-10-12 adds #1474–#1525 (late merges of the day) 2026-10-13 06:56:37 +07:00
BFlat 02a68e1738 Merge pull request #1540 from storytold/fix/1479-too-large-note
Part of #1479: an image too large to decode is reported on Open, Place and in the Links panel
2026-10-13 06:43:25 +07:00
BFlat b631002c58 Merge pull request #1538 from storytold/fix/1499-paste-pdf-eps
Fix #1499: PDF and EPS another app copied paste as editable vector art
2026-10-13 06:36:24 +07:00
BFlat 041776fc9f Merge pull request #1537 from storytold/fix/compound-group-paint
Make Compound Path: the compound path of a group takes its backmost path's paint
2026-10-13 06:36:02 +07:00
BFlat 78155ed5b8 Merge pull request #1498 from lewandowskit/i18n-polish
i18n: add Polish (pl) interface language
2026-10-13 06:34:52 +07:00
BFlat 51c18f603a Merge pull request #1492 from switch87/fix/1484-compact-anchor-heavy-saves
Native save: documents whose JSON is large are written compact
2026-10-13 06:34:35 +07:00
bflatastic 66add30d65 Part of #1479: an image too large to decode is reported on Open, Place and in the Links panel
An image whose decode needs more than the 2 GiB allowance (512 MB on the web) is not drawn.
A raster export says so since #1517; on screen it was still blank with no word. Open and
Place now carry a warning for it, and the Links panel's row a note (links.list: note).
2026-10-13 06:34:12 +07:00
bflatastic b3f6edddfe Fix #1499: PDF and EPS another app copied paste as editable vector art
Paste read PDF only from the Windows clipboard and EPS nowhere, so on macOS a copied
equation or drawing pasted nothing new (the last thing copied in the app came back).
- macOS: the pasteboard's PDF, EPS and SVG are read, ahead of text and bitmaps.
- Windows: EPS is read beside PDF.
- Everywhere: an .eps file copied in a file manager pastes.
- clipboard.importEps loads an EPS into the clipboard as document.open reads one.
2026-10-13 06:34:12 +07:00
bflatastic a046fd30fe Make Compound Path: the compound path of a group takes its backmost path's paint
A group has no paint of its own, so a compound path made of one (outlined type) had none
and drew nothing until a fill was set. The paint now comes from the backmost path, or
from the compound path that painted it.
2026-10-13 06:34:12 +07:00
bflatastic 1e5f430ac5 Polish: the strings added since the catalog was written 2026-10-13 06:34:12 +07:00
Gert Pellin f3040e3762 Contributors: add my real name 2026-10-13 06:34:12 +07:00
Tomasz LewandowskiandClaude Opus 5.5 db54eefeae i18n: add Polish (pl) interface language
Complete Polish catalog (4,492 rows): every menu string, tl! literal,
plural and status/error message, enforced by the existing completeness
tests (complete_menus, KEEPS_MENU_NAMES, COMPLETE_MESSAGES).

- pl.tsv: clean-room translation from the English meaning, following
  common Polish desktop-software conventions (obszar kompozycji for
  artboard, obszar roboczy for workspace, obrys, wypełnienie, próbki…)
- plural_polish: one / few (2–4, not 12–14) / many (0, 5–21, 25…)
- every pl-* locale (pl-PL, pl_PL.UTF-8) resolves to it
- tests: Polish plural forms, vocabulary, nested message translation;
  Polish letters in the bundled-font coverage test
- docs: README, development.md, localization-parity.md

Drafted with AI assistance; native review welcome.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DukHNvUY45rjRnvtz91x33
2026-10-13 06:34:12 +07:00
Gert Pellin 37954523ae Native save: documents whose JSON is large are written compact
SaveOptions::for_doc chose pretty-printed JSON by the object count in
the layers alone. A document with few layer objects but many anchors,
or with its art in symbols, patterns or graph designs, was therefore
written pretty, about ten times the compact size: every anchor's "p",
"in" and "out" spread over several indented lines.

A document is now pretty only when it has at most PRETTY_MAX_OBJECTS
objects and its compact JSON is at most PRETTY_MAX_BYTES (1 MiB). The
size is measured by serializing into a writer that stops at the limit,
so a large document costs at most 1 MiB of extra serializing. Small
documents stay readable and diffable.

Fixes #1484
2026-10-13 06:34:12 +07:00
BFlat c391e1dbf2 Merge pull request #1535 from storytold/u/trace-shared
Image Trace: abutting regions share one curve along their edge (no gaps, no overlaps)
2026-10-13 06:27:57 +07:00
bflatastic 20ec49b2e7 Image Trace: abutting regions share one curve along their edge
Each region's outline was fitted on its own, so the edge between two regions was fitted twice, a little
differently, and left hairline gaps and overlaps.

- An outline is cut at its junctions: the pixel corners where three or more regions meet, where two parts of a
  region touch by a corner only, and where an edge reaches the image's border (each side of the image is a
  neighbour of its own, so the image's corners stay exact). A junction lies where the edges around it say, the
  same for every region around it.
- Each piece between two junctions is the whole edge between two regions. Both get exactly the same points for
  it (shifts are rounded to 1/1024 px so that the two sides agree to the last bit; whether a piece is hard is
  decided by the piece alone) and it is fitted the same way from either side (from its end further left), so it
  is one and the same curve in both paths. A loop without junctions is fitted clockwise from its leftmost point:
  a shape's outline and the hole it leaves in the shape around it are one curve too.
- Stacked layers (Overlapping) share no edges and are cut at the image's border only.

On each preset's own inputs, all sizes and variants (docs/image-trace-quality.md), before -> after:
- Default: gaps 22.2 -> 0.8 px, overlaps 22.4 -> 0.5 px
- 3 Colors: gaps 48.6 -> 0.0, overlaps 29.4 -> 0.0; outlines 0.087 -> 0.104 px off on average
- 6 Colors: gaps 39.0 -> 0.2, overlaps 35.7 -> 0.3; 0.137 -> 0.140 px off, largest 1.09 -> 1.34
- 16 Colors: gaps 34.5 -> 0.2, overlaps 26.4 -> 0.2; 0.133 -> 0.141 px off, largest 1.09 -> 1.31
2026-10-13 06:00:40 +07:00
BFlat 8715130c8b Merge pull request #1522 from anders94/readme-fix
README.md: add clone instructions to quick start
2026-10-13 05:57:22 +07:00
BFlat 6689be0351 Merge pull request #1526 from AyberkA0/feat/3d-inflate-twist-taper-cap
3D and Materials: Inflate takes Twist, Taper and Cap
2026-10-13 05:56:34 +07:00
BFlat c2c8a07b75 Merge pull request #1525 from AyberkA0/fix/3d-twisted-walls
3D and Materials: twisted Extrude & Bevel walls keep their faces
2026-10-13 05:56:18 +07:00
BFlat b83eafd794 Merge pull request #1524 from AyberkA0/fix/3d-twist-range
3D and Materials: Extrude & Bevel's Twist runs 0° to 360°, as documented
2026-10-13 05:56:03 +07:00
BFlat e93fc20294 Merge pull request #1523 from dotCooCoo/feat/mac-menu-sync-skips-drag-steps
macOS: the app no longer reads the menus at every step of a move, scale or shape drag
2026-10-13 05:55:48 +07:00
BFlat 9e2a7c41a0 Merge pull request #1519 from dotCooCoo/feat/many-path-edits-one-pass
Part of #1429: path, Pathfinder and live-object commands add and remove many objects in one pass
2026-10-13 05:55:31 +07:00
BFlat a4ba47a439 Merge pull request #1515 from dotCooCoo/feat/many-row-edits-one-pass
Part of #1429: Layers panel and artboard commands on many rows take time linear in the document
2026-10-13 05:55:21 +07:00
BFlat 93e8c00607 Merge pull request #1517 from fastmikey99/fix/decode-print-size-rasters
Decode print-size rasters in Crop Image trim and the renderer; say when an export is missing an image
2026-10-13 05:55:05 +07:00
Anders Brownworth 1e0063258a README.md: add clone instructions to quick start 2026-10-13 05:22:01 +07:00
Ayberk A. 15cef94ba6 3D and Materials: Inflate takes Twist, Taper and Cap
The public 3D and Materials panel options list Depth, Twist, Taper and Cap
for every 3D type; Inflate had only Depth.

- Twist (0° to 360°) and Taper (1–100 %) turn and scale the back about the
  shape's centre, as Extrude & Bevel's do: a puffed back is turned and
  lowered in proportion, and the sides follow in slices.
- Cap: Solid closes the back; Hollow leaves it off, so the inflated front is
  a shell open behind. The documentation doesn't say what Cap means for
  Inflate; this reading is stated in docs/three-d.md.
- The dialog's Object tab shows them in the documented order (Depth, Twist,
  Taper, Cap), then Volume and Both sides.

At 0 % volume a twisted, tapered Inflate has the extrusion's outline from
every side (tested).

A twisted, tapered, hollow Inflate draws on the canvas exactly as it
exports, and expands to faces with their own ids (tested). ROADMAP and the
parity pages list the new options; the 3D score stays at ~25 %.
2026-10-13 05:22:00 +07:00
Ayberk A. 431dc43e43 3D and Materials: twisted Extrude & Bevel walls keep their faces
A twist bends the strip between two slices into a saddle; its normal came
from one corner's triangle, which leaned so far back that from about 60° of
twist every wall was taken for facing away and dropped, leaving the front
cap alone. Each strip now takes the whole quad's average normal (Newell's),
as Inflate's facets do. A test checks the faces kept against each strip's
average normal oriented away from the axis, for twists up to 300° and four
views.
2026-10-13 05:21:41 +07:00
Ayberk A. e750891912 3D and Materials: Extrude & Bevel's Twist runs 0° to 360°, as documented
The public 3D and Materials panel options give Twist as up to 360°; it took
-360° to 360°. Values beyond either end now hold at that end (the effect is
a day old, so only fresh files carry a negative twist).
2026-10-13 05:21:32 +07:00
dotCooCoo fb2089aaf5 macOS: the app no longer reads the menus at every step of a move, scale or shape drag
On macOS, native_menu::sync reads every row of the menus (each
command's enabled and checked state, and each label) whenever
state_hash changes, and the macOS backend updates the AppKit items
whose label, enabled or checked state changed. The hash included the
active document's revision, and Session::preview makes a new revision
at each step of a drag, so the app read every row again at each step
of a move, scale or shape drag. In a release build on an M2 Max, that
took about 1.5 ms a step with one object selected, and 13.8 ms a step
with 5,001 objects selected.

While an interaction is open, state_hash leaves the revision out.
Move, scale and shape drags, dialog previews and the font menu's
preview are interactions. The menus are read when an interaction
begins and again on the frame it ends: when a drag's button is
released, when Escape cancels a drag, when a move is dragged onto a
panel, when a dialog's preview is applied or canceled, when the font
menu's preview ends, or when a control request such as
ui.dialog.cancel ends it. They are still read on a click or a key
press during an interaction.

docs/development.md says when the menus are updated during an
interaction.
2026-10-13 05:21:32 +07:00
dotCooCoo 88bd4812e0 Part of #1429: path, Pathfinder and live-object commands add and remove many objects in one pass
Offset Path, Outline Stroke, the Pathfinder panel, Clean Up, Make
Blend, Rasterize and the other commands that #1429's table marks 3,
except Split Into Grid, added, removed or replaced their objects one at
a time, and so did Remove Anchor Points, Redefine Symbol and the
removal of Shaper groups whose source art is gone. Each insertion or
removal moved the later objects of the layer or group. The lookups by
id that followed walked the tree, and every fourth walk rebuilt the
lookup cache. On 25,000 rectangles a release build of vectorcraft-cli
took 29.1 s for Offset Path.

These commands now make their edits with Document::wrap,
Document::insert_beside and Document::remove_many, in one pass over the
children of each layer or group, and Outline Stroke and Expand write
each new object into the place of the object it replaces. A list that
holds an object twice, or an object and another inside it, and that was
edited without an error before, is still edited one object at a time.
The documents, selections and undo steps are the same. On the same
rectangles Offset Path now takes 1.3 s.

Docs: docs/target-app-parity.md.
2026-10-13 05:21:31 +07:00
dotCooCoo 6f9e2d5c16 Part of #1429: Layers panel and artboard commands on many rows take time linear in the document
These commands removed, moved or copied one row or object at a time:
the Layers panel's Delete Selection, Duplicate Selection, Collect in
New Layer, row drags, Merge Selected, Flatten Artwork and Release to
Layers, and Cut Artboard, Duplicate Artboard and the Artboard tool's
Alt-drags that copy art. Each edit moved the later rows of the same
layer or group to other indices. The next lookup by id then walked the
tree, and after every fourth such walk Document::index_path rebuilt
the whole lookup cache. Release to Layers also walked the document
twice for each new layer to name and color it. With 25,000 rectangles
in one layer, a release build of vectorcraft-cli took 11.9 s for
Duplicate Selection and 17.7 s for Release to Layers.

The commands now remove, move and copy the rows in one pass over each
layer or group, with Document::remove_many and Document::wrap, and
with copy_above, the copy pass of duplicate_in, which Duplicate
Selection and the artboard copies now share. Release to Layers names
its new layers from one walk of the document. Merge Selected checks
the target layer's objects against a set of the listed rows, and
Delete Selection checks the top-level layers against such a set. In a
document whose ids are unique, the rows keep their order, new rows and
layers take the same ids, names and colors, and the selection, the
undo step and the journal are the same. A release build with this
change takes 98 ms for Duplicate Selection and 26 ms for Release to
Layers.

Docs: docs/target-app-parity.md.
2026-10-13 05:21:04 +07:00
fastmikey99andClaude Opus 5.5 d084af162f Render: decode print-size rasters, and say when an image is missing from an export
The renderer decoded images with the decoder's default 512 MB allocation
limit, so a 300 ppi roll (6614 x 59055 px, 1.56 GB as RGBA) that opens and
exports to PDF fine drew nothing in a raster export - a fully transparent PNG,
exit code 0, no warning. It now decodes with the allowance opening has (2 GB,
512 MB on the web), shrinks an image past a pixmap's 65535 px side to fit
instead of dropping it, and counts any image it still can't decode: a raster
export that drew fewer images than it should says so in its warnings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 05:20:57 +07:00
fastmikey99andClaude Opus 5.5 e01b9a20d9 Crop Image trim: decode print-size rasters, and leave CMYK images alone
Trim decoded the image with the decoder's default 512 MB allocation limit, so
a 300 ppi roll (6614 x 59055 px, 1.56 GB as RGBA) that opens fine failed with
"the image's pixels can't be read". It now decodes with the allowance opening
already has (MAX_RASTER_ALLOC: 2 GB, 512 MB on the web). A CMYK image, kept as
its ink amounts, has no alpha: trim leaves it alone (trimmed: false) instead
of failing to decode it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 05:20:48 +07:00
BFlat bd9b8a2db3 Merge pull request #1511 from Atalantis/fr-complete-catalog
i18n: complete the French (fr) UI catalog (423 entries)
2026-10-13 05:10:38 +07:00
BFlat c67c25128c Merge pull request #1509 from marcoarnulfo/fix/direct-select-active-anchor-precedence
Direct Selection: a selected path's anchor is picked before one of an object above it
2026-10-13 05:10:23 +07:00
BFlat b9e5536794 Merge pull request #1507 from duydev/feat/vietnamese-localization
G16: Vietnamese interface (vi)
2026-10-13 05:10:08 +07:00
BFlat 15e1f6327f Merge pull request #1502 from dotCooCoo/feat/perf-windows-load-memory
CLI: perf on Windows reports the cores busy and its working set, and the help lists --deep
2026-10-13 05:09:52 +07:00
bflatastic 57a4d9c6e1 French: the shortcut warning starts with a word, as in the other catalogs (the UI fonts have no warning sign) 2026-10-13 05:03:42 +07:00
Florent Siegenthaler e87abf02a8 i18n: align French terms with the names vector illustrators know (188 entries)
Rewords French entries to the feature names French-speaking users of vector illustration software know, as the catalog header asks: Repères commentés, Sélection directe progressive, Trait for Line Segment, Déformation for Shear, Associer for Group, Annuler for Release in the Make/Release submenus, Étape de dégradé, Redéfinir les couleurs de l'illustration, the graph and symbolism tool names. 27 terms are attested in Adobe's public French help pages; the others come from the reviewer's knowledge of the French interface. The eight strings pinned by french_reads_as_french and the MENU_KEEP_AS_IS strings are untouched. Keys with two meanings (Trim, Crop, Merge, Outline, Gradient) are left unchanged: they need @id entries.
2026-10-13 05:03:42 +07:00
Marco Arnulfo e4c2b3db94 Direct Selection: a selected path's anchor is picked before one of an object above it (fixes #1508) 2026-10-13 05:03:41 +07:00
bflatastic 2ec817e76a Vietnamese: the 3D dialog's and 3D effects' rows the other complete catalogs have 2026-10-13 05:03:41 +07:00
Florent Siegenthaler 9e39a6d124 i18n: complete the French (fr) UI catalog (423 entries)
Adds the 423 keys that other catalogs translate and fr.tsv lacked. The 19 MENU_KEEP_AS_IS strings stay out of the catalog, as the menu tests require. Entries follow the existing catalog's wording and typography (no-break space before : ; %, typographic apostrophe); placeholders, edge spaces, trailing ellipses and plural forms are preserved.
2026-10-13 05:03:41 +07:00
Trần Nhật Duy ec8dc0c2da i18n: add complete Vietnamese localization 2026-10-13 05:02:43 +07:00
dotCooCoo 22e06db73d CLI: perf on Windows reports the cores busy and its working set, and the help lists --deep
On Windows, perf printed "load average ?": load_average runs sysctl
or reads /proc/loadavg, and Windows has neither. The warning for a
busy machine could not print, so a run over budget on a busy machine
failed, where macOS and Linux warn and exit 0. perf --deep printed no
memory rows, because rss_mb runs ps. --help did not list --deep.

On Windows, perf now reads GetSystemTimes twice, one second apart,
and its first line gives the cores busy on average over that second
where macOS and Linux give the load average. It warns above three
quarters of the cores, as on macOS and Linux: with all 32 logical
processors of a test machine kept busy, the line read "cores busy
32.0" and a run with three budgets over exited 0. The --deep memory
rows give the working set (GetProcessMemoryInfo). Both calls use
winsafe 0.0.29, which Cargo.lock already lists for the desktop app;
the CLI depends on it on Windows with the kernel and psapi features.
The help lists --deep and says that a run over budget on a busy
machine exits 0. perf's report on macOS and Linux does not change.
2026-10-13 05:02:25 +07:00
BFlat aebeb66268 Merge pull request #1520 from storytold/u/trace-docs
Image Trace: progress docs for the palette and photo changes
2026-10-13 04:59:45 +07:00
bflatastic cf137c8c90 Docs: Image Trace's colour and photo presets, measured (ROADMAP log, parity evidence) 2026-10-13 04:42:29 +07:00
BFlat e131dfbb1c Merge pull request #1516 from storytold/u/trace-photo
Image Trace: photos trace into smooth tones (smoothing first, stacked layers by lightness)
2026-10-13 04:42:08 +07:00
bflatastic 77f81c8944 Image Trace: photos are smoothed within their tones first, and stacked layers go by lightness
A photo's noise is as large as the step from one palette colour to the next, so noise decided pixel by pixel
which of two neighbouring colours a pixel got: tens of thousands of specks, or (since the palette change)
neighbouring tones merged into one.

- A continuous-tone image (eight colours leave much of it unsaid; flat art, however noisy or unevenly lit, is
  not one) is smoothed before it is quantised: three rounds of a small bilateral filter, which averages noise
  away within a tone and keeps the edges between tones where and as sharp as they were.
- With Method: Overlapping, layers are stacked by lightness, from the largest colour's end of the scale,
  instead of by area. Each layer reaches under those above it, so where two colours meet every layer between
  them in the stack ends on that same edge and shows through its anti-aliasing: by area that was an unrelated
  colour's hairline around every region; by lightness it is a neighbouring tone.
- Ignore White with Overlapping: no layer reaches under the white that is left out.

On each preset's own inputs, all sizes and variants (docs/image-trace-quality.md), before -> after:
- High Fidelity Photo: colour error 2.37 -> 1.75 (2.30 at the baseline), edge error 2.59 -> 1.98, 639 -> 121
  paths (3,653 at the baseline), 25,604 -> 9,818 anchors, specks 152 -> 10; a 16 megapixel photo-like image is
  traced in 3.5 s (31,131 paths) where it was refused
- Low Fidelity Photo: colour error 2.67 -> 2.45, 55 -> 37 paths
- Shades of Gray: 73 -> 17 paths, colour error 9.33 -> 9.26
- The other presets' numbers are unchanged
2026-10-13 04:28:02 +07:00
BFlat 7fadeb4ed2 Merge pull request #1485 from webdevtodayjason/graph-csv-precision
Graph Data: the CSV keeps each value exactly, not rounded to two decimals
2026-10-13 04:06:03 +07:00
BFlat 396d7d2b76 Merge pull request #1487 from itrycodinganditsbad/fix-1458
Tabs panel: drag a tab stop from where the press landed
2026-10-13 04:05:48 +07:00
BFlat e30b1492a1 Merge pull request #1506 from storytold/fix/1483-slider-rails
Fix #1483: sliders in dialogs show their rail
2026-10-13 04:05:31 +07:00
BFlat e6ae1d0df3 Merge pull request #1505 from storytold/fix/1486-template-outline
Fix #1486: a template layer stays in Preview in Outline view
2026-10-13 04:05:18 +07:00
webdevtodayjason 43e1a7380c Graph Data: the CSV keeps each value exactly, not rounded to two decimals 2026-10-13 04:00:18 +07:00
Fabio LussiandClaude Opus 5.5 7ab9a46bf8 Tabs panel: drag a tab stop from where the press landed
egui reports drag_started only once the pointer is past its drag
threshold, farther from the press than the ruler's 5 px hit tolerance,
so hit-testing the current pointer usually missed the stop. Hit-test the
press origin instead, falling back to the pointer position.

Fixes #1458

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 04:00:17 +07:00
bflatastic dd1c26b627 Part of #1483: sliders in dialogs show their rail
The theme's widget fill matches the dialog background, so the sliders of
Save for Web, the raster export options, Preferences and the opacity
popup showed only their handle. They share one slider widget now, with a
visible rail filled up to the handle.
2026-10-13 04:00:17 +07:00
bflatastic a787fb487c Fix #1486: a template layer stays in Preview in Outline view
In Outline view a template layer drew as outlines like any other, so a
picture placed to be traced turned into a box. It now keeps drawing in
Preview (dimmed as before) while the other layers are in outline.
2026-10-13 04:00:17 +07:00
BFlat ce0c86f91a Merge pull request #1504 from storytold/u/trace-palette
Image Trace: colour presets trace flat art with its own colours (no shattering, no slivers)
2026-10-13 03:55:45 +07:00
109 changed files with 12463 additions and 946 deletions

No files matched your search

Generated
+1
View File
@@ -4580,6 +4580,7 @@ dependencies = [
"vectorcraft-testkit",
"vectorcraft-text",
"windows",
"winsafe",
]
[[package]]
+4 -1
View File
@@ -148,6 +148,9 @@ exposes to agents, and exported by VectorCraft's own renderer. The source files
## Quick start
```sh
git clone https://github.com/storytold/vectorcraft
cd vectorcraft
cargo run --release -p vectorcraft # desktop app
cargo run --release -p vectorcraft -- examples/dusk-poster.vectorcraft
cargo run --release -p vectorcraft -- --control 7979 # + JSON control channel
@@ -217,7 +220,7 @@ doesn't write Affinity files. Current `.af` validation includes 33 pinned files,
and every-board SVG/PDF/PSD export, with fixes for Affinity 3 artboards, source-backed JPEGs and text runs.
[Scope and limits](crates/affinity/README.md); [source audit and remaining gaps](docs/affinity-validation.md).
The interface
speaks English, German, Japanese, Korean, Traditional and Simplified Chinese, Spanish, French, Hungarian, Italian, Russian and Ukrainian (and Czech and Brazilian Portuguese in the menus);
speaks English, German, Japanese, Korean, Vietnamese, Traditional and Simplified Chinese, Spanish, French, Hungarian, Italian, Polish, Russian and Ukrainian (and Czech and Brazilian Portuguese in the menus);
[localization-parity.md](docs/localization-parity.md) has the details.
The scores are self-assessed from our code against Illustrator's public documentation;
[target-app-parity.md](docs/target-app-parity.md#how-this-was-measured-2026-10-10) explains how far to trust them.
+7 -5
View File
@@ -6,7 +6,7 @@
**Stage: alpha** · next: beta, ~13 points (ready for real work ~62% → ~75%, and reliable `.ai` exchange) and ~170–270 h away
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (community PRs and fixes of 2026-10-12: Split Into Grid options, #1462; Transform Objects and Reflect across an angle, #1448 and #1460; Pathfinder on a group, #1450; unknown parameter keys refused, #1442; grayscale TIFFs with alpha, #1466 in part; many-object edits, #1429 in part; headline numbers unchanged; Image Trace places edges to a fraction of a pixel, measured in `docs/image-trace-quality.md`, headline numbers unchanged; Transform dialogs preview and the transform tools act on direct-selected anchors, #1412 and #1408; `.ai` compound path paint, #1410, overprint, #1388, and text-only PDF parts, #1387; community PRs: strokes wider than their shape, corner drags without the bounding box, pasted pictures, compound paths in `document.inspect`, MCP guide; headline numbers unchanged; community PRs: `.ai` editing-data follow-ups (gradient stops, type of objects with an appearance, short area-type frames), PDF bleed with editing data, dialog keyboard focus, art flush with an artboard, font rescan, symbol instance redraw, `--control` port check; headline numbers unchanged; Rectangular Grid and Polar Grid tool options, #1377 in part; `.ai` files with placed (linked) pictures open from their editing data, #1264; community PRs: `.ai` and PDF bleed and editing-data import, gradient shapes imported as paths, ruler origin, Align To, Live Corners corner selection; headline numbers unchanged; G2: Film Grain added; Photoshop effects 29/57; 28 filters remain; community PRs: graph designs, Graph Data worksheet and Graph Type options; Align both centres; Pen endpoint fixes; earlier: Effect › Brush Strokes landed: Photoshop-style filters 28 of 57, raster effects 40% → 48%; `.ai` gradients, meshes and artboard names from the editing data; headline numbers unchanged; `.ai` art styles and clipping fills from the editing data; headline numbers unchanged; `editingData: "always"`; headline numbers unchanged) · **Target:** Adobe Illustrator 2026 (30.x)
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (community PRs and fixes of late 2026-10-12: type that does not fit its frame is reported, #1471; Tabs panel drags, #1458; template layers in Outline view, #1486; dialog slider rails, #1483; Direct Selection anchor precedence, #1508; print-size images, #1517; French catalog complete again, #1511; headline numbers unchanged; Image Trace colour and photo presets, measured in `docs/image-trace-quality.md`, headline numbers unchanged; community PRs and fixes of 2026-10-12: Split Into Grid options, #1462; Transform Objects and Reflect across an angle, #1448 and #1460; Pathfinder on a group, #1450; unknown parameter keys refused, #1442; grayscale TIFFs with alpha, #1466 in part; many-object edits, #1429 in part; headline numbers unchanged; Image Trace places edges to a fraction of a pixel, measured in `docs/image-trace-quality.md`, headline numbers unchanged; Transform dialogs preview and the transform tools act on direct-selected anchors, #1412 and #1408; `.ai` compound path paint, #1410, overprint, #1388, and text-only PDF parts, #1387; community PRs: strokes wider than their shape, corner drags without the bounding box, pasted pictures, compound paths in `document.inspect`, MCP guide; headline numbers unchanged; community PRs: `.ai` editing-data follow-ups (gradient stops, type of objects with an appearance, short area-type frames), PDF bleed with editing data, dialog keyboard focus, art flush with an artboard, font rescan, symbol instance redraw, `--control` port check; headline numbers unchanged; Rectangular Grid and Polar Grid tool options, #1377 in part; `.ai` files with placed (linked) pictures open from their editing data, #1264; community PRs: `.ai` and PDF bleed and editing-data import, gradient shapes imported as paths, ruler origin, Align To, Live Corners corner selection; headline numbers unchanged; G2: Film Grain added; Photoshop effects 29/57; 28 filters remain; community PRs: graph designs, Graph Data worksheet and Graph Type options; Align both centres; Pen endpoint fixes; earlier: Effect › Brush Strokes landed: Photoshop-style filters 28 of 57, raster effects 40% → 48%; `.ai` gradients, meshes and artboard names from the editing data; headline numbers unchanged; `.ai` art styles and clipping fills from the editing data; headline numbers unchanged; `editingData: "always"`; headline numbers unchanged) · **Target:** Adobe Illustrator 2026 (30.x)
VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adobe Illustrator workflow. It runs
on macOS, Windows, Linux, FreeBSD and the web (WASM), and agents can drive all of it over MCP, the CLI and a JSON
@@ -35,7 +35,7 @@ blocking it ([Alpha gate](docs/roadmap.md#alpha-gate)).
| Audience | Ready % | Opus 5.5 agent hours to ~95% (one agent) | With 4–6 agents | Work that dominates |
|---|---:|---:|---:|---|
| **Full Illustrator** (ready for real work; decides the stage) | **~62%** (57–67%) | **~340–560 h** | ~95–160 h | the mainstream work below, plus 3D (50–85 h), raster effects (23–39 h), advanced type (20–28 h), generative AI (30–60 h), localization (60–100 h) and ecosystem |
| **Full Illustrator** (ready for real work; decides the stage) | **~62%** (57–67%) | **~340–560 h** | ~95–160 h | the mainstream work below, plus 3D (50–85 h), raster effects (23–39 h), advanced type (20–28 h), generative AI (30–60 h), localization (55–90 h) and ecosystem |
| **Mainstream illustrator** | **~65%** (60–70%) | **~230–380 h** | ~65–110 h | the interaction-fidelity pass (60–90 h), hardening and QA (30–50 h), stability (20–35 h), performance budgets (15–25 h), `.ai` exchange (10–20 h), the remaining depth of the everyday areas |
| **Essentials user** | **~75%** (70–80%) | **~60–105 h** | ~25–45 h | launch and stability on Windows (20–35 h), in-app help and onboarding (8–15 h), basic QA (10–15 h), Shape Builder regions (4–8 h), UI polish |
@@ -52,7 +52,7 @@ everything is measured from our code against Illustrator's public documentation.
| UI/UX fidelity | 55% | 70–110 | [ui-parity.md](docs/ui-parity.md) |
| File formats | 75% | 15–30 | [file-format-parity.md](docs/file-format-parity.md) |
| Hardware (GPU, pen, touch, displays) | 35% | 25–45 | [hardware-parity.md](docs/hardware-parity.md) |
| Localization (12 key languages) | 63% (measured) | 60–100 | [localization-parity.md](docs/localization-parity.md) |
| Localization (12 key languages) | 71% (measured) | 55–90 | [localization-parity.md](docs/localization-parity.md) |
| Performance | ~60% | 15–25 | [gaps.md › G15](docs/gaps.md#g15-performance-budgets-and-a-gpu-renderer) |
| Stability | ~60% | 30–50 | [gaps.md › G10](docs/gaps.md#g10-launch-and-stability-on-real-machines) |
| Platforms | 80% | 15–25 | [gaps.md › G8](docs/gaps.md#g8-hardening-at-scale) |
@@ -107,7 +107,7 @@ Weights, evidence and the missing items per area: [target-app-parity.md](docs/ta
| Japanese | `ja` | full | 100% |
| German | `de` | full | 98% |
| Korean | `ko` | full | 100% |
| Vietnamese | `vi` | none | 0% |
| Vietnamese | `vi` | full | 100% |
Also shipped: Traditional Chinese (partial, 80%), Hungarian, Italian, Russian and Ukrainian (full), Czech (catalog complete; render-site gaps reduced; native review pending).
No catalog has had a native speaker's review. Details: [localization-parity.md](docs/localization-parity.md).
@@ -127,7 +127,9 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
| Date | What landed |
|---|---|
| 2026-10-13 | Image Trace's colour presets trace flat art with its own colours however many are asked for (noise no longer shatters it: 16 Colors 70 → 4 paths on the harness's flat art; no slivers of in-between colour along anti-aliased edges), and the photo presets trace a photo into smooth tones without specks or hairlines (High Fidelity Photo 3,653 → 121 paths, colour error 2.30 → 1.75; 16 megapixels traced where 4 were refused) ([`docs/image-trace-quality.md`](docs/image-trace-quality.md)). |
| 2026-10-13 | Image Trace traces anti-aliased and blurred images to a fraction of a pixel in Black and White, Grayscale and Color, with corners put back, straight edges as lines and round outlines as circles; a harness measures every preset before and after ([`docs/image-trace-quality.md`](docs/image-trace-quality.md)): outlines 0.31 → 0.09 px off on average (Default), 0.27 → 0.06 (Black and White Logo). |
| 2026-10-13 | Effect › 3D and Materials: Inflate takes Twist, Taper and Cap (Hollow leaves the back open), as the 3D docs list for every type. |
| 2026-10-12 | Effect › 3D and Materials: Extrude & Bevel (depth, twist, taper, solid or hollow caps, five bevel shapes with repeat, spacing, inside and both sides), Inflate (volume, both sides) and Rotate, with Position presets and the rotation and light gizmos; live, exported as vector faces, expandable (#1407). |
| 2026-10-12 | `convert --editing-data` (`editingData: "always"`) opens a `.ai` from its editing data even where its page, which can be older, draws differently, with a note. |
| 2026-10-12 | `.ai` import reads an object's art style (a fill and a stroke, variable widths too, with an Outer Glow or Drop Shadow) as its own appearance, paints a clipping path's own fill under what it clips and keeps a group's transparency as its PDF part draws them. |
@@ -135,7 +137,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
| 2026-10-12 | The Rectangular Grid and Polar Grid tools take their options: a click opens the size, the divider counts with a skew slider each, Use Outside Rectangle As Frame (rectangular) or Create Compound Path From Ellipses (polar) and Fill Grid; the choices stay with the tool, so dragging draws with them, and scripts and agents pass them to `shape.rectangularGrid` and `shape.polarGrid` (#1377, in part). |
| 2026-10-12 | A `.ai` file with placed (linked) pictures opens from its editing data, with its guides, sublayers and hidden objects: each picture is a linked image in its place, showing the low-resolution preview the file keeps until its file is found or relinked (#1264). Scores unchanged. |
| 2026-10-12 | Desktop printing adopts the shared `craft-print` spooler with exact physical sheet sizes. Windows 7 retains its WMI/viewer transport and excludes the shared backend; compatibility CI checks the dependency tree and PE imports. Scores unchanged. |
| 2026-10-12 | Graphs: Object › Graph › Design… and Marker… (designs with a preview, New Design, Rename, Delete Design, Paste Design, Select Unused, and markers drawn with a design or None) (#1092); Graph Data opens as a worksheet with Import Data…, column width and decimals (#1138), and takes Transpose, Switch x/y, `|` line breaks in labels and the pie Legend, Position and Sort options (#1115); Graph Type adds Add Drop Shadow and Add Legend Across Top (#1119), widths past 100%, First Row and First Column in Front, and Draw Filled Lines (#1136); graphs keep their label formatting when drawn again (#1137). Align: a Horizontal & Vertical Align Center button (#1073); Align to Key Object makes the topmost selected object the key (#1221), and the palette's key entry reads Cancel Key Object (#1224). Pen: the nearest end wins over snapping, Alt on the last anchor edits it, and Enter, Escape or a tool switch finish a handle preview as one undo step (#821). Direct Selection: a click on an anchor of an already selected path selects that anchor alone (#1237). Make Compound Path keeps the backmost object's paint, and a selected member reads and changes the compound's fill rule (#1225). Shape Builder and Live Paint no longer turn a line's loose end past a crossing into a piece that runs out and back (#1230). Art moved or duplicated with an artboard follows Transform Pattern Tiles (#1219). A click with the Rectangular Grid tool opens its options dialog (#1169). Commands that change nothing (Lock, Hide, Transform Each, Rearrange Artboards and others) add no undo step (#1233). Saving with missing placed files keeps their relink data, and .ai export honours the chosen artboards (#718). SVG export keeps Unicode data-attribute names, and SVG Options refuses an invalid artboard range (#989). CMYK colours given in percent with a component under 1 keep their scale (#1249). Colour Image Trace keeps close dark tones apart (#1247). macOS: the Save sheet has a Format menu (#1235). The Hand and Zoom tools show drawn cursors on every platform (#1238). Czech: the remaining strings are translated, and Pathfinder's Add reads "Sjednotit" (#1226). MCP: a lost reply reports that the edit may have happened instead of replaying it (#1246); `select.key` checks its id and agents can read the key object (#1222). Tests: the command sweeps and import fuzz tests fail on a panic caught by the engine's guard (#1218), and the envelope export test ignores PDF dates and file IDs (#1220). Effect › Artistic › Film Grain (Grain, Highlight Area, Intensity; Photoshop-style filters 29/57) (#1282), and Craquelure, Mosaic Tiles and Stained Glass redraw 25–30% faster with identical pixels (#1265). Direct Selection: clicking a segment selects only that segment, and Delete removes just it (#1300); Shift-click deselects one anchor of a path selected whole (#1263). Pen + Alt converts anchors of paths inside a selected group or compound path (#1306). The Curvature tool shows circular point markers without direction handles (#1284). Snap to Point: pressing near an anchor drags by that anchor, with Smart Guides on or off (#1313). Transform Again repeats the options of the transform it repeats (#1303). Aligning anchors that are already aligned adds no undo step (#1276), and type commands that change nothing record none either (#1316). Simplify keeps the path selected with its new anchors, and its dialog previews and shows the anchor count (#1305). Adding a stroke colour to an unpainted zero-width stroke gives it a visible 1 pt width (#1256). The Eyedropper samples locked objects, template layers and art outside isolation mode (#1260), and shows a pipette cursor (#1288). Fonts named by their full name resolve to the right face (#1267), and Proportional Metrics brings the matching kerning (`apkn`, `vkrn`, `vapk`) (#1291). Artboards: Escape leaves Artboard editing (#1296), Document Setup's Edit Artboards switches to the Artboard tool (#1294), and the Artboard tool starts on the active artboard (#1309). New and imported documents use the Gridline every and Subdivisions preferences (#1314). Send to Current Layer refuses a hidden or locked current layer (#1301), and layer row commands check explicit ids (#1255). Links: Find in Folder… finds missing linked files in a folder and its subfolders and can copy them into the document's folder (#1287). Image Trace traces images over 64 megapixels scaled down instead of refusing them (#1315). DXF export marks closed curves as closed SPLINE entities (#1320). EPS import: closepath respects the path size limit (#1311). The interface is available in Hungarian (#1302), and more Czech labels are translated (#1259). Linux RPMs declare shared-library capabilities (#1290). CI pins every third-party action to a verified commit (#1321). Select menu commands skip hidden and locked art and stay inside the isolated group in isolation mode (#1325). Fill, stroke, gradient and Appearance panel commands that change nothing add no undLine truncated
| 2026-10-12 | Graphs: Object › Graph › Design… and Marker… (designs with a preview, New Design, Rename, Delete Design, Paste Design, Select Unused, and markers drawn with a design or None) (#1092); Graph Data opens as a worksheet with Import Data…, column width and decimals (#1138), and takes Transpose, Switch x/y, `|` line breaks in labels and the pie Legend, Position and Sort options (#1115); Graph Type adds Add Drop Shadow and Add Legend Across Top (#1119), widths past 100%, First Row and First Column in Front, and Draw Filled Lines (#1136); graphs keep their label formatting when drawn again (#1137). Align: a Horizontal & Vertical Align Center button (#1073); Align to Key Object makes the topmost selected object the key (#1221), and the palette's key entry reads Cancel Key Object (#1224). Pen: the nearest end wins over snapping, Alt on the last anchor edits it, and Enter, Escape or a tool switch finish a handle preview as one undo step (#821). Direct Selection: a click on an anchor of an already selected path selects that anchor alone (#1237). Make Compound Path keeps the backmost object's paint, and a selected member reads and changes the compound's fill rule (#1225). Shape Builder and Live Paint no longer turn a line's loose end past a crossing into a piece that runs out and back (#1230). Art moved or duplicated with an artboard follows Transform Pattern Tiles (#1219). A click with the Rectangular Grid tool opens its options dialog (#1169). Commands that change nothing (Lock, Hide, Transform Each, Rearrange Artboards and others) add no undo step (#1233). Saving with missing placed files keeps their relink data, and .ai export honours the chosen artboards (#718). SVG export keeps Unicode data-attribute names, and SVG Options refuses an invalid artboard range (#989). CMYK colours given in percent with a component under 1 keep their scale (#1249). Colour Image Trace keeps close dark tones apart (#1247). macOS: the Save sheet has a Format menu (#1235). The Hand and Zoom tools show drawn cursors on every platform (#1238). Czech: the remaining strings are translated, and Pathfinder's Add reads "Sjednotit" (#1226). MCP: a lost reply reports that the edit may have happened instead of replaying it (#1246); `select.key` checks its id and agents can read the key object (#1222). Tests: the command sweeps and import fuzz tests fail on a panic caught by the engine's guard (#1218), and the envelope export test ignores PDF dates and file IDs (#1220). Effect › Artistic › Film Grain (Grain, Highlight Area, Intensity; Photoshop-style filters 29/57) (#1282), and Craquelure, Mosaic Tiles and Stained Glass redraw 25–30% faster with identical pixels (#1265). Direct Selection: clicking a segment selects only that segment, and Delete removes just it (#1300); Shift-click deselects one anchor of a path selected whole (#1263). Pen + Alt converts anchors of paths inside a selected group or compound path (#1306). The Curvature tool shows circular point markers without direction handles (#1284). Snap to Point: pressing near an anchor drags by that anchor, with Smart Guides on or off (#1313). Transform Again repeats the options of the transform it repeats (#1303). Aligning anchors that are already aligned adds no undo step (#1276), and type commands that change nothing record none either (#1316). Simplify keeps the path selected with its new anchors, and its dialog previews and shows the anchor count (#1305). Adding a stroke colour to an unpainted zero-width stroke gives it a visible 1 pt width (#1256). The Eyedropper samples locked objects, template layers and art outside isolation mode (#1260), and shows a pipette cursor (#1288). Fonts named by their full name resolve to the right face (#1267), and Proportional Metrics brings the matching kerning (`apkn`, `vkrn`, `vapk`) (#1291). Artboards: Escape leaves Artboard editing (#1296), Document Setup's Edit Artboards switches to the Artboard tool (#1294), and the Artboard tool starts on the active artboard (#1309). New and imported documents use the Gridline every and Subdivisions preferences (#1314). Send to Current Layer refuses a hidden or locked current layer (#1301), and layer row commands check explicit ids (#1255). Links: Find in Folder… finds missing linked files in a folder and its subfolders and can copy them into the document's folder (#1287). Image Trace traces images over 64 megapixels scaled down instead of refusing them (#1315). DXF export marks closed curves as closed SPLINE entities (#1320). EPS import: closepath respects the path size limit (#1311). The interface is available in Hungarian (#1302), and more Czech labels are translated (#1259). Linux RPMs declare shared-library capabilities (#1290). CI pins every third-party action to a verified commit (#1321). Select menu commands skip hidden and locked art and stay inside the isolated group in isolation mode (#1325). Fill, stroke, gradient and Appearance panel commands that change nothing add no undLine truncated
| 2026-10-11 | Effect › Brush Strokes: Accented Edges, Angled Strokes, Crosshatch, Dark Strokes, Ink Outlines, Spatter, Sprayed Strokes, Sumi-e (G2). Command parameters from agents and files checked before anything changes (paint, place, cuts, dashes, crop, asset ids, anchors, paths, distort; #984–#999); command dialogs keep whole numbers whole, so Create Object Mosaic takes the tiles typed (#1000); stepper arrows take Shift (×10) and Ctrl/Cmd (÷10) like the arrow keys (#991). Exports and Rasterize supersample Art Optimized edges, so shapes meeting edge to edge leave no seam (#983). Character and paragraph styles take leading, kerning, mojikumi and the other attributes left out at their defaults (#1001). Drawing, typing and pasting with no layer shown and unlocked is refused instead of adding art to a hidden or locked layer (#1002). MCP `add_text` gives type on or in a path the colour asked for (#1003). MCP `screenshot` of a connected app renders the artboard asked for (#1004). `vectorcraft-cli run` ends quietly when its reader closes early (#1005). Select › All on Active Artboard selects on the artboard made active, not always the first (#1006). Reverse Gradient keeps off-centre midpoints, mirrored (#1007). A polar grid with no radial dividers draws none (#1008). Use Precise Cursors also covers the Pen's join pointer (#1009). SVGs with one absolute and one unitless root side import at their size, unstretched (#1010). DXF US survey inches, yards and miles open at their size and name (#1011). A file placed into a document with no other links follows its first change even while the app sits idle (#1031). PDF import keeps the style a font name says when the file doesn't embed the font (#1023). Shift selects ruler guides and art together, and Delete removes both (#1022). Open filled paths are hit by their fill on every side, the rotate cursor bows around the corner it is at, the flip icons match their flips, the Color Picker previews on the selection, and Properties › Transform reaches Scale Corners and Scale Strokes & Effects (#1036). Offset Path and the other booleans finish on outlines where the sweep used to loop until memory ran out (linesweeper 0.5, #1028). Floating panel groups stack into sets that move together, collapse to their tabs and dock as extra dock columns that scroll (#1020). Ruler guides live on layers: listed in the Layers panel, shown, hidden, locked, duplicated, merged and deleted with their layer, and moved between layers (#1021). A `.ai` whose editing data uses global process colours (`Xk`/`XK`) or pattern fills keeps its sublayers: the colours come in as global swatches at their tint, the patterns as pattern swatches (#1025). A `.ai` in PostScript form opens through its layers, read from the program itself, also when it names the prolog defining its operators without including it, as Rhino and other CAD apps write it (#1027). A fill or stroke chosen while the Type tool has characters selected colours just those characters (#1063). Scaled type shows its scaled font size, leading, baseline shift and horizontal scale in the Character panel, and a size typed there is the size you get (#1034). Character panel menu › Proportional Metrics sets Japanese and Chinese full-width glyphs on the font's proportional widths in horizontal type (#966). Align, Distribute, Move, Arrange, Lock, Hide, Ungroup and other Object commands that would change nothing no longer record an undo step or mark the document changed (#1060). Spot colours defined in Lab open with their Lab values from `.ai` and PDF files, instead of as wrong RGB colours or their CMYK equivalents (#1032). Build scripts leave a generated source they wouldn't change untouched, so the next build doesn't compile most of the workspace again where file times lose their sub-second part (#1051). A fill colour recolours the gradient mesh point last clicked with the Mesh tool or Direct Selection, and a Mesh tool click on a mesh's point selects that mesh (#1052). The All Tools drawer stays two tools wide instead of filling a wide window (#1054). Text Wrap's Make, Release and Options refuse a list of object ids with a malformed or unknown id instead of skipping it (#1055). A freeform gradient line with a malformed point index is refused instead of being shortened to the indices that are valid (#1056). The Corners dialog (`ui.corners`) refuses a malformed object id or a listed anchor that isn't a corner instead of editing the selection or the other corners (#1057). New View refuses a centre that isn't exactly [x, y] and a rotation that isn't a number, instead of trimming the one and saving the other as 0° (#1058). The command sweeps try junk scale, spacing and artboard values too, which they had skipped since before those bugs were fixed (#1059). EPS and PostScript `arc` and `arcn` with huge angles no longer hang the import, and an arc whose angles are whole turns apart is empty, as the PostScript reference defines it (#1062). Align and DisLine truncated
| 2026-10-10 | Initial live Revolve (Effect › 3D and Materials, #846, #605), in its own `three-d` crate. Progress docs re-measured and restructured to the craftrules standard (this page, `docs/target-app-parity.md`, `gaps.md`, `ui-parity.md`, the format, hardware, localization, effects and type checklists). Same day: v0.8.0; Effect › Distort, Pixelate and Texture filters (13); German interface; Variables (data merge); Graph Type value axes and tick marks; restart when the first frame never reaches the screen (#964) |
| 2026-10-09 | Radial Blur, Smart Blur, Unsharp Mask (gap 2 begins); 340 commits, the busiest day |
+6
View File
@@ -26,6 +26,12 @@ vectorcraft-text = { workspace = true }
serde_json = { workspace = true }
log = { workspace = true }
# `perf` on Windows (src/perf.rs) reads how busy the processors are (GetSystemTimes) and this
# process's working set (GetProcessMemoryInfo) through winsafe's safe wrappers over Win32 (MIT),
# which the desktop app's src/gpu.rs also uses.
[target.'cfg(windows)'.dependencies]
winsafe = { version = "0.0.29", default-features = false, features = ["kernel", "psapi"] }
# DirectWrite's system font collection (the desktop app's src/system_fonts.rs, shared): fonts that
# font services such as Adobe Fonts load in place (#579). MIT OR Apache-2.0.
[target.'cfg(all(windows, not(target_vendor = "win7")))'.dependencies]
+6 -4
View File
@@ -7,7 +7,7 @@
//! vectorcraft-cli convert IN OUT [--scale 2] [--artboard 0 | --range 1-3,5] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data]
//! vectorcraft-cli info FILE
//! vectorcraft-cli bench FILE [--size 2880x1800] [--iters 5]
//! vectorcraft-cli perf [--paths 50000]
//! vectorcraft-cli perf [--paths 50000] [--deep]
//! ```
// Denied, not forbidden: the font listers shared with the desktop app allow it for their
// DirectWrite (Windows) and CoreText (macOS) calls, and nothing else may.
@@ -104,9 +104,11 @@ USAGE:
Render FILE (any readable format) fitted to WxH (default 2880x1800) and print ms per frame
(warm), multithreaded and single-threaded.
vectorcraft-cli perf [--paths N]
Check the performance budgets (render, pan, hit test, save/load, SVG, Pathfinder) on a
synthetic N-path document (default 50000). Exits non-zero if a budget is exceeded.
vectorcraft-cli perf [--paths N] [--deep]
Check the performance budgets (render, pan, hit test, save/load, SVG, Pathfinder, handle
and segment drags) on a synthetic N-path document (default 50000). Exits non-zero if a
budget is exceeded, unless the report says the machine is busy. --deep also times work with
no budget yet and prints memory use (the working set on Windows).
";
/// The usage text plus the formats `document.open` reads and `document.export` writes.
+78 -5
View File
@@ -1,7 +1,8 @@
//! `vectorcraft-cli perf`: the performance budgets (plan §4) measured on a synthetic document.
//!
//! Each row is the median of several runs. Timings are wall-clock: on a busy machine (load
//! average above the core count) they are noise, and the report says so.
//! Each row is the median of several runs. Timings are wall-clock: on a busy machine (a load
//! average above three quarters of the cores, or on Windows more than three quarters of the
//! cores busy over a second) they are noise, and the report says so.
use std::time::Instant;
@@ -61,6 +62,7 @@ fn median_ms(runs: usize, mut f: impl FnMut()) -> f64 {
}
/// 1-minute load average (macOS / Linux), if available.
#[cfg(not(windows))]
fn load_average() -> Option<f64> {
let out = std::process::Command::new("sysctl").args(["-n", "vm.loadavg"]).output().ok().filter(|o| o.status.success());
let text = match out {
@@ -70,6 +72,27 @@ fn load_average() -> Option<f64> {
text.split_whitespace().map(|t| t.trim_matches(|c| c == '{' || c == '}')).find_map(|t| t.parse().ok())
}
/// The cores busy on average over one second (Windows), if available: the share of the
/// processors' time that `GetSystemTimes` reports as kernel or user time but not as idle time,
/// times `cores`. A load average also counts the threads waiting for a core.
#[cfg(windows)]
fn busy_cores(cores: usize) -> Option<f64> {
let times = || winsafe::GetSystemTimes().ok().map(|(idle, kernel, user)| [idle, kernel, user].map(u64::from));
let before = times()?;
std::thread::sleep(std::time::Duration::from_secs(1));
busy_share(before, times()?).map(|share| share * cores as f64)
}
/// The share of the processors' time between two `[idle, kernel, user]` readings of
/// `GetSystemTimes` that was busy (kernel time includes idle time). It is None when no time
/// passed, a time went back, or the idle time exceeds the kernel and user time.
#[cfg(any(windows, test))]
fn busy_share([idle0, kernel0, user0]: [u64; 3], [idle1, kernel1, user1]: [u64; 3]) -> Option<f64> {
let total = kernel1.checked_sub(kernel0)?.checked_add(user1.checked_sub(user0)?)?;
let busy = total.checked_sub(idle1.checked_sub(idle0)?)?;
(total > 0).then(|| busy as f64 / total as f64)
}
/// Milliseconds per pointer move of a Direct Selection drag of a handle, then of a segment, of a
/// 5,000-anchor wave of smooth anchors added on top of the synthetic `n`-path document.
fn edit_drags(n: usize) -> Result<(f64, f64), String> {
@@ -114,12 +137,21 @@ fn edit_drags(n: usize) -> Result<(f64, f64), String> {
}
/// Resident memory of this process in MB (`ps`), if available.
#[cfg(not(windows))]
fn rss_mb() -> Option<f64> {
let pid = std::process::id().to_string();
let out = std::process::Command::new("ps").args(["-o", "rss=", "-p", &pid]).output().ok().filter(|o| o.status.success())?;
String::from_utf8_lossy(&out.stdout).trim().parse::<f64>().ok().map(|kb| kb / 1024.0)
}
/// The working set of this process in MB (`GetProcessMemoryInfo`), if available: its pages that
/// are in physical memory, the figure `ps` reports as resident memory elsewhere.
#[cfg(windows)]
fn rss_mb() -> Option<f64> {
let counters = winsafe::HPROCESS::GetCurrentProcess().GetProcessMemoryInfo().ok()?;
Some(counters.WorkingSetSize as f64 / (1024.0 * 1024.0))
}
/// `--deep`: tracked rows (no budget yet) for work the budgets above don't reach: editing a whole
/// selection, live effects, every Pathfinder operation, typing in a long story, and memory.
fn deep(n: usize) -> Result<(), String> {
@@ -243,8 +275,10 @@ fn deep(n: usize) -> Result<(), String> {
for (name, ms) in &rows {
outln!(" {name:<52} {ms:>10.2} ms");
}
// `rss_mb` reads the working set on Windows.
let memory = if cfg!(windows) { "working set" } else { "memory" };
for (what, mb) in &mem {
outln!(" memory {what:<45} {mb:>8.0} MB");
outln!(" {:<52} {mb:>8.0} MB", format!("{memory} {what}"));
}
Ok(())
}
@@ -261,8 +295,12 @@ pub fn run(args: &[String]) -> Result<(), String> {
}
}
let cores = std::thread::available_parallelism().map_or(1, |c| c.get());
let load = load_average();
outln!("VectorCraft performance budgets — {n} paths, {cores} cores, load average {}", load.map_or("?".into(), |l| format!("{l:.1}")));
// The figure is the 1-minute load average, or on Windows the cores busy over one second.
#[cfg(not(windows))]
let (load, label) = (load_average(), "load average");
#[cfg(windows)]
let (load, label) = (busy_cores(cores), "cores busy");
outln!("VectorCraft performance budgets — {n} paths, {cores} cores, {label} {}", load.map_or("?".into(), |l| format!("{l:.1}")));
let noisy = load.is_some_and(|l| l > cores as f64 * 0.75);
if noisy {
outln!("WARNING: the machine is busy; wall-clock timings below are not trustworthy.");
@@ -358,3 +396,38 @@ pub fn run(args: &[String]) -> Result<(), String> {
_ => Err(format!("{over} budget(s) exceeded")),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn busy_share_leaves_out_idle_time() {
// In one second four processors log 40,000,000 ticks of 100 ns of kernel and user time,
// 10,000,000 of them idle.
assert_eq!(busy_share([7, 100, 50], [10_000_007, 25_000_100, 15_000_050]), Some(0.75));
// There is no share when no time passed, a time went back, or the idle time exceeds the
// kernel and user time.
assert_eq!(busy_share([7, 100, 50], [7, 100, 50]), None);
assert_eq!(busy_share([7, 100, 50], [8, 99, 60]), None);
assert_eq!(busy_share([0, 0, 0], [30, 10, 10]), None);
}
/// On Windows `busy_cores` gives a number between 0 and the cores.
#[cfg(windows)]
#[test]
fn windows_reads_how_many_cores_are_busy() {
let cores = std::thread::available_parallelism().map_or(1, |c| c.get());
let busy = busy_cores(cores);
assert!(busy.is_some_and(|b| (0.0..=cores as f64).contains(&b)), "{busy:?} of {cores}");
}
/// On Windows `rss_mb` gives this process's working set: more than 0 MB and less than
/// 10,000 MB.
#[cfg(windows)]
#[test]
fn windows_reads_the_working_set() {
let mb = rss_mb();
assert!(mb.is_some_and(|mb| mb > 0.0 && mb < 10_000.0), "{mb:?}");
}
}
+6
View File
@@ -83,6 +83,12 @@ fn help_lists_readable_formats() {
assert!(out.contains("Readable formats: .vectorcraft") && out.contains(".ait") && out.contains(".webp"), "{out}");
}
#[test]
fn help_lists_perf_deep() {
let out = ok(&["--help"]);
assert!(out.contains("vectorcraft-cli perf [--paths N] [--deep]") && out.contains("--deep also times"), "{out}");
}
/// `info` reports the import warnings: an EPS read only up to an error names it.
#[test]
fn info_reports_why_an_eps_read_partly() {
+93 -46
View File
@@ -2,20 +2,21 @@
//! (`Services::system_clipboard`).
//!
//! - Windows: text, SVG, PDF, PNG and an opaque bitmap (for apps that don't read PNG) in one go;
//! Paste reads each of them, a bitmap as PNG, else as the device-independent bitmap that
//! Paste reads each of them and EPS, a bitmap as PNG, else as the device-independent bitmap that
//! screenshots and most apps copy (`CF_DIBV5`, `CF_DIB`; the system makes them of a `CF_BITMAP`).
//! - macOS and Linux: one format at a time, the text (a type-only copy's text or the SVG markup),
//! else the PNG as a bitmap; Paste reads text and bitmaps (on macOS the pasteboard's PNG or TIFF
//! as they are, as screenshots copy them). On Wayland, arboard's data-control
//! else the PNG as a bitmap; Paste reads text and bitmaps, and on macOS the pasteboard's SVG, PDF
//! and EPS as vector art (#1499) and its PNG or TIFF as they are, as screenshots copy them (on
//! Linux arboard reads no other formats). On Wayland, arboard's data-control
//! backend reads the compositor's clipboard (X11 through XWayland only sees what X11 apps
//! copied), falling back to X11 where the compositor lacks the protocol.
//! - Everywhere: files copied in a file manager paste as the first one that is art (SVG, PDF, a
//! metafile or a bitmap), before the clipboard's other formats (the files' paths as text).
//! - Everywhere: files copied in a file manager paste as the first one that is art (SVG, PDF, EPS,
//! a metafile or a bitmap), before the clipboard's other formats (the files' paths as text).
use std::io::{Cursor, Read};
use std::path::PathBuf;
use vectorcraft_engine::cmd::clipboard::{BITMAP, FILE_HEAD, Flavour, PNG, TEXT, file_flavour};
use vectorcraft_engine::cmd::clipboard::{BITMAP, EPS, FILE_HEAD, Flavour, PDF, PNG, SVG, TEXT, file_flavour};
use vectorcraft_ui_egui::SystemClipboard;
/// This platform's system clipboard.
@@ -27,6 +28,34 @@ pub fn system_clipboard() -> Box<dyn SystemClipboard> {
cb
}
/// The registered Windows clipboard formats a flavour is written under (and read from, first held
/// first).
#[cfg_attr(not(windows), allow(dead_code))]
fn windows_formats(mime: &str) -> &'static [&'static str] {
match mime {
SVG => &["image/svg+xml"],
PDF => &["Portable Document Format", "application/pdf"],
EPS => &["Encapsulated PostScript", "application/postscript"],
PNG => &["PNG"],
_ => &[],
}
}
/// The macOS pasteboard types Paste reads for `mime` (`image/*`: any bitmap), best first, each with
/// the MIME type of its data. They are the system's uniform type identifiers (the values of
/// `NSPasteboardTypePDF`, `NSPasteboardTypePNG` and `NSPasteboardTypeTIFF` among them) and the
/// older name some apps still give PDF. Text is read through arboard.
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
fn pasteboard_types(mime: &str) -> &'static [(&'static str, &'static str)] {
match mime {
SVG => &[("public.svg-image", SVG)],
PDF => &[("com.adobe.pdf", PDF), ("Apple PDF pasteboard type", PDF)], // brand-ok: the system's type identifier
EPS => &[("com.adobe.encapsulated-postscript", EPS)], // brand-ok: the system's type identifier
BITMAP => &[("public.png", PNG), ("public.tiff", "image/tiff")],
_ => &[],
}
}
/// The text flavour among `flavours`.
fn text_of(flavours: &[Flavour]) -> Option<String> {
flavours.iter().find(|f| f.mime == TEXT).map(|f| String::from_utf8_lossy(&f.data).into_owned())
@@ -127,27 +156,15 @@ mod win {
use std::num::NonZeroU32;
use clipboard_win::{formats, options::NoClear, raw};
use vectorcraft_engine::cmd::clipboard::{PDF, SVG};
use super::*;
/// The registered clipboard formats a flavour is written under (and read from, first held
/// first).
fn names(mime: &str) -> &'static [&'static str] {
match mime {
SVG => &["image/svg+xml"],
PDF => &["Portable Document Format", "application/pdf"],
PNG => &["PNG"],
_ => &[],
}
}
/// The device-independent bitmaps, the one that carries alpha first. Each is there whenever the
/// other or a `CF_BITMAP` is: the system converts between them.
const DIBS: [u32; 2] = [formats::CF_DIBV5, formats::CF_DIB];
fn formats_of(mime: &str) -> impl Iterator<Item = u32> {
names(mime).iter().filter_map(|n| raw::register_format(n)).map(NonZeroU32::get)
windows_formats(mime).iter().filter_map(|n| raw::register_format(n)).map(NonZeroU32::get)
}
fn err(e: impl std::fmt::Display) -> String {
@@ -350,27 +367,30 @@ mod portable {
if let Some(f) = cb.get().file_list().ok().and_then(|paths| copied_file(paths, mimes)) {
return Some(f);
}
mimes.iter().find_map(|m| match *m {
TEXT => cb.get_text().ok().filter(|t| !t.is_empty()).map(|t| Flavour { mime: TEXT, data: t.into_bytes() }),
BITMAP => {
#[cfg(target_os = "macos")]
if let Some(f) = super::mac::bitmap() {
return Some(f);
mimes.iter().find_map(|m| {
#[cfg(target_os = "macos")]
if let Some(f) = super::mac::read(m) {
return Some(f);
}
match *m {
TEXT => cb.get_text().ok().filter(|t| !t.is_empty()).map(|t| Flavour { mime: TEXT, data: t.into_bytes() }),
BITMAP => {
let img = cb.get_image().ok()?;
let rgba =
image::RgbaImage::from_raw(u32::try_from(img.width).ok()?, u32::try_from(img.height).ok()?, img.bytes.into_owned())?;
png_flavour(&rgba)
}
let img = cb.get_image().ok()?;
let rgba = image::RgbaImage::from_raw(u32::try_from(img.width).ok()?, u32::try_from(img.height).ok()?, img.bytes.into_owned())?;
png_flavour(&rgba)
_ => None,
}
_ => None,
})
}
/// Text, and on macOS a bitmap (by the pasteboard's types). Linux has no cheap way to ask
/// for a bitmap (reading one costs as much as pasting it): the paste keys take it, the
/// menu item waits for text.
/// Text, and on macOS vector art or a bitmap (by the pasteboard's types). Linux has no
/// cheap way to ask for a bitmap (reading one costs as much as pasting it): the paste keys
/// take it, the menu item waits for text.
fn has(&mut self, mimes: &[&'static str]) -> bool {
#[cfg(target_os = "macos")]
if mimes.contains(&BITMAP) && super::mac::has_bitmap() {
if super::mac::has(mimes) {
return true;
}
mimes.contains(&TEXT) && self.cb().is_ok_and(|cb| cb.get_text().is_ok_and(|t| !t.is_empty()))
@@ -378,7 +398,8 @@ mod portable {
}
}
/// The macOS pasteboard's bitmaps as they are (arboard reads TIFF only, and decodes it).
/// The macOS pasteboard's vector art and bitmaps as they are (arboard reads text, and of the
/// pictures TIFF only, decoded).
#[cfg(target_os = "macos")]
mod mac {
use objc2::rc::autoreleasepool;
@@ -387,24 +408,20 @@ mod mac {
use super::*;
/// The bitmap types Paste reads, best first (the values of `NSPasteboardTypePNG` and
/// `NSPasteboardTypeTIFF`), with their MIME types.
const TYPES: [(&str, &str); 2] = [("public.png", PNG), ("public.tiff", "image/tiff")];
/// Does the pasteboard hold a bitmap? Asks for its types only.
pub fn has_bitmap() -> bool {
/// Does the pasteboard hold one of `mimes` ([`pasteboard_types`])? Asks for its types only.
pub fn has(mimes: &[&'static str]) -> bool {
autoreleasepool(|_| {
let types = TYPES.map(|(t, _)| NSString::from_str(t));
let types: Vec<_> = mimes.iter().flat_map(|m| pasteboard_types(m)).map(|(t, _)| NSString::from_str(t)).collect();
let types: Vec<&NSString> = types.iter().map(|t| &**t).collect();
NSPasteboard::generalPasteboard().availableTypeFromArray(&NSArray::from_slice(&types)).is_some()
!types.is_empty() && NSPasteboard::generalPasteboard().availableTypeFromArray(&NSArray::from_slice(&types)).is_some()
})
}
/// The pasteboard's bitmap, PNG before TIFF.
pub fn bitmap() -> Option<Flavour> {
/// The pasteboard's data for `mime`, the first of its types held ([`pasteboard_types`]).
pub fn read(mime: &str) -> Option<Flavour> {
autoreleasepool(|_| {
let pasteboard = NSPasteboard::generalPasteboard();
TYPES.into_iter().find_map(|(t, mime)| {
pasteboard_types(mime).iter().find_map(|&(t, mime)| {
let data = pasteboard.dataForType(&NSString::from_str(t))?.to_vec();
(!data.is_empty()).then_some(Flavour { mime, data })
})
@@ -414,7 +431,7 @@ mod mac {
#[cfg(test)]
mod tests {
use vectorcraft_engine::cmd::clipboard::{PASTE_ORDER, SVG};
use vectorcraft_engine::cmd::clipboard::{EMF, PASTE_ORDER};
use super::*;
@@ -448,6 +465,36 @@ mod tests {
assert!(copied_file(vec![], &PASTE_ORDER).is_none());
}
/// What another app copied as vector art is asked for under the names the platforms give it,
/// and read as the flavour the paste imports (#1499).
#[test]
fn vector_art_is_read_under_each_platforms_names() {
let mac = |m| pasteboard_types(m).iter().map(|t| t.0).collect::<Vec<_>>();
assert_eq!(mac(PDF), ["com.adobe.pdf", "Apple PDF pasteboard type"]);
assert_eq!(mac(EPS), ["com.adobe.encapsulated-postscript"]);
assert_eq!(mac(SVG), ["public.svg-image"]);
assert_eq!(pasteboard_types(BITMAP), [("public.png", PNG), ("public.tiff", "image/tiff")]);
assert!(windows_formats(EPS).contains(&"Encapsulated PostScript") && windows_formats(PDF).contains(&"Portable Document Format"));
for asked in PASTE_ORDER {
// Each type's data is the flavour asked for (a bitmap its own type): what
// `clipboard.import*` then reads. Text and metafiles come another way.
assert!(pasteboard_types(asked).iter().all(|(_, mime)| *mime == asked || asked == BITMAP), "{asked}");
assert_eq!(pasteboard_types(asked).is_empty(), [TEXT, EMF].contains(&asked), "{asked}");
}
// Vector art before text, text before bitmaps.
let at = |m| PASTE_ORDER.iter().position(|x| *x == m).unwrap();
assert!(at(PDF) < at(EPS) && at(EPS) < at(TEXT) && at(TEXT) < at(BITMAP));
}
/// An .eps file copied in a file manager pastes as EPS.
#[test]
fn a_copied_eps_file_pastes() {
let eps = dir("eps").join("equation.eps");
std::fs::write(&eps, "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 10 10\n0 0 10 10 rectfill\n").unwrap();
assert_eq!(copied_file(vec![eps.clone()], &PASTE_ORDER).map(|f| f.mime), Some(EPS));
assert!(copied_file(vec![eps], &[BITMAP, TEXT]).is_none());
}
#[test]
fn a_crlf_left_by_the_uri_list_is_ignored() {
let red = dir("crlf").join("red.png");
+4
View File
@@ -89,3 +89,7 @@ sync_github_name = false
[people.Nael-Nathanael]
sync_github_name = true
[people.switch87]
real_name = "Gert Pellin"
sync_github_name = false
+3 -3
View File
@@ -207,15 +207,15 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
EXTRUDE,
"Extrude & Bevel…",
&["Effect", "3D and Materials"],
"{depth: pt (0..2000, 50), twist: degrees (-360..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspective: % (0..100, 0), shade: bool (true), lightAzimuth: degrees (-45), lightElevation: degrees (45), lightIntensity: % (80), ambient: % (25)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).",
"{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspective: % (0..100, 0), shade: bool (true), lightAzimuth: degrees (-45), lightElevation: degrees (45), lightIntensity: % (80), ambient: % (25)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).",
json!({"depth":50.0,"twist":0.0,"taper":100.0,"cap":true,"bevel":"none","bevelWidth":4.0,"bevelHeight":4.0,"bevelRepeat":1,"bevelSpace":0.0,"bevelInside":false,"bevelBothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspective":0.0,"shade":true,"lightAzimuth":-45.0,"lightElevation":45.0,"lightIntensity":80.0,"ambient":25.0}),
),
g(
INFLATE,
"Inflate…",
&["Effect", "3D and Materials"],
"{depth: pt (0..2000, 0; flat depth between front and back), volume: % (0..100, 50; 50 rounds the edge like a half sphere), bothSides: bool (false: flat back), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspective: % (0..100, 0), shade: bool (true), lightAzimuth: degrees (-45), lightElevation: degrees (45), lightIntensity: % (80), ambient: % (25)}. Painted with the top fill (else the top stroke).",
json!({"depth":0.0,"volume":50.0,"bothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspective":0.0,"shade":true,"lightAzimuth":-45.0,"lightElevation":45.0,"lightIntensity":80.0,"ambient":25.0}),
"{depth: pt (0..2000, 0; flat depth between front and back), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: no back, a shell open behind), volume: % (0..100, 50; 50 rounds the edge like a half sphere), bothSides: bool (false: flat back), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspective: % (0..100, 0), shade: bool (true), lightAzimuth: degrees (-45), lightElevation: degrees (45), lightIntensity: % (80), ambient: % (25)}. Painted with the top fill (else the top stroke).",
json!({"depth":0.0,"twist":0.0,"taper":100.0,"cap":true,"volume":50.0,"bothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspective":0.0,"shade":true,"lightAzimuth":-45.0,"lightElevation":45.0,"lightIntensity":80.0,"ambient":25.0}),
),
g(
ROTATE,
+8 -1
View File
@@ -90,7 +90,14 @@ pub fn extrude_options(p: &Value) -> Extrude {
}
pub fn inflate_options(p: &Value) -> Inflate {
Inflate { depth: num(p, "depth", 0.0), volume: num(p, "volume", 50.0), both_sides: flag(p, "bothSides", false) }
Inflate {
depth: num(p, "depth", 0.0),
volume: num(p, "volume", 50.0),
both_sides: flag(p, "bothSides", false),
twist: num(p, "twist", 0.0),
taper: num(p, "taper", 100.0) / 100.0,
cap: flag(p, "cap", true),
}
}
/// The shape a solid is made from: a path's or a compound path's outline.
+35
View File
@@ -120,6 +120,32 @@ fn export_and_expand_bake_faces_with_their_own_ids() {
}
}
/// A twisted, tapered, hollow Inflate (both sides) exports and expands like the others: faces with
/// their own ids, no 3D effect left on them.
#[test]
fn a_twisted_tapered_hollow_inflate_exports_and_expands() {
let mut d = Document::new(400.0, 400.0);
let mut n = square_node();
n.id = d.alloc_id();
let params = json!({"twist": 120, "taper": 50, "cap": false, "bothSides": true, "rotationX": -20, "rotationY": 35});
n.appearance.effects.push(fx(INFLATE, params));
let art = solid_art(&n).unwrap();
assert_eq!(crate::bake_appearance(&n), Some(art.clone()));
assert!(faces(&art).len() > 20, "{} faces", faces(&art).len());
let mut stroke = |_: &mut Document, _: &PathData, _: FillRule, _: &StrokeLayer| None;
let expanded = crate::expand_leaf(&mut d, &n, &mut stroke).unwrap();
let mut ids = std::collections::HashSet::new();
fn visit(n: &Node, ids: &mut std::collections::HashSet<NodeId>) {
assert!(ids.insert(n.id), "{:?} twice", n.id);
assert!(!has_solid(n));
for c in n.children().into_iter().flatten() {
visit(c, ids);
}
}
visit(&expanded, &mut ids);
assert!(ids.len() > 20, "{} nodes", ids.len());
}
#[test]
fn effects_before_it_shape_the_solid_and_effects_after_it_bend_the_result() {
let mut n = square_node();
@@ -156,3 +182,12 @@ fn parameters_are_validated_and_lengths_scale_with_the_object() {
assert_eq!((b.shape, b.space, b.repeat), (BevelShape::Step, 0.3, 32));
assert!(extrude_options(&json!({})).bevel.is_none());
}
#[test]
fn inflate_reads_twist_taper_and_cap() {
let o = inflate_options(&json!({"twist": 90, "taper": 40, "cap": false}));
assert_eq!((o.twist, o.taper, o.cap), (90.0, 0.4, false));
let d = inflate_options(&json!({}));
assert_eq!((d.twist, d.taper, d.cap), (0.0, 1.0, true));
assert_eq!(crate::default_params(INFLATE).unwrap()["cap"], json!(true));
}
+7 -9
View File
@@ -15,6 +15,7 @@ use vectorcraft_doc::{AppearanceItem, Document, FillLayer, Node, NodeId, NodeKin
use vectorcraft_geom::{Affine, Point, Vec2};
use super::edit::selected_roots;
use super::pathops::{remove_each, separate};
use super::*;
use crate::EngineError;
@@ -569,6 +570,10 @@ fn symbol_list(s: &mut Session, _: &Value) -> Result<Value> {
/// Replace the root nodes `ids` with one instance of `name` (art already stored). Returns the id.
fn replace_with_instance(d: &mut Document, ids: &[NodeId], name: &str, xf: Affine) -> Result<NodeId> {
let top = *ids.last().ok_or_else(|| EngineError::Other("nothing selected".into()))?;
if separate(d, ids) {
let id = d.alloc_id();
return Ok(d.wrap(ids, |_| Node::new(id, NodeKind::SymbolInstance { symbol: name.into(), xf }))?);
}
let (par, idx, _) = d.position(top).ok_or(EngineError::NoNode(top))?;
let id = d.alloc_id();
d.insert(par, idx + 1, Node::new(id, NodeKind::SymbolInstance { symbol: name.into(), xf }))?;
@@ -742,9 +747,7 @@ fn symbol_delete(s: &mut Session, p: &Value) -> Result<Value> {
if expand {
break_links(d, &inst)?;
} else {
for i in inst {
d.remove(i)?;
}
remove_each(d, &inst)?;
}
d.symbols.retain(|x| x.name != name);
set_natural_size(d, &name, None);
@@ -871,12 +874,7 @@ fn symbol_spray(s: &mut Session, p: &Value) -> Result<Value> {
.collect();
let n = doomed.len();
if n > 0 {
s.edit("Symbol Sprayer", |d, _| {
for id in &doomed {
d.remove(*id)?;
}
Ok(())
})?;
s.edit("Symbol Sprayer", |d, _| remove_each(d, &doomed))?;
}
return Ok(json!({ "count": n }));
}
+20 -17
View File
@@ -26,7 +26,7 @@ use vectorcraft_trace as tr;
use super::edit::selected_roots;
use super::paint::paint_from;
use super::pathops::shape_node;
use super::pathops::{Beside, shape_node};
use super::*;
/// Name of an Image Trace group.
@@ -341,19 +341,16 @@ fn sb_merge(s: &mut Session, p: &Value) -> Result<Value> {
/// Remove the roots and insert `nodes` where the front-most root was. Returns the new ids.
/// (Roots go first: the new nodes may reuse their ids, e.g. Live Paint sources.)
fn replace_roots(d: &mut Document, roots: &[NodeId], nodes: Vec<Node>) -> Result<Vec<NodeId>> {
let top = *roots.last().ok_or_else(|| EngineError::Other("nothing selected".into()))?;
let (par, idx, _) = d.position(top).ok_or(EngineError::NoNode(top))?;
let before = roots.iter().filter(|r| **r != top && d.position(**r).is_some_and(|(p, i, _)| p == par && i < idx)).count();
for r in roots {
let Some((&top, rest)) = roots.split_last() else { return Err(EngineError::Other("nothing selected".into())) };
let ids = nodes.iter().map(|n| n.id).collect();
let mut replaced = Beside::replacing(d, roots);
for r in rest {
if d.node(*r).is_some() {
d.remove(*r)?;
replaced.put(d, *r, vec![])?;
}
}
let at = idx - before;
let mut ids = vec![];
for (k, n) in nodes.into_iter().enumerate() {
ids.push(d.insert(par, at + k, n)?);
}
replaced.put(d, top, nodes)?;
replaced.finish(d)?;
Ok(ids)
}
@@ -508,14 +505,14 @@ fn lp_merge(s: &mut Session, p: &Value) -> Result<Value> {
Arc::make_mut(e).appearance = app.into();
}
}
let mut merged = Beside::replacing(d, &roots);
for r in roots.iter().filter(|r| **r != target) {
if d.node(*r).is_some() {
d.remove(*r)?;
merged.put(d, *r, vec![])?;
}
}
let (par, idx, _) = d.position(target).ok_or(EngineError::NoNode(target))?;
d.remove(target)?;
d.insert(par, idx, g)?;
merged.put(d, target, vec![g])?;
merged.finish(d)?;
sel.set([target]);
Ok((target, nf, ne))
})?;
@@ -536,11 +533,14 @@ fn lp_release(s: &mut Session, p: &Value) -> Result<Value> {
let targets = live_targets(s, p)?;
let ids = s.edit("Release Live Paint", |d, sel| {
let mut out = vec![];
let mut released = Beside::replacing(d, &targets);
for g in &targets {
let n = d.node(*g).cloned().ok_or(EngineError::NoNode(*g))?;
let srcs: Vec<Node> = source_nodes(&n).iter().map(|c| (**c).clone()).collect();
out.extend(replace_roots(d, &[*g], srcs)?);
out.extend(srcs.iter().map(|c| c.id));
released.put(d, *g, srcs)?;
}
released.finish(d)?;
sel.set(out.iter().copied());
Ok(out)
})?;
@@ -836,12 +836,15 @@ fn trace_release(s: &mut Session, p: &Value) -> Result<Value> {
let targets = trace_targets(s, p)?;
let ids = s.edit("Release Image Trace", |d, sel| {
let mut out = vec![];
let mut released = Beside::replacing(d, &targets);
for g in &targets {
let n = d.node(*g).cloned().ok_or(EngineError::NoNode(*g))?;
let mut img = (**n.children().and_then(|c| c.first()).ok_or(EngineError::NoNode(*g))?).clone();
img.visible = true;
out.extend(replace_roots(d, &[*g], vec![img])?);
out.push(img.id);
released.put(d, *g, vec![img])?;
}
released.finish(d)?;
sel.set(out.iter().copied());
Ok(out)
})?;
+1 -1
View File
@@ -21,7 +21,7 @@ use vectorcraft_color::Swatch;
use vectorcraft_doc::{Document, GraphicStyle, ImageBlob, Node, NodeId, PatternDef, Symbol, TextStyleDef};
use vectorcraft_geom::Rect;
pub use flavours::{BITMAP, EMF, FILE_HEAD, Flavour, PASTE_ORDER, PDF, PNG, SVG, TEXT, file_flavour, is_address, names_a_picture};
pub use flavours::{BITMAP, EMF, EPS, FILE_HEAD, Flavour, PASTE_ORDER, PDF, PNG, SVG, TEXT, file_flavour, is_address, names_a_picture};
pub(crate) use resources::SwatchChoices;
use super::*;
+34 -5
View File
@@ -1,5 +1,5 @@
//! Clipboard flavours: what Copy offers other apps besides SVG (PNG, PDF and plain text) and what
//! Paste takes from them (bitmaps, plain text, PDF and Windows metafiles).
//! Paste takes from them (bitmaps, plain text, PDF, EPS and Windows metafiles).
//!
//! The UI owns the platform clipboard (`Services::system_clipboard` in the egui frontend): on Copy
//! it publishes [`Session::clipboard_flavours`]; before a Paste it turns what another app put on
@@ -27,9 +27,12 @@ pub const BITMAP: &str = "image/*";
/// An EMF (or WMF) picture: what Windows apps copy as vector art (the system clipboard reads it
/// where the platform offers it).
pub const EMF: &str = "image/emf";
/// An EPS (or other PostScript) picture: what drawing and typesetting apps copy as vector art
/// beside, or instead of, a PDF (#1499).
pub const EPS: &str = "application/postscript";
/// What Paste reads from other apps, best first: vector art before text, text before bitmaps
/// (word processors offer a picture of copied text too).
pub const PASTE_ORDER: [&str; 5] = [SVG, PDF, EMF, TEXT, BITMAP];
pub const PASTE_ORDER: [&str; 6] = [SVG, PDF, EPS, EMF, TEXT, BITMAP];
/// Is `text` only an address (a web page's, an image's, a file's)? A browser's Copy Image puts the
/// image's address as text next to the picture: then the picture is what Paste takes (#597). An
/// address alone pastes as text, and nothing is fetched.
@@ -67,13 +70,14 @@ fn only_images(html: &str) -> bool {
pub const FILE_HEAD: usize = 4096;
/// What a file copied in a file manager pastes as, if one of `mimes` (`image/*`: any bitmap):
/// SVG, PDF, a Windows metafile or a bitmap (its own `image/…` type), told from its first
/// SVG, PDF, EPS, a Windows metafile or a bitmap (its own `image/…` type), told from its first
/// [`FILE_HEAD`] bytes and its name. The file's bytes are that flavour's data.
pub fn file_flavour(name: &str, head: &[u8], mimes: &[&str]) -> Option<&'static str> {
let f = fileio::detect(name, head)?;
let (asked, mime) = match f.id {
"svg" => (SVG, SVG),
"pdf" => (PDF, PDF),
"eps" => (EPS, EPS),
"emf" | "wmf" => (EMF, EMF),
_ if f.raster => (BITMAP, f.mime),
_ => return None,
@@ -167,6 +171,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
import_emf
),
cmd!(
query "clipboard.importEps",
"Load EPS into Clipboard",
[],
None,
"{dataBase64 (EPS or other PostScript bytes), center?: [x, y]} replace the clipboard with the picture's objects as document.open reads an EPS (editable paths, type and images, with the images, patterns and swatches they use), centred on `center` (default: the first artboard) → {count, warnings}; then run edit.paste",
has_doc,
import_eps
),
]
}
@@ -345,10 +358,26 @@ fn import_emf(s: &mut Session, p: &Value) -> Result<Value> {
if vectorcraft_metafile::sniff(&bytes).is_none() {
return Err(bad(C, "the data isn't an EMF or WMF picture"));
}
let loaded = fileio::load("Clipboard.emf", &bytes).map_err(|e| bad(C, e.to_string()))?;
import_picture(s, p, C, "Clipboard.emf", &bytes)
}
fn import_eps(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "clipboard.importEps";
let bytes = data_param(p, C)?;
if !vectorcraft_pdf::is_postscript(&bytes) {
return Err(bad(C, "the data isn't an EPS or PostScript picture"));
}
import_picture(s, p, C, "Clipboard.eps", &bytes)
}
/// Replace the clipboard with the objects of the picture `bytes`, read as the file `name` is
/// opened (command `cmd`).
fn import_picture(s: &mut Session, p: &Value, cmd: &str, name: &str, bytes: &[u8]) -> Result<Value> {
let mut loaded = fileio::load(name, bytes).map_err(|e| bad(cmd, e.to_string()))?;
loaded.doc.drop_edit_modes();
let clip = Clipboard::from_document(&loaded.doc);
if clip.is_empty() {
return Err(bad(C, "the picture has no objects"));
return Err(bad(cmd, "the picture has no objects"));
}
let count = s.load_clipboard(clip, p)?;
Ok(json!({ "count": count, "warnings": loaded.warnings }))
+4 -2
View File
@@ -14,7 +14,7 @@ use vectorcraft_pathops::BoolOp;
use super::draw2::{components, erase_outline, ids_json, replace_with_pieces};
use super::edit::selected_roots;
use super::pathops::node_path;
use super::pathops::{Beside, node_path};
use super::*;
pub fn specs() -> Vec<CommandSpec> {
@@ -163,10 +163,12 @@ fn apply(s: &mut Session, label: &str, plan: Plan) -> Result<Value> {
}
let (ids, removed) = s.edit(label, |d: &mut Document, sel| {
let (mut all, mut removed) = (vec![], 0);
let mut cut = Beside::replacing(d, &plan.iter().map(|(id, _)| *id).collect::<Vec<_>>());
for (id, pieces) in plan {
removed += pieces.is_empty() as usize;
all.extend(replace_with_pieces(d, id, pieces)?);
all.extend(replace_with_pieces(d, &mut cut, id, pieces)?);
}
cut.finish(d)?;
sel.set(all.iter().copied());
Ok((all, removed))
})?;
+6 -2
View File
@@ -10,6 +10,7 @@ use vectorcraft_doc::{CharStyle, Guide, Node, NodeId, NodeKind, SavedSelection,
use vectorcraft_geom::Vec2;
use super::edit::selected_roots;
use super::pathops::Beside;
use super::select::{selectable_ids, walk_selectable};
use super::*;
@@ -504,10 +505,13 @@ fn clear_guides(s: &mut Session, _: &Value) -> Result<Value> {
}
s.edit("Clear Guides", |d, _| {
d.guides.clear();
let mut gone = Beside::replacing(d, &paths);
for id in &paths {
let _ = d.remove(*id);
if d.node(*id).is_some() {
gone.put(d, *id, vec![])?;
}
}
Ok(())
gone.finish(d)
})?;
Ok(json!({ "count": n }))
}
+36 -17
View File
@@ -13,6 +13,7 @@ use vectorcraft_pathops as po;
use vectorcraft_pathops::{BoolOp, Cap, Join, SimplifyOptions};
use super::create::{add_look, add_node};
use super::pathops::{Beside, remove_each};
use super::*;
use crate::EngineError;
@@ -310,20 +311,25 @@ fn sibling_with(d: &mut Document, id: NodeId, pd: PathData) -> Result<Node> {
}
/// Replace path or compound path `id` with `pieces` (first keeps the id, the rest go right above
/// it; none removes it). Returns ids.
pub(super) fn replace_with_pieces(d: &mut Document, id: NodeId, pieces: Vec<PathData>) -> Result<Vec<NodeId>> {
/// it; none removes it). `cut` removes the path or puts the other pieces above it. Returns ids.
pub(super) fn replace_with_pieces(d: &mut Document, cut: &mut Beside, id: NodeId, pieces: Vec<PathData>) -> Result<Vec<NodeId>> {
let mut it = pieces.into_iter();
let Some(first) = it.next() else {
d.remove(id)?;
cut.put(d, id, vec![])?;
return Ok(vec![]);
};
let (parent, idx, _) = d.position(id).ok_or(EngineError::NoNode(id))?;
let mut ids = vec![id];
for (k, pd) in it.enumerate() {
let mut above = vec![];
for pd in it {
let n = sibling_with(d, id, pd)?;
ids.push(d.insert(parent, idx + 1 + k, n)?);
ids.push(n.id);
above.push(n);
}
set_geometry(d, id, first)?;
if !above.is_empty() {
let n = d.node(id).cloned().ok_or(EngineError::NoNode(id))?;
cut.put(d, id, [n].into_iter().chain(above).collect())?;
}
Ok(ids)
}
@@ -733,7 +739,10 @@ fn remove_anchor(s: &mut Session, p: &Value) -> Result<Value> {
if ai >= sp.anchors.len() {
return Err(EngineError::Other("no such anchor".into()));
}
remove_anchors_of(d, sel, id, [(si, ai)])
let mut emptied = Beside::replacing(d, &[id]);
let removed = remove_anchors_of(d, sel, &mut emptied, id, [(si, ai)])?;
emptied.finish(d)?;
Ok(removed)
})?;
Ok(json!({ "removedObject": removed }))
}
@@ -752,18 +761,26 @@ fn remove_anchors(s: &mut Session, _: &Value) -> Result<Value> {
}
let removed = s.edit("Remove Anchor Points", |d, sel| {
let mut removed = 0;
let mut emptied = Beside::replacing(d, &jobs.iter().map(|(id, _)| *id).collect::<Vec<_>>());
for (id, anchors) in jobs {
removed += usize::from(remove_anchors_of(d, sel, id, anchors)?);
removed += usize::from(remove_anchors_of(d, sel, &mut emptied, id, anchors)?);
}
emptied.finish(d)?;
Ok(removed)
})?;
Ok(json!({ "removedObjects": removed }))
}
/// Remove `anchors` (subpath, anchor) of path `id` without opening it, refitting the curve round
/// each one; a subpath left with one anchor goes, and the path with its last subpath. True when
/// the path went.
fn remove_anchors_of(d: &mut Document, sel: &mut Selection, id: NodeId, anchors: impl IntoIterator<Item = (usize, usize)>) -> Result<bool> {
/// each one. A subpath left with one anchor is removed, and a path left with no subpath is removed
/// through `emptied`. True when the path went.
fn remove_anchors_of(
d: &mut Document,
sel: &mut Selection,
emptied: &mut Beside,
id: NodeId,
anchors: impl IntoIterator<Item = (usize, usize)>,
) -> Result<bool> {
let mut anchors: Vec<(usize, usize)> = anchors.into_iter().collect();
// The last first, so the indexes still to come stay valid.
anchors.sort_unstable_by(|a, b| b.cmp(a));
@@ -777,7 +794,7 @@ fn remove_anchors_of(d: &mut Document, sel: &mut Selection, id: NodeId, anchors:
path.subpaths.retain(|sp| sp.anchors.len() >= 2);
let gone = path.is_empty();
if gone {
d.remove(id)?;
emptied.put(d, id, vec![])?;
sel.remove(id);
} else {
sel.anchors.remove(&id);
@@ -920,9 +937,11 @@ fn knife(s: &mut Session, p: &Value) -> Result<Value> {
}
let ids = s.edit("Knife", |d, sel| {
let mut all = vec![];
let mut cut = Beside::replacing(d, &plan.iter().map(|(id, _)| *id).collect::<Vec<_>>());
for (id, pieces) in plan {
all.extend(replace_with_pieces(d, id, pieces)?);
all.extend(replace_with_pieces(d, &mut cut, id, pieces)?);
}
cut.finish(d)?;
sel.set(all.iter().copied());
Ok(all)
})?;
@@ -960,9 +979,11 @@ fn apply_plan(s: &mut Session, label: &str, plan: Vec<(NodeId, Vec<PathData>)>)
}
let ids = s.edit(label, |d, sel| {
let mut all = vec![];
let mut cut = Beside::replacing(d, &plan.iter().map(|(id, _)| *id).collect::<Vec<_>>());
for (id, pieces) in plan {
all.extend(replace_with_pieces(d, id, pieces)?);
all.extend(replace_with_pieces(d, &mut cut, id, pieces)?);
}
cut.finish(d)?;
sel.set(all.iter().copied());
Ok(all)
})?;
@@ -1256,9 +1277,7 @@ fn blob(s: &mut Session, p: &Value) -> Result<Value> {
let others: Vec<NodeId> = rest.iter().map(|m| m.0).collect();
s.edit("Blob Brush", |d, sel| {
*path_mut(d, keep)? = merged;
for id in others {
d.remove(id)?;
}
remove_each(d, &others)?;
sel.set([keep]);
Ok(())
})?;
+15 -6
View File
@@ -558,10 +558,20 @@ fn duplicate(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() }))
}
/// Duplicate `roots` directly above each original, transform the copies, select them. The copies
/// take new ids in the order of `roots`. Roots listed twice, or inside another root, are copied one
/// at a time: each copy is made from the document as the copies before it left it.
/// Duplicate `roots` directly above each original, transform the copies, select them
/// ([`copy_above`]).
pub(crate) fn duplicate_in(d: &mut Document, sel: &mut vectorcraft_doc::Selection, roots: &[NodeId], xf: Affine) -> Result<Vec<NodeId>> {
let out = copy_above(d, roots, |_, _, c| c.transform(xf, true))?;
sel.set(out.iter().copied());
Ok(out)
}
/// Copy `roots` directly above each original and return the copies' ids. `change` gets the
/// document, each original and its copy before the copy goes in, and must leave the document's
/// tree as it is. The copies take new ids in the order of `roots`. Roots listed twice, or inside
/// another root, are copied one at a time: each copy is made from the document as the copies
/// before it left it.
pub(crate) fn copy_above(d: &mut Document, roots: &[NodeId], mut change: impl FnMut(&mut Document, &Node, &mut Node)) -> Result<Vec<NodeId>> {
let paths = d.index_paths(roots.iter().copied());
let mut found: Vec<_> = roots.iter().filter_map(|id| paths.get(id)).collect();
found.sort_unstable();
@@ -570,7 +580,7 @@ pub(crate) fn duplicate_in(d: &mut Document, sel: &mut vectorcraft_doc::Selectio
for id in roots {
let Some(n) = paths.get(id).and_then(|p| d.node_at(p)).cloned() else { continue };
let mut c = d.reid(&n);
c.transform(xf, true);
change(d, &n, &mut c);
copies.push((*id, vec![c]));
}
let out: Vec<NodeId> = copies.iter().flat_map(|(_, c)| c.iter().map(|n| n.id)).collect();
@@ -582,12 +592,11 @@ pub(crate) fn duplicate_in(d: &mut Document, sel: &mut vectorcraft_doc::Selectio
let Some((par, idx, _)) = d.position(*id) else { continue };
let Some(n) = d.node(*id).cloned() else { continue };
let mut c = d.reid(&n);
c.transform(xf, true);
change(d, &n, &mut c);
out.push(d.insert(par, idx + 1, c)?);
}
out
};
sel.set(out.iter().copied());
Ok(out)
}
+6
View File
@@ -382,7 +382,13 @@ pub fn encode_all(doc: &Document, format: &str, p: &Value) -> Result<Encoded> {
/// [`encode_all`] of `doc` as it is.
fn encode_all_of(doc: &Document, format: &str, p: &Value) -> Result<Encoded> {
let f = super::writable(C, Some(format), None)?;
let failed = vectorcraft_render::decode_failures();
let mut enc = encode_files(doc, f, p)?;
// An image the renderer couldn't decode draws nothing: say so rather than write a picture
// that silently lacks it.
if f.raster && vectorcraft_render::decode_failures() > failed {
enc.warnings.push("an image couldn't be decoded and is missing from the picture".into());
}
// Formats that draw type: missing fonts come out in the fallback font (PDF and SVG say so
// themselves: SVG only when it outlines or embeds fonts).
if (f.raster || matches!(f.id, "eps" | "emf" | "wmf"))
+14 -2
View File
@@ -192,7 +192,7 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
let title = file_name(name);
let mut converted = false;
let mut preview_only = false;
let (mut doc, warnings, restored) = match format.id {
let (mut doc, mut warnings, restored) = match format.id {
// EPS and PostScript .ai: the document our EPS files carry, else the PostScript read.
_ if format.id == "eps" || vectorcraft_pdf::is_postscript(bytes) => {
let editing = vectorcraft_eps::has_native(bytes).then_some((true, || vectorcraft_eps::native(bytes)));
@@ -263,6 +263,7 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
if !matches!(format.id, "vectorcraft" | "template") || doc.title.is_empty() {
doc.title = title;
}
warnings.extend(doc.images.values().filter_map(|b| too_large_note(&b.bytes)));
Ok(Loaded { doc, format, warnings, restored, converted, preview_only })
}
@@ -392,7 +393,18 @@ pub(super) fn new_from_template(s: &mut Session, p: &Value) -> Result<Value> {
/// The most memory decoding one image may take: a 60 in print sheet at 300 ppi (18000 × 6600 px)
/// is ~475 MB as RGBA, past the decoder's 512 MB default once it is converted. The web app keeps
/// that default: wasm32 has 4 GB to address and aborts when an allocation fails.
const MAX_RASTER_ALLOC: u64 = if cfg!(target_arch = "wasm32") { 512 << 20 } else { 2 << 30 };
pub(crate) const MAX_RASTER_ALLOC: u64 = if cfg!(target_arch = "wasm32") { 512 << 20 } else { 2 << 30 };
/// What to say of encoded image `bytes` that need more than [`MAX_RASTER_ALLOC`] to decode (its
/// header says so; the pixels aren't read): the renderer, which has the same allowance, draws
/// nothing for them, so Open, Place and the Links panel say it (#1479). `None` for images that
/// decode, and for bytes that aren't an image.
pub(crate) fn too_large_note(bytes: &[u8]) -> Option<String> {
use image::ImageDecoder as _;
let d = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?.into_decoder().ok()?;
let (w, h) = d.dimensions();
(d.total_bytes() > MAX_RASTER_ALLOC).then(|| format!("an image of {w} × {h} pixels is too large to draw"))
}
/// Decode an image's header (and, for formats stored as PNG, its pixels). CMYK TIFFs are kept as
/// they are, with their ink amounts ([`ImageBlob::cmyk`]); CMYK TIFFs with an alpha channel, which
+1
View File
@@ -28,6 +28,7 @@ pub mod eps;
mod export;
pub(crate) mod imagemap;
mod load;
pub(crate) use load::{MAX_RASTER_ALLOC, too_large_note};
mod metafile;
mod native;
pub mod pdf;
@@ -163,3 +163,20 @@ fn an_image_opens_at_the_size_its_resolution_declares() {
assert!((art.width() - w).abs() < 1e-6 && (art.height() - h).abs() < 1e-6, "{what}: the image fills it, {art:?}");
}
}
#[test]
fn a_raster_export_says_when_an_image_could_not_be_decoded() {
// A PNG whose header reads (so it places at its size) but whose pixel data is cut short:
// the renderer can't decode it and draws nothing, which the export must say.
let mut s = session(72.0, 36.0, 1);
let mut png = Vec::new();
image::RgbaImage::from_pixel(64, 32, image::Rgba([200, 30, 30, 255]))
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
.unwrap();
let cut = png_chunk(&png, b"IDAT").map(|d| d.as_ptr() as usize - png.as_ptr() as usize).unwrap() + 4;
png.truncate(cut);
s.execute("file.place", &json!({"name": "cut.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap();
let r = s.execute("document.export", &json!({"format": "png", "background": "transparent"})).unwrap();
let warnings = r["warnings"].as_array().cloned().unwrap_or_default();
assert!(warnings.iter().any(|w| w.as_str().is_some_and(|w| w.contains("couldn't be decoded"))), "{r}");
}
+21 -9
View File
@@ -35,7 +35,7 @@ use vectorcraft_render::effects;
use super::edit::roots_of;
use super::menucmds::{MAX_PIXELS, isolated_doc, unique_key};
use super::pathops::{node_path, outline_strokes, outline_strokes_under, shape_node};
use super::pathops::{node_path, outline_strokes, outline_strokes_under, separate, shape_node};
use super::*;
pub fn specs() -> Vec<CommandSpec> {
@@ -1038,7 +1038,10 @@ pub(crate) fn flatten_document(doc: &Document, o: &FlattenOptions) -> Result<Opt
fn apply(d: &mut Document, sel: &mut vectorcraft_doc::Selection, plan: Plan, o: &FlattenOptions) -> Result<(Vec<NodeId>, usize, usize)> {
let (mut vector, mut rasterized) = (0, 0);
let mut ids = vec![];
let (mut ids, mut flat) = (vec![], vec![]);
// The groups replace their objects in one pass at the end. When an object is listed twice or
// lies inside another listed one, each group replaces its objects as it is made instead.
let one_pass = separate(d, &plan.flat.iter().flat_map(|f| f.roots.iter().copied()).collect::<Vec<_>>());
for f in plan.flat {
// A group always has objects.
let Some(&top) = f.roots.last() else { continue };
@@ -1060,13 +1063,23 @@ fn apply(d: &mut Document, sel: &mut vectorcraft_doc::Selection, plan: Plan, o:
children.push(Arc::new(n));
vector += 1;
}
let (par, idx, _) = d.position(top).ok_or(EngineError::NoNode(top))?;
let g = Node::group(d.alloc_id(), children);
ids.push(d.insert(par, idx + 1, g)?);
for r in &f.roots {
d.remove(*r)?;
ids.push(g.id);
if one_pass {
// The group replaces the topmost object, and the other objects are removed.
flat.extend(f.roots.iter().filter(|r| **r != top).map(|r| (*r, vec![])));
flat.push((top, vec![g]));
} else {
let (par, idx, _) = d.position(top).ok_or(EngineError::NoNode(top))?;
d.insert(par, idx + 1, g)?;
for r in &f.roots {
d.remove(*r)?;
}
}
}
if !flat.is_empty() {
d.insert_beside(flat, true)?;
}
let brushes = if o.strokes_to_outlines { vectorcraft_brush::library(d) } else { vec![] };
for mut id in plan.kept {
if o.text_to_outlines {
@@ -1113,9 +1126,8 @@ fn outline_texts_under(d: &mut Document, root: NodeId) -> Result<NodeId> {
for t in texts {
let Some(o) = outlined_text(&t) else { continue };
let o = d.reid(&o);
let (par, idx, _) = d.position(t.id).ok_or(EngineError::NoNode(t.id))?;
let nid = d.insert(par, idx, o)?;
d.remove(t.id)?;
let nid = o.id;
*d.node_mut(t.id).ok_or(EngineError::NoNode(t.id))? = o;
if t.id == root {
out = nid;
}
+10 -1
View File
@@ -146,7 +146,7 @@ fn to_csv(g: &GraphSpec) -> String {
}
out.push(',');
}
out.push_str(&r.iter().map(|v| v.map(fmt_value).unwrap_or_default()).collect::<Vec<_>>().join(","));
out.push_str(&r.iter().map(|v| v.map(|v| v.to_string()).unwrap_or_default()).collect::<Vec<_>>().join(","));
out.push('\n');
}
out
@@ -2338,6 +2338,15 @@ mod tests {
assert_eq!(super::nice_axis(0.0, 7.0, 0), (0.0, 8.0, 2.0));
}
#[test]
fn numeric_csv_cells_round_trip_without_rounding_or_saturation() {
let mut g = GraphSpec::default();
g.set_cells(vec![vec![Some(1.2345), Some(-1.2345)], vec![Some(1e-6), Some(-1e-6)], vec![Some(1e20), Some(-1e20)], vec![Some(0.0), None]]);
let csv = super::to_csv(&g);
let (_, _, cells) = super::parse_csv(&csv);
assert_eq!(cells, g.cells(), "{csv}");
}
#[test]
fn empty_cells_are_blank_and_quoted_numbers_are_labels() {
// Quoted years label the rows; empty and non-numeric cells are blank values, not zeros.
+5 -6
View File
@@ -232,12 +232,11 @@ fn halftone(s: &mut Session, p: &Value) -> Result<Value> {
let gid = d.alloc_id();
let mut g = Node::group(gid, children);
g.name = Some("Vector Halftone".into());
let (par, idx, _) = d.position(top).ok_or(EngineError::NoNode(top))?;
d.insert(par, idx + 1, g)?;
if !keep {
for r in &roots {
d.remove(*r)?;
}
if keep {
let (par, idx, _) = d.position(top).ok_or(EngineError::NoNode(top))?;
d.insert(par, idx + 1, g)?;
} else {
d.wrap(&roots, |_| g)?;
}
sel.set([gid]);
Ok(gid)
+71 -45
View File
@@ -234,23 +234,47 @@ pub(crate) fn locked_within(d: &Document, id: NodeId) -> bool {
d.ancestry(id).unwrap_or_default().iter().any(|a| d.node(*a).is_some_and(|n| n.locked))
}
/// Every layer and sublayer, depth first.
fn all_layers(d: &Document) -> Vec<&Node> {
let mut out = vec![];
d.walk(|n| {
/// The number and the names of a document's layers and sublayers, from which [`NewLayers::make`]
/// names and colors a new layer. [`NewLayers::of`] reads them in one walk of the document, and
/// [`NewLayers::add`] counts each new layer as it goes in.
pub(crate) struct NewLayers {
count: usize,
taken: HashSet<String>,
}
impl NewLayers {
pub(crate) fn of(d: &Document) -> Self {
let mut layers = Self { count: 0, taken: HashSet::new() };
d.walk(|n| layers.note(n));
layers
}
/// A new layer named `name` (default: the next `Layer N`, as [`Document::next_layer_name`]
/// gives it) in the next layer color.
pub(crate) fn make(&self, d: &mut Document, name: Option<&str>) -> Node {
let name = name
.map(str::to_string)
.unwrap_or_else(|| (self.count + 1..).map(|i| format!("Layer {i}")).find(|name| !self.taken.contains(name)).unwrap_or_default());
let id = d.alloc_id();
Node::layer(id, &name, LayerColor::Preset((self.count % LAYER_COLORS.len()) as u8))
}
/// Count `n`, a layer going into the document, and the layers inside it.
pub(crate) fn add(&mut self, n: &Node) {
n.walk(&mut |c| self.note(c));
}
fn note(&mut self, n: &Node) {
if n.is_layer() {
out.push(n);
self.count += 1;
self.taken.extend(n.name.clone());
}
});
out
}
}
/// A new layer named `name` (default: the next `Layer N`) in the next layer colour.
pub(crate) fn make_layer(d: &mut Document, name: Option<&str>) -> Node {
let n = all_layers(d).len();
let name = name.map(str::to_string).unwrap_or_else(|| d.next_layer_name());
let id = d.alloc_id();
Node::layer(id, &name, LayerColor::Preset((n % LAYER_COLORS.len()) as u8))
NewLayers::of(d).make(d, name)
}
/// A layer colour: a preset index (0–26), `#rrggbb` or a preset's name (any case).
@@ -464,13 +488,12 @@ fn delete_rows(s: &mut Session, p: &Value) -> Result<Value> {
if ids.is_empty() {
return Err(bad("layer.delete", "no such rows"));
}
if st.doc.layers.iter().all(|l| ids.contains(&l.id)) {
let listed: HashSet<NodeId> = ids.iter().copied().collect();
if st.doc.layers.iter().all(|l| listed.contains(&l.id)) {
return Err(EngineError::Other("a document needs at least one layer".into()));
}
s.edit("Delete Selection", |d, sel| {
for id in &ids {
d.remove(*id)?;
}
d.remove_many(&ids)?;
// The guides on the deleted layers go with them.
d.drop_guides_of_deleted_layers(sel);
sel.prune(d);
@@ -491,18 +514,12 @@ fn duplicate_rows(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad("layer.duplicate", "no such rows"));
}
let copies = s.edit("Duplicate Selection", |d, _| {
let mut out = vec![];
for id in &ids {
let (par, idx, _) = d.position(*id).ok_or(EngineError::NoNode(*id))?;
let n = d.node(*id).cloned().ok_or(EngineError::NoNode(*id))?;
let mut c = d.reid(&n);
super::edit::copy_above(d, &ids, |d, n, c| {
if n.is_layer() {
c.name = Some(format!("{} copy", n.display_name()));
d.copy_layer_guides(&n, &c);
d.copy_layer_guides(n, c);
}
out.push(d.insert(par, idx + 1, c)?);
}
Ok(out)
})
})?;
s.doc_mut()?.layer_rows = copies.clone();
Ok(json!({ "ids": copies.iter().map(|i| i.0).collect::<Vec<_>>() }))
@@ -579,14 +596,23 @@ fn collect(s: &mut Session, p: &Value) -> Result<Value> {
let lid = s.edit("Collect in New Layer", |d, sel| {
// Where the topmost of them is: beside it in its layer, or on top of the layer holding
// its group.
let (parent, index) = match d.position(top) {
Some((par, i, _)) if par.is_none_or(|p| d.node(p).is_some_and(Node::is_layer)) => (par, i + 1),
_ => (d.layer_containing(top), usize::MAX),
};
let layer = make_layer(d, None);
let lid = d.insert(parent, index, layer)?;
for id in &ids {
d.move_node(*id, Some(lid), usize::MAX)?;
let beside = d.position(top).is_some_and(|(par, _, _)| par.is_none_or(|p| d.node(p).is_some_and(Node::is_layer)));
let holder = d.layer_containing(top);
let mut layer = make_layer(d, None);
let lid = layer.id;
if beside {
d.wrap(&ids, |rows| {
if let Some(ch) = layer.children_mut() {
*ch = rows;
}
layer
})?;
} else {
let rows = d.remove_many(&ids)?;
if let Some(ch) = layer.children_mut() {
*ch = rows;
}
d.insert(holder, usize::MAX, layer)?;
}
sel.prune(d);
sel.deselect_uneditable(d);
@@ -683,19 +709,20 @@ fn move_rows(s: &mut Session, p: &Value) -> Result<Value> {
}
let label = if copy { "Duplicate Rows" } else { "Move Rows" };
let moved = s.edit(label, |d, sel| {
let mut nodes = vec![];
for id in &ids {
nodes.push(if copy {
let nodes = if copy {
let mut nodes = vec![];
for id in &ids {
let n = d.node(*id).cloned().ok_or(EngineError::NoNode(*id))?;
let c = d.reid(&n);
if n.is_layer() {
d.copy_layer_guides(&n, &c);
}
c
} else {
Arc::unwrap_or_clone(d.remove(*id)?)
});
}
nodes.push(Arc::new(c));
}
nodes
} else {
d.remove_many(&ids)?
};
let count = d.children(parent).map_or(0, Vec::len);
let mut index = match anchor {
None => count,
@@ -708,11 +735,10 @@ fn move_rows(s: &mut Session, p: &Value) -> Result<Value> {
if count > 0 && parent.and_then(|p| d.node(p)).is_some_and(Node::clips) {
index = index.max(1);
}
let mut out = vec![];
for n in nodes {
out.push(d.insert(parent, index, n)?);
index += 1;
}
let out: Vec<NodeId> = nodes.iter().map(|n| n.id).collect();
let ch = d.children_mut(parent)?;
let index = index.min(ch.len());
ch.splice(index..index, nodes);
sel.prune(d);
sel.deselect_uneditable(d);
Ok(out)
+22 -30
View File
@@ -9,7 +9,7 @@ use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
use super::layer::{make_layer, row_roots, rows_param};
use super::layer::{NewLayers, row_roots, rows_param};
use super::*;
use crate::EngineError;
@@ -234,28 +234,23 @@ fn template(s: &mut Session, p: &Value) -> Result<Value> {
/// another) into layer `into`, keeping the document's stacking order, then delete the emptied
/// layers.
fn merge_into(d: &mut Document, into: NodeId, others: &[NodeId]) -> Result<()> {
let listed: HashSet<NodeId> = others.iter().copied().collect();
let own: Vec<NodeId> =
d.node(into).and_then(|n| n.children()).map(|c| c.iter().map(|c| c.id).filter(|c| !others.contains(c)).collect()).unwrap_or_default();
let mut moved = vec![];
d.node(into).and_then(|n| n.children()).map(|c| c.iter().map(|c| c.id).filter(|c| !listed.contains(c)).collect()).unwrap_or_default();
let (mut moved, mut emptied) = (vec![], vec![]);
for id in others {
let n = d.node(*id).ok_or(EngineError::NoNode(*id))?;
if n.is_layer() {
moved.extend(n.children().into_iter().flatten().map(|c| c.id));
emptied.push(*id);
} else {
moved.push(*id);
}
}
// Where everything is now: the merged layer stacks its contents in this order.
let keys: HashMap<NodeId, Vec<usize>> = own.iter().chain(&moved).filter_map(|id| Some((*id, d.index_path(*id)?))).collect();
let mut taken = vec![];
for id in &moved {
taken.push(d.remove(*id)?);
}
for id in others {
if d.node(*id).is_some() {
d.remove(*id)?;
}
}
let taken = d.remove_many(&moved)?;
d.remove_many(&emptied)?;
let ch = d.children_mut(Some(into))?;
let mut all = std::mem::take(ch);
all.extend(taken);
@@ -312,9 +307,7 @@ fn flatten(s: &mut Session, p: &Value) -> Result<Value> {
let others: Vec<NodeId> = d.layers.iter().filter(|l| l.id != into && l.visible && !l.is_template()).map(|l| l.id).collect();
let hidden: Vec<NodeId> = d.layers.iter().filter(|l| l.id != into && !l.visible && !l.is_template()).map(|l| l.id).collect();
s.edit("Flatten Artwork", |d, sel| {
for h in &hidden {
d.remove(*h)?;
}
d.remove_many(&hidden)?;
// Hidden layers are discarded with their guides.
d.drop_guides_of_deleted_layers(sel);
merge_into(d, into, &others)?;
@@ -352,39 +345,38 @@ fn release(s: &mut Session, p: &Value) -> Result<Value> {
}
let new = s.edit(if build { "Release to Layers (Build)" } else { "Release to Layers (Sequence)" }, |d, sel| {
// A group's objects go into sublayers of the layer holding it, where it was.
let (parent, mut index) = if group {
let (parent, index) = if group {
let layer = d.layer_containing(id).ok_or(EngineError::NoNode(id))?;
let (par, i, _) = d.position(id).ok_or(EngineError::NoNode(id))?;
if par == Some(layer) { (layer, i) } else { (layer, usize::MAX) }
} else {
(id, 0)
};
let mut originals = vec![];
for o in &objects {
originals.push(Arc::unwrap_or_clone(d.remove(*o)?));
}
let originals = d.remove_many(&objects)?;
if group {
d.remove(id)?;
}
let mut new = vec![];
let mut names = NewLayers::of(d);
let mut layers = Vec::with_capacity(originals.len());
let last = originals.len().saturating_sub(1);
for k in 0..originals.len() {
let mut layer = make_layer(d, None);
let lid = layer.id;
let held: Vec<Node> = if build {
let mut layer = names.make(d, None);
let held: Vec<Arc<Node>> = if build {
// Copies of the objects below and itself; the top layer keeps the originals.
(0..=k).filter_map(|j| originals.get(j)).map(|o| if k == last { o.clone() } else { d.reid(o) }).collect()
(0..=k).filter_map(|j| originals.get(j)).map(|o| if k == last { o.clone() } else { Arc::new(d.reid(o)) }).collect()
} else {
originals.get(k).cloned().into_iter().collect()
};
if let Some(ch) = layer.children_mut() {
ch.extend(held.into_iter().map(Arc::new));
ch.extend(held);
}
let at = if group { index } else { index.min(d.children(Some(parent)).map_or(0, Vec::len)) };
d.insert(Some(parent), at, layer)?;
index = at.saturating_add(1);
new.push(lid);
names.add(&layer);
layers.push(Arc::new(layer));
}
let new: Vec<NodeId> = layers.iter().map(|l| l.id).collect();
let ch = d.children_mut(Some(parent))?;
let at = index.min(ch.len());
ch.splice(at..at, layers);
sel.prune(d);
Ok(new)
})?;
+9 -2
View File
@@ -75,7 +75,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Links",
[],
None,
"{show?: all (default)|missing|modified|embedded, sort?: name|kind (file format)|status (missing, modified, ok, embedded); default: stacking order; top first} every image object and placed document in the layers, as the Links panel lists them → {links: [{id, name, linked, status: ok|modified|missing|embedded, format, pixelWidth, pixelHeight, path?, found?: path (found away from its path), page?, preview?: true (showing the saved preview), document?: true (a placed document: pageWidth and pageHeight in pt instead of pixels)}], missing, modified, embedded}",
"{show?: all (default)|missing|modified|embedded, sort?: name|kind (file format)|status (missing, modified, ok, embedded); default: stacking order; top first} every image object and placed document in the layers, as the Links panel lists them → {links: [{id, name, linked, status: ok|modified|missing|embedded, format, pixelWidth, pixelHeight, path?, found?: path (found away from its path), page?, preview?: true (showing the saved preview), note?: said of an image too large to draw, document?: true (a placed document: pageWidth and pageHeight in pt instead of pixels)}], missing, modified, embedded}",
has_doc,
list
),
@@ -1011,7 +1011,14 @@ fn list(s: &mut Session, p: &Value) -> Result<Value> {
}
let (link, mut row) = match &n.kind {
NodeKind::Image(im) => {
(im.link.as_ref(), json!({ "format": format_label(&st.doc, im), "pixelWidth": im.width, "pixelHeight": im.height }))
let mut row = json!({ "format": format_label(&st.doc, im), "pixelWidth": im.width, "pixelHeight": im.height });
// Only an image that could be past the decode allowance (at 16 bytes a pixel, the
// most a decoder gives) has its header read for this.
let large = im.width as u64 * im.height as u64 > fileio::MAX_RASTER_ALLOC / 16;
if let Some(note) = st.doc.images.get(&im.key).filter(|_| large).and_then(|b| fileio::too_large_note(&b.bytes)) {
row["note"] = json!(note);
}
(im.link.as_ref(), row)
}
NodeKind::PlacedDocument(p) => (Some(&p.link), document_row(p)),
_ => continue,
+12 -9
View File
@@ -18,6 +18,7 @@ use vectorcraft_geom::{Affine, PathData, Point, Vec2};
use super::edit::selected_roots;
use super::expand::gradient_sampler;
use super::pathops::Beside;
use super::*;
pub fn specs() -> Vec<CommandSpec> {
@@ -360,14 +361,11 @@ fn has_mesh(s: &Session) -> std::result::Result<(), String> {
/// Wrap `roots` (paint order) into a new node built by `make`, placed where the topmost root was.
fn wrap(d: &mut Document, sel: &mut Selection, roots: &[NodeId], make: impl FnOnce(NodeId, Vec<Arc<Node>>) -> Node) -> Result<NodeId> {
let top = *roots.last().ok_or_else(|| EngineError::Other("nothing to wrap".into()))?;
let (par, idx, _) = d.position(top).ok_or(EngineError::NoNode(top))?;
let nodes: Vec<Arc<Node>> = roots.iter().filter_map(|id| d.node(*id).cloned()).map(Arc::new).collect();
let id = d.alloc_id();
d.insert(par, idx + 1, make(id, nodes))?;
for r in roots {
d.remove(*r)?;
if roots.is_empty() {
return Err(EngineError::Other("nothing to wrap".into()));
}
let id = d.alloc_id();
d.wrap(roots, |nodes| make(id, nodes))?;
sel.set([id]);
Ok(id)
}
@@ -546,6 +544,7 @@ fn blend_release(s: &mut Session, _: &Value) -> Result<Value> {
let blends = selected_of(s, is_blend);
let (ids, spines, groups) = s.edit("Release Blend", |d, sel| {
let (mut keys, mut spines, mut groups) = (vec![], vec![], vec![]);
let mut released = Beside::replacing(d, &blends);
for b in &blends {
let Some(n) = d.node(*b).cloned() else { continue };
let NodeKind::Blend { children, spec } = &n.kind else { continue };
@@ -572,8 +571,9 @@ fn blend_release(s: &mut Session, _: &Value) -> Result<Value> {
groups.push(g.id);
nodes = vec![g];
}
replace_with(d, *b, nodes)?;
released.put(d, *b, nodes)?;
}
released.finish(d)?;
if groups.is_empty() {
sel.set(spines.iter().chain(&keys).copied());
} else {
@@ -1171,6 +1171,7 @@ fn env_release(s: &mut Session, _: &Value) -> Result<Value> {
let envs = selected_of(s, is_envelope);
let ids = s.edit("Release Envelope", |d, sel| {
let mut out = vec![];
let mut released = Beside::replacing(d, &envs);
for e in &envs {
let Some(n) = d.node(*e).cloned() else { continue };
let NodeKind::Envelope { content, kind, .. } = &n.kind else { continue };
@@ -1179,8 +1180,10 @@ fn env_release(s: &mut Session, _: &Value) -> Result<Value> {
shape.id = d.alloc_id();
nodes.push(shape);
}
out.extend(replace_with(d, *e, nodes)?);
out.extend(nodes.iter().map(|c| c.id));
released.put(d, *e, nodes)?;
}
released.finish(d)?;
sel.set(out.iter().copied());
Ok(out)
})?;
+21 -13
View File
@@ -443,9 +443,10 @@ fn rasterize(s: &mut Session, p: &Value) -> Result<Value> {
.map(|(bp, rule)| (PathData::from_bezpath(&bp), rule));
let tmp = isolated_doc(&st.doc, nodes);
let (png, w, h) = render_png(&tmp, region, scale, &raster.render_options(RasterFormat::Png), look.color_model)?;
let top = *roots.last().ok_or_else(|| bad(C, "nothing selected"))?;
if roots.is_empty() {
return Err(bad(C, "nothing selected"));
}
let id = s.edit("Rasterize", |d, sel| {
let (par, idx, _) = d.position(top).ok_or(EngineError::NoNode(top))?;
let key = unique_key(d, "raster");
d.images.insert(key.clone(), vectorcraft_doc::ImageBlob::new("image/png", png));
let id = d.alloc_id();
@@ -455,11 +456,7 @@ fn rasterize(s: &mut Session, p: &Value) -> Result<Value> {
if let Some((path, rule)) = clip {
node = super::rasterfx::clip_group(d, path, rule, node);
}
let id = node.id;
d.insert(par, idx + 1, node)?;
for r in &roots {
d.remove(*r)?;
}
let id = d.wrap(&roots, |_| node)?;
sel.set([id]);
Ok(id)
})?;
@@ -625,7 +622,18 @@ fn trim_image(s: &mut Session, id: NodeId, im: ImageObject) -> Result<Value> {
const C: &str = "object.cropImage";
let st = s.doc()?;
let blob = st.doc.images.get(&im.key).ok_or_else(|| bad(C, "the image's pixels are missing"))?;
let px = image::load_from_memory(&blob.bytes).map_err(|_| bad(C, "the image's pixels can't be read"))?.to_rgba8();
// A CMYK image (kept as its ink amounts) has no alpha: nothing to cut.
if blob.is_cmyk() {
return Ok(json!({ "id": id.0, "width": im.width, "height": im.height, "trimmed": false }));
}
// Print rasters run to gigabytes decoded: the same allowance opening them has.
let mut reader = image::ImageReader::new(std::io::Cursor::new(blob.bytes.as_slice()))
.with_guessed_format()
.map_err(|_| bad(C, "the image's pixels can't be read"))?;
let mut limits = image::Limits::default();
limits.max_alloc = Some(crate::cmd::fileio::MAX_RASTER_ALLOC);
reader.limits(limits);
let px = reader.decode().map_err(|e| bad(C, format!("the image's pixels can't be read: {e}")))?.to_rgba8();
let (w, h) = px.dimensions();
let (mut x0, mut y0, mut x1, mut y1) = (w, h, 0, 0);
for (x, y, p) in px.enumerate_pixels() {
@@ -818,7 +826,7 @@ fn convert_to_shape(s: &mut Session, _: &Value) -> Result<Value> {
fn convert_to_artboards(s: &mut Session, _: &Value) -> Result<Value> {
let roots = selected_roots(s)?;
let n = s.edit("Convert to Artboards", |d, sel| {
let mut n = 0;
let mut converted = vec![];
for id in &roots {
let Some(b) = d.node(*id).and_then(|n| n.geometric_bounds()) else { continue };
if b.width() <= 0.0 || b.height() <= 0.0 {
@@ -832,14 +840,14 @@ fn convert_to_artboards(s: &mut Session, _: &Value) -> Result<Value> {
show_center_mark: false,
show_cross_hairs: false,
});
d.remove(*id)?;
n += 1;
converted.push(*id);
}
if n == 0 {
if converted.is_empty() {
return Err(EngineError::Other("Convert to Artboards: selection has no area".into()));
}
d.remove_many(&converted)?;
sel.clear();
Ok(n)
Ok(converted.len())
})?;
Ok(json!({ "artboards": n }))
}
+37 -26
View File
@@ -719,42 +719,39 @@ fn compound_make(s: &mut Session, _: &Value) -> Result<Value> {
let ids = selected_roots(s)?;
let Some(backmost) = ids.first().copied() else { return Err(EngineError::Other("nothing selected".into())) };
let id = s.edit("Make Compound Path", |d, sel| {
let appearance = d.node(backmost).ok_or(EngineError::NoNode(backmost))?.appearance.clone();
let mut paths: Vec<Arc<Node>> = vec![];
d.node(backmost).ok_or(EngineError::NoNode(backmost))?;
let mut units: Vec<Vec<Arc<Node>>> = vec![];
let mut appearance = None;
for id in &ids {
let n = d.node(*id).cloned().ok_or(EngineError::NoNode(*id))?;
match &n.kind {
NodeKind::Path { .. } => paths.push(Arc::new(n)),
NodeKind::Compound { children, .. } => paths.extend(children.iter().cloned()),
NodeKind::Group { .. } => {
n.walk(&mut |c| {
if matches!(c.kind, NodeKind::Path { .. }) {
paths.push(Arc::new(c.clone()))
}
});
}
_ => return Err(EngineError::Other("compound paths can only contain paths".into())),
let n = d.node(*id).ok_or(EngineError::NoNode(*id))?;
if !matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. } | NodeKind::Group { .. }) {
return Err(EngineError::Other("compound paths can only contain paths".into()));
}
compound_members(n, &mut appearance, &mut units);
}
let cid = d.alloc_id();
let mut c = Node::new(cid, NodeKind::Compound { children: vec![], rule: FillRule::NonZero });
c.appearance = appearance;
c.appearance = appearance.unwrap_or_default();
let ch = c.children_mut().ok_or(EngineError::NoNode(cid))?;
// The paths in front run against the backmost one, so where they overlap it they cut holes
// under the non-zero fill rule (#1197).
// under the non-zero fill rule (#1197). A compound path's paths turn together, by its
// first: its own holes (a letter's counters) stay holes.
let direction = |n: &Node| n.path_data().and_then(|pd| pd.subpaths.first()).map_or(0.0, |sp| sp.signed_area().signum());
let back = paths.first().map_or(0.0, |p| direction(p));
for (i, mut p) in paths.into_iter().enumerate() {
let pn = Arc::make_mut(&mut p);
pn.appearance = Appearance::default().into();
let flip = i > 0 && back != 0.0 && direction(pn) == back;
if let NodeKind::Path { path, live, .. } = &mut pn.kind {
*live = None;
if flip {
path.reverse();
let first = |unit: &[Arc<Node>]| unit.first().map_or(0.0, |p| direction(p));
let back = units.first().map_or(0.0, |u| first(u));
for (i, unit) in units.into_iter().enumerate() {
let flip = i > 0 && back != 0.0 && first(&unit) == back;
for mut p in unit {
let pn = Arc::make_mut(&mut p);
pn.appearance = Appearance::default().into();
if let NodeKind::Path { path, live, .. } = &mut pn.kind {
*live = None;
if flip {
path.reverse();
}
}
ch.push(p);
}
ch.push(p);
}
d.wrap(&ids, |_| c)?;
sel.set([cid]);
@@ -763,6 +760,20 @@ fn compound_make(s: &mut Session, _: &Value) -> Result<Value> {
Ok(json!({ "id": id.0 }))
}
/// The paths in `n` (a path, a compound path, or a group searched in depth) onto `out`, in paint
/// order: each path alone, a compound path's paths together. Into `paint` goes the appearance of
/// the backmost found so far: the path's own, or its compound path's, which is what painted it. A
/// group has no paint of its own to give: a group of outlined type made a compound path that drew
/// nothing.
fn compound_members(n: &Node, paint: &mut Option<vectorcraft_doc::Shared<Appearance>>, out: &mut Vec<Vec<Arc<Node>>>) {
match (&n.kind, n.children()) {
(NodeKind::Path { .. }, _) => out.push(vec![Arc::new(n.clone())]),
(NodeKind::Compound { .. }, Some(paths)) if !paths.is_empty() => out.push(paths.clone()),
(_, children) => return children.into_iter().flatten().for_each(|c| compound_members(c, paint, out)),
}
paint.get_or_insert_with(|| n.appearance.clone());
}
/// Is `n` a compound path to release: a compound path, or a path of several subpaths (an SVG `d`
/// with several `M`s, a PDF path), which is one in Illustrator too (#1163)?
fn releases(n: &Node) -> bool {
+10 -6
View File
@@ -13,6 +13,7 @@ use vectorcraft_color::BlendMode;
use vectorcraft_doc::{Document, Knockout, Node, NodeId, OpacityMask, Selection};
use super::maskedit::{begin, finish, mask_group, mask_parts, show_editing};
use super::pathops::{Beside, separate};
use super::*;
use crate::EngineError;
@@ -189,6 +190,9 @@ fn make(s: &mut Session, p: &Value) -> Result<Value> {
// Several objects are grouped so they share one mask.
let target = if let [one] = art {
*one
} else if separate(d, art) {
let gid = d.alloc_id();
d.wrap(art, |children| Node::group(gid, children))?
} else {
let last = art[art.len() - 1];
let (par, idx, _) = d.position(last).ok_or(EngineError::NoNode(last))?;
@@ -223,16 +227,16 @@ fn release(s: &mut Session, p: &Value) -> Result<Value> {
// Leave mask editing first: its art goes back into the mask, which is released below.
finish(d, sel);
let mut out = vec![];
let mut released = Beside::above(d, &ids);
for id in &ids {
let Some(m) = d.node_mut(*id).and_then(|n| n.extras_mut().mask.take()) else { continue };
let (par, idx, _) = d.position(*id).ok_or(EngineError::NoNode(*id))?;
out.push(*id);
for (k, part) in mask_parts(&m.art).iter().enumerate() {
// Fresh ids: copies of a masked object share the ids inside their mask art.
let art = d.reid(part);
out.push(d.insert(par, idx + 1 + k, art)?);
}
// Fresh ids: copies of a masked object share the ids inside their mask art.
let parts: Vec<Node> = mask_parts(&m.art).iter().map(|part| d.reid(part)).collect();
out.extend(parts.iter().map(|p| p.id));
released.put(d, *id, parts)?;
}
released.finish(d)?;
sel.set(out);
Ok(())
})?;
+2 -11
View File
@@ -136,10 +136,7 @@ pub(crate) fn artboard_copy(s: &mut Session, p: &Value, cut: bool) -> Result<Val
// Its guides go with it.
let gone = d.artboards.remove(i).id;
d.retain_guides(sel, |_, g| g.artboard != Some(gone));
for id in &art {
// Always there: none of the art is inside another of it.
let _ = d.remove(*id);
}
d.remove_many(&art)?;
sel.prune(d);
Ok(())
})?;
@@ -161,13 +158,7 @@ pub(crate) fn copy_artboard(d: &mut vectorcraft_doc::Document, i: usize, dv: Vec
if let Some(id) = d.artboards.get(index).map(|a| a.id) {
d.copy_artboard_guides(src.id, id, dv);
}
let mut copies = Vec::with_capacity(art.len());
for id in art {
let (Some((parent, at, _)), Some(n)) = (d.position(*id), d.node(*id).cloned()) else { continue };
let mut c = d.reid(&n);
c.transform(Affine::translate(dv), sc);
copies.push(d.insert(parent, at + 1, c)?);
}
let copies = super::edit::copy_above(d, art, |_, _, c| c.transform(Affine::translate(dv), sc))?;
Ok((index, copies))
}
+7 -2
View File
@@ -7,6 +7,7 @@ use vectorcraft_doc::{NodeId, NodeKind, Scaling};
use vectorcraft_geom::{AnchorKind, PathData, Point, SubPath, Vec2};
use super::create::anchor_from_json;
use super::pathops::Beside;
use super::*;
use crate::EngineError;
@@ -466,6 +467,7 @@ pub(crate) fn delete_anchors(s: &mut Session, _: &Value) -> Result<Value> {
let segments = st.selection.segments.clone();
s.edit("Clear", |d, selection| {
let mut survivors = vec![];
let mut emptied = Beside::replacing(d, &sel.keys().copied().collect::<Vec<_>>());
for (id, set) in &sel {
let remove_node = {
let path = path_mut(d, *id)?;
@@ -499,11 +501,12 @@ pub(crate) fn delete_anchors(s: &mut Session, _: &Value) -> Result<Value> {
path.subpaths.is_empty()
};
if remove_node {
d.remove(*id)?;
emptied.put(d, *id, vec![])?;
} else if segments.contains_key(id) {
survivors.push(*id);
}
}
emptied.finish(d)?;
// Another Delete removes the remaining path after a segment cut. Anchor Delete keeps
// its existing deselection behavior.
selection.set(survivors);
@@ -625,11 +628,12 @@ fn cut_at_anchors(s: &mut Session, _: &Value) -> Result<Value> {
}
let ids = s.edit("Cut Path", |d, sel| {
let (mut all, mut picked) = (vec![], vec![]);
let mut cut = Beside::replacing(d, &cuts.iter().map(|(id, ..)| *id).collect::<Vec<_>>());
for (id, subs, starts) in cuts {
// A path of one subpath becomes one path per piece (the first keeps the id); the
// pieces of a compound shape stay subpaths of it.
if d.node(id).and_then(|n| n.path_data()).is_some_and(|pd| pd.subpaths.len() == 1) {
let ids = super::draw2::replace_with_pieces(d, id, subs.into_iter().map(PathData::single).collect())?;
let ids = super::draw2::replace_with_pieces(d, &mut cut, id, subs.into_iter().map(PathData::single).collect())?;
picked.extend(ids.iter().zip(&starts).filter(|(_, s)| **s).map(|(id, _)| (*id, (0, 0))));
all.extend(ids);
} else {
@@ -638,6 +642,7 @@ fn cut_at_anchors(s: &mut Session, _: &Value) -> Result<Value> {
all.push(id);
}
}
cut.finish(d)?;
// Each cut leaves one of its two coincident anchors selected, so a drag pulls the ends apart.
sel.clear();
for (id, a) in picked {
+86 -22
View File
@@ -286,6 +286,73 @@ fn shape_node_styled(d: &mut Document, path: PathData, style: &Style) -> Node {
n
}
/// Whether `ids` are separate objects, as [`Document::remove_many`] and [`Document::insert_beside`]
/// take them: each one is in the tree and listed once, and none lies inside another listed one.
pub(crate) fn separate(d: &Document, ids: &[NodeId]) -> bool {
let paths = d.index_paths(ids.iter().copied());
let mut found: Vec<_> = ids.iter().filter_map(|id| paths.get(id)).collect();
found.sort_unstable();
found.len() == ids.len() && found.windows(2).all(|w| !w[1].starts_with(w[0]))
}
/// Lists of nodes that go in place of objects, or directly above them; an empty list in place of
/// an object removes it. When the objects are [`separate`], [`Beside::put`] holds each list and
/// leaves the tree as it is, and [`Beside::finish`] inserts them all in one pass over the children
/// of each parent ([`Document::insert_beside`]). Otherwise [`Beside::put`] inserts each list at
/// once, where its object is at that moment.
pub(crate) struct Beside {
replace: bool,
waiting: Option<Vec<(NodeId, Vec<Node>)>>,
}
impl Beside {
/// Lists that go in place of objects among `ids`.
pub(crate) fn replacing(d: &Document, ids: &[NodeId]) -> Self {
Beside { replace: true, waiting: separate(d, ids).then(Vec::new) }
}
/// Lists that go directly above objects among `ids`.
pub(crate) fn above(d: &Document, ids: &[NodeId]) -> Self {
Beside { replace: false, waiting: separate(d, ids).then(Vec::new) }
}
/// Put `nodes`, in their order, in place of object `id` or directly above it.
pub(crate) fn put(&mut self, d: &mut Document, id: NodeId, nodes: Vec<Node>) -> Result<()> {
if let Some(waiting) = &mut self.waiting {
waiting.push((id, nodes));
return Ok(());
}
let (parent, idx, _) = d.position(id).ok_or(EngineError::NoNode(id))?;
let at = if self.replace {
d.remove(id)?;
idx
} else {
idx + 1
};
for (k, n) in nodes.into_iter().enumerate() {
d.insert(parent, at + k, n)?;
}
Ok(())
}
/// Insert the lists that [`Beside::put`] held.
pub(crate) fn finish(self, d: &mut Document) -> Result<()> {
match self.waiting {
Some(waiting) if !waiting.is_empty() => Ok(d.insert_beside(waiting, self.replace)?),
_ => Ok(()),
}
}
}
/// Remove `ids` through a [`Beside`], which removes them in one pass when they are [`separate`].
pub(crate) fn remove_each(d: &mut Document, ids: &[NodeId]) -> Result<()> {
let mut gone = Beside::replacing(d, ids);
for id in ids {
gone.put(d, *id, vec![])?;
}
gone.finish(d)
}
// ---------- Pathfinder ----------
fn pf_label(op: PathfinderOp) -> &'static str {
@@ -305,7 +372,9 @@ fn pf_label(op: PathfinderOp) -> &'static str {
fn run_pf(s: &mut Session, op: PathfinderOp) -> Result<Value> {
let roots = selected_roots(s)?;
let Some(&top) = roots.last() else { return Err(EngineError::Other("nothing selected".into())) };
if roots.is_empty() {
return Err(EngineError::Other("nothing selected".into()));
}
let shape_mode =
matches!(op, PathfinderOp::Unite | PathfinderOp::MinusFront | PathfinderOp::Intersect | PathfinderOp::Exclude | PathfinderOp::MinusBack);
let label = pf_label(op);
@@ -371,7 +440,6 @@ fn run_pf(s: &mut Session, op: PathfinderOp) -> Result<Value> {
if results.iter().all(|r| r.path.is_empty()) {
return Err(EngineError::Other(format!("{label} produced an empty result")));
}
let (par, idx, _) = d.position(top).ok_or(EngineError::NoNode(top))?;
let new_node = if shape_mode {
let r =
results.into_iter().find(|r| !r.path.is_empty()).ok_or_else(|| EngineError::Other(format!("{label} produced an empty result")))?;
@@ -403,11 +471,7 @@ fn run_pf(s: &mut Session, op: PathfinderOp) -> Result<Value> {
let gid = d.alloc_id();
Node::group(gid, children)
};
let nid = new_node.id;
d.insert(par, idx + 1, new_node)?;
for id in &roots {
d.remove(*id)?;
}
let nid = d.wrap(&roots, |_| new_node)?;
sel.set([nid]);
Ok(vec![nid])
})?;
@@ -433,7 +497,7 @@ fn offset_path(s: &mut Session, p: &Value) -> Result<Value> {
let miter = num_param(p, "miterLimit").unwrap_or(4.0).clamp(1.0, 500.0);
let roots = selected_roots(s)?;
let ids = s.edit("Offset Path", |d, sel| {
let mut out = vec![];
let (mut out, mut above) = (vec![], vec![]);
for id in &roots {
let Some(n) = d.node(*id).cloned() else { continue };
let mut lv = vec![];
@@ -460,12 +524,13 @@ fn offset_path(s: &mut Session, p: &Value) -> Result<Value> {
let gid = d.alloc_id();
Node::group(gid, made.into_iter().map(Arc::new).collect())
};
let (par, idx, _) = d.position(*id).ok_or(EngineError::NoNode(*id))?;
out.push(d.insert(par, idx + 1, new)?);
out.push(new.id);
above.push((*id, vec![new]));
}
if out.is_empty() {
return Err(EngineError::Other("Offset Path: select paths".into()));
}
d.insert_beside(above, false)?;
sel.set(out.iter().copied());
Ok(out)
})?;
@@ -614,9 +679,8 @@ pub(crate) fn replace_leaves(d: &mut Document, root: NodeId, mut f: impl FnMut(&
let (mut replacement, mut changed) = (root, 0);
for l in lv {
let Some(new) = f(d, &l) else { continue };
let (par, idx, _) = d.position(l.id).ok_or(EngineError::NoNode(l.id))?;
let nid = d.insert(par, idx, new)?;
d.remove(l.id)?;
let nid = new.id;
*d.node_mut(l.id).ok_or(EngineError::NoNode(l.id))? = new;
changed += 1;
if l.id == root {
replacement = nid;
@@ -840,12 +904,13 @@ fn clean_up(s: &mut Session, p: &Value) -> Result<Value> {
return Ok(json!({ "removed": 0 }));
}
s.edit("Clean Up", |d, _| {
let mut gone = Beside::replacing(d, &found);
for id in &found {
if d.node(*id).is_some() {
d.remove(*id)?;
gone.put(d, *id, vec![])?;
}
}
Ok(())
gone.finish(d)
})?;
Ok(json!({ "removed": found.len() }))
}
@@ -885,6 +950,7 @@ fn divide_objects_below(s: &mut Session, _: &Value) -> Result<Value> {
&& d.node(*id).and_then(Node::geometric_bounds).is_some_and(|b| b.intersect(cb).area() > 0.0)
});
let mut out = vec![];
let mut cut = Beside::replacing(d, &[targets.as_slice(), &[cutter_id]].concat());
for t in targets {
let Some(n) = d.node(t).cloned() else { continue };
let Some((tp, tr)) = node_path(&n) else { continue };
@@ -893,14 +959,12 @@ fn divide_objects_below(s: &mut Session, _: &Value) -> Result<Value> {
if inside.is_empty() || outside.is_empty() {
continue;
}
let (par, idx, _) = d.position(t).ok_or(EngineError::NoNode(t))?;
d.remove(t)?;
for (k, piece) in [outside, inside].into_iter().enumerate() {
let node = shape_node(d, piece, Some(&n));
out.push(d.insert(par, idx + k, node)?);
}
let pieces: Vec<Node> = [outside, inside].into_iter().map(|piece| shape_node(d, piece, Some(&n))).collect();
out.extend(pieces.iter().map(|p| p.id));
cut.put(d, t, pieces)?;
}
d.remove(cutter_id)?;
cut.put(d, cutter_id, vec![])?;
cut.finish(d)?;
sel.set(out.iter().copied());
Ok(out)
})?;
+10 -13
View File
@@ -18,6 +18,7 @@ use vectorcraft_doc::{Document, Node, NodeId, NodeKind, Selection};
use vectorcraft_geom::Rect;
use super::edit::selected_roots;
use super::pathops::Beside;
use super::*;
pub fn specs() -> Vec<CommandSpec> {
@@ -633,15 +634,12 @@ fn make_repeat(s: &mut Session, p: &Value, label: &str, make: impl Fn(Vec<Arc<No
return Ok(json!({ "id": r.0 }));
}
let roots = roots(s, p)?;
let Some(&top) = roots.last() else { return Err(EngineError::Other("select the art to repeat".into())) };
if roots.is_empty() {
return Err(EngineError::Other("select the art to repeat".into()));
}
let id = s.edit(label, |d, sel| {
let (par, idx, _) = d.position(top).ok_or(EngineError::NoNode(top))?;
let nodes: Vec<Arc<Node>> = roots.iter().filter_map(|id| d.node(*id).cloned()).map(Arc::new).collect();
let id = d.alloc_id();
d.insert(par, idx + 1, Node::new(id, NodeKind::Repeat(make(nodes))))?;
for r in &roots {
d.remove(*r)?;
}
d.wrap(&roots, |nodes| Node::new(id, NodeKind::Repeat(make(nodes))))?;
sel.set([id]);
Ok(id)
})?;
@@ -682,15 +680,14 @@ fn repeat_release(s: &mut Session, _: &Value) -> Result<Value> {
let reps = selected_repeats(s);
let ids = s.edit("Release Repeat", |d, sel| {
let mut out = vec![];
let mut released = Beside::replacing(d, &reps);
for r in &reps {
let Some(n) = d.node(*r).cloned() else { continue };
let (par, idx, _) = d.position(*r).ok_or(EngineError::NoNode(*r))?;
d.remove(*r)?;
for (k, c) in n.children().into_iter().flatten().enumerate() {
out.push(c.id);
d.insert(par, idx + k, (**c).clone())?;
}
let art: Vec<Node> = n.children().into_iter().flatten().map(|c| (**c).clone()).collect();
out.extend(art.iter().map(|c| c.id));
released.put(d, *r, art)?;
}
released.finish(d)?;
sel.set(out.iter().copied());
Ok(out)
})?;
+2 -1
View File
@@ -183,7 +183,8 @@ fn load(p: &Value, cmd: &str, board: Option<Rect>) -> Result<Loaded> {
let (sx, sy) = pt_per_px(img.ppi);
let natural = Rect::new(0.0, 0.0, img.width as f64 * sx, img.height as f64 * sy);
let link = src.path.map(|path| super::links::link_info(path, &src.bytes));
return Ok(Loaded { name, format, art: Art::Image(img), natural, warnings: vec![], link, board: None });
let warnings = fileio::too_large_note(&img.blob.bytes).into_iter().collect();
return Ok(Loaded { name, format, art: Art::Image(img), natural, warnings, link, board: None });
}
let anchored = format.id == "dxf" && (opts.dxf.fit || !opts.dxf.center);
let (mut doc, warnings) = match format.id {
+8 -6
View File
@@ -1,6 +1,7 @@
//! Shaper compositions are groups of generated fills/strokes with transparent, editable source
//! art retained underneath. Recipes select topology regions; source edits re-evaluate them in
//! the same undo transaction. Rendering and exporters only see ordinary groups and paths.
use super::pathops::Beside;
use super::*;
use serde_json::{Value, json};
use std::{collections::BTreeMap, sync::Arc};
@@ -380,7 +381,10 @@ pub(crate) fn refresh(before: &Document, d: &mut Document) -> Result<()> {
ids.push(n.id)
}
});
for id in ids {
// Groups whose source art is all gone are removed through `emptied`, which is made when the
// first one is found.
let mut emptied: Option<Beside> = None;
for &id in &ids {
let Some(current) = d.node(id).cloned() else { continue };
let Some(old) = before.node(id) else { continue };
let src = sources(&current);
@@ -395,7 +399,7 @@ pub(crate) fn refresh(before: &Document, d: &mut Document) -> Result<()> {
continue;
}
if src.is_empty() {
d.remove(id)?;
emptied.get_or_insert_with(|| Beside::replacing(d, &ids)).put(d, id, vec![])?;
continue;
}
let map = map_of(&src)?;
@@ -494,7 +498,7 @@ pub(crate) fn refresh(before: &Document, d: &mut Document) -> Result<()> {
*ch = children;
}
}
Ok(())
emptied.map_or(Ok(()), |e| e.finish(d))
}
fn candidates(s: &Session, p: &Value, points: &[Point], tolerance: f64) -> Result<Vec<NodeId>> {
@@ -670,9 +674,7 @@ fn scribble(s: &mut Session, p: &Value) -> Result<Value> {
let mut group = Node::group(id, children);
group.name = Some("Shaper Group".into());
group.extras_mut().shaper = Some(Box::new(spec));
for id in &roots {
d.remove(*id)?;
}
d.remove_many(&roots)?;
d.insert(parent, index.saturating_sub(earlier), group)?;
sel.set([id]);
Ok(id)
+53
View File
@@ -1596,6 +1596,59 @@ fn inspect_reports_compound_paint_and_blend() {
assert!(plain.get("blend").is_none(), "Normal is omitted: {plain}");
}
/// A compound path made of a group (outlined type is one) takes the paint of the backmost path in
/// it, not the group's own (none): it drew nothing. A compound path in the group gives the paint
/// that painted its paths.
#[test]
fn compound_of_a_group_takes_its_backmost_paths_paint() {
let paint = |s: &Session, id: u64| (*s.doc().unwrap().doc.node(NodeId(id)).unwrap().appearance).clone();
let made = |s: &mut Session, cmd: &str| s.execute(cmd, &json!({})).unwrap()["id"].as_u64().unwrap();
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 40.0, 40.0);
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
let b = rect(&mut s, 10.0, 10.0, 10.0, 10.0);
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
let red = paint(&s, a.0);
assert_ne!(red, paint(&s, b.0));
assert_ne!(red, Default::default());
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
made(&mut s, "object.group");
let c = made(&mut s, "object.compoundPath.make");
assert_eq!(paint(&s, c), red, "the backmost path's paint");
// Grouped again and joined with a path in front: the paint the compound path gave its paths.
let g = made(&mut s, "object.group");
let front = rect(&mut s, 20.0, 20.0, 5.0, 5.0);
s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap();
s.execute("select.set", &json!({"ids": [g, front.0]})).unwrap();
let c = made(&mut s, "object.compoundPath.make");
assert_eq!(paint(&s, c), red);
assert_eq!(s.doc().unwrap().doc.node(NodeId(c)).unwrap().children().unwrap().len(), 3);
}
/// Compound paths joined into one keep their own holes: each one's paths turn together, so the
/// counters of outlined letters stay open (they filled in when every path was turned alone).
#[test]
fn joined_compound_paths_keep_their_holes() {
let made = |s: &mut Session, cmd: &str| s.execute(cmd, &json!({})).unwrap()["id"].as_u64().unwrap();
let mut s = session();
let mut rings = vec![];
for x in [0.0, 100.0, 200.0] {
let (outer, inner) = (rect(&mut s, x, 0.0, 40.0, 40.0), rect(&mut s, x + 10.0, 10.0, 10.0, 10.0));
s.execute("select.set", &json!({"ids": [outer.0, inner.0]})).unwrap();
rings.push(made(&mut s, "object.compoundPath.make"));
}
s.execute("select.set", &json!({"ids": rings})).unwrap();
made(&mut s, "object.group");
let c = made(&mut s, "object.compoundPath.make");
let d = &s.doc().unwrap().doc;
let turns: Vec<f64> =
d.node(NodeId(c)).unwrap().children().unwrap().iter().map(|p| p.path_data().unwrap().subpaths[0].signed_area().signum()).collect();
assert_eq!(turns.len(), 6);
for ring in turns.chunks(2) {
assert_eq!(ring[0], -ring[1], "a hole runs against its outline: {turns:?}");
}
// The rings in front run against the backmost one (#1197).
assert_eq!((turns[2], turns[4]), (-turns[0], -turns[0]), "{turns:?}");
}
/// `document.node {summary: true}` answers the `document.inspect` shape for one node:
/// the same fields the full-tree summary carries, without serializing the whole tree.
#[test]
+19
View File
@@ -398,6 +398,25 @@ fn new_symbol_replaces_selection_with_instance_of_same_bounds() {
assert_eq!(s.doc().unwrap().doc.symbols.len(), 1);
}
/// New Symbol given `ids` that list an object and then the group that holds it puts the instance
/// where the group was and removes both, as removing one object at a time does.
#[test]
fn new_symbol_of_an_object_and_the_group_that_holds_it_keeps_order_and_ids() {
let mut s = session();
let (a, b) = (rect(&mut s, 0.0, 0.0, 10.0, 10.0), rect(&mut s, 100.0, 0.0, 10.0, 10.0));
select(&mut s, &[a, b]);
let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
let c = rect(&mut s, 200.0, 0.0, 10.0, 10.0);
let before = s.doc().unwrap().doc.clone();
let r = s.execute("symbol.new", &json!({"name": "Pair", "ids": [a.0, group.0]})).unwrap();
let inst = NodeId(r["id"].as_u64().unwrap());
let ids = |n: &Node| n.children().unwrap().iter().map(|c| c.id).collect::<Vec<_>>();
assert_eq!(ids(&s.doc().unwrap().doc.layers[0]), [inst, c]);
assert_eq!(s.doc().unwrap().selection.objects, [inst]);
s.execute("edit.undo", &json!({})).unwrap();
assert!(*s.doc().unwrap().doc == *before, "Undo gives back the document");
}
#[test]
fn place_and_break_link_round_trip_geometry() {
let mut s = session();
+17
View File
@@ -310,6 +310,23 @@ fn flatten_is_one_undo_step() {
assert!(!exists(&s, a));
}
/// Flattening a document for export in which two objects have the same id (a damaged file)
/// removes both objects and puts one group in their place.
#[test]
fn flattening_objects_that_share_an_id_removes_both() {
let _settings = settings_lock();
let mut s = session();
let a = rect(&mut s, 10.0, 10.0, 100.0, 100.0, "#ff0000");
let b = rect(&mut s, 60.0, 60.0, 100.0, 100.0, "#0000ff");
run(&mut s, "transparency.set", json!({"ids": [a, b], "opacity": 50}));
let mut doc = (*s.doc().unwrap().doc).clone();
doc.node_mut(NodeId(b)).unwrap().id = NodeId(a);
let flat = crate::cmd::flatten::flatten_document(&doc, &crate::cmd::FlattenOptions::default()).unwrap().unwrap();
let art = flat.layers[0].children().unwrap();
assert_eq!(art.len(), 1, "one group where the two objects were");
assert!(matches!(art[0].kind, NodeKind::Group { .. }) && art[0].id != NodeId(a));
}
#[test]
fn objects_without_transparency_stay_unless_outlined() {
let _settings = settings_lock();
+292 -1
View File
@@ -6,7 +6,7 @@ use std::sync::Arc;
use std::time::Duration;
use serde_json::{Value, json};
use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind};
use vectorcraft_doc::{Appearance, Document, LAYER_COLORS, LayerColor, Node, NodeId, NodeKind};
use vectorcraft_geom::{FillRule, Rect, shapes};
use vectorcraft_tools::{Mods, PointerEvent, PointerKind};
@@ -112,6 +112,28 @@ fn delete_of_100000_objects_finishes_within_20_s() {
undo_gives_back(&mut s, &before);
}
#[test]
fn delete_selection_of_100000_rows_finishes_within_20_s() {
let s = session(100_000, square);
let (before, ids) = (s.doc().unwrap().doc.clone(), layer(&s, 0));
let (mut s, r) = run_soon(s, "layer.delete", json!({"ids": ids}));
assert_eq!(r["deleted"], json!(100_000));
assert!(layer(&s, 0).is_empty());
assert!(selected(&s, &[]));
undo_gives_back(&mut s, &before);
}
#[test]
fn clean_up_of_100000_unpainted_paths_finishes_within_20_s() {
let s = session(100_000, |d, k| Node::path(d.alloc_id(), shapes::rectangle(square_at(k)), Appearance::default()));
let before = s.doc().unwrap().doc.clone();
let (mut s, r) = run_soon(s, "object.path.cleanUp", json!({}));
assert_eq!(r["removed"], json!(100_000));
assert!(layer(&s, 0).is_empty());
assert!(selected(&s, &[]));
undo_gives_back(&mut s, &before);
}
#[test]
fn group_of_50000_objects_finishes_within_20_s() {
let s = session(50_000, square);
@@ -184,6 +206,21 @@ fn transform_each_with_copy_of_50000_objects_finishes_within_20_s() {
undo_gives_back(&mut s, &before);
}
#[test]
fn offset_path_of_50000_objects_finishes_within_20_s() {
let s = session(50_000, square);
let (before, ids, first) = (s.doc().unwrap().doc.clone(), layer(&s, 0), s.doc().unwrap().doc.peek_next_id());
let (mut s, r) = run_soon(s, "object.path.offsetPath", json!({"offset": 1}));
// Each offset path goes directly above its square and takes the next id, in the squares' order.
let offsets = ids_from(first, ids.len());
assert!(ids_in(&r) == offsets);
assert!(layer(&s, 0) == in_turn(&ids, &offsets), "each offset path directly above its square");
assert!(selected(&s, &offsets));
let grown = bounds(&s, offsets[1]);
assert!((grown.width() - 12.0).abs() < 1e-6 && (grown.x0 - 19.0).abs() < 1e-6, "{grown:?}");
undo_gives_back(&mut s, &before);
}
#[test]
fn compound_path_of_100000_objects_finishes_within_20_s() {
let s = session(100_000, square);
@@ -211,6 +248,34 @@ fn send_to_current_layer_of_100000_objects_finishes_within_20_s() {
undo_gives_back(&mut s, &before);
}
#[test]
fn row_drag_of_100000_rows_finishes_within_20_s() {
let mut s = session(100_000, square);
let ids = layer(&s, 0);
let to = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap());
let before = s.doc().unwrap().doc.clone();
let (mut s, r) = run_soon(s, "layer.move", json!({"ids": ids, "target": to}));
assert!(ids_in(&r) == ids);
assert!(layer(&s, 0).is_empty());
assert!(children(&s, to) == ids, "the layer holds the rows in their order");
assert!(selected(&s, &ids));
undo_gives_back(&mut s, &before);
}
#[test]
fn merge_selected_of_100000_objects_finishes_within_20_s() {
let mut s = session(100_000, square);
let (from, ids) = (s.doc().unwrap().doc.layers[0].id, layer(&s, 0));
let into = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap());
let before = s.doc().unwrap().doc.clone();
let (mut s, r) = run_soon(s, "layer.merge", json!({"ids": [from, into]}));
assert_eq!(r["id"], json!(into));
assert!(s.doc().unwrap().doc.node(from).is_none(), "the emptied layer goes");
assert!(children(&s, into) == ids, "the layer holds the objects in their order");
assert!(selected(&s, &ids));
undo_gives_back(&mut s, &before);
}
#[test]
fn ungroup_of_25000_groups_finishes_within_20_s() {
// Each group holds two squares, and ungrouping one adds an object to the layer.
@@ -240,6 +305,45 @@ fn compound_path_release_of_25000_compound_paths_finishes_within_20_s() {
undo_gives_back(&mut s, &before);
}
#[test]
fn release_to_layers_of_100000_objects_finishes_within_20_s() {
let s = session(100_000, square);
let doc = &s.doc().unwrap().doc;
let (before, l, ids, first) = (doc.clone(), doc.layers[0].id, layer(&s, 0), doc.peek_next_id());
let (mut s, r) = run_soon(s, "layer.releaseToLayers", json!({"id": l}));
// Each object goes into a sublayer of its own, in their order. The sublayers take the next ids,
// and with Layer 1 counted, sublayer k is named `Layer k + 2` and takes layer color k + 1,
// wrapping around after the last preset.
let subs = ids_from(first, ids.len());
assert!(ids_in(&r) == subs);
assert!(layer(&s, 0) == subs);
let doc = &s.doc().unwrap().doc;
for (k, (sub, id)) in subs.iter().zip(&ids).enumerate() {
let n = doc.node(*sub).unwrap();
assert_eq!(ids_of(n), [*id]);
assert_eq!(n.name.as_deref(), Some(format!("Layer {}", k + 2).as_str()));
assert!(matches!(n.kind, NodeKind::Layer { color: LayerColor::Preset(c), .. } if usize::from(c) == (k + 1) % LAYER_COLORS.len()));
}
assert!(selected(&s, &ids));
undo_gives_back(&mut s, &before);
}
#[test]
fn outline_stroke_of_25000_objects_finishes_within_20_s() {
let s = session(25_000, square);
let (before, first) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().doc.peek_next_id());
let (mut s, r) = run_soon(s, "object.path.outlineStroke", json!({}));
// Each square, filled and stroked, becomes a group of its fill and the outline of its stroke,
// where the square was, and the groups take new ids in the squares' order.
let groups = ids_in(&r);
assert_eq!(groups.len(), 25_000);
assert!(layer(&s, 0) == groups, "each group where its square was");
assert!(groups[0].0 >= first && groups.windows(2).all(|w| w[0] < w[1]));
assert!(groups.iter().all(|g| children(&s, *g).len() == 2));
assert!(selected(&s, &groups));
undo_gives_back(&mut s, &before);
}
/// With Alt held, a Selection tool press on one of 30,000 selected squares, four moves of 20 pt
/// and the release copy the squares once, as one undo step.
#[test]
@@ -339,6 +443,193 @@ fn group_delete_and_duplicate_across_layers_and_inside_a_group_keep_order_and_id
undo_gives_back(&mut s, &before);
}
/// After the Layers panel's Delete Selection, Duplicate Selection, row drags, Collect in New Layer
/// and Merge Selected on rows in two layers and inside a group, the layers hold the rows and the
/// new ones in the order, and with the ids, that each check lists, and Undo gives back the
/// document.
#[test]
fn layers_panel_rows_across_layers_and_inside_a_group_keep_order_and_ids() {
let (mut s, [a, b, c, d, e, f, g, h, group]) = two_layers();
let before = s.doc().unwrap().doc.clone();
let (n, l1, l2) = (before.peek_next_id(), before.layers[0].id.0, before.layers[1].id.0);
let r = s.execute("layer.delete", &json!({"ids": [a, e, h]})).unwrap();
assert_eq!(r["deleted"], 3);
assert_eq!(layers(&s), [json!([b, c, [group, d, f]]), json!([g])]);
assert!(selected(&s, &[NodeId(c), NodeId(g)]));
undo_gives_back(&mut s, &before);
// Each copy goes directly above its row and takes the next id; a layer's copy is renamed.
let r = s.execute("layer.duplicate", &json!({"ids": [a, e, h]})).unwrap();
assert_eq!(r["ids"], json!([n, n + 1, n + 2]));
assert_eq!(layers(&s), [json!([a, n, b, c, [group, d, e, n + 1, f]]), json!([g, h, n + 2])]);
undo_gives_back(&mut s, &before);
let r = s.execute("layer.duplicate", &json!({"ids": [l2]})).unwrap();
assert_eq!(r["ids"], json!([n]));
assert_eq!(layers(&s), [json!([a, b, c, [group, d, e, f]]), json!([g, h]), json!([n + 1, n + 2])]);
assert_eq!(s.doc().unwrap().doc.layers[2].name.as_deref(), Some("Layer 2 copy"));
undo_gives_back(&mut s, &before);
// Rows are dragged below c, then above d in the group, and copies of rows are dragged above g.
let r = s.execute("layer.move", &json!({"ids": [a, e, h], "target": c, "place": "below"})).unwrap();
assert_eq!(r["ids"], json!([a, e, h]));
assert_eq!(layers(&s), [json!([b, a, e, h, c, [group, d, f]]), json!([g])]);
undo_gives_back(&mut s, &before);
s.execute("layer.move", &json!({"ids": [a, g], "target": d, "place": "above"})).unwrap();
assert_eq!(layers(&s), [json!([b, c, [group, d, a, g, e, f]]), json!([h])]);
undo_gives_back(&mut s, &before);
let r = s.execute("layer.move", &json!({"ids": [a, e], "target": g, "place": "above", "copy": true})).unwrap();
assert_eq!(r["ids"], json!([n, n + 1]));
assert_eq!(layers(&s), [json!([a, b, c, [group, d, e, f]]), json!([g, n, n + 1, h])]);
undo_gives_back(&mut s, &before);
// The new layer goes where the topmost row was when that row is in a layer, and on top of the
// layer holding the topmost row's group when it is in a group.
assert_eq!(s.execute("layer.collectInNew", &json!({"ids": [a, e, g]})).unwrap()["id"], json!(n));
assert_eq!(layers(&s), [json!([b, c, [group, d, f]]), json!([[n, a, e, g], h])]);
assert_eq!(s.doc().unwrap().doc.node(NodeId(n)).unwrap().name.as_deref(), Some("Layer 3"));
undo_gives_back(&mut s, &before);
assert_eq!(s.execute("layer.collectInNew", &json!({"ids": [a, e]})).unwrap()["id"], json!(n));
assert_eq!(layers(&s), [json!([b, c, [group, d, f], [n, a, e]]), json!([g, h])]);
undo_gives_back(&mut s, &before);
// Rows merge into the layer listed last, in the stacking order, and so does a merged layer's
// art.
s.execute("layer.merge", &json!({"ids": [e, g, l1]})).unwrap();
assert_eq!(layers(&s), [json!([a, b, c, [group, d, f], e, g]), json!([h])]);
undo_gives_back(&mut s, &before);
s.execute("layer.merge", &json!({"ids": [l1, l2]})).unwrap();
assert_eq!(layers(&s), [json!([a, b, c, [group, d, e, f], g, h])]);
undo_gives_back(&mut s, &before);
}
/// Release to Layers (Sequence on a layer and on a group, Build on a layer) and Flatten Artwork
/// leave the layers, sublayers and objects in the order, and with the ids and names, that each
/// check lists, and Undo gives back the document.
#[test]
fn release_to_layers_and_flatten_artwork_keep_order_and_ids() {
let (mut s, [a, b, c, d, e, f, g, h, group]) = two_layers();
let l2 = s.doc().unwrap().doc.layers[1].id.0;
// Layer 2 also holds a sublayer, on top of g and h.
let sub = s.execute("layer.newSublayer", &json!({"parent": l2})).unwrap()["id"].as_u64().unwrap();
let before = s.doc().unwrap().doc.clone();
let (n, l1) = (before.peek_next_id(), before.layers[0].id.0);
let names = |s: &Session, r: &Value| ids_in(r).iter().map(|id| s.doc().unwrap().doc.node(*id).unwrap().display_name()).collect::<Vec<_>>();
// A layer's objects go into sublayers of their own, below its sublayers.
let r = s.execute("layer.releaseToLayers", &json!({"id": l2})).unwrap();
assert_eq!(r["ids"], json!([n, n + 1]));
assert_eq!(layers(&s), [json!([a, b, c, [group, d, e, f]]), json!([[n, g], [n + 1, h], [sub]])]);
assert_eq!(names(&s, &r), ["Layer 4", "Layer 5"]);
undo_gives_back(&mut s, &before);
// Build: a sublayer holds copies of the objects below its own and a copy of its own, and the
// top one holds the objects.
let r = s.execute("layer.releaseToLayersBuild", &json!({"id": l2})).unwrap();
assert_eq!(r["ids"], json!([n, n + 2]));
assert_eq!(layers(&s), [json!([a, b, c, [group, d, e, f]]), json!([[n, n + 1], [n + 2, g, h], [sub]])]);
assert_eq!(names(&s, &r), ["Layer 4", "Layer 5"]);
undo_gives_back(&mut s, &before);
// A group's objects go into sublayers of its layer, where the group was.
let r = s.execute("layer.releaseToLayers", &json!({"id": group})).unwrap();
assert_eq!(r["ids"], json!([n, n + 1, n + 2]));
assert_eq!(layers(&s), [json!([a, b, c, [n, d], [n + 1, e], [n + 2, f]]), json!([g, h, [sub]])]);
assert_eq!(names(&s, &r), ["Layer 4", "Layer 5", "Layer 6"]);
undo_gives_back(&mut s, &before);
// Flatten Artwork into Layer 1 deletes the two hidden layers and keeps the template layer.
for p in [json!({"top": true, "visible": false}), json!({"top": true, "visible": false}), json!({"top": true, "template": true})] {
s.execute("layer.new", &p).unwrap();
}
let before = s.doc().unwrap().doc.clone();
assert_eq!(s.execute("layer.flatten", &json!({"id": l1})).unwrap()["discarded"], 2);
assert_eq!(layers(&s), [json!([a, b, c, [group, d, e, f], g, h, [sub]]), json!([])]);
undo_gives_back(&mut s, &before);
}
/// Duplicate Artboard and `artboard.move` with `copy` and `moveArt` (the Artboard tool's Alt-drag
/// with Move/Copy Artwork with Artboard on) put a copy of each object on the artboard directly
/// above it, moved with the artboard's copy, and Cut Artboard removes those objects. An object off
/// the artboard stays. The layers then hold the objects in the order, and with the ids, that each
/// check lists, and Undo gives back the document.
#[test]
fn artboard_copies_and_cut_keep_order_and_ids() {
let (mut s, [a, b, c, d, e, f, g, h, group]) = two_layers();
let off = s.execute("shape.rectangle", &json!({"x": 900, "y": 10, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
s.execute("artboard.new", &json!({})).unwrap();
let before = s.doc().unwrap().doc.clone();
let n = before.peek_next_id();
let copies = json!([n, n + 1, n + 2, n + 3, n + 7, n + 8]);
let copied = [json!([a, n, b, n + 1, c, n + 2, [group, d, e, f], [n + 3, n + 4, n + 5, n + 6]]), json!([g, n + 7, h, n + 8, off])];
// The copy of h, the last object on the artboard, sits where h sits, moved by `dx`.
let moved_by = |s: &Session, dx: f64| bounds(s, NodeId(n + 8)) == bounds(s, NodeId(h)) + vectorcraft_geom::Vec2::new(dx, 0.0);
// Duplicate Artboard places the copy 20 pt right of the last artboard.
let right = before.artboards.iter().map(|ab| ab.rect.x1).fold(f64::MIN, f64::max);
assert_eq!(s.execute("artboard.duplicate", &json!({"index": 0, "art": true})).unwrap()["ids"], copies);
assert_eq!(layers(&s), copied);
assert!(moved_by(&s, right + 20.0));
undo_gives_back(&mut s, &before);
let r = s.execute("artboard.move", &json!({"index": 0, "dx": 900, "dy": 0, "copy": true, "moveArt": true})).unwrap();
assert_eq!(r["moved"], copies);
assert_eq!(layers(&s), copied);
assert!(moved_by(&s, 900.0));
undo_gives_back(&mut s, &before);
assert_eq!(s.execute("artboard.cut", &json!({"index": 0, "art": true})).unwrap()["copied"], 6);
assert_eq!(layers(&s), [json!([]), json!([off])]);
undo_gives_back(&mut s, &before);
}
/// After Offset Path, Outline Stroke, Unite and Clean Up of objects in two layers and inside a
/// group, the layers hold the objects and the new ones in the order, and with the ids, that each
/// check lists, and Undo gives back the document.
#[test]
fn path_commands_across_layers_and_inside_a_group_keep_order_and_ids() {
let (mut s, [a, b, c, d, e, f, g, h, group]) = two_layers();
let before = s.doc().unwrap().doc.clone();
let n = before.peek_next_id();
let r = s.execute("object.path.offsetPath", &json!({"offset": 1})).unwrap();
assert_eq!(r["ids"], json!([n, n + 1, n + 2, n + 3, n + 4]));
assert_eq!(layers(&s), [json!([a, n, b, c, n + 1, [group, d, e, n + 2, f]]), json!([g, n + 3, h, n + 4])]);
assert!(selected(&s, &ids_from(n, 5)));
undo_gives_back(&mut s, &before);
// Each object becomes a group of its fill and the outline of its stroke, where it was.
let r = s.execute("object.path.outlineStroke", &json!({})).unwrap();
let [a2, c2, e2, g2, h2] = <[NodeId; 5]>::try_from(ids_in(&r)).unwrap();
assert!(n <= a2.0 && a2 < c2 && c2 < e2 && e2 < g2 && g2 < h2);
assert_eq!(layer(&s, 0), [a2, NodeId(b), c2, NodeId(group)]);
assert_eq!(children(&s, NodeId(group)), [NodeId(d), e2, NodeId(f)]);
assert_eq!(layer(&s, 1), [g2, h2]);
assert!(selected(&s, &[a2, c2, e2, g2, h2]));
undo_gives_back(&mut s, &before);
// The result goes where the topmost object, h, was.
let r = s.execute("object.pathfinder.unite", &json!({})).unwrap();
assert_eq!(r["ids"], json!([n]));
assert_eq!(layers(&s)[0], json!([b, [group, d, f]]));
assert_eq!(layer(&s, 1), [NodeId(n)]);
assert!(selected(&s, &[NodeId(n)]));
undo_gives_back(&mut s, &before);
s.edit("Paint nothing", |d, _| {
for id in [a, e, h] {
d.node_mut(NodeId(id)).unwrap().appearance = Appearance::default().into();
}
Ok(())
})
.unwrap();
let before = s.doc().unwrap().doc.clone();
let r = s.execute("object.path.cleanUp", &json!({})).unwrap();
assert_eq!(r["removed"], json!(3));
assert_eq!(layers(&s), [json!([b, c, [group, d, f]]), json!([g])]);
undo_gives_back(&mut s, &before);
}
/// `object.transform` copies ids listed twice, and an object listed before a group around it.
/// Each copy goes directly above its original, a later copy of the same object goes below an
/// earlier one, and the copy of the group holds a copy of the copy made inside the group before it.
+32
View File
@@ -17,6 +17,38 @@ fn place_embedded(s: &mut Session, path: &str) -> NodeId {
NodeId(r["ids"][0].as_u64().unwrap())
}
/// A PNG that says it is `w` × `h` 1-bit grey pixels (its header and no rows, which is all that
/// placing and listing read).
fn png_header(w: u32, h: u32) -> Vec<u8> {
let mut out = b"\x89PNG\r\n\x1a\n".to_vec();
let ihdr: Vec<u8> = [&b"IHDR"[..], &w.to_be_bytes(), &h.to_be_bytes(), &[1, 0, 0, 0, 0]].concat();
for chunk in [&ihdr[..], b"IDAT\x78\x9c", b"IEND"] {
out.extend((chunk.len() as u32 - 4).to_be_bytes());
out.extend(chunk);
out.extend(crc32fast::hash(chunk).to_be_bytes());
}
out
}
/// An image past what a decode may take isn't drawn: Place and Open say so and the Links panel's
/// row carries the note, where the image used to be blank with no word (#1479).
#[test]
fn an_image_too_large_to_draw_is_reported() {
const NOTE: &str = "an image of 200000 × 200000 pixels is too large to draw";
let dir = Folder::new("huge");
let (big, small) = (dir.file("wall.png"), dir.file("small.png"));
write(&big, &png_header(200_000, 200_000));
write(&small, &png(40, 20, BLUE));
let mut s = session();
assert_eq!(run(&mut s, "file.place", json!({"path": big, "at": [200, 150], "link": false}))["warnings"], json!([NOTE]));
assert_eq!(run(&mut s, "file.place", json!({"path": small, "at": [20, 20], "link": false}))["warnings"], json!([]));
let l = run(&mut s, "links.list", json!({}));
let notes: Vec<&Value> = l["links"].as_array().unwrap().iter().map(|r| &r["note"]).collect();
assert_eq!(notes, [&Value::Null, &json!(NOTE)], "top first: the small image has nothing to say");
// Opened as a document: said too. An image that decodes (16,000 px square) has no note.
assert_eq!(crate::cmd::fileio::load("wall.png", &png_header(200_000, 200_000)).unwrap().warnings, [NOTE]);
assert!(crate::cmd::fileio::load("fine.png", &png_header(16_000, 16_000)).unwrap().warnings.is_empty());
}
fn close(a: f64, b: f64) -> bool {
(a - b).abs() < 1e-6
}
+29
View File
@@ -217,6 +217,35 @@ fn blend_release_restores_keys() {
assert!(s.execute("object.blend.release", &json!({})).is_ok() || s.execute("object.blend.release", &json!({})).is_err());
}
/// Release Blend of a blend and of a blend inside a group that is a key object of the first puts
/// the outer blend's spine and keys where it was, then the inner blend's spine and keys where it
/// was inside that group, as releasing one blend at a time does.
#[test]
fn blend_release_of_a_blend_and_a_blend_inside_it_keeps_order_and_ids() {
let mut s = session();
let (r1, r2) = (rect(&mut s, 0.0, 0.0, 10.0, 10.0), rect(&mut s, 100.0, 0.0, 10.0, 10.0));
sel(&mut s, &[r1, r2]);
let inner = id_of(&s.execute("object.blend.make", &json!({})).unwrap());
let r3 = rect(&mut s, 200.0, 0.0, 10.0, 10.0);
sel(&mut s, &[inner, r3]);
let group = id_of(&s.execute("object.group", &json!({})).unwrap());
let r4 = rect(&mut s, 400.0, 0.0, 10.0, 10.0);
sel(&mut s, &[group, r4]);
let outer = id_of(&s.execute("object.blend.make", &json!({})).unwrap());
sel(&mut s, &[outer, inner]);
let before = s.doc().unwrap().doc.clone();
let n = before.peek_next_id();
let r = s.execute("object.blend.release", &json!({})).unwrap();
assert_eq!(r["ids"], json!([group.0, r4.0, r1.0, r2.0]));
assert_eq!(r["spines"], json!([n, n + 1]));
let ids = |n: &Node| n.children().unwrap().iter().map(|c| c.id).collect::<Vec<_>>();
assert_eq!(ids(&s.doc().unwrap().doc.layers[0]), [NodeId(n), group, r4]);
assert_eq!(ids(&node(&s, group)), [NodeId(n + 1), r1, r2, r3]);
assert_eq!(s.doc().unwrap().selection.objects, [NodeId(n), NodeId(n + 1), group, r4, r1, r2]);
s.execute("edit.undo", &json!({})).unwrap();
assert!(*s.doc().unwrap().doc == *before, "Undo gives back the document");
}
#[test]
fn blend_expand_makes_group_with_unique_ids() {
let mut s = session();
+12
View File
@@ -1826,3 +1826,15 @@ fn crop_image_trim_cuts_to_the_opaque_pixels_as_they_are() {
assert_eq!((r["trimmed"].as_bool(), r["width"].as_u64()), (Some(false), Some(30)), "{r}");
assert_eq!(bounds(&s, img), b);
}
#[test]
fn crop_image_trim_leaves_a_cmyk_image_alone() {
// CMYK images keep their ink amounts and have no alpha: nothing to cut, and not an error.
let inks = vectorcraft_doc::cmyk::Inks::new(4, 2, [255, 0, 0, 0].repeat(8)).unwrap();
let tiff = vectorcraft_doc::ImageBlob::cmyk_tiff(&inks).unwrap();
let mut s = Session::new();
s.execute("document.open", &json!({"name": "inks.tif", "dataBase64": vectorcraft_format::base64_encode(&tiff.bytes)})).unwrap();
s.execute("select.all", &json!({})).unwrap();
let r = s.execute("object.cropImage", &json!({"trim": true})).unwrap();
assert_eq!((r["trimmed"].as_bool(), r["width"].as_u64(), r["height"].as_u64()), (Some(false), Some(4), Some(2)), "{r}");
}
+24
View File
@@ -152,6 +152,30 @@ fn release_while_editing_leaves_editing_first() {
assert!(mask(&s, obj).is_some() && doc(&s).mask_edit.is_some());
}
/// Releasing the masks of a group and of an object inside it puts each mask's art directly above
/// its object, as releasing one mask at a time does.
#[test]
fn release_of_a_masked_group_and_a_masked_object_inside_it_keeps_order_and_ids() {
let mut s = session();
let (a, m1) = (rect(&mut s, 0.0, 100.0), rect(&mut s, 0.0, 50.0));
s.execute("transparency.makeOpacityMask", &json!({"ids": [a.0, m1.0]})).unwrap();
let b = rect(&mut s, 150.0, 100.0);
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
let m2 = rect(&mut s, 0.0, 300.0);
s.execute("transparency.makeOpacityMask", &json!({"ids": [group.0, m2.0]})).unwrap();
let before = doc(&s).clone();
let n = before.peek_next_id();
s.execute("transparency.releaseOpacityMask", &json!({"ids": [group.0, a.0]})).unwrap();
let ids = |n: &vectorcraft_doc::Node| n.children().unwrap().iter().map(|c| c.id).collect::<Vec<_>>();
assert_eq!(ids(&doc(&s).layers[0]), [group, NodeId(n)]);
assert_eq!(ids(doc(&s).node(group).unwrap()), [a, NodeId(n + 1), b]);
assert!(mask(&s, group).is_none() && mask(&s, a).is_none());
assert_eq!(s.doc().unwrap().selection.objects, [group, NodeId(n), a, NodeId(n + 1)]);
s.execute("edit.undo", &json!({})).unwrap();
assert!(*doc(&s) == before, "Undo gives back the document");
}
#[test]
fn one_object_gets_an_empty_mask_drawn_in_editing_mode() {
let mut s = session();
+7
View File
@@ -1290,6 +1290,13 @@ proptest! {
survive("mutated EPS PostScript", || vectorcraft_eps::import(&bytes).ok().map(|r| r.document))?;
}
/// A damaged EPS another app copied: Paste reads it as an error or as objects.
#[test]
fn pasted_eps_never_panics(cut in 0usize..400_000, edits in prop::collection::vec((0usize..400_000, any::<u8>()), 0..12)) {
static SAMPLE: std::sync::OnceLock<Vec<u8>> = std::sync::OnceLock::new();
paste_from_elsewhere("clipboard.importEps", json!({"dataBase64": mutated_b64(SAMPLE.get_or_init(foreign_eps_sample).clone(), cut, &edits)}))?;
}
/// Hostile PostScript programs: operators in any order with any operands, opened and placed;
/// as files in the legacy Illustrator format too (the creator line is what turns on its
/// documented `u` … `U` groups), the groups unbalanced, deep and among clips; in a layer, which
+26 -2
View File
@@ -243,13 +243,32 @@ impl SaveOptions {
Ok(())
}
/// The defaults for saving `doc` to disk: pretty when small (see [`PRETTY_MAX_OBJECTS`]).
/// The defaults for saving `doc` to disk: pretty when small (see [`PRETTY_MAX_OBJECTS`] and
/// [`PRETTY_MAX_BYTES`]).
pub fn for_doc(doc: &Document) -> Self {
let objects: usize = doc.layers.iter().map(|l| l.count()).sum();
Self { pretty: objects <= PRETTY_MAX_OBJECTS, ..Self::default() }
Self { pretty: objects <= PRETTY_MAX_OBJECTS && compact_size_at_most(doc, PRETTY_MAX_BYTES), ..Self::default() }
}
}
/// Is `doc` at most `limit` bytes as compact JSON? Serializing stops as soon as it is past the
/// limit, so a large document costs no more than `limit` bytes of work.
fn compact_size_at_most(doc: &Document, limit: usize) -> bool {
struct Capped {
left: usize,
}
impl Write for Capped {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.left = self.left.checked_sub(buf.len()).ok_or_else(|| std::io::Error::other("over the limit"))?;
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
serde_json::to_writer(Capped { left: limit }, doc).is_ok()
}
/// Serialize a document (pretty = human-diffable) in the current version. Editing-mode working
/// copies are left out ([`Document::without_edit_modes`]).
pub fn save(doc: &Document, pretty: bool) -> Vec<u8> {
@@ -260,6 +279,11 @@ pub fn save(doc: &Document, pretty: bool) -> Vec<u8> {
/// compact, where indentation would multiply the file size and slow opening down.
pub const PRETTY_MAX_OBJECTS: usize = 2000;
/// Documents whose compact JSON is larger than this are saved compact even with few objects:
/// pretty-printing spreads every path anchor over several lines, so traced or generated art (in
/// layers, symbols or patterns alike) would grow about tenfold.
pub const PRETTY_MAX_BYTES: usize = 1 << 20;
/// Serialize for saving to disk: pretty when small, compact when large.
pub fn save_file(doc: &Document) -> Vec<u8> {
save_with(doc, &SaveOptions::for_doc(doc)).unwrap_or_default()
+68 -3
View File
@@ -8,9 +8,11 @@ use std::sync::Arc;
use serde_json::Value;
use vectorcraft_doc::links::LinkInfo;
use vectorcraft_doc::{Document, ImageBlob, ImageObject, Node, NodeKind};
use vectorcraft_format::{ICC_MIME, SaveOptions, load, load_file, pdf_content, save_with};
use vectorcraft_geom::Affine;
use vectorcraft_doc::{Document, ImageBlob, ImageObject, Node, NodeKind, Symbol};
use vectorcraft_format::{ICC_MIME, PRETTY_MAX_BYTES, PRETTY_MAX_OBJECTS, SaveOptions, load, load_file, pdf_content, save_file, save_with};
use vectorcraft_geom::path::{PathData, SubPath};
use vectorcraft_geom::{Affine, Point};
use vectorcraft_testkit::fixtures::DocBuilder;
fn json_of(bytes: &[u8]) -> Value {
serde_json::from_slice(bytes).unwrap()
@@ -82,3 +84,66 @@ fn embedded_profiles_and_pdf_round_trip() {
let damaged = String::from_utf8(plain).unwrap().replacen("AAECA/o=", "not base64!", 1);
assert!(load_file(damaged.as_bytes()).unwrap().profiles.is_empty());
}
/// A document of `paths` open paths with `anchors` anchors each.
fn paths_doc(paths: usize, anchors: usize) -> Document {
let mut b = DocBuilder::new(1000.0, 1000.0);
for i in 0..paths {
let points: Vec<Point> = (0..anchors).map(|j| Point::new(j as f64, i as f64 + (j % 2) as f64)).collect();
let node = b.path_node(PathData::single(SubPath::polyline(&points, false)), Default::default());
b.add(node);
}
b.doc
}
fn is_pretty(bytes: &[u8]) -> bool {
bytes.windows(3).any(|w| w == b"\n ")
}
#[test]
fn small_documents_are_saved_pretty() {
let d = paths_doc(10, 10);
assert!(SaveOptions::for_doc(&d).pretty);
assert!(is_pretty(&save_file(&d)));
}
#[test]
fn many_objects_are_saved_compact() {
let d = paths_doc(PRETTY_MAX_OBJECTS + 1, 2);
assert!(!SaveOptions::for_doc(&d).pretty);
}
/// Anchors per path that make a document of `paths` paths about `bytes` of compact JSON.
fn anchors_for(paths: usize, bytes: usize) -> usize {
let per_anchor = serde_json::to_vec(&paths_doc(1, 1000)).unwrap().len() / 1000;
bytes / per_anchor / paths
}
#[test]
fn few_objects_with_many_anchors_are_saved_compact() {
let d = paths_doc(3, anchors_for(3, 2 * PRETTY_MAX_BYTES));
assert!(!SaveOptions::for_doc(&d).pretty, "3 objects, but about {} bytes", 2 * PRETTY_MAX_BYTES);
let bytes = save_file(&d);
assert!(!is_pretty(&bytes));
assert_eq!(load(&bytes).unwrap().layers[0].count(), d.layers[0].count());
}
#[test]
fn documents_under_the_size_limit_stay_pretty() {
let d = paths_doc(2, anchors_for(2, PRETTY_MAX_BYTES / 2));
assert!(SaveOptions::for_doc(&d).pretty);
}
#[test]
fn art_outside_the_layers_counts_too() {
// Generated art kept in a symbol: one instance-sized document, a symbol full of anchors.
let mut d = paths_doc(1, 4);
let mut art = paths_doc(1, anchors_for(1, 2 * PRETTY_MAX_BYTES));
let path = Arc::clone(&art.layers[0]);
art.layers.clear();
d.symbols.push(Symbol { name: "Leaves".into(), art: path });
assert!(!SaveOptions::for_doc(&d).pretty);
let bytes = save_file(&d);
assert!(!is_pretty(&bytes));
assert_eq!(load(&bytes).unwrap().symbols.len(), 1);
}
+8 -1
View File
@@ -16,6 +16,7 @@ mod ink;
mod live;
mod lru;
mod paint;
pub use paint::decode_failures;
mod pattern;
pub mod placed_document;
pub mod proof;
@@ -1023,7 +1024,13 @@ impl Renderer {
&& f.opts.dim_templates
&& !f.opts.skip_templates
{
if !preview && !f.opts.outline {
// A template layer stays in Preview while the view is in Outline (and whatever its own
// Preview option says): its picture is there to be traced (#1486).
if *template && f.opts.outline {
let opts = RenderOptions { outline: false, ..f.opts.clone() };
return self.draw_node(ctx, &Frame { opts: &opts, ..*f }, n, force);
}
if !preview && !template && !f.opts.outline {
let opts = RenderOptions { outline: true, ..f.opts.clone() };
return self.draw_node(ctx, &Frame { opts: &opts, ..*f }, n, force);
}
+42 -3
View File
@@ -52,14 +52,53 @@ pub(crate) fn set_paint(ctx: &mut RenderContext, p: &Paint, bounds: Rect, f: &Fr
}
}
/// Decode encoded image bytes into a premultiplied pixmap.
/// The most memory decoding one image may take: print rasters run to gigabytes (a 300 ppi roll,
/// 6614 x 59055 px, is 1.56 GB as RGBA), past the decoder's 512 MB default. The web keeps it.
const MAX_DECODE_ALLOC: u64 = if cfg!(target_arch = "wasm32") { 512 << 20 } else { 2 << 30 };
/// Images that couldn't be decoded (and so drew nothing), counted for exports to report.
static DECODE_FAILURES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
/// How many images have failed to decode so far (process-wide): an export compares the count
/// before and after to say it left images out.
pub fn decode_failures() -> u64 {
DECODE_FAILURES.load(std::sync::atomic::Ordering::Relaxed)
}
/// `bytes` decoded within [`MAX_DECODE_ALLOC`]; a failure is counted in [`decode_failures`].
fn decode(bytes: &[u8]) -> Option<image::DynamicImage> {
let img = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().ok().and_then(|mut r| {
let mut limits = image::Limits::default();
limits.max_alloc = Some(MAX_DECODE_ALLOC);
r.limits(limits);
r.decode().ok()
});
if img.is_none() {
DECODE_FAILURES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
}
img
}
/// `img` shrunk, keeping its proportions, to fit a pixmap's sides (at most `u16::MAX` pixels).
fn fit_pixmap(img: image::DynamicImage) -> image::DynamicImage {
let (w, h) = (img.width(), img.height());
let max = u16::MAX as u32;
if w <= max && h <= max {
return img;
}
let s = max as f64 / w.max(h) as f64;
let (nw, nh) = (((w as f64 * s).round() as u32).clamp(1, max), ((h as f64 * s).round() as u32).clamp(1, max));
img.resize_exact(nw, nh, image::imageops::FilterType::Triangle)
}
/// Decode encoded image bytes into a premultiplied pixmap (shrunk to fit a pixmap's sides).
pub fn decode_pixmap(bytes: &[u8]) -> Option<vello_cpu::Pixmap> {
pixmap_of(image::load_from_memory(bytes).ok()?.to_rgba8())
pixmap_of(fit_pixmap(decode(bytes)?).to_rgba8())
}
/// [`decode_pixmap`] shrunk to `w`×`h` pixels when the image is larger (never enlarged).
pub fn decode_pixmap_fit(bytes: &[u8], w: u16, h: u16) -> Option<vello_cpu::Pixmap> {
let img = image::load_from_memory(bytes).ok()?;
let img = decode(bytes)?;
let img = if img.width() > w as u32 || img.height() > h as u32 {
img.resize_exact(w as u32, h as u32, image::imageops::FilterType::Triangle)
} else {
+28
View File
@@ -67,6 +67,34 @@ fn dim_images_fades_only_the_images() {
assert_eq!(render(&d, true).pixel(65, 25), [255, 0, 0, 255], "exports are not dimmed");
}
/// In Outline view a template layer still draws in Preview, dimmed, so its picture can be traced;
/// the layer above it draws in outline (#1486).
#[test]
fn a_template_layer_stays_in_preview_in_outline_view() {
let mut d = doc(|k| {
if let NodeKind::Layer { template, preview, .. } = k {
*template = true;
// Preview off doesn't put a template in outline either.
*preview = false;
}
});
let top = Node::layer(d.alloc_id(), "Drawing", vectorcraft_doc::LayerColor::Preset(0));
let top_id = d.insert(None, 9, top).unwrap();
let red = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0);
let sq = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(10.0, 60.0, 40.0, 90.0)), red);
d.insert(Some(top_id), 0, sq).unwrap();
let draw = |outline: bool| {
let opts = RenderOptions { background: Some([255, 255, 255, 255]), outline, ..Default::default() };
Renderer::new().render(&d, 100, 100, Affine::IDENTITY, &opts)
};
let (preview, outline) = (draw(false), draw(true));
let [r, g, b, _] = outline.pixel(65, 25);
assert!(r == 255 && (120..=135).contains(&g) && g == b, "the template's image, dimmed: {:?}", outline.pixel(65, 25));
assert_eq!(outline.pixel(65, 25), preview.pixel(65, 25), "as in Preview");
assert_eq!(outline.pixel(25, 75), [255, 255, 255, 255], "the drawing layer has no fill in outline");
assert_eq!(preview.pixel(25, 75), [255, 0, 0, 255]);
}
/// A guide path draws on screen only: exports leave it out, as they leave templates out (and as
/// the SVG, PSD and PDF exports and printing already do).
#[test]
+4 -2
View File
@@ -65,13 +65,15 @@ fn revolve_canvas_matches_baked_art_and_shades_its_surface() {
assert_eq!(live.pixels, render_threads(&d, 4).pixels);
}
/// Extrude & Bevel, Inflate and Rotate draw on the canvas exactly as they export, filling more
/// than the flat square with faces of differing shades (Rotate: one shade, narrower).
/// Extrude & Bevel, Inflate (also twisted, tapered and hollow) and Rotate draw on the canvas exactly
/// as they export, filling more than the flat square with faces of differing shades (Rotate: one
/// shade, narrower).
#[test]
fn solid_effects_canvas_matches_baked_art_and_shades_their_faces() {
for (effect, params) in [
("threeD.extrude", json!({"depth": 30, "bevel": "rounded"})),
("threeD.inflate", json!({"depth": 10})),
("threeD.inflate", json!({"depth": 10, "twist": 90, "taper": 60, "cap": false, "rotationX": -20, "rotationY": 35})),
("threeD.rotate", json!({"rotationX": 0, "rotationY": 55, "rotationZ": 0})),
] {
let mut n = Node::path(
+66 -29
View File
@@ -161,7 +161,7 @@ impl Default for Bevel {
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Extrude {
pub depth: f64,
/// The turn of the back face against the front, about the shape's centre.
/// The turn of the back face against the front, about the shape's centre: 0° to 360°.
pub twist: f64,
/// The size of the back face, as a share (0.01..1) of the front's.
pub taper: f64,
@@ -185,11 +185,17 @@ pub struct Inflate {
pub volume: f64,
/// Puff the back out too; otherwise it stays flat.
pub both_sides: bool,
/// The turn of the back against the front, about the shape's centre: 0° to 360°.
pub twist: f64,
/// The size of the back, as a share (0.01..1) of the front's.
pub taper: f64,
/// A closed back (a solid) or none, so the inflated front is a shell open behind.
pub cap: bool,
}
impl Default for Inflate {
fn default() -> Self {
Self { depth: 0.0, volume: 50.0, both_sides: false }
Self { depth: 0.0, volume: 50.0, both_sides: false, twist: 0.0, taper: 1.0, cap: true }
}
}
@@ -233,7 +239,7 @@ impl Extrude {
fn sanitized(self) -> Self {
Self {
depth: finite(self.depth, 50.0, 0.0, 2000.0),
twist: finite(self.twist, 0.0, -360.0, 360.0),
twist: finite(self.twist, 0.0, 0.0, 360.0),
taper: finite(self.taper, 1.0, 0.01, 1.0),
bevel: self.bevel.map(|b| Bevel {
width: finite(b.width, 4.0, 0.0, 1000.0),
@@ -249,7 +255,13 @@ impl Extrude {
impl Inflate {
fn sanitized(self) -> Self {
Self { depth: finite(self.depth, 0.0, 0.0, 2000.0), volume: finite(self.volume, 50.0, 0.0, 100.0), ..self }
Self {
depth: finite(self.depth, 0.0, 0.0, 2000.0),
volume: finite(self.volume, 50.0, 0.0, 100.0),
twist: finite(self.twist, 0.0, 0.0, 360.0),
taper: finite(self.taper, 1.0, 0.01, 1.0),
..self
}
}
}
@@ -464,10 +476,9 @@ impl Builder<'_> {
for i in 0..n {
let j = (i + 1) % n;
let quad = vec![a[i], a[j], b[j], b[i]];
let mut normal = quad[1].sub(quad[0]).cross(quad[2].sub(quad[0]));
if normal.dot(normal) < 1e-18 {
normal = quad[2].sub(quad[0]).cross(quad[3].sub(quad[0]));
}
// A twist bends the strip between two slices into a saddle: its normal is the whole
// quad's average (Newell's), not one corner's triangle, which leans far to one side.
let mut normal = newell(std::slice::from_ref(&quad));
if normal.dot(normal) < 1e-18 {
continue;
}
@@ -517,15 +528,29 @@ fn outward(ring: &[Point], i: usize, z: f64) -> V3 {
/// The cross-section of a side: each ring of the shape at depth fraction `t` (0 front, 1 back),
/// turned by the twist and scaled by the taper about the centre of `bounds`.
fn section(ring: &[Point], bounds: Rect, o: &Extrude, t: f64) -> Vec<Point> {
let c = bounds.center();
let (s, cos) = (o.twist * t).to_radians().sin_cos();
let k = 1.0 + (o.taper - 1.0) * t;
ring.iter()
.map(|p| {
let (x, y) = ((p.x - c.x) * k, (p.y - c.y) * k);
Point::new(c.x + x * cos - y * s, c.y + x * s + y * cos)
})
.collect()
let turn = Turn::new(bounds, o.twist, o.taper, t);
ring.iter().map(|p| turn.apply(*p)).collect()
}
/// The twist and taper at depth fraction `t` (0 front, 1 back): a turn by `twist · t` and a
/// scale from 1 to `taper`, about the centre of the bounds.
#[derive(Clone, Copy)]
struct Turn {
centre: Point,
sin: f64,
cos: f64,
scale: f64,
}
impl Turn {
fn new(bounds: Rect, twist: f64, taper: f64, t: f64) -> Self {
let (sin, cos) = (twist * t).to_radians().sin_cos();
Self { centre: bounds.center(), sin, cos, scale: 1.0 + (taper - 1.0) * t }
}
fn apply(&self, p: Point) -> Point {
let (x, y) = ((p.x - self.centre.x) * self.scale, (p.y - self.centre.y) * self.scale);
Point::new(self.centre.x + x * self.cos - y * self.sin, self.centre.y + x * self.sin + y * self.cos)
}
}
/// One step of an extrusion's outline: how far it is inset (negative: outset) and its depth
@@ -997,8 +1022,11 @@ pub fn inflate(path: &PathData, bounds: Rect, options: Inflate, view: View) -> R
height * (m.at(p).max(0.0) / m.peak).sqrt()
};
let camera = Camera::new(view, bounds, o.depth + 2.0 * height);
let mut b = Builder { camera: &camera, closed: true, facets: vec![] };
// Without its back cap the object is a shell open behind, its inside showing.
let mut b = Builder { camera: &camera, closed: o.cap, facets: vec![] };
let half = o.depth / 2.0;
// The back: turned and scaled by the twist and taper, its puff too.
let back_turn = Turn::new(bounds, o.twist, o.taper, 1.0);
// The grid's cells, those the surface rises steeply across (near the outline) cut into
// halves or quarters each way, so the steep rim is drawn in facets as fine as its curve.
// Every corner sits on one fine lattice (a quarter cell), computed the same way wherever it
@@ -1119,16 +1147,18 @@ pub fn inflate(path: &PathData, bounds: Rect, options: Inflate, view: View) -> R
// Each piece lifted onto the surface. Its normal is the lifted piece's own average
// (Newell's), not the slope at one point: near the edge the surface turns
// vertical, and a point sample there misjudges which way a whole piece faces.
let lifted = |sign: f64| -> Vec<Vec<V3>> {
pieces.iter().zip(&lifts).map(|(p, h)| p.iter().zip(h).map(|(q, h)| camera.place(*q, sign * (half + h))).collect()).collect()
};
let front = lifted(1.0);
let front: Vec<Vec<V3>> =
pieces.iter().zip(&lifts).map(|(p, h)| p.iter().zip(h).map(|(q, h)| camera.place(*q, half + h)).collect()).collect();
let n = newell(&front);
b.face(front, n)?;
if o.both_sides {
if o.both_sides && o.cap {
// The back winds the same way round as the front, so its outward normal is
// reversed.
let back = lifted(-1.0);
let back: Vec<Vec<V3>> = pieces
.iter()
.zip(&lifts)
.map(|(p, h)| p.iter().zip(h).map(|(q, h)| camera.place(back_turn.apply(*q), -half - h * back_turn.scale)).collect())
.collect();
let n = newell(&back);
b.face(back, V3(-n.0, -n.1, -n.2))?;
}
@@ -1136,15 +1166,22 @@ pub fn inflate(path: &PathData, bounds: Rect, options: Inflate, view: View) -> R
}
}
}
if !o.both_sides {
let back: Vec<Vec<V3>> = rings.iter().map(|r| r.iter().map(|p| camera.place(*p, -half)).collect()).collect();
if !o.both_sides && o.cap {
let back: Vec<Vec<V3>> = rings.iter().map(|r| r.iter().map(|p| camera.place(back_turn.apply(*p), -half)).collect()).collect();
b.face(back, camera.rotate(V3(0.0, 0.0, -1.0)))?;
}
if o.depth > 0.0 {
// The sides, cut into slices that follow a twist or taper.
let slices = if o.twist != 0.0 || o.taper != 1.0 { ((o.twist.abs() / 6.0).ceil() as usize).clamp(8, 64) } else { 1 };
for ring in &rings {
let front: Vec<V3> = ring.iter().map(|p| camera.place(*p, half)).collect();
let back: Vec<V3> = ring.iter().map(|p| camera.place(*p, -half)).collect();
b.band(&front, &back, |i| outward(ring, i, 0.0))?;
let at = |k: usize| -> Vec<V3> {
let t = k as f64 / slices as f64;
let turn = Turn::new(bounds, o.twist, o.taper, t);
ring.iter().map(|p| camera.place(turn.apply(*p), half - o.depth * t)).collect()
};
for k in 0..slices {
b.band(&at(k), &at(k + 1), |i| outward(ring, i, 0.0))?;
}
}
}
Ok(b.finish())
+114 -1
View File
@@ -218,7 +218,10 @@ fn malformed_and_degenerate_input_is_bounded() {
};
let f = extrude(&p, b, wild, View { rotation_x: f64::NAN, perspective: 9.0, ..front() }).unwrap();
assert!(f.iter().flat_map(|f| f.contours.iter().flatten()).all(|q| q.x.is_finite() && q.y.is_finite()));
assert!(inflate(&p, b, Inflate { depth: -5.0, volume: f64::NAN, both_sides: true }, front()).is_ok());
assert!(
inflate(&p, b, Inflate { depth: -5.0, volume: f64::NAN, both_sides: true, twist: f64::INFINITY, taper: f64::NAN, cap: true }, front())
.is_ok()
);
assert!(extrude(&PathData::default(), b, Extrude::default(), front()).unwrap().is_empty());
// A line has no area to extrude.
let mut line = BezPath::new();
@@ -362,3 +365,113 @@ fn the_edge_index_looks_along_the_side_from_outside() {
let (fast, slow) = (edges.distance(q), edge_distance(&rings, q));
assert!((fast - slow).abs() < 1e-9, "{fast} against {slow}");
}
/// Twist runs 0° to 360°, as documented: beyond either end it holds at that end.
#[test]
fn twist_holds_between_0_and_360_degrees() {
let (p, b) = shape(&square(0.0, 0.0, 100.0));
let v = View { rotation_x: -20.0, rotation_y: 30.0, ..front() };
let at = |twist: f64| extrude(&p, b, Extrude { twist, ..Extrude::default() }, v).unwrap();
assert_eq!(at(-45.0), at(0.0));
assert_eq!(at(500.0), at(360.0));
assert_ne!(at(45.0), at(0.0));
}
/// A twisted extrusion shows every wall facing the viewer: a twist bends each strip between two
/// slices into a saddle, and its normal from one corner's triangle leaned so far back that from
/// 60° on every wall was dropped. Checked against each strip's average normal, oriented away from
/// the square's axis.
#[test]
fn twisted_walls_face_the_way_they_turn() {
let (p, b) = shape(&square(0.0, 0.0, 100.0));
let c = b.center();
for twist in [60.0, 120.0, 180.0, 300.0] {
for (x, y) in [(-20.0, 30.0), (0.0, 90.0), (30.0, -60.0), (-45.0, 150.0)] {
let v = View { rotation_x: x, rotation_y: y, ..front() };
let o = Extrude { twist, ..Extrude::default() };
let got = extrude(&p, b, o, v).unwrap();
// Expected: walls (and caps) whose outward normal faces the viewer.
let o = o.sanitized();
let camera = Camera::new(v, b, o.depth);
let ring = &rings(&p, b.width().max(b.height()), MAX_SOLID_POINTS).unwrap()[0];
let slices = ((twist / 6.0).ceil() as usize).clamp(8, 64);
let z = |t: f64| o.depth / 2.0 - o.depth * t;
let mut expected = 0;
for k in 0..slices {
let (t0, t1) = (k as f64 / slices as f64, (k + 1) as f64 / slices as f64);
let (r0, r1) = (section(ring, b, &o, t0), section(ring, b, &o, t1));
for i in 0..ring.len() {
let j = (i + 1) % ring.len();
let q = [camera.place(r0[i], z(t0)), camera.place(r0[j], z(t0)), camera.place(r1[j], z(t1)), camera.place(r1[i], z(t1))];
let mut n = newell(&[q.to_vec()]).unit();
let mid = r0[i].midpoint(r1[j]);
let away = camera.rotate(V3(mid.x - c.x, mid.y - c.y, 0.0));
if n.dot(away) < 0.0 {
n = V3(-n.0, -n.1, -n.2);
}
let centre = V3((q[0].0 + q[2].0) / 2.0, (q[0].1 + q[2].1) / 2.0, (q[0].2 + q[2].2) / 2.0);
// Kept as the builder keeps them: facing, or seen almost edge-on, with an area.
let projected: Vec<Point> = q.iter().map(|v| camera.project(*v)).collect();
if camera.facing(centre, n) > -0.02 && signed_area(&projected).abs() >= 1e-10 {
expected += 1;
}
}
}
for (n, t) in [(1.0, 0.0), (-1.0, 1.0)] {
let cap: Vec<Point> = section(ring, b, &o, t).iter().map(|p| camera.project(camera.place(*p, z(t)))).collect();
if camera.facing(V3::default(), camera.rotate(V3(0.0, 0.0, n))) > -0.02 && signed_area(&cap).abs() >= 1e-10 {
expected += 1;
}
}
assert_eq!(got.len(), expected, "twist {twist}, view ({x}, {y})");
}
}
}
/// Inflate takes Twist, Taper and Cap like the other types: the back turned and scaled (its puff
/// too), the sides following, and without a cap no back at all.
#[test]
fn inflate_twists_tapers_and_opens_its_back() {
let (p, b) = shape(&square(0.0, 0.0, 100.0));
let side = View { rotation_y: 90.0, ..front() };
let o = Inflate { depth: 60.0, volume: 0.0, ..Inflate::default() };
// From the side, a flat (0 % volume) cushion is the extrusion: front 100 high, the back 50
// at a 50 % taper.
let tapered = inflate(&p, b, Inflate { taper: 0.5, ..o }, side).unwrap();
let e = extent(&tapered);
assert!(close(e.width(), 60.0, 1e-6) && close(e.height(), 100.0, 1e-6), "{e:?}");
let back: Vec<Point> = tapered.iter().flat_map(|f| f.contours.iter().flatten().copied()).filter(|q| close(q.x, e.x0, 1e-6)).collect();
let (lo, hi) = back.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), q| (lo.min(q.y), hi.max(q.y)));
assert!(close(hi - lo, 50.0, 1e-6), "back {}", hi - lo);
// From behind, a 45° twist shows the flat back as a diamond.
let behind = View { rotation_y: 180.0, ..front() };
let twisted = inflate(&p, b, Inflate { twist: 45.0, ..o }, behind).unwrap();
assert!(close(extent(&twisted).width(), 100.0 * 2f64.sqrt(), 1e-6), "{:?}", extent(&twisted));
// Hollow: no back; from behind the inside of the inflated front shows instead of a flat face.
let solid = inflate(&p, b, Inflate { volume: 50.0, ..o }, behind).unwrap();
assert_eq!(solid.len(), 1, "the flat back alone");
let hollow = inflate(&p, b, Inflate { volume: 50.0, cap: false, ..o }, behind).unwrap();
assert!(hollow.len() > 100 && hollow.iter().all(|f| f.contours.len() == 1 && f.contours[0].len() < 12));
// With both sides puffed, the back puff is scaled with the taper: lower and smaller.
let both = |taper: f64| extent(&inflate(&p, b, Inflate { both_sides: true, volume: 50.0, taper, depth: 0.0, ..o }, side).unwrap());
assert!(both(0.5).width() < both(1.0).width() && both(0.5).height() <= both(1.0).height() + 1e-6);
// Out of range values hold at the documented ends.
let at = |i: Inflate| inflate(&p, b, i, View { rotation_x: -20.0, rotation_y: 30.0, ..front() }).unwrap();
assert_eq!(at(Inflate { twist: -30.0, ..o }), at(o));
assert_eq!(at(Inflate { taper: 0.0, ..o }), at(Inflate { taper: 0.01, ..o }));
}
/// At 0 % volume an inflated shape is the extruded one: twisted and tapered, their outlines
/// agree from every side (no wall goes missing in either).
#[test]
fn a_flat_twisted_inflate_matches_the_extrusion() {
let (p, b) = shape(&square(0.0, 0.0, 100.0));
for (x, y) in [(-20.0, 30.0), (0.0, 90.0), (30.0, -60.0), (-45.0, 150.0), (60.0, 200.0)] {
let v = View { rotation_x: x, rotation_y: y, ..front() };
let e = extent(&extrude(&p, b, Extrude { depth: 60.0, twist: 120.0, taper: 0.6, ..Extrude::default() }, v).unwrap());
let i = extent(&inflate(&p, b, Inflate { depth: 60.0, twist: 120.0, taper: 0.6, volume: 0.0, ..Inflate::default() }, v).unwrap());
for (a, c) in [(e.x0, i.x0), (e.y0, i.y0), (e.x1, i.x1), (e.y1, i.y1)] {
assert!(close(a, c, 1e-6), "view ({x}, {y}): extrusion {e:?}, inflate {i:?}");
}
}
}
+32 -3
View File
@@ -235,10 +235,13 @@ fn anchor_owners(cx: &ToolContext, f: fn(&Node) -> bool) -> Vec<NodeId> {
v
}
/// The anchor within `tol` of `p` nearest to it, of the topmost visible path or area type frame
/// that has one: (id, si, ai, where it is).
/// The anchor within `tol` of `p` nearest to it, of the topmost selected path or area type frame
/// that has one, else of the topmost visible one: (id, si, ai, where it is). Selected objects come
/// first so an object above can't take the press from the one being edited (#1508), as
/// [`hovered_anchor`] marks it.
fn hit_anchor(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId, usize, usize, Point)> {
let owners = anchor_owners(cx, |n| matches!(n.kind, NodeKind::Path { .. }) || is_area_type(n));
let mut owners = anchor_owners(cx, |n| matches!(n.kind, NodeKind::Path { .. }) || is_area_type(n));
owners.sort_by_key(|id| !cx.selection.contains(*id));
owners.into_iter().find_map(|id| {
let pd = cx.doc.node(id).and_then(editable_path)?;
nearest_anchor(&pd, p, tol).map(|(si, ai, a)| (id, si, ai, a))
@@ -1224,6 +1227,32 @@ mod tests {
(d, a, b)
}
/// An anchor of a selected path is picked before the one of an unselected path on a layer
/// above that covers it, as Highlight anchors on mouse over already marks it (#1508); with
/// nothing selected, the topmost path's anchor is picked.
#[test]
fn a_selected_path_s_anchor_is_picked_before_one_above_it() {
let (mut d, a) = doc_with_rect();
let top = d.add_layer(None);
let b = d.alloc_id();
let sq = vectorcraft_geom::shapes::rectangle(Rect::new(101.0, 100.0, 201.0, 200.0));
d.insert(Some(top), 0, vectorcraft_doc::Node::path(b, sq, vectorcraft_doc::Appearance::default_art())).unwrap();
let p = paint();
let pick = |id: NodeId| vec![Action::Exec("select.anchors".into(), json!({"id": id.0, "anchors": [[0, 0]], "mode": "set"}))];
let s = anchors_of(a, &[(0, 2)]);
let mut t = DirectSelectionTool::new(false);
assert_eq!(t.pointer(&cx(&d, &s, &p), &PointerEvent::new(PointerKind::Down, 101.0, 100.0)), pick(a));
let mut whole = Selection::default();
whole.set([a]);
let mut t = DirectSelectionTool::new(false);
let cx2 = cx(&d, &whole, &p);
assert!(t.pointer(&cx2, &PointerEvent::new(PointerKind::Down, 101.0, 100.0)).is_empty());
assert_eq!(t.pointer(&cx2, &PointerEvent::new(PointerKind::Up, 101.0, 100.0)), pick(a));
let none = Selection::default();
let mut t = DirectSelectionTool::new(false);
assert_eq!(t.pointer(&cx(&d, &none, &p), &PointerEvent::new(PointerKind::Down, 101.0, 100.0)), pick(b));
}
/// The anchors `anchors` of path `id` direct-selected.
fn anchors_of(id: NodeId, anchors: &[AnchorRef]) -> Selection {
let mut s = Selection::default();
+86 -15
View File
@@ -4,7 +4,7 @@ use vectorcraft_geom::{Anchor, AnchorKind, CubicBez, ParamCurve, PathData, Point
use vectorcraft_pathops::{SimplifyOptions, simplify_with};
use crate::contour::Loop;
use crate::logo::{Cubic, Stats, Style, all_within, fit_outline, resample_closed, sample_cubics};
use crate::logo::{Cubic, Stats, Style, all_within, fit_open, fit_outline, resample_closed, resample_open, sample_cubics};
use crate::subpixel::{self, Crack};
#[derive(Clone, Copy, Debug)]
@@ -48,27 +48,98 @@ fn rdp(pts: &[Point], a: usize, b: usize, tol: f64, keep: &mut [bool]) {
}
}
/// Fit one loop of a `w × h` image into a closed Bézier subpath (pixel coordinates): its points
/// are placed to a fraction of a pixel ([`subpixel::outline`], which explains `shift`) and fitted as
/// Flat Logo mode fits its outlines (corners restored, straight runs as lines, the rest as few
/// curves as `style.tol` allows).
pub(crate) fn fit_loop(l: &Loop, w: usize, h: usize, shift: &dyn Fn(Crack) -> f64, style: &Style) -> Option<SubPath> {
let (pts, hard) = subpixel::outline(l, w, h, shift);
let mut style = *style;
if hard {
// No anti-aliasing: the edge is only known to about half a pixel (as in Flat Logo mode).
style.tol *= 2.5;
style.line_tol *= 1.8;
style.circle_tol *= 1.8;
style.sigma = 0.9;
fn reversed(mut segs: Vec<Cubic>) -> Vec<Cubic> {
segs.reverse();
for c in &mut segs {
c.reverse();
}
segs
}
fn before(a: Point, b: Point) -> std::cmp::Ordering {
a.x.total_cmp(&b.x).then(a.y.total_cmp(&b.y))
}
/// A whole loop fitted. The same loop gives the same curves whichever way it runs and wherever it
/// starts (it is fitted clockwise from its leftmost point): the outline of a shape and the hole it
/// leaves in the shape around it are one curve.
fn fit_closed(pts: &[Point], style: &Style) -> Option<Vec<Cubic>> {
let n = pts.len();
let area2: f64 = (0..n).map(|i| pts[i].x * pts[(i + 1) % n].y - pts[(i + 1) % n].x * pts[i].y).sum();
let flip = area2 < 0.0;
let mut pts = pts.to_vec();
if flip {
pts.reverse();
}
let start = (0..n).min_by(|&i, &j| before(pts[i], pts[j])).unwrap_or(0);
pts.rotate_left(start);
let mut stats = Stats::default();
let mut segs = fit_outline(&pts, &style, &mut stats)?;
let mut segs = fit_outline(&pts, style, &mut stats)?;
// A fit that strayed was replaced by a plain one that nothing has checked: one that strays too
// (a wild handle on a tiny or ragged loop) gives way to the outline's own points.
if stats.reverted > 0 && !all_within(&sample_cubics(&segs, 0.25), &resample_closed(&pts, 0.5).map_or_else(|| pts.clone(), |(p, _)| p), 1.5) {
segs = polygon(&pts, style.tol);
}
Some(if flip { reversed(segs) } else { segs })
}
/// A piece of a loop between two junctions fitted, from its first point to its last. The same
/// piece gives the same curve whichever way it runs (it is fitted from its end further left): the
/// edge two regions share is one curve.
fn fit_piece(pts: &[Point], style: &Style) -> Vec<Cubic> {
let n = pts.len();
let (Some(&first), Some(&last)) = (pts.first(), pts.last()) else { return vec![] };
let flip = match before(first, last) {
std::cmp::Ordering::Equal => n > 3 && before(pts[1], pts[n - 2]).is_gt(),
order => order.is_gt(),
};
let mut pts = pts.to_vec();
if flip {
pts.reverse();
}
let mut segs = fit_open(&pts, style, &mut Stats::default());
// Nothing else checks this fit: one that strays gives way to the piece's own points.
if !all_within(&sample_cubics(&segs, 0.25), &resample_open(&pts, 0.5).map_or_else(|| pts.clone(), |(p, _)| p), 1.5) {
let mut keep = vec![false; n];
rdp(&pts, 0, n - 1, style.tol, &mut keep);
keep[0] = true;
keep[n - 1] = true;
let kept: Vec<Point> = (0..n).filter(|&i| keep[i]).map(|i| pts[i]).collect();
segs = kept.windows(2).filter(|p| p[0] != p[1]).map(|p| [p[0], p[0], p[1], p[1]]).collect();
}
if flip { reversed(segs) } else { segs }
}
/// Fit one loop of a `w × h` image into a closed Bézier subpath (pixel coordinates): its points
/// are placed to a fraction of a pixel ([`subpixel::outline`], which explains `across`) and fitted
/// as Flat Logo mode fits its outlines (corners restored, straight runs as lines, the rest as few
/// curves as `style.tol` allows), piece by piece between its junctions, so that the regions on
/// either side of an edge get the same curve for it.
pub(crate) fn fit_loop(
l: &Loop,
w: usize,
h: usize,
across: &dyn Fn(Crack) -> (f64, u32),
junction_at: &dyn Fn(i32, i32) -> Option<Point>,
style: &Style,
) -> Option<SubPath> {
let pieces = subpixel::outline(l, w, h, across, junction_at);
let mut segs: Vec<Cubic> = Vec::new();
for piece in &pieces {
let mut style = *style;
if piece.hard {
// No anti-aliasing: the edge is only known to about half a pixel (as in Flat Logo mode).
style.tol *= 2.5;
style.line_tol *= 1.8;
style.circle_tol *= 1.8;
style.sigma = 0.9;
}
if piece.closed {
segs = fit_closed(&piece.pts, &style)?;
} else {
segs.extend(fit_piece(&piece.pts, &style));
}
}
let n = segs.len();
// A straight piece has no handles.
let straight = |c: &Cubic| seg_dist(c[1], c[0], c[3]) < 1e-6 && seg_dist(c[2], c[0], c[3]) < 1e-6;
+70 -2
View File
@@ -12,6 +12,9 @@
//! colours: the blends that anti-aliasing and blur leave along edges take none of it, colours that
//! noise made of one colour are merged, and a blend pixel goes to one of the two colours it lies
//! between (see `quantize`).
//! A continuous-tone image (a photo) is first smoothed within its tones, edges kept (see
//! `smooth`): otherwise its noise decides, pixel by pixel, which of two neighbouring tones a
//! pixel gets, and every such pixel is a speck.
//! 2. **Remove noise**: 4-connected same-colour components smaller than `noise` pixels are merged
//! into their most common neighbouring colour.
//! 3. **Follow boundaries**: for each colour layer, the pixel-crack edges between inside and
@@ -22,6 +25,9 @@
//! is (an anti-aliased or blurred edge pixel is part one tone, part the other), so the outline
//! is right to a fraction of a pixel before any fitting; hard-edged images are read as
//! staircases instead (see `subpixel`).
//! Outlines are cut at their junctions (where three regions meet, and at the image's border)
//! and each piece between two is fitted on its own, the same way from either side, so that two
//! abutting regions have one and the same curve along the edge they share.
//! 5. **Curves**: the outline is fitted as Flat Logo mode fits its own (`logo::fit_outline`):
//! corners the pixels rounded are put back, straight runs become lines, a round outline a
//! true circle, and the rest as few cubic Béziers as the Paths tolerance allows; Snap Curves To
@@ -41,6 +47,7 @@ mod fit;
mod logo;
mod mosaic;
mod quantize;
mod smooth;
mod subpixel;
use std::sync::atomic::{AtomicUsize, Ordering};
@@ -457,6 +464,9 @@ pub fn trace_within(img: &Raster, params: &TraceParams, max_anchors: usize) -> R
if params.mode == Mode::Logo {
return logo::trace_logo(img, params, max_anchors);
}
// A photo is traced from a copy with its noise smoothed away (see `smooth`).
let smoothed = (params.mode != Mode::BlackAndWhite && quantize::continuous_tone(img)).then(|| smooth::smoothed(img));
let img = smoothed.as_ref().unwrap_or(img);
let mut q = quantize(img, params);
denoise(&mut q.labels, w, h, params.noise as usize);
// Pixel count per palette entry.
@@ -469,6 +479,19 @@ pub fn trace_within(img: &Raster, params: &TraceParams, max_anchors: usize) -> R
// Layers bottom → top: largest area first.
let mut order: Vec<usize> = (0..q.palette.len()).filter(|&i| counts[i] > 0).collect();
order.sort_by(|a, b| counts[*b].cmp(&counts[*a]).then(a.cmp(b)));
if params.method == Method::Overlapping {
// Stacked layers go by lightness instead, from the largest colour's end of the scale: each
// layer reaches under all those above it, so where two colours meet, every layer between
// them in the stack ends on that same edge and shows through its anti-aliasing. Neighbours
// in a picture are mostly neighbours in tone, and in this order they are neighbours in the
// stack too (by area, an unrelated colour's edge would shine through as a hairline).
let light = |i: usize| q.palette.get(i).map_or(0, |c| u32::from(c[0]) * 299 + u32::from(c[1]) * 587 + u32::from(c[2]) * 114);
let first = order.first().copied();
order.sort_by(|a, b| light(*a).cmp(&light(*b)).then(a.cmp(b)));
if first.is_some_and(|f| order.iter().position(|&i| i == f).is_some_and(|at| at * 2 >= order.len())) {
order.reverse();
}
}
let mut rank = vec![usize::MAX; q.palette.len()];
for (r, &i) in order.iter().enumerate() {
rank[i] = r;
@@ -538,6 +561,51 @@ struct Layers<'a> {
}
impl Layers<'_> {
/// Ignore White: white is no part of any layer (stacked layers reach under the layers above
/// them, and must not reach under white that is left out).
fn ignored(&self, label: u16) -> bool {
self.params.ignore_white && self.q.palette.get(label as usize).is_some_and(|c| is_white(*c))
}
/// The region across a crack, for cutting outlines at their junctions: the outside pixel's
/// colour. Stacked layers end on many colours at once and share no edge: one neighbour.
fn neighbour(&self, c: Crack) -> u32 {
if self.params.method == Method::Overlapping {
return 0;
}
c.at(1).and_then(|i| self.q.labels.get(i)).map_or(u32::from(TRANSPARENT), |&l| u32::from(l))
}
/// The junction at pixel corner `(x, y)`, if there is one: where three or four regions
/// meet, or two parts of a region touch by the corner only, or an edge reaches the image's
/// border. It lies at the corner, moved across by what the edges that run up and down from it
/// say, and up or down by what those to its left and right say (the mean, where there are
/// two). It depends on the corner alone, so every region around it gets the same point; on the
/// image's border it stays on the border.
fn junction(&self, x: i32, y: i32) -> Option<vectorcraft_geom::Point> {
let label = |px: i32, py: i32| Crack::new((px, py), (1, 0), self.w, self.h).at(0).and_then(|i| self.q.labels.get(i).copied());
// The four pixels around the corner (`None` off the image), and the edges between them.
let around = [label(x - 1, y - 1), label(x, y - 1), label(x, y), label(x - 1, y)];
let edges = (0..4).filter(|&i| around[i] != around[(i + 1) % 4]).count();
let apart = |a: usize, b: usize, c: usize, d: usize| around[a] == around[c] && around[b] != around[a] && around[d] != around[a];
let touching = apart(0, 1, 2, 3) || apart(1, 2, 3, 0);
// (Stacked layers share no edges: they are cut at the image's border only.)
if edges < 3 && !touching || self.params.method == Method::Overlapping {
return None;
}
// The shift of the crack between `a` and the pixel `step` from it, if both are in the
// image and of different regions.
let shift = |a: (i32, i32), step: (i32, i32)| {
let (la, lb) = (label(a.0, a.1)?, label(a.0 + step.0, a.1 + step.1)?);
(la != lb).then(|| self.shift(Crack::new(a, step, self.w, self.h)).clamp(-0.5, 0.5))
};
let mean = |a: Option<f64>, b: Option<f64>| match (a, b) {
(Some(a), Some(b)) => (a + b) / 2.0,
(Some(v), None) | (None, Some(v)) => v,
(None, None) => 0.0,
};
let dx = mean(shift((x - 1, y - 1), (1, 0)), shift((x - 1, y), (1, 0)));
let dy = mean(shift((x - 1, y - 1), (0, 1)), shift((x, y - 1), (0, 1)));
Some(vectorcraft_geom::Point::new(f64::from(x) + dx, f64::from(y) + dy))
}
/// How far the edge lies from a crack between two pixels, towards the outside one (−0.5 to 0.5).
///
/// Each pixel of the column across the crack is read as a blend of the tones on its two sides
@@ -649,7 +717,7 @@ impl Layers<'_> {
.map(|(i, &l)| {
l != TRANSPARENT
&& !thin.get(i).copied().unwrap_or(false)
&& if overlapping { self.rank.get(l as usize).is_some_and(|&lr| lr >= r) } else { l as usize == ci }
&& if overlapping { self.rank.get(l as usize).is_some_and(|&lr| lr >= r) && !self.ignored(l) } else { l as usize == ci }
})
.collect();
// Without Fills, areas are outlined with a 1 px stroke.
@@ -665,7 +733,7 @@ impl Layers<'_> {
true
};
for comp in trace_mask(&mask, w, h) {
let fit = |l: &Loop| fit::fit_loop(l, w, h, &|c| self.shift(c), &self.style);
let fit = |l: &Loop| fit::fit_loop(l, w, h, &|c| (self.shift(c), self.neighbour(c)), &|x, y| self.junction(x, y), &self.style);
let Some(outer) = fit(&comp.outer) else { continue };
let mut subs = vec![outer];
for hole in &comp.holes {
+35
View File
@@ -52,6 +52,41 @@ pub(crate) fn resample_closed(p: &[Point], step: f64) -> Option<(Vec<Point>, f64
Some((out, total / m as f64))
}
/// An open polyline resampled at (about) `step` spacing, both ends kept; also returns the exact
/// spacing used.
pub(crate) fn resample_open(p: &[Point], step: f64) -> Option<(Vec<Point>, f64)> {
let n = p.len();
let (first, last) = (*p.first()?, *p.last()?);
if n < 2 || step.is_nan() || step <= 0.0 || !p.iter().all(|&q| finite(q)) {
return None;
}
let mut cum = Vec::with_capacity(n);
cum.push(0.0);
for pair in p.windows(2) {
cum.push(cum.last().copied().unwrap_or(0.0) + pair[0].distance(pair[1]));
}
let total = cum.last().copied().unwrap_or(0.0);
if total.is_nan() || total <= 0.0 {
return None;
}
let m = ((total / step).round() as usize).clamp(1, MAX_POINTS);
let mut out = Vec::with_capacity(m + 1);
out.push(first);
let mut j = 0usize;
for i in 1..m {
let s = total * i as f64 / m as f64;
while cum.get(j + 1).is_some_and(|&c| c < s) {
j += 1;
}
let (c0, c1) = (*cum.get(j)?, *cum.get(j + 1)?);
let t = if c1 > c0 { (s - c0) / (c1 - c0) } else { 0.0 };
let (a, b) = (*p.get(j)?, *p.get(j + 1)?);
out.push(a + (b - a) * t);
}
out.push(last);
Some((out, total / m as f64))
}
fn kernel(sigma: f64) -> Vec<f64> {
let s = sigma.max(0.3);
let r = ((3.0 * s).ceil() as i64).max(1);
+2 -2
View File
@@ -24,7 +24,7 @@ mod tests;
mod testutil;
mod unmix;
pub(crate) use geom::{Cubic, all_within, resample_closed, sample_cubics};
pub(crate) use outline::{Stats, Style, fit_outline};
pub(crate) use geom::{Cubic, all_within, resample_closed, resample_open, sample_cubics};
pub(crate) use outline::{Stats, Style, fit_open, fit_outline};
pub(crate) use pipeline::trace_logo;
pub(crate) use restore::RestoreParams;
+103 -44
View File
@@ -1,7 +1,9 @@
//! One outline: smooth, restore corners, snap to lines and arcs, fit Béziers, and verify.
use super::bezier::{fit_cubics, tangent};
use super::geom::{Cubic, all_within, arc_cubics, circle_fit, find_corners, finite, resample_closed, sample_cubics, smooth_closed, smooth_open};
use super::geom::{
Cubic, all_within, arc_cubics, circle_fit, find_corners, finite, resample_closed, resample_open, sample_cubics, smooth_closed, smooth_open,
};
use super::restore::{RestoreParams, restore_corners};
use vectorcraft_geom::Point;
@@ -95,6 +97,105 @@ fn plain_fit(p: &[Point], tol: f64) -> Vec<Cubic> {
fit_cubics(&closed, t, -t, tol)
}
/// One run between two corners, added to `segs`: a line or an arc where it is one, else fitted
/// curves. `sg` is the smoothing, in samples.
fn fit_run(run: &[Point], sg: f64, st: &Style, stats: &mut Stats, segs: &mut Vec<Cubic>) {
let (Some(&first), Some(&last)) = (run.first(), run.last()) else { return };
if run.len() < 4 {
if run.len() >= 2 && first.distance(last) > 1e-9 {
segs.push(line_cubic(first, last));
}
return;
}
let sm = smooth_open(run, sg);
let (Some(&a), Some(&b)) = (sm.first(), sm.last()) else { return };
let len = a.distance(b);
if st.snap && len > 1.5 {
let d = b - a;
let nrm = kurbo::Vec2::new(-d.y, d.x) / len;
if sm.iter().all(|q| (*q - a).dot(nrm).abs() < st.line_tol) {
stats.lines += 1;
segs.push(line_cubic(a, b));
return;
}
}
if st.snap
&& st.arcs
&& sm.len() > 12
&& len > 1.0
&& let Some(c) = circle_fit(&sm)
&& c.resid < st.circle_tol
&& c.r > 2.5
&& c.r < 400.0
&& let Some((a0, a1)) = sweep(&sm, c.c)
&& (a1 - a0).abs() > 0.35
{
stats.arcs += 1;
let first = segs.len();
segs.extend(arc_cubics(c.c, c.r, a0, a1));
// The fitted circle may miss the corners by up to the snap tolerance: end exactly on them.
if let Some(s) = segs.get_mut(first) {
s[0] = a;
}
if let Some(s) = segs.last_mut() {
s[3] = b;
}
return;
}
segs.extend(fit_cubics(&sm, tangent(&sm, 0, 4, 1), tangent(&sm, sm.len() - 1, 4, -1), st.tol));
}
/// The open run `p` as cubic Béziers from its first point to its last, both kept exactly: cut at
/// its corners, each stretch a line, an arc or fitted curves as in a closed outline. (No corner is
/// put back here: a piece of an outline between two junctions ends on pixel corners anyway.)
pub(crate) fn fit_open(p: &[Point], st: &Style, stats: &mut Stats) -> Vec<Cubic> {
let mut segs = Vec::new();
let (Some(&first), Some(&last)) = (p.first(), p.last()) else { return segs };
let whole = |segs: &mut Vec<Cubic>| {
if first.distance(last) > 1e-9 {
segs.push(line_cubic(first, last));
}
};
let Some((r, step)) = resample_open(p, st.step) else {
whole(&mut segs);
return segs;
};
let n = r.len();
let s0 = smooth_open(&r, (0.18 / step).max(1.0));
let w = ((st.corner_win / step).round() as usize).max(2);
let angle = |i: usize| {
let (Some(&c), Some(&a), Some(&b)) = (s0.get(i), i.checked_sub(w).and_then(|j| s0.get(j)), s0.get(i + w)) else { return 0.0 };
let (v1, v2) = (c - a, b - c);
v1.cross(v2).atan2(v1.dot(v2)).abs().to_degrees()
};
let mut cuts = vec![0];
for i in w..n.saturating_sub(w) {
let here = angle(i);
if here >= st.corner_deg && here >= angle(i - 1) && here > angle(i + 1) && cuts.last().is_none_or(|&l| i - l > w) {
cuts.push(i);
}
}
cuts.push(n - 1);
let sg = st.sigma / step;
for pair in cuts.windows(2) {
let Some(run) = r.get(pair[0]..=pair[1]) else { continue };
let before = segs.len();
fit_run(run, sg, st, stats, &mut segs);
// Every stretch must lead on to the next.
if segs.len() == before
&& let (Some(&a), Some(&b)) = (run.first(), run.last())
&& a.distance(b) > 1e-9
{
segs.push(line_cubic(a, b));
}
}
if !sane(&segs) {
segs.clear();
whole(&mut segs);
}
segs
}
fn styled_fit(p: &[Point], st: &Style, stats: &mut Stats) -> Option<Vec<Cubic>> {
let (mut r, step) = resample_closed(p, st.step)?;
let sg = st.sigma / step;
@@ -147,49 +248,7 @@ fn styled_fit(p: &[Point], st: &Style, stats: &mut Stats) -> Option<Vec<Cubic>>
let i1 = *corners.get((ci + 1) % corners.len())?;
let count = if i1 <= i0 { i1 + n - i0 } else { i1 - i0 } + 1;
let run: Vec<Point> = (0..count).filter_map(|k| r.get((i0 + k) % n).copied()).collect();
let (Some(&first), Some(&last)) = (run.first(), run.last()) else { continue };
if run.len() < 4 {
if run.len() >= 2 && first.distance(last) > 1e-9 {
segs.push(line_cubic(first, last));
}
continue;
}
let sm = smooth_open(&run, sg);
let (Some(&a), Some(&b)) = (sm.first(), sm.last()) else { continue };
let len = a.distance(b);
if st.snap && len > 1.5 {
let d = b - a;
let nrm = kurbo::Vec2::new(-d.y, d.x) / len;
if sm.iter().all(|q| (*q - a).dot(nrm).abs() < st.line_tol) {
stats.lines += 1;
segs.push(line_cubic(a, b));
continue;
}
}
if st.snap
&& st.arcs
&& sm.len() > 12
&& len > 1.0
&& let Some(c) = circle_fit(&sm)
&& c.resid < st.circle_tol
&& c.r > 2.5
&& c.r < 400.0
&& let Some((a0, a1)) = sweep(&sm, c.c)
&& (a1 - a0).abs() > 0.35
{
stats.arcs += 1;
let first = segs.len();
segs.extend(arc_cubics(c.c, c.r, a0, a1));
// The fitted circle may miss the corners by up to the snap tolerance: end exactly on them.
if let Some(s) = segs.get_mut(first) {
s[0] = a;
}
if let Some(s) = segs.last_mut() {
s[3] = b;
}
continue;
}
segs.extend(fit_cubics(&sm, tangent(&sm, 0, 4, 1), tangent(&sm, sm.len() - 1, 4, -1), st.tol));
fit_run(&run, sg, st, stats, &mut segs);
}
(!segs.is_empty()).then_some(segs)
}
+29
View File
@@ -305,6 +305,35 @@ fn settled(mut q: Quantized, img: &Raster, own: &[bool]) -> Quantized {
if changed { compact(q.labels, q.palette) } else { q }
}
/// Whether `img` is continuous tone (a photo, a gradient) rather than flat art, however noisy
/// or unevenly lit (a scan): whether eight colours leave much of it unsaid. Flat art is a few
/// colours and what noise and lighting make of them, and eight colours come within a few levels
/// of every pixel; a photo's tones spread all through its range, and eight colours stay far from
/// most of them (more than 6 levels, and more than a tenth of how far a single colour stays).
pub(crate) fn continuous_tone(img: &Raster) -> bool {
let hk = HistKey::new(img);
let mut bins = vec![Bin::default(); 1 << 15];
for p in img.rgba.as_chunks::<4>().0 {
if p[3] >= 128 {
bins[hk.key(p[0], p[1], p[2])].add(p);
}
}
let used: Vec<Used> = bins.iter().enumerate().filter(|(_, b)| b.n > 0).map(|(i, b)| (i, b.mean(), b.n as f64)).collect();
// The root-mean-square distance (levels) from the pixels to the nearest of `k` colours.
let unsaid = |k: usize| {
let colors = centers(&median_cut(&used, k, 0.0));
let (mut sum, mut n) = (0.0, 0.0);
for (_, c, weight) in &used {
let d2 = colors.iter().map(|m| (0..3).map(|ch| (m[ch] - c[ch]).powi(2)).sum::<f64>()).fold(f64::INFINITY, f64::min);
sum += d2 * weight;
n += weight;
}
if n > 0.0 { (sum / n).sqrt() } else { 0.0 }
};
let eight = unsaid(8);
eight > 6.0 && eight > 0.1 * unsaid(1)
}
/// Drop unused palette entries and merge duplicates.
fn compact(mut labels: Vec<u16>, palette: Vec<[u8; 3]>) -> Quantized {
let mut used = vec![false; palette.len()];
+97
View File
@@ -0,0 +1,97 @@
//! Edge-preserving smoothing of continuous-tone images before they are quantised.
//!
//! A photo's tones run into each other, and its noise is as large as the step from one palette
//! colour to the next: quantised as it is, noise decides pixel by pixel which of two neighbouring
//! colours a pixel gets, and the trace is tens of thousands of specks. Each pixel is averaged with
//! its neighbours instead, each weighted by how alike it is (a bilateral filter: C. Tomasi and
//! R. Manduchi, "Bilateral Filtering for Gray and Color Images", 1998), so that noise within a tone
//! is averaged away while an edge between two tones stays where and as sharp as it was. Three
//! rounds, each along rows and then along columns, three pixels at a time.
use crate::{Raster, parallel_map};
/// Colours this far apart (levels, all channels together) count half as much as equal ones.
const ALIKE: f64 = 20.0;
/// One pass along rows (`dx = 1`) or columns (`dx = 0`).
fn pass(src: &[u8], w: usize, h: usize, along_rows: bool) -> Vec<u8> {
let rows: Vec<usize> = (0..h).collect();
let px = |x: usize, y: usize| src.get((y * w + x) * 4..(y * w + x) * 4 + 4);
let done = parallel_map(&rows, |&y| {
let mut out = Vec::with_capacity(w * 4);
for x in 0..w {
let Some(p) = px(x, y) else { continue };
if p[3] < 128 {
out.extend_from_slice(p);
continue;
}
let near = if along_rows {
[(x > 0).then(|| (x - 1, y)), (x + 1 < w).then(|| (x + 1, y))]
} else {
[(y > 0).then(|| (x, y - 1)), (y + 1 < h).then(|| (x, y + 1))]
};
let (mut sum, mut weight) = ([f64::from(p[0]), f64::from(p[1]), f64::from(p[2])], 1.0);
for q in near.into_iter().flatten().filter_map(|(x, y)| px(x, y)).filter(|q| q[3] >= 128) {
let d2: f64 = (0..3).map(|k| (f64::from(q[k]) - f64::from(p[k])).powi(2)).sum();
let wt = 1.0 / (1.0 + d2 / (ALIKE * ALIKE)).powi(2);
for k in 0..3 {
sum[k] += wt * f64::from(q[k]);
}
weight += wt;
}
out.extend(sum.map(|v| (v / weight).round() as u8));
out.push(p[3]);
}
out
});
done.concat()
}
/// `img` with the noise within its tones smoothed away and its edges kept.
pub(crate) fn smoothed(img: &Raster) -> Raster {
let (w, h) = (img.width as usize, img.height as usize);
let mut rgba = img.rgba.clone();
if rgba.len() == w * h * 4 {
for _ in 0..3 {
rgba = pass(&pass(&rgba, w, h, true), w, h, false);
}
}
Raster { width: img.width, height: img.height, rgba }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn noise_goes_and_an_edge_stays() {
// Left half about 60, right half about 160, with noise of ±6 on both.
let img = Raster::from_fn(40, 20, |x, y| {
let mut n = x.wrapping_mul(0x9E37_79B1) ^ y.wrapping_mul(0x85EB_CA77);
n ^= n >> 15;
n = n.wrapping_mul(0x2C1B_3C6D);
let n = ((n >> 12) % 13) as u8;
let v = if x < 20 { 54 + n } else { 154 + n };
[v, v, v, 255]
});
let out = smoothed(&img);
let spread = |r: &Raster, x0: u32, x1: u32| {
let v: Vec<u8> = (0..20).flat_map(|y| (x0..x1).map(move |x| (x, y))).map(|(x, y)| r.pixel(x, y)[0]).collect();
v.iter().max().unwrap() - v.iter().min().unwrap()
};
assert_eq!(spread(&img, 0, 20), 12);
assert!(spread(&out, 0, 20) <= 6 && spread(&out, 20, 40) <= 6, "{} {}", spread(&out, 0, 20), spread(&out, 20, 40));
// The edge is still one pixel sharp, where it was.
assert!(out.pixel(19, 10)[0] < 70 && out.pixel(20, 10)[0] > 150);
}
#[test]
fn transparent_pixels_and_odd_sizes_pass_through() {
let img = Raster::from_fn(3, 1, |x, _| [10 * x as u8, 0, 0, if x == 1 { 0 } else { 255 }]);
let out = smoothed(&img);
assert_eq!(out.pixel(1, 0), [10, 0, 0, 0]);
assert_eq!((out.width, out.height, out.rgba.len()), (3, 1, 12));
let broken = Raster { width: 4, height: 4, rgba: vec![0; 7] };
assert_eq!(smoothed(&broken).rgba.len(), 7);
}
}
+192 -44
View File
@@ -40,6 +40,10 @@ pub(crate) struct Crack {
}
impl Crack {
/// The crack between pixel `inside` and the pixel `step` (one pixel right or down) from it.
pub fn new(inside: (i32, i32), step: (i32, i32), w: usize, h: usize) -> Self {
Self { inside, step, w, h }
}
/// The index of the pixel `k` steps out from the inside pixel (0: the inside pixel, 1: the
/// outside one, −1: the one behind the inside pixel), if the image has it.
pub fn at(&self, k: i32) -> Option<usize> {
@@ -52,20 +56,58 @@ fn pixel(p: (i32, i32), w: usize, h: usize) -> Option<usize> {
(x < w && y < h).then(|| y * w + x)
}
/// The outline of `l` (a loop of a `w × h` image) as points, and whether its edge is hard.
/// A stretch of an outline with one neighbour along it: its points, and whether its edge is hard.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct Piece {
pub pts: Vec<Point>,
pub hard: bool,
/// The piece is a whole loop without a junction.
pub closed: bool,
}
/// What lies across a crack on the image's border: one neighbour per side, so that the image's
/// corners are junctions and stay exact.
fn border(dir: (i32, i32)) -> u32 {
u32::MAX
- match dir {
(1, 0) => 0,
(0, 1) => 1,
(-1, 0) => 2,
_ => 3,
}
}
/// The outline of `l` (a loop of a `w × h` image) as points.
///
/// `shift` says how far (in pixels, −0.5 to 0.5, positive towards the outside pixel) the edge lies
/// from a crack.
pub(crate) fn outline(l: &Loop, w: usize, h: usize, shift: &dyn Fn(Crack) -> f64) -> (Vec<Point>, bool) {
/// `across` says, for a crack, how far (in pixels, −0.5 to 0.5, positive towards the outside
/// pixel) the edge lies from it, and which region is on its other side.
///
/// The outline comes in pieces, cut at its junctions: the pixel corners where the region on the
/// other side changes (three or more regions meet there, or the image's border begins), and
/// those where two parts of a region touch by a corner only (there its outline and its
/// neighbour's part ways without the neighbour changing). `junction_at` says of a pixel corner
/// whether it is a junction of that second kind, when asked without `must`, and where the
/// junction really lies, the same for every region around it. A piece
/// is the whole edge between two regions, and both get exactly the same points for it (a crack
/// gives the same point from either side, shifts are rounded to 1/1024 px so that they agree to
/// the last bit, and whether a piece is hard is decided by the piece alone), so that fitted the
/// same way it is one curve for both. A loop without junctions is one closed piece.
pub(crate) fn outline(
l: &Loop,
w: usize,
h: usize,
across: &dyn Fn(Crack) -> (f64, u32),
junction_at: &dyn Fn(i32, i32) -> Option<Point>,
) -> Vec<Piece> {
let v = &l.pts;
let n = v.len();
let at = |i: usize| Point::new(f64::from(v[i % n].0), f64::from(v[i % n].1));
let raw = || (0..n).map(at).collect::<Vec<_>>();
if n < 4 {
return (raw(), true);
return vec![Piece { pts: (0..n).map(at).collect(), hard: true, closed: true }];
}
let mut edges = Vec::with_capacity(n);
let mut shifts: Vec<f64> = Vec::new();
// Per crack: its shift, the region across it, and the edge it is on.
let (mut shifts, mut others, mut edge_of): (Vec<f64>, Vec<u32>, Vec<usize>) = (vec![], vec![], vec![]);
for i in 0..n {
let (a, b) = (v[i], v[(i + 1) % n]);
let (dx, dy) = (b.0 - a.0, b.1 - a.1);
@@ -82,43 +124,95 @@ pub(crate) fn outline(l: &Loop, w: usize, h: usize, shift: &dyn Fn(Crack) -> f64
_ => ((sx, sy - 1), (sx - 1, sy - 1)),
};
let crack = Crack { inside, step: (outside.0 - inside.0, outside.1 - inside.1), w, h };
let s = match crack.at(1) {
Some(_) => shift(crack),
let (s, other) = match crack.at(1) {
Some(_) => across(crack),
// The edge of the image is where it is.
_ => 0.0,
_ => (0.0, border(dir)),
};
shifts.push(if s.is_finite() { s.clamp(-0.5, 0.5) } else { 0.0 });
shifts.push(if s.is_finite() { (s.clamp(-0.5, 0.5) * 1024.0).round() / 1024.0 } else { 0.0 });
others.push(other);
edge_of.push(i);
}
}
// A hard edge: nearly every crack moves by the same amount.
let mut sorted = shifts.clone();
let mid = sorted.len() / 2;
let median = if sorted.is_empty() { 0.0 } else { *sorted.select_nth_unstable_by(mid, f64::total_cmp).1 };
let hard = shifts.iter().filter(|s| (*s - median).abs() > 0.03).count() * 4 < shifts.len();
let cracks = shifts.len();
if cracks == 0 {
return vec![Piece { pts: (0..n).map(at).collect(), hard: true, closed: true }];
}
// The pixel corner each crack starts at.
let corner_of = |c: usize| {
let (i, e) = (edge_of[c], &edges[edge_of[c]]);
(v[i].0 + e.dir.0 * (c - e.first) as i32, v[i].1 + e.dir.1 * (c - e.first) as i32)
};
// A junction lies at the start of each crack whose neighbour is not the crack before's, and
// where the callback says one is.
let junctions: Vec<Option<Point>> = (0..cracks)
.map(|c| {
let (x, y) = corner_of(c);
let changed = others[c] != others[(c + cracks - 1) % cracks];
junction_at(x, y).or_else(|| changed.then(|| Point::new(f64::from(x), f64::from(y))))
})
.collect();
let junction = |c: usize| junctions[c].is_some();
let first = (0..cracks).find(|&c| junction(c));
// A hard edge: nearly every crack of the piece moves by the same amount. (The middle of the
// two middle shifts, so that the piece is as hard read from its other side, shifts negated.)
let is_hard = |piece: &[f64]| {
let mut sorted = piece.to_vec();
sorted.sort_by(f64::total_cmp);
let median = (sorted[sorted.len() / 2] + sorted[(sorted.len() - 1) / 2]) / 2.0;
piece.iter().filter(|s| (*s - median).abs() > 0.03).count() * 4 < piece.len()
};
// Which way the loop turns at vertex `i`, and whether edge `i` is a step of a staircase: one
// pixel long, turning one way where it starts and the other where it ends.
// (At a junction the loop goes its own way, its neighbour another: a turn there says nothing
// about the edge they share, and counts as none.)
let turn = |i: usize| {
let (a, b) = (edges[(i + n - 1) % n].dir, edges[i % n].dir);
(a.0 * b.1 - a.1 * b.0).signum()
if junctions[edges[i % n].first].is_some() { 0 } else { (a.0 * b.1 - a.1 * b.0).signum() }
};
let step: Vec<bool> = (0..n).map(|i| edges[i].len == 1 && turn(i) * turn(i + 1) < 0).collect();
let outward = |d: (i32, i32)| Vec2::new(f64::from(d.1), f64::from(-d.0));
let shift_of = |e: &Edge, k: usize| shifts.get(e.first + k).copied().unwrap_or(0.0);
let mut out = Vec::with_capacity(if hard { n } else { shifts.len() + n });
for i in 0..n {
let (before, e) = (&edges[(i + n - 1) % n], &edges[i]);
if !step[i] && !step[(i + n - 1) % n] {
// A true corner: where its two edges, each moved by its own shift, meet.
out.push(at(i) + outward(before.dir) * shift_of(before, before.len.saturating_sub(1)) + outward(e.dir) * shift_of(e, 0));
let mut pieces: Vec<Piece> = Vec::new();
let start = first.unwrap_or(0);
let mut c = 0;
while c < cracks {
// The cracks of one piece: up to the next junction.
let len = (1..cracks - c).find(|&k| junction((start + c + k) % cracks)).unwrap_or(cracks - c);
let own: Vec<f64> = (0..len).map(|k| shifts[(start + c + k) % cracks]).collect();
let hard = is_hard(&own);
let mut pts = Vec::with_capacity(len + 2);
for k in 0..len {
let crack = (start + c + k) % cracks;
let i = edge_of[crack];
let (e, along_edge) = (&edges[i], crack - edges[i].first);
let corner = at(i) + Vec2::new(f64::from(e.dir.0), f64::from(e.dir.1)) * along_edge as f64;
if k == 0 && first.is_some() {
// The junction itself: the one point every region around it has.
pts.push(junctions[crack].unwrap_or(corner));
} else if along_edge == 0 && !step[i] && !step[(i + n - 1) % n] {
// A true corner: where its two edges, each moved by its own shift, meet.
let before = &edges[(i + n - 1) % n];
pts.push(corner + outward(before.dir) * shifts[(crack + cracks - 1) % cracks] + outward(e.dir) * shifts[crack]);
}
if step[i] || !hard {
pts.push(corner + Vec2::new(f64::from(e.dir.0), f64::from(e.dir.1)) * 0.5 + outward(e.dir) * shifts[crack]);
}
}
if step[i] || !hard {
let along = Vec2::new(f64::from(e.dir.0), f64::from(e.dir.1));
out.extend((0..e.len).map(|k| at(i) + along * (k as f64 + 0.5) + outward(e.dir) * shift_of(e, k)));
if first.is_some() {
// It ends on the next junction: the corner the next piece starts on.
let next = (start + c + len) % cracks;
let (x, y) = corner_of(next);
pts.push(junctions[next].unwrap_or(Point::new(f64::from(x), f64::from(y))));
}
pieces.push(Piece { pts, hard, closed: first.is_none() });
c += len;
}
if out.len() < 3 { (raw(), hard) } else { (out, hard) }
if first.is_none() && pieces.first().is_some_and(|p| p.pts.len() < 3) {
return vec![Piece { pts: (0..n).map(at).collect(), hard: true, closed: true }];
}
pieces
}
#[cfg(test)]
@@ -130,11 +224,27 @@ mod tests {
trace_mask(mask, w, h).remove(0).outer
}
/// No junctions but where the neighbour changes, and those on the pixel grid.
fn grid(_: i32, _: i32) -> Option<Point> {
None
}
/// The outline with one neighbour all round (the image's border too): its points, and whether
/// it is hard.
fn whole(l: &Loop, w: usize, h: usize, shift: &dyn Fn(Crack) -> f64) -> (Vec<Point>, bool) {
let mut pieces = outline(l, w, h, &|c| (shift(c), 0), &grid);
let hard = pieces.iter().all(|p| p.hard);
// Only the image's border makes junctions here: drop each piece's closing point.
let split = pieces.len() > 1;
let pts = pieces.iter_mut().flat_map(|p| p.pts.drain(..p.pts.len() - usize::from(split))).collect();
(pts, hard)
}
#[test]
fn a_hard_rectangle_keeps_its_four_corners() {
let (w, h) = (8, 6);
let mask: Vec<bool> = (0..w * h).map(|i| (2..6).contains(&(i % w)) && (1..5).contains(&(i / w))).collect();
let (pts, hard) = outline(&loop_of(&mask, w, h), w, h, &|_| 0.0);
let (pts, hard) = whole(&loop_of(&mask, w, h), w, h, &|_| 0.0);
assert!(hard);
assert_eq!(pts, [(2.0, 1.0), (6.0, 1.0), (6.0, 5.0), (2.0, 5.0)].map(Point::from));
}
@@ -144,7 +254,7 @@ mod tests {
// Below the line y = x / 4 + 2: treads four pixels long.
let (w, h) = (16, 8);
let mask: Vec<bool> = (0..w * h).map(|i| (i / w) as f64 + 0.5 > (i % w) as f64 / 4.0 + 2.0).collect();
let (pts, hard) = outline(&loop_of(&mask, w, h), w, h, &|_| 0.0);
let (pts, hard) = whole(&loop_of(&mask, w, h), w, h, &|_| 0.0);
assert!(hard);
// Every step's middle lies on one line, a quarter of a pixel's rise per pixel.
let steps: Vec<Point> = pts.iter().copied().filter(|p| p.y.fract() == 0.5 && p.x > 0.0 && p.x < w as f64).collect();
@@ -157,28 +267,66 @@ mod tests {
let (w, h) = (6, 4);
// The left half is inside; its right edge really lies 0.3 px further right.
let mask: Vec<bool> = (0..w * h).map(|i| i % w < 3).collect();
let shift = |c: Crack| if c.at(0).is_some_and(|i| i % w == 2) && c.at(1).is_some_and(|i| i % w == 3) { 0.3 } else { 0.0 };
// (0.1 px in the lower rows: a shift that is the same all along makes a hard edge.)
let shift = |c: Crack| match (c.at(0), c.at(1)) {
(Some(a), Some(b)) if a % w == 2 && b % w == 3 => {
if a / w < 2 {
0.3
} else {
0.1
}
}
_ => 0.0,
};
let l = loop_of(&mask, w, h);
let (pts, hard) = outline(&l, w, h, &shift);
assert!(!hard);
let (pts, _) = whole(&l, w, h, &shift);
// Each crack comes with the column of pixels across it.
outline(&l, w, h, &|c| {
let (a, b) = (c.at(0).unwrap(), c.at(1).unwrap());
assert_eq!((c.at(-1), c.at(2)), (Some(a - 1), Some(b + 1)));
assert_eq!((c.at(-3), c.at(4)), (None, None));
0.0
});
let right: Vec<&Point> = pts.iter().filter(|p| p.x > 2.5).collect();
// The four cracks' middles and the two corners, all at x = 3.3.
assert_eq!(right.len(), 6);
assert!(right.iter().all(|p| (p.x - 3.3).abs() < 1e-12), "{right:?}");
outline(
&l,
w,
h,
&|c| {
let (a, b) = (c.at(0).unwrap(), c.at(1).unwrap());
assert_eq!((c.at(-1), c.at(2)), (Some(a - 1), Some(b + 1)));
assert_eq!((c.at(-3), c.at(4)), (None, None));
(0.0, 0)
},
&grid,
);
// The four cracks' middles, at x = 3.3 (rounded to 1/1024); the edge ends on the image's
// border, at junctions on the pixel grid.
let right: Vec<&Point> = pts.iter().filter(|p| p.x > 3.05).collect();
assert_eq!(right.len(), 4);
assert!(right.iter().all(|p| (p.x - if p.y < 2.0 { 3.3 } else { 3.1 }).abs() < 1e-3), "{right:?}");
assert!(pts.contains(&Point::new(3.0, 0.0)) && pts.contains(&Point::new(3.0, 4.0)));
}
#[test]
fn a_shift_that_is_not_a_number_moves_nothing() {
let mask = [true, true, false, false, true, true, false, false];
let (pts, _) = outline(&loop_of(&mask, 4, 2), 4, 2, &|_| f64::NAN);
let (pts, _) = whole(&loop_of(&mask, 4, 2), 4, 2, &|_| f64::NAN);
assert_eq!(pts.len(), 4);
assert!(pts.iter().all(|p| p.x.is_finite() && p.y.is_finite()));
}
#[test]
fn two_regions_get_the_same_points_for_their_shared_edge() {
// Left and right halves meet along a staircase; each sees the other's shifts negated.
let (w, h) = (12, 10);
let left: Vec<bool> = (0..w * h).map(|i| (i % w) as f64 + 0.5 < 4.0 + (i / w) as f64 * 0.4).collect();
let right: Vec<bool> = left.iter().map(|b| !b).collect();
let wave = |c: Crack| 0.4 * ((c.at(0).unwrap() + c.at(1).unwrap()) as f64).sin();
let a = outline(&loop_of(&left, w, h), w, h, &|c| (if left[c.at(0).unwrap()] { wave(c) } else { -wave(c) }, 1), &grid);
let b = outline(&loop_of(&right, w, h), w, h, &|c| (if left[c.at(0).unwrap()] { wave(c) } else { -wave(c) }, 2), &grid);
// The piece that is not on the image's border, from either side.
let inner = |pieces: &[Piece]| {
pieces.iter().find(|p| p.pts.iter().any(|q| q.x > 0.0 && q.x < w as f64 && q.y > 0.0 && q.y < h as f64)).unwrap().clone()
};
let (mut ours, theirs) = (inner(&a), inner(&b));
ours.pts.reverse();
assert_eq!(ours, theirs);
assert!(ours.pts.len() > 12);
// Each side of the image is a piece of its own: its corners are exact.
assert!(a.iter().chain(&b).all(|p| p.pts.first().is_some_and(|q| q.x.fract() == 0.0 && q.y.fract() == 0.0)));
}
}
+93
View File
@@ -944,3 +944,96 @@ fn the_bands_of_a_gradient_stay_apart() {
});
assert!(quantize(&noisy, &sixteen_colors()).palette.len() >= 12);
}
#[test]
fn a_noisy_gradient_keeps_its_tones_without_specks() {
// Tones 0–255 across with noise larger than High Fidelity Photo's 64 steps are apart.
let img = Raster::from_fn(256, 96, |x, y| {
let c = |k: u32| (f64::from(x) + 5.0 * jitter(x, y, k)).round().clamp(0.0, 255.0) as u8;
[c(0), c(1), c(2), 255]
});
let params = preset("High Fidelity Photo").unwrap();
let res = trace(&img, &params);
// Smoothed first, the noise mixes fewer neighbouring tones into one (`quantize` alone works
// on the picture as it is), and leaves no specks.
let unsmoothed = quantize(&img, &params).palette.len();
assert!(res.palette.len() > unsmoothed && res.palette.len() >= 24, "{} colours, {unsmoothed} unsmoothed", res.palette.len());
assert!(res.paths.len() <= 2 * res.palette.len(), "{} paths of {} colours", res.paths.len(), res.palette.len());
}
#[test]
fn stacked_layers_go_by_lightness_and_leave_ignored_white_alone() {
// Stripes: black, white, mid gray, light gray (the widest).
let img = Raster::from_fn(100, 20, |x, _| {
let v = match x {
0..20 => 0,
20..40 => 255,
40..60 => 120,
_ => 200,
};
[v, v, v, 255]
});
let params = TraceParams { mode: Mode::Grayscale, colors: 4, noise: 0, method: Method::Overlapping, ..TraceParams::default() };
let tones = |res: &TraceResult| res.paths.iter().map(|p| p.color[0]).collect::<Vec<u8>>();
// The largest colour is light, so the stack starts at the light end.
// (Each layer reaches under those above it: under the black stripe too, a part of its own.)
assert_eq!(tones(&trace(&img, &params)), [255, 200, 200, 120, 120, 0]);
// Without white, no layer reaches under where it was.
let res = trace(&img, &TraceParams { ignore_white: true, ..params });
assert_eq!(tones(&res), [200, 200, 120, 120, 0]);
for p in &res.paths {
let b = p.path.bounds().unwrap();
assert!(b.x1 <= 20.5 || b.x0 >= 39.5, "a {} layer covers the white stripe: {b:?}", p.color[0]);
}
}
/// The cubic pieces of a path: (from, handle, handle, to).
fn pieces_of(p: &vectorcraft_geom::PathData) -> Vec<[Point; 4]> {
p.subpaths
.iter()
.flat_map(|sp| {
(0..sp.segment_count()).map(move |i| {
let c = sp.segment(i);
[c.p0, c.p1, c.p2, c.p3]
})
})
.collect()
}
#[test]
fn abutting_regions_share_one_curve_along_their_edge() {
// A disc of two halves on a field: three colours, two junctions where all three meet.
let color = |x: f64, y: f64| {
if Point::new(x, y).distance(Point::new(50.3, 49.6)) > 35.2 {
[255.0, 255.0, 255.0]
} else if x < 50.3 + 0.2 * (y - 50.0) {
[200.0, 40.0, 50.0]
} else {
[30.0, 90.0, 200.0]
}
};
let img = Raster::from_fn(100, 100, |x, y| {
let mut sum = [0.0f64; 3];
for i in 0..16 {
let c = color(f64::from(x) + (f64::from(i % 4) + 0.5) / 4.0, f64::from(y) + (f64::from(i / 4) + 0.5) / 4.0);
for k in 0..3 {
sum[k] += c[k] / 16.0;
}
}
[sum[0].round() as u8, sum[1].round() as u8, sum[2].round() as u8, 255]
});
let res = trace(&img, &TraceParams { mode: Mode::Color, colors: 3, ..TraceParams::default() });
assert_eq!(res.paths.len(), 3);
let all: Vec<Vec<[Point; 4]>> = res.paths.iter().map(|p| pieces_of(&p.path)).collect();
// Every curve that is not on the image's border is another path's curve too, run the other way.
let inner = |c: &[Point; 4]| c.iter().all(|p| p.x > 0.5 && p.x < 99.5 && p.y > 0.5 && p.y < 99.5);
let mut shared = 0;
for (i, path) in all.iter().enumerate() {
for c in path.iter().filter(|c| inner(c)) {
let back = [c[3], c[2], c[1], c[0]];
assert!(all.iter().enumerate().any(|(j, other)| j != i && other.contains(&back)), "path {i} has an edge of its own: {c:?}");
shared += 1;
}
}
assert!(shared >= 12, "{shared} shared curves");
}
+1 -1
View File
@@ -739,7 +739,7 @@ mod tests {
let fr = crate::i18n::Lang::from_code("fr").unwrap();
let shown = crate::i18n::message(fr, "2 font file(s) are now in /Fonts; 1 couldn't be added: a.otf: larger than 256 MB");
assert!(shown.contains("se trouvent maintenant dans /Fonts") && shown.contains("a.otf") && shown.contains("plus de 256 Mo"), "{shown}");
for code in ["de", "es", "fr", "hu", "it", "ru"] {
for code in ["de", "es", "fr", "hu", "it", "pl", "ru"] {
let lang = crate::i18n::Lang::from_code(code).unwrap();
for s in [
"every search thread stopped on an internal error (please report this bug)",
+1 -1
View File
@@ -239,7 +239,7 @@ fn quality_row(ui: &mut egui::Ui, d: &mut Dialog, label: &dyn Fn(&mut egui::Ui,
label(ui, tl!("Quality:"));
let mut q = (d.f64("quality", 90.0) / 10.0).round().clamp(0.0, 10.0) as u8;
ui.horizontal(|ui| {
if ui.add(egui::Slider::new(&mut q, 0..=10)).changed() {
if widgets::slider(ui, egui::Slider::new(&mut q, 0..=10)).changed() {
d.fields.insert("quality".into(), json!(u32::from(q) * 10));
}
label(ui, QUALITY_BANDS[q as usize]);
+4 -1
View File
@@ -155,6 +155,9 @@ fn solid_controls(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, id: &
} else {
heading(ui, tl!("Object"));
number(ui, d, "depth", tl!("Depth"), (0.0, 2000.0), "", 1, Some(unit));
number(ui, d, "twist", tl!("Twist"), (0.0, 360.0), "°", 1, None);
number(ui, d, "taper", tl!("Taper"), (1.0, 100.0), "%", 1, None);
choice(ui, d, "cap", c3("Cap"), &[(json!(true), c3("Solid")), (json!(false), c3("Hollow"))]);
number(ui, d, "volume", tl!("Volume"), (0.0, 100.0), "%", 1, None);
toggle(ui, d, "bothSides", tl!("Both sides"), false);
}
@@ -167,7 +170,7 @@ fn solid_controls(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, id: &
fn extrude_controls(ui: &mut egui::Ui, d: &mut Dialog, unit: Unit) {
heading(ui, tl!("Object"));
number(ui, d, "depth", tl!("Depth"), (0.0, 2000.0), "", 1, Some(unit));
number(ui, d, "twist", tl!("Twist"), (-360.0, 360.0), "°", 1, None);
number(ui, d, "twist", tl!("Twist"), (0.0, 360.0), "°", 1, None);
number(ui, d, "taper", tl!("Taper"), (1.0, 100.0), "%", 1, None);
choice(ui, d, "cap", c3("Cap"), &[(json!(true), c3("Solid")), (json!(false), c3("Hollow"))]);
ui.add_space(10.0);
+1 -1
View File
@@ -632,7 +632,7 @@ fn slider_row(ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str, suffix:
widgets::label_row(ui, label, LABEL_W, |ui| {
let mut v = d.f64(key, 0.0).round().clamp(0.0, 100.0) as u8;
ui.spacing_mut().slider_width = FIELD_W - 60.0;
if ui.add(egui::Slider::new(&mut v, 0..=100).suffix(suffix)).changed() {
if widgets::slider(ui, egui::Slider::new(&mut v, 0..=100).suffix(suffix)).changed() {
d.fields.insert(key.into(), json!(v));
}
});
+1 -1
View File
@@ -213,7 +213,7 @@ fn the_other_3d_effects_show_their_options_and_position_presets() {
let square = "M100 100 L200 100 L200 200 L100 200 Z";
for (effect, own) in [
(EXTRUDE, &["Depth", "Twist", "Taper", "Cap", "Bevel", "Bevel Shape", "Space", "Bevel Inside", "Bevel both sides"][..]),
(INFLATE, &["Depth", "Volume", "Both sides"][..]),
(INFLATE, &["Depth", "Twist", "Taper", "Cap", "Volume", "Both sides"][..]),
(ROTATE, &[][..]),
] {
let mut h = Harness::with(square, effect, vec2(1400.0, 1000.0));
+2
View File
@@ -4683,3 +4683,5 @@ mark-style Japanese Japonské
@msg unknown parameter `{key}`; did you mean `{near}`? neznámý parametr `{key}`; mysleli jste `{near}`?
@msg unknown parameter `{key}`; the command takes no parameters neznámý parametr `{key}`; příkaz nemá žádné parametry
@msg unknown parameter `{key}`; the command takes: {keys} neznámý parametr `{key}`; příkaz přijímá: {keys}
Load EPS into Clipboard Načíst EPS do schránky
@msg an image of {w} × {h} pixels is too large to draw obraz o velikosti {w} × {h} obrazových bodů je příliš velký na vykreslení
Can't render this file because it contains an unexpected character in line 2 and column 73.
+2
View File
@@ -4206,3 +4206,5 @@ theme Appearance Erscheinungsbild
@msg unknown parameter `{key}`; did you mean `{near}`? unbekannter Parameter `{key}`; meinten Sie `{near}`?
@msg unknown parameter `{key}`; the command takes no parameters unbekannter Parameter `{key}`; der Befehl hat keine Parameter
@msg unknown parameter `{key}`; the command takes: {keys} unbekannter Parameter `{key}`; der Befehl akzeptiert: {keys}
Load EPS into Clipboard EPS in die Zwischenablage laden
@msg an image of {w} × {h} pixels is too large to draw ein Bild mit {w} × {h} Pixeln ist zu groß, um gezeichnet zu werden
Can't render this file because it contains an unexpected character in line 2 and column 73.
+2
View File
@@ -4623,3 +4623,5 @@ mark-style Japanese Japonesas
@msg unknown parameter `{key}`; did you mean `{near}`? parámetro desconocido `{key}`; ¿quiso decir `{near}`?
@msg unknown parameter `{key}`; the command takes no parameters parámetro desconocido `{key}`; el comando no tiene parámetros
@msg unknown parameter `{key}`; the command takes: {keys} parámetro desconocido `{key}`; el comando acepta: {keys}
Load EPS into Clipboard Cargar EPS en el portapapeles
@msg an image of {w} × {h} pixels is too large to draw una imagen de {w} × {h} píxeles es demasiado grande para dibujarse
Can't render this file because it contains an unexpected character in line 2 and column 73.
File diff suppressed because it is too large. Load diff
+2
View File
@@ -4649,3 +4649,5 @@ theme Appearance Kinézet
@msg unknown parameter `{key}`; did you mean `{near}`? ismeretlen paraméter: `{key}`; erre gondolt: `{near}`?
@msg unknown parameter `{key}`; the command takes no parameters ismeretlen paraméter: `{key}`; a parancsnak nincs paramétere
@msg unknown parameter `{key}`; the command takes: {keys} ismeretlen paraméter: `{key}`; a parancs ezeket fogadja el: {keys}
Load EPS into Clipboard EPS betöltése a vágólapra
@msg an image of {w} × {h} pixels is too large to draw egy {w} × {h} pixeles kép túl nagy a kirajzoláshoz
Can't render this file because it contains an unexpected character in line 2 and column 73.
+2
View File
@@ -4251,3 +4251,5 @@ lighting Light Luce
@msg unknown parameter `{key}`; did you mean `{near}`? parametro sconosciuto `{key}`; forse intendevate `{near}`?
@msg unknown parameter `{key}`; the command takes no parameters parametro sconosciuto `{key}`; il comando non ha parametri
@msg unknown parameter `{key}`; the command takes: {keys} parametro sconosciuto `{key}`; il comando accetta: {keys}
Load EPS into Clipboard Carica EPS negli appunti
@msg an image of {w} × {h} pixels is too large to draw un'immagine di {w} × {h} pixel è troppo grande per essere disegnata
Can't render this file because it contains an unexpected character in line 2 and column 73.
+2
View File
@@ -4245,3 +4245,5 @@ lighting Light ライト
@msg unknown parameter `{key}`; did you mean `{near}`? `{key}` は不明なパラメーターです。`{near}` のことですか?
@msg unknown parameter `{key}`; the command takes no parameters `{key}` は不明なパラメーターです。このコマンドにパラメーターはありません
@msg unknown parameter `{key}`; the command takes: {keys} `{key}` は不明なパラメーターです。このコマンドで使えるパラメーター: {keys}
Load EPS into Clipboard EPS をクリップボードに読み込む
@msg an image of {w} × {h} pixels is too large to draw {w} × {h} ピクセルの画像は大きすぎて描画できません
Can't render this file because it contains an unexpected character in line 2 and column 73.
+2
View File
@@ -4215,3 +4215,5 @@ lighting Light 광원
@msg unknown parameter `{key}`; did you mean `{near}`? 알 수 없는 매개변수 `{key}`: `{near}`을(를) 의미하셨습니까?
@msg unknown parameter `{key}`; the command takes no parameters 알 수 없는 매개변수 `{key}`: 이 명령에는 매개변수가 없습니다
@msg unknown parameter `{key}`; the command takes: {keys} 알 수 없는 매개변수 `{key}`: 이 명령이 받는 매개변수: {keys}
Load EPS into Clipboard EPS를 클립보드로 불러오기
@msg an image of {w} × {h} pixels is too large to draw {w} × {h}픽셀 이미지는 너무 커서 그릴 수 없습니다
Can't render this file because it contains an unexpected character in line 2 and column 73.
+22 -1
View File
@@ -81,8 +81,20 @@ fn plural_east_slavic(n: u64) -> usize {
}
}
/// Polish: only 1 is `one`; 2–4 (but not 12–14) `few`; everything else (0, 5–21, 25…) `many`
/// (unlike Russian and Ukrainian, 21, 31 … take `many`: "21 warstw").
fn plural_polish(n: u64) -> usize {
if n == 1 {
return 0;
}
match (n % 10, n % 100) {
(2..=4, r) if !(12..=14).contains(&r) => 1,
_ => 2,
}
}
/// The registry. English first: it is the fallback and the source language.
pub static LANGUAGES: [LangInfo; 14] = [
pub static LANGUAGES: [LangInfo; 16] = [
LangInfo { code: "en", name: "English", source: "", plural: plural_one_other, complete_menus: false, catalog: OnceLock::new() },
// Japanese: the whole interface (every menu string and `tl!` literal) and the status and error
// messages, keeping the product, workspace and perspective preset names in English (`MENU_KEEP_AS_IS`).
@@ -91,6 +103,11 @@ pub static LANGUAGES: [LangInfo; 14] = [
// English as Japanese; a count takes no plural, so plurals have one form. Hangul is drawn with an
// installed system font (craft-fonts has no Korean UI face yet); every `ko-*` locale resolves here.
LangInfo { code: "ko", name: "한국어", source: include_str!("ko.tsv"), plural: plural_none, complete_menus: true, catalog: OnceLock::new() },
// Vietnamese: complete menus and messages, with one plural form.
// Every `vi-*` locale resolves here.
LangInfo {
code: "vi", name: "Tiếng Việt", source: include_str!("vi.tsv"), plural: plural_none, complete_menus: true, catalog: OnceLock::new()
},
// Czech: the whole interface (every menu string and `tl!` literal) and the status and error
// messages, with one/few/other plurals, keeping the same names in English as Spanish.
LangInfo { code: "cs", name: "Čeština", source: include_str!("cs.tsv"), plural: plural_czech, complete_menus: true, catalog: OnceLock::new() },
@@ -151,6 +168,10 @@ pub static LANGUAGES: [LangInfo; 14] = [
// English as Spanish; a count takes the singular ("3 réteg"), so plurals have one form. Every
// `hu-*` locale (including `hu-HU`) resolves here.
LangInfo { code: "hu", name: "Magyar", source: include_str!("hu.tsv"), plural: plural_none, complete_menus: true, catalog: OnceLock::new() },
// Polish: the whole interface and the status and error messages, with one/few/many plurals,
// keeping the same names in English as Spanish; every `pl-*` locale (including `pl-PL`)
// resolves here.
LangInfo { code: "pl", name: "Polski", source: include_str!("pl.tsv"), plural: plural_polish, complete_menus: true, catalog: OnceLock::new() },
// Brazilian Portuguese: every menu label (`menu_catalogs_translate_every_menu_label`), every
// `tl!` literal and the plural messages; left English on purpose are the `MENU_KEEP_AS_IS`
// strings (product name, language names, workspace names, perspective grid presets).
File diff suppressed because it is too large. Load diff
+1
View File
@@ -3692,3 +3692,4 @@ axis Both Ambos
@msg unknown parameter `{key}`; did you mean `{near}`? parâmetro desconhecido `{key}`; você quis dizer `{near}`?
@msg unknown parameter `{key}`; the command takes no parameters parâmetro desconhecido `{key}`; o comando não tem parâmetros
@msg unknown parameter `{key}`; the command takes: {keys} parâmetro desconhecido `{key}`; o comando aceita: {keys}
Load EPS into Clipboard Carregar EPS na Área de Transferência
Can't render this file because it contains an unexpected character in line 6 and column 47.
+2
View File
@@ -4247,3 +4247,5 @@ lighting Light Свет
@msg unknown parameter `{key}`; did you mean `{near}`? неизвестный параметр `{key}`; возможно, имелся в виду `{near}`?
@msg unknown parameter `{key}`; the command takes no parameters неизвестный параметр `{key}`; у команды нет параметров
@msg unknown parameter `{key}`; the command takes: {keys} неизвестный параметр `{key}`; команда принимает: {keys}
Load EPS into Clipboard Загрузить EPS в буфер обмена
@msg an image of {w} × {h} pixels is too large to draw изображение размером {w} × {h} пикселей слишком велико для отрисовки
Can't render this file because it contains an unexpected character in line 2 and column 73.
+117 -4
View File
@@ -32,6 +32,9 @@ fn tags_map_to_languages() {
for tag in ["ko", "ko-KR", "ko_KR.UTF-8", "KO-kr"] {
assert_eq!(lang_from_tag(tag), Some(ko()), "{tag}");
}
for tag in ["vi", "vi-VN", "vi_VN.UTF-8", "VI-vn"] {
assert_eq!(lang_from_tag(tag), Some(vi()), "{tag}");
}
// Traditional Chinese: by region, by script, and with a region after the script.
assert_eq!(lang_from_tag("zh_TW.UTF-8"), Some(ZH()));
assert_eq!(lang_from_tag("zh-TW"), Some(ZH()));
@@ -449,7 +452,7 @@ fn cs() -> Lang {
}
/// Languages whose catalogs leave [`MENU_KEEP_AS_IS`] in English.
const KEEPS_MENU_NAMES: [&str; 11] = ["cs", "de", "es", "fr", "hu", "it", "ja", "ko", "pt-br", "ru", "uk"];
const KEEPS_MENU_NAMES: [&str; 13] = ["cs", "de", "es", "fr", "hu", "it", "ja", "ko", "pl", "pt-br", "ru", "uk", "vi"];
/// Menu labels the menu-complete catalogs (Czech, German, Spanish, Italian, Japanese, Brazilian Portuguese) show as they are: the product name, a format name, the built-in workspace
/// names and the perspective grid presets (names, shown untranslated wherever else they appear).
@@ -662,6 +665,63 @@ fn korean_reads_as_korean() {
assert_eq!(message(ko(), nested), "명령 `object.group`은(는) 지금 사용할 수 없습니다: 선택된 항목이 없습니다");
}
fn vi() -> Lang {
Lang::from_code("vi").expect("vi registered")
}
/// Vietnamese has one plural form and covers the complete interface and messages.
#[test]
fn vietnamese_reads_as_vietnamese() {
assert_eq!(vi().name(), "Tiếng Việt");
assert!(vi().complete_menus());
assert_eq!(Lang::from_pref("vi"), vi());
assert_eq!(Lang::from_pref("VI"), vi());
for (en, want) in [
("Artboard Tool", "Công cụ Bảng vẽ"),
("Swatches", "Mẫu màu"),
("Stroke", "Nét"),
("Fill", "Tô"),
("Direct Selection Tool", "Công cụ Chọn trực tiếp"),
("Save As…", "Lưu thành…"),
("Undo", "Hoàn tác"),
("Close", "Đóng"),
] {
assert_eq!(tr(vi(), en), want);
}
for n in [0, 1, 3, 21] {
assert_eq!(trn(vi(), n, "{n} Layer", "{n} Layers"), format!("{n} lớp"));
}
let nested = "command `object.group` is not available right now: nothing selected";
assert_eq!(message(vi(), nested), "lệnh `object.group` hiện không khả dụng: chưa chọn gì");
}
/// Ambiguous English terms keep their intended Vietnamese meaning across UI contexts.
#[test]
fn vietnamese_domain_terms_are_consistent() {
for (en, want) in [
("All Scripts", "Tất cả hệ chữ"),
("Pointillize", "Hiệu ứng chấm"),
("Object Highlighting", "Đánh dấu đối tượng"),
("Color Theme", "Bộ màu"),
("Color Themes", "Bộ màu"),
("Asset Export", "Xuất asset"),
("Envelope Distort", "Biến dạng Envelope"),
("Move Spine Point", "Di chuyển điểm trục"),
("Dashed Line", "Đường nét đứt"),
("Eyedropper Tool", "Công cụ Ống hút màu"),
("Character Alignment", "Căn chỉnh ký tự"),
] {
assert_eq!(tr(vi(), en), want, "{en}");
}
assert_eq!(tr(vi(), "Appearance"), "Diện mạo");
assert_eq!(tr_ctx(vi(), "theme", "Appearance"), "Giao diện");
assert_eq!(message(vi(), "no saved themes"), "chưa có bộ màu nào được lưu");
assert_eq!(message(vi(), r#"choice must be "merge" or "add", not `foo`"#), r#"lựa chọn phải là "merge" hoặc "add", không phải `foo`"#);
assert_eq!(message(vi(), "select a blend"), "hãy chọn một đối tượng hòa trộn");
assert_eq!(message(vi(), "select a repeat"), "hãy chọn một đối tượng lặp");
assert_eq!(message(vi(), "Replace Spine: select a blend and a path"), "Thay thế trục: chọn một đối tượng hòa trộn và một đường dẫn");
}
fn uk() -> Lang {
Lang::from_code("uk").expect("uk registered")
}
@@ -921,7 +981,7 @@ fn russian_plurals_have_three_forms() {
assert_eq!(forms, [2, 0, 1, 1, 2, 2, 0, 1, 2, 2, 0]);
}
/// Czech, German, Spanish, French, Italian and Hungarian letters (and the punctuation their text uses) come from each family's own first font, not
/// Czech, German, Spanish, French, Italian, Hungarian and Polish letters (and the punctuation their text uses) come from each family's own first font, not
/// from a fallback further down the stack. (`has_glyph` can't tell: it counts characters of the
/// face that draws missing glyphs, the first one, as missing.)
#[test]
@@ -936,7 +996,7 @@ fn latin_script_glyphs_are_available_without_system_fonts() {
let first = first.unwrap();
let mut font = fonts.fonts.font(&family);
let chars = font.characters();
for ch in "áčďéěíňóřšťúůýžÁČĎÉĚÍŇÓŘŠŤÚŮÝŽ„“‚‘…–ñÑüÜ¿¡”àèìòùÀÈÌÒÙ«»’âêîôûçëïÿœæÂÊÎÔÛÇËÏŒÆäöÄÖßőűŐŰ\u{a0}".chars()
for ch in "áčďéěíňóřšťúůýžÁČĎÉĚÍŇÓŘŠŤÚŮÝŽ„“‚‘…–ñÑüÜ¿¡”àèìòùÀÈÌÒÙ«»’âêîôûçëïÿœæÂÊÎÔÛÇËÏŒÆäöÄÖßőűŐŰąćęłńśźżĄĆĘŁŃŚŹŻ\u{a0}".chars()
{
assert!(chars.get(&ch).is_some_and(|fonts| fonts.contains(&first)), "{first} ({family:?}) has no {ch}");
}
@@ -1103,7 +1163,7 @@ fn select_key_param_error_is_translated() {
}
/// Languages whose catalogs cover every status and error message.
const COMPLETE_MESSAGES: &[&str] = &["cs", "de", "es", "fr", "hu", "it", "ja", "ko", "ru", "uk"];
const COMPLETE_MESSAGES: &[&str] = &["cs", "de", "es", "fr", "hu", "it", "ja", "ko", "pl", "ru", "uk", "vi"];
/// Crates whose error and status messages reach the status bar.
const MESSAGE_CRATES: &[&str] = &["ui-egui", "engine", "doc", "format", "svg", "pdf", "eps", "text", "plugins", "metafile", "cad", "trace"];
@@ -1235,3 +1295,56 @@ fn czech_render_site_follow_up() {
assert_eq!(trn(cs(), n, "{n} PR", "{n} PRs"), format!("{n} PR"));
}
}
fn pl() -> Lang {
Lang::from_code("pl").expect("pl registered")
}
#[test]
fn polish_plurals_have_three_forms() {
let forms: Vec<usize> = [0, 1, 2, 4, 5, 11, 12, 14, 21, 22, 25, 101, 112, 122].into_iter().map(plural_polish).collect();
assert_eq!(forms, [2, 0, 1, 1, 2, 2, 2, 2, 2, 1, 2, 2, 2, 1]);
// Every Polish plural row has the three forms, and each count picks its own.
let (entries, _) = parse_entries(pl().0.source);
let mut count = 0;
for (ctx, src, tr) in &entries {
if ctx != "@plural" {
continue;
}
count += 1;
let forms: Vec<&str> = tr.split('|').collect();
assert_eq!(forms.len(), 3, "{src}");
let (one, other) = src.split_once('|').unwrap();
for (n, form) in [(1, 0), (3, 1), (5, 2), (21, 2), (22, 1)] {
assert_eq!(trn(pl(), n, one, other), forms[form].replace("{n}", &n.to_string()), "{src}: {n}");
}
}
assert!(count >= 13, "Polish plural rows missing");
}
/// Polish uses its vector-illustration vocabulary (obszar kompozycji, ścieżka, obrys…), resolves
/// every `pl-*` locale, counts with one/few/many and translates the reason inside a message too.
#[test]
fn polish_reads_as_polish() {
for tag in ["pl", "pl-PL", "pl_PL.UTF-8", "PL-pl"] {
assert_eq!(lang_from_tag(tag), Some(pl()), "{tag}");
}
for (en, want) in [
("File", "Plik"),
("Artboard Tool", "Narzędzie Obszar kompozycji"),
("Swatches", "Próbki"),
("Pathfinder", "Odnajdywanie ścieżek"),
("Stroke", "Obrys"),
("Fill", "Wypełnienie"),
("Workspace", "Obszar roboczy"),
] {
assert_eq!(tr(pl(), en), want);
}
for (n, word) in [(1, "warstwa"), (3, "warstwy"), (5, "warstw"), (22, "warstwy"), (21, "warstw")] {
assert_eq!(trn(pl(), n, "{n} Layer", "{n} Layers"), format!("{n} {word}"));
}
assert_eq!(tr_ctx(pl(), "axis", "Both"), "Obie");
assert_eq!(tr_id(pl(), "pathfinder.add", "Add"), "Połącz");
let nested = "command `object.group` is not available right now: nothing selected";
assert_eq!(message(pl(), nested), "polecenie `object.group` jest teraz niedostępne: nic nie zaznaczono");
}
+2
View File
@@ -4231,3 +4231,5 @@ lighting Light Світло
@msg unknown parameter `{key}`; did you mean `{near}`? невідомий параметр `{key}`; можливо, ви мали на увазі `{near}`?
@msg unknown parameter `{key}`; the command takes no parameters невідомий параметр `{key}`; команда не має параметрів
@msg unknown parameter `{key}`; the command takes: {keys} невідомий параметр `{key}`; команда приймає: {keys}
Load EPS into Clipboard Завантажити EPS у буфер обміну
@msg an image of {w} × {h} pixels is too large to draw зображення розміром {w} × {h} пікселів завелике для відображення
Can't render this file because it contains an unexpected character in line 659 and column 40.
File diff suppressed because it is too large. Load diff
+2
View File
@@ -3842,3 +3842,5 @@ lighting Light 光源
@msg unknown parameter `{key}`; did you mean `{near}`? 未知参数 `{key}`;您是否想输入 `{near}`?
@msg unknown parameter `{key}`; the command takes no parameters 未知参数 `{key}`;该命令没有参数
@msg unknown parameter `{key}`; the command takes: {keys} 未知参数 `{key}`;该命令接受:{keys}
Load EPS into Clipboard 将 EPS 载入剪贴板
@msg an image of {w} × {h} pixels is too large to draw {w} × {h} 像素的图像过大,无法绘制
Can't render this file because it contains an unexpected character in line 2 and column 73.
+2
View File
@@ -3623,3 +3623,5 @@ lighting Light 光源
@msg unknown parameter `{key}`; did you mean `{near}`? 未知的參數 `{key}`;您是指 `{near}` 嗎?
@msg unknown parameter `{key}`; the command takes no parameters 未知的參數 `{key}`;此指令沒有參數
@msg unknown parameter `{key}`; the command takes: {keys} 未知的參數 `{key}`;此指令接受:{keys}
Load EPS into Clipboard 將 EPS 載入剪貼簿
@msg an image of {w} × {h} pixels is too large to draw {w} × {h} 像素的影像過大,無法繪製
Can't render this file because it contains an unexpected character in line 6 and column 47.
+9 -3
View File
@@ -560,7 +560,9 @@ pub fn run(app: &mut VectorcraftApp, ctx: &egui::Context) {
/// Bring the native menu up to date when anything it shows may have changed: a command ran, the
/// document, its history or selection changed, the user clicked or pressed a key. Reading the rows
/// asks every command whether it is enabled, so frames that only animate or scroll skip it.
/// asks every command whether it is enabled, so frames that only animate or scroll skip it, and so
/// do the previews of an open interaction (the steps of a move, scale or shape drag, a dialog's
/// preview), whose new revisions [`state_hash`] leaves out.
pub fn sync(app: &mut VectorcraftApp, ctx: &egui::Context) {
let Some(menu) = app.services.native_menu.as_ref() else { return };
let input = ctx
@@ -585,7 +587,10 @@ pub fn sync(app: &mut VectorcraftApp, ctx: &egui::Context) {
/// What the menus' rows depend on, cheaply (no allocation): commands run, the active document,
/// its revision (edits, selection and view changes), history and clipboard, the language,
/// shortcuts, plug-ins and an open file dialog. `input` forces a change on frames with a click or
/// a key press, which covers what the hash doesn't list (panels shown, a tool picked).
/// a key press, which covers what the hash doesn't list (panels shown, a tool picked). While an
/// interaction is open (for example a move, scale or shape drag, a dialog's or the font menu's
/// preview, or a typing session), the revision, which each of its previews changes, is left out:
/// the hash changes as the interaction begins and as it ends.
fn state_hash(app: &VectorcraftApp, input: Option<u64>) -> u64 {
let mut h = DefaultHasher::new();
input.hash(&mut h);
@@ -593,7 +598,8 @@ fn state_hash(app: &VectorcraftApp, input: Option<u64>) -> u64 {
let s = &app.session;
(s.journal.len(), s.active_index(), s.clipboard.is_empty(), s.tool_composing()).hash(&mut h);
if let Some(d) = s.active() {
(d.uid, d.revision, d.history.undo.len(), d.history.redo.len(), d.transparency_grid, d.print_tiling).hash(&mut h);
let revision = d.interaction.is_none().then_some(d.revision);
(d.uid, revision, d.history.undo.len(), d.history.redo.len(), d.transparency_grid, d.print_tiling).hash(&mut h);
}
(app.system_paste, app.last_effect.is_some(), app.ui.recent_files.len(), app.ui.recent_files.first(), app.recent_fonts().len()).hash(&mut h);
app.file_dialog_open().hash(&mut h);
+6 -1
View File
@@ -219,11 +219,16 @@ fn badge(ui: &Ui, r: egui::Rect, status: &str) {
fn status_tip(r: &Value) -> String {
let path = r["found"].as_str().or(r["path"].as_str()).unwrap_or_default();
match r["status"].as_str().unwrap_or_default() {
let tip = match r["status"].as_str().unwrap_or_default() {
"missing" => crate::i18n::fmt(tl!("Missing: {path}"), &[("path", path)]),
"modified" => crate::i18n::fmt(tl!("Modified since it was read: {path}"), &[("path", path)]),
"embedded" => tl!("Embedded").into(),
_ => path.to_string(),
};
// An image too large to draw (`links.list`'s note).
match r["note"].as_str() {
Some(note) => format!("{tip}\n{}", crate::i18n::msg(note)),
None => tip,
}
}
+53 -3
View File
@@ -203,10 +203,14 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
}
}
let drag: Option<usize> = pstate(ui.ctx(), "tabs-drag");
// The stop within 5 px of `x`.
let hit_at = |x: f32| stops.iter().position(|s| (to_x(s.position) - x).abs() <= 5.0);
// egui reports the drag only once the pointer is a few pixels from the press, past the hit
// tolerance, so hit-test where the button went down (#1458).
if resp.drag_started()
&& let Some(pos) = resp.interact_pointer_pos()
&& let Some(pos) = ui.input(|i| i.pointer.press_origin()).or(resp.interact_pointer_pos())
{
let hit = stops.iter().position(|s| (to_x(s.position) - pos.x).abs() <= 5.0);
let hit = hit_at(pos.x);
set_pstate(ui.ctx(), "tabs-drag", hit);
if let Some(i) = hit {
set_pstate(ui.ctx(), "tabs-sel", i);
@@ -229,7 +233,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
} else if resp.clicked()
&& let Some(pos) = resp.interact_pointer_pos()
{
match stops.iter().position(|s| (to_x(s.position) - pos.x).abs() <= 5.0) {
match hit_at(pos.x) {
Some(i) => set_pstate(ui.ctx(), "tabs-sel", i),
None => {
let position = to_pt(pos.x);
@@ -359,6 +363,52 @@ mod tests {
}
}
/// #1458: a stop moves when the drag starts on it, even though egui only reports the drag once
/// the pointer is past its threshold (farther from the press than the 5 px hit tolerance).
#[test]
fn dragging_a_stop_moves_it() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({})).unwrap();
app.session.execute("text.create", &json!({"x": 10, "y": 20, "text": "a b", "area": {"width": 300, "height": 100}})).unwrap();
app.session.execute("text.tabs.set", &json!({"stops": [{"position": 50}]})).unwrap();
let ctx = egui::Context::default();
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(320.0, 400.0));
// One frame with `events` → where the ruler's inch labels (9 pt) are painted.
let frame = |app: &mut VectorcraftApp, events: Vec<egui::Event>| {
let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }, |ui| show(app, ui));
out.textures_delta.clear();
out.shapes
.iter()
.filter_map(|c| match &c.shape {
egui::Shape::Text(t) if t.galley.job.sections.first().is_some_and(|s| s.format.font_id.size == 9.0) => {
Some((t.galley.text().to_string(), t.pos))
}
_ => None,
})
.collect::<Vec<_>>()
};
let labels = frame(&mut app, vec![]);
let at = |label: &str| labels.iter().find(|(t, _)| t == label).unwrap_or_else(|| panic!("{label} in {labels:?}")).1;
// A label sits 2 px right of its tick: 0 and 1 inch give the ruler's scale.
let (zero, inch) = (at("0"), at("1"));
let to_x = |pt: f32| zero.x - 2.0 + pt * (inch.x - zero.x) / 72.0;
let y = zero.y + 15.0;
let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
// Press 3 px right of the stop, then drag right; egui starts the drag 6+ px from the press.
let press = egui::pos2(to_x(50.0) + 3.0, y);
frame(&mut app, vec![egui::Event::PointerMoved(press), button(press, true)]);
for dx in [9.0, 20.0, 40.0] {
frame(&mut app, vec![egui::Event::PointerMoved(press + vec2(dx, 0.0))]);
}
let end = press + vec2(40.0, 0.0);
frame(&mut app, vec![button(end, false)]);
frame(&mut app, vec![]);
let stops = current(&app).unwrap().1;
assert_eq!(stops.len(), 1);
let moved_to = to_x(stops[0].position as f32);
assert!((moved_to - end.x).abs() < 1.0, "stop at {moved_to}, released at {}", end.x);
}
/// Position Panel Above Text floats the panel over the text, its ruler's 0 on the frame's left
/// edge and a stop's mark over the column it sets, at any zoom (#729).
#[test]
+2 -2
View File
@@ -274,7 +274,7 @@ fn category_fields(ui: &mut egui::Ui, d: &mut Dialog, cat: &str) {
labeled(ui, sp.label, |ui| {
let mut x = v.as_f64().unwrap_or(min);
let new = if sp.key == "uiScaling" {
ui.add(egui::Slider::new(&mut x, min..=max).step_by(0.05).text(tl!("Smaller ↔ Larger"))).changed().then_some(x)
widgets::slider(ui, egui::Slider::new(&mut x, min..=max).step_by(0.05).text(tl!("Smaller ↔ Larger"))).changed().then_some(x)
} else {
widgets::range_field(ui, sp.key, x, min..=max, &format!(" {unit}"), 3, 110.0)
};
@@ -297,7 +297,7 @@ fn category_fields(ui: &mut egui::Ui, d: &mut Dialog, cat: &str) {
labeled(ui, sp.label, |ui| {
let mut x = v.as_i64().unwrap_or(min);
let new = if sp.key == "anchorSize" {
ui.add(egui::Slider::new(&mut x, min..=max).show_value(false).text(tl!("Size"))).changed().then_some(x)
widgets::slider(ui, egui::Slider::new(&mut x, min..=max).show_value(false).text(tl!("Size"))).changed().then_some(x)
} else {
widgets::range_field(ui, sp.key, x as f64, min as f64..=max as f64, "", 0, 110.0).map(|x| x as i64)
};
+3 -2
View File
@@ -1,6 +1,6 @@
//! The system clipboard's formats: Copy and Cut publish every flavour the engine makes
//! ([`Session::clipboard_flavours`](vectorcraft_engine::Session::clipboard_flavours): text, SVG,
//! PDF, PNG), and a Paste first turns what another app copied (SVG, PDF, an EMF, text, a bitmap,
//! PDF, PNG), and a Paste first turns what another app copied (SVG, PDF, EPS, an EMF, text, a bitmap,
//! or a copied file that is one of them) into the internal clipboard with the `clipboard.import*`
//! commands. The host installs the platform side as
//! [`Services::system_clipboard`](crate::Services::system_clipboard); without it (the web) Copy
@@ -8,7 +8,7 @@
//! reads from a paste itself ([`VectorcraftApp::paste_from_host`]).
use serde_json::{Value, json};
use vectorcraft_engine::cmd::clipboard::{BITMAP, EMF, Flavour, PASTE_ORDER, PDF, SVG, TEXT, looks_like_svg, names_a_picture};
use vectorcraft_engine::cmd::clipboard::{BITMAP, EMF, EPS, Flavour, PASTE_ORDER, PDF, SVG, TEXT, looks_like_svg, names_a_picture};
use crate::VectorcraftApp;
@@ -43,6 +43,7 @@ pub(crate) fn import_command(f: &Flavour, center: Option<[f64; 2]>) -> (&'static
}
SVG => ("clipboard.importSvg", json!({ "dataBase64": b64(), "center": center })),
PDF => ("clipboard.importPdf", json!({ "dataBase64": b64(), "center": center })),
EPS => ("clipboard.importEps", json!({ "dataBase64": b64(), "center": center })),
EMF => ("clipboard.importEmf", json!({ "dataBase64": b64(), "center": center })),
mime => ("clipboard.importImage", json!({ "dataBase64": b64(), "mime": mime, "center": center })),
}
+181
View File
@@ -334,6 +334,71 @@ impl Mac {
fn selected(&self) -> usize {
self.app.session.active().unwrap().selection.objects.len()
}
/// Where the document's point (`x`, `y`) is on the screen.
fn on_canvas(&self, x: f64, y: f64) -> Pos2 {
crate::canvas::Xf::new(self.app.canvas_rect.unwrap(), self.app.view().unwrap()).to_screen(vectorcraft_geom::Point::new(x, y))
}
/// Run `n` frames, each with the events that `step` returns (`step` may act on the app first),
/// and return the number of frames in which the app read the menus.
fn reads(&mut self, n: usize, mut step: impl FnMut(&mut Mac, usize) -> Vec<Event>) -> usize {
let synced = self.fake.synced();
for i in 0..n {
let events = step(self, i);
self.frame(events);
}
self.fake.synced() - synced
}
/// Press on the selected rectangle and move the pointer 8 points to the right: the Selection
/// tool's move begins. Returns where the press was.
fn start_move(&mut self) -> Pos2 {
let start = self.on_canvas(38.5, 40.0);
self.frame(vec![Event::PointerMoved(start), click(start, true)]);
self.frame(vec![Event::PointerMoved(start + vec2(8.0, 0.0))]);
assert!(self.app.session.in_interaction(), "the move began");
start
}
/// Open the Rotate dialog with Preview on: the rotation previews on the canvas.
fn rotate_preview(&mut self) {
menus::invoke(&mut self.app, "object.rotate", json!({}));
self.frame(vec![]);
self.app.ui.dialog.as_mut().unwrap().fields.insert("preview".into(), json!(true));
self.frame(vec![]);
assert!(self.app.session.in_interaction(), "the rotation previews");
}
/// Set `n` new angles in the open dialog through the control port, one a frame, and return the
/// number of frames in which the app read the menus.
fn angles(&mut self, n: usize) -> usize {
self.reads(n, |m, i| {
crate::tests_synthetic::control(&mut m.app, &m.ctx, "ui.dialog.set", json!({"field": "angle", "value": 10 * (i + 1)}));
vec![]
})
}
}
fn click(at: Pos2, pressed: bool) -> Event {
Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }
}
/// Run `drag` on a new app with the fake native menu, and run it again on another new app until
/// the shortcut and plug-in generations hold still through a run (at most 20 runs). Return that app
/// and what `drag` returned. The generations are process-wide and only grow. A test running
/// alongside can bump them, and the app then reads the menus again.
fn undisturbed<R>(drag: impl Fn(&mut Mac) -> R) -> (Mac, R) {
let generations = || (crate::shortcut_editor::GENERATION.load(std::sync::atomic::Ordering::Relaxed), crate::menus::plugin_revision());
for _ in 0..20 {
let mut m = Mac::new(true);
let before = generations();
let r = drag(&mut m);
if generations() == before {
return (m, r);
}
}
panic!("tests running alongside kept bumping the generations");
}
/// A key equivalent runs through the app's own key handling, once: ⌘A selects every object, ⌘Z
@@ -365,6 +430,122 @@ fn key_equivalents_run_through_the_normal_shortcut_path_once() {
assert_eq!(crate::control::inspect(&m.app, &m.ctx)["nativeMenuBar"], json!(true));
}
/// Each step of a drag previews the move as a new revision: the menus aren't read again for it
/// while the button is held, and are read when the button is released, with Undo naming the move.
#[test]
fn a_drag_reads_the_menus_when_it_is_released() {
let (mut m, (start, read)) = undisturbed(|m| {
let start = m.start_move();
(start, m.reads(6, |_, i| vec![Event::PointerMoved(start + vec2(8.0 * (i + 2) as f32, 0.0))]))
});
assert_eq!(read, 0, "the menus weren't read at any step of the drag");
let synced = m.fake.synced();
m.frame(vec![click(start + vec2(56.0, 0.0), false)]);
assert!(!m.app.session.in_interaction());
assert_eq!(m.fake.synced(), synced + 1, "the menus were read on the release");
assert_eq!(find(&m.fake.last(), "edit.undo").label, "Undo Move");
}
/// Escape ends a Rectangle tool drag while its button is still held: the menus are read then, with
/// the preview's rectangle gone (nothing selected, so Cut is off), and not at the steps before.
#[test]
fn escape_during_a_drag_reads_the_menus() {
let (mut m, read) = undisturbed(|m| {
m.app.run("select.none", json!({})).unwrap();
m.app.run("tool.select", json!({"tool": "rectangle"})).unwrap();
let start = m.on_canvas(200.0, 150.0);
m.frame(vec![Event::PointerMoved(start), click(start, true)]);
m.frame(vec![Event::PointerMoved(start + vec2(10.0, 10.0))]);
assert!(m.app.session.in_interaction(), "the rectangle is being drawn");
m.reads(6, |_, i| vec![Event::PointerMoved(start + vec2(10.0, 10.0) * (i + 2) as f32)])
});
assert_eq!(read, 0, "the menus weren't read at any step of the drag");
assert!(find(&m.fake.last(), "edit.cut").enabled, "the preview's rectangle is selected");
let synced = m.fake.synced();
m.frame(vec![Event::Key { key: Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }]);
assert!(!m.app.session.in_interaction(), "Escape dropped the rectangle");
assert_eq!(m.fake.synced(), synced + 1, "the menus were read");
assert!(!find(&m.fake.last(), "edit.cut").enabled, "nothing is selected");
}
/// A move dragged off the canvas onto a panel stops being a move with its button still held
/// (`canvas::drag_art_out`): the menus are read then, without a release or a key, and Undo still
/// names the step before the drag.
#[test]
fn a_move_dragged_onto_a_panel_reads_the_menus() {
let (mut m, (start, undo, read)) = undisturbed(|m| {
let undo = find(&m.fake.last(), "edit.undo").label.clone();
let start = m.start_move();
(start, undo, m.reads(4, |_, i| vec![Event::PointerMoved(start + vec2(8.0 * (i + 2) as f32, 0.0))]))
});
assert_eq!(read, 0, "the menus weren't read at any step of the drag");
let synced = m.fake.synced();
let panel = Pos2::new(m.app.canvas_rect.unwrap().right() + 40.0, start.y);
m.frame(vec![Event::PointerMoved(panel)]);
assert!(!m.app.session.in_interaction(), "the move was dropped");
assert_eq!(m.fake.synced(), synced + 1, "the menus were read");
assert_eq!(find(&m.fake.last(), "edit.undo").label, undo);
}
/// A dialog previews each angle that the control port sets, and the menus aren't read for the
/// angles: `ui.dialog.cancel` on the control port ends the preview, and the menus are read then,
/// without a release or a key.
#[test]
fn a_control_port_cancel_of_a_dialog_preview_reads_the_menus() {
let (mut m, read) = undisturbed(|m| {
m.rotate_preview();
m.angles(4)
});
assert_eq!(read, 0, "the menus weren't read while the dialog previewed the angles");
let synced = m.fake.synced();
crate::tests_synthetic::control(&mut m.app, &m.ctx, "ui.dialog.cancel", json!({}));
m.frame(vec![]);
assert!(!m.app.session.in_interaction() && m.app.ui.dialog.is_none());
assert_eq!(m.fake.synced(), synced + 1, "the menus were read");
}
/// OK applies the rotation a dialog previews as one undo step: the menus are read then, with Undo
/// naming it, and not for the angles previewed before.
#[test]
fn applying_a_dialog_preview_reads_the_menus() {
let (mut m, read) = undisturbed(|m| {
m.rotate_preview();
m.angles(4)
});
assert_eq!(read, 0, "the menus weren't read while the dialog previewed the angles");
let synced = m.fake.synced();
crate::tests_synthetic::control(&mut m.app, &m.ctx, "ui.dialog.confirm", json!({}));
m.frame(vec![]);
assert!(!m.app.session.in_interaction() && m.app.ui.dialog.is_none());
assert_eq!(m.fake.synced(), synced + 1, "the menus were read");
assert_eq!(find(&m.fake.last(), "edit.undo").label, "Undo Rotate");
}
/// The font menu previews each font it highlights on the selected type, in one interaction: the
/// menus are read as the preview begins and as it ends, and not for the fonts between.
#[test]
fn the_font_menu_preview_reads_the_menus_when_it_ends() {
use crate::font_menu::FontPick;
// The app reads the menus after each pick as at the end of a frame. A whole frame would start
// with `font_menu::end_stale_preview`, which ends a preview whose menu isn't drawn.
let apply = |m: &mut Mac, pick: FontPick| {
let synced = m.fake.synced();
crate::font_menu::apply(&mut m.app, &m.ctx, pick);
native_menu::sync(&mut m.app, &m.ctx);
m.fake.synced() - synced
};
let (mut m, read) = undisturbed(|m| {
m.app.run("select.none", json!({})).unwrap();
m.app.run("text.create", json!({"x": 50, "y": 50, "text": "Hi"})).unwrap();
m.frame(vec![]);
assert_eq!(apply(m, FontPick::Preview("Source Serif 4".into(), None)), 1, "the menus were read as the preview began");
apply(m, FontPick::Preview("Source Sans 3".into(), None)) + apply(m, FontPick::Preview("Inter".into(), None))
});
assert_eq!(read, 0, "the menus weren't read for the fonts after the first");
assert_eq!(apply(&mut m, FontPick::EndPreview), 1, "the menus were read as the preview ended");
assert!(!m.app.session.in_interaction());
}
/// A click runs its command like an in-window click, and the menus follow: View › Show Rulers
/// reads Hide Rulers afterwards; the app menu's Appearance items run with their params.
#[test]
+34 -2
View File
@@ -4,7 +4,7 @@
use serde_json::json;
use vectorcraft_doc::NodeKind;
use vectorcraft_engine::Session;
use vectorcraft_engine::cmd::clipboard::{EMF, PNG};
use vectorcraft_engine::cmd::clipboard::{EMF, EPS, Flavour, PASTE_ORDER, PDF, PNG, TEXT, file_flavour};
use crate::sysclip::import_command;
use crate::tests_sysclip::{app, blue_png, copy_elsewhere, pasted, run};
@@ -17,7 +17,7 @@ fn an_emf_from_another_app_pastes_as_vectors_ahead_of_its_bitmap() {
other.execute("shape.ellipse", &json!({"x": 10, "y": 10, "width": 30, "height": 30})).unwrap();
let emf = other.execute("document.export", &json!({"format": "emf"})).unwrap();
let emf = vectorcraft_format::base64_decode(emf["dataBase64"].as_str().unwrap()).unwrap();
let flavour = vectorcraft_engine::cmd::clipboard::Flavour { mime: EMF, data: emf.clone() };
let flavour = Flavour { mime: EMF, data: emf.clone() };
assert_eq!(import_command(&flavour, None).0, "clipboard.importEmf");
copy_elsewhere(&board, vec![(PNG, blue_png()), (EMF, emf)]);
run(&mut app, "edit.paste", json!({}));
@@ -26,3 +26,35 @@ fn an_emf_from_another_app_pastes_as_vectors_ahead_of_its_bitmap() {
let b = p[0].geometric_bounds().unwrap();
assert!((b.width() - 30.0).abs() < 0.05, "{b:?}");
}
/// A 30 pt red square, as an EPS written by hand from the EPSF specification.
const SQUARE_EPS: &str = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 100\n%%EndComments\n1 0 0 setrgbcolor\nnewpath 10 10 moveto 40 10 lineto 40 40 lineto 10 40 lineto closepath fill\nshowpage\n%%EOF\n";
/// An EPS another app copied (an equation editor's, a drawing app's) pastes as editable paths, not
/// as the bitmap or the text beside it, and not as what was copied in the app before (#1499).
#[test]
fn an_eps_from_another_app_pastes_as_vectors() {
let (mut app, board) = app();
crate::tests_sysclip::copy_rect(&mut app);
let eps = SQUARE_EPS.as_bytes().to_vec();
assert_eq!(import_command(&Flavour { mime: EPS, data: eps.clone() }, None).0, "clipboard.importEps");
copy_elsewhere(&board, vec![(PNG, blue_png()), (TEXT, b"x = 1".to_vec()), (EPS, eps.clone())]);
run(&mut app, "edit.paste", json!({}));
let p = pasted(&app);
assert!(!p.is_empty(), "something pasted");
let path = |n: &vectorcraft_doc::Node| matches!(n.kind, NodeKind::Path { .. });
let mut paths = vec![];
p.iter().for_each(|n| n.walk(&mut |c| paths.extend(path(c).then(|| c.geometric_bounds().unwrap()))));
assert_eq!(paths.len(), 1, "{p:?}");
assert!((paths[0].width() - 30.0).abs() < 0.05 && (paths[0].height() - 30.0).abs() < 0.05, "{paths:?}");
assert!(p.iter().all(|n| !matches!(n.kind, NodeKind::Image(_) | NodeKind::Text(_))), "{p:?}");
// A PDF beside it is the better copy: the apps that offer both mean the same picture.
assert!(PASTE_ORDER.iter().position(|m| *m == PDF) < PASTE_ORDER.iter().position(|m| *m == EPS));
// Not PostScript: refused, nothing pasted over.
let pdf = vectorcraft_format::base64_encode(b"%PDF-1.7");
assert!(app.session.execute("clipboard.importEps", &json!({"dataBase64": pdf})).is_err());
// An .eps file copied in a file manager is that flavour too (told by its bytes, not its name).
assert_eq!(file_flavour("equation.eps", &eps, &PASTE_ORDER), Some(EPS));
assert_eq!(file_flavour("equation.dat", &eps, &PASTE_ORDER), Some(EPS));
assert_eq!(file_flavour("equation.eps", &eps, &[TEXT]), None);
}
+14 -1
View File
@@ -895,7 +895,7 @@ pub fn opacity_blend(
icons::paint(ui, "chevron-right", r.shrink2(vec2(3.0, 7.0)), if enabled { t.icon } else { t.text_disabled });
egui::Popup::menu(&resp).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| {
let mut o = opacity.unwrap_or(1.0) * 100.0;
let r = ui.add(egui::Slider::new(&mut o, 0.0..=100.0).show_value(false));
let r = slider(ui, egui::Slider::new(&mut o, 0.0..=100.0).show_value(false));
let phase = if r.drag_stopped() || (r.changed() && !r.dragged()) {
Live::Released
} else if r.changed() {
@@ -990,6 +990,19 @@ pub fn icon_button_enabled(ui: &mut Ui, icon: &str, tip: &str, selected: bool, e
if tip.is_empty() { resp } else { resp.on_hover_text(tl!(tip)) }
}
/// A slider whose rail shows, filled up to the handle: the theme's widget fill matches the panel
/// and dialog background, which leaves only the handle visible (#1483).
pub fn slider(ui: &mut Ui, slider: egui::Slider<'_>) -> Response {
let t = Tokens::get(ui.ctx());
ui.scope(|ui| {
let v = ui.visuals_mut();
v.widgets.inactive.bg_fill = t.input_border;
v.selection.bg_fill = t.accent;
ui.add(slider.trailing_fill(true))
})
.inner
}
/// Regular-weight panel sub-header ("Shape Modes:", "Align Objects:").
pub fn subheader(ui: &mut Ui, text: &str) {
let t = Tokens::get(ui.ctx());
+2 -1
View File
@@ -507,7 +507,8 @@ type with those options (`file.place {text: {…}}`).
System clipboard formats: through the desktop app, `edit.copy` and `edit.cut` publish what `clipboard.flavours`
lists to the system clipboard, and every Paste command first loads what another app copied (`clipboard.importSvg`,
`importPdf`, `importText` or `importImage`, centred in the view); an import error answers the Paste with that error
`importPdf`, `importEps`, `importText` or `importImage`, centred in the view; the desktop app reads PDF and EPS from
the Windows clipboard and, with SVG, from the macOS pasteboard, and an `.eps` file copied in a file manager anywhere); an import error answers the Paste with that error
and pastes nothing. Cmd+V also pastes a bitmap or PDF with no text beside it (on the key's release, as egui sends no
Paste event for it). Screenshots paste on every platform: Windows reads `PNG`, else `CF_DIBV5`/`CF_DIB`, macOS the
pasteboard's PNG or TIFF, Linux `image/png`, and the web the picture the browser's paste event carries (#457).
+6 -6
View File
@@ -92,7 +92,7 @@ By default VectorCraft's own crates log at `info` and everything else at `warn`.
On macOS the menus live in the system menu bar, not in the window's app bar (which keeps the brand mark, Home, the search icon and the workspace switcher next to the traffic lights, centred on the bar by `apps/vectorcraft/src/mac_window.rs`). `--in-window-menus` or `VECTORCRAFT_IN_WINDOW_MENUS=1` keeps them in the window, as on Windows, Linux and the web; so does a menu bar AppKit refuses to build (logged). `ui.inspect` says which with `nativeMenuBar`.
- **One menu model.** `crates/ui-egui/src/native_menu.rs` (platform-free, tested on every platform) builds the menu bar from the in-window menus (`menus::menu_tree`, each item through `menus::entry`, which the in-window menus draw too) and lays it out the Mac way: the VectorCraft menu holds About, Settings ▸ (one item per Preferences page, General… ⌘K), Language ▸, Appearance ▸ (UI brightness), Services, Hide VectorCraft ⌃⌘H (⌘H stays View › Hide Edges), Hide Others ⌥⌘H, Show All and Quit ⌘Q (the app's own `app.quit`, so unsaved documents are asked about); those leave Edit and Help. The in-window bar itself never shows the VectorCraft menu (it starts at File, as in Illustrator, on every platform): Language and Appearance have no in-window menu and are synthesized in `mac_layout`, and Quit is File › Exit in the window, relabelled to Quit in the App menu. Window starts with Minimize ⌃⌘M and Zoom and ends with Bring All to Front, and Help is the system's Help menu (its search field). A system key a command (or a user's shortcut) already has stays the command's, and the log says so.
- **The native side** is `apps/vectorcraft/src/mac_menu.rs`: muda (`=0.21.1`, default features off, macOS only, no `unsafe`) builds the `NSMenu`s. Labels, enabled and checked are updated in place when anything they show may have changed (a command ran, the document, its history or selection changed, a click or a key press); a change of structure (a recent file, the language, a shortcut) rebuilds the menus.
- **The native side** is `apps/vectorcraft/src/mac_menu.rs`: muda (`=0.21.1`, default features off, macOS only, no `unsafe`) builds the `NSMenu`s. Labels, enabled and checked are updated in place when anything they show may have changed (a command ran, the document, its history or selection changed, a click or a key press); a change of structure (a recent file, the language, a shortcut) rebuilds the menus. While an interaction is open (for example a move, scale or shape drag, a dialog's preview or the font menu's preview), the app updates them for the document's changes only when the interaction begins and when it ends.
- **Keys stay with egui.** AppKit runs a menu's key equivalents before the window sees the key, so the item's key goes back to egui as the key press it was (⌘X/⌘C/⌘V as egui's Cut/Copy/Paste events), through `raw_input_hook`: `shortcuts::handle` runs it once, user shortcuts apply, and a focused text field keeps ⌘A, ⌘C, ⌘V and ⌘Z. A click runs the item like an in-window click. Bare keys and ⌥/⇧ chords are never key equivalents (they type).
- Built and clippy-checked for `aarch64-apple-darwin` and `x86_64-apple-darwin` from any host: `cargo clippy -p vectorcraft --target aarch64-apple-darwin --all-targets -- -D warnings`.
@@ -171,14 +171,15 @@ always use the English ids and labels, so agents and scripts never see translate
Languages shipped: English (`en`, the source), Traditional Chinese (`zh-hant`, complete, in the vocabulary used
in Taiwan; `zh-TW`, `zh-HK`, `zh-MO` and `zh-Hant-*` locales all resolve to it), Simplified Chinese (`zh-hans`,
complete, in the vocabulary used in mainland China; `zh-CN`, `zh-SG`, `zh-Hans-*` and a bare `zh` resolve to it,
so the two scripts never mix), Japanese (`ja`, complete), Korean (`ko`, complete; every `ko-*` locale resolves to it; a count takes no plural, and Hangul is drawn with an installed system font), German (`de`, complete; `de-DE`, `de-AT`, `de-CH` and every
so the two scripts never mix), Japanese (`ja`, complete), Korean (`ko`, complete; every `ko-*` locale resolves to it; a count takes no plural, and Hangul is drawn with an installed system font), Vietnamese (`vi`, complete; every `vi-*` locale resolves to it; a count takes no plural, so plurals have one form), German (`de`, complete; `de-DE`, `de-AT`, `de-CH` and every
other `de-*` locale resolve to it), Spanish (`es`, complete, in neutral
international Spanish; every `es-*` locale such as `es-ES`, `es-MX`, `es-AR` or `es-419` resolves to it), French (`fr`,
complete; `fr-FR`, `fr-BE`, `fr-CA`, `fr-CH` and every other `fr-*` locale resolve to it), Italian (`it`,
complete; `it-IT`, `it-CH` and every other `it-*` locale resolve to it), Russian (`ru`, complete; every `ru-*`
locale such as `ru-RU`, `ru-BY` or `ru-KZ` resolves to it), Ukrainian (`uk`, complete; `uk-UA`,
`uk_UA.UTF-8` and every other `uk-*` locale resolve to it; integer plurals use one/few/many), Hungarian (`hu`, complete;
`hu-HU` and every other `hu-*` locale resolve to it; a count takes the singular, so plurals have one form), Czech (`cs`, every menu label) and Brazilian Portuguese
`hu-HU` and every other `hu-*` locale resolve to it; a count takes the singular, so plurals have one form), Polish (`pl`, complete; `pl-PL` and every other `pl-*`
locale resolve to it; plurals use one/few/many, with 21, 31 … taking many), Czech (`cs`, every menu label) and Brazilian Portuguese
(`pt-br`, every menu label and every `tl!` literal). Untranslated text falls back to English until its rows are added.
- `tl!("…")` translates a literal into the language the UI is drawn in; `i18n::t(s)` is the same for a
@@ -206,10 +207,9 @@ locale such as `ru-RU`, `ru-BY` or `ru-KZ` resolves to it), Ukrainian (`uk`, com
control channel, MCP and tests read them) and are translated only where the status bar draws them
(`i18n::msg`). `@msg` catalog rows hold a whole message or a template such as
`Couldn't open {name}: {e}`; `{_1}`, `{_2}` … stand for the format string's `{}`, and the values in the
placeholders are translated in turn (the reason after `: {e}` is often a message too). Spanish, French, Hungarian, Italian, Japanese, Russian and Ukrainian cover every
placeholders are translated in turn (the reason after `: {e}` is often a message too). Czech, German, Spanish, French, Hungarian, Italian, Japanese, Korean, Polish, Russian, Ukrainian and Vietnamese cover every
message literal the test scan finds (`complete_languages_translate_every_message`, languages listed in
`COMPLETE_MESSAGES`): a new `Err("…")`, `Other(…)`, `#[error(…)]` or `status(…)` message needs an `es.tsv`,
a `fr.tsv`, a `hu.tsv`, an `it.tsv`, a `ja.tsv`, a `ru.tsv` and a `uk.tsv` row (`VECTORCRAFT_I18N_DUMP_MESSAGES=messages.txt cargo test -p vectorcraft-ui-egui
`COMPLETE_MESSAGES`): a new `Err("…")`, `Other(…)`, `#[error(…)]` or `status(…)` message needs a row in each of those catalogs (`VECTORCRAFT_I18N_DUMP_MESSAGES=messages.txt cargo test -p vectorcraft-ui-egui
complete_languages_translate_every_message` lists them all). Other languages show messages in English
until they add `@msg` rows.
- Not translated on purpose: names that are user data (layers, swatches, fonts, documents), the tab
+4 -2
View File
@@ -1,6 +1,6 @@
# Effects parity
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (3D and Materials: Extrude & Bevel, Inflate and Rotate added, ~8% → ~25%; G2: Film Grain added; Photoshop effects 29/57; 28 filters remain) · **Target:** Adobe Illustrator 2026 (30.x)
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (3D and Materials on outlined type and other shapes of many small curves, #1481; Twist 0° to 360°, #1524; twisted walls keep their faces, #1525; score unchanged; 3D and Materials: Inflate takes Twist, Taper and Cap; score unchanged) · **Target:** Adobe Illustrator 2026 (30.x)
Every entry of Illustrator's Effect menu, by its public feature name, against VectorCraft's effects catalogue
(`effect_catalog()` in `crates/effects/src/lib.rs`) and the Effect menu built from it
@@ -85,7 +85,7 @@ not an accuracy guarantee for arbitrary artwork. Tests: `pixel::tests::film_grai
| Item | Ours |
|---|---|
| Revolve | initial: live, editable profile, rotation and light gizmos, flat shading, SVG/PDF output, Expand Appearance ([revolve.md](revolve.md), #846) |
| Extrude & Bevel, Inflate, Rotate | initial: live, depth, twist, taper, solid or hollow caps, five original bevel shapes, Inflate volume and both sides, Rotate of every fill and stroke, Position presets, rotation and light gizmos, SVG/PDF output, Expand Appearance ([three-d.md](three-d.md)) |
| Extrude & Bevel, Inflate, Rotate | initial: live, depth, twist, taper, solid or hollow caps, five original bevel shapes, Inflate volume, both sides, twist, taper and cap, Rotate of every fill and stroke, Position presets, rotation and light gizmos, SVG/PDF output, Expand Appearance ([three-d.md](three-d.md)) |
| Materials panel, lighting, ray-traced render | one directional light with flat shading only; no materials, several lights, light colour, shadows or ray tracing |
| 3D (Classic): Extrude & Bevel, Revolve, Rotate | none |
| Turntable (30.0 beta) | none |
@@ -99,6 +99,8 @@ Revolve caps, 3D Classic, Turntable, 3D export) is 25–45 h.
| Date | Change | Summary |
|---|---|---|
| 2026-10-13 | minor | 3D and Materials: outlined words and other shapes of many small curves take Rotate, Extrude & Bevel and Inflate (curves are sampled by a tolerance; Rotate takes up to 65,536 outline points; #1481); Extrude & Bevel's Twist runs 0° to 360° as the public panel reference gives it, a negative value drawing untwisted (#1524); a twisted extrusion keeps its walls, which were dropped from about 45° (#1525); details in [three-d.md](three-d.md); 3D stays ~25%, 25–45 h (estimated) |
| 2026-10-13 | minor | Inflate takes Twist, Taper and Cap ([three-d.md](three-d.md)); 3D stays ~25%, 25–45 h: materials, lights and shadows are the bulk of what remains |
| 2026-10-12 | minor | Extrude & Bevel, Inflate and Rotate (initial, [three-d.md](three-d.md)); 3D ~8% → ~25%, 45–75 → 25–45 h |
| 2026-10-12 | minor | G2: Artistic › Film Grain added with live controls and raster exports; measured Photoshop filters 29/57, 28 remaining (23–39 h). |
| 2026-10-11 | minor | PDF cap warnings identify original objects after appearance splitting and report the lowest achieved ppi; cap/rendering and scores unchanged |
Loaded 100 of 109 files, more files were not shown because too many files have changed in this diff. Show more