Compare commits

...
Author SHA1 Message Date
bflatasticandClaude Opus 5.5 ba93f62bcb Fix #577: the gradient stop popover stays open after the click that opens it
The Gradient panel's colour chip opens the stop popover on a click. The
popover closes on a click elsewhere, and the opening click itself, which
is released in the frame the popover first draws and lies outside it,
counted as one: the popover closed at once (a double-click got through,
as the popover lets the double-click that opens it from the canvas pass).

The popover now records the frame it first drew in and only a click in a
later frame closes it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 03:48:27 +07:00
BFlat 28846a98a0 Merge pull request: land #574 (fix #526)
Land #574 (fix #526: the exports and the CLI write .ai as Save As does)
2026-10-09 03:31:37 +07:00
bflatastic 4051a895d7 Merge #574: Fix #526: the exports and the CLI write .ai as Save As does
# Conflicts:
#	ROADMAP.md
2026-10-09 03:26:21 +07:00
bflatasticandClaude Opus 5.5 1e2cb082ba Fix #526: the exports and the CLI write .ai as Save As does
file.saveAs and document.save wrote a PDF-compatible .ai, but
document.export (and with it the CLI's run --export x.ai and convert
in.svg out.ai, and MCP's export) refused it as a format that can only be
opened, and --help didn't list it as writable.

The .ai encoder is now shared: save.rs's ai_params and encode_ai (a PDF
of every artboard with the PDF options, carrying the native document,
blank pages with pdfCompatible: false) serve Save As and the exports
alike. The .ai format is writable, so document.formats, --help and the
MCP export tool list it; an export leaves the document's own path alone.
Export As and Export for Screens keep leaving .ai to Save As.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 03:18:07 +07:00
BFlat 207bd09635 Merge pull request #572 from storytold/fix/issue-569
Fix #569: Shape Builder merges leave no stray edges in their outlines
2026-10-09 03:12:05 +07:00
bflatasticandClaude Opus 5.5 2023a47188 Fix #569: Shape Builder merges leave no stray edges in their outlines
Merging regions united the faces' outlines with a boolean union. Each
face had been refit on its own, so two faces' shared edge could come out
a hair apart: the union then kept the edge between them, or a spur of
it, and a stroked merged shape (unfilled art) showed a stray line inside.
Subtracting the merged shape from the others left slivers along it too.

pathops::FaceMerger merges faces from the planar arrangement itself,
made once per merge: their contours share their edges exactly, so the
edges between merged faces vanish. The Shape Builder builds the merged
shape that way, and what is left of each shape from its faces not merged
(rather than subtracting the merged shape from it). Selections with open
paths keep the old union.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 03:04:48 +07:00
BFlat 85319c972c Merge pull request #571 from mo0kid/fix/macos-native-menu-dismissal
Fix macOS native menu dismissal
2026-10-09 03:00:47 +07:00
David Whiting 94ecbec9fc M14.8: opt in to public GitHub profile-name credit 2026-10-08 20:50:54 +01:00
David Whiting cb61bdf61f M14.8: dismiss macOS native menus after selection or outside input 2026-10-08 20:50:54 +01:00
David Whiting d1d78e61da M0.CI: restore checks without optional fonts 2026-10-08 20:50:54 +01:00
BFlat c26c4a2060 Merge pull request #564 from Haven-King/feat/vectorcraft-placed-documents
Feat/vectorcraft placed documents
2026-10-09 02:26:56 +07:00
haven 5e7af3f83c Placed documents: Place's Link tooltip, Break Link in the Links panel 2026-10-08 12:20:59 -07:00
haven 2418921760 Placed documents: on screen, cached bitmaps made in the background 2026-10-08 12:20:51 -07:00
haven e04b94938b Placed documents: Links commands check, update, relink and break their links 2026-10-08 12:20:51 -07:00
haven afc45cdeb8 Placed documents: File › Place links a VectorCraft document by default; output reads its file 2026-10-08 12:20:51 -07:00
haven 6d56195eda Placed documents: the object, drawn exactly and kept as art by every exporter 2026-10-08 12:20:51 -07:00
haven 02072c310a Format v4: large data after the JSON 2026-10-08 12:20:51 -07:00
haven 92817d6ca1 Widgets: check_tip, a checkbox whose tooltip shows over its box and label 2026-10-08 12:20:51 -07:00
BFlat 857273001b Merge pull request: land #565 (fix #541)
Land #565 (fix #541: a click on a selected object makes it the key object)
2026-10-09 02:16:52 +07:00
bflatastic 48f07958a9 Merge #565: Fix #541: a click on a selected object makes it the key object
# Conflicts:
#	ROADMAP.md
2026-10-09 02:11:01 +07:00
BFlat c6bea61ffc Merge pull request: land #562 (fix #555)
Land #562 (fix #555: the font menu scrolls only its list)
2026-10-09 02:09:49 +07:00
bflatasticandClaude Opus 5.5 f31d6874aa Fix #541: a click on a selected object makes it the key object
With the Selection tool, a click (no drag, no modifier) on one object of a
selection of several makes it the key object (select.key); a click on the
key again lets it go. The key object is drawn with a thicker outline,
Align aligns to it (the Align panel shows Align to Key Object while there
is a key, and choosing Selection or Artboard lets it go), and
object.align without `to` aligns to the key when there is one, so the
Control bar's and the Properties panel's Align buttons do too. With a
spacing, Distribute Spacing keeps the key object still and spaces the
others from it, and it reports too few objects instead of indexing an
empty list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 02:08:56 +07:00
bflatastic c44572d272 Merge #562: Fix #555: the font menu scrolls only its list
# Conflicts:
#	ROADMAP.md
2026-10-09 02:05:49 +07:00
bflatasticandClaude Opus 5.5 1b43d8b8f9 Fix #555: the font menu scrolls only its list
egui's combo box puts its own scroll area around a combo's list, so the
font menu, which scrolls its families itself, had two scrollbars: once
the families reached their end the wheel scrolled the outer one, taking
the search field and the filters out of view.

The font menu (widgets::combo with searchable) now opens its list in a
popup of its own, drawn like the combo box, without that outer scroll
area: below the button, or above it when there is more room there. The
families list fills the popup's room under the search field and filters,
which stay at the top while the list scrolls.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 01:54:11 +07:00
BFlat 2b321d240f Merge pull request: land #558 (fix #550)
Land #558 (fix #550: an SVG of chosen artboards holds only their art)
2026-10-09 01:50:20 +07:00
bflatastic 2139c4d661 Merge #558: Fix #550: an SVG of chosen artboards holds only their art
# Conflicts:
#	ROADMAP.md
2026-10-09 01:45:04 +07:00
BFlat 179a87d0a6 Merge pull request: land #557 (fix #525)
Land #557 (fix #525: Image Trace of a large photo no longer crashes)
2026-10-09 01:42:04 +07:00
bflatasticandClaude Opus 5.5 b832599a47 Fix #550: an SVG of chosen artboards holds only their art
Exporting one artboard of many to SVG wrote the whole document's art into
that artboard's file, the other artboards' art outside its viewBox: an
editor opening it showed every artboard's art. A file for an artboard
named in the export (Use Artboards with a range or All, Export for
Screens) now holds the objects over that artboard only, at any depth of
layers, as DXF's crop leaves them; objects reaching into it stay whole
and a clipping layer keeps all of its objects. An SVG with no artboard
named (Save As) still holds the whole document.

Part of #546: Export As with a range writes the chosen artboard alone in
SVG, DXF, PDF and PNG, each file with that artboard's art (tested from
the dialogs).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 01:38:38 +07:00
bflatastic d7b4d85d3c Merge #557: Fix #525: Image Trace of a large photo no longer crashes the app
# Conflicts:
#	ROADMAP.md
2026-10-09 01:35:31 +07:00
BFlat af7a5239be Merge pull request #556: Release: VectorCraft v0.7.0
Release: VectorCraft v0.7.0
2026-10-09 01:18:16 +07:00
bflatasticandClaude Opus 5.5 06242cd3ab Fix #525: Image Trace of a large photo no longer crashes the app
Tracing a 2048 x 2048 photo with High Fidelity Photo made 733,000 paths
and 7.8 million anchors. The selected result's outlines and anchor
squares then made an egui mesh of 1.8 GB, over the GPU's largest buffer:
wgpu panicked while painting and the app quit (or ran out of memory
first, at 6.4 GB).

- Canvas: a selection with more than 100,000 anchors shows its bounds
  instead of every outline and anchor, and the hover highlight skips
  such an object. The Contextual Task Bar and that outline read the
  selection's bounds from a per-revision cache (VectorcraftApp::
  selection_bounds): a selected trace drew a frame in 20 ms, not 170.
- Image Trace: the colour layers are traced in parallel (26 s to 1.9 s
  for that photo; the web traces them in turn). trace_within stops once
  the paths pass an anchor budget; imageTrace.make allows two million
  and otherwise reports the trace as too complex, with what to change.
  Images over 64 megapixels are refused from their header, before they
  are decoded.
- The trace crate's messages are translated (es, it) and scanned.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 01:18:03 +07:00
bflatasticandClaude Opus 5.5 c3279f1bcf Release: VectorCraft v0.7.0
For users, since 0.6.0:
- Linux: no more startup crash on desktops whose compositor runs on another
  GPU (#502, #551); the window renders on the desktop's GPU and retries
  the next one instead of crashing.
- Windows: rendering through DirectX 12 first, fixing the black flicker on
  Intel GPUs (#545).
- Italian interface (#514).
- macOS: the menus live in the system menu bar.
- Panels, panel groups and the Tools panel undock into floating panels (#495).
- Live Corners on any path's corners: stars, polygons, pen paths (#511).
- Drawing tools snap to Smart Guides as the Selection tool does (#506).
- Pen: Cmd/Ctrl edits the path being drawn, Alt reshapes segments, drags
  out of the first anchor always close (#494, #501); Convert buttons for
  whole paths (#504).
- Right-click a ruler to change the document's units; the Control bar's
  Transform link opens the Transform panel.
- Object > Image Trace > Make traces with the Default preset (#543).
- Edit menu Select All, Cut, Copy and Paste act on a focused field (#516).
- Japanese UI: new type starts top-to-top with em box centre alignment (#432).
- PDF/.ai import keeps type strokes, wrapped lines and layer order (#508);
  EPS import fixes (#498, #505).
- macOS 27: only file URLs are opened (#433); Linux: the Paste menu no
  longer freezes on an unresponsive clipboard owner (#510).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 01:16:08 +07:00
BFlat 4f07bd93b0 Merge pull request #553: land #533, #548, #549, #552
Land #533, #548, #549, #552 with review fixes
2026-10-09 01:08:30 +07:00
bflatastic 086d6287be Merge #552: Fix #543: Object › Image Trace › Make traces with the Default preset
# Conflicts:
#	ROADMAP.md
2026-10-09 01:03:27 +07:00
bflatasticandClaude Opus 5.5 0e6a47e72d Control bar: Italian for the Transform link's tooltip
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 01:03:03 +07:00
bflatasticandClaude Opus 5.5 f8004250fb Fix #543: Object › Image Trace › Make traces with the Default preset
Make… and Make and Expand… opened the generic parameter form, whose
preset was a text box holding a preset's name (Black and White Logo,
6 Colors), so the other presets looked missing. As in Illustrator, Make
and Make and Expand now trace at once with the Default preset, as the
Control bar's Image Trace button does; the button's arrow and the Image
Trace panel's Preset list choose among the 12 presets. The catalogs drop
the two "…" labels; Czech gets Make and Expand.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 01:01:02 +07:00
bflatastic 03288f34dc Merge #549: Fix #545: Windows renders through DX12 before Vulkan
# Conflicts:
#	ROADMAP.md
2026-10-09 00:58:47 +07:00
bflatastic aa4fa48751 Merge #548: Part of #516: the in-window menus' Select All, Cut, Copy and Paste act on a focused field
# Conflicts:
#	ROADMAP.md
2026-10-09 00:58:46 +07:00
bflatastic 165db95dd4 Merge #533: Control bar: Transform link opens the Transform panel; reference point locator redrawn 2026-10-09 00:58:40 +07:00
bflatasticandClaude Opus 5.5 ac043129c8 Fix #545: Windows renders through DX12 before Vulkan
Windows lists each GPU under both backends, and Vulkan came first. On an
Intel GPU its driver made the whole window flicker black while the
pointer moved; the same machine was fine with WGPU_BACKEND=dx12 or gl.
adapter_order now ranks a GPU's DX12 adapter before its Vulkan one, after
the power preference, so the GPU chosen doesn't change, only how it is
driven. Vulkan stays the fallback (a failed DX12 start restarts on it)
and WGPU_BACKEND=vulkan still picks it. Elsewhere there is no DX12
adapter, so nothing changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 00:56:49 +07:00
bflatasticandClaude Opus 5.5 8e753d746e Part of #516: the in-window menus' Select All, Cut, Copy and Paste act on a focused field
The clipboard keys already went to a focused text field, but on Windows,
Linux and the web the press that opens a menu takes the keyboard from the
field, so Edit > Copy (and Cut, Paste, Select > All) acted on the art.
The menu bar now keeps the field that had the keyboard, and its
selection, while the menus are open; those four commands go to it as the
events their keys send, the frame after the click that chose them, and
give it the keyboard back. Everything else, and those commands with no
field, run as before. The macOS menu bar shares the same helpers.

Tests: Copy, Cut and Paste events in the W field and the Color panel's
hex field edit the text, never the art; Select > All, Edit > Copy and
Edit > Paste clicked in the in-window menus act on the field.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 00:51:02 +07:00
BFlat 85dcb28e41 Merge pull request #547: land #542, #523, #528, #527, #538, #529
Land #542, #523, #528, #527, #538, #529 with review fixes
2026-10-09 00:48:38 +07:00
bflatastic 971b0bb95e Merge #529: Fix #506: drawing tools snap to Smart Guides as the Selection tool does
# Conflicts:
#	ROADMAP.md
2026-10-09 00:44:46 +07:00
bflatasticandClaude Opus 5.5 01c9be7d35 Part of #511: Italian rows for the Live Corners messages on any path
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 00:44:29 +07:00
bflatastic 7248c6aeec Merge #538: Fix #511: Live Corners on any path's corners (stars, polygons, pen paths)
# Conflicts:
#	ROADMAP.md
2026-10-09 00:44:29 +07:00
bflatasticandClaude Opus 5.5 6efe9df3e8 Type (#432): the language test keeps its frames in English
The drawing language is process-wide, so a Japanese frame translated the
tests running beside it (Appearance, Attributes, menus). The test now
checks that each frame hands the engine its language without leaving
English.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 00:44:10 +07:00
bflatastic 7a270c8deb Merge #527: Type (#432): new type in a Japanese interface starts top-to-top with em box centre alignment
# Conflicts:
#	ROADMAP.md
2026-10-09 00:44:10 +07:00
bflatastic 5d695dcb80 Merge #523: Fix #433: open only file URLs handed to the app (macOS 27) 2026-10-09 00:43:58 +07:00
bflatastic cb6e996243 Merge #542: Clippy: use as_chunks for constant-size chunks (Rust 1.98) 2026-10-09 00:43:57 +07:00
bflatasticandClaude Opus 5.5 d9544d8f87 UI: the ruler unit menu in the ROADMAP; its test names the PR
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 00:43:50 +07:00
bflatastic e28d9222e8 Merge #528: UI: right-click a ruler to swap the document units 2026-10-09 00:43:49 +07:00
Michael GiesonandClaude Opus 5.5 c21f783286 Clippy: use as_chunks for constant-size chunks (Rust 1.98)
Rust 1.98's clippy adds `chunks_exact_to_as_chunks`, which `-D warnings`
turns into an error, so `cargo xtask ci` fails on main with the current
stable toolchain. The EPS stencil-mask loop and the cursor rasterizer
(and two cursor tests) now use `as_chunks`, which yields fixed-size
arrays; like `chunks_exact`, it skips an incomplete last chunk, so
nothing changes in behaviour.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-08 12:57:16 -04:00
BFlat 843f46108c Merge pull request #509 from storytold/feat/macos-menu-bar
macOS: the menus live in the system menu bar, settings in the VectorCraft menu
2026-10-08 23:48:25 +07:00
bflatasticandClaude Opus 5.5 ab65474044 macOS: the menus live in the system menu bar, settings in the VectorCraft menu
On macOS the menus are in the system menu bar, laid out as a Mac app's (Illustrator on the Mac as
the reference), and the app settings sit in the VectorCraft menu: 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
quit, so unsaved documents are asked about); they leave Edit and Help. Window gets Minimize ⌃⌘M,
Zoom and Bring All to Front; Help is the system's Help menu. Windows, Linux and the web keep the
in-window menu bar unchanged; --in-window-menus or VECTORCRAFT_IN_WINDOW_MENUS keeps it on macOS
too, and so does a menu bar AppKit refuses to build.

One menu model: the in-window menus and the native bar draw the same rows (menus::entry), and the
platform-free native_menu module lays them out, decides when to update (a cheap state hash; labels,
enabled and checked in place, a rebuild only when the structure changes) and hands key equivalents
back to egui as the key presses they were, so shortcuts, user overrides and focused text fields
behave as in the window and nothing fires twice. The muda backend (pinned =0.21.1, macOS only, no
unsafe) is apps/vectorcraft/src/mac_menu.rs, mirroring PhotoCraft's. ui.inspect reports
nativeMenuBar. Translations for the new labels in ja, es, zh-hans, zh-hant, cs and pt-br.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 23:45:31 +07:00
BFlat 8c4c665ee2 Merge pull request #540 from storytold/fix/eps-sources-restore
Fix #498, part of #505: EPS image sources read in turn, restore undoes dictionary changes (PLRM)
2026-10-08 23:44:50 +07:00
BFlat 4c2c606e25 Merge pull request #535 from storytold/pr/eps-spec-only-tests
EPS tests: interpreter programs written from the PostScript Language Reference
2026-10-08 23:44:33 +07:00
bflatasticandClaude Opus 5.5 b43b15a6e8 Part of #505: restore puts dictionaries back as they were at the save
The PostScript Language Reference (3rd ed., §3.7.3 "Save and Restore")
has `restore` reset composite objects in local VM to their values at the
`save`. The reader only restored the graphics state, so dictionary
entries changed between `save` and `restore` stayed changed: a program
that counts its open saves in a dictionary and refuses to go past a depth
stopped after that many saves in sequence, and the file fell back to its
preview. EPS files with many images, each drawn between `save` and
`restore`, are a likely case of #505; its reporter hasn't sent a file, so
this is part of it.

- While a `save` is open, `def`, `store`, `put`, `undef` and dictionary
  `copy` keep each entry's old value in a journal (counted against the
  memory budget); `restore` undoes it, newest change first, down to its
  save. A save restored already, itself or through an outer one, is no
  longer valid (`invalidrestore`, §3.7.3).
- `cachestatus` reports a device's cache sizes (chapter 8) instead of
  zeros: its last value, the most bytes one cached glyph may take, is what
  programs divide by.
- Tests (programs written from the reference): 100 saves counted in a
  dictionary under a depth limit, each dictionary change undone, saves
  restored twice, `cachestatus`'s glyph limit. Mutation-checked: without
  the journal or with a zero `cachestatus` the test fails. The import fuzz
  vocabulary has saves and restores around dictionary changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 23:43:51 +07:00
bflatasticandClaude Opus 5.5 1d265951df Fix #498: EPS images with several data sources read them in turn
An image can take one data source per colour component
(MultipleDataSources, or `colorimage` with multi true). The PostScript
Language Reference (3rd ed., §4.10 "Images" and `image`/`colorimage` in
chapter 8) has the operator read the sources in turn, the same amount
from each. The reader drained each source on its own instead: when the
sources are procedures reading one file a row at a time, the first plane
took the rows of every component and the image came out in sheared
horizontal bands, as in #498.

- Data sources are read in turn by one reader, `read_sources`: a procedure
  once a round, a file or string a row a round, until each plane is full or
  its source ends. Single sources, procedure filters and masked images use
  it too; a string source resumes where it left off.
- Tests (`tests_images.rs`, programs written from the reference):
  procedures reading one file in the dictionary and `colorimage` operand
  forms (fails without the fix), separate string sources, rows padded to a
  byte at 1, 2, 4, 12 and 16 bits with an odd width (one and several
  sources), Flate PNG predictors with every row filter at an odd width.
  The import fuzz vocabulary has several sources reading one file and
  sources of uneven lengths.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 23:43:49 +07:00
bflatasticandClaude Opus 5.5 eb255ef379 EPS tests: interpreter programs written from the PostScript Language Reference
Two EPS import tests become programs written from the PostScript Language
Reference (3rd ed.), with their own names and structure, covering the
interpreter features the importer relies on:
- `level_2_and_3_probes_read_as_vectors`: a resource category made from
  Generic, resources defined and found in it (§3.9), local and global VM
  (`currentglobal`, `setglobal`, `gcheck`, §3.7.2), `internaldict` probed
  through `stopped`, a halftone dictionary set and restored, `cachestatus`,
  `rootfont` and `currentcolorrendering`, drawing with its own procedures.
- `executable_strings_and_integer_keys`: shading dictionaries closed by an
  executable string (`(>>) cvx`, or a Level 1 builder with `counttomark`),
  procedures kept under integer keys run with `load` through `stopped`,
  `cvx`/`cvlit`/`xcheck` on strings.
Each was mutation-checked: making any of findresource, defineresource,
currentglobal, setglobal, gcheck, internaldict, sethalftone,
currenthalftone, currentcolorrendering, cachestatus, rootfont, stopped,
cvx, load, counttomark, cvlit or xcheck unknown fails a test, and so do
strings that `cvx` leaves literal, `load` refusing integer keys and
`gcheck` answering true.

The ROADMAP's EPS paragraph, file-formats row and last-updated line state
the PostScript features the reader supports; the legacy `.ai` comments in
the import module and the interpreter cite that format's published
specification (PRONOM fmt/423) for the `%AI` header comments and `u`/`U`
group operators the reader keys on.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 23:43:48 +07:00
bflatasticandClaude Opus 5.5 4eac7b505f Fix #506: drawing tools snap to Smart Guides as the Selection tool does
Every drawing tool now asks one snapper (guides::DrawSnap) for the points it
places: the Pen's and Curvature tool's anchors, the Pencil's ends, the shape
tools' start and dragged corner or radius (Rectangle, Rounded Rectangle,
Ellipse, Polygon, Star, Line Segment, Arc, Spiral, the grids), the Type tool's
click and frame and a new artboard's corners. Points land on other objects'
anchors, centres and paths ("anchor", "center", "path") or line up with their
anchors, edges and centres ("align"); hovering shows it before the press, the
Pen's guides end its rubber band, and the Pen lands on the path being drawn
too. Shift keeps a point to its 45-degree step (from Constrain Angle) or a
box's diagonal and slides it along that way into line with a target.
Preferences > Smart Guides > Construction Guides and Angles now act: a drawn
point near a guide through the point it leaves from lands on it.

Before, the Pen snapped only its press and showed nothing, and the shape tools
re-gathered targets on every drag step from the document showing their own
preview, so the dragged corner stuck to where the last step left it.

Performance: targets are gathered once per document state (keyed on the
document's uid and revision, now in ToolContext), from the art in the window,
and sorted, so the anchors, centres and lines near the pointer are found by
bisection. Leaving objects out of the targets no longer looks up each node's
ancestry (quadratic in the document's size): one pruned walk does it, which
also speeds up the Selection tool's moves and resizes.

The direction handles' HandleSnap (#494) is now a DrawSnap holding its own
targets (Targets::for_handle) for the drag: one cache, one lookup.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 23:20:27 +07:00
BFlat 8b036df705 Merge pull request #515 from callmeBalloch/i18n-italian
Fix #514: Italian interface (it)
2026-10-08 23:14:48 +07:00
bflatasticandClaude Opus 5.5 1d14f337db Fix #511: Live Corners on any path's corners (stars, polygons, pen paths)
Corner widgets only ever showed on live rectangles: CornerWidgets::of bailed
out unless the selection's live shape was LiveShape::Rectangle, and
object.setLiveShape only edited rectangle radii. A star is a plain path, so it
had no widgets with either selection tool.

- geom::corners: the corners of any path (anchors without handles between two
  straight sides) and the path with them cut round, inverted round or
  chamfered, each corner a circle tangent to both sides, its radius no larger
  than takes the cut halfway along its shorter side. Rectangles now cut their
  corners with it (bit-identical anchors and layout).
- doc::corners::LiveCorners/set_corners: one model for a live rectangle's,
  a live polygon's (new radii/kinds) and any other path's corners (new
  LiveShape::Path keeping the uncut outline, plain again once nothing is cut);
  radii scale with transforms (Scale Corners) and stay circular.
- object.setLiveShape takes anchor indices for `corners` on any path; polygons
  keep a shared radius as their sides change.
- Widgets: Direct Selection on any path, Selection on live rectangles and
  polygons; placed on each corner's bisector, the drag follows it, the red
  limit outline marks corners at their own limit; the angle preference and
  View > Hide Corner Widget apply. Corners dialog and the Properties and
  Transform panels' Corner Radius (now on polygons too) work on them.
- Tests for the star, the polygon and a pen path in geom, doc, tools, engine
  and ui-egui; docs and ROADMAP.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 23:05:41 +07:00
bflatasticandClaude Opus 5.5 7c5799aec6 i18n: Italian rows for strings added since the PR's base, consistency and fit fixes (review of #515)
- Italian rows for the strings main gained after the PR's base: the
  floating panels of #513 (Float Panel, Dock Panel, the drag hints, two
  window.float messages) and the GPU fallback status message of #519, so
  the completeness tests pass on current main.
- File > Document Setup... reads "Imposta documento..." like the dialog
  title and the Properties button, instead of "Impostazione documento...".
- The Properties panel's quick action "Arrange: Bring to Front" reads
  "Porta in primo piano": "Disponi: Porta in primo piano" was clipped at
  both ends of its fixed-width button.
- OpenType figure style "Proportional Oldstyle" reads "Proporzionali stile
  antico", matching "Tabulari stile antico".
- Blank line between the Italian test and the next item; ROADMAP's
  "Last updated" lists the Italian interface (#514).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 23:04:36 +07:00
callmeBallochandClaude Opus 5.5 4ba8a02107 Contributors: add callmeBalloch (Riccardo Balloch)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iayep93edeimiAE8oSfaT
2026-10-08 23:04:33 +07:00
callmeBallochandClaude Opus 5.5 7c7ae55625 i18n: Italian interface (it)
Adds an Italian catalog (crates/ui-egui/src/i18n/it.tsv, 3,549 rows in
es.tsv's order) covering every menu string, every tl! literal, the
plurals and every status/error message, at the same scope as Spanish.
Standard Italian in sentence case, written clean-room from the meaning
of the English labels; the product, workspace, perspective preset and
language names stay in English as in es and ja.

Registered as "Italiano" with the one/other plural rule and
complete_menus; every it-* locale resolves to it. Tests: it joins
KEEPS_MENU_NAMES and COMPLETE_MESSAGES, italian_reads_as_italian checks
vocabulary and plurals, tags_map_to_languages the locale tags, and the
bundled-font glyph test covers Italian accents and guillemets. README,
ROADMAP and docs/development.md list the language.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011iayep93edeimiAE8oSfaT
2026-10-08 23:04:31 +07:00
BFlat 89ea46c805 Merge pull request #531 from storytold/fix/issue-508
Fix #508: PDF/.ai import keeps type strokes, wrapped lines and layer order
2026-10-08 22:54:27 +07:00
BFlat ffd31fd9cf Merge pull request #534 from storytold/pr/linux-clipboard-probe
Linux: check the system clipboard for Paste off the UI thread (#510)
2026-10-08 22:52:37 +07:00
David PanuschandClaude Opus 5.5 b5759662c1 Control bar: Transform link opens the Transform panel; reference point locator redrawn
The Control bar's underlined Transform link opens the Transform panel as a
popover under it (reference point, X/Y/W/H, Rotate and Shear with their icons
and angle presets, flips, shape properties, Scale Corners, Scale Strokes &
Effects), as the Stroke link does the Stroke panel. X/Y/W/H stay inline while
the bar has room.

The reference point locator is now nine squares with the outer eight joined
around the box; the old outline was inset off the squares' centres.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 17:38:18 +02:00
bflatasticandClaude Opus 5.5 e63606826a Fix #508: PDF/.ai import keeps type strokes, wrapped lines and layer order
- Type left unfinished when a layer's marked content ends, and a clip that closes in a later layer,
  stay in their own layer (no stray "Page N" layer, no art moved to the next layer).
- Top-level layers stack as the pages mark them, so a layer whose art starts on a later page keeps its
  place; layers marked with no art come in empty.
- A stroke written as each glyph's outline stroked, right after (or before) the type, becomes the type
  object's stroke above (or below) its characters: the type stays one editable object.
- Spaces read from gaps wider than a space get their own tracking where even tracking would put the
  glyphs after them more than a tenth of an em off (barcode digit groups); lines are measured to their
  last visible glyph, so a wrapped line's trailing space no longer spreads into the tracking.
- Lines wrapped in a frame (each wrapped line ending in a space, one left edge, font, size and leading,
  with an optional paragraph spacing) come back as one area type object, left aligned or justified,
  only where laying it out breaks the lines exactly where the file does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 22:37:37 +07:00
bflatasticandClaude Opus 5.5 71371b9d58 Linux clipboard probe: look only while Paste depends on it, stop at once (review of #510)
- The worker reads the clipboard only while nothing is copied in the app
  and a document is open (as the in-line check did before), and idles on
  a channel otherwise; it sends a verdict and wakes the UI only when the
  answer changes.
- The in-line check (Windows, macOS, web) keeps its short-circuit: it
  doesn't open the system clipboard after an in-app copy or without a
  document, as before the PR.
- A dead worker hands the check back to the UI thread instead of
  freezing the last verdict.
- Dropping the app wakes the worker and waits (250 ms at most) until it
  has let go of its clipboard handle: on X11 the last arboard handle
  alive hands what the app copied to the clipboard manager, and a
  detached worker holding it would lose that handover at exit.
- The factory stays in `Services` until the first frame takes it (no
  extra app fields); main.rs installs it with `cfg!(target_os = "linux")`.
- Tests trimmed from five to three that share tests_sysclip's helpers:
  the frame never waits on a slow clipboard and only the probe thread
  reads it (nothing read without a document), the probe rests after an
  in-app copy and lets go of its handle when the app drops, and a dead
  probe falls back to the in-line check. The in-line case is already
  covered by tests_clipboard.
- ROADMAP (Last updated, Platforms, Shipped so far) and
  docs/development.md (Linux: clipboard owners that never answer).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 22:36:44 +07:00
Oscar Sebastián Mellado Bustos 5db200d392 Linux: check the system clipboard for Paste off the UI thread
`has()` on an X11 clipboard owner that never answers can block for
seconds; the app called it every 0.25 s on the UI thread to decide
whether Paste is enabled, so a stuck owner froze the frame loop (the
window stopped drawing and could not be closed).

`clipboard_probe` owns a second clipboard handle on a worker thread,
publishes its verdict over a channel and wakes the UI only when it
changes; the frame reads the latest verdict without ever blocking.
Without a factory the check stays in line, throttled, exactly as before
(the web shows SVG text only; hosts that don't install one keep the old
path).

The factory is installed on Linux only for now (the environment the bug
reproduces in); other platforms keep the in-line check, so this cannot
change their behaviour.

Tests: a fake clipboard whose `has()` blocks on a gate, a probe factory
sharing a recorder, and a headless frame whose elapsed time is measured.
They assert the frame does not wait on the clipboard and that the check
runs on the probe thread, that the probe's verdict reaches `system_paste`
and the Paste menu, that dropping the app stops the probe, and that the
in-line check (no factory: the web, older hosts) still works.
2026-10-08 22:34:29 +07:00
BFlat c0396c0761 Merge pull request #524 from storytold/fix/issue-504
Fix #504: Convert corner/smooth for a path selected as a whole with the anchor tools
2026-10-08 22:32:32 +07:00
BFlat c7f1e00955 Merge pull request #521 from storytold/fix/issue-501
Fix #501: a Pen drag out of the first anchor always closes the path
2026-10-08 22:31:56 +07:00
BFlat 3c91ca8a1d Merge pull request #517 from storytold/fix/issue-494
Fix #494: Pen + Cmd edits the path being drawn; Pen + Alt reshapes segments; handle drags fixed and fast
2026-10-08 22:31:38 +07:00
BFlat 7e3bcc48fe Merge pull request #519 from storytold/fix/issue-502
Fix #502: no startup crash on dual-GPU Linux desktops under Wayland
2026-10-08 22:31:07 +07:00
imachusandClaude Opus 5.5 fba610284c Type (#432): new type in a Japanese interface starts top-to-top with em box centre alignment
As decided in #432 (option 2): while the interface is in Japanese, new type starts with em box
top-to-top leading and em box centre character alignment; other languages keep the Roman
baseline, so Latin area type doesn't move.

- The UI tells the engine the language it is drawn in each frame (`Session::ui_language`); without
  a UI, an explicit `interfaceLanguage` preference counts (`Session::japanese_interface`).
- `text.create` and `text.createInPath` (the Type tools' clicks and drags) apply it, and take
  `leadingModel` / `charAlign` to choose; the values used are journaled, so a replay does the same
  in any language.
- `paraStyle.new` / `charStyle.new` made from nothing (no `attrs`, no text selected) carry them.
- Imported text (PDF, SVG, DXF…) keeps the Roman baseline. Saved documents keep what they say.
- docs/mcp.md (New type in a Japanese interface) and the ROADMAP note it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 00:08:03 +09:00
bflatasticandClaude Opus 5.5 ac63002df9 Fix #504: Convert corner/smooth for a path selected as a whole with the anchor tools
Reported: Alt-click with the Pen should toggle an anchor between corner and smooth, and the
Control bar had no way to make a corner anchor smooth.

v0.5.0 already has Pen + Alt as the Anchor Point tool (#473) and the Control bar's and the
Properties panel's Convert buttons for direct-selected anchors, the path being drawn included (its
last anchor is selected). The remaining gap: with Direct Selection, the Pen, the Curvature or the
anchor tools, a path selected as a whole shows all its anchors selected, yet the Convert buttons
only appeared once anchors were direct-selected.

- chrome::anchor_controls decides what the Control bar and the Properties panel show: Convert and
  Anchors for direct-selected anchors (as before), Convert alone for paths selected as a whole
  with a tool that edits anchors (path.convertAnchors already converts every anchor of those);
  Remove and Cut still wait for anchors direct-selected, as they act on those only.
- Tests: the Control bar and the Properties panel offer Convert for a whole rectangle with Direct
  Selection and the Pen, not with the Selection tool, and smooth converts every corner; Pen + Alt
  on the path being drawn makes a smooth anchor a corner (click) and a corner smooth (drag), and
  drawing goes on. ROADMAP.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 22:03:17 +07:00
bflatasticandClaude Opus 5.5 f6cd4588ee Fix #501: a Pen drag out of the first anchor always closes the path
Reported: closing a shape by pressing on the first anchor and dragging out a curve flickered, and
releasing at the wrong moment left the shape open.

The press decided to close (path.close preview), but every move asked again which path was being
drawn: the closing preview leaves the path closed, so no longer one the Pen extends, and the move
fell through to "first anchor of a new path" (a path.create preview), the next move back to a
close of a path that no longer existed in the preview... The release committed whichever was last.

- The press now records what it placed (Place: the anchor, the path it goes on, none for a new
  path, and whether it closes it), and the drag only shapes that anchor's handles: a close stays a
  close, symmetric by default and Alt breaking the handles, and the release closes the path wherever
  it ends. The first anchor of a new path no longer depends on the selection either.
- Tests: tools (the drag sees the closed path), engine (closed throughout a 12-move drag, symmetric
  handles at the release), MCP headless pointer_gesture. ROADMAP.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 22:00:24 +07:00
bflatasticandClaude Opus 5.5 aefd961bbd Fix #494: Pen + Cmd edits the path being drawn; Pen + Alt reshapes segments; handle drags fixed and fast
Reported: with the Pen there was no way to edit curves in place as Ctrl does in Illustrator on
Windows (Cmd on the Mac), segments couldn't be grabbed, and the curve-editing tools felt slow and
sometimes didn't take a handle.

- Cmd/Ctrl held at a press with any tool but a selection tool now borrows the selection tool in the
  engine (Session::pointer), not in the canvas: the selection tool chosen last, or Direct Selection
  for the Pen, Curvature and anchor tools until one is chosen. The tool lent to isn't deactivated,
  so the Pen goes on drawing its path after the release while that path stays selected; it no
  longer draws on another open path selected meanwhile. Agents reach it with pointer_gesture
  mods.cmd. With Cmd held the pointer is the borrowed tool's. Choosing a tool or switching
  documents mid-gesture gives the tool back first.
- Pen + Alt over a segment of a selected path reshapes it, as the Anchor Point tool does.
- The handles shown are the handles that drag (one helper for Direct Selection, the Anchor Point
  tool and Pen + Alt): Direct Selection now drags the handles of a path selected as a whole (as
  the Pen leaves it, so Cmd + drag of a handle while drawing works), the Anchor Point tool no
  longer grabs handles that Show handles when multiple anchors are selected hides, the nearest
  handle wins, and a handle shorter than the tolerance leaves its anchor to be picked. The anchor
  tools pick within Selection & Anchor Display > Tolerance instead of a fixed 4 px.
- path.reshapeSegment keeps a smooth anchor at either end smooth (its other handle turns with the
  moved one) instead of kinking it.
- A dragged handle gathered its smart guide targets from the whole document on every pointer move
  (21 ms per move on 20,000 paths): HandleSnap now gathers them once per drag (1 ms).
  vectorcraft-cli perf measures handle and segment drags on a 5,000-anchor path.
- catalog::is_selection_tool and catalog::edits_anchors replace the UI's own lists.
- Tests in tools, engine and MCP (headless pointer_gesture); docs/mcp.md, control-protocol.md,
  ROADMAP.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 22:00:13 +07:00
bflatasticandClaude Opus 5.5 d12d5195da Fix #502: no startup crash on dual-GPU Linux desktops under Wayland
0.5.0 asked wgpu for the low-power adapter everywhere (#306). On a Linux
desktop whose KDE Wayland compositor runs on an NVIDIA GPU, wgpu sorted the
Ryzen's integrated RADV GPU first: it reports that it can present to the
window, but KWin can't import the buffers it allocates ("importing the
supplied dmabufs failed"), which is a fatal Wayland protocol error. The next
surface configuration then got ERROR_SURFACE_LOST_KHR and egui-wgpu panicked
("The surface isn't supported by this adapter", winit.rs:129).

- Preferences > Performance > Graphics Processor gains Automatic, the new
  default: power saving on Windows and macOS as #306 wanted, and on Linux the
  system's order, where Mesa's device-select layer puts the GPU the desktop
  runs on first. Values are now automatic / lowPower / highPerformance; 0.5.0
  saved powerSaving for everyone, which reads as automatic.
- The app picks the window's adapter itself (apps/vectorcraft/src/gpu.rs,
  eframe's native_adapter_selector): only adapters that present to the
  surface, WGPU_ADAPTER_NAME first, hardware before software, native backends
  before OpenGL, then the power preference. Every adapter and the pick are
  logged.
- run_native runs under the engine guard. When the graphics fail during the
  first frames (a wgpu error, or a panic in wgpu, egui-wgpu or naga), the app
  starts again without that adapter (exec on Unix, so an AppImage stays
  mounted; a new process on Windows), passing the failed adapters in
  VECTORCRAFT_GPU_SKIP, and says so in the status bar. When none is left it
  logs why and exits with an error, never a panic.
- docs/development.md, README and ROADMAP: the new default, the restart and
  the escape hatches (WGPU_POWER_PREF, WGPU_ADAPTER_NAME, WGPU_BACKEND,
  MESA_VK_DEVICE_SELECT, DRI_PRIME).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 21:59:55 +07:00
FryandClaude Opus 4.8 e6a3b37bed UI: right-click a ruler to swap the document units
A right-click on either ruler (or the origin box) now opens a context
menu listing the ten document units, the current one checked. Choosing
one runs document.setUnits — the same one-undo-step change as
Preferences ▸ Units ▸ General / Document Setup.

The guide-drag interact on each ruler becomes click-and-drag so the same
widget both drags out guides (left) and opens the unit menu (right); the
origin box gets its own click interact. checked() reports the active unit
so the menu shows the check-mark; the unit labels are already translated
as the Units preference choices.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-10-08 10:57:01 -04:00
imachusandClaude Opus 5.5 b7644d31f2 Fix #433: open only file URLs handed to the app (macOS 27 turns an https URL into a path)
`application:openURLs:` can pass URLs that aren't files, and on macOS 27 `to_file_path()` returns
the path of an https URL ("/a.svg"), so it was queued as a document. Keep the file URLs
(`isFileURL`) before converting; `opened_files_wait_for_the_ui` passes again on macOS 27.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 23:54:22 +09:00
BFlat 99a5318fe4 Merge pull request #520 from storytold/pr/clean-room-rules
Clean-room: never run, automate or observe Adobe software
2026-10-08 21:42:18 +07:00
bflatasticandClaude Opus 5.5 87cf1ff3e6 Clean-room: never run, automate or observe Adobe software; behaviour from public docs only
Adobe's Terms of Use forbid reverse engineering, including observing a program's inputs and
outputs to recreate it. The agent rules allowed black-box observation of the running app; they
now forbid running, automating, screenshotting or measuring any Adobe application, reading an
Adobe install, and copying Adobe-authored code or text (procsets, prologs, sample files) into
the repo, tests included. Behaviour comes from public documentation and published specs only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 21:39:16 +07:00
BFlat 0e59e0a38d Merge pull request #513 from storytold/fix/issue-495
Fix #495: panels, panel groups and the Tools panel undock into floating panels
2026-10-08 21:37:23 +07:00
bflatasticandClaude Opus 5.5 ea1993c848 Fix #495: panels, panel groups and the Tools panel undock into floating panels
Nothing could be undocked: the dock's tabs only switched panels, the icon
column only popped its panels out next to it, and only tool flyouts
(#437) could float.

- A dock tab, a panel icon or a popped-out panel's title dragged out of
  the dock floats that panel inside the app window; the strip right of
  the dock's tabs floats the whole Properties | Layers | Libraries group.
- A floating group moves by its title bar (or the strip right of its
  tabs); a tab dragged out of it floats on its own; dropped on another
  group's title bar or tabs it stacks with that group; dropped on the
  dock, which lights up under the pointer, its panels go back where they
  live in the dock (tabbed group or icon column). Its x does the same.
- The Tools panel floats by its title bar or grip and docks again on the
  window's left edge, which lights up the same way.
- window.panel.float {panel, x?, y?, onto?, group?} and window.panel.dock
  {panel, group?} (panel "tools" for the Tools panel) for the control
  channel and MCP; every panel menu ends with Float Panel / Dock Panel;
  window.panel on a floating panel shows its tab.
- Floating groups and the Tools panel's position are kept with the
  preferences and in user workspaces (built-ins dock everything),
  sanitized on load, and clamped into a smaller window when drawn.
- One move state in egui temp memory drives every drag, so a tab torn off
  keeps following the pointer; per frame the work is a lookup per panel.
- Icon buttons can be drawn for a caller's response (paint_icon_button),
  so the column's icons keep their ids when one above them floats.
- Translations (ja, es, zh-hans, zh-hant; cs and pt-br for the commands),
  es @msg rows, docs/control-protocol.md and ROADMAP.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 21:14:31 +07:00
Brandon ThomasandClaude Opus 5.5 f12188ad15 Bump version to 0.6.0 (from 0.5.0) for release
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 10:01:57 -04:00
90bc58ef24 README Downloads: where to get it first, then builds with Windows before macOS (#512)
Co-authored-by: Brandon Thomas <shared2@storyteller.ai>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 10:01:10 -04:00
73bf92b5a9 Release: Flatpak bundles, AppImage zsync updates, README Downloads (#500)
* Release: Flatpak x86_64/aarch64 bundles, AppImage zsync updates, README Downloads

- New `flatpak` matrix job (ubuntu-24.04 and ubuntu-24.04-arm) repackages each Linux tarball
  into vectorcraft-<ver>-linux-<arch>.flatpak via packaging/linux/flatpak-bundle.sh and the
  new ai.storyteller.vectorcraft.bundle.yml; packaging-lint keeps its runtime and finish-args
  identical to the from-source Flathub manifest.
- AppImages embed gh-releases-zsync update information and ship a .zsync beside them; the
  Linux job checks both.
- Jobs that sign nothing (version, linux, flatpak, freebsd, web) leave the `release`
  environment, so a branch workflow_dispatch is a dry run; the draft-release job still needs
  the signed macOS/Windows jobs.
- README: a Downloads section listing every build; docs/releasing.md updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Release: read AppImage update info without extract-and-run

With APPIMAGE_EXTRACT_AND_RUN=1 the runtime forwards --appimage-updateinformation to the app,
which then tries to open a window and fails on the headless runner.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Brandon Thomas <shared2@storyteller.ai>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 10:00:34 -04:00
BFlat de4f836f4d Merge pull request #493 from XusBadia/dmg-background
macOS DMG: branded window background and icon layout
2026-10-08 20:37:13 +07:00
bflatasticandClaude Opus 5.5 d0a99faf1e macOS DMG: generate DS_Store and TIFF from a script, attribute the assets (review of #493)
- packaging/macos/dmg/generate.py writes background.tiff and DS_Store on any OS (resvg with
  the repo's fonts; ds_store and mac_alias, as dmgbuild uses). Both are byte-reproducible and
  carry nothing from the machine that made them.
- DS_Store: same window, icon size, positions and background alias as before, without the
  bookmark (pBBk/pBB0) and the alias's disk-image record, which held the author's boot volume
  UUID and name, its creation date and temporary paths.
- background.tiff: the same pixels as before (checked), now opaque RGB with Deflate (1.8 MB to
  1.0 MB) and LittleCMS's built-in sRGB profile instead of an HP profile with no open licence;
  no file names or software tags.
- background.svg: drop an unused pattern and the xlink namespace (renders the same).
- ASSETS.md rows for the three files; README, docs/releasing.md (volume name) and ROADMAP.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 20:36:43 +07:00
Xus BadiaandClaude Opus 5.5 884df22408 macOS DMG: branded window background and icon layout
The DMG opened as a plain Finder window. It now shows the app icon's figure on
the VectorCraft colour, with VectorCraft.app and the Applications link side by side.

- packaging/macos/dmg/: background (SVG source, 1x + 2x HiDPI TIFF) and the
  Finder view settings (DS_Store: window, icon size 128, positions, background).
- package.sh copies them into the staging folder. The image is still built with
  hdiutil makehybrid: no mounted device and no Finder scripting on CI.
- The volume name drops the version: .DS_Store finds the background through an
  alias that includes the volume name. The DMG file name keeps the version.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 20:36:40 +07:00
BFlat d3625f0b70 Merge pull request #499 from storytold/feat/task-bar-drag
Contextual Task Bar: drag it by its handle, pin and reset its position
2026-10-08 20:35:17 +07:00
BFlat 5abffd7622 Merge pull request #488 from wstock/feat/issue-394-auto-collapse
Part of #394: Auto-Collapse Iconic Panels
2026-10-08 20:34:23 +07:00
BFlat b5ffeeab57 Merge pull request #486 from wstock/feat/issue-394-bare-numbers-points
Part of #394: Numbers Without Units Are Points
2026-10-08 20:33:53 +07:00
BFlat 94d888a010 Merge pull request #484 from wstock/feat/issue-394-home-screen
Part of #394: Show The Home Screen When No Documents Are Open
2026-10-08 20:33:25 +07:00
BFlat 6641ffd225 Merge pull request #497 from storytold/fix/issue-485
Fix #485: the mouse wheel steps the focused numeric field
2026-10-08 20:33:03 +07:00
BFlat 810085ae56 Merge pull request #492 from storytold/fix/issue-483
Fix #483: Shift-drag marquees toggle the selection; the Lasso's Alt keeps the rest
2026-10-08 20:32:40 +07:00
BFlat bd9c32d384 Merge pull request #490 from storytold/fix/issue-482
Fix #482: Smart Guides land resize handles on anchors and snap the transform tools' drags
2026-10-08 20:32:22 +07:00
bflatasticandClaude Opus 5.5 d11daabdc7 Contextual Task Bar: drag it by its handle, pin and reset its position
The grip at the bar's left end now drags the bar anywhere on the canvas
(grab cursor), which always holds it whole, also when the window shrinks.
Unpinned, the bar keeps that offset as it follows the selection (in the
document it was moved in); the "…" button opens a More Options menu with
Hide Bar, Pin Bar Position (checked while pinned: the bar stays where it
is across selection changes and the handle still moves it; unpinned it
follows the selection again from there), Reset Bar Position (unpinned,
back under the selection) and Show Properties Panel, as in Illustrator.
As there, the position and the pin last for the session only.

- UI commands window.taskBar.pin {pinned?} and window.taskBar.reset, so
  the control channel and MCP reach them; ui.inspect reports taskBar
  {pinned, rect}.
- One opt_bool helper reads the {key?: bool} params of the toggling window
  commands (toolbarColumns, floatTools, collapseDock, taskBar.pin).
- New strings in ja, es, zh-hans, zh-hant, pt-br and cs; the dropped
  "Hide Contextual Task Bar" tooltip and per-key es messages removed.
- Headless egui test: dragging the grip moves the bar, the offset follows
  the selection, pin holds it across selection changes and a shrinking
  window, unpin follows from there, reset restores.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 20:23:15 +07:00
bflatasticandClaude Opus 5.5 d728c47e6f Auto-Collapse Iconic Panels: dialogs keep the panel, the dock doesn't (review of #488)
- A press inside a dialog the popped-out panel opened (Swatch Options from its
  menu, say), or on a modal dialog's backdrop, put the panel away under the
  dialog. The press now counts as away only when it lands on no foreground
  layer (the flyout itself, dialogs, palettes) and not on the modal backdrop
  (`dialogs::modal::backdrop`), as the popovers decide a click elsewhere.
- A press in the expanded dock's panel group left the flyout open: only the
  icon column is spared now (its icons swap or close the flyout themselves),
  so a click in another docked panel puts it away, as a click anywhere else in
  the workspace does in the reference app.
- The test covers a click in a dialog, on its backdrop and in the docked group.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 20:22:15 +07:00
wstockandClaude Fable 5.1 948f696f52 Part of #394: Auto-Collapse Iconic Panels
Preferences › User Interface › Auto-Collapse Iconic Panels was stored
and never read: a panel popped out of the icon column stayed until its
» or its icon. On, a press away from the flyout now puts it away. A
press on the icon column is left to the icons (they swap or close the
flyout on release, so acting on the press would reopen the one being
closed), and a press in a popup the flyout opened (a panel menu, a
dropdown) keeps it. Off by default, as in Illustrator.

Developed with AI assistance (Claude Code); reviewed and tested locally.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-08 20:22:14 +07:00
bflatasticandClaude Opus 5.5 077e4f34ec Numbers Without Units Are Points: picas fields, on by default (review of #486)
The option tells points from picas, where a bare `12` could be either: the
reference app dims it unless a unit is Picas, and it starts on. A number typed
with no unit into a field in picas is now read in points with it on (the
default again, as before #486), and in picas with it off; fields in any other
unit read it in their unit either way, as there. The Preferences dialog dims
the checkbox unless one of the Units is Picas.

The fields learn the preference when it changes, through
`prefs_dialog::apply_runtime` as Scrub Numeric Fields does, rather than from a
write into the egui context every frame. Tests for picas and other fields, the
wiring and the dimming; docs/mcp.md and ROADMAP say so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 20:22:11 +07:00
wstockandClaude Fable 5.1 b1aac0cc1b Part of #394: Numbers Without Units Are Points
Preferences › Units › Numbers Without Units Are Points was stored and
never read. On, a number typed with no unit into any length field
(`num_field`, `opt_field`, and so the spin fields built on them) is read
in points whatever the field's unit; a typed unit (`12 mm`, `1in`)
still wins, and the field keeps showing its value in its own unit. The
app sets the frame's rule from the preference in `logic`, the fields
read it through the egui context (`widgets::typed_unit`), so none of
the 45 callers change.

The default flips from true to false, which is Illustrator's default
and the behaviour the fields had while the option was unread.

Developed with AI assistance (Claude Code); reviewed and tested locally.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-08 20:22:10 +07:00
wstockandClaude Fable 5.1 f1935596ef Part of #394: Show The Home Screen When No Documents Are Open
Preferences › General › Show The Home Screen When No Documents Are Open
was stored and never read: the Home screen always replaced the canvas
while no document was open. Off, the window is now empty while no
document is open (as when Illustrator's option is off), and the Home
button (`app.home`) still shows the screen; closing the last document
returns to the empty window. `menus::home_showing` is the one place
that decides, for the canvas and the Home button's lit state.

Developed with AI assistance (Claude Code); reviewed and tested locally.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-08 20:21:42 +07:00
192 changed files with 16988 additions and 2177 deletions

No files matched your search

+10 -1
View File
@@ -54,4 +54,13 @@ jobs:
desktop-file-validate packaging/linux/ai.storyteller.vectorcraft.desktop
sed -e 's/@VERSION@/0.0.0/' -e 's/@DATE@/2026-01-01/' packaging/linux/ai.storyteller.vectorcraft.metainfo.xml.in >"$RUNNER_TEMP/ai.storyteller.vectorcraft.metainfo.xml"
appstreamcli validate --no-net --explain "$RUNNER_TEMP/ai.storyteller.vectorcraft.metainfo.xml"
python3 -c "import yaml; m = yaml.safe_load(open('packaging/linux/flatpak/ai.storyteller.vectorcraft.yml')); assert m['id'] == 'ai.storyteller.vectorcraft' and m['command'] == 'vectorcraft'"
python3 - <<'EOF'
import yaml
src = yaml.safe_load(open("packaging/linux/flatpak/ai.storyteller.vectorcraft.yml"))
bundle = yaml.safe_load(open("packaging/linux/flatpak/ai.storyteller.vectorcraft.bundle.yml"))
for m in (src, bundle):
assert m["id"] == "ai.storyteller.vectorcraft" and m["command"] == "vectorcraft", m["id"]
for key in ("runtime", "runtime-version", "sdk", "finish-args"):
assert src[key] == bundle[key], f"Flatpak manifests disagree on {key}: {src[key]} vs {bundle[key]}"
print("Flatpak manifests ok")
EOF
+62 -10
View File
@@ -1,9 +1,11 @@
# Release pipeline: every push to `release` builds signed installers for every platform and
# creates or updates the draft GitHub Release "VectorCraft v<version>". See docs/releasing.md.
#
# All jobs run in the `release` environment (restricted to the `release` branch), which holds
# the signing secrets. Every secret is optional: missing ones produce unsigned artifacts and a
# warning, never a failed build.
# Jobs that sign (macOS, Windows) and the job that creates the release run in the `release`
# environment (restricted to the `release` branch), which holds the signing secrets. Every secret
# is optional: missing ones produce unsigned artifacts and a warning, never a failed build. The
# other jobs sign nothing and get no environment, so a `workflow_dispatch` on any branch is a dry
# run: they build and upload artifacts, the signed jobs are refused, and no release is drafted.
name: Release
on:
@@ -35,7 +37,7 @@ jobs:
version:
name: version
runs-on: ubuntu-latest
environment: release
# No `environment: release`: no secrets here.
outputs:
version: ${{ steps.v.outputs.version }}
date: ${{ steps.v.outputs.date }}
@@ -175,7 +177,7 @@ jobs:
# The oldest GitHub-hosted image, so the binaries only need glibc >= 2.35 (Ubuntu 22.04+,
# Debian 12+, Fedora 36+, RHEL 10). See docs/releasing.md.
runs-on: ${{ matrix.runner }}
environment: release
# No `environment: release`: Linux packages are not signed (checksums in SHA256SUMS.txt).
strategy:
fail-fast: false
matrix:
@@ -200,7 +202,7 @@ jobs:
sudo apt-get update
sudo apt-get install -y --no-install-recommends \
libxkbcommon-dev libwayland-dev libx11-dev libxrandr-dev libxi-dev libgl1-mesa-dev \
desktop-file-utils appstream python3-yaml
desktop-file-utils appstream python3-yaml zsync
curl -fsSL -o "$RUNNER_TEMP/nfpm.deb" \
"https://github.com/goreleaser/nfpm/releases/download/v${NFPM_VERSION}/nfpm_${NFPM_VERSION}_${{ matrix.deb }}.deb"
sudo dpkg -i "$RUNNER_TEMP/nfpm.deb"
@@ -225,6 +227,12 @@ jobs:
for appimage in dist/release/*.AppImage; do
chmod +x "$appimage"
APPIMAGE_EXTRACT_AND_RUN=1 "$appimage" --version
# Update information is embedded, and the .zsync for delta updates sits beside it.
# No APPIMAGE_EXTRACT_AND_RUN here: with it the runtime passes --appimage-* flags on
# to the app instead of answering them itself.
"$appimage" --appimage-updateinformation \
| grep -F "gh-releases-zsync|${GITHUB_REPOSITORY%%/*}|${GITHUB_REPOSITORY#*/}|latest|vectorcraft-*-linux-${{ matrix.arch }}.AppImage.zsync"
test -s "$appimage.zsync"
done
- uses: actions/upload-artifact@v4
with:
@@ -232,13 +240,52 @@ jobs:
path: dist/release/*
if-no-files-found: error
flatpak:
name: Flatpak ${{ matrix.arch }}
needs: [version, linux]
# Repackages the Linux job's tarball (the same binaries as the AppImage/deb/rpm); no Rust
# build here. 24.04 for a newer flatpak-builder (1.4) than 22.04 ships.
runs-on: ${{ matrix.runner }}
# No `environment: release`: this job signs nothing, so it gets no release secrets.
strategy:
fail-fast: false
matrix:
include:
- { arch: x86_64, runner: ubuntu-24.04 }
- { arch: aarch64, runner: ubuntu-24.04-arm }
env:
VECTORCRAFT_VERSION: ${{ needs.version.outputs.version }}
VECTORCRAFT_BUILD_DATE: ${{ needs.version.outputs.date }}
steps:
- uses: actions/checkout@v4
- uses: actions/download-artifact@v4
with:
name: release-linux-${{ matrix.arch }}
path: dist/linux
- name: Install flatpak-builder
run: |
sudo apt-get update
# librsvg2-common: the SVG pixbuf loader. flatpak-builder runs the host's
# `appstreamcli compose`, which renders the scalable icon and fails without it.
sudo apt-get install -y --no-install-recommends flatpak flatpak-builder librsvg2-common
# Ubuntu 24.04's AppArmor blocks the unprivileged user namespaces bubblewrap needs.
sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0
- name: Build the Flatpak bundle
run: packaging/linux/flatpak-bundle.sh "dist/linux/vectorcraft-$VECTORCRAFT_VERSION-linux-${{ matrix.arch }}.tar.gz"
- uses: actions/upload-artifact@v4
with:
name: release-flatpak-${{ matrix.arch }}
path: dist/release/*.flatpak
if-no-files-found: error
freebsd:
name: FreeBSD x86_64
needs: version
# GitHub has no FreeBSD runners: build in a FreeBSD 14.3 VM (same image as freebsd.yml).
# GitHub has no FreeBSD runners: build in a FreeBSD 14.3 VM (same image and packages as
# freebsd.yml).
runs-on: ubuntu-latest
timeout-minutes: 150
environment: release
# No `environment: release`: this job signs nothing, so it gets no release secrets.
env:
VECTORCRAFT_VERSION: ${{ needs.version.outputs.version }}
VECTORCRAFT_BUILD_DATE: ${{ needs.version.outputs.date }}
@@ -262,6 +309,7 @@ jobs:
with:
release: "14.3"
usesh: true
cpu: 4
mem: 12288
# Passed through by name; never templated into the script.
envs: "VECTORCRAFT_VERSION VECTORCRAFT_BUILD_DATE VECTORCRAFT_BUILD_SHA"
@@ -276,6 +324,8 @@ jobs:
export CRAFT_FONTS_DIR="$PWD/craft-fonts" CRAFT_FONTS_REQUIRED=1
export CARGO_TARGET_DIR=/var/tmp/vectorcraft-target CARGO_BUILD_JOBS=4
bash packaging/freebsd/package.sh
tar -tzf dist/release/vectorcraft-*-freebsd-x86_64.tar.gz \
| grep -E '/bin/vectorcraft$|/bin/vectorcraft-cli$|/share/applications/ai\.storyteller\.vectorcraft\.desktop$'
- uses: actions/upload-artifact@v4
with:
name: release-freebsd
@@ -286,7 +336,7 @@ jobs:
name: Web (wasm)
needs: version
runs-on: ubuntu-latest
environment: release
# No `environment: release`: no secrets here.
env:
VECTORCRAFT_VERSION: ${{ needs.version.outputs.version }}
VECTORCRAFT_BUILD_DATE: ${{ needs.version.outputs.date }}
@@ -327,7 +377,9 @@ jobs:
release:
name: Draft GitHub Release
needs: [version, macos, windows, linux, freebsd, web]
# Needs the signed jobs, so a branch dry run (where the environment refuses them) never
# drafts a release.
needs: [version, macos, windows, linux, flatpak, freebsd, web]
runs-on: ubuntu-latest
environment: release
permissions:
+10 -4
View File
@@ -6,13 +6,19 @@ Formerly **DrawCraft** (renamed 2026-10-01): old `.drawcraft` files and `"format
## Start every session here
1. Read the [honest assessment in `ROADMAP.md`](ROADMAP.md#honest-assessment-2026-10-05): where we stand by dimension, **where we're lacking** (the prioritized gap list) and **where we're going**. Unless the user gives you a task, pick work from that list.
2. Read `plan/STATUS.md` (local session notes, may lag the ROADMAP), then the task in `plan/execution-plan.md` §3 and the relevant `plan/architecture.md` section. Behaviour reference: `plan/illustrator/*.md`.
2. Read `plan/STATUS.md` (local session notes, may lag the ROADMAP), then the task in `plan/execution-plan.md` §3 and the relevant `plan/architecture.md` section. Behaviour reference: public documentation only (see Clean-room below); `plan/illustrator/*.md` holds notes from it.
3. Follow the autonomous operation protocol (`plan/execution-plan.md` §7): orient → plan → implement + test → verify → record → commit. Don't stop to ask unless §7 lists the decision as the user's.
`plan/` is gitignored (local only).
## Non-negotiables
- **Clean-room.** Never read, disassemble or copy anything inside the Illustrator bundle (names/listings only). Never copy Adobe icons, artwork, presets or wording beyond feature names. Behaviour comes from public docs and black-box observation of the running app with synthetic documents only (screenshots by window id, stored under `plan/illustrator/screenshots/`, never committed). Never copy GPL/AGPL code (Inkscape, lib2geom…).
- **Clean-room: never use Adobe software (absolute rule, from the project owner).** Adobe's Terms of Use forbid reverse engineering, including observing a program's inputs and outputs to recreate it. So:
- Never launch, run, script, automate (COM, AppleScript, ExtendScript, UI automation), screenshot or measure Illustrator or any other Adobe application, and never compare our output against one. Don't make test files with them, not even "synthetic" ones.
- Never read, disassemble or copy anything inside an Adobe install (binaries, plug-ins, presets, procsets, resources, help files, fonts, ICC profiles).
- Never copy Adobe-authored code or text into this repo, tests included: no PostScript procsets or prologs (AGM, CoolType, the Illustrator prologs), no sample files. Write test inputs from scratch from the public specifications (PostScript Language Reference, PDF / ISO 32000, TIFF, EPSF/DCS).
- Behaviour comes only from public documentation (helpx, published specs, public forum posts), cited by URL, and from files users send us that they own (used locally, never committed). Never copy Adobe icons, artwork, presets or wording beyond feature names.
- If a task seems to need any of this, stop and say so instead. `cargo xtask cleanroom` (run by `cargo xtask ci`) fails on Adobe copyright notices and on fixtures made with Adobe applications.
- Never copy GPL/AGPL code (Inkscape, lib2geom…).
- **Assets: no Adobe iconography or images — ever (absolute rule, from the project owner).**
- Never add, copy, trace, redraw-from, embed or ship any icon, image, artwork, cursor, preset, swatch/brush/symbol/pattern/style library, ICC profile or screenshot from Adobe products or from any other source whose licence doesn't allow it.
- Every image, icon, font or other asset must be one of:
@@ -44,7 +50,7 @@ Formerly **DrawCraft** (renamed 2026-10-01): old `.drawcraft` files and `"format
## Running and looking at the app
- `cargo run --release -p vectorcraft -- --control 7979 [file.svg|file.vectorcraft]` (sibling apps' agents use the same default port: if the log says it failed to bind, pick another port — otherwise your requests reach a different app).
- Drive it: JSON lines on `127.0.0.1:7979`, e.g. `{"id":1,"method":"engine.execute","params":{"command":"shape.rectangle","params":{"x":10,"y":10,"width":100,"height":50}}}` then `{"id":2,"method":"ui.screenshot","params":{"path":"/tmp/shot.png"}}`. Methods: `crates/ui-egui/src/control.rs`.
- **For UI work, look at the result** (take `ui.screenshot`, read the PNG) and compare with `plan/illustrator/02-ui-ux.md` / `10-observed-ui.md`. `ui.screenshot` needs a presented frame: if it errors (screen locked), check the art with `ui.render` / `vectorcraft-cli run … --export x.png`, and cover panels with a headless egui frame test (see `panels/transparency.rs` tests).
- **For UI work, look at the result** (take `ui.screenshot`, read the PNG) and compare with the public documentation (`plan/illustrator/02-ui-ux.md` notes). `ui.screenshot` needs a presented frame: if it errors (screen locked), check the art with `ui.render` / `vectorcraft-cli run … --export x.png`, and cover panels with a headless egui frame test (see `panels/transparency.rs` tests).
- **Performance:** `vectorcraft-cli perf` checks the budgets (render/pan/zoom, hit test, save/open, SVG, Pathfinder) on a synthetic 50k-path document; `vectorcraft-cli bench FILE` times one file. Run them before and after renderer, format or geometry changes, on an idle machine (the report warns when the load average makes timings noise).
- MCP: `vectorcraft-cli mcp` (see `docs/mcp.md`).
- Shell gotcha: `mv`/`cp` are aliased interactive here — use `/bin/mv -f` / `/bin/cp -f`.
@@ -53,7 +59,7 @@ Formerly **DrawCraft** (renamed 2026-10-01): old `.drawcraft` files and `"format
## Roadmap
`ROADMAP.md` (committed) is the shared picture of where VectorCraft stands. It holds status, the honest assessment (by dimension, the gap list, the direction), milestones, the parity table and time-to-parity estimates.
- When a task lands, update it in the same PR: the milestone row, the parity-table row (score, missing items, hours), "Shipped so far", and the gap list if the gap closed or shrank.
- Grade by behaviour against `plan/illustrator/`, not by whether a menu item exists. Scores are self-assessed, so err low.
- Grade by behaviour against the public documentation (`plan/illustrator/` notes), not by whether a menu item exists. Scores are self-assessed, so err low.
- Keep the README's Status section in step with the ROADMAP headline.
## Contributor credits (About window)
+3
View File
@@ -37,6 +37,9 @@ Generated-in-code art is original and has no file to list. This covers the defau
| `assets/app-icon/vectorcraft.icns` | Project owner (ArtCraft team) | Original artwork drawn in ArtCraft for VectorCraft, vectorised and rendered by `packaging/icons.sh` | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | App icon (engraved dragon) |
| `assets/app-icon/vectorcraft.ico` | Project owner (ArtCraft team) | Original artwork drawn in ArtCraft for VectorCraft, vectorised and rendered by `packaging/icons.sh` | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | App icon (engraved dragon) |
| `assets/app-icon/vectorcraft.svg` | Project owner (ArtCraft team) | Original artwork drawn in ArtCraft for VectorCraft, vectorised and rendered by `packaging/icons.sh` | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | App icon (engraved dragon) |
| `packaging/macos/dmg/background.svg` | Xus Badia (contributed in #493) | Original artwork for VectorCraft's DMG window; links the app icon `assets/app-icon/vectorcraft-small.svg` | MIT OR Apache-2.0 (licensed by the contributor under the project licence) | DMG background source. Text in Inter and JetBrains Mono (OFL-1.1, `assets/fonts`), not embedded; paper grain generated by an SVG `feTurbulence` filter |
| `packaging/macos/dmg/background.tiff` | Xus Badia (contributed in #493) | Rendered from `packaging/macos/dmg/background.svg` by `packaging/macos/dmg/generate.py` | MIT OR Apache-2.0 | 1x + 2x DMG background; includes the app icon (see its rows), text rendered from OFL-1.1 fonts and LittleCMS's built-in sRGB profile ("No copyright, use freely") |
| `packaging/macos/dmg/DS_Store` | Xus Badia (layout, #493) | Written by `packaging/macos/dmg/generate.py` | MIT OR Apache-2.0 | Finder view settings for the DMG (window, icon size and positions, background alias); no machine data |
| `assets/fonts/Inter-Medium.ttf` | Rasmus Andersson / The Inter Project Authors | https://github.com/rsms/inter | OFL-1.1 (`assets/fonts/OFL-Inter.txt`) | Open-source typeface, not product iconography or artwork |
| `assets/fonts/Inter-Regular.ttf` | Rasmus Andersson / The Inter Project Authors | https://github.com/rsms/inter | OFL-1.1 (`assets/fonts/OFL-Inter.txt`) | Open-source typeface, not product iconography or artwork |
| `assets/fonts/Inter-SemiBold.ttf` | Rasmus Andersson / The Inter Project Authors | https://github.com/rsms/inter | OFL-1.1 (`assets/fonts/OFL-Inter.txt`) | Open-source typeface, not product iconography or artwork |
+10 -4
View File
@@ -6,13 +6,19 @@ Formerly **DrawCraft** (renamed 2026-10-01): old `.drawcraft` files and `"format
## Start every session here
1. Read the [honest assessment in `ROADMAP.md`](ROADMAP.md#honest-assessment-2026-10-05): where we stand by dimension, **where we're lacking** (the prioritized gap list) and **where we're going**. Unless the user gives you a task, pick work from that list.
2. Read `plan/STATUS.md` (local session notes, may lag the ROADMAP), then the task in `plan/execution-plan.md` §3 and the relevant `plan/architecture.md` section. Behaviour reference: `plan/illustrator/*.md`.
2. Read `plan/STATUS.md` (local session notes, may lag the ROADMAP), then the task in `plan/execution-plan.md` §3 and the relevant `plan/architecture.md` section. Behaviour reference: public documentation only (see Clean-room below); `plan/illustrator/*.md` holds notes from it.
3. Follow the autonomous operation protocol (`plan/execution-plan.md` §7): orient → plan → implement + test → verify → record → commit. Don't stop to ask unless §7 lists the decision as the user's.
`plan/` is gitignored (local only).
## Non-negotiables
- **Clean-room.** Never read, disassemble or copy anything inside the Illustrator bundle (names/listings only). Never copy Adobe icons, artwork, presets or wording beyond feature names. Behaviour comes from public docs and black-box observation of the running app with synthetic documents only (screenshots by window id, stored under `plan/illustrator/screenshots/`, never committed). Never copy GPL/AGPL code (Inkscape, lib2geom…).
- **Clean-room: never use Adobe software (absolute rule, from the project owner).** Adobe's Terms of Use forbid reverse engineering, including observing a program's inputs and outputs to recreate it. So:
- Never launch, run, script, automate (COM, AppleScript, ExtendScript, UI automation), screenshot or measure Illustrator or any other Adobe application, and never compare our output against one. Don't make test files with them, not even "synthetic" ones.
- Never read, disassemble or copy anything inside an Adobe install (binaries, plug-ins, presets, procsets, resources, help files, fonts, ICC profiles).
- Never copy Adobe-authored code or text into this repo, tests included: no PostScript procsets or prologs (AGM, CoolType, the Illustrator prologs), no sample files. Write test inputs from scratch from the public specifications (PostScript Language Reference, PDF / ISO 32000, TIFF, EPSF/DCS).
- Behaviour comes only from public documentation (helpx, published specs, public forum posts), cited by URL, and from files users send us that they own (used locally, never committed). Never copy Adobe icons, artwork, presets or wording beyond feature names.
- If a task seems to need any of this, stop and say so instead. `cargo xtask cleanroom` (run by `cargo xtask ci`) fails on Adobe copyright notices and on fixtures made with Adobe applications.
- Never copy GPL/AGPL code (Inkscape, lib2geom…).
- **Assets: no Adobe iconography or images — ever (absolute rule, from the project owner).**
- Never add, copy, trace, redraw-from, embed or ship any icon, image, artwork, cursor, preset, swatch/brush/symbol/pattern/style library, ICC profile or screenshot from Adobe products or from any other source whose licence doesn't allow it.
- Every image, icon, font or other asset must be one of:
@@ -44,7 +50,7 @@ Formerly **DrawCraft** (renamed 2026-10-01): old `.drawcraft` files and `"format
## Running and looking at the app
- `cargo run --release -p vectorcraft -- --control 7979 [file.svg|file.vectorcraft]` (sibling apps' agents use the same default port: if the log says it failed to bind, pick another port — otherwise your requests reach a different app).
- Drive it: JSON lines on `127.0.0.1:7979`, e.g. `{"id":1,"method":"engine.execute","params":{"command":"shape.rectangle","params":{"x":10,"y":10,"width":100,"height":50}}}` then `{"id":2,"method":"ui.screenshot","params":{"path":"/tmp/shot.png"}}`. Methods: `crates/ui-egui/src/control.rs`.
- **For UI work, look at the result** (take `ui.screenshot`, read the PNG) and compare with `plan/illustrator/02-ui-ux.md` / `10-observed-ui.md`. `ui.screenshot` needs a presented frame: if it errors (screen locked), check the art with `ui.render` / `vectorcraft-cli run … --export x.png`, and cover panels with a headless egui frame test (see `panels/transparency.rs` tests).
- **For UI work, look at the result** (take `ui.screenshot`, read the PNG) and compare with the public documentation (`plan/illustrator/02-ui-ux.md` notes). `ui.screenshot` needs a presented frame: if it errors (screen locked), check the art with `ui.render` / `vectorcraft-cli run … --export x.png`, and cover panels with a headless egui frame test (see `panels/transparency.rs` tests).
- **Performance:** `vectorcraft-cli perf` checks the budgets (render/pan/zoom, hit test, save/open, SVG, Pathfinder) on a synthetic 50k-path document; `vectorcraft-cli bench FILE` times one file. Run them before and after renderer, format or geometry changes, on an idle machine (the report warns when the load average makes timings noise).
- MCP: `vectorcraft-cli mcp` (see `docs/mcp.md`).
- Shell gotcha: `mv`/`cp` are aliased interactive here — use `/bin/mv -f` / `/bin/cp -f`.
@@ -53,5 +59,5 @@ Formerly **DrawCraft** (renamed 2026-10-01): old `.drawcraft` files and `"format
## Roadmap
`ROADMAP.md` (committed) is the shared picture of where VectorCraft stands. It holds status, the honest assessment (by dimension, the gap list, the direction), milestones, the parity table and time-to-parity estimates.
- When a task lands, update it in the same PR: the milestone row, the parity-table row (score, missing items, hours), "Shipped so far", and the gap list if the gap closed or shrank.
- Grade by behaviour against `plan/illustrator/`, not by whether a menu item exists. Scores are self-assessed, so err low.
- Grade by behaviour against the public documentation (`plan/illustrator/` notes), not by whether a menu item exists. Scores are self-assessed, so err low.
- Keep the README's Status section in step with the ROADMAP headline.
Generated
+28 -29
View File
@@ -2283,9 +2283,9 @@ dependencies = [
[[package]]
name = "muda"
version = "0.21.0"
version = "0.21.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c6744ab645ebe79f9c428455c7cb9dfa4275fa3b50a25408e08f927da8dc618c"
checksum = "9a7b000cca0783af26837fe2ebd9ddf1c42279463c085b97622ee1d2f444b89e"
dependencies = [
"crossbeam-channel",
"dpi",
@@ -2294,7 +2294,6 @@ dependencies = [
"objc2-app-kit 0.3.2",
"objc2-core-foundation",
"objc2-foundation 0.3.2",
"once_cell",
"png 0.18.1",
"thiserror 2.0.21",
"windows-sys 0.61.2",
@@ -2777,7 +2776,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"
dependencies = [
"libc",
"windows-sys 0.52.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -4297,7 +4296,7 @@ dependencies = [
[[package]]
name = "vectorcraft"
version = "0.5.0"
version = "0.7.0"
dependencies = [
"arboard",
"block2 0.6.2",
@@ -4321,7 +4320,7 @@ dependencies = [
[[package]]
name = "vectorcraft-brush"
version = "0.5.0"
version = "0.7.0"
dependencies = [
"kurbo 0.13.1",
"serde",
@@ -4333,7 +4332,7 @@ dependencies = [
[[package]]
name = "vectorcraft-cad"
version = "0.5.0"
version = "0.7.0"
dependencies = [
"image",
"kurbo 0.13.1",
@@ -4349,7 +4348,7 @@ dependencies = [
[[package]]
name = "vectorcraft-cli"
version = "0.5.0"
version = "0.7.0"
dependencies = [
"serde_json",
"vectorcraft-color",
@@ -4365,7 +4364,7 @@ dependencies = [
[[package]]
name = "vectorcraft-color"
version = "0.5.0"
version = "0.7.0"
dependencies = [
"kurbo 0.13.1",
"moxcms",
@@ -4377,7 +4376,7 @@ dependencies = [
[[package]]
name = "vectorcraft-doc"
version = "0.5.0"
version = "0.7.0"
dependencies = [
"image",
"jpeg-encoder",
@@ -4394,7 +4393,7 @@ dependencies = [
[[package]]
name = "vectorcraft-effects"
version = "0.5.0"
version = "0.7.0"
dependencies = [
"kurbo 0.13.1",
"serde_json",
@@ -4408,7 +4407,7 @@ dependencies = [
[[package]]
name = "vectorcraft-engine"
version = "0.5.0"
version = "0.7.0"
dependencies = [
"flate2",
"image",
@@ -4440,7 +4439,7 @@ dependencies = [
[[package]]
name = "vectorcraft-eps"
version = "0.5.0"
version = "0.7.0"
dependencies = [
"flate2",
"image",
@@ -4458,7 +4457,7 @@ dependencies = [
[[package]]
name = "vectorcraft-format"
version = "0.5.0"
version = "0.7.0"
dependencies = [
"flate2",
"proptest",
@@ -4472,7 +4471,7 @@ dependencies = [
[[package]]
name = "vectorcraft-geom"
version = "0.5.0"
version = "0.7.0"
dependencies = [
"kurbo 0.13.1",
"proptest",
@@ -4484,7 +4483,7 @@ dependencies = [
[[package]]
name = "vectorcraft-mcp"
version = "0.5.0"
version = "0.7.0"
dependencies = [
"image",
"log",
@@ -4503,7 +4502,7 @@ dependencies = [
[[package]]
name = "vectorcraft-metafile"
version = "0.5.0"
version = "0.7.0"
dependencies = [
"image",
"kurbo 0.13.1",
@@ -4517,7 +4516,7 @@ dependencies = [
[[package]]
name = "vectorcraft-pathops"
version = "0.5.0"
version = "0.7.0"
dependencies = [
"kurbo 0.13.1",
"linesweeper",
@@ -4529,7 +4528,7 @@ dependencies = [
[[package]]
name = "vectorcraft-pdf"
version = "0.5.0"
version = "0.7.0"
dependencies = [
"aes",
"flate2",
@@ -4558,7 +4557,7 @@ dependencies = [
[[package]]
name = "vectorcraft-plugins"
version = "0.5.0"
version = "0.7.0"
dependencies = [
"serde",
"serde_json",
@@ -4572,7 +4571,7 @@ dependencies = [
[[package]]
name = "vectorcraft-render"
version = "0.5.0"
version = "0.7.0"
dependencies = [
"flate2",
"gif",
@@ -4597,7 +4596,7 @@ dependencies = [
[[package]]
name = "vectorcraft-svg"
version = "0.5.0"
version = "0.7.0"
dependencies = [
"flate2",
"image",
@@ -4621,7 +4620,7 @@ dependencies = [
[[package]]
name = "vectorcraft-testkit"
version = "0.5.0"
version = "0.7.0"
dependencies = [
"image",
"kurbo 0.13.1",
@@ -4638,7 +4637,7 @@ dependencies = [
[[package]]
name = "vectorcraft-text"
version = "0.5.0"
version = "0.7.0"
dependencies = [
"harfrust 0.13.3",
"kurbo 0.13.1",
@@ -4656,7 +4655,7 @@ dependencies = [
[[package]]
name = "vectorcraft-tools"
version = "0.5.0"
version = "0.7.0"
dependencies = [
"image",
"kurbo 0.13.1",
@@ -4671,7 +4670,7 @@ dependencies = [
[[package]]
name = "vectorcraft-trace"
version = "0.5.0"
version = "0.7.0"
dependencies = [
"image",
"kurbo 0.13.1",
@@ -4684,7 +4683,7 @@ dependencies = [
[[package]]
name = "vectorcraft-ui-egui"
version = "0.5.0"
version = "0.7.0"
dependencies = [
"egui",
"egui_extras",
@@ -4713,7 +4712,7 @@ dependencies = [
[[package]]
name = "vectorcraft-web"
version = "0.5.0"
version = "0.7.0"
dependencies = [
"eframe",
"egui",
@@ -5816,7 +5815,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee"
[[package]]
name = "xtask"
version = "0.5.0"
version = "0.7.0"
dependencies = [
"serde_json",
]
+1 -1
View File
@@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"]
default-members = ["crates/*", "apps/vectorcraft", "apps/vectorcraft-cli", "xtask"]
[workspace.package]
version = "0.5.0"
version = "0.7.0"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.95"
+52 -4
View File
@@ -54,6 +54,7 @@
<a href="#why-vectorcraft">Why VectorCraft</a> ·
<a href="#quick-start">Quick start</a> ·
<a href="#status">Status</a> ·
<a href="#downloads">Downloads</a> ·
<a href="#the-crafting-apps">The Crafting Apps</a> ·
<a href="#license-and-credits">License</a>
</p>
@@ -162,9 +163,11 @@ Japanese fonts come from [storytold/craft-fonts](https://github.com/storytold/cr
build input (releases always use it): `CRAFT_FONTS_DIR="$PWD/../craft-fonts" cargo run --release -p vectorcraft` (an absolute path).
Without it, Japanese text uses the installed system fonts. See [`docs/development.md`](docs/development.md#fonts-craft-fonts-optional-build-input).
On laptops with two graphics processors, VectorCraft uses the power-saving (integrated) one by default.
To use the discrete one, choose **Preferences › Performance › Graphics Processor › High Performance**
and restart, or start the app with `WGPU_POWER_PREF=high` (see [`docs/development.md`](docs/development.md#desktop-graphics-processor)).
On machines with two graphics processors, VectorCraft renders on the power-saving (integrated) one by default on
Windows and macOS, and on the one the desktop runs on under Linux. To choose, use **Preferences › Performance ›
Graphics Processor** and restart. If a graphics processor can't show the window, VectorCraft starts again on the
next one. To pick one when starting the app, set `WGPU_POWER_PREF=high` (or `low`), or `WGPU_ADAPTER_NAME` to part of
its name, such as `WGPU_ADAPTER_NAME=nvidia` (see [`docs/development.md`](docs/development.md#desktop-graphics-processor)).
On Linux under KDE Plasma 6.3 or later with Wayland, a drawing tablet's pen moves the cursor but VectorCraft doesn't
respond to it yet (#491). Start the app under XWayland instead: `WAYLAND_DISPLAY= vectorcraft` (see
@@ -191,7 +194,7 @@ milestones, and honest time-to-parity estimates.
"a power user can't tell the difference". Everyday vector illustration is close to usable: drawing and path tools,
Pathfinder and Shape Builder, paint, gradients, appearance and transparency, type with styles, threading and Hebrew/Arabic bidirectional layout, and
files (SVG, PDF and PDF-compatible `.ai` with PDF/X, EPS, DXF, EMF/WMF, raster formats and PSD, Print, Package). The interface
speaks English, Japanese, Traditional and Simplified Chinese and Spanish (and Czech and Brazilian Portuguese in the menus).
speaks English, Japanese, Traditional and Simplified Chinese, Spanish and Italian (and Czech and Brazilian Portuguese in the menus).
The scores are
self-assessed, so the [honest assessment](ROADMAP.md#honest-assessment-2026-10-05) explains how far to trust them.
@@ -216,6 +219,51 @@ Agent and contributor rules (clean-room, the asset policy, no panics in shipped
explains how VectorCraft avoids crashing, and [`docs/releasing.md`](docs/releasing.md) how releases are built,
signed and published. Every bundled asset is listed with its licence in [`ASSETS.md`](ASSETS.md).
## Downloads
**New to VectorCraft?** Download it from the [VectorCraft page on getartcraft.com](https://getartcraft.com/apps/vectorcraft). That's the easiest way to install it.
**Want a specific build or format?** On GitHub, the [latest release](https://github.com/storytold/vectorcraft/releases/latest) has every build listed below, and [all releases](https://github.com/storytold/vectorcraft/releases) has earlier versions and their notes. `<ver>` in the file names is the version number, and `SHA256SUMS.txt` lists a checksum for every file.
### Windows
| Build | Installer | Portable |
|---|---|---|
| x64 (64-bit Intel/AMD) | `vectorcraft-<ver>-windows-x64.msi` | `vectorcraft-<ver>-windows-x64-portable.zip` |
| arm64 (Snapdragon and other ARM PCs) | `vectorcraft-<ver>-windows-arm64.msi` | `vectorcraft-<ver>-windows-arm64-portable.zip` |
| x86 (32-bit) | `vectorcraft-<ver>-windows-x86.msi` | `vectorcraft-<ver>-windows-x86-portable.zip` |
Installers and executables are code-signed.
### macOS
| Build | File | Notes |
|---|---|---|
| App, universal (Apple silicon + Intel) | `vectorcraft-<ver>-macos-universal.dmg` | Signed and notarized |
| Command-line tool, universal | `vectorcraft-cli-<ver>-macos-universal.zip` | Signed and notarized |
### Linux
| Format | x86_64 | aarch64 (ARM64) | Notes |
|---|---|---|---|
| AppImage | `vectorcraft-<ver>-linux-x86_64.AppImage` | `vectorcraft-<ver>-linux-aarch64.AppImage` | Runs anywhere; updates itself with [AppImageUpdate](https://github.com/AppImageCommunity/AppImageUpdate) (`.zsync` files) |
| Flatpak | `vectorcraft-<ver>-linux-x86_64.flatpak` | `vectorcraft-<ver>-linux-aarch64.flatpak` | Sandboxed; `flatpak install --user <file>` |
| Debian/Ubuntu | `vectorcraft-<ver>-linux-x86_64.deb` | `vectorcraft-<ver>-linux-aarch64.deb` | |
| Fedora/RHEL/openSUSE | `vectorcraft-<ver>-linux-x86_64.rpm` | `vectorcraft-<ver>-linux-aarch64.rpm` | |
| Tarball | `vectorcraft-<ver>-linux-x86_64.tar.gz` | `vectorcraft-<ver>-linux-aarch64.tar.gz` | Unpack anywhere |
### FreeBSD
| Build | File |
|---|---|
| x86_64 | `vectorcraft-<ver>-freebsd-x86_64.tar.gz` |
### Web (WebAssembly)
| Build | File | Notes |
|---|---|---|
| Static site | `vectorcraft-web-<ver>.zip` | Runs in a modern browser; host it on any static server |
## The Crafting Apps
VectorCraft is one of the **Crafting Apps**: free, open-source creative tools from the
+31 -25
View File
@@ -4,7 +4,7 @@ VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adob
This file tracks **how far we are and what's left**. Time estimates are wall-clock hours of continuous Claude Opus 5.5 agent work (including builds and the CI gate), given both for **one agent** and for **4–6 parallel agents** on disjoint crates. They are counted from the remaining work (see [Parity estimate](#parity-estimate)), calibrated against measured throughput, and updated as work lands.
_Last updated: 2026-10-08 (after M4.14–M4.98, M8.1–M8.20, M14.4–M14.7, the MCP prompts, resource templates, completions and logging, the 2026-10-07 issue fixes, the Layers panel rework and the 2026-10-08 community contributions: Pen and shape-tool modifiers, path editing, Layers, Artboards, Swatches/Brushes and dialogs, Japanese composition and PDF text, Hebrew/Arabic type, interface languages (Spanish among them), the font menu, saved selections, MCP and EPS, the missing-font export warning (#319), open paths in the Shape Builder (#374), PDF/`.ai` import keeping strokes live and hidden and nested layers (#372), per-corner Live Corners (#381), SVG type opening at the size it draws at (#396), the Wayland clipboard with copied-file paste (#398), ruler guides that can be selected, moved and deleted (#414), two batches of Preferences options that were stored but unused (#394), skeleton reads with `document.find` for large documents over MCP (#416) and anchors dragged with Direct Selection snapping to points, segments and smart guides, clipped SVG layers opening as clipping layers (#420), PDF/`.ai` layers read on pages of tens of millions of operators (#419), Document Color Mode putting RGB greys on the black plate on request and converting pattern tiles (#421) and movable dialogs with Offset Path's Joins dropdown (#423) and numeric fields scrubbed by dragging their label (#400), stroke weight presets in the stroke unit (#426), the Appearance panel's Opacity popup (#430), type on a path brackets, flip and Type on a Path Options that keep the type in place (#429), Layers rows dragged with a ghost and dropped on the trash or New Layer (#435), tool flyouts opening on a right or corner press (#436), tool flyouts torn off into floating toolbars (#437), the Shape Builder's erase mode deleting edges too (#439), installed fonts registered outside the font folders and fonts installed while the app runs listed in the font menus (#443), alike circular corners on rectangles that aren't square (#442), tool cursors as OS cursors so the pointer no longer trails over the canvas (#444), artboards copied and pasted with their art (#446), guides dragged out of the rulers snapping to the art's side midpoints and the artboards, artboard guides (#451), the toolbar's double arrow and Window › Toolbars › Double Column switching between one and two columns in any window height (#455), the Smart Guides display options and Snapping Tolerance (#394), Font Size and Leading combo boxes with preset lists in the Character and Properties panels and the Control bar (#458), screenshots pasted from the clipboard on macOS, Windows and the web (#457), the Properties panel's Fill and Stroke matching the Control bar's, Illustrator's Window menu panel keys (Shift+F7 for Align…) and Alt-wheel zoom whatever the wheel preference (Discord feedback), the point/area type widget (Discord feedback), groups in legacy Illustrator .ai files (Discord feedback), a rotating desktop log file (#465), image controls in the Control bar and Properties panel: Image Trace with its presets, Mask, Crop Image, Embed/Unembed, and an Image Trace object's preset, Expand and Release (Discord feedback), the Pen working as the Anchor Point tool with Alt held over a selected path's handles and anchors, and anchor buttons that convert, connect and cut paths at the selected anchors (Discord feedback), Japanese hanging punctuation (burasagari, #463), Escape leaving Presentation Mode with no screen mode saved across restarts, documents dropped on the desktop app opening as tabs of their own and a note that an `.ai` file's art off its artboards isn't in the part read (#472), Add/Delete Anchor Point tool icons drawn from the Pen tool's (#479), EPS files from Illustrator 2026, Inkscape/cairo, matplotlib, CorelDRAW, Affinity, LibreOffice and Ghostscript opening as vectors, and a preview that stands in saying why (Discord feedback, #466, #469, #474), chords with modifiers recorded in Edit › Keyboard Shortcuts (#487), Type Object Selection by Path Only (#394), Anti-aliased Artwork (#394), Show Pixel Grid (#394), pen and touch taps pressed and lifted within one frame clicking where they tapped and the Linux/Wayland pen-tablet workaround (#491), bounding-box resizes landing on the other objects' anchors and centres with labels, and the Rotate, Scale, Shear and Reflect tools snapping their drags (#482), Shift-drag marquees that toggle the objects or anchors they reach and a Lasso whose Alt subtraction keeps the rest of the selection (#483), the mouse wheel stepping the focused numeric field, the dialogs' and preferences' drag values made such fields (#485); see [Honest assessment](#honest-assessment-2026-10-05))._
_Last updated: 2026-10-09 (after placed documents (File › Place of a `.vectorcraft` file, linked), M4.14–M4.98, M8.1–M8.20, M14.4–M14.7, the MCP prompts, resource templates, completions and logging, the 2026-10-07 issue fixes, the Layers panel rework and the 2026-10-08 community contributions: Pen and shape-tool modifiers, path editing, Layers, Artboards, Swatches/Brushes and dialogs, Japanese composition and PDF text, Hebrew/Arabic type, interface languages (Spanish among them), the font menu, saved selections, MCP and EPS, the missing-font export warning (#319), open paths in the Shape Builder (#374), PDF/`.ai` import keeping strokes live and hidden and nested layers (#372), per-corner Live Corners (#381), SVG type opening at the size it draws at (#396), the Wayland clipboard with copied-file paste (#398), ruler guides that can be selected, moved and deleted (#414), two batches of Preferences options that were stored but unused (#394), skeleton reads with `document.find` for large documents over MCP (#416) and anchors dragged with Direct Selection snapping to points, segments and smart guides, clipped SVG layers opening as clipping layers (#420), PDF/`.ai` layers read on pages of tens of millions of operators (#419), Document Color Mode putting RGB greys on the black plate on request and converting pattern tiles (#421) and movable dialogs with Offset Path's Joins dropdown (#423) and numeric fields scrubbed by dragging their label (#400), stroke weight presets in the stroke unit (#426), the Appearance panel's Opacity popup (#430), type on a path brackets, flip and Type on a Path Options that keep the type in place (#429), Layers rows dragged with a ghost and dropped on the trash or New Layer (#435), tool flyouts opening on a right or corner press (#436), tool flyouts torn off into floating toolbars (#437), the Shape Builder's erase mode deleting edges too (#439), installed fonts registered outside the font folders and fonts installed while the app runs listed in the font menus (#443), alike circular corners on rectangles that aren't square (#442), tool cursors as OS cursors so the pointer no longer trails over the canvas (#444), artboards copied and pasted with their art (#446), guides dragged out of the rulers snapping to the art's side midpoints and the artboards, artboard guides (#451), the toolbar's double arrow and Window › Toolbars › Double Column switching between one and two columns in any window height (#455), the Smart Guides display options and Snapping Tolerance (#394), Font Size and Leading combo boxes with preset lists in the Character and Properties panels and the Control bar (#458), screenshots pasted from the clipboard on macOS, Windows and the web (#457), the Properties panel's Fill and Stroke matching the Control bar's, Illustrator's Window menu panel keys (Shift+F7 for Align…) and Alt-wheel zoom whatever the wheel preference (Discord feedback), the point/area type widget (Discord feedback), groups in legacy Illustrator .ai files (Discord feedback), a rotating desktop log file (#465), image controls in the Control bar and Properties panel: Image Trace with its presets, Mask, Crop Image, Embed/Unembed, and an Image Trace object's preset, Expand and Release (Discord feedback), the Pen working as the Anchor Point tool with Alt held over a selected path's handles and anchors, and anchor buttons that convert, connect and cut paths at the selected anchors (Discord feedback), Japanese hanging punctuation (burasagari, #463), Escape leaving Presentation Mode with no screen mode saved across restarts, documents dropped on the desktop app opening as tabs of their own and a note that an `.ai` file's art off its artboards isn't in the part read (#472), Add/Delete Anchor Point tool icons drawn from the Pen tool's (#479), EPS import running more of PostScript Level 3 (patterns, Type 3 fonts, mesh shadings, masked images, VM and resource probes), and a preview that stands in saying why (Discord feedback, #466, #469, #474), chords with modifiers recorded in Edit › Keyboard Shortcuts (#487), Type Object Selection by Path Only (#394), Anti-aliased Artwork (#394), Show Pixel Grid (#394), pen and touch taps pressed and lifted within one frame clicking where they tapped and the Linux/Wayland pen-tablet workaround (#491), bounding-box resizes landing on the other objects' anchors and centres with labels, and the Rotate, Scale, Shear and Reflect tools snapping their drags (#482), Shift-drag marquees that toggle the objects or anchors they reach and a Lasso whose Alt subtraction keeps the rest of the selection (#483), the mouse wheel stepping the focused numeric field, the dialogs' and preferences' drag values made such fields (#485), Show The Home Screen When No Documents Are Open (#394), Numbers Without Units Are Points (#394), Auto-Collapse Iconic Panels (#394), the Contextual Task Bar moved by its handle and its More Options menu pinning and resetting its position, a designed macOS DMG windoLine truncated
## Where we are
@@ -42,7 +42,7 @@ since 2026-10-01.
| **Bundled content:** brush, symbol, style and swatch libraries | ~30% | Ours are original and generated in code, and far fewer than Illustrator ships; brush and symbol libraries are still missing |
| **Performance** | unverified | Multithreaded, off-thread rendering and caches are in place. The last budget run (2026-10-01, loaded machine) measured 290 ms for a 50k-path fit against a 16 ms budget. Re-run `vectorcraft-cli perf` on an idle machine |
| **Robustness** | good, new | ~2,840 tests, property tests, no panics in shipped code (lints, the `guard` safety net, import fuzzing), Data Recovery. Missing: a corpus of real-world files, Windows/Linux/browser QA |
| **Platforms and 1.0 polish** | ~60% | The macOS app and the web build work, and Finder opens every readable format with the macOS app (#295, #354); hybrid-graphics laptops render on the power-saving GPU by default (#306); web drops land in the document they were dropped on (#359); desktop drops carry no pointer position (winit 0.30), so a dropped document opens as a tab of its own and a picture or text is placed in the middle of the view, while the web places anything dropped on the canvas and opens what is dropped off it, as Illustrator does (#472); a web page that loses its WebGPU device or WebGL context restarts its graphics with the same documents (#369); on Linux/Wayland the clipboard reads the compositor's own (data-control) and copied image files paste, but files can't be dropped on the window under Wayland until eframe moves to winit 0.31 (#398; the Wayland side is verified by compilation only); on KDE Plasma 6.3+ under Wayland, pens and pen displays reach the app only under XWayland (`WAYLAND_DISPLAY=`) or with KWin's `KWIN_WAYLAND_EMULATE_TABLET=1`, since winit 0.30 has no Wayland tablet input (#491, not verified on hardware); Windows/Linux packaging and accessibility are pending; an experimental, unsupported Windows 7 x64 OpenGL build exists (community-contributed, not verified by maintainers) |
| **Platforms and 1.0 polish** | ~60% | The macOS app and the web build work, and Finder opens every readable format with the macOS app (#295, #354); on macOS the menus are in the system menu bar, laid out as a Mac app's, with the in-window menus as a fallback (`--in-window-menus`; verified on Windows and by cross-compilation, not yet by hand on a Mac); hybrid-graphics laptops render on the power-saving GPU by default on Windows and macOS (#306), and Windows renders through DX12 before Vulkan (#545: Vulkan flickered black on an Intel GPU, DX12 and OpenGL didn't; verified by unit tests and the reporter's runs with `WGPU_BACKEND`), and Linux on the GPU the desktop runs on, since a Wayland compositor may refuse frames from the other one; a window that fails on its GPU while starting up starts again on the next one instead of crashing (#502; the dual-GPU Wayland case is verified by unit tests and cross-compilation, not on such hardware); web drops land in the document they were dropped on (#359); desktop drops carry no pointer position (winit 0.30), so a dropped document opens as a tab of its own and a picture or text is placed in the middle of the view, while the web places anything dropped on the canvas and opens what is dropped off it, as Illustrator does (#472); a web page that loses its WebGPU device or WebGL context restarts its graphics with the same documents (#369); on Linux/Wayland the clipboard reads the compositor's own (data-control) and copied image files paste, but files can't be dropped on the window under Wayland until eframe moves to winit 0.31 (#398; the Wayland side is verified by compilation only); on Linux the Paste menu checks the system clipboard on a background thread, so a clipboard owner that never answers no longer freezes the window, while Windows and macOS keep their quick in-line check (#510; the X11 hang verified by the contributor, here by headless tests); on KDE Plasma 6.3+ under Wayland, pens and pen displays reach the app only under XWayland (`WAYLAND_DISPLAY=`) or with KWin's `KWIN_WAYLAND_EMULATE_TABLET=1`, since winit 0.30 has no Wayland tablet input (#491, not verified on hardware); Windows/Linux packaging and accessibility are pending; an experimental, unsupported Windows 7 x64 OpenGL build exists (community-contributed, not verified by maintainers) |
| **Agent automation** | beyond Illustrator | Every command, gesture and dialog is drivable over MCP, the CLI and the control channel |
| **Scrubby numeric fields** | beyond Illustrator | As in Photoshop, dragging a numeric field's label (`W:`, `Opacity:`, the Character panel's icons) left or right steps its value live; one undo step per drag, Escape cancels (#400) |
@@ -97,30 +97,35 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist
- **UI:** Illustrator 2026 layout restyled to measured values:
- Medium Dark theme, categorized and Advanced toolbars (a tool group's flyout opens on a right press, a long press or a press on its corner triangle), 35 pt document tabs, 33 pt panel tabs.
- Hint bar, contextual task bar, 19 dock panels with ≡ menus.
- The contextual task bar's handle drags it anywhere on the canvas (kept whole on it as the window resizes); unpinned it keeps that offset as it follows the selection, and its More Options menu hides it, pins its position across selection changes (`window.taskBar.pin`), resets it under the selection (`window.taskBar.reset`) and shows the Properties panel. As in Illustrator the position isn't kept across launches. Not done: the bar's tool-specific variants (only the selection tools show it).
- Tool flyouts tear off: dragging or clicking the tear-off bar on a flyout's right side (or releasing the long press over it) floats its group as a strip of tool buttons, moved by the same bar and put back in the toolbar by the × at its top (`window.floatTools`). While a group floats, the presses that would open its flyout raise the strip instead. Floating strips are kept with the preferences and in user workspaces. Not done: turning a strip vertical, docking it.
- Panels undock (#495): a dock tab, a panel icon or a popped-out panel's title dragged out of the dock floats that panel inside the window, and the strip right of the dock's tabs floats the whole tabbed group. A floating group moves by its title bar, a tab dragged out of it floats on its own, and dropped on another group's title bar or tabs it stacks with that group; dropped on the dock, which lights up under the pointer, its panels go back where they live (the tabbed group or the icon column), as its × and the panel menus' Float Panel / Dock Panel do (`window.panel.float`, `window.panel.dock`). The Tools panel floats by its title bar and docks again on the window's left edge. Floating panels and the Tools panel's position are kept with the preferences and in user workspaces, and clamped into a smaller window. Not done: panels in separate OS windows, docking a panel into a dock group it doesn't belong to, reordering tabs by dragging, collapsing a floating group to icons, resizing floating panels.
- The dock's double arrow collapses Properties, Layers and Libraries to icons at the top of the icon column, popping out like the other icon panels, and expands them again (`window.collapseDock`, kept with the preferences and in saved workspaces). The icon column's own arrow (expanding the icon panels into a full column) is not done.
- Localised UI: menus (in-window and native), panels, dialogs, toolbar and Preferences read from per-language catalogs (`crates/ui-egui/src/i18n`, see `docs/development.md`); Traditional Chinese (Taiwan), Simplified Chinese (mainland), Japanese and Spanish ship complete, and Czech and Brazilian Portuguese cover every menu label (and more), with system-locale detection on macOS, Windows, Linux and the web (the browser's languages, or `?lang=`), a VectorCraft ▸ Language menu and a Language preference. Names are never translated (fonts and their styles, layers, artboards, saved presets, user libraries, custom workspaces, recent files, plug-ins).
- Native macOS menu bar, vector tool cursors, a ⌘K command palette, middle-button panning with any tool.
- macOS: Finder opens every format File › Open reads with VectorCraft (double-click, Open With, a drop on the Dock icon, `open -a`), at launch or while it runs; the release and `cargo xtask bundle` apps share one `Info.plist` that declares those document types, owning only VectorCraft's own formats.
- Localised UI: menus (in-window and native), panels, dialogs, toolbar and Preferences read from per-language catalogs (`crates/ui-egui/src/i18n`, see `docs/development.md`); Traditional Chinese (Taiwan), Simplified Chinese (mainland), Japanese, Spanish and Italian ship complete, and Czech and Brazilian Portuguese cover every menu label (and more), with system-locale detection on macOS, Windows, Linux and the web (the browser's languages, or `?lang=`), a VectorCraft ▸ Language menu and a Language preference. Names are never translated (fonts and their styles, layers, artboards, saved presets, user libraries, custom workspaces, recent files, plug-ins).
- Native macOS menu bar, vector tool cursors, a ⌘K command palette, middle-button panning with any tool. Native menus explicitly end tracking on command selection, outside window presses and Escape; menu updates wait until tracking ends, and a dismissing press never starts a canvas gesture (M14.8).
- The macOS menu bar is built from the in-window menus (one model, `native_menu`) and laid out as a Mac app's: the VectorCraft menu holds About, Settings ▸ (each Preferences page, General… ⌘K), Language ▸, Appearance ▸ (UI brightness), Services, Hide VectorCraft ⌃⌘H (⌘H stays Hide Edges), Hide Others, Show All and Quit; Window gains Minimize ⌃⌘M, Zoom and Bring All to Front, and Help the system's search field. Its key equivalents go back to egui as key presses, so user shortcuts, focused text fields and the Type tool's input method behave as in the window, and nothing fires twice; enabled, check marks and labels update in place. `--in-window-menus` or `VECTORCRAFT_IN_WINDOW_MENUS=1` keeps the menus in the window; `ui.inspect` reports `nativeMenuBar`.
- macOS: Finder opens every format File › Open reads with VectorCraft (double-click, Open With, a drop on the Dock icon, `open -a`), at launch or while it runs; the release and `cargo xtask bundle` apps share one `Info.plist` that declares those document types, owning only VectorCraft's own formats. The DMG opens on a designed Finder window, VectorCraft.app beside the `Applications` link over a background with the app icon (#493).
- A canvas context menu: right-click selects the object under the pointer and lists what applies to the selection (Undo/Redo, clipboard, group, isolation, join, Remove Anchor Points when anchors are selected, masks, compound paths, guides, Transform, Arrange, Select, Export Selection), or the view commands on empty canvas.
- Save / Don't Save / Cancel before closing or quitting with unsaved documents (tabs, Close, Close All, Quit, window close).
- Four brightness themes, persistent preferences.
- Preferences that act (#394, in part): Show Tool Tips, Double Click To Isolate, Zoom with Mouse Wheel (the wheel zooms about the pointer, Shift-wheel scrolls up and down, Cmd/Ctrl-wheel sideways; Alt/Option-wheel and a trackpad pinch zoom about the pointer either way), Use Precise Cursors; Selection & Anchor Display › Tolerance (objects, anchors and handles), Object Selection by Path Only, Command Click to Select Objects Behind (cycling down the stack), Zoom to Selection, anchor Size, Highlight anchors on mouse over; Type › Number of Recent Fonts (up to 15); Guides & Grid › guide and grid Color and Style (lines or dots) and Grids In Back. Then Snap to Point (its distance, for moves, drawn points and reference points), Move Locked and Hidden Artwork with Artboard, Enable Rubber Band for the Pen and Curvature tools, Handles style, Show handles when multiple anchors are selected, Hide Corner Widget for angles greater than; General › Transform Pattern Tiles (the transforms' and dialogs' Transform Patterns) and Select Same Tint %; Type › Size/Leading, Tracking and Baseline Shift increments (`type.step`, Cmd+Shift+. and Cmd+Shift+, for the size, the Type tool's Alt+arrows), Enable Missing Glyph Protection and Fill New Type Objects With Placeholder Text. Then Smart Guides › Color, Alignment Guides, Anchor/Path Labels, Measurement Labels, Transform Tools, Object Highlighting (with Smart Guides on) and Snapping Tolerance (4 px by default, for every smart guide snap). Then Type › Type Object Selection by Path Only (type is picked on the baseline of any of its lines, area type's frame or the path of type on a path, no longer anywhere in its bounds; the Type tools and the Eyedropper still take a click among the characters). Then General › Anti-aliased Artwork (off, the canvas draws the art with hard edges). Then Guides & Grid › Show Pixel Grid (Above 600% Zoom), a line at every document pixel over the art in Pixel Preview, turning with a rotated view as the document grid now does too. They reach agents too (`prefs.set`, then `pointer_gesture` or `press_key`; `ui.wheel` on the control channel). About 35 stored options still do nothing yet (the rest of #394: Auto Size New Area Type, Show Font Names in English, Highlight Alternate Glyphs, Construction and Spacing Guides, performance, devices…).
- Preferences that act (#394, in part): Show Tool Tips, Double Click To Isolate, Zoom with Mouse Wheel (the wheel zooms about the pointer, Shift-wheel scrolls up and down, Cmd/Ctrl-wheel sideways; Alt/Option-wheel and a trackpad pinch zoom about the pointer either way), Use Precise Cursors; Selection & Anchor Display › Tolerance (objects, anchors and handles), Object Selection by Path Only, Command Click to Select Objects Behind (cycling down the stack), Zoom to Selection, anchor Size, Highlight anchors on mouse over; Type › Number of Recent Fonts (up to 15); Guides & Grid › guide and grid Color and Style (lines or dots) and Grids In Back. Then Snap to Point (its distance, for moves, drawn points and reference points), Move Locked and Hidden Artwork with Artboard, Enable Rubber Band for the Pen and Curvature tools, Handles style, Show handles when multiple anchors are selected, Hide Corner Widget for angles greater than; General › Transform Pattern Tiles (the transforms' and dialogs' Transform Patterns) and Select Same Tint %; Type › Size/Leading, Tracking and Baseline Shift increments (`type.step`, Cmd+Shift+. and Cmd+Shift+, for the size, the Type tool's Alt+arrows), Enable Missing Glyph Protection and Fill New Type Objects With Placeholder Text. Then Smart Guides › Color, Alignment Guides, Anchor/Path Labels, Measurement Labels, Transform Tools, Object Highlighting (with Smart Guides on) and Snapping Tolerance (4 px by default, for every smart guide snap), then Construction Guides and their Angles (#506: a drawn point near a line at one of those angles through the point it leaves from lands on it). Then Type › Type Object Selection by Path Only (type is picked on the baseline of any of its lines, area type's frame or the path of type on a path, no longer anywhere in its bounds; the Type tools and the Eyedropper still take a click among the characters). Then General › Anti-aliased Artwork (off, the canvas draws the art with hard edges). Then Guides & Grid › Show Pixel Grid (Above 600% Zoom), a line at every document pixel over the art in Pixel Preview, turning with a rotated view as the document grid now does too. Then General › Show The Home Screen When No Documents Are Open (off, closing the last document leaves an empty window; the Home button still opens the screen). Then Units › Numbers Without Units Are Points (on by default: a number typed with no unit into a field in picas is read in points, a typed unit still wins; dimmed unless a unit is Picas). Then User Interface › Auto-Collapse Iconic Panels (off by default: on, a click away from a panel popped out of the icon column puts it away). They reach agents too (`prefs.set`, then `pointer_gesture` or `press_key`; `ui.wheel` on the control channel). About 30 stored options still do nothing yet (the rest of #394: Auto Size New Area Type, Show Font Names in English, Highlight Alternate Glyphs, Spacing Guides, performance, devices…).
- Dialogs move by dragging their heading (the band down from the top edge, as a title bar), stay on screen and keep where they were moved for the session; the form dialogs' choices are dropdowns (Offset Path's Joins, Average's and Shear's and Reflect's axis), and Offset Path lists Offset, Joins, Miter Limit and previews (#423).
- Dialogs open with their first field focused and its value selected: type a value and press Enter (Move, Rotate, Scale…). Number fields in panels, the Control bar and dialogs (preferences too) step with Up/Down, or with the mouse wheel over the focused field (#485: a notch a step; the panel under it then stays put, and an unfocused field leaves the wheel to scrolling) (Shift: ten, Ctrl/Cmd: a tenth of their unit), applied at once.
- Scrubby labels (#400, beyond Illustrator, as in Photoshop): dragging a numeric field's label left or right (the ↔ cursor shows over it) steps the value one unit every 2 points (Shift: ten, Ctrl/Cmd: a tenth; counts stay whole), in the field's unit and within its limits, applied live as the art follows; the whole drag is one undo step and Escape puts the value back. A click on the label focuses the field; the text box itself never scrubs, and a field with no label doesn't. Text labels before a field (Transform, Properties, Control bar, Stroke, Transparency, form rows in dialogs) and the Character and Paragraph panels' icons act as labels. Preferences › General › Scrub Numeric Fields by Dragging (on by default) turns it off.
- The Control bar's underlined Transform link opens the Transform panel in a popover under it (reference point, X/Y/W/H, Rotate and Shear with their icons and angle presets, flips, shape properties, Scale Corners and Scale Strokes & Effects), as its Stroke link does the Stroke panel; X/Y/W/H also show inline while the bar has room. The reference point locator is nine squares, the outer eight joined around the box.
- Tab shows and hides the panels (in the Type tool it types a tab) without moving the keyboard focus onto a field, so the next shortcut or letter still works; in dialogs and panel fields it moves between fields.
- Cmd/Ctrl+A follows the keyboard: in a panel, dialog or search field it selects the field's text, while the Type tool edits it selects all of that text (also `select.all` over MCP), and only otherwise every object. On macOS the menu bar's Select All, Cut, Copy and Paste (keys or clicks) act on a focused field too. Not yet: Select All across threaded frames (one frame's text is selected).
- Cmd/Ctrl+A follows the keyboard: in a panel, dialog or search field it selects the field's text, while the Type tool edits it selects all of that text (also `select.all` over MCP), and only otherwise every object. On macOS the menu bar's Select All, Cut, Copy and Paste (keys or clicks) act on a focused field too, and elsewhere the in-window menus' do: the field that had the keyboard when the menu opened gets them, with its selection, and the keyboard back (#516). Not yet: Select All across threaded frames (one frame's text is selected).
- On Windows and Linux the app bar is the window's title bar (its own minimize, maximize and close buttons, drag to move, edges to resize), with the dragon app icon as the brand mark; dialogs and menus size to their content. As on a native menu bar, once one menu is open, moving the pointer onto another title opens that one.
- **Tools:**
- **Selection:** Selection, Direct/Group Selection, Magic Wand, Lasso. A Shift-drag marquee toggles what it reaches: objects with the Selection tool, anchors with Direct and Group Selection (#483); the Lasso adds with Shift and subtracts with Alt. Dragging a path segment with Direct Selection bends it when it's curved (its anchors stay) and moves its two anchors when it's straight, one undo step; the fill, Shift or Alt still pick the whole path (Alt-drag copies it).
- **Saved selections:** Select ▸ Save Selection… asks for a name and keeps the selection in the document (saved with the file, undoable, up to 25); each one is listed at the bottom of the Select menu and a click selects its objects again; Edit Selection… lists them to rename or delete, applied together on OK. A file's saved selections are capped and checked against its objects when it opens. Not yet: Update Selection and the Layers panel's saved-selection menu.
- **Drawing:** Pen, Curvature, anchor tools, Pencil, Paintbrush, Blob Brush, Smooth, Path Eraser, Join. Direction handles dragged with Direct Selection or the Anchor Point tool snap to smart guides, and Shift keeps them at 45° steps from their anchor.
- **Drawing:** Pen, Curvature, anchor tools, Pencil, Paintbrush, Blob Brush, Smooth, Path Eraser, Join. Direction handles dragged with Direct Selection or the Anchor Point tool snap to smart guides, and Shift keeps them at 45° steps from their anchor. Every point a drawing tool places snaps to Smart Guides through one snapper (#506): the Pen's and Curvature tool's anchors, the Pencil's ends, the shape tools' start and dragged corner or radius (Rectangle, Rounded Rectangle, Ellipse, Polygon, Star, Line Segment, Arc, Spiral, the grids), the Type tool's click and frame, a new artboard's corners.
- **Shapes:** all shape tools (including Flare) and the line, arc, spiral and grid tools. Space held while dragging out a shape, line, arc, spiral or grid moves it at its current size. While a grid is dragged out, Up/Down change its rows (concentric dividers) and Left/Right its columns (radial dividers).
- **Cutting:** Eraser, Scissors, Knife, Mirror & Cut, Line Cut and Rectangle Cut (real geometry, compound paths keep their holes).
- **Transform:** Rotate, Reflect, Scale, Shear (click or Alt-click snaps the reference point to anchors and centres; Alt-click opens the tool's dialog, and a drag with Alt down at the release, from the press or pressed mid-drag, transforms a copy), Reshape, Free Transform (free and perspective distort and shear, switched by the keys held during a handle drag).
- **Live Corners:** drag a live rectangle's corner widgets (Selection or Direct Selection) to round all corners, with a radius readout; with Direct Selection, select corner anchors to show and round just those corners (#381). Each corner keeps its own radius and kind (Round, Inverted Round, Chamfer): Alt-click a widget to cycle the kind, double-click it for the Corners dialog, and the Properties and Transform radius fields set the selected corners (`object.setLiveShape {corners, radius, kind}`). Corners stay circular when the rectangle is scaled unevenly or along its own sides when rotated (the radius keeps its size, or scales by the mean scale with Scale Corners on); only a shear distorts them. On a rectangle that isn't square every corner is the same circle: a radius past half the shorter side stops there for all of them, the widgets sit on the corners as drawn and turn the edited corners red at that limit, CSS export writes the drawn radii, and rectangles saved stretched by older versions get circular corners when their corners are next set (#442).
- **Pen:** Alt pressed in the middle of dragging out an anchor splits its handles and keeps the curve already shaped into it (only the outgoing handle follows the pointer); Space held while dragging out an anchor moves it, handles and all. Clicking the last anchor of the path being drawn retracts its outgoing handle (convert cursor), and dragging from it pulls out a new one on its own. Auto Add/Delete: over a selected path, a click on a segment adds an anchor and a click on an anchor deletes it (add and delete cursors); Shift held, or Preferences › General › Disable Auto Add/Delete, starts a new path instead. Alt held over a handle end or an anchor of a selected path (the one being drawn too) works as the Anchor Point tool, with its convert cursor: dragging a handle moves it alone, clicking a smooth anchor makes it a corner, dragging an anchor pulls out new symmetric handles; drawing then goes on.
- **Live Corners:** drag a live rectangle's corner widgets (Selection or Direct Selection) to round all corners, with a radius readout; with Direct Selection, select corner anchors to show and round just those corners (#381). Each corner keeps its own radius and kind (Round, Inverted Round, Chamfer): Alt-click a widget to cycle the kind, double-click it for the Corners dialog, and the Properties and Transform radius fields set the selected corners (`object.setLiveShape {corners, radius, kind}`). Corners stay circular when the rectangle is scaled unevenly or along its own sides when rotated (the radius keeps its size, or scales by the mean scale with Scale Corners on); only a shear distorts them. On a rectangle that isn't square every corner is the same circle: a radius past half the shorter side stops there for all of them, the widgets sit on the corners as drawn and turn the edited corners red at that limit, CSS export writes the drawn radii, and rectangles saved stretched by older versions get circular corners when their corners are next set (#442). Live Corners work on any path's corners too, as on a rectangle's (#511): a star's, a live polygon's (which also shows them to the Selection tool, has a Corner Radius field in the Properties and Transform panels and keeps its radius as its sides change) and a pen path's, wherever two straight sides meet at an anchor. Direct Selection shows the widgets of every corner, or of the corners holding selected anchors; each corner is a circle tangent to both sides, drawn no larger than takes its cut halfway along its shorter side; a path keeps its uncut outline so its corners stay editable, and the same command, dialog, angle preference and View › Hide Corner Widget apply.
- **Pen:** Alt pressed in the middle of dragging out an anchor splits its handles and keeps the curve already shaped into it (only the outgoing handle follows the pointer); Space held while dragging out an anchor moves it, handles and all. A press on the first anchor of the path being drawn closes it whatever the drag then does: the drag shapes the closing curve (symmetric handles, Alt breaks them) and the release closes the path wherever it ends (#501). Clicking the last anchor of the path being drawn retracts its outgoing handle (convert cursor), and dragging from it pulls out a new one on its own. Auto Add/Delete: over a selected path, a click on a segment adds an anchor and a click on an anchor deletes it (add and delete cursors); Shift held, or Preferences › General › Disable Auto Add/Delete, starts a new path instead. Alt held over a handle end or an anchor of a selected path (the one being drawn too) works as the Anchor Point tool, with its convert cursor: dragging a handle moves it alone, clicking a smooth anchor makes it a corner, dragging an anchor pulls out new symmetric handles, dragging a segment reshapes it; drawing then goes on. Cmd (Ctrl) held drags with the selection tool chosen last, Direct Selection until one is (handles, anchors and segments of the path being drawn or another), and the Pen then goes on drawing its path while that stays selected; the pointer shows that tool's while Cmd is held. The same holds for agents (`pointer_gesture` with `mods.cmd`), as the borrowing now lives in the engine (#494).
- **Path editing (#494):** the handles shown are the handles that drag: Direct Selection drags those of a path selected as a whole (as the Pen leaves it), the Anchor Point tool and Pen+Alt no longer grab handles that Show handles when multiple anchors are selected hides, a handle shorter than the tolerance leaves its anchor to be picked, and the anchor tools pick within Selection & Anchor Display › Tolerance. A dragged segment keeps a smooth anchor at either end smooth. With Direct Selection, the Pen, the Curvature and the anchor tools, a path selected as a whole shows all its anchors selected, and the Control bar and the Properties panel offer Convert (corner, smooth) for them too; Remove and Cut wait for anchors direct-selected (#504). A handle drag gathers its snap targets once per drag (it took 21 ms per pointer move on a 20,000-path document, now 1 ms; `vectorcraft-cli perf` measures handle and segment drags on a 5,000-anchor path).
- **Graphs:** Column, Stacked Column, Bar, Stacked Bar, Line, Area, Scatter, Pie and Radar graph tools with Graph Data and Graph Type.
- **Other:** Eyedropper, Gradient annotator, Artboard (Alt-drag duplicates an artboard, and its art with Move/Copy Artwork with Artboard on; Copy, Cut and Paste take the artboard with its art, Paste right of the last artboard, Paste in Place where it was, into this or another document, #446), Measure, Type, Hand, Zoom, Rotate View.
- **Editing type:** double-clicking type with a selection tool switches to the Type tool with the caret where it was clicked.
@@ -128,15 +133,15 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist
- **Panel drag and drop:** art dragged off the canvas onto the Symbols panel becomes a symbol, onto the Swatches panel a pattern swatch and onto the Brushes panel an Art brush; a symbol dragged onto the canvas places an instance where it is dropped, and a brush dragged onto a path is applied to it.
- **Tool double-clicks:** double-clicking a tool's button opens its options: Hand fits the artboard in the window, Zoom shows 100 %, Rotate, Scale, Reflect and Shear open their Object › Transform dialogs, the Selection, Direct Selection and Group Selection tools the Move dialog (Enter opens these seven tools' dialogs too), Gradient, Eyedropper, Blend and the Liquify tools their panels or options, and the Pencil, Paintbrush, Smooth, Blob Brush and Eraser tools their Tool Options (Fidelity, fill, the tolerances, the brush size).
- **Layers panel:** every layer, sublayer, group and object is a clickable row at any depth: a click highlights it and makes its layer current (new art goes there), Shift-click a range, Ctrl/Cmd-click toggles. Sublayers are no longer treated as objects: clicks, marquees, Select All and the Select menu take the art inside them, and each sublayer selects in its own colour. Selection squares on rows with selected art (click selects a row's art, Shift adds or removes; dragging the square moves the selection to another row, Alt copies), the eye and lock on every row with drag-down-the-column (one undo step), Ctrl/Cmd-click an eye for per-layer Outline, Alt-click an eye or lock to hide or lock the other layers (again: show or unlock them all), triangles with Alt to open or close everything inside, drag and drop rows above, below or into layers and groups with a drop line (Alt copies) and a dimmed copy of the row under the pointer (dropped on the trash rows are deleted, on New Layer duplicated, as in Illustrator), inline rename, Delete key on highlighted rows. Buttons and the full panel menu: New Layer/Sublayer (Alt: options, Ctrl: on top), Duplicate, Delete, Options for Selection, clipping mask, isolation, Locate Object, Merge Selected, Flatten Artwork, Collect in New Layer, Release to Layers (Sequence and Build), Reverse Order, Template, Hide/Outline/Lock Others and Show/Preview/Unlock All, Paste Remembers Layers, Panel Options (row size, thumbnails per kind, Show Layers Only). Layer Options: name, colour (presets, each with a chip of its colour, or custom), Template, Lock, Show, Print, Preview (outline drawing and clicking) and Dim Images to %. Every operation is a command (`layer.move`, `layer.highlight`, `layer.merge`…) with validation against cycles and invalid nesting.
- **Drawing aids:** Smart Guides and snapping (moving, with the Selection, Group Selection or Direct Selection tool, and resizing by the bounding-box handles with the Selection or Free Transform tool, Shift and Alt too: the dragged corner or side lands on the other objects' anchors and centres ("anchor", "center") or lines up with their edges and centres (a line and "align"); the Rotate, Scale, Shear and Reflect tools drag from the anchor they grab and snap the pointer the same way, so a corner dragged onto another object's anchor scales exactly onto it, #482; anchors dragged with Direct Selection: the one pressed on lands on other anchors, its own path's that stay put among them, on path segments or in line with them, the others following, Shift keeps 45° steps, and with Smart Guides off Snap to Point pulls it onto anchors; the Artboard tool snaps artboards, and their bleed, to other artboards, bleeds and art, the grid or whole pixels while moving, copying and resizing them, and the Transform panel shows and edits the active artboard's X/Y/W/H), guides dragged out of the rulers (#451: they snap as moved guides do, Shift to the ruler's ticks; with the Artboard tool they are artboard guides, which run across their artboard only and move, copy and delete with it, `guide.add {artboard}`) that the Selection, Direct Selection and Group Selection tools then pick and drag (#414: the selected guides highlight and move together, Alt copies them, Shift snaps the dragged one to the ticks, otherwise it snaps to pixels, the grid or the edges, centres (so the sides' midpoints) and anchors of the art and the artboards, or with Smart Guides off Snap to Point pulls it onto anchors; the arrow keys nudge them, Delete deletes them, dragging one back onto its ruler deletes it, Lock Guides and Hide Guides leave them alone; `guide.list`, `guide.select`, `guide.move` and `guide.remove` reach agents), and Draw Normal / Behind / Inside modes.
- **Drawing aids:** Smart Guides and snapping (moving, with the Selection, Group Selection or Direct Selection tool, and resizing by the bounding-box handles with the Selection or Free Transform tool, Shift and Alt too: the dragged corner or side lands on the other objects' anchors and centres ("anchor", "center") or lines up with their edges and centres (a line and "align"); the Rotate, Scale, Shear and Reflect tools drag from the anchor they grab and snap the pointer the same way, so a corner dragged onto another object's anchor scales exactly onto it, #482; anchors dragged with Direct Selection: the one pressed on lands on other anchors, its own path's that stay put among them, on path segments or in line with them, the others following, Shift keeps 45° steps, and with Smart Guides off Snap to Point pulls it onto anchors; the Artboard tool snaps artboards, and their bleed, to other artboards, bleeds and art, the grid or whole pixels while moving, copying and resizing them, and the Transform panel shows and edits the active artboard's X/Y/W/H; drawn points, #506: hovering shows where the press goes, the point lands on the other objects' anchors, centres and paths ("anchor", "center", "path") or lines up with their anchors, edges and centres ("align"), the Pen's on the path being drawn too, near a construction guide through the anchor before it on that guide (Preferences › Smart Guides › Construction Guides and Angles), and with Shift kept to its 45° step or a square's diagonal it slides along that way into line; the targets are gathered once per document state, from the art in the window, and the anchors, centres and lines near the pointer are found by bisection, so hovering never rescans the document), guides dragged out of the rulers (#451: they snap as moved guides do, Shift to the ruler's ticks; with the Artboard tool they are artboard guides, which run across their artboard only and move, copy and delete with it, `guide.add {artboard}`) that the Selection, Direct Selection and Group Selection tools then pick and drag (#414: the selected guides highlight and move together, Alt copies them, Shift snaps the dragged one to the ticks, otherwise it snaps to pixels, the grid or the edges, centres (so the sides' midpoints) and anchors of the art and the artboards, or with Smart Guides off Snap to Point pulls it onto anchors; the arrow keys nudge them, Delete deletes them, dragging one back onto its ruler deletes it, Lock Guides and Hide Guides leave them alone; `guide.list`, `guide.select`, `guide.move` and `guide.remove` reach agents), a right-click on either ruler or the origin box to pick the document's units (the current one checked; `document.setUnits`, one undo step, #528), and Draw Normal / Behind / Inside modes.
- **Views:** the status bar's artboard navigator (first, previous, next, last; `view.goToArtboard`) goes to an artboard and fits it, and Fit Artboard in Window and Actual Size show the navigator's artboard. The Artboards panel highlights that active artboard: clicking a row makes it active (the Artboard tool's too, while it is chosen) as does clicking an artboard with the Artboard tool, double-clicking its number also fits it in the window and double-clicking its name renames it. Duplicate Artboards, or a row dragged onto New Artboard, copies the artboard with its art (#446). Escape leaves Presentation Mode, F from it goes back to Normal Screen Mode, and the screen mode isn't saved with the preferences: the app always starts in Normal Screen Mode with its menus and panels (#472).
- **Geometry and effects:**
- Pathfinder (10 exact curve booleans), Offset, Outline Stroke, Simplify, Clean Up, Split Into Grid, Divide Objects Below. Object › Path › Remove Anchor Points (`path.removeAnchors`) removes the direct-selected anchors without opening their paths (the Delete key still deletes them with their segments): the neighbours keep their handle directions and their facing handles are refitted so one cubic follows the two old segments, and straight sides stay straight. The Delete Anchor Point tool uses the same refit. The Control bar, the contextual task bar, the Properties quick actions and the canvas context menu offer it when anchors are selected. With anchors selected, the Control bar and the Properties panel also convert them to corner or smooth (`path.convertAnchors`), connect end points (Join) and cut the path at them (`path.cutAtAnchors`, also on the task bar and the context menu): a closed path opens there and an open one becomes one path per piece, each cut leaving one of its two coincident anchors selected so a drag pulls the path apart.
- Live effects with previewing dialogs: Distort & Transform, Path, Convert to Shape, 15 Warp styles, Round Corners, Scribble, Effect → Pathfinder (all 10 operations, live on groups; several loose objects are grouped first, in one undo step), Color Adjustments (Brightness/Contrast, Curves, Levels, Hue/Saturation, Shift to Color, Temperature/Tint, on vectors, live type and embedded images), and raster drop shadow, glows and feather. SVG and PDF export keep live effects (geometry baked; SVG raster effects as filters).
- **Type:** Text Wrap, Type on a Path effects (Rainbow/Skew/3D Ribbon/Stair Step/Gravity) and Options (Flip, Align to Path, Spacing; OK keeps the type where it is), type on a path's start, centre and end brackets (Selection and Direct Selection drag them to set where the type runs, slide it along its path and, across the path, flip it: #429), Character and Paragraph Styles (override-preserving redefine), Area Type Options (rows/columns/inset/first baseline), threaded text across any closed shapes, Fit Headline. Area type resizes like Illustrator's type areas: a bounding-box handle drag (Selection tool) or Area Type Options Width/Height size the frame and the text reflows at its size (threads too); Direct Selection drags a frame corner or edge (`text.reshapeArea`). Point type still scales. The Selection tool shows the type widget beside selected type's bounding box (hollow on point type, filled on area type); double-clicking it converts between them (Type › Convert To Area Type / Convert To Point Type), keeping the text and its styles in place. Variable fonts list every named instance as a style of their family (Figtree Light to Black and their italics, Bahnschrift, Segoe UI Variable), and the instance chosen is shaped, drawn, outlined and measured at its axis settings; PDF and SVG embed it as that instance. Variation axis sliders are not done. Hebrew and Arabic are laid out right to left with the Unicode bidirectional algorithm (embedded Latin and numbers keep their direction, lines put in visual order after wrapping) in point, area and path type, with caret, selection and arrow keys in visual order; each paragraph's direction comes from its first strong character unless Paragraph Direction sets it (Paragraph panel with Show Indic Options, `text.setFormat {direction}`), and new type aligns to the start of its direction. SVG export outlines right-to-left text. Font Size and Leading are combo boxes in the Character and Properties panels (Font Size in the Control bar too, beside the Character link, font family and style): type, step with ↑/↓ or the spinner, scrub the label, or pick a preset (6–72 pt, shown in the type unit; Leading also Auto), each pick one undo step; Kerning and Tracking list -100…200; a size, leading, kerning or tracking the selected text doesn't share shows blank (#458).
- **Interface languages, vertical type:** VectorCraft ▸ Language (or Preferences ▸ User Interface) picks Automatic (the system locale) or a registered language, persisted as `interfaceLanguage`. Translations come from per-language catalogs (`i18n/*.tsv`): Traditional and Simplified Chinese, Japanese and Spanish (neutral international Spanish, for every `es-*` locale) cover the whole interface, Czech and Brazilian Portuguese every menu label, Brazilian Portuguese the shell's `tl!` literals too (tested); Spanish also translates status-bar and error messages as they are shown (`@msg` templates, every message literal tested; the messages themselves stay English for agents); untranslated text stays English. Japanese and Chinese glyphs come from the craft-fonts build input (release builds) or the installed fonts, Czech and Spanish ones from the bundled UI fonts. The web app follows the browser's languages (or `?lang=`). The Basic toolbar's Type button holds Vertical Type in its flyout. Vertical Type, Vertical Area Type and Vertical Type on a Path create vertical text (columns right to left, upright CJK glyphs and marks with `vert` alternates, Latin and longer numbers on their side, two- and three-digit numbers set as tate-chu-yoko in one em of the column (kept whole when justified), upright glyphs centred on the column (tracked or justified too), point type's anchor on the first column's centre line); kinsoku (the strict set) applies to horizontal and vertical Japanese, and justified Japanese lines spread their room between characters (not inside Latin words); Paragraph panel › Mojikumi Set (shown with Preferences › Type › Show East Asian Options, `text.setFormat {mojikumi}`): None or Line-end Punctuation Half Width (new type's default, as in Illustrator; older documents and imported text keep None) shares one half-em space between consecutive punctuation, sets a closing mark ending a line half width and an opening bracket starting a wrapped line flush with its start, and puts a quarter em between Japanese and Latin letters or digits; Paragraph panel menu › Top-to-Top / Bottom-to-Bottom Leading measures leading from em box top to top (area type's first line touches the frame) or from baseline to baseline; Paragraph panel menu › Burasagari None / Regular / Force (`text.setFormat {burasagari: "none"|"standard"|"forced"}`) hangs an East Asian comma or full stop (、。,.、。) ending an area type line outside it, Regular (new type's default) when it doesn't fit and Force always (the rest of the line then fills the measure; closing brackets and Latin punctuation don't hang); Character panel menu › Character Alignment (with the East Asian options; `text.setFormat` or `text.setRangeStyle {charAlign}`) lines characters smaller than the largest on their line up on the Roman baseline or the em box top/right, centre or bottom/left (ICF top and bottom not yet); Type ▸ Type Orientation switches existing text; caret, selection, hit testing and arrow keys follow the writing direction. Vertical text exports to PDF as real text and to SVG as outlines.
- **Interface languages, vertical type:** VectorCraft ▸ Language (or Preferences ▸ User Interface) picks Automatic (the system locale) or a registered language, persisted as `interfaceLanguage`. Translations come from per-language catalogs (`i18n/*.tsv`): Traditional and Simplified Chinese, Japanese, Spanish (neutral international Spanish, for every `es-*` locale) and Italian (every `it-*` locale) cover the whole interface, Czech and Brazilian Portuguese every menu label, Brazilian Portuguese the shell's `tl!` literals too (tested); Spanish and Italian also translate status-bar and error messages as they are shown (`@msg` templates, every message literal tested; the messages themselves stay English for agents); untranslated text stays English. Japanese and Chinese glyphs come from the craft-fonts build input (release builds) or the installed fonts, Czech, Spanish and Italian ones from the bundled UI fonts. The web app follows the browser's languages (or `?lang=`). The Basic toolbar's Type button holds Vertical Type in its flyout. Vertical Type, Vertical Area Type and Vertical Type on a Path create vertical text (columns right to left, upright CJK glyphs and marks with `vert` alternates, Latin and longer numbers on their side, two- and three-digit numbers set as tate-chu-yoko in one em of the column (kept whole when justified), upright glyphs centred on the column (tracked or justified too), point type's anchor on the first column's centre line); kinsoku (the strict set) applies to horizontal and vertical Japanese, and justified Japanese lines spread their room between characters (not inside Latin words); Paragraph panel › Mojikumi Set (shown with Preferences › Type › Show East Asian Options, `text.setFormat {mojikumi}`): None or Line-end Punctuation Half Width (new type's default, as in Illustrator; older documents and imported text keep None) shares one half-em space between consecutive punctuation, sets a closing mark ending a line half width and an opening bracket starting a wrapped line flush with its start, and puts a quarter em between Japanese and Latin letters or digits; Paragraph panel menu › Top-to-Top / Bottom-to-Bottom Leading measures leading from em box top to top (area type's first line touches the frame) or from baseline to baseline (new type in a Japanese interface starts top to top, with em box centre character alignment, #432); Paragraph panel menu › Burasagari None / Regular / Force (`text.setFormat {burasagari: "none"|"standard"|"forced"}`) hangs an East Asian comma or full stop (、。,.、。) ending an area type line outside it, Regular (new type's default) when it doesn't fit and Force always (the rest of the line then fills the measure; closing brackets and Latin punctuation don't hang); Character panel menu › Character Alignment (with the East Asian options; `text.setFormat` or `text.setRangeStyle {charAlign}`) lines characters smaller than the largest on their line up on the Roman baseline or the em box top/right, centre or bottom/left (ICF top and bottom not yet); Type ▸ Type Orientation switches existing text; caret, selection, hit testing and arrow keys follow the writing direction. Vertical text exports to PDF as real text and to SVG as outlines.
- **Transparency:** opacity masks (clip/invert/disable/link), exported as SVG `<mask>` and PDF soft masks.
- **Advanced art:** live Blends (steps/distance/smooth colour, editable spine, anchor-targeted Blend tool, faithful interpolation, knockout), Envelope Distort (warp/mesh/top object, Reset, full Envelope Options, mesh handles, Edit Contents; type, images, symbols, gradients, patterns and appearance distorted everywhere), Liquify tools with options and pen pressure, Puppet Warp with rotating pins, Perspective Grid with presets, movable planes and projected type (choosing a perspective tool shows the grid; Hide Grid hides it with the tool still chosen), Gradient Mesh, Shape Builder (stroke-only open paths and lines cut the regions they cross and enclose regions of their own; filled open paths count as closed; erase mode while Alt/Option is held: a minus pointer, red highlights of what will go, a click or drag deletes the regions touched, the pieces of open lines and the edges (outline pieces between the points where paths meet, opening their paths there) it passes over, one undo step, `shapeBuilder.merge {erase}` and `shapeBuilder.regions` edges over MCP), Live Paint (every path an edge, open lines included), Image Trace (12 presets; with an image selected the Control bar and the Properties panel show Image Trace, whose arrow traces with any preset, Mask (`object.maskImage`: a clipping path on the image's outline, selected so its handles crop), Crop Image and Embed or Unembed in place of Fill and Stroke; with an Image Trace object selected, its Preset (choosing another traces again), the Image Trace panel and Expand, plus Release in Properties; the View modes are not done), pattern swatches with pattern editing mode, live Repeat (radial/grid/mirror).
- **Advanced art:** live Blends (steps/distance/smooth colour, editable spine, anchor-targeted Blend tool, faithful interpolation, knockout), Envelope Distort (warp/mesh/top object, Reset, full Envelope Options, mesh handles, Edit Contents; type, images, symbols, gradients, patterns and appearance distorted everywhere), Liquify tools with options and pen pressure, Puppet Warp with rotating pins, Perspective Grid with presets, movable planes and projected type (choosing a perspective tool shows the grid; Hide Grid hides it with the tool still chosen), Gradient Mesh, Shape Builder (stroke-only open paths and lines cut the regions they cross and enclose regions of their own; filled open paths count as closed; erase mode while Alt/Option is held: a minus pointer, red highlights of what will go, a click or drag deletes the regions touched, the pieces of open lines and the edges (outline pieces between the points where paths meet, opening their paths there) it passes over, one undo step, `shapeBuilder.merge {erase}` and `shapeBuilder.regions` edges over MCP), Live Paint (every path an edge, open lines included), Image Trace (12 presets, colour layers traced in parallel; a trace past two million anchor points or an image over 64 megapixels is refused with advice rather than running out of memory, and a selection too large to outline shows its bounds (#525); Object › Image Trace › Make and Make and Expand trace at once with the Default preset, #543; with an image selected the Control bar and the Properties panel show Image Trace, whose arrow traces with any preset, Mask (`object.maskImage`: a clipping path on the image's outline, selected so its handles crop), Crop Image and Embed or Unembed in place of Fill and Stroke; with an Image Trace object selected, its Preset (choosing another traces again), the Image Trace panel and Expand, plus Release in Properties; the View modes are not done), pattern swatches with pattern editing mode, live Repeat (radial/grid/mirror).
- **Paint and appearance (M3):**
- **Swatches:** names follow the colour model and are unique; Swatch Options (process/spot, Global, Gray/RGB/HSB/CMYK/Web, live preview); editing a global or spot swatch recolours every linked fill, stroke and text run in one undo step; multi-select and delete with confirmation; New Swatch and New Color Group dialogs (a group from the selected artwork's colours); swatches in colour groups convert, separate and count like any other. The Swatches panel selects ranges and whole groups, has a find field, and drags swatches to reorder, regroup or paint art; Add Used Colors, Select All Unused, Merge, Ungroup and Sort by Kind; a CMYK document keeps applied colours in CMYK. Swatch libraries: nine generated colour libraries and five gradient libraries in a library panel, saved and loaded as `.vcswatches`, `.gpl` or CSS. Tints of global and spot colours ("Name 40%") stay linked and separate as a percentage of their plate. Spot colours can be defined in Lab (Spot Colors options). A built-in [Registration] swatch prints on every plate.
- **Colour:** a Color Picker (colour field, H/S/B/R/G/B channel slider, HSB/RGB/Lab/CMYK fields, hex, web-only snapping, out-of-gamut correction); the Color panel follows each colour's own model and Alt-click paints the other proxy; proxies look through groups and show "?" for mixed paint; Invert, Complement, Apply Last Color (`,`) and Apply Last Gradient (`.`) keep the colour model; every paint command feeds the recent colours. The Color Guide has 21 harmony rules, Steps and Variation options and Limit to Library. Adjust Color Balance (its Global mode shifts tints) and Saturate preview live; Edit Colors and Recolor also reach meshes, images and patterns. Recolor Artwork has colour reduction, five recolour methods, presets, Limit to Library, a colour-wheel Edit tab and Edit Color Group; a local Color Themes panel saves five-colour themes. Fill/Stroke chips open swatch and mixer popovers (the Properties panel has the Control bar's Fill and Stroke chips, Stroke link and weight spinner, with nothing selected too), panels have Illustrator's Window menu keys (Align Shift+F7, Transform Shift+F8, Pathfinder Cmd+Shift+F9, Layers F7, Character Cmd+T…; every panel can be given one in Edit › Keyboard Shortcuts), and Eyedropper Options pick up and apply chosen attributes (Alt and Shift+Alt, image pixels). Fills and strokes can overprint (Attributes panel, Overprint Black options), and CMYK documents blend in inks on screen, in PDF and when flattening. Document Color Mode converts the art, symbols, pattern tiles and swatches through the colour settings: Gray stays Gray, RGB greys separate into four-colour greys and a rich black as Illustrator does, or go on the black plate only with `grays: "black"` (also for `document.open {colorMode}`).
@@ -151,11 +156,12 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist
- **Fonts:** a font is found by any of its names (family and style in every language of its name table, legacy family/style pairs, PostScript name), so documents from other apps open with the font they name; Find Font and `text.fonts` say for each font whether it was found exactly, by another name, substituted or missing, and how many glyphs are missing. PDF and `.ai` import brings Japanese text back as live type: CID fonts without a ToUnicode map read through the standard CMaps, vertical columns (WMode 1) as vertical type, letter spacing as tracking; a glyph is live type only when the installed font (in the closest style of its family) draws the same glyph, and text in a font that isn't installed comes in as live type shown in the fallback font until the font is installed (exports that draw it — PDF, EPS, EMF/WMF, raster, SVG outlines or embedded fonts — warn that they wrote the fallback font; `textAs: outlines` keeps the PDF's embedded glyphs).
- **Files (M4):**
- `.vectorcraft` (lossless JSON, compressed, atomic saves, save down to v1), Save As with a format chooser, Save a Copy, Revert, templates, Data Recovery after a crash (browser tabs hold their copies with Web Locks too, so a background tab's copies are never taken for a crash's, and a tab repairs copies another removed when it resumes: #367), background save and export. The desktop app writes its warnings and errors (graphics adapter, a lost graphics device, panics the guard recovered from) to standard error and to `logs/vectorcraft.log` next to the preferences, the two previous runs kept and each file capped at 16 MiB, so a launch without a terminal still leaves something to attach to a bug report (#465).
- SVG/SVGZ in and out with SVG Options, Preserve Editing, symbols, filters, rich text and physical units (SVG type under a transform or `viewBox` scale opens at the size it draws at, the scale moved into its size, leading, baseline shift and strokes, a stretch, skew or rotation kept as its transform: #396; a top-level group with a clip path, such as a clipped Inkscape layer, opens as a layer with a clipping mask, its name kept: #420); PDF and PDF-compatible `.ai` in and out (layers, with hidden ones kept hidden with their art and nested ones as sublayers, on pages of up to 64 million operators, art whose layer can't be told going to a hidden, non-printing layer rather than showing or printing: #419; strokes kept live, a fill and a stroke of one outline as one object; masks, editable text with type set along a curve coming back as type on a path, each artboard's art on its own page only, an `.ai`'s white page under its layers left out rather than coming in as art, spot colours, presets, security, marks and bleed, ICC output intents, raster effects, subset fonts, PDF/X, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3). CMYK images keep their ink amounts from PDF import (and from placed CMYK TIFFs) to PDF export: a CMYK JPEG passes through unchanged, others stay CMYK (DeviceCMYK, or ICC-based CMYK in PDF/X-3/X-4) unless the Output settings convert them; the canvas shows them through the working CMYK profile (#320).
- EPS and DXF in and out, EMF/WMF in and out; PNG (with PNG-8), JPEG, WebP, GIF, TIFF, BMP, Targa and layered PSD export. EPS import runs Illustrator's AGM/CoolType prologs (resource categories, `resourceforall`, `clipsave`/`cliprestore`, subarrays and substrings that share storage, the standard dictionaries in `systemdict`, `dictstack`, `internaldict`, executable filters, `cshow`, metadata skipped with `flushfile`), so Illustrator 30 EPS files open as vectors. It also runs what other generators write (Discord feedback, #466, #469): Illustrator 2026's procsets (`gcheck`, `rootfont`, `currentcolorrendering`: every Illustrator 2026 EPS fell back to its preview before), cairo/Inkscape (`status`/`flushfile`, images with a mask, `ImageType 3`, reusable streams), matplotlib's Type 3 fonts, Illustrator 8 EPS (stock art's usual format: executable strings such as its gradients' `ed`, `load` by integer keys, #474), Ghostscript's `//name` immediate names, `pdfmark`, `token`, `execform` and user paths. Tiling patterns come in as pattern swatches, uncoloured ones too; Type 3 fonts' glyphs as their outlines, spaced by `ashow`/`widthshow`/`xshow`/`kshow`; mesh and function-based shadings (types 1, 4–7) as gradient meshes; sampled functions (type 0) and Flate/LZW predictors are read. When a file's PostScript still can't be read, it opens as its TIFF preview, its Windows metafile preview (as vectors) or its EPSI preview, and the warning (in the status bar, `document.open`/`app.open`/MCP `open_file` replies and `vectorcraft-cli info`) names the error, the operator that raised it and the procedures it ran in. Legacy PostScript `.ai` files (Illustrator 3–8, written with the prolog that defines their operators) keep their groups and nested groups (`u` … `U`), between and inside clipping groups; EPS and EMF/WMF import nest clips (and groups) at most 128 deep, so a hostile file can't exhaust the stack. DXF TEXT justified Fit or Aligned spans its two points (stretched, or scaled as a whole).
- Place and the Links panel, Package, File Info, Print with print presets, PostScript output and print tiling, slices and Save for Web, Export for Screens and Asset Export, CSS Properties, PNG/PDF/SVG/text clipboard flavours; files copied in a file manager paste as art (SVG, PDF, EMF/WMF, bitmaps) on every desktop platform, and Linux/Wayland reads the compositor's clipboard (#398); screenshots and other copied pictures paste as embedded images at the view centre everywhere, the web included (#457).
- SVG/SVGZ in and out with SVG Options, Preserve Editing, symbols, filters, rich text and physical units (SVG type under a transform or `viewBox` scale opens at the size it draws at, the scale moved into its size, leading, baseline shift and strokes, a stretch, skew or rotation kept as its transform: #396; a top-level group with a clip path, such as a clipped Inkscape layer, opens as a layer with a clipping mask, its name kept: #420); PDF and PDF-compatible `.ai` in and out (layers, with hidden ones kept hidden with their art and nested ones as sublayers, on pages of up to 64 million operators, art whose layer can't be told going to a hidden, non-printing layer rather than showing or printing: #419; strokes kept live, a fill and a stroke of one outline as one object; a type object's stroke written as each glyph's outline stroked back on the type, so it stays one editable object; lines wrapped in a frame (each wrapped line ending in a space, one left edge, leading and font) back as one area type object, left aligned or justified with its paragraph spacing, where laying it out breaks the lines where the file does; glyphs set apart by gaps wider than a space (a barcode's digit groups) keeping their places; layers stacked as the pages mark them even when one first paints on a later page, art ending a layer's marked content or a clip closing in a later layer kept in its own layer, and layers with no art kept empty: #508; masks, editable text with type set along a curve coming back as type on a path, each artboard's art on its own page only, an `.ai`'s white page under its layers left out rather than coming in as art, spot colours, presets, security, marks and bleed, ICC output intents, raster effects, subset fonts, PDF/X, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3). CMYK images keep their ink amounts from PDF import (and from placed CMYK TIFFs) to PDF export: a CMYK JPEG passes through unchanged, others stay CMYK (DeviceCMYK, or ICC-based CMYK in PDF/X-3/X-4) unless the Output settings convert them; the canvas shows them through the working CMYK profile (#320).
- EPS and DXF in and out, EMF/WMF in and out; PNG (with PNG-8), JPEG, WebP, GIF, TIFF, BMP, Targa and layered PSD export. EPS import runs a PostScript Level 3 interpreter written from the PostScript Language Reference: resource categories and `resourceforall`, local and global VM (`currentglobal`/`setglobal`/`gcheck`), `clipsave`/`cliprestore`, subarrays and substrings that share storage, the standard dictionaries in `systemdict`, `dictstack`, `internaldict`, executable filters and strings, `load` by any key, `//name` immediate names, `token`, `execform`, user paths, `cshow`, `rootfont`, `cachestatus`, colour rendering and halftone queries, file `status` and data read with `flushfile`, and `pdfmark` marks dropped (Discord feedback, #466, #469, #474). Masked images (`ImageType 3` in its three interleavings) and reusable streams are read, and an image's several data sources are read in turn, as the reference defines (procedures that read one file get their own rows: such images came in banded, #498). `restore` puts dictionaries back as they were at the `save`, so programs that count their saves in a dictionary read to their end (part of #505). Tiling patterns come in as pattern swatches, uncoloured ones too; Type 3 fonts' glyphs as their outlines, spaced by `ashow`/`widthshow`/`xshow`/`kshow`; mesh and function-based shadings (types 1, 4–7) as gradient meshes; sampled functions (type 0) and Flate/LZW predictors are read. It is tested with programs written from the specification in the ways common generators use these features; Inkscape/cairo EPS files open as vectors. When a file's PostScript still can't be read, it opens as its TIFF preview, its Windows metafile preview (as vectors) or its EPSI preview, and the warning (in the status bar, `document.open`/`app.open`/MCP `open_file` replies and `vectorcraft-cli info`) names the error, the operator that raised it and the procedures it ran in. Legacy PostScript `.ai` files (Illustrator 3–8, written with the prolog that defines their operators) keep their groups and nested groups (`u` … `U`), between and inside clipping groups; EPS and EMF/WMF import nest clips (and groups) at most 128 deep, so a hostile file can't exhaust the stack. DXF TEXT justified Fit or Aligned spans its two points (stretched, or scaled as a whole).
- Placed documents: File › Place of a `.vectorcraft` file links to it by default (`file.place`'s `link`): one locked object showing an artboard of the document (or its art's bounds), read the way placing it without Link reads it, its symbols, patterns and images kept apart from the document's; without Link (or from bytes, not a file) it is an editable copy as before. It stays vectors in every output (SVG, PDF, EPS, EMF, DXF), and so do placed documents inside it, read from their own files up to 8 levels deep (documents that place each other stop there). On screen they draw from bitmaps cached per file and zoom step, shared by every copy and made in the background (a placeholder until ready), so a sheet of them redraws in about a millisecond; exports and prints draw them exactly. Like linked images, a save keeps only a preview of each (JPEG when opaque) unless Include Linked Files; output, and zooming past the preview, read the file again, falling back to the preview with a warning when it is gone or changed. Saves for older versions write them as plain art. Links check, update, relink, Update Links on open, Link Info (the artboard's size), Placement Options, Break Link (also Embed, Object › Expand: the editable copy placing without Link gives, its resources joining the document), Edit Original (the document in a new tab) and the Links panel cover them; saving a document updates the open documents that place it. The native format (v4) keeps data of 8 KB or more after the JSON instead of base64 in it.
- Place and the Links panel, Package, File Info, Print with print presets, PostScript output and print tiling, slices and Save for Web, Export for Screens and Asset Export, CSS Properties, PNG/PDF/SVG/text clipboard flavours; files copied in a file manager paste as art (SVG, PDF, EMF/WMF, bitmaps) on every desktop platform, and Linux/Wayland reads the compositor's clipboard (#398); on Linux the Paste menu checks the clipboard off the UI thread, so an X11 owner that never answers can't freeze the window (#510); screenshots and other copied pictures paste as embedded images at the view centre everywhere, the web included (#457).
- **Performance:** 20k shapes + 1k texts render in 27 ms per full-retina frame (7.8 ms zoomed), 7× faster than the first version. The UI thread never blocks. The web build is 7.1 MB gzipped.
- **Graphics processor:** the canvas is rasterized on the CPU and the GPU only composites it, so the desktop app asks for the power-saving GPU by default (the integrated one on hybrid-graphics laptops, where presenting from the discrete GPU made the window flicker, #306). Preferences › Performance › Graphics Processor (`gpuPreference`) or `WGPU_POWER_PREF` picks the discrete one; Help › About and `ui.inspect` name the adapter in use. When the browser drops the page's WebGPU device or WebGL context, the web build writes recovery copies, starts again on new graphics with the same app and uploads its textures again; if it can't, it removes the stale canvas and says to reload, which offers the copies back. The desktop app writes the copies and says to restart (#369). On Windows and Linux the tools' cursors are OS cursors (bitmaps rasterized once per display scale), which the system moves itself: painted into the window, they trailed the pointer by the frames waiting to be shown, and the window now queues one frame instead of two (#444). macOS and the web still paint them (macOS sizes cursor bitmaps in points, eframe has no bitmap cursors on the web). Pens and touch drive the tools as the mouse does, and a tap pressed and lifted within one frame clicks where it tapped (#491); pen pressure reaches the Liquify tools' Use Pressure Pen on Windows, while winit 0.30 reports none on macOS or Linux and egui none on the web. On Linux, see `docs/development.md` for pens under Wayland.
- **Graphics processor:** the canvas is rasterized on the CPU and the GPU only composites it, so any GPU that can show the window will do. Preferences › Performance › Graphics Processor (`gpuPreference`) is Automatic by default: the power-saving GPU on Windows and macOS (the integrated one on hybrid-graphics laptops, where presenting from the discrete GPU made the window flicker, #306), and the GPU the desktop runs on under Linux, where KWin on an NVIDIA GPU refused frames from a Ryzen's integrated GPU and 0.5.0 crashed at startup (#502). Power Saving and High Performance pick a kind of GPU; `WGPU_POWER_PREF`, `WGPU_ADAPTER_NAME` and `WGPU_BACKEND` override them. The app picks among the adapters that can present to the window (native backends before OpenGL, hardware before software, and on Windows a GPU's DX12 adapter before its Vulkan one: Intel's Vulkan driver made the whole window flicker black, #545), and if the window fails on one while starting up it starts again without it instead of crashing; Help › About, `ui.inspect` and the log name the adapter in use. When the browser drops the page's WebGPU device or WebGL context, the web build writes recovery copies, starts again on new graphics with the same app and uploads its textures again; if it can't, it removes the stale canvas and says to reload, which offers the copies back. The desktop app writes the copies and says to restart (#369). On Windows and Linux the tools' cursors are OS cursors (bitmaps rasterized once per display scale), which the system moves itself: painted into the window, they trailed the pointer by the frames waiting to be shown, and the window now queues one frame instead of two (#444). macOS and the web still paint them (macOS sizes cursor bitmaps in points, eframe has no bitmap cursors on the web). Pens and touch drive the tools as the mouse does, and a tap pressed and lifted within one frame clicks where it tapped (#491); pen pressure reaches the Liquify tools' Use Pressure Pen on Windows, while winit 0.30 reports none on macOS or Linux and egui none on the web. On Linux, see `docs/development.md` for pens under Wayland.
- **Tests and robustness:** ~2,840 automated tests: model-based property tests, a junk-parameter sweep over every command, import fuzzing (SVG, PDF, libraries), golden renders, and MCP end-to-end tests over stdio. Shipped code never panics (workspace lints and a rollback safety net; see `docs/development.md`).
## Milestones and estimates
@@ -164,7 +170,7 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist
|---|---|---|---|
| M0 | Skeleton + vertical slice | ✅ done | — |
| M1 | Selection, transform, layers, MCP | ✅ mostly done (transform reference point snaps to anchors/centres; rotated objects keep a rotated bounding box and their angle; Free Transform, Scale and Reflect along a rotated box pending) | 4–6 |
| M2 | Drawing tools + smart guides | ✅ mostly done (Flare, Reshape, Live Corners widget dragging and per-corner radii and kinds landed; Shaper, the remaining Pen modifier nuances) | 15–20 |
| M2 | Drawing tools + smart guides | ✅ mostly done (Flare, Reshape, Live Corners widget dragging and per-corner radii and kinds landed, on any path's corners; Shaper, the remaining Pen modifier nuances) | 15–20 |
| M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Color Picker, Color panel, Color Guide, Color Themes, Edit Colors and Recolor Artwork; gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool, Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries. Left: freeform and mixed spot/process gradients export as stops or process colours to SVG/PDF; confirm the Scale Strokes & Effects default | 4–8 |
| M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out, EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, Asset Export, clipboard flavours, File Info. Left: DWG (use DXF), PSD placement as layers, overprint read back from PDF, polish | 3–6 |
| M5 | Performance | 🟡 background render + caches + MT done; `vectorcraft-cli bench` and `vectorcraft-cli perf` (budget suite); file format v2 opens 3× faster (50k paths: 722 → 244 ms); raster effects (glows, shadows, blur, feather) no longer force the whole frame single-threaded (filtered offscreen per effect, verified equal to the single-threaded reference); effect-heavy demos need a clean-machine benchmark; dirty-region rendering, GPU backend spike pending | 15–25 |
@@ -176,7 +182,7 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist
| M11 | Artboards & views (artboard panel/tool, Trim View, middle-button pan, print tiling and the status bar's artboard navigator done; multiple windows, presentation polish) | 🟡 | 15–25 |
| M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (12 presets, 18 ms/1k² image), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, regenerate in place) done; graph Design/Column/Marker designs pending | 6–10 |
| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 | 18–27 |
| M14 | 1.0 polish (preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) | 🟡 Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed), workspaces, a custom title bar on Windows/Linux with a Home button, content-sized dialogs and menus that scroll when longer than the window done; an experimental, unsupported Windows 7 x64 portable OpenGL build (not verified by maintainers); accessibility and broader Windows/Linux packaging/QA pending | 18–28 |
| M14 | 1.0 polish (preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) | 🟡 Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed), workspaces, a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8); an experimental, unsupported Windows 7 x64 portable OpenGL build (not verified by maintainers); accessibility and broader Windows/Linux packaging/QA pending | 18–28 |
| — | Interaction fidelity pass (every tool's modifiers, Properties panel per context, isolation, nuance) | ⬜ | 60–90 |
| — | Hardening at scale (big-file corpus, fuzzing, cross-platform + browser QA) | 🟡 | 50–80 |
| | **Total to full parity** (one agent; re-derived from the [Parity estimate](#parity-estimate) table) | | **~320–500** |
@@ -196,7 +202,7 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale)
| Area | Weight | Done | Missing (main items) | One agent (h) |
|---|---:|---:|---|---:|
| Selection, transform & align tools | 6 | 85% | Free Transform/Scale/Reflect along a rotated box, Start Global Edit, transform nuances (the rotated persistent bounding box is done) | 4–6 |
| Drawing tools | 7 | 85% | Shaper Groups (merge/punch overlapping shapes), pencil and the remaining pen modifier nuances, the freehand Tool Options' Keep selected, Alt to the Smooth tool, Blob Brush Merge Only with Selection and brush angle/roundness, Touch Type, Live Corners on plain paths and polygons (and Relative rounding) | 10–15 |
| Drawing tools | 7 | 85% | Shaper Groups (merge/punch overlapping shapes), pencil and the remaining pen modifier nuances, the freehand Tool Options' Keep selected, Alt to the Smooth tool, Blob Brush Merge Only with Selection and brush angle/roundness, Touch Type, Live Corners on corners between curved sides (and Relative rounding) | 10–15 |
| Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 86% | Live Paint gap options, Shape Builder gap detection, options (Tool Options dialog, clicking a stroke in merge mode) and Shift-drag marquee | 3–6 |
| Colour, swatches, gradients, patterns, mesh, recolor | 7 | 96% | freeform and mixed spot/process gradients in SVG/PDF (exported as stops or process colours), pattern fills in Expand | 2–4 |
| Strokes, brushes, width profiles | 5 | 88% | brush options depth, brush libraries (generated in code), brushes driven by pen tilt, bearing and barrel rotation (6D art pens) | 12–20 |
@@ -210,13 +216,13 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale)
| Image Trace, graphs, image tools | 3 | 70% | graph Design/Column/Marker, Create Object Mosaic, Crop Image polish (an on-canvas crop box), Image Trace View modes (Outlines, Source Image) (Vector Halftone is done) | 6–10 |
| Layers, artboards, document setup | 5 | 82% | Layers panel: a confirmation before deleting layers that hold art, Collect for Export, row context menus, the Layer Options dialog for several rows with mixed values, Paste Remembers Layers for sublayers, drag-scrolling a long panel while dragging rows; artboard presets/rearrange polish (Document Setup, New Document and the rest of the Layers panel are done) | 4–7 |
| View & navigation | 3 | 70% | New View/Edit Views, multiple windows/arrange, Snap to Pixel/Glyph (print tiling is done) | 9–14 |
| Guides, grids, smart guides, snapping, rulers | 3 | 82% | global/video rulers, smart-guide preference depth, Alt swapping a ruler guide's orientation, ruler guides selected together with art (marquee, Shift-click), ruler guides as Layers rows with their own lock and hide (#451: Lock Guides locks them all; Make Guides paths are Layers rows already) (dragging existing guides is done, #414; new guides snapping to side midpoints and artboards, and artboard guides, #451) | 3–5 |
| File formats | 6 | 85% | DWG (no open spec: DXF instead), PSD placement as layers, EPS checked against more real files (Illustrator 2026 and Inkscape files open as vectors; CorelDRAW, Affinity, LibreOffice, matplotlib and Ghostscript output checked with synthetic programs only; CID-keyed CJK type and `CCITTFaxDecode` images not read), legacy `.ai` files saved without the prolog that defines their operators (their own operator set isn't read yet), the remaining fidelity polish; EPS, DXF, EMF/WMF, TIFF, BMP, Targa, PSD export, SVGZ, PDF security, PDF/X, PDF layers and presets are done | 6–10 |
| Guides, grids, smart guides, snapping, rulers | 3 | 84% | global/video rulers, Spacing Guides, Smart Guides' angle and distance readouts while drawing, Alt swapping a ruler guide's orientation, ruler guides selected together with art (marquee, Shift-click), ruler guides as Layers rows with their own lock and hide (#451: Lock Guides locks them all; Make Guides paths are Layers rows already) (dragging existing guides is done, #414; new guides snapping to side midpoints and artboards, and artboard guides, #451; the drawing tools snapping, with Construction Guides, #506) | 2–4 |
| File formats | 6 | 85% | DWG (no open spec: DXF instead), PSD placement as layers, EPS checked against more real files users send (Inkscape files open as vectors; other generators' constructs are tested with programs written from the PostScript Language Reference only; CID-keyed CJK type and `CCITTFaxDecode` images not read), legacy `.ai` files saved without the prolog that defines their operators (their own operator set isn't read yet), the remaining fidelity polish; EPS, DXF, EMF/WMF, TIFF, BMP, Targa, PSD export, SVGZ, PDF security, PDF/X, PDF layers and presets are done | 6–10 |
| Export for Screens, Asset Export, slices, Save for Web | 3 | 85% | polish only (all four are done) | 2–4 |
| Print, colour management, separations, flattener | 3 | 80% | print preview fidelity (flattener presets in PDF and print, overprint in PDF and composite print, Print dialog, presets, PostScript, marks, separations, Print Tiling, print overprint/flattener/bitmap options and printer profile are done) | 1–2 |
| Automation | 3 | 60% | Variables (data merge), scripting surface, batch | 8–12 |
| UI chrome (panels, contextual Properties, workspaces, prefs) | 6 | 78% | Variables, SVG Interactivity, Properties per context, Consolidate All Windows, context menus beyond the canvas (Links, Asset Export, CSS Properties, Attributes and the canvas context menu are done), about 35 Preferences options stored but not yet acted on (#394: Construction and Spacing Guides, Auto Size New Area Type, Show Font Names in English, Highlight Alternate Glyphs, performance, devices…) | 14–22 |
| Libraries, Links, Package | 2 | 50% | a local Libraries panel (no cloud by design); Links and Package are done | 5–8 |
| UI chrome (panels, contextual Properties, workspaces, prefs) | 6 | 78% | macOS native menu dismissal fixed (M14.8); remaining: Variables, SVG Interactivity, Properties per context, Consolidate All Windows, floating panels outside the app window and docked into any group, context menus beyond the canvas (Links, Asset Export, CSS Properties, Attributes and the canvas context menu are done), about 30 Preferences options stored but not yet acted on (#394: Spacing Guides, Auto Size New Area Type, Show Font Names in English, Highlight Alternate Glyphs, performance, devices…) | 14–22 |
| Libraries, Links, Package | 2 | 50% | a local Libraries panel (no cloud by design); Links and Package are done; placed VectorCraft documents are done (linked by default, vectors in every output, previews, Break Link, Expand, Edit Original, refresh on save) | 5–8 |
| **Feature parity** | **103** | **~75%** | | **~210–330** |
| Interaction-fidelity pass (side by side with Illustrator: every tool modifier, cursor, dialog, Properties context) | | | | 60–90 |
| Hardening (big-file corpus, fuzzing, cross-platform and browser QA, accessibility, packaging) | | | | 50–80 |
@@ -235,7 +241,7 @@ lossless SVG/PDF export of live effects with SVG filters, a documented JSON form
command, gesture and dialog drivable by agents (MCP, CLI, control channel).
## Out of scope (by design or by law)
- **Native `.ai` private data:** it's undocumented. We read the PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Art off the page that a PDF does draw opens on the pasteboard.
- **Native `.ai` private data:** it's undocumented. We read the PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard.
- **Adobe cloud services** (Libraries sync, Adobe Fonts, Firefly/generative): these are pluggable provider APIs, not built in.
- **Adobe's bundled assets** (swatch/brush/symbol libraries, presets, icons): ours are original.
+52
View File
@@ -70,6 +70,49 @@ fn load_average() -> Option<f64> {
text.split_whitespace().map(|t| t.trim_matches(|c| c == '{' || c == '}')).find_map(|t| t.parse().ok())
}
/// 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> {
use vectorcraft_engine::tools::{Mods, PointerEvent, PointerKind};
use vectorcraft_geom::{Anchor, PathData, SubPath, Vec2};
let mut doc = synthetic(n)?;
let l = doc.layers.first().map(|l| l.id);
let id = doc.alloc_id();
// Anchors 2 pt apart, up and down by 20 pt, their handles 0.6 pt long.
let anchor = |i: usize| {
let p = Point::new(i as f64 * 2.0, if i.is_multiple_of(2) { 500.0 } else { 520.0 });
Anchor::smooth(p, p + Vec2::new(0.6, 0.0))
};
let path = PathData::single(SubPath::new((0..5000).map(anchor).collect(), false));
doc.insert(l, usize::MAX, Node::path(id, path, Appearance::default_art())).map_err(|e| e.to_string())?;
let mut s = vectorcraft_engine::Session::new();
s.add_document(doc, None);
let view = vectorcraft_engine::ViewInfo { zoom: 8.0, ..Default::default() };
let err = |e: vectorcraft_engine::EngineError| e.to_string();
let mut drag = |down: Point| -> Result<f64, String> {
let ev = |kind, y: f64| PointerEvent { kind, pos: down + Vec2::new(0.0, y), mods: Mods::default(), pressure: 1.0 };
s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 400]]})).map_err(err)?;
s.select_tool("directSelection", view).map_err(err)?;
let undo = s.doc().map_err(err)?.history.undo.len();
s.pointer(&ev(PointerKind::Down, 0.0), view).map_err(err)?;
let mut y = 0.0;
let ms = median_ms(9, || {
y += 3.0;
// A failed move shows as the missing undo step below.
let _ = s.pointer(&ev(PointerKind::Drag, y), view);
});
s.pointer(&ev(PointerKind::Up, y), view).map_err(err)?;
if s.doc().map_err(err)?.history.undo.len() != undo + 1 {
return Err(format!("the drag from {down:?} made no undo step"));
}
Ok(ms)
};
// Anchor 400 is at (800, 500): its outgoing handle's end, then its segment to anchor 401.
let handle = drag(Point::new(800.6, 500.0))?;
let segment = drag(Point::new(801.0, 510.0))?;
Ok((handle, segment))
}
pub fn run(args: &[String]) -> Result<(), String> {
let mut n = 50_000usize;
let mut it = args.iter();
@@ -145,6 +188,15 @@ pub fn run(args: &[String]) -> Result<(), String> {
}
});
rows.push(("Pathfinder Unite, 1,000 paths", unite, 150.0));
// Path editing: one pointer move of a Direct Selection drag (the tool event and the preview it
// applies), on a 5,000-anchor path among the synthetic paths.
let (handle, segment) = edit_drags(n).unwrap_or_else(|e| {
failed = Some(e);
(0.0, 0.0)
});
rows.push(("handle drag, 5,000-anchor path (per move)", handle, 8.0));
rows.push(("segment drag, 5,000-anchor path (per move)", segment, 8.0));
if let Some(e) = failed {
return Err(e);
}
+4 -2
View File
@@ -37,9 +37,11 @@ winit = { version = "0.30", default-features = false }
clipboard-win = { workspace = true }
[target.'cfg(target_os = "macos")'.dependencies]
muda = { version = "0.21", default-features = false }
# The macOS menu bar (src/mac_menu.rs): Tauri's menu crate, AppKit menus behind a safe API (no GTK
# with default features off). Pinned exactly: review the diff before bumping.
muda = { version = "=0.21.1", default-features = false }
objc2 = "0.6"
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSApplication", "NSPasteboard", "NSResponder", "NSTextInputContext"] }
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSApplication", "NSMenu", "NSEvent", "NSPasteboard", "NSResponder", "NSTextInputContext"] }
# Files opened from Finder and the Dock (src/open_documents.rs) and pasted bitmaps (src/clipboard.rs); both already come with winit, muda and rfd.
objc2-foundation = { version = "0.3", default-features = false, features = ["std", "block2", "NSArray", "NSData", "NSNotification", "NSOperation", "NSString", "NSURL"] }
block2 = "0.6"
+489
View File
@@ -0,0 +1,489 @@
//! Which graphics adapter the window renders with (#306, #502), and what happens when it can't
//! show the window.
//!
//! The canvas is rasterized on the CPU; the GPU only composites it and draws the UI, so any
//! adapter that can present to the window will do. [`adapter_order`] ranks the adapters: those that
//! can't present to the window's surface never, then the one `WGPU_ADAPTER_NAME` names, hardware
//! before software, the native backends (Vulkan, Metal, DX12) before OpenGL, the power preference
//! ([`power_preference`]) among the rest, and a GPU's DX12 adapter before its Vulkan one (#545).
//! eframe is handed [`selector`], which takes the first of that order.
//!
//! An adapter can report that it presents to the window and still fail once it does: on a hybrid
//! Linux desktop under Wayland, the compositor runs on one GPU and may refuse the frame buffers
//! another GPU allocates, which kills the window's Wayland connection; egui-wgpu then panics while
//! configuring the surface (#502). Nothing in the process can show a window after that, so when
//! the graphics fail while the window is starting up, [`finish`] starts the app again without
//! that adapter, as the next one in the order would be tried. Each restart leaves out one more
//! adapter, so it ends when none is left.
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, OnceLock};
use eframe::egui_wgpu::NativeAdapterSelectorMethod;
use eframe::wgpu::{self, Backend, DeviceType, PowerPreference};
/// The adapters a restart leaves out, those the window failed on, as comma-separated
/// `backend:vendor:device` keys (`Vulkan:1002:164e`). Set by the app itself when it starts again.
pub const SKIP_ENV: &str = "VECTORCRAFT_GPU_SKIP";
/// wgpu's variable for choosing an adapter by (part of) its name, any case.
const NAME_ENV: &str = "WGPU_ADAPTER_NAME";
/// Where to read how to choose another adapter, for the error that ends the app.
const HELP: &str =
"to choose a graphics adapter, see https://github.com/storytold/vectorcraft/blob/main/docs/development.md#desktop-graphics-processor";
/// Frames the UI ran before the failure, below which it was still starting up. The failure in
/// #502 came on the first or second frame; later, the adapter has proved itself, and a lost
/// window is something else (such as the compositor restarting).
const STARTUP_FRAMES: u64 = 10;
/// The preference used when Preferences say Automatic. Windows and macOS show frames from any GPU
/// (the integrated one avoids the flicker of #306). Elsewhere, the system's own order: Mesa's
/// device-select layer puts the GPU the desktop runs on first (the integrated one on hybrid
/// laptops), and a Wayland compositor may not show frames from another GPU (#502).
pub const AUTOMATIC: PowerPreference = if cfg!(any(windows, target_os = "macos")) { PowerPreference::LowPower } else { PowerPreference::None };
/// The power preference that orders the adapters: the `WGPU_POWER_PREF` environment variable
/// (`low`, `high`, `none`) when set, otherwise Preferences › Performance › Graphics Processor
/// (`gpuPreference`). Automatic, and any value this version doesn't know (0.5.0's default
/// `powerSaving`, a newer or damaged preference file), is [`AUTOMATIC`].
pub fn power_preference(pref: Option<&str>, env: Option<PowerPreference>) -> PowerPreference {
match (env, pref) {
(Some(p), _) => p,
(None, Some("highPerformance")) => PowerPreference::HighPerformance,
(None, Some("lowPower")) => PowerPreference::LowPower,
(None, _) => AUTOMATIC,
}
}
/// One adapter, as [`adapter_order`] sees it.
#[derive(Clone, Debug)]
pub struct Candidate {
/// Identifies the adapter across a restart: `backend:vendor:device` ([`key`]).
pub key: String,
pub name: String,
pub backend: Backend,
pub device_type: DeviceType,
/// Reports that it can present to the window's surface.
pub presents: bool,
}
impl Candidate {
fn new(adapter: &wgpu::Adapter, surface: Option<&wgpu::Surface<'_>>) -> Self {
let info = adapter.get_info();
Self {
key: key(info.backend, info.vendor, info.device),
presents: surface.is_none_or(|s| adapter.is_surface_supported(s)),
name: info.name,
backend: info.backend,
device_type: info.device_type,
}
}
}
/// `backend:vendor:device`, e.g. `Vulkan:1002:164e` (PCI ids, as `MESA_VK_DEVICE_SELECT` takes them).
fn key(backend: Backend, vendor: u32, device: u32) -> String {
format!("{backend:?}:{vendor:04x}:{device:04x}")
}
/// The order to try `candidates` in (their indices): only those that present to the window and
/// aren't in `skip`; the one whose name contains `named` (any case) first; hardware before
/// software; native backends before OpenGL; then by `power`; then DX12 before Vulkan, keeping the
/// system's order among equals (all of it for [`PowerPreference::None`]). Windows lists each GPU
/// under both, and Intel's Vulkan driver made the whole window flicker black where DX12 and OpenGL
/// didn't (#545); elsewhere there is no DX12 adapter, so the order is unchanged.
pub fn adapter_order(candidates: &[Candidate], power: PowerPreference, named: Option<&str>, skip: &[String]) -> Vec<usize> {
let named = named.map(str::to_lowercase).filter(|n| !n.is_empty());
let mut order: Vec<(usize, &Candidate)> = candidates.iter().enumerate().filter(|(_, c)| c.presents && !skip.contains(&c.key)).collect();
// Stable, so equals keep the system's order.
order.sort_by_key(|(_, c)| {
let unnamed = named.as_ref().is_some_and(|n| !c.name.to_lowercase().contains(n));
(unnamed, c.device_type == DeviceType::Cpu, c.backend == Backend::Gl, power_rank(c.device_type, power), c.backend == Backend::Vulkan)
});
order.into_iter().map(|(i, _)| i).collect()
}
/// wgpu's own ranking for a power preference: the preferred kind of GPU, the other kind, unknown,
/// virtual, software.
fn power_rank(t: DeviceType, power: PowerPreference) -> u8 {
match (power, t) {
(PowerPreference::None, _) => 0,
(PowerPreference::LowPower, DeviceType::IntegratedGpu) | (PowerPreference::HighPerformance, DeviceType::DiscreteGpu) => 0,
(_, DeviceType::IntegratedGpu | DeviceType::DiscreteGpu) => 1,
(_, DeviceType::Other) => 2,
(_, DeviceType::VirtualGpu) => 3,
(_, DeviceType::Cpu) => 4,
}
}
/// The adapters [`SKIP_ENV`] lists.
pub fn skipped() -> Vec<String> {
std::env::var(SKIP_ENV).map(|v| parse_skip(&v)).unwrap_or_default()
}
fn parse_skip(v: &str) -> Vec<String> {
v.split(',').map(str::trim).filter(|k| !k.is_empty()).map(String::from).collect()
}
/// What the window's start-up leaves for [`finish`].
#[derive(Default)]
pub struct Startup {
/// The key of the adapter [`selector`] picked.
adapter: OnceLock<String>,
/// The UI's context, which counts the frames run.
ui: OnceLock<egui::Context>,
}
impl Startup {
/// The app was created on `ctx`.
pub fn created(&self, ctx: &egui::Context) {
// Set once; the window is created once.
let _ = self.ui.set(ctx.clone());
}
}
/// eframe's adapter choice: the first of [`adapter_order`] for `power`, `WGPU_ADAPTER_NAME` and the
/// adapters a restart left out. Every adapter and the choice are logged, for bug reports.
pub fn selector(power: PowerPreference, startup: Arc<Startup>) -> NativeAdapterSelectorMethod {
let named = std::env::var(NAME_ENV).ok();
let skip = skipped();
Arc::new(move |adapters, surface| {
let candidates: Vec<Candidate> = adapters.iter().map(|a| Candidate::new(a, surface)).collect();
let order = adapter_order(&candidates, power, named.as_deref(), &skip);
let listed: Vec<String> = candidates
.iter()
.map(|c| {
let note = if !c.presents {
", can't show the window"
} else if skip.contains(&c.key) {
", failed before"
} else {
""
};
format!("{} ({:?}, {:?}, {}{note})", c.name.trim(), c.backend, c.device_type, c.key)
})
.collect();
log::info!("graphics adapters: {}", listed.join("; "));
let first = order.first().and_then(|&i| adapters.get(i).zip(candidates.get(i)));
let Some((adapter, chosen)) = first else {
return Err(format!("no graphics adapter can show the window (power preference {power:?}, {} adapters)", adapters.len()));
};
// Set once; eframe picks the adapter once.
let _ = startup.adapter.set(chosen.key.clone());
Ok(adapter.clone())
})
}
/// The last panic came from the graphics stack (see [`watch_panics`]).
static GRAPHICS_PANIC: AtomicBool = AtomicBool::new(false);
/// Note whether each panic comes from the graphics stack, so [`finish`] can tell a failing adapter
/// from a bug. The default hook still prints it.
pub fn watch_panics() {
let default = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
GRAPHICS_PANIC.store(info.location().is_some_and(|l| in_graphics_stack(l.file())), Ordering::Relaxed);
default(info);
}));
}
/// A source file of wgpu (`wgpu-core-30.0.1/src/…`, `wgpu-hal-…`), egui-wgpu or naga.
fn in_graphics_stack(file: &str) -> bool {
file.split(['/', '\\']).any(|dir| ["wgpu-", "egui-wgpu-", "naga-"].iter().any(|p| dir.starts_with(p)))
}
/// The adapter to start again without: the one picked, when the graphics failed while the window
/// was starting up and it wasn't already left out.
fn restart_without<'a>(graphics_failed: bool, frames: u64, picked: Option<&'a str>, skip: &[String]) -> Option<&'a str> {
picked.filter(|p| graphics_failed && frames < STARTUP_FRAMES && !skip.iter().any(|s| s == p))
}
/// After the window's run: `Ok` when it closed normally or the app started again (see the module
/// docs), otherwise why it failed. `outcome` is eframe's result, or the message of a panic that
/// ended it.
pub fn finish(outcome: Result<eframe::Result, String>, startup: &Startup) -> Result<(), String> {
let (why, graphics_failed) = match outcome {
Ok(Ok(())) => return Ok(()),
Ok(Err(e @ eframe::Error::Wgpu(_))) => (e.to_string(), true),
Ok(Err(e)) => (e.to_string(), false),
Err(panic) => (panic, GRAPHICS_PANIC.load(Ordering::Relaxed)),
};
let frames = startup.ui.get().map_or(0, egui::Context::cumulative_frame_nr);
let mut skip = skipped();
let Some(failed) = restart_without(graphics_failed, frames, startup.adapter.get().map(String::as_str), &skip) else {
return Err(if graphics_failed { format!("{why} ({HELP})") } else { why });
};
log::error!("the window failed on graphics adapter {failed} ({why}): starting again without it");
skip.push(failed.to_string());
restart(&skip.join(",")).map_err(|e| format!("{why}; starting again failed: {e}"))
}
/// Start the app again with the same arguments, leaving out the adapters in `skip`. On Unix the
/// new app replaces this process (same process id, so an AppImage keeps its files mounted), and
/// this returns only on failure; on Windows it starts beside this one, which then exits.
fn restart(skip: &str) -> std::io::Result<()> {
log::logger().flush();
let mut c = std::process::Command::new(std::env::current_exe()?);
c.args(std::env::args_os().skip(1)).env(SKIP_ENV, skip);
#[cfg(unix)]
{
use std::os::unix::process::CommandExt as _;
Err(c.exec())
}
#[cfg(not(unix))]
c.spawn().map(|_| ())
}
#[cfg(test)]
mod tests {
use super::*;
fn gpu(name: &str, backend: Backend, device_type: DeviceType) -> Candidate {
Candidate { key: format!("{backend:?}:{name}"), name: name.into(), backend, device_type, presents: true }
}
fn names(c: &[Candidate], order: &[usize]) -> Vec<String> {
order.iter().map(|&i| c[i].name.clone()).collect()
}
/// The machine of #502 as Vulkan lists it with Mesa's device-select layer: the GPU KDE's
/// compositor runs on (NVIDIA) first, then the Ryzen's integrated GPU, Mesa's software
/// renderer, and OpenGL.
fn issue_502() -> Vec<Candidate> {
vec![
gpu("NVIDIA GeForce RTX 5070", Backend::Vulkan, DeviceType::DiscreteGpu),
gpu("AMD Ryzen 9 7900X (RADV RAPHAEL_MENDOCINO)", Backend::Vulkan, DeviceType::IntegratedGpu),
gpu("llvmpipe (LLVM 20.1.8, 256 bits)", Backend::Vulkan, DeviceType::Cpu),
gpu("NVIDIA GeForce RTX 5070/PCIe/SSE2", Backend::Gl, DeviceType::Other),
]
}
#[test]
fn automatic_keeps_the_systems_order_on_linux_and_saves_power_elsewhere() {
let c = issue_502();
let order = adapter_order(&c, power_preference(None, None), None, &[]);
let first = &c[order[0]].name;
if cfg!(any(windows, target_os = "macos")) {
assert_eq!(first, "AMD Ryzen 9 7900X (RADV RAPHAEL_MENDOCINO)");
} else {
// #502: the integrated GPU couldn't show frames to a compositor on the NVIDIA GPU.
assert_eq!(first, "NVIDIA GeForce RTX 5070");
}
}
#[test]
fn each_preference_orders_the_adapters_then_falls_back_to_opengl_and_software() {
let c = issue_502();
let order = |power| names(&c, &adapter_order(&c, power, None, &[]));
assert_eq!(
order(PowerPreference::None),
[
"NVIDIA GeForce RTX 5070",
"AMD Ryzen 9 7900X (RADV RAPHAEL_MENDOCINO)",
"NVIDIA GeForce RTX 5070/PCIe/SSE2",
"llvmpipe (LLVM 20.1.8, 256 bits)"
]
);
assert_eq!(
order(PowerPreference::LowPower),
[
"AMD Ryzen 9 7900X (RADV RAPHAEL_MENDOCINO)",
"NVIDIA GeForce RTX 5070",
"NVIDIA GeForce RTX 5070/PCIe/SSE2",
"llvmpipe (LLVM 20.1.8, 256 bits)"
]
);
assert_eq!(
order(PowerPreference::HighPerformance),
[
"NVIDIA GeForce RTX 5070",
"AMD Ryzen 9 7900X (RADV RAPHAEL_MENDOCINO)",
"NVIDIA GeForce RTX 5070/PCIe/SSE2",
"llvmpipe (LLVM 20.1.8, 256 bits)"
]
);
}
/// A restart leaves out the adapter the window failed on, so Power Saving on the machine of
/// #502 ends up on the NVIDIA GPU, and once every adapter failed there is nothing to try.
#[test]
fn a_restart_tries_the_next_adapter() {
let c = issue_502();
let mut skip = vec![];
let mut tried = vec![];
while let Some(&i) = adapter_order(&c, PowerPreference::LowPower, None, &skip).first() {
tried.push(c[i].name.clone());
skip.push(c[i].key.clone());
}
assert_eq!(
tried,
[
"AMD Ryzen 9 7900X (RADV RAPHAEL_MENDOCINO)",
"NVIDIA GeForce RTX 5070",
"NVIDIA GeForce RTX 5070/PCIe/SSE2",
"llvmpipe (LLVM 20.1.8, 256 bits)"
]
);
}
#[test]
fn adapters_that_cannot_present_to_the_window_are_never_tried() {
let mut c = issue_502();
c[0].presents = false;
c[3].presents = false;
for power in [PowerPreference::None, PowerPreference::LowPower, PowerPreference::HighPerformance] {
let order = adapter_order(&c, power, None, &[]);
assert!(!order.contains(&0) && !order.contains(&3), "{power:?}: {order:?}");
assert_eq!(order.len(), 2);
}
for p in &mut c {
p.presents = false;
}
assert!(adapter_order(&c, PowerPreference::None, None, &[]).is_empty());
assert!(adapter_order(&[], PowerPreference::HighPerformance, None, &[]).is_empty());
}
#[test]
fn wgpu_adapter_name_picks_an_adapter_first_and_the_rest_stay_as_fallbacks() {
let c = issue_502();
let order = adapter_order(&c, PowerPreference::HighPerformance, Some("radv"), &[]);
assert_eq!(c[order[0]].name, "AMD Ryzen 9 7900X (RADV RAPHAEL_MENDOCINO)");
assert_eq!(order.len(), 4);
// Any case; every match comes before the rest, natively first.
let order = adapter_order(&c, PowerPreference::LowPower, Some("GeForce"), &[]);
assert_eq!(names(&c, &order[..2]), ["NVIDIA GeForce RTX 5070", "NVIDIA GeForce RTX 5070/PCIe/SSE2"]);
// An empty name or one nothing matches changes nothing.
for named in ["", "no such gpu"] {
assert_eq!(adapter_order(&c, PowerPreference::LowPower, Some(named), &[]), adapter_order(&c, PowerPreference::LowPower, None, &[]));
}
// A named adapter that failed is left out like any other.
let skip = vec![c[1].key.clone()];
assert_eq!(adapter_order(&c, PowerPreference::None, Some("radv"), &skip)[0], 0);
}
/// A Windows machine lists every GPU twice (Vulkan and DX12): power saving still takes the
/// integrated GPU first, as wgpu's own choice did (#306), each GPU through DX12 first (#545).
#[test]
fn hybrid_laptop_on_windows_renders_on_the_integrated_gpu_with_power_saving() {
let c = vec![
gpu("Intel(R) Arc(TM) A370M", Backend::Vulkan, DeviceType::DiscreteGpu),
gpu("Intel(R) Iris(R) Xe Graphics", Backend::Vulkan, DeviceType::IntegratedGpu),
gpu("Intel(R) Arc(TM) A370M", Backend::Dx12, DeviceType::DiscreteGpu),
gpu("Intel(R) Iris(R) Xe Graphics", Backend::Dx12, DeviceType::IntegratedGpu),
gpu("Microsoft Basic Render Driver", Backend::Dx12, DeviceType::Cpu),
];
let order = adapter_order(&c, PowerPreference::LowPower, None, &[]);
assert_eq!(order, [3, 1, 2, 0, 4]);
assert_eq!(adapter_order(&c, PowerPreference::HighPerformance, None, &[]), [2, 0, 3, 1, 4]);
}
/// The machine of #545: one Intel GPU, whose Vulkan driver made the window flicker black.
/// DX12 comes first whatever the preference; Vulkan stays a fallback, and `WGPU_ADAPTER_NAME`
/// or a restart leaving DX12 out still reach it.
#[test]
fn a_windows_gpu_renders_through_dx12_before_vulkan() {
let c = vec![
gpu("Intel(R) Graphics", Backend::Vulkan, DeviceType::IntegratedGpu),
gpu("Intel(R) Graphics", Backend::Dx12, DeviceType::IntegratedGpu),
gpu("Microsoft Basic Render Driver", Backend::Dx12, DeviceType::Cpu),
gpu("Intel(R) Graphics", Backend::Gl, DeviceType::Other),
];
for power in [PowerPreference::LowPower, PowerPreference::HighPerformance, PowerPreference::None] {
assert_eq!(adapter_order(&c, power, None, &[]), [1, 0, 3, 2], "{power:?}");
}
assert_eq!(adapter_order(&c, PowerPreference::LowPower, None, &[c[1].key.clone()]), [0, 3, 2], "DX12 failed: Vulkan next");
}
#[test]
fn power_preference_follows_the_environment_then_the_preference() {
assert_eq!(power_preference(None, None), AUTOMATIC);
assert_eq!(power_preference(Some("automatic"), None), AUTOMATIC);
assert_eq!(power_preference(Some("lowPower"), None), PowerPreference::LowPower);
assert_eq!(power_preference(Some("highPerformance"), None), PowerPreference::HighPerformance);
// 0.5.0's default, and values this version doesn't know (a newer or damaged file).
for old in ["powerSaving", "turbo", ""] {
assert_eq!(power_preference(Some(old), None), AUTOMATIC, "{old}");
}
// WGPU_POWER_PREF wins over the preference, either way.
assert_eq!(power_preference(Some("lowPower"), Some(PowerPreference::HighPerformance)), PowerPreference::HighPerformance);
assert_eq!(power_preference(Some("highPerformance"), Some(PowerPreference::LowPower)), PowerPreference::LowPower);
assert_eq!(power_preference(Some("lowPower"), Some(PowerPreference::None)), PowerPreference::None);
assert_eq!(AUTOMATIC, if cfg!(any(windows, target_os = "macos")) { PowerPreference::LowPower } else { PowerPreference::None });
}
/// The preference the engine saves is the one the app reads back before the window opens.
#[test]
fn the_saved_engine_preference_is_found() {
let mut prefs = vectorcraft_engine::Prefs::default();
let saved = prefs.to_json();
assert_eq!(saved.get("gpuPreference").and_then(serde_json::Value::as_str), Some("automatic"));
for (value, power) in [("lowPower", PowerPreference::LowPower), ("highPerformance", PowerPreference::HighPerformance)] {
prefs.gpu_preference = value.into();
let saved = prefs.to_json();
assert_eq!(power_preference(saved.get("gpuPreference").and_then(serde_json::Value::as_str), None), power);
}
// Every choice Preferences offer means something here.
for (value, _) in vectorcraft_engine::cmd::prefscmds::GPU_PREFERENCES {
assert!(["automatic", "lowPower", "highPerformance"].contains(value), "{value}");
}
}
#[test]
fn skipped_adapters_parse_from_a_comma_separated_list() {
assert_eq!(parse_skip("Vulkan:1002:164e, Gl:10de:2f04,,"), ["Vulkan:1002:164e", "Gl:10de:2f04"]);
assert!(parse_skip("").is_empty());
assert_eq!(key(Backend::Vulkan, 0x1002, 0x164e), "Vulkan:1002:164e");
assert_eq!(key(Backend::Gl, 0x10de, 0x2f04), "Gl:10de:2f04");
}
#[test]
fn panics_in_wgpu_egui_wgpu_and_naga_are_graphics_failures() {
for file in [
"/home/u/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/egui-wgpu-0.36.2/src/winit.rs",
r"C:\Users\u\.cargo\registry\src\index.crates.io-1949cf8c6b5b557f\wgpu-core-30.0.1\src\device\mod.rs",
"/rustc/deps/wgpu-hal-30.0.1/src/vulkan/adapter.rs",
"naga-30.0.0/src/back/spv/writer.rs",
] {
assert!(in_graphics_stack(file), "{file}");
}
for file in [
"apps/vectorcraft/src/main.rs",
"/home/wgpu/vectorcraft/crates/ui-egui/src/lib.rs",
"egui-0.36.2/src/context.rs",
"winit-0.30.12/src/x.rs",
] {
assert!(!in_graphics_stack(file), "{file}");
}
}
#[test]
fn only_a_graphics_failure_while_starting_up_restarts_without_the_adapter() {
let amd = Some("Vulkan:1002:164e");
assert_eq!(restart_without(true, 0, amd, &[]), amd);
assert_eq!(restart_without(true, STARTUP_FRAMES - 1, amd, &[]), amd);
// After start-up the adapter has shown frames; a lost window is something else.
assert_eq!(restart_without(true, STARTUP_FRAMES, amd, &[]), None);
// A bug outside the graphics, or no adapter picked: nothing another adapter would change.
assert_eq!(restart_without(false, 0, amd, &[]), None);
assert_eq!(restart_without(true, 0, None, &[]), None);
// Never the same adapter twice, so restarts end.
assert_eq!(restart_without(true, 0, amd, &["Vulkan:1002:164e".into()]), None);
}
#[test]
fn a_normal_exit_or_another_failure_does_not_restart() {
let startup = Startup::default();
assert_eq!(finish(Ok(Ok(())), &startup), Ok(()));
// No adapter was picked (none can show the window): the error is returned, nothing restarts.
let none =
eframe::Error::Wgpu(eframe::egui_wgpu::WgpuError::CustomNativeAdapterSelectionError("no graphics adapter can show the window".into()));
assert_eq!(
finish(Ok(Err(none)), &startup),
Err(format!("WGPU error: Adapter selection failed: no graphics adapter can show the window ({HELP})"))
);
let _ = startup.adapter.set("Vulkan:1002:164e".into());
GRAPHICS_PANIC.store(false, Ordering::Relaxed);
assert_eq!(finish(Err("a bug".into()), &startup), Err("a bug".into()));
}
}
+487
View File
@@ -0,0 +1,487 @@
//! The macOS menu bar, through muda (Tauri's menu crate: AppKit menus behind a safe API, no GTK
//! with default features off). The menus, their Mac layout and how their keys reach VectorCraft
//! are in `vectorcraft_ui_egui::native_menu`; this file only builds and updates the `NSMenu`s.
//!
//! - Item ids are the items' places (`vc12`, depth first): one command can run from several items
//! (each language of VectorCraft › Language is `app.language` with its own code).
//! - A structure change (a recent file added, the language or a shortcut changed) rebuilds the
//! menu; labels, enabled and checked are updated in place.
//! - A chosen item is a click or a key equivalent: AppKit's current event says which. A key
//! equivalent goes back to egui as the key press that was made (the event's modifiers, not the
//! item's: AppKit may match ⌘R to a ⇧⌘R item), so VectorCraft's key rules still apply.
//! - Hide and Hide Others are items of ours calling `NSApplication`: AppKit's own always take ⌘H
//! (View › Hide Edges) and ⌥⌘H.
use std::sync::Once;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{Receiver, channel};
use block2::RcBlock;
use egui::{Key, KeyboardShortcut};
use muda::accelerator::{Accelerator, Code, Modifiers};
use muda::{CheckMenuItem, Menu, MenuEvent, MenuItem, PredefinedMenuItem, Submenu};
use objc2::MainThreadMarker;
use objc2_app_kit::{NSApplication, NSEventModifierFlags, NSEventType, NSMenuDidBeginTrackingNotification, NSMenuDidEndTrackingNotification};
use objc2_foundation::{NSNotification, NSNotificationCenter};
use vectorcraft_ui_egui::VectorcraftApp;
use vectorcraft_ui_egui::native_menu::{self, Backend, Event, MenuBar, MenuRole, Node, Standard};
// AppKit can deliver window input while its system menu is still tracking (especially with
// asynchronous menu presentation). Keep the native tracking state separate from egui popups.
static TRACKING: AtomicBool = AtomicBool::new(false);
fn observe_tracking(ctx: &egui::Context) {
static INSTALL: Once = Once::new();
INSTALL.call_once(|| {
// SAFETY: AppKit initializes these immutable notification-name constants.
#[allow(unsafe_code)]
let notifications = unsafe { [(NSMenuDidBeginTrackingNotification, true), (NSMenuDidEndTrackingNotification, false)] };
for (name, tracking) in notifications {
let repaint = ctx.clone();
let block = RcBlock::new(move |_: std::ptr::NonNull<NSNotification>| {
TRACKING.store(tracking, Ordering::Relaxed);
// Apply any deferred menu updates as soon as the tracking session ends.
if !tracking {
repaint.request_repaint();
}
});
// SAFETY: these are AppKit's notification names. The notification center retains
// the observer and block for the application's lifetime; callbacks update an atomic and request repaint.
#[allow(unsafe_code)]
unsafe {
NSNotificationCenter::defaultCenter().addObserverForName_object_queue_usingBlock(Some(name), None, None, &block);
}
}
});
}
fn cancel_tracking() {
if let Some(mtm) = MainThreadMarker::new()
&& let Some(menu) = NSApplication::sharedApplication(mtm).mainMenu()
{
menu.cancelTracking();
}
TRACKING.store(false, Ordering::Relaxed);
}
/// A dismissing click belongs to the menu, so the canvas and panel controls must not see it.
fn dismiss_input(raw: &mut egui::RawInput, tracking: bool) -> bool {
if !raw
.events
.iter()
.any(|e| matches!(e, egui::Event::PointerButton { pressed: true, .. } | egui::Event::Key { key: egui::Key::Escape, pressed: true, .. }))
{
return false;
}
if tracking {
raw.events.retain(|e| !matches!(e, egui::Event::PointerButton { .. } | egui::Event::Key { key: egui::Key::Escape, .. }));
}
true
}
/// Inspect real window input before native key equivalents and control events are added.
pub fn raw_input_hook(raw: &mut egui::RawInput) {
// Asynchronous menu presentation may leave a displayed menu after its tracking notification.
// Still cancel it, but consume the dismissing input only during a reported tracking session.
if dismiss_input(raw, TRACKING.load(Ordering::Relaxed)) {
cancel_tracking();
}
}
enum Handle {
Plain(MenuItem),
Check(CheckMenuItem),
}
/// One native item, in the order of [`MenuBar::items`].
struct Entry {
handle: Handle,
item: native_menu::Item,
/// Its shortcut, when it is a key equivalent.
chord: Option<KeyboardShortcut>,
}
/// How an item was chosen, read from AppKit's current event while it calls the handler.
struct Chosen {
id: String,
/// A key press (not a mouse click), and the modifiers held: ⌘, ⌃, ⌥, ⇧.
key: bool,
mods: [bool; 4],
}
pub struct MacMenu {
menu: Option<Menu>,
entries: Vec<Entry>,
rx: Receiver<Chosen>,
structure: u64,
/// Latest menu state to apply after AppKit finishes tracking; item ids stay stable meanwhile.
pending: Option<MenuBar>,
}
impl MacMenu {
fn new(ctx: &egui::Context) -> MacMenu {
observe_tracking(ctx);
let (tx, rx) = channel();
let repaint = ctx.clone();
MenuEvent::set_event_handler(Some(move |e: MenuEvent| {
// AppKit calls this on the main thread, from the event that chose the item: a key
// equivalent is a key-down, a click a mouse-up (or ↩ inside the open menu).
let event = MainThreadMarker::new().and_then(|mtm| NSApplication::sharedApplication(mtm).currentEvent());
let key = event.as_ref().is_some_and(|ev| ev.r#type() == NSEventType::KeyDown);
let flags = event.as_ref().map_or(NSEventModifierFlags::empty(), |ev| ev.modifierFlags());
let mods = [NSEventModifierFlags::Command, NSEventModifierFlags::Control, NSEventModifierFlags::Option, NSEventModifierFlags::Shift]
.map(|m| flags.contains(m));
// The receiver only goes away with the app.
let _ = tx.send(Chosen { id: e.id.0, key, mods });
// Wake egui, so the item runs now rather than on the next mouse move.
repaint.request_repaint();
}));
MacMenu { menu: None, entries: Vec::new(), rx, structure: 0, pending: None }
}
/// Build the menus of `bar` and make them the app's, in place of the ones before.
fn build(&mut self, bar: &MenuBar) -> muda::Result<()> {
let mut entries = Vec::new();
let menu = Menu::new();
let mut special = Vec::new();
for m in &bar.menus {
let sub = Submenu::new(escape(&m.title), true);
append(&sub, &m.children, &mut entries)?;
menu.append(&sub)?;
if matches!(m.role, MenuRole::Window | MenuRole::Help) {
special.push((m.role, sub));
}
}
if let Some(old) = self.menu.take() {
old.remove_for_nsapp();
}
menu.init_for_nsapp();
// Only once the menu is the app's: muda looks the submenus up in the installed main menu.
for (role, sub) in special {
match role {
MenuRole::Window => sub.set_as_windows_menu_for_nsapp(),
_ => sub.set_as_help_menu_for_nsapp(),
}
}
self.menu = Some(menu);
self.entries = entries;
self.structure = native_menu::structure_key(bar);
Ok(())
}
}
fn append(sub: &Submenu, nodes: &[Node], entries: &mut Vec<Entry>) -> muda::Result<()> {
for n in nodes {
match n {
Node::Separator => sub.append(&PredefinedMenuItem::separator())?,
Node::Header(label) => sub.append(&MenuItem::new(escape(label), false, None))?,
Node::Submenu { label, children } => {
let s = Submenu::new(escape(label), !children.is_empty());
append(&s, children, entries)?;
sub.append(&s)?;
}
Node::Standard(item) => {
let text = Some(vectorcraft_ui_egui::i18n::t(item.label()));
let p = match item {
Standard::Services => PredefinedMenuItem::services(text),
Standard::ShowAll => PredefinedMenuItem::show_all(text),
Standard::Zoom => PredefinedMenuItem::maximize(text),
Standard::BringAllToFront => PredefinedMenuItem::bring_all_to_front(text),
};
sub.append(&p)?;
}
Node::Item(it) => {
let id = format!("vc{}", entries.len());
let chord = it.shortcut.and_then(vectorcraft_ui_egui::shortcuts::parse).filter(native_menu::native_ok);
let accel = chord.as_ref().and_then(accelerator);
let handle = match it.checked {
Some(c) => {
let h = CheckMenuItem::with_id(id, escape(&it.label), it.enabled, c, accel);
sub.append(&h)?;
Handle::Check(h)
}
None => {
let h = MenuItem::with_id(id, escape(&it.label), it.enabled, accel);
sub.append(&h)?;
Handle::Plain(h)
}
};
entries.push(Entry { handle, item: it.clone(), chord });
}
}
}
Ok(())
}
impl Backend for MacMenu {
fn sync(&mut self, bar: &MenuBar) {
// Replacing or mutating an NSMenu during tracking can strand its displayed menu. Keep
// the latest state: the shared model considers this sync complete and may not resend it.
if TRACKING.load(Ordering::Relaxed) {
self.pending = Some(bar.clone());
return;
}
self.pending = None;
let items = bar.items();
if self.menu.is_none() || native_menu::structure_key(bar) != self.structure || items.len() != self.entries.len() {
if let Err(e) = self.build(bar) {
// The menus as they were stay up (a failed build changed nothing).
log::warn!("couldn't rebuild the macOS menu bar: {e}");
}
return;
}
for (e, it) in self.entries.iter_mut().zip(items) {
if e.item.label != it.label {
let text = escape(&it.label);
match &e.handle {
Handle::Plain(h) => h.set_text(text),
Handle::Check(h) => h.set_text(text),
}
}
if e.item.enabled != it.enabled {
match &e.handle {
Handle::Plain(h) => h.set_enabled(it.enabled),
Handle::Check(h) => h.set_enabled(it.enabled),
}
}
// Compare with AppKit's own state: muda toggles a check item when it's clicked.
if let (Handle::Check(h), Some(c)) = (&e.handle, it.checked)
&& h.is_checked() != c
{
h.set_checked(c);
}
if e.item != *it {
e.item = it.clone();
}
}
}
fn drain(&mut self) -> Vec<Event> {
let mut out = Vec::new();
while let Ok(chosen) = self.rx.try_recv() {
cancel_tracking();
// Ids that aren't ours are AppKit's own items (Services, Zoom…), already handled.
let Some(e) = chosen.id.strip_prefix("vc").and_then(|n| n.parse::<usize>().ok()).and_then(|i| self.entries.get(i)) else { continue };
if let Some(command @ (native_menu::HIDE | native_menu::HIDE_OTHERS)) = e.item.command {
if let Some(mtm) = MainThreadMarker::new() {
let app = NSApplication::sharedApplication(mtm);
if command == native_menu::HIDE { app.hide(None) } else { app.hideOtherApplications(None) }
}
continue;
}
// A key-down chose it: its key equivalent, unless it was ↩ or Space inside the open
// menu (no ⌘ or ⌃ while the item's shortcut has one). The key is the item's (AppKit
// matched on it); the modifiers are the ones held.
let [cmd, ctrl, alt, shift] = chosen.mods;
let key = e
.chord
.filter(|c| {
chosen.key && e.item.command != Some(native_menu::MINIMIZE) && (cmd || ctrl || !(c.modifiers.command || c.modifiers.ctrl))
})
.map(|c| KeyboardShortcut::new(egui::Modifiers { alt, ctrl, shift, mac_cmd: cmd, command: cmd }, c.logical_key));
out.push(match key {
Some(k) => Event::Key(k),
None => Event::Click(e.item.clone()),
});
}
// Drain against the old item ids before a deferred structure change replaces them.
if !TRACKING.load(Ordering::Relaxed)
&& let Some(bar) = self.pending.take()
{
self.sync(&bar);
}
out
}
}
/// Install the menu bar (in eframe's creator closure, so winit's default menu doesn't stay up).
/// `None` keeps the menus in the window: AppKit refused them (logged), never a crash.
pub fn install(ctx: &egui::Context, app: &VectorcraftApp) -> Option<native_menu::NativeMenu> {
vectorcraft_ui_egui::i18n::set_current(app.ui_language());
let bar = native_menu::layout(app).bar;
let built = vectorcraft_engine::guard::catch_panic(|| {
let mut menu = MacMenu::new(ctx);
menu.build(&bar).map(|()| menu)
});
match built {
Ok(Ok(menu)) => Some(native_menu::NativeMenu::new(Box::new(menu))),
Ok(Err(e)) => {
log::warn!("couldn't install the macOS menu bar ({e}); the menus stay in the window");
None
}
Err(e) => {
log::warn!("couldn't install the macOS menu bar ({e}); the menus stay in the window");
None
}
}
}
/// `&` marks a mnemonic in muda labels: "Fill & Stroke" keeps its ampersand.
fn escape(s: &str) -> String {
s.replace('&', "&&")
}
/// A key equivalent for AppKit. `Cmd` is ⌘ (`META`) and `Ctrl` is ⌃: never folded together.
fn accelerator(c: &KeyboardShortcut) -> Option<Accelerator> {
let m = c.modifiers;
let mut mods = Modifiers::empty();
for (on, flag) in [(m.command || m.mac_cmd, Modifiers::META), (m.ctrl, Modifiers::CONTROL), (m.alt, Modifiers::ALT), (m.shift, Modifiers::SHIFT)]
{
if on {
mods |= flag;
}
}
Some(Accelerator::new(mods, code(c.logical_key)?))
}
/// The key code AppKit matches for an egui key.
fn code(key: Key) -> Option<Code> {
Some(match key {
Key::A => Code::KeyA,
Key::B => Code::KeyB,
Key::C => Code::KeyC,
Key::D => Code::KeyD,
Key::E => Code::KeyE,
Key::F => Code::KeyF,
Key::G => Code::KeyG,
Key::H => Code::KeyH,
Key::I => Code::KeyI,
Key::J => Code::KeyJ,
Key::K => Code::KeyK,
Key::L => Code::KeyL,
Key::M => Code::KeyM,
Key::N => Code::KeyN,
Key::O => Code::KeyO,
Key::P => Code::KeyP,
Key::Q => Code::KeyQ,
Key::R => Code::KeyR,
Key::S => Code::KeyS,
Key::T => Code::KeyT,
Key::U => Code::KeyU,
Key::V => Code::KeyV,
Key::W => Code::KeyW,
Key::X => Code::KeyX,
Key::Y => Code::KeyY,
Key::Z => Code::KeyZ,
Key::Num0 => Code::Digit0,
Key::Num1 => Code::Digit1,
Key::Num2 => Code::Digit2,
Key::Num3 => Code::Digit3,
Key::Num4 => Code::Digit4,
Key::Num5 => Code::Digit5,
Key::Num6 => Code::Digit6,
Key::Num7 => Code::Digit7,
Key::Num8 => Code::Digit8,
Key::Num9 => Code::Digit9,
Key::F1 => Code::F1,
Key::F2 => Code::F2,
Key::F3 => Code::F3,
Key::F4 => Code::F4,
Key::F5 => Code::F5,
Key::F6 => Code::F6,
Key::F7 => Code::F7,
Key::F8 => Code::F8,
Key::F9 => Code::F9,
Key::F10 => Code::F10,
Key::F11 => Code::F11,
Key::F12 => Code::F12,
Key::F13 => Code::F13,
Key::F14 => Code::F14,
Key::F15 => Code::F15,
Key::F16 => Code::F16,
Key::F17 => Code::F17,
Key::F18 => Code::F18,
Key::F19 => Code::F19,
Key::F20 => Code::F20,
Key::F21 => Code::F21,
Key::F22 => Code::F22,
Key::F23 => Code::F23,
Key::F24 => Code::F24,
Key::OpenBracket => Code::BracketLeft,
Key::CloseBracket => Code::BracketRight,
Key::Backslash => Code::Backslash,
Key::Slash => Code::Slash,
// `+` is Shift+`=` on the keyboards AppKit matches by key: Zoom In shows ⌘=.
Key::Equals | Key::Plus => Code::Equal,
Key::Minus => Code::Minus,
Key::Quote => Code::Quote,
Key::Semicolon => Code::Semicolon,
Key::Comma => Code::Comma,
Key::Period => Code::Period,
Key::Backtick => Code::Backquote,
Key::Backspace => Code::Backspace,
Key::Delete => Code::Delete,
Key::Enter => Code::Enter,
Key::Tab => Code::Tab,
Key::Space => Code::Space,
Key::Escape => Code::Escape,
Key::ArrowLeft => Code::ArrowLeft,
Key::ArrowRight => Code::ArrowRight,
Key::ArrowUp => Code::ArrowUp,
Key::ArrowDown => Code::ArrowDown,
_ => return None,
})
}
#[cfg(test)]
mod tests {
use super::*;
/// Every shortcut the Mac menu shows as a key equivalent has one AppKit can match.
#[test]
fn every_menu_shortcut_maps_to_a_key_equivalent() {
let app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
let bar = native_menu::layout(&app).bar;
let mut native = 0;
for it in bar.items() {
let Some(c) = it.shortcut.and_then(vectorcraft_ui_egui::shortcuts::parse).filter(native_menu::native_ok) else { continue };
assert!(accelerator(&c).is_some(), "{:?} ({:?}) has no key equivalent", it.shortcut, it.command);
native += 1;
}
assert!(native > 70, "{native} key equivalents");
}
#[test]
fn control_and_command_stay_distinct() {
let parse = |s| vectorcraft_ui_egui::shortcuts::parse(s).and_then(|c| accelerator(&c));
assert_ne!(parse("Cmd+M"), parse("Ctrl+Cmd+M"));
assert!(parse("Cmd+M").is_some());
}
fn press() -> egui::Event {
egui::Event::PointerButton {
pos: egui::pos2(300.0, 200.0),
button: egui::PointerButton::Primary,
pressed: true,
modifiers: Default::default(),
}
}
#[test]
fn outside_press_dismisses_without_starting_a_canvas_gesture() {
let moved = egui::Event::PointerMoved(egui::pos2(300.0, 200.0));
let mut raw = egui::RawInput { events: vec![moved.clone(), press()], ..Default::default() };
assert!(dismiss_input(&mut raw, true));
assert_eq!(raw.events, [moved]);
assert!(!dismiss_input(&mut raw, true));
raw.events.push(press());
assert!(dismiss_input(&mut raw, false));
assert_eq!(raw.events.len(), 2, "ordinary canvas presses still reach egui");
}
#[test]
fn escape_dismisses_without_reaching_the_active_tool() {
let escape = |pressed| egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed, repeat: false, modifiers: Default::default() };
let mut raw = egui::RawInput { events: vec![escape(true), escape(false)], ..Default::default() };
assert!(dismiss_input(&mut raw, true));
assert!(raw.events.is_empty());
}
#[test]
fn moving_the_pointer_does_not_dismiss_a_tracking_menu() {
let mut raw = egui::RawInput { events: vec![egui::Event::PointerMoved(egui::pos2(300.0, 200.0))], ..Default::default() };
assert!(!dismiss_input(&mut raw, true));
assert_eq!(raw.events.len(), 1);
}
}
+101 -113
View File
@@ -1,6 +1,9 @@
//! VectorCraft desktop app.
//!
//! Usage: `vectorcraft [--control <port>] [files…]`
//! Usage: `vectorcraft [--control <port>] [--in-window-menus] [files…]`
//!
//! `--in-window-menus` (or `VECTORCRAFT_IN_WINDOW_MENUS=1`) keeps the menus inside the window on
//! macOS instead of the macOS menu bar (`mac_menu`).
//!
//! `--control <port>` (or `VECTORCRAFT_CONTROL_PORT`) starts a localhost JSON-lines control server:
//! `{"id":1,"method":"ui.inspect","params":{}}` → `{"id":1,"ok":true,"result":…}`.
@@ -16,9 +19,11 @@ compile_error!("the win7 target requires --no-default-features --features window
mod clipboard;
mod control_server;
#[cfg(feature = "wgpu")]
mod gpu;
mod logging;
#[cfg(target_os = "macos")]
mod native_menu;
mod mac_menu;
#[cfg(target_os = "macos")]
mod open_documents;
mod printing;
@@ -27,7 +32,7 @@ mod window;
use vectorcraft_engine::Session;
use vectorcraft_engine::cmd::fileio;
use vectorcraft_ui_egui::graphics::GraphicsLoss;
use vectorcraft_ui_egui::{FilePick, Services, VectorcraftApp};
use vectorcraft_ui_egui::{ClipboardProbeFactory, FilePick, Services, VectorcraftApp};
struct App {
app: VectorcraftApp,
@@ -35,8 +40,6 @@ struct App {
graphics_loss: GraphicsLoss,
/// The graphics device was lost and the unsaved changes are kept for Data Recovery.
graphics_lost: bool,
#[cfg(target_os = "macos")]
menu: Option<native_menu::NativeMenu>,
}
impl eframe::App for App {
@@ -57,15 +60,7 @@ impl eframe::App for App {
return;
}
#[cfg(target_os = "macos")]
{
if self.menu.is_none() && std::env::var_os("VECTORCRAFT_NO_NATIVE_MENU").is_none() {
self.menu = Some(native_menu::NativeMenu::install(&mut self.app));
}
if let Some(m) = &mut self.menu {
m.poll(&mut self.app, ctx);
}
open_files(&mut self.app, open_documents::take());
}
open_files(&mut self.app, open_documents::take());
self.app.logic(ctx);
window::track(ctx, &mut self.app.ui.window);
if self.app.ui.status == "quit" {
@@ -73,6 +68,10 @@ impl eframe::App for App {
}
}
fn raw_input_hook(&mut self, _ctx: &egui::Context, raw: &mut egui::RawInput) {
#[cfg(target_os = "macos")]
if self.app.services.native_menu.is_some() {
mac_menu::raw_input_hook(raw);
}
self.app.raw_input_hook(raw);
}
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
@@ -254,6 +253,10 @@ fn services() -> Services {
write_shared: Some(std::sync::Arc::new(write_file)),
// Every format Copy offers and Paste reads (menu-bar Paste never sees egui's Paste event).
system_clipboard: Some(clipboard::system_clipboard()),
// Linux checks whether Paste has something to take on a background thread: an X11 clipboard
// owner that never answers holds a read for up to 4 s. Windows only asks which formats the
// clipboard holds and macOS asks the pasteboard server, so they check in line.
clipboard_probe: cfg!(target_os = "linux").then(|| Box::new(clipboard::system_clipboard) as ClipboardProbeFactory),
// Help → Discord / website / GitHub, the Discord button, About and Home links.
open_url: Some(Box::new(|url: &str| {
let _ = webbrowser::open(url);
@@ -297,23 +300,6 @@ fn app_icon() -> egui::IconData {
eframe::icon_data::from_png_bytes(png).unwrap_or_default()
}
/// The power preference wgpu picks the window's graphics adapter with (#306): the
/// `WGPU_POWER_PREF` environment variable (`low`, `high`, `none`) when set, otherwise Preferences ›
/// Performance › Graphics Processor (`gpuPreference`). Power saving unless the preference asks for
/// high performance: the canvas is rasterized on the CPU and the GPU only composites it, which the
/// integrated GPU of a hybrid-graphics laptop does easily, while presenting frames rendered on the
/// discrete GPU through the integrated one made the window flicker on some laptops. With a single
/// GPU both preferences pick it.
#[cfg(feature = "wgpu")]
fn power_preference(pref: Option<&str>, env: Option<eframe::wgpu::PowerPreference>) -> eframe::wgpu::PowerPreference {
use eframe::wgpu::PowerPreference;
match (env, pref) {
(Some(p), _) => p,
(None, Some("highPerformance")) => PowerPreference::HighPerformance,
(None, _) => PowerPreference::LowPower,
}
}
/// "name (backend, kind)" of the adapter the window renders with, for Help › About and bug reports.
#[cfg(feature = "wgpu")]
fn adapter_summary(info: &eframe::wgpu::AdapterInfo) -> String {
@@ -324,19 +310,21 @@ fn adapter_summary(info: &eframe::wgpu::AdapterInfo) -> String {
/// macOS keeps its traffic lights over the integrated title strip.
const CUSTOM_TITLEBAR: bool = !cfg!(target_os = "macos");
fn main() -> eframe::Result {
fn main() -> std::process::ExitCode {
// First, so every start-up warning is recorded (`logging`).
let logger = logging::install();
vectorcraft_ui_egui::i18n::detect_system_lang_in_background();
let mut control_port: Option<u16> = std::env::var("VECTORCRAFT_CONTROL_PORT").ok().and_then(|p| p.parse().ok());
let mut files = Vec::new();
let mut in_window_menus = std::env::var_os("VECTORCRAFT_IN_WINDOW_MENUS").is_some_and(|v| !v.is_empty() && v != "0");
let mut args = std::env::args().skip(1);
while let Some(a) = args.next() {
match a.as_str() {
"--control" => control_port = args.next().and_then(|p| p.parse().ok()),
"--in-window-menus" => in_window_menus = true,
"--version" => {
println!("vectorcraft {}", env!("CARGO_PKG_VERSION"));
return Ok(());
return std::process::ExitCode::SUCCESS;
}
_ => files.push(a),
}
@@ -360,7 +348,9 @@ fn main() -> eframe::Result {
#[cfg(feature = "wgpu")]
let gpu_pref = saved.as_ref().and_then(|ui| ui.engine_prefs.get("gpuPreference")).and_then(serde_json::Value::as_str);
#[cfg(feature = "wgpu")]
let power = power_preference(gpu_pref, eframe::wgpu::PowerPreference::from_env());
let power = gpu::power_preference(gpu_pref, eframe::wgpu::PowerPreference::from_env());
#[cfg(feature = "wgpu")]
let startup = std::sync::Arc::new(gpu::Startup::default());
let options = eframe::NativeOptions {
viewport: egui::ViewportBuilder::default()
.with_title("VectorCraft")
@@ -383,86 +373,96 @@ fn main() -> eframe::Result {
// One frame queued, not two: the canvas is rasterized on the CPU and the GPU only
// composites it, so the window answers the pointer a frame sooner (#444).
options.wgpu_options.surface = eframe::egui_wgpu::SurfaceConfig::LOW_LATENCY;
// Only adapters that can show the window, in the order `gpu` gives (#306, #502).
if let eframe::egui_wgpu::WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup {
create.power_preference = power;
create.native_adapter_selector = Some(gpu::selector(power, startup.clone()));
}
options
};
#[cfg(feature = "wgpu")]
gpu::watch_panics();
// Files opened from Finder and the Dock arrive as events, not arguments.
#[cfg(target_os = "macos")]
open_documents::install();
eframe::run_native(
"VectorCraft",
options,
Box::new(move |cc| {
let mut app = VectorcraftApp::new(Session::new(), services());
load_prefs(&mut app, saved);
// Fit the window to its monitor, or put it back where it was (still hidden).
if let Some(w) = cc.winit_window() {
app.ui.window = Some(window::restore(w, saved_window));
}
// User Defined swatch and graphic style libraries live next to the preferences.
let swatches = prefs_path().and_then(|p| Some(p.parent()?.join("Swatches").to_string_lossy().to_string()));
app.session.swatch_libraries.set_user_dir(swatches);
let styles = prefs_path().and_then(|p| Some(p.parent()?.join("Graphic Styles").to_string_lossy().to_string()));
app.session.style_libraries.set_user_dir(styles);
// Data Recovery copies live next to the preferences too (none for runs without
// preferences, such as agents' test runs, unless the recoveryFolder preference is set).
if std::env::var_os("VECTORCRAFT_NO_PREFS").is_none() {
let recovery = prefs_path().and_then(|p| Some(p.parent()?.join("Data Recovery").to_string_lossy().to_string()));
app.session.recovery.set_default_folder(recovery);
}
let graphics_loss = GraphicsLoss::default();
#[cfg(feature = "wgpu")]
if let Some(rs) = &cc.wgpu_render_state {
let summary = adapter_summary(&rs.adapter.get_info());
log::info!("rendering with {summary} (power preference {power:?})");
app.graphics_adapter = Some(summary);
let (loss, ctx) = (graphics_loss.clone(), cc.egui_ctx.clone());
rs.device.set_device_lost_callback(move |reason, msg| loss.report(&ctx, format!("{reason:?}: {msg}")));
}
#[cfg(feature = "windows7")]
{
app.graphics_adapter = Some("OpenGL (Windows 7 compatibility)".into());
}
app.integrated_titlebar = cfg!(target_os = "macos");
app.custom_titlebar = CUSTOM_TITLEBAR;
if let Some(port) = control_port {
let rx = control_server::start(port, cc.egui_ctx.clone());
app = app.with_control(rx);
}
#[cfg(target_os = "macos")]
open_documents::set_ui(&cc.egui_ctx);
open_files(&mut app, files);
Ok(Box::new(App {
app,
graphics_loss,
graphics_lost: false,
#[cfg(feature = "wgpu")]
let created = startup.clone();
// A panic that ends the window (egui-wgpu's own, #502) is caught here: never a crash.
let outcome = vectorcraft_engine::guard::catch_panic(|| {
eframe::run_native(
"VectorCraft",
options,
Box::new(move |cc| {
let mut app = VectorcraftApp::new(Session::new(), services());
load_prefs(&mut app, saved);
// Fit the window to its monitor, or put it back where it was (still hidden).
if let Some(w) = cc.winit_window() {
app.ui.window = Some(window::restore(w, saved_window));
}
// User Defined swatch and graphic style libraries live next to the preferences.
let swatches = prefs_path().and_then(|p| Some(p.parent()?.join("Swatches").to_string_lossy().to_string()));
app.session.swatch_libraries.set_user_dir(swatches);
let styles = prefs_path().and_then(|p| Some(p.parent()?.join("Graphic Styles").to_string_lossy().to_string()));
app.session.style_libraries.set_user_dir(styles);
// Data Recovery copies live next to the preferences too (none for runs without
// preferences, such as agents' test runs, unless the recoveryFolder preference is set).
if std::env::var_os("VECTORCRAFT_NO_PREFS").is_none() {
let recovery = prefs_path().and_then(|p| Some(p.parent()?.join("Data Recovery").to_string_lossy().to_string()));
app.session.recovery.set_default_folder(recovery);
}
let graphics_loss = GraphicsLoss::default();
#[cfg(feature = "wgpu")]
if let Some(rs) = &cc.wgpu_render_state {
let summary = adapter_summary(&rs.adapter.get_info());
log::info!("rendering with {summary} (power preference {power:?})");
created.created(&cc.egui_ctx);
if !gpu::skipped().is_empty() {
app.status(format!("The graphics processor tried first couldn't show the window, so VectorCraft started again on {summary}"));
}
app.graphics_adapter = Some(summary);
let (loss, ctx) = (graphics_loss.clone(), cc.egui_ctx.clone());
rs.device.set_device_lost_callback(move |reason, msg| loss.report(&ctx, format!("{reason:?}: {msg}")));
}
#[cfg(feature = "windows7")]
{
app.graphics_adapter = Some("OpenGL (Windows 7 compatibility)".into());
}
app.integrated_titlebar = cfg!(target_os = "macos");
app.custom_titlebar = CUSTOM_TITLEBAR;
if let Some(port) = control_port {
let rx = control_server::start(port, cc.egui_ctx.clone());
app = app.with_control(rx);
}
#[cfg(target_os = "macos")]
menu: None,
}))
}),
)
{
open_documents::set_ui(&cc.egui_ctx);
// The macOS menu bar, installed now so winit's default menu doesn't stay up.
if !in_window_menus {
app.services.native_menu = mac_menu::install(&cc.egui_ctx, &app);
}
}
#[cfg(not(target_os = "macos"))]
let _ = in_window_menus;
open_files(&mut app, files);
Ok(Box::new(App { app, graphics_loss, graphics_lost: false }))
}),
)
});
#[cfg(feature = "wgpu")]
let outcome = gpu::finish(outcome, &startup);
#[cfg(not(feature = "wgpu"))]
let outcome = outcome.and_then(|r| r.map_err(|e| e.to_string()));
match outcome {
Ok(()) => std::process::ExitCode::SUCCESS,
Err(e) => {
log::error!("VectorCraft stopped: {e}");
std::process::ExitCode::FAILURE
}
}
}
#[cfg(all(test, feature = "wgpu"))]
mod tests {
use super::*;
use eframe::wgpu::PowerPreference;
#[test]
fn power_saving_unless_the_preference_or_the_environment_says_otherwise() {
assert_eq!(power_preference(None, None), PowerPreference::LowPower);
assert_eq!(power_preference(Some("powerSaving"), None), PowerPreference::LowPower);
assert_eq!(power_preference(Some("highPerformance"), None), PowerPreference::HighPerformance);
// A value this version doesn't know (a newer or damaged preference file) is the default.
assert_eq!(power_preference(Some("turbo"), None), PowerPreference::LowPower);
assert_eq!(power_preference(Some(""), None), PowerPreference::LowPower);
// WGPU_POWER_PREF wins over the preference, either way.
assert_eq!(power_preference(Some("powerSaving"), Some(PowerPreference::HighPerformance)), PowerPreference::HighPerformance);
assert_eq!(power_preference(Some("highPerformance"), Some(PowerPreference::LowPower)), PowerPreference::LowPower);
assert_eq!(power_preference(None, Some(PowerPreference::None)), PowerPreference::None);
}
/// The file extensions the macOS bundle declares: its document types and its own exported type.
fn plist_extensions(plist: &str) -> Vec<&str> {
@@ -492,16 +492,4 @@ mod tests {
assert!(types > 1 && plist.matches("<key>LSHandlerRank</key>").count() == types, "every document type has a rank");
assert_eq!(plist.matches("<string>Owner</string>").count(), 2, "only VectorCraft documents and templates are owned");
}
/// The preference the engine saves is the one the app reads back before the window opens.
#[test]
fn the_saved_engine_preference_is_found() {
let mut prefs = vectorcraft_engine::Prefs::default();
let saved = prefs.to_json();
assert_eq!(saved.get("gpuPreference").and_then(serde_json::Value::as_str), Some("powerSaving"));
prefs.gpu_preference = "highPerformance".into();
let saved = prefs.to_json();
let pref = saved.get("gpuPreference").and_then(serde_json::Value::as_str);
assert_eq!(power_preference(pref, None), PowerPreference::HighPerformance);
}
}
-183
View File
@@ -1,183 +0,0 @@
//! macOS: VectorCraft's menu tree as the native system menu bar (like Illustrator on the Mac).
//! Items dispatch through the same command path as the in-window menus; enablement, check marks
//! and dynamic labels ("Undo Move") are refreshed a few times per second, and the menu is rebuilt
//! when saved views or recent files come and go.
use std::collections::HashMap;
use std::str::FromStr;
use muda::accelerator::Accelerator;
use muda::{CheckMenuItem, Menu, MenuEvent, MenuItem, PredefinedMenuItem, Submenu};
use serde_json::Value;
use vectorcraft_ui_egui::VectorcraftApp;
use vectorcraft_ui_egui::i18n::{self, Lang, t};
use vectorcraft_ui_egui::menus::{self, Item};
enum Handle {
Plain(MenuItem),
Check(CheckMenuItem),
}
pub struct NativeMenu {
_menu: Menu,
items: HashMap<String, (String, Value, Handle, String)>,
last_refresh: f64,
/// Shortcut-override / workspace-list generation the menu was built for.
generation: u64,
/// Saved views and recent files listed (empty slots are left out, so a change rebuilds).
slots: usize,
/// Plug-in registry revision the Plug-ins submenus were built for.
plugins: u64,
/// The language the labels were built in (a change rebuilds the menu).
language: Lang,
}
/// Accelerator for a shortcut like "Cmd+Shift+]" (modifier-less shortcuts stay in the app so they
/// don't steal keys from text fields; a focused field still gets Cmd+A/X/C/V, see [`NativeMenu::poll`]).
fn accel(sc: &str) -> Option<Accelerator> {
if !(sc.contains("Cmd") || sc.contains("Ctrl") || sc.contains("Alt") || sc.starts_with('F')) {
return None;
}
Accelerator::from_str(&sc.replace("Cmd", "CMD").replace("Alt", "ALT").replace("Shift", "SHIFT").replace("Ctrl", "CTRL")).ok()
}
impl NativeMenu {
pub fn install(app: &mut VectorcraftApp) -> Self {
// Accelerators come from `shortcut_of`, which honours the user's overrides.
vectorcraft_ui_egui::shortcut_editor::sync(&app.ui);
let generation = vectorcraft_ui_egui::shortcut_editor::GENERATION.load(std::sync::atomic::Ordering::Relaxed);
let menu = Menu::new();
let mut items = HashMap::new();
let mut counter = 0usize;
for (title, entries) in menus::menu_tree() {
let sub = Submenu::new(t(title), true);
build(app, &sub, &entries, &mut items, &mut counter);
let _ = menu.append(&sub);
}
menu.init_for_nsapp();
app.native_menu = true;
app.native_shortcuts = items
.values()
.filter(|(_, p, _, c)| (p.is_null() || p.as_object().is_some_and(|o| o.is_empty())) && menus::shortcut_of(c).and_then(accel).is_some())
.map(|(_, _, _, c)| c.clone())
.collect();
Self {
_menu: menu,
items,
last_refresh: 0.0,
generation,
slots: menus::listed_slots(app),
plugins: menus::plugin_revision(),
language: i18n::current(),
}
}
/// Dispatch chosen items (a focused text field takes Select All and the clipboard) and refresh
/// state.
pub fn poll(&mut self, app: &mut VectorcraftApp, ctx: &egui::Context) {
while let Ok(ev) = MenuEvent::receiver().try_recv() {
if let Some((cmd, params, _, _)) = self.items.get(ev.id.as_ref()) {
let p = if params.is_null() { serde_json::json!({}) } else { params.clone() };
menus::invoke_from_system_menu(app, ctx, cmd, p);
}
}
let now = vectorcraft_ui_egui::now_ms();
if now - self.last_refresh < 250.0 {
return;
}
self.last_refresh = now;
// Shortcuts edited, workspaces added, saved views, recent files, plug-ins or the UI language
// changed: rebuild so accelerators, lists and labels are current.
if vectorcraft_ui_egui::shortcut_editor::GENERATION.load(std::sync::atomic::Ordering::Relaxed) != self.generation
|| menus::listed_slots(app) != self.slots
|| menus::plugin_revision() != self.plugins
|| i18n::current() != self.language
{
*self = NativeMenu::install(app);
return;
}
for (run, rp, h, cmd) in self.items.values() {
let null = Value::Null;
let params = if run == cmd { rp } else { &null };
let en = menus::enabled(app, cmd);
match h {
Handle::Plain(i) => {
i.set_enabled(en);
if matches!(
cmd.as_str(),
"edit.undo"
| "edit.redo"
| "view.outline"
| "view.rulers"
| "view.guides"
| "view.grid"
| "view.edges"
| "view.artboards"
| "view.boundingBox"
| "view.transparencyGrid"
| "window.workspace.reset"
) || cmd.starts_with("file.openRecent")
|| cmd.starts_with("type.recentFont")
|| cmd.starts_with("view.goto")
|| matches!(
cmd.as_str(),
"view.cornerWidget" | "view.textThreads" | "view.gradientAnnotator" | "effect.last" | "type.hiddenCharacters"
)
{
i.set_text(menus::display_label(app, cmd, ""));
}
}
Handle::Check(c) => {
c.set_enabled(en);
c.set_checked(menus::checked(app, cmd, params).unwrap_or(false));
}
}
}
}
}
fn build(
app: &VectorcraftApp,
parent: &Submenu,
entries: &[Item],
items: &mut HashMap<String, (String, Value, Handle, String)>,
counter: &mut usize,
) {
for e in entries {
match e {
Item::Sep => {
let _ = parent.append(&PredefinedMenuItem::separator());
}
Item::Header(h) => {
let _ = parent.append(&MenuItem::new(t(h), false, None));
}
Item::Todo(label, sc) => {
let _ = parent.append(&MenuItem::new(t(label), false, accel(sc)));
}
Item::Sub(label, children) => {
let sub = Submenu::new(t(label), true);
build(app, &sub, children, items, counter);
let _ = parent.append(&sub);
}
// Unused saved-view and recent-file slots are left out, as in the in-window menus.
Item::Cmd(_, cmd, _) if menus::hidden_slot(app, cmd) => {}
Item::Cmd(label, cmd, params) => {
*counter += 1;
let id = format!("dc{counter}");
let sc = if params.is_null() { menus::shortcut_of(cmd).and_then(accel) } else { None };
let handle = if menus::checked(app, cmd, params).is_some() {
let c = CheckMenuItem::with_id(id.clone(), menus::display_label(app, cmd, label), true, false, sc);
let _ = parent.append(&c);
Handle::Check(c)
} else {
let i = MenuItem::with_id(id.clone(), menus::display_label(app, cmd, label), true, sc);
let _ = parent.append(&i);
Handle::Plain(i)
};
let (run, run_params) = menus::click_target(label, cmd, params);
let _ = &run_params;
items.insert(id, (run, run_params, handle, cmd.to_string()));
}
}
}
}
+2 -1
View File
@@ -78,7 +78,8 @@ fn add_open_urls_method() {
/// Queue the files among `urls` and wake the UI. Never panics: it runs inside AppKit.
extern "C-unwind" fn open_urls(_delegate: &AnyObject, _cmd: Sel, _app: &AnyObject, urls: &NSArray<NSURL>) {
let paths = urls.iter().filter_map(|u| u.to_file_path()).map(|p| p.to_string_lossy().into_owned());
// Only file URLs: macOS 27 turns an https URL's path into a file path too (#433).
let paths = urls.iter().filter(|u| u.isFileURL()).filter_map(|u| u.to_file_path()).map(|p| p.to_string_lossy().into_owned());
PENDING.lock().unwrap_or_else(PoisonError::into_inner).extend(paths);
if let Some(ctx) = UI.get() {
ctx.request_repaint();
+7
View File
@@ -21,3 +21,10 @@
real_name = "Brandon Thomas"
display_name = "Brandon Thomas"
sync_github_name = false
[people.callmeBalloch]
real_name = "Riccardo Balloch"
sync_github_name = false
[people.mo0kid]
sync_github_name = true
+1 -1
View File
@@ -315,7 +315,7 @@ impl<'a> Scene<'a> {
}
}
// Live blends, envelopes, meshes and repeats are written as their evaluated art.
NodeKind::Blend { .. } | NodeKind::Envelope { .. } | NodeKind::Mesh(_) | NodeKind::Repeat(_) => {
NodeKind::Blend { .. } | NodeKind::Envelope { .. } | NodeKind::Mesh(_) | NodeKind::Repeat(_) | NodeKind::PlacedDocument(_) => {
let g = vectorcraft_effects::expand_live_deep(Some(self.doc), n);
for c in g.children().into_iter().flatten() {
self.node(c, false);
+3 -1
View File
@@ -527,7 +527,8 @@ impl Lerp {
(NodeKind::Mesh(ma), NodeKind::Mesh(mb)) if ma.rows == mb.rows && ma.cols == mb.cols && ma.points.len() == mb.points.len() => Shape::Mesh,
(NodeKind::Text(_), NodeKind::Text(_))
| (NodeKind::SymbolInstance { .. }, NodeKind::SymbolInstance { .. })
| (NodeKind::Image(_), NodeKind::Image(_)) => Shape::Placed,
| (NodeKind::Image(_), NodeKind::Image(_))
| (NodeKind::PlacedDocument(_), NodeKind::PlacedDocument(_)) => Shape::Placed,
_ => match (node_path(a), node_path(b)) {
(Some((pa, ra, ma)), Some((pb, rb, mb))) => {
Shape::Path { pair: PathPair::new(&pa, &pb, starts), rules: (ra, rb), members: ma.zip(mb) }
@@ -586,6 +587,7 @@ impl Lerp {
*o = lerp_affine(*x, *y, t)
}
(NodeKind::Image(o), NodeKind::Image(x), NodeKind::Image(y)) => o.xf = lerp_affine(x.xf, y.xf, t),
(NodeKind::PlacedDocument(o), NodeKind::PlacedDocument(x), NodeKind::PlacedDocument(y)) => o.xf = lerp_affine(x.xf, y.xf, t),
_ => {}
}
n.mask = None;
+271
View File
@@ -0,0 +1,271 @@
//! Live Corners on any path: the corners of its uncut outline (a live rectangle's or polygon's, a
//! live path's, or a plain path's own), each one's radius and kind, and the anchors of the path as
//! drawn that belong to each. [`set_corners`] edits them.
use std::borrow::Cow;
use std::collections::BTreeSet;
use vectorcraft_geom::corners::{Corner, cut_corners, path_corners};
use vectorcraft_geom::shapes::{self, CornerKind};
use vectorcraft_geom::{Affine, PathData, Rect};
use crate::node::{LiveShape, Node, NodeKind};
use crate::selection::AnchorRef;
/// The Live Corners of a path.
#[derive(Clone, Debug)]
pub struct LiveCorners<'a> {
/// The path with its corners uncut, in the corners' own space: a live rectangle's (its size
/// and radii in document units, see [`LiveShape::folded`]), else the document's.
pub base: Cow<'a, PathData>,
/// Maps `base` into the document.
pub xf: Affine,
/// The corners that can be cut, in anchor order ([`path_corners`] of `base`).
pub corners: Vec<Corner>,
radii: Vec<f64>,
kinds: Vec<CornerKind>,
/// For each anchor of the path as drawn (per subpath), the anchor of `base` it comes from.
sources: Vec<Vec<usize>>,
}
impl<'a> LiveCorners<'a> {
/// The Live Corners of `path` and its live shape; `None` for shapes without corners (ellipses,
/// lines).
pub fn new(path: &'a PathData, live: Option<&'a LiveShape>) -> Option<Self> {
let (base, xf, radii, kinds) = match live {
None => (Cow::Borrowed(path), Affine::IDENTITY, vec![], vec![]),
Some(l @ LiveShape::Rectangle { .. }) => {
let LiveShape::Rectangle { w, h, radii, kinds, xf } = l.folded() else { return None };
(Cow::Owned(shapes::rectangle(Rect::new(0.0, 0.0, w, h))), xf, radii.to_vec(), kinds.to_vec())
}
Some(l @ LiveShape::Polygon { radii, kinds, .. }) => (Cow::Owned(l.polygon_outline()), Affine::IDENTITY, radii.clone(), kinds.clone()),
Some(LiveShape::Path { base, radii, kinds }) => (Cow::Borrowed(base), Affine::IDENTITY, radii.clone(), kinds.clone()),
Some(LiveShape::Ellipse { .. } | LiveShape::Line { .. }) => return None,
};
let sources = if radii.iter().any(|r| *r > 0.0) {
cut_corners(&base, &radii, &kinds).1
} else {
let mut first = 0;
base.subpaths
.iter()
.map(|sp| {
first += sp.anchors.len();
(first - sp.anchors.len()..first).collect()
})
.collect()
};
Some(Self { corners: path_corners(&base), base, xf, radii, kinds, sources })
}
/// The Live Corners of a path object.
pub fn of(node: &'a Node) -> Option<Self> {
let NodeKind::Path { path, live, .. } = &node.kind else { return None };
Self::new(path, live.as_ref())
}
/// The corner at anchor `index` of `base`.
pub fn corner(&self, index: usize) -> Option<&Corner> {
self.corners.binary_search_by_key(&index, |c| c.index).ok().and_then(|i| self.corners.get(i))
}
/// The radius corner `index` is set to, in document units (drawn no larger than fits).
pub fn radius(&self, index: usize) -> f64 {
self.radii.get(index).copied().unwrap_or(0.0)
}
/// The kind corner `index` is cut with.
pub fn kind(&self, index: usize) -> CornerKind {
self.kinds.get(index).copied().unwrap_or_default()
}
/// Every corner.
pub fn all(&self) -> BTreeSet<usize> {
self.corners.iter().map(|c| c.index).collect()
}
/// The corners holding one of `anchors` (of the path as drawn).
pub fn corners_of(&self, anchors: &BTreeSet<AnchorRef>) -> BTreeSet<usize> {
anchors.iter().filter_map(|(si, ai)| self.sources.get(*si)?.get(*ai).copied()).filter(|k| self.corner(*k).is_some()).collect()
}
/// The corners Live Corners edit for a selection: those holding a selected anchor when the
/// path is partly selected (Direct Selection), else every corner.
pub fn picked(&self, partial: Option<&BTreeSet<AnchorRef>>) -> BTreeSet<usize> {
let picked = partial.map(|a| self.corners_of(a)).unwrap_or_default();
if picked.is_empty() { self.all() } else { picked }
}
/// The anchors of the path as drawn that belong to `corners` (to keep them selected as the
/// path changes).
pub fn anchors_of(&self, corners: &BTreeSet<usize>) -> BTreeSet<AnchorRef> {
let mut out = BTreeSet::new();
for (si, from) in self.sources.iter().enumerate() {
out.extend(from.iter().enumerate().filter(|(_, k)| corners.contains(k)).map(|(ai, _)| (si, ai)));
}
out
}
/// For each anchor of the path as drawn (per subpath), the anchor of `base` it comes from.
pub fn sources(&self) -> &[Vec<usize>] {
&self.sources
}
/// The radius (document units) and kind `corners` share (each `None` when they differ, or
/// for no corners).
pub fn style(&self, corners: &BTreeSet<usize>) -> (Option<f64>, Option<CornerKind>) {
fn shared<T: Copy>(mut it: impl Iterator<Item = T>, same: impl Fn(T, T) -> bool) -> Option<T> {
let first = it.next()?;
it.all(|x| same(x, first)).then_some(first)
}
let radius = shared(corners.iter().map(|k| self.radius(*k)), |a, b| (a - b).abs() < 1e-9);
(radius, shared(corners.iter().map(|k| self.kind(*k)), |a, b| a == b))
}
}
/// Set `radius` (document units; negative: 0) and/or `kind` on the `corners` (anchor indices of
/// the uncut outline, see [`LiveCorners`]) of a path and its live shape, then cut the path again.
/// A path that isn't a live shape keeps its uncut outline as a [`LiveShape::Path`], which is a
/// plain path again once no corner is cut. Ellipses and lines have no corners: they stay as they
/// are.
pub fn set_corners(path: &mut PathData, live: &mut Option<LiveShape>, corners: &BTreeSet<usize>, radius: Option<f64>, kind: Option<CornerKind>) {
fn edit(radii: &mut [f64], kinds: &mut [CornerKind], corners: &BTreeSet<usize>, radius: Option<f64>, kind: Option<CornerKind>) {
for k in corners {
if let (Some(r), Some(slot)) = (radius, radii.get_mut(*k)) {
*slot = r.max(0.0);
}
if let (Some(kind), Some(slot)) = (kind, kinds.get_mut(*k)) {
*slot = kind;
}
}
}
/// One radius and kind per corner of an outline of `n` anchors while editing; none saved
/// when all are sharp or round.
fn edit_vec(
n: usize,
radii: &mut Vec<f64>,
kinds: &mut Vec<CornerKind>,
corners: &BTreeSet<usize>,
radius: Option<f64>,
kind: Option<CornerKind>,
) {
radii.resize(n, 0.0);
kinds.resize(n, CornerKind::Round);
edit(radii, kinds, corners, radius, kind);
if radii.iter().all(|r| *r <= 0.0) {
radii.clear();
}
if kinds.iter().all(|k| *k == CornerKind::Round) {
kinds.clear();
}
}
let l = live.get_or_insert_with(|| LiveShape::Path { base: path.clone(), radii: vec![], kinds: vec![] });
// Radii are document lengths and corners circular, also on a rectangle from a file that kept
// an uneven scale in its transform (#442).
l.fold_scale();
match l {
LiveShape::Rectangle { radii, kinds, .. } => edit(radii, kinds, corners, radius, kind),
LiveShape::Polygon { sides, radii, kinds, .. } => edit_vec(*sides as usize, radii, kinds, corners, radius, kind),
LiveShape::Path { base, radii, kinds } => edit_vec(base.anchor_count(), radii, kinds, corners, radius, kind),
LiveShape::Ellipse { .. } | LiveShape::Line { .. } => return,
}
match live {
Some(LiveShape::Path { base, radii, kinds }) if radii.is_empty() && kinds.is_empty() => {
*path = std::mem::take(base);
*live = None;
}
Some(l) => *path = l.to_path(),
None => {}
}
}
#[cfg(test)]
mod tests {
use super::*;
use vectorcraft_geom::{Point, SubPath};
fn set(v: &[usize]) -> BTreeSet<usize> {
v.iter().copied().collect()
}
fn anchors(v: &[usize]) -> BTreeSet<AnchorRef> {
v.iter().map(|ai| (0, *ai)).collect()
}
#[test]
fn rectangle_corners_map_to_their_anchors() {
let l = LiveShape::Rectangle { w: 100.0, h: 50.0, radii: [0.0, 10.0, 0.0, 0.0], kinds: Default::default(), xf: Affine::IDENTITY };
let path = l.to_path();
let c = LiveCorners::new(&path, Some(&l)).unwrap();
// Anchors: top-left, the top-right corner's two, bottom-right, bottom-left.
assert_eq!(c.sources(), [vec![0, 1, 1, 2, 3]]);
assert_eq!(path.anchor_count(), 5);
assert_eq!(c.corners_of(&anchors(&[2, 4])), set(&[1, 3]));
assert!(c.corners_of(&anchors(&[9])).is_empty(), "out of range");
assert_eq!(c.anchors_of(&set(&[1, 3])), anchors(&[1, 2, 4]));
// Partly selected: the corners of the selected anchors; wholly (or no anchor): all four.
assert_eq!(c.picked(Some(&anchors(&[0]))), set(&[0]));
assert_eq!(c.picked(None), set(&[0, 1, 2, 3]));
assert_eq!(c.picked(Some(&anchors(&[]))), set(&[0, 1, 2, 3]));
assert_eq!(c.style(&set(&[1])), (Some(10.0), Some(CornerKind::Round)));
assert_eq!(c.style(&set(&[0, 1])), (None, Some(CornerKind::Round)));
assert_eq!(c.style(&set(&[0, 2, 3])), (Some(0.0), Some(CornerKind::Round)));
let e = LiveShape::Ellipse { w: 1.0, h: 1.0, pie: (0.0, 360.0), xf: Affine::IDENTITY };
assert!(LiveCorners::new(&e.to_path(), Some(&e)).is_none());
}
/// #511: a plain path (a star) rounds its corners and keeps them editable; with none cut it
/// is plain again.
#[test]
fn a_plain_path_keeps_its_cut_corners_live() {
let star = shapes::star(Point::new(100.0, 100.0), 50.0, 25.0, 5, 0.0);
let (mut path, mut live) = (star.clone(), None);
set_corners(&mut path, &mut live, &set(&[0, 2]), Some(5.0), None);
let Some(LiveShape::Path { base, radii, kinds }) = &live else { panic!("live corners: {live:?}") };
assert_eq!((base, radii.len(), kinds.len()), (&star, 10, 0));
assert_eq!(path.anchor_count(), 12, "two corners cut");
let c = LiveCorners::new(&path, live.as_ref()).unwrap();
assert_eq!(c.style(&set(&[0, 2])), (Some(5.0), Some(CornerKind::Round)));
assert_eq!(c.corners_of(&anchors(&[0, 11])), set(&[0]), "the first corner's cut ends the path");
// Kinds alone keep it live; squaring every corner makes it the plain star again.
set_corners(&mut path, &mut live, &set(&[0, 2]), Some(0.0), Some(CornerKind::Chamfer));
assert!(matches!(&live, Some(LiveShape::Path { radii, .. }) if radii.is_empty()));
set_corners(&mut path, &mut live, &set(&[0, 2]), None, Some(CornerKind::Round));
assert_eq!((path, live), (star, None));
}
/// A polygon's corners are cut in the document and survive a change of sides when shared.
#[test]
fn polygon_corners_follow_their_sides() {
let mut l = LiveShape::Polygon { radius: 50.0, sides: 6, xf: Affine::translate((100.0, 100.0)), radii: vec![], kinds: vec![] };
let (mut path, mut live) = (l.to_path(), Some(l.clone()));
set_corners(&mut path, &mut live, &set(&[0, 1, 2, 3, 4, 5]), Some(8.0), None);
assert_eq!(path.anchor_count(), 12);
l = live.clone().unwrap();
l.set_sides(8);
assert!(matches!(&l, LiveShape::Polygon { radii, .. } if *radii == vec![8.0; 8]));
assert_eq!(l.to_path().anchor_count(), 16);
// Mixed radii: the new corners are sharp.
set_corners(&mut path, &mut live, &set(&[1]), Some(3.0), None);
let mut l = live.unwrap();
l.set_sides(7);
assert!(matches!(&l, LiveShape::Polygon { radii, .. } if *radii == [8.0, 3.0, 8.0, 8.0, 8.0, 8.0, 0.0]));
// An uneven scale keeps the cuts circular: the radius scales by the mean scale.
let mut p = l.clone();
assert!(p.transform(Affine::scale_non_uniform(4.0, 1.0)));
assert!(matches!(&p, LiveShape::Polygon { radii, .. } if (radii[0] - 16.0).abs() < 1e-9));
assert!(!p.transform(Affine::translate((5.0, 0.0))), "a move needs no new cuts");
}
#[test]
fn open_paths_and_curves_keep_their_ends_and_smooth_anchors() {
let pen = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 80.0)], false));
let c = LiveCorners::new(&pen, None).unwrap();
assert_eq!(c.all(), set(&[1]));
assert_eq!(c.picked(Some(&anchors(&[0]))), set(&[1]), "an end is no corner: every corner");
let (mut path, mut live) = (pen.clone(), None);
set_corners(&mut path, &mut live, &c.all(), Some(10.0), None);
assert_eq!(path.anchor_count(), 4);
assert_eq!(path.subpaths[0].anchors[0].p, Point::new(0.0, 0.0));
assert_eq!(path.subpaths[0].anchors[3].p, Point::new(100.0, 80.0));
}
}
+6 -3
View File
@@ -199,9 +199,12 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions) -> Option<HitKind> {
n.geometric_bounds().filter(|b| b.inflate(opt.tol, opt.tol).contains(p))?;
on_type_path(n, t, p, opt.tol).then_some(HitKind::Outline)
}
NodeKind::Text(_) | NodeKind::Image(_) | NodeKind::SymbolInstance { .. } | NodeKind::Blend { .. } | NodeKind::Envelope { .. } => {
n.geometric_bounds().filter(|b| b.inflate(opt.tol, opt.tol).contains(p)).map(|_| HitKind::Bounds)
}
NodeKind::Text(_)
| NodeKind::Image(_)
| NodeKind::PlacedDocument(_)
| NodeKind::SymbolInstance { .. }
| NodeKind::Blend { .. }
| NodeKind::Envelope { .. } => n.geometric_bounds().filter(|b| b.inflate(opt.tol, opt.tol).contains(p)).map(|_| HitKind::Bounds),
NodeKind::Repeat(r) => r.expand().iter().find_map(|g| hit_any(g, p, opt)),
NodeKind::Mesh(m) => {
let bp = m.outline().to_bezpath();
+4
View File
@@ -10,6 +10,7 @@ pub mod assets;
pub mod blend;
pub mod clipnest;
pub mod cmyk;
pub mod corners;
pub mod graph;
pub mod hit;
pub mod inks;
@@ -23,6 +24,7 @@ pub mod overprint;
pub mod pattern;
pub mod perspective;
mod pixels;
pub mod placed_document;
pub mod profiles;
pub mod puppet;
pub mod range;
@@ -58,6 +60,7 @@ pub use appearance::{
StrokeLayer, WidthProfile,
};
pub use assets::ExportAsset;
pub use corners::LiveCorners;
pub use graph::{GraphKind, GraphSpec};
pub use hit::{Hit, HitKind};
pub use links::{LinkInfo, PlacementOptions};
@@ -70,6 +73,7 @@ pub use node::{ImageObject, LAYER_COLORS, LayerColor, LiveShape, Node, NodeId, N
pub use orient::OrientedBox;
pub use pattern::{Overlap, PatternDef, PatternEdit, RepeatKind, RepeatSpec, TileType};
pub use perspective::PerspectiveAttachment;
pub use placed_document::PlacedDocument;
pub use profiles::ColorProfiles;
pub use puppet::{PuppetPin, PuppetPins};
pub use rastersettings::{RasterColorModel, RasterEffectsSettings};
+3 -1
View File
@@ -137,7 +137,7 @@ impl Document {
}
}
/// The keys of image blobs only linked images show: what a save writes as their preview.
/// The keys of image blobs only linked images (or placed documents, always linked) show: what a save writes as their preview.
pub fn linked_only_images(&self) -> BTreeSet<String> {
if self.images.values().all(|b| b.proxy.is_none()) {
return BTreeSet::new();
@@ -152,6 +152,8 @@ impl Document {
u.1 = true;
}
});
// A placed document saves its file's preview the same way.
self.visit_placed(|_, p| uses.entry(p.key.as_str()).or_default().0 = true);
uses.into_iter().filter(|(_, (linked, embedded))| *linked && !embedded).map(|(k, _)| k.to_string()).collect()
}
}
+4 -1
View File
@@ -1447,6 +1447,8 @@ fn map_node(n: &Node, w: &Warper) -> Node {
let im = im.clone();
return warp_image(&out, &im, w);
}
// Its art is plain, so it warps at this depth.
NodeKind::PlacedDocument(_) => return map_node(&expanded_group_hooks(n, w.hooks), w),
}
out
}
@@ -1607,7 +1609,7 @@ pub fn envelope_bounds(content: &[Arc<Node>], kind: &EnvelopeKind, frame: Affine
/// Is this one of the live kinds?
pub fn is_live(n: &Node) -> bool {
matches!(n.kind, NodeKind::Blend { .. } | NodeKind::Envelope { .. } | NodeKind::Mesh(_) | NodeKind::Repeat(_))
matches!(n.kind, NodeKind::Blend { .. } | NodeKind::Envelope { .. } | NodeKind::Mesh(_) | NodeKind::Repeat(_) | NodeKind::PlacedDocument(_))
}
/// Mesh tessellation as filled quad paths (no stroke), `n`×`n` per patch.
@@ -1641,6 +1643,7 @@ pub fn expand_live_hooks(n: &Node, hooks: Hooks) -> Vec<Node> {
NodeKind::Envelope { content, kind, fidelity, options, frame, .. } => expand_envelope(content, kind, *fidelity, *options, *frame, hooks),
NodeKind::Mesh(m) => mesh_quad_nodes(m, 8),
NodeKind::Repeat(r) => r.expand(),
NodeKind::PlacedDocument(p) => p.art(n),
_ => vec![n.clone()],
}
}
+112 -73
View File
@@ -1,17 +1,16 @@
//! Document nodes.
use std::collections::BTreeSet;
use std::sync::Arc;
use serde::{Deserialize, Serialize};
use vectorcraft_color::BlendMode;
use vectorcraft_geom::corners::cut_corners;
use vectorcraft_geom::shapes::{self, CornerKind};
use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect};
use crate::appearance::Appearance;
use crate::live::{BlendSpec, EnvelopeKind, GradientMesh, Outliner};
use crate::pattern::RepeatSpec;
use crate::selection::AnchorRef;
use crate::text::TextObject;
/// Stable per-document object id. Never reused.
@@ -104,11 +103,30 @@ pub enum LiveShape {
radius: f64,
sides: u32,
xf: Affine,
/// Corner radii in document units, by vertex from the first one clockwise (none: sharp).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
radii: Vec<f64>,
/// Corner kinds, in the same order (none: round).
#[serde(default, skip_serializing_if = "all_round")]
kinds: Vec<CornerKind>,
},
Line {
a: Point,
b: Point,
},
/// Any other path whose corners Live Corners cut (a star, a pen path): it keeps its uncut
/// outline so the corners stay editable. Without a cut corner it is a plain path again.
Path {
/// The path with its corners uncut, in the document.
base: PathData,
/// Corner radii in document units, by anchor index of `base` (counting every subpath's
/// anchors in order; missing: sharp).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
radii: Vec<f64>,
/// Corner kinds, in the same order (missing: round).
#[serde(default, skip_serializing_if = "all_round")]
kinds: Vec<CornerKind>,
},
}
impl LiveShape {
@@ -119,6 +137,7 @@ impl LiveShape {
LiveShape::Ellipse { .. } => "Ellipse",
LiveShape::Polygon { .. } => "Polygon",
LiveShape::Line { .. } => "Line",
LiveShape::Path { .. } => "Path",
}
}
/// Regenerate the path.
@@ -128,10 +147,33 @@ impl LiveShape {
shapes::rectangle_with_corners(Rect::new(0.0, 0.0, *w, *h), *radii, *kinds).transformed(*xf)
}
LiveShape::Ellipse { w, h, xf, .. } => shapes::ellipse(Rect::new(0.0, 0.0, *w, *h)).transformed(*xf),
LiveShape::Polygon { radius, sides, xf } => shapes::polygon(Point::ZERO, *radius, *sides, 0.0).transformed(*xf),
LiveShape::Polygon { radii, kinds, .. } => cut_corners(&self.polygon_outline(), radii, kinds).0,
LiveShape::Line { a, b } => shapes::line(*a, *b),
LiveShape::Path { base, radii, kinds } => cut_corners(base, radii, kinds).0,
}
}
/// A polygon's outline with its corners uncut, in the document (empty for other shapes).
pub fn polygon_outline(&self) -> PathData {
match self {
LiveShape::Polygon { radius, sides, xf, .. } => shapes::polygon(Point::ZERO, *radius, *sides, 0.0).transformed(*xf),
_ => PathData::default(),
}
}
/// Give a polygon `n` sides (3–1000). Its corners keep the radius and kind they shared; else
/// the corners past the old last one are sharp.
pub fn set_sides(&mut self, n: u64) {
let LiveShape::Polygon { sides, radii, kinds, .. } = self else { return };
*sides = n.clamp(3, 1000) as u32;
fn spread<T: Copy + PartialEq + Default>(v: &mut Vec<T>, n: usize) {
match v.first().copied() {
Some(x) if v.iter().all(|y| *y == x) => *v = vec![x; n],
Some(_) => v.resize(n, T::default()),
None => {}
}
}
spread(radii, *sides as usize);
spread(kinds, *sides as usize);
}
/// Apply `a` to the shape. True when the shape is no longer `a` applied to the old path, so
/// the caller must regenerate the path with [`LiveShape::to_path`].
///
@@ -140,19 +182,27 @@ impl LiveShape {
/// only the rotation, reflection and position. The radii scale by the mean scale (the square
/// root of the determinant), which [`LiveShape::keep_corners`] undoes for Scale Corners off.
/// A shear can't keep circular corners: `xf` takes it, as do moves (so files saved with a
/// scale in `xf` keep their exact geometry until they're next transformed).
/// scale in `xf` keep their exact geometry until they're next transformed). A polygon's or a
/// path's corner radii are document lengths: they scale by the mean scale and the corners are
/// cut again, circular whatever `a` does.
pub fn transform(&mut self, a: Affine) -> bool {
match self {
LiveShape::Rectangle { xf, .. } => {
*xf = a * *xf;
let [a0, a1, a2, a3, _, _] = a.as_coeffs();
let moves_only = (a0 - 1.0).abs() < 1e-12 && a1.abs() < 1e-12 && a2.abs() < 1e-12 && (a3 - 1.0).abs() < 1e-12;
!moves_only && self.fold_scale()
!moves_only(a) && self.fold_scale()
}
LiveShape::Ellipse { xf, .. } | LiveShape::Polygon { xf, .. } => {
LiveShape::Ellipse { xf, .. } => {
*xf = a * *xf;
false
}
LiveShape::Polygon { xf, radii, .. } => {
*xf = a * *xf;
scale_radii(radii, a)
}
LiveShape::Path { base, radii, .. } => {
base.transform(a);
scale_radii(radii, a)
}
LiveShape::Line { a: p, b } => {
*p = a * *p;
*b = a * *b;
@@ -192,52 +242,16 @@ impl LiveShape {
/// Divide live corner radii by `k`, the mean scale of a transform just applied, so the corners
/// keep their size (Scale Corners off). False when nothing changed.
pub fn keep_corners(&mut self, k: f64) -> bool {
match self {
LiveShape::Rectangle { radii, .. } if radii.iter().any(|r| *r > 0.0) && k > 1e-12 => {
radii.iter_mut().for_each(|r| *r /= k);
true
}
_ => false,
let radii: &mut [f64] = match self {
LiveShape::Rectangle { radii, .. } => radii,
LiveShape::Polygon { radii, .. } | LiveShape::Path { radii, .. } => radii,
LiveShape::Ellipse { .. } | LiveShape::Line { .. } => return false,
};
if !radii.iter().any(|r| *r > 0.0) || k <= 1e-12 {
return false;
}
}
/// The corner (radii order) of each anchor of a rectangle's path; empty for other shapes.
pub fn anchor_corners(&self) -> Vec<usize> {
match self {
LiveShape::Rectangle { w, h, radii, .. } => shapes::rectangle_anchor_corners(Rect::new(0.0, 0.0, *w, *h), *radii),
_ => vec![],
}
}
/// The corners of a rectangle that hold one of `anchors` (of its only subpath).
pub fn corners_of(&self, anchors: &BTreeSet<AnchorRef>) -> [bool; 4] {
let map = self.anchor_corners();
let mut out = [false; 4];
for k in anchors.iter().filter(|(si, _)| *si == 0).filter_map(|(_, ai)| map.get(*ai)) {
if let Some(c) = out.get_mut(*k) {
*c = true;
}
}
out
}
/// The corners Live Corners edit for a selection: those holding a selected anchor when the
/// shape is partly selected (Direct Selection), else all four.
pub fn picked_corners(&self, partial: Option<&BTreeSet<AnchorRef>>) -> [bool; 4] {
let picked = partial.map_or([true; 4], |a| self.corners_of(a));
if picked.contains(&true) { picked } else { [true; 4] }
}
/// The anchors of a rectangle's `corners` (to keep them selected as its path changes).
pub fn corner_anchors(&self, corners: [bool; 4]) -> BTreeSet<AnchorRef> {
self.anchor_corners().into_iter().enumerate().filter(|(_, k)| corners.get(*k) == Some(&true)).map(|(ai, _)| (0, ai)).collect()
}
/// The radius (in document units, see [`LiveShape::folded`]) and kind the `corners` of a
/// rectangle share (each `None` when they differ).
pub fn corner_style(&self, corners: [bool; 4]) -> (Option<f64>, Option<CornerKind>) {
let LiveShape::Rectangle { radii, kinds, .. } = self.folded() else { return (None, None) };
fn shared<T: Copy>(v: [T; 4], corners: [bool; 4], same: impl Fn(T, T) -> bool) -> Option<T> {
let mut it = v.into_iter().zip(corners).filter(|(_, on)| *on).map(|(x, _)| x);
let first = it.next()?;
it.all(|x| same(x, first)).then_some(first)
}
(shared(radii, corners, |a, b| (a - b).abs() < 1e-9), shared(kinds, corners, |a, b| a == b))
radii.iter_mut().for_each(|r| *r /= k);
true
}
/// Rotation angle of the live shape in degrees (shown in the Properties panel).
pub fn angle_deg(&self) -> f64 {
@@ -247,14 +261,33 @@ impl LiveShape {
c[1].atan2(c[0]).to_degrees()
}
LiveShape::Line { a, b } => (b.y - a.y).atan2(b.x - a.x).to_degrees(),
LiveShape::Path { .. } => 0.0,
}
}
}
fn all_round(kinds: &[CornerKind; 4]) -> bool {
fn all_round(kinds: &[CornerKind]) -> bool {
kinds.iter().all(|k| *k == CornerKind::Round)
}
/// Whether `a` only moves (no rotation, scale, shear or reflection).
fn moves_only(a: Affine) -> bool {
let [a0, a1, a2, a3, _, _] = a.as_coeffs();
(a0 - 1.0).abs() < 1e-12 && a1.abs() < 1e-12 && a2.abs() < 1e-12 && (a3 - 1.0).abs() < 1e-12
}
/// Scale corner radii in document units by the mean scale of `a`, applied to their path. True
/// when the path must be cut again: some corner is cut and `a` does more than move it (an
/// uneven scale would otherwise make the cuts elliptical).
fn scale_radii(radii: &mut [f64], a: Affine) -> bool {
if moves_only(a) || !radii.iter().any(|r| *r > 0.0) {
return false;
}
let k = a.determinant().abs().sqrt();
radii.iter_mut().for_each(|r| *r *= k);
true
}
/// What a transform scales besides geometry, by its mean scale (the square root of its
/// determinant). `Scaling::default()` (and `false`) scales nothing else; `true` scales stroke
/// weights and dashes only. Transforms the user asks for take theirs from Scale Strokes & Effects
@@ -390,6 +423,9 @@ pub enum NodeKind {
Mesh(GradientMesh),
/// Live Repeat (radial / grid / mirror) of source art.
Repeat(RepeatSpec),
/// A placed document: an artboard of another VectorCraft file, linked and locked (see
/// [`crate::placed_document`]).
PlacedDocument(Box<crate::placed_document::PlacedDocument>),
}
fn yes() -> bool {
@@ -609,6 +645,7 @@ impl Node {
NodeKind::Envelope { .. } => "Envelope",
NodeKind::Mesh(_) => "Mesh",
NodeKind::Repeat(r) => r.kind.label(),
NodeKind::PlacedDocument(_) => "Placed Document",
}
}
/// Name shown in the Layers panel: explicit name or `<Kind>`.
@@ -682,6 +719,7 @@ impl Node {
NodeKind::Envelope { content, kind, frame, .. } => crate::live::envelope_bounds(content, kind, *frame),
NodeKind::Mesh(m) => m.bounds(),
NodeKind::Repeat(r) => r.bounds(),
NodeKind::PlacedDocument(p) => Some(p.bounds()),
}
}
/// Visual bounds: what the object paints, its strokes included (paths and compound paths
@@ -777,6 +815,7 @@ impl Node {
}
}
NodeKind::Image(im) => im.xf = a * im.xf,
NodeKind::PlacedDocument(p) => p.xf = a * p.xf,
NodeKind::SymbolInstance { xf, .. } => *xf = a * *xf,
NodeKind::Blend { children, spec } => {
for c in children.iter_mut() {
@@ -939,6 +978,10 @@ impl Node {
let frame = shapes::rectangle(Rect::new(0.0, 0.0, im.width as f64, im.height as f64)).transformed(im.xf);
out.push((frame.to_bezpath(), FillRule::NonZero));
}
NodeKind::PlacedDocument(p) => {
let frame = shapes::rectangle(p.natural()).transformed(p.xf);
out.push((frame.to_bezpath(), FillRule::NonZero));
}
NodeKind::Blend { .. } | NodeKind::Envelope { .. } | NodeKind::Mesh(_) | NodeKind::Repeat(_) => {
crate::live::expand_deep(self, text).push_clip_shapes(text, out);
}
@@ -1214,7 +1257,7 @@ impl Node {
/// Shapes drawn with the shape tools (live rectangles, ellipses and polygons) show their centre.
pub fn shows_center_by_default(&self) -> bool {
matches!(&self.kind, NodeKind::Path { live: Some(l), .. } if !matches!(l, LiveShape::Line { .. }))
matches!(&self.kind, NodeKind::Path { live: Some(l), .. } if !matches!(l, LiveShape::Line { .. } | LiveShape::Path { .. }))
}
/// Change this object's attributes with `f`; all-default attributes are dropped.
@@ -1276,23 +1319,9 @@ mod tests {
}
#[test]
fn rectangle_corners_map_to_their_anchors() {
fn corner_kinds_save_only_when_some_corner_isnt_round() {
let mut l = LiveShape::Rectangle { w: 100.0, h: 50.0, radii: [0.0, 10.0, 0.0, 0.0], kinds: Default::default(), xf: Affine::IDENTITY };
// Anchors: top-left, the top-right corner's two, bottom-right, bottom-left.
assert_eq!(l.anchor_corners(), [0, 1, 1, 2, 3]);
assert_eq!(l.to_path().anchor_count(), 5);
let set = |v: &[usize]| v.iter().map(|ai| (0, *ai)).collect::<BTreeSet<AnchorRef>>();
assert_eq!(l.corners_of(&set(&[2, 4])), [false, true, false, true]);
assert_eq!(l.corners_of(&set(&[9])), [false; 4], "out of range");
assert_eq!(l.corner_anchors([false, true, false, true]), set(&[1, 2, 4]));
// Partly selected: the corners of the selected anchors; wholly (or no anchor): all four.
assert_eq!(l.picked_corners(Some(&set(&[0]))), [true, false, false, false]);
assert_eq!(l.picked_corners(None), [true; 4]);
assert_eq!(l.picked_corners(Some(&set(&[]))), [true; 4]);
assert_eq!(l.corner_style([false, true, false, false]), (Some(10.0), Some(CornerKind::Round)));
assert_eq!(l.corner_style([true, true, false, false]), (None, Some(CornerKind::Round)));
assert_eq!(l.corner_style([true, false, true, true]), (Some(0.0), Some(CornerKind::Round)));
// Corner kinds save only when some corner isn't round, and older files read as round.
// Older files read as round.
let json = serde_json::to_value(&l).unwrap();
assert!(json.get("kinds").is_none(), "{json}");
assert_eq!(serde_json::from_value::<LiveShape>(json).unwrap(), l);
@@ -1302,7 +1331,16 @@ mod tests {
let json = serde_json::to_value(&l).unwrap();
assert_eq!(json["kinds"], serde_json::json!(["round", "chamfer", "round", "round"]));
assert_eq!(serde_json::from_value::<LiveShape>(json).unwrap(), l);
assert!(LiveShape::Ellipse { w: 1.0, h: 1.0, pie: (0.0, 360.0), xf: Affine::IDENTITY }.anchor_corners().is_empty());
// Polygons saved before Live Corners cut theirs read as sharp; a live path round-trips.
let p: LiveShape =
serde_json::from_value(serde_json::json!({"shape": "polygon", "radius": 10.0, "sides": 5, "xf": [1, 0, 0, 1, 0, 0]})).unwrap();
assert_eq!(p, LiveShape::Polygon { radius: 10.0, sides: 5, xf: Affine::IDENTITY, radii: vec![], kinds: vec![] });
let star = shapes::star(Point::new(0.0, 0.0), 20.0, 10.0, 5, 0.0);
let path = LiveShape::Path { base: star, radii: vec![2.0; 10], kinds: vec![] };
let json = serde_json::to_value(&path).unwrap();
assert_eq!((json["shape"].as_str(), json.get("kinds")), (Some("path"), None));
assert_eq!(serde_json::from_value::<LiveShape>(json).unwrap(), path);
assert_eq!(path.label(), "Path");
}
/// A node holding a live rectangle (`w` × `h`, all radii `r`, placed by `xf`) and its path.
@@ -1427,7 +1465,8 @@ mod tests {
assert!(near_xf(*xf, Affine::translate((5.0, 5.0))));
let (a, b) = (folded.to_path().bounds().unwrap(), live.to_path().bounds().unwrap());
assert!(near(a.x0, b.x0) && near(a.y0, b.y0) && near(a.x1, b.x1) && near(a.y1, b.y1), "same place and size: {a:?} {b:?}");
assert_eq!(live.corner_style([true; 4]).0, Some(40.0), "the radius in document units");
let corners = crate::LiveCorners::of(&n).unwrap();
assert_eq!(corners.style(&corners.all()).0, Some(40.0), "the radius in document units");
// Nothing to fold: a moved, rotated or reflected rectangle and a sheared one stay as they are.
let place = Affine::translate((5.0, 5.0)) * Affine::rotate(0.5) * Affine::scale_non_uniform(-1.0, 1.0);
let shear = Affine::new([1.0, 0.0, 0.5, 1.0, 0.0, 0.0]);
+684
View File
@@ -0,0 +1,684 @@
//! Placed documents: another VectorCraft file placed linked ([`PlacedDocument`]).
//!
//! The object keeps the link to the file and the file's bytes, stored like image data in
//! [`Document::images`] (with a small preview a save writes instead, as for linked images), so the
//! document shows correctly without the file. The art it shows is read from those bytes and never
//! joins the object tree, so editing can't reach it: it is locked by design. Drawing and exporting
//! expand it like a live object ([`crate::live::expanded`]).
//!
//! The file is read by the native format's loader, which lives above this crate and registers
//! itself ([`set_loader`]); the art read is kept in a small cache by content. Before exporting,
//! every exporter calls [`Document::with_placed_art`], which adds the resources the art uses
//! (images, symbols, patterns) under names of their own ([`RESOURCE_PREFIX`]) to a temporary copy
//! of the document, so they never meet the user's or show in panels. Placed documents inside a
//! placed document are read the same way, up to [`MAX_DEPTH`] deep (documents that place each
//! other stop there, showing their previews).
use std::borrow::Cow;
use std::collections::BTreeSet;
use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError};
use serde::{Deserialize, Serialize};
use vectorcraft_geom::{Affine, Rect};
use vectorcraft_color::Paint;
use crate::{AppearanceItem, Document, ImageBlob, ImageObject, LinkInfo, Node, NodeKind, PatternDef, PlacementOptions, Symbol};
/// A placed document: an artboard of another VectorCraft file, shown as one locked object.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PlacedDocument {
/// The file (its `page` is the artboard shown, 1-based).
pub link: LinkInfo,
/// Key into [`Document::images`]: the file's bytes (see [`key_for`]).
pub key: String,
/// The art's bounds rather than the artboard (File › Place's `crop: "bounding"`).
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
pub bounding: bool,
/// The artboard's size (or the art's) at 100% (pt).
pub width: f64,
pub height: f64,
/// Maps the box (0..width, 0..height) into the document.
pub xf: Affine,
/// Links panel → Placement Options: how the file read again takes this object's place.
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
pub placement: PlacementOptions,
}
/// The images key of a file's bytes (`hash`, [`crate::links::hash_bytes`]) placed showing
/// artboard `page` (`bounding`: its art's bounds): objects showing the same thing share a blob and
/// its preview.
pub fn key_for(hash: &str, page: u32, bounding: bool) -> String {
format!("{hash}-{page}{}", if bounding { "b" } else { "" })
}
impl PlacedDocument {
/// The artboard shown (1-based).
pub fn page(&self) -> u32 {
self.link.page.unwrap_or(1)
}
/// The box at 100%.
pub fn natural(&self) -> Rect {
Rect::new(0.0, 0.0, self.width, self.height)
}
/// The four corners of the box in the document.
pub fn corners(&self) -> [vectorcraft_geom::Point; 4] {
let r = self.natural();
[(r.x0, r.y0), (r.x1, r.y0), (r.x1, r.y1), (r.x0, r.y1)].map(|(x, y)| self.xf * vectorcraft_geom::Point::new(x, y))
}
/// The box in the document (axis-aligned).
pub fn bounds(&self) -> Rect {
self.xf.transform_rect_bbox(self.natural())
}
/// The transform from the file's coordinates (its artboard or art bounds `frame`) to the
/// document; `None` when either size is empty.
pub fn art_xf(&self, frame: Rect) -> Option<Affine> {
let ok = self.width > 0.0 && self.height > 0.0 && frame.width() > 0.0 && frame.height() > 0.0;
ok.then(|| {
self.xf * Affine::scale_non_uniform(self.width / frame.width(), self.height / frame.height()) * Affine::translate((-frame.x0, -frame.y0))
})
}
/// The art the object shows, as plain objects with `n`'s id: one group, its resources named
/// as [`Document::with_placed_art`] adds them (nothing until that has read it).
pub fn art(&self, n: &Node) -> Vec<Node> {
let prefix = prefix(&self.key);
read_cached(self).and_then(|e| self.art_node(n, &e, &prefix)).into_iter().collect()
}
/// Read `e`'s art placed as this object `n` shows it (`n`'s id), its resources renamed with
/// `prefix`.
fn art_node(&self, n: &Node, e: &ReadDocument, prefix: &str) -> Option<Node> {
let m = self.art_xf(e.frame)?;
let mut g = (*e.art).clone();
rename(&mut g, prefix);
g.transform(m, true);
each_mut(&mut g, &mut |c| crate::pattern::transform_pattern_paints(c, m));
g.id = n.id;
Some(g)
}
/// An image object showing preview `bytes` (stored under this object's key) in this object's
/// box: what it shows and outputs as when the file can't be read.
pub fn preview_image(&self, bytes: &[u8]) -> Option<ImageObject> {
let (w, h) = image_size(bytes).filter(|(w, h)| *w > 0 && *h > 0)?;
let px = Affine::scale_non_uniform(self.width / w as f64, self.height / h as f64);
Some(ImageObject { key: self.key.clone(), width: w, height: h, xf: self.xf * px, link: None, placement: Default::default() })
}
}
/// The names the resources of the art stored under `key` take in a prepared document.
fn prefix(key: &str) -> String {
format!("{RESOURCE_PREFIX}{key}/")
}
/// `n` and every descendant, opacity-mask art included.
fn walk_all<'a>(n: &'a Node, f: &mut impl FnMut(&'a Node)) {
f(n);
if let Some(m) = &n.mask {
walk_all(&m.art, f);
}
for c in n.children().into_iter().flatten() {
walk_all(c, f);
}
}
/// The roots of `d`'s art: layers, symbol definitions and pattern swatches.
fn roots(d: &Document) -> impl Iterator<Item = &Arc<Node>> {
d.layers.iter().chain(d.symbols.iter().map(|s| &s.art)).chain(d.patterns.iter().flat_map(|p| &p.art))
}
fn roots_mut(d: &mut Document) -> impl Iterator<Item = &mut Arc<Node>> {
d.layers.iter_mut().chain(d.symbols.iter_mut().map(|s| &mut s.art)).chain(d.patterns.iter_mut().flat_map(|p| &mut p.art))
}
impl Document {
/// Visit every placed document: in the layers, then in symbol definitions and pattern
/// swatches, opacity-mask art included.
pub fn visit_placed<'a>(&'a self, mut f: impl FnMut(&'a Node, &'a PlacedDocument)) {
for root in roots(self) {
walk_all(root, &mut |n| {
if let NodeKind::PlacedDocument(p) = &n.kind {
f(n, p);
}
});
}
}
/// Does the document hold a placed document anywhere?
pub fn has_placed(&self) -> bool {
let mut any = false;
self.visit_placed(|_, _| any = true);
any
}
/// Every placed document (those in the art they show too) replaced by a plain group of that
/// art, for apps that don't know them: call it on [`Self::with_placed_art`]'s copy. Only the
/// subtrees holding one are copied.
pub fn placed_as_groups(&mut self) {
fn holds(n: &Node) -> bool {
let mut hit = false;
walk_all(n, &mut |c| hit |= matches!(c.kind, NodeKind::PlacedDocument(_)));
hit
}
fn update(n: &mut Arc<Node>) {
if !holds(n) {
return;
}
if matches!(n.kind, NodeKind::PlacedDocument(_)) {
let mut g = crate::live::expanded_group(n, None);
g.appearance = n.appearance.clone();
*n = Arc::new(g);
}
// The art shown may hold placed documents too.
let n = Arc::make_mut(n);
if let Some(m) = &mut n.mask {
update(&mut m.art);
}
for c in n.children_mut().into_iter().flatten() {
update(c);
}
}
for root in roots_mut(self) {
update(root);
}
}
/// Placed documents whose key is in `keys` replaced by images of their previews (for output
/// when their files can't be read).
pub fn placed_as_previews(&mut self, keys: &BTreeSet<String>) {
fn update(n: &mut Arc<Node>, keys: &BTreeSet<String>, images: &std::collections::BTreeMap<String, ImageBlob>) {
let mut hit = false;
walk_all(n, &mut |c| hit |= matches!(&c.kind, NodeKind::PlacedDocument(p) if keys.contains(&p.key)));
if !hit {
return;
}
let n = Arc::make_mut(n);
if let NodeKind::PlacedDocument(p) = &n.kind
&& keys.contains(&p.key)
{
if let Some(im) = images.get(&p.key).and_then(|b| p.preview_image(&b.bytes)) {
n.kind = NodeKind::Image(im);
}
return;
}
if let Some(m) = &mut n.mask {
update(&mut m.art, keys, images);
}
for c in n.children_mut().into_iter().flatten() {
update(c, keys, images);
}
}
let images = self.images.clone();
for root in roots_mut(self) {
update(root, keys, &images);
}
}
}
// ---------- previews and the files' bytes ----------
/// A placed document's preview: this many pixels per point of its box…
pub const PREVIEW_PX_PER_PT: f64 = 1.0;
/// …and at most this many on its longer side.
pub const PREVIEW_MAX: u32 = 1024;
/// How deep placed documents inside placed documents are read; deeper ones show their previews.
pub const MAX_DEPTH: usize = 8;
/// Reads `p`'s file again (`None`: not found, or changed since it was read). The engine registers
/// one with [`set_file_reader`].
pub type FileReader = fn(&PlacedDocument) -> Option<Vec<u8>>;
static FILE_READER: OnceLock<FileReader> = OnceLock::new();
/// Register how files are read again (the first registration stays).
pub fn set_file_reader(f: FileReader) {
// Already set: the same engine, registered by another session.
let _ = FILE_READER.set(f);
}
/// The most bytes of files read again kept.
const FULL_BYTES: usize = 512 << 20;
/// Files read again, by key, the most recently read last.
type FullFiles = Vec<(String, Arc<Vec<u8>>)>;
static FULL: Mutex<FullFiles> = Mutex::new(Vec::new());
fn full() -> MutexGuard<'static, FullFiles> {
// Entries are only pushed and removed: a panic while held leaves it whole.
FULL.lock().unwrap_or_else(PoisonError::into_inner)
}
/// The file's bytes when they are at hand: stored (`blob` isn't just the preview) or read again
/// already. Never reads it.
pub fn full_bytes_cached(p: &PlacedDocument, blob: &ImageBlob) -> Option<Arc<Vec<u8>>> {
if !blob.is_proxy() {
return Some(blob.bytes.clone());
}
full().iter().rev().find(|(k, _)| *k == p.key).map(|(_, b)| b.clone())
}
/// The file's bytes: stored, read again already, or read again now ([`set_file_reader`]). `None`
/// when only the preview can be had.
pub fn full_bytes(p: &PlacedDocument, blob: &ImageBlob) -> Option<Arc<Vec<u8>>> {
if let Some(b) = full_bytes_cached(p, blob) {
return Some(b);
}
let b = Arc::new(FILE_READER.get()?(p)?);
let mut c = full();
c.push((p.key.clone(), b.clone()));
let mut total: usize = c.iter().map(|(_, b)| b.len()).sum();
while total > FULL_BYTES && c.len() > 1 {
total = total.saturating_sub(c.remove(0).1.len());
}
Some(b)
}
/// The size in pixels of image bytes `bytes` (a preview), read from its header.
pub fn image_size(bytes: &[u8]) -> Option<(u32, u32)> {
image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().ok()?.into_dimensions().ok()
}
// ---------- reading files ----------
/// The prefix of the names the resources of placed documents' art take in a prepared document:
/// `placed:<key>/<name>`.
pub const RESOURCE_PREFIX: &str = "placed:";
/// Reads a placed document's file (its bytes) into what it shows: a document holding the
/// resources (no layers), the art as one group in the file's coordinates, and the frame shown
/// (the artboard, or the art's bounds). The native format lives above this crate, so the engine
/// registers one with [`set_loader`].
pub type Loader = fn(&PlacedDocument, &[u8]) -> Option<(Document, Node, Rect)>;
static LOADER: OnceLock<Loader> = OnceLock::new();
/// Register how files are read (the first registration stays).
pub fn set_loader(l: Loader) {
// Already set: the same loader, registered by another session.
let _ = LOADER.set(l);
}
/// The most files kept read whatever their size.
const CACHE_SIZE: usize = 64;
/// Past [`CACHE_SIZE`], the most bytes of files kept read (their own sizes, standing for what
/// reading them holds).
const CACHE_BYTES: usize = 256 << 20;
/// A placed document's file read: the art it shows, ready to draw with its own resources.
pub struct ReadDocument {
key: String,
/// Read from the preview, not the file.
preview: bool,
/// The bytes read (what tells a cached read is still the one shown).
bytes: Arc<Vec<u8>>,
/// The artboard (or art bounds) shown: what the object's box shows.
pub frame: Rect,
/// The art as one group, in the file's coordinates. Its images, symbols and patterns are
/// `doc`'s, under their own names.
pub art: Arc<Node>,
/// The file's resources and setup (no layers: the art is `art`).
pub doc: Arc<Document>,
}
struct Entry {
e: Arc<ReadDocument>,
used: u64,
}
#[derive(Default)]
struct Cache {
entries: std::collections::HashMap<(String, bool), Entry>,
clock: u64,
}
static CACHE: std::sync::LazyLock<Mutex<Cache>> = std::sync::LazyLock::new(Default::default);
fn cache() -> MutexGuard<'static, Cache> {
// A panic while the cache was held leaves it whole (entries are only inserted and removed).
CACHE.lock().unwrap_or_else(PoisonError::into_inner)
}
impl Cache {
/// The read of `key` (its preview's when `preview`; made from `bytes` when given), marked used.
fn get(&mut self, key: &str, preview: bool, bytes: Option<&Arc<Vec<u8>>>) -> Option<Arc<ReadDocument>> {
self.clock += 1;
let clock = self.clock;
let e = self.entries.get_mut(&(key.to_string(), preview))?;
if bytes.is_some_and(|b| !Arc::ptr_eq(&e.e.bytes, b)) {
return None;
}
e.used = clock;
Some(e.e.clone())
}
fn insert(&mut self, e: Arc<ReadDocument>) {
self.clock += 1;
self.entries.insert((e.key.clone(), e.preview), Entry { e, used: self.clock });
// The least recently used go while over both limits.
let mut total: usize = self.entries.values().map(|x| x.e.bytes.len()).sum();
while self.entries.len() > CACHE_SIZE && total > CACHE_BYTES {
let Some(k) = self.entries.iter().min_by_key(|(_, x)| x.used).map(|(k, _)| k.clone()) else { break };
if let Some(x) = self.entries.remove(&k) {
total = total.saturating_sub(x.e.bytes.len());
}
}
}
}
/// `p`'s file (`bytes`) read, from the cache when it was read already: what the renderer draws a
/// placed document from. `None` when it can't be read (or no loader is registered).
pub fn read(p: &PlacedDocument, bytes: &Arc<Vec<u8>>) -> Option<Arc<ReadDocument>> {
if let Some(e) = cache().get(&p.key, false, Some(bytes)) {
return Some(e);
}
let loader = LOADER.get()?;
let (doc, art, frame) = loader(p, bytes)?;
let e = Arc::new(ReadDocument { key: p.key.clone(), preview: false, bytes: bytes.clone(), frame, art: Arc::new(art), doc: Arc::new(doc) });
cache().insert(e.clone());
Some(e)
}
/// `p`'s preview (`bytes`) read as art: one image filling the box.
fn read_preview(p: &PlacedDocument, bytes: &Arc<Vec<u8>>) -> Option<Arc<ReadDocument>> {
if let Some(e) = cache().get(&p.key, true, Some(bytes)) {
return Some(e);
}
let (w, h) = image_size(bytes).filter(|(w, h)| *w > 0 && *h > 0)?;
let frame = p.natural();
let mut doc = Document::new(frame.width().max(1.0), frame.height().max(1.0));
doc.layers.clear();
doc.swatches.clear();
let mime = if bytes.starts_with(&[0xff, 0xd8]) { "image/jpeg" } else { "image/png" };
doc.images.insert("preview".into(), ImageBlob { mime: mime.into(), bytes: bytes.clone(), proxy: None });
let xf = Affine::scale_non_uniform(frame.width() / w as f64, frame.height() / h as f64);
let im = ImageObject { key: "preview".into(), width: w, height: h, xf, link: None, placement: Default::default() };
let art = Node::new(art_id(), NodeKind::Group { children: vec![Arc::new(Node::new(art_id(), NodeKind::Image(im)))], clip: false });
let e = Arc::new(ReadDocument { key: p.key.clone(), preview: true, bytes: bytes.clone(), frame, art: Arc::new(art), doc: Arc::new(doc) });
cache().insert(e.clone());
Some(e)
}
/// `p`'s file as read already (else its preview's), without reading it.
pub fn read_cached(p: &PlacedDocument) -> Option<Arc<ReadDocument>> {
let mut c = cache();
c.get(&p.key, false, None).or_else(|| c.get(&p.key, true, None))
}
/// Keep `read` (what [`Loader`] gives), just read from `bytes` for `p` (when it was placed), so
/// drawing it doesn't read it again.
pub fn prime(p: &PlacedDocument, bytes: Arc<Vec<u8>>, (doc, art, frame): (Document, Node, Rect)) {
cache().insert(Arc::new(ReadDocument { key: p.key.clone(), preview: false, bytes, frame, art: Arc::new(art), doc: Arc::new(doc) }));
}
/// The id the read art's own nodes take (their object's, once expanded).
fn art_id() -> crate::NodeId {
crate::NodeId(0)
}
/// Visit `n` and every descendant (opacity-mask art included) mutably.
fn each_mut(n: &mut Node, f: &mut impl FnMut(&mut Node)) {
f(n);
if let Some(m) = &mut n.mask {
each_mut(Arc::make_mut(&mut m.art), f);
}
for c in n.children_mut().into_iter().flatten() {
each_mut(Arc::make_mut(c), f);
}
}
/// `n`'s references to images, symbols, patterns and placed files prefixed with `prefix`. Colours
/// keep their swatch links (a spot colour stays a plate, one with the parent's spot of that name).
fn rename(n: &mut Node, prefix: &str) {
let paint = |p: &mut Paint| {
if let Paint::Pattern { pattern, .. } = p {
*pattern = format!("{prefix}{pattern}");
}
};
each_mut(n, &mut |n| {
for it in &mut n.appearance.items {
match it {
AppearanceItem::Fill(f) => paint(&mut f.paint),
AppearanceItem::Stroke(s) => paint(&mut s.paint),
}
}
match &mut n.kind {
NodeKind::Text(t) => {
for r in &mut t.runs {
paint(&mut r.style.fill);
paint(&mut r.style.stroke);
}
}
NodeKind::Image(im) => im.key = format!("{prefix}{}", im.key),
NodeKind::PlacedDocument(p) => p.key = format!("{prefix}{}", p.key),
NodeKind::SymbolInstance { symbol, .. } => *symbol = format!("{prefix}{symbol}"),
_ => {}
}
});
}
impl Document {
/// This document ready to export its placed documents: their files read (the file read again
/// when only the preview is stored, else the preview), and the resources their art uses added
/// under names of their own ([`RESOURCE_PREFIX`]); the same for the placed documents in that
/// art, up to [`MAX_DEPTH`] deep. Borrowed when there is none. (The renderer draws them from
/// [`read`] instead.)
pub fn with_placed_art(&self) -> Cow<'_, Document> {
let mut queue: Vec<(PlacedDocument, usize)> = vec![];
let mut seen = BTreeSet::new();
self.visit_placed(|_, p| {
if seen.insert(p.key.clone()) {
queue.push((p.clone(), 0));
}
});
if queue.is_empty() {
return Cow::Borrowed(self);
}
let mut d = self.clone();
let mut found: Vec<Arc<ReadDocument>> = vec![];
while let Some((p, depth)) = queue.pop() {
let Some(blob) = d.images.get(&p.key).cloned() else { continue };
let full = if depth < MAX_DEPTH { full_bytes(&p, &blob) } else { None };
if full.and_then(|b| read(&p, &b)).is_none() {
let preview = if blob.is_proxy() { Some(blob.bytes.clone()) } else { blob.proxy.clone() };
if let Some(bytes) = preview {
read_preview(&p, &bytes);
}
}
// What the art (`PlacedDocument::art`) will show.
let Some(e) = read_cached(&p) else { continue };
let prefix = prefix(&p.key);
add_resources(&mut d, &e.doc, &prefix);
// The placed documents in that art, under their names here.
let inner = std::iter::once(&e.art).chain(e.doc.symbols.iter().map(|s| &s.art)).chain(e.doc.patterns.iter().flat_map(|p| &p.art));
for root in inner {
walk_all(root, &mut |n| {
if let NodeKind::PlacedDocument(q) = &n.kind {
let key = format!("{prefix}{}", q.key);
if seen.insert(key.clone()) {
queue.push((PlacedDocument { key, ..(**q).clone() }, depth + 1));
}
}
});
}
found.push(e);
}
// Read last, so all stay read while the art is made (see `PlacedDocument::art`).
{
let mut c = cache();
for e in &found {
c.get(&e.key, e.preview, None);
}
}
Cow::Owned(d)
}
/// Drop the resources [`Self::with_placed_art`] added under its names (what a save leaves out).
pub fn drop_placed_resources(&mut self) {
self.symbols.retain(|s| !s.name.starts_with(RESOURCE_PREFIX));
self.patterns.retain(|p| !p.name.starts_with(RESOURCE_PREFIX));
self.images.retain(|k, _| !k.starts_with(RESOURCE_PREFIX));
}
}
/// The resources of `src` (a read file's) added to `d` under `prefix`: symbols, patterns, images;
/// swatches by name, when `d` has none of that name.
fn add_resources(d: &mut Document, src: &Document, prefix: &str) {
for s in &src.symbols {
let name = format!("{prefix}{}", s.name);
if !d.symbols.iter().any(|x| x.name == name) {
let mut s = s.clone();
rename(Arc::make_mut(&mut s.art), prefix);
d.symbols.push(Symbol { name, ..s });
}
}
for p in &src.patterns {
let name = format!("{prefix}{}", p.name);
if d.pattern(&name).is_none() {
let mut p = p.clone();
p.art.iter_mut().for_each(|a| rename(Arc::make_mut(a), prefix));
d.patterns.push(PatternDef { name, ..p });
}
}
for (k, b) in &src.images {
d.images.entry(format!("{prefix}{k}")).or_insert_with(|| b.clone());
}
for w in &src.swatches {
if d.swatch(&w.name).is_none() {
d.swatches.push(w.clone());
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::NodeId;
fn placed(key: &str) -> PlacedDocument {
PlacedDocument {
link: LinkInfo::new("/art/logo.vectorcraft"),
key: key.into(),
bounding: false,
width: 80.0,
height: 40.0,
xf: Affine::translate((10.0, 10.0)),
placement: Default::default(),
}
}
/// Whatever the bytes: a 40×20 artboard showing a symbol instance and, when the bytes say
/// `nest`, a placed document of key `inner`.
fn stub_loader(_: &PlacedDocument, bytes: &[u8]) -> Option<(Document, Node, Rect)> {
let mut d = Document::new(40.0, 20.0);
d.layers.clear();
let art = Node::new(
NodeId(50),
NodeKind::Image(ImageObject { key: "pic".into(), width: 1, height: 1, xf: Affine::IDENTITY, link: None, placement: Default::default() }),
);
d.symbols.push(Symbol { name: "Star".into(), art: Arc::new(art) });
d.images.insert("pic".into(), ImageBlob::new("image/png", vec![1, 2, 3]));
let mut children = vec![Arc::new(Node::new(NodeId(51), NodeKind::SymbolInstance { symbol: "Star".into(), xf: Affine::IDENTITY }))];
if bytes.starts_with(b"nest") {
d.images.insert("inner".into(), ImageBlob::new("application/json", b"leaf".to_vec()));
let inner = PlacedDocument { key: "inner".into(), width: 10.0, height: 10.0, xf: Affine::IDENTITY, ..placed("inner") };
children.push(Arc::new(Node::new(NodeId(52), NodeKind::PlacedDocument(Box::new(inner)))));
}
Some((d, Node::new(NodeId(0), NodeKind::Group { children, clip: false }), Rect::new(0.0, 0.0, 40.0, 20.0)))
}
#[test]
fn round_trips_through_json() {
let n = Node::new(NodeId(3), NodeKind::PlacedDocument(Box::new(placed("doc1-1"))));
let v = serde_json::to_value(&n).unwrap();
assert_eq!(v["kind"]["type"], "placeddocument");
assert_eq!(v["kind"]["link"]["path"], "/art/logo.vectorcraft");
let back: Node = serde_json::from_value(v).unwrap();
assert_eq!(back, n);
assert_eq!(key_for("img00", 2, true), "img00-2b");
}
#[test]
fn the_art_and_its_resources_join_only_a_prepared_copy_under_their_own_names() {
set_loader(stub_loader);
let mut d = Document::new(200.0, 200.0);
d.symbols.push(Symbol { name: "Star".into(), art: Arc::new(Node::new(NodeId(60), NodeKind::Group { children: vec![], clip: false })) });
d.images.insert("doc1-1".into(), ImageBlob::new("application/json", b"nest".to_vec()));
let p = placed("doc1-1");
let layer = d.layers[0].id;
d.insert(Some(layer), 0, Node::new(NodeId(7), NodeKind::PlacedDocument(Box::new(p.clone())))).unwrap();
assert!(d.has_placed());
let prepared = d.with_placed_art();
let names: Vec<&str> = prepared.symbols.iter().map(|s| s.name.as_str()).collect();
// The placed document inside is read too, its resources under its own names.
assert_eq!(names, ["Star", "placed:doc1-1/Star", "placed:placed:doc1-1/inner/Star"]);
assert!(prepared.images.contains_key("placed:doc1-1/pic"));
assert_eq!(d.symbols.len(), 1, "the document itself is unchanged");
// The art: a group of the drawing, its resources renamed.
let n = d.node(NodeId(7)).unwrap();
let art = p.art(n);
let [g] = &art[..] else { panic!("{art:?}") };
let mut refs = vec![];
g.walk(&mut |c| match &c.kind {
NodeKind::SymbolInstance { symbol, .. } => refs.push(symbol.clone()),
NodeKind::PlacedDocument(q) => {
// Its 10×10 box at the file's origin, scaled ×2 into the box at (10, 10).
assert_eq!(q.bounds(), Rect::new(10.0, 10.0, 30.0, 30.0));
refs.push(q.key.clone())
}
_ => {}
});
assert_eq!(refs, ["placed:doc1-1/Star", "placed:doc1-1/inner"]);
// For older apps: plain groups all the way down.
let mut older = prepared.clone().into_owned();
older.placed_as_groups();
assert!(!older.has_placed());
let mut saved = prepared.into_owned();
saved.drop_placed_resources();
assert_eq!((saved.symbols.len(), saved.images.len()), (1, 1));
}
#[test]
fn more_files_than_the_cache_holds_all_draw() {
set_loader(stub_loader);
let mut d = Document::new(200.0, 200.0);
let layer = d.layers[0].id;
let n = CACHE_SIZE + 10;
for i in 0..n {
let key = format!("many{i}-1");
d.images.insert(key.clone(), ImageBlob::new("application/json", format!("doc {i}").into_bytes()));
d.insert(Some(layer), i, Node::new(NodeId(100 + i as u64), NodeKind::PlacedDocument(Box::new(placed(&key))))).unwrap();
}
let _prepared = d.with_placed_art();
let mut empty = 0;
d.visit_placed(|n, p| empty += usize::from(p.art(n).is_empty()));
assert_eq!(empty, 0, "every file of the document is kept read");
}
#[test]
fn a_file_that_cant_be_read_shows_its_preview() {
set_loader(stub_loader);
let mut png = vec![];
image::RgbaImage::from_pixel(8, 4, image::Rgba([0, 200, 0, 255]))
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
.unwrap();
let mut blob = ImageBlob::new("image/png", png);
blob.proxy = Some(blob.bytes.clone());
let mut d = Document::new(200.0, 200.0);
d.images.insert("gone-1".into(), blob);
let layer = d.layers[0].id;
d.insert(Some(layer), 0, Node::new(NodeId(7), NodeKind::PlacedDocument(Box::new(placed("gone-1"))))).unwrap();
// No file reader: only the preview can be had.
let prepared = d.with_placed_art();
assert!(prepared.images.contains_key("placed:gone-1/preview"));
let n = d.node(NodeId(7)).unwrap();
let NodeKind::PlacedDocument(p) = &n.kind else { panic!("not a placed document") };
let art = p.art(n);
assert_eq!(art.first().and_then(Node::geometric_bounds), Some(Rect::new(10.0, 10.0, 90.0, 50.0)));
}
}
+11 -6
View File
@@ -324,14 +324,19 @@ pub fn bake_appearance(n: &Node) -> Option<Node> {
Some(m)
}
/// A copy of `doc` with every live geometry effect baked into plain paths, or `None` when the
/// document has none (export it as is).
/// A copy of `doc` ready to export: every live geometry effect baked into plain paths, and the
/// resources of its placed documents' art added ([`Document::with_placed_art`]); `None` when
/// there is nothing to do (export it as is).
pub fn bake_document(doc: &Document) -> Option<Document> {
if !doc.layers.iter().any(|l| needs_bake(l)) {
return None;
let placed = doc.with_placed_art();
if !placed.layers.iter().any(|l| needs_bake(l)) {
return match placed {
std::borrow::Cow::Owned(d) => Some(d),
std::borrow::Cow::Borrowed(_) => None,
};
}
let mut d = doc.clone();
let layers = doc.layers.clone();
let mut d = placed.into_owned();
let layers = d.layers.clone();
d.layers = layers.iter().map(|l| bake_node(&mut d, l).map(Arc::new).unwrap_or_else(|| l.clone())).collect();
Some(d)
}
+1
View File
@@ -26,6 +26,7 @@ pub fn needs_outline(n: &Node) -> bool {
| NodeKind::Envelope { .. }
| NodeKind::Mesh(_)
| NodeKind::Repeat(_)
| NodeKind::PlacedDocument(_)
)
}
+19 -3
View File
@@ -250,7 +250,8 @@ fn sb_merge(s: &mut Session, p: &Value) -> Result<Value> {
// Edges come back from the planar map within a few hundredths of the outlines they follow.
let cut_tol = step * 0.2;
let picked: Vec<&po::Region> = touched.regions.iter().filter_map(|&i| map.regions.get(i).map(|r| &r.0)).collect();
let union = if picked.is_empty() { PathData::default() } else { po::merge_regions(&picked) };
let faces = po::FaceMerger::new(&map.shapes);
let union = if picked.is_empty() { PathData::default() } else { faces.merge(&picked) };
// The merged shape takes the look of the front-most object over the first region, or (for an
// area only lines enclose) of the front-most object and the current fill.
let covered = picked.iter().find_map(|r| r.top());
@@ -278,7 +279,17 @@ fn sb_merge(s: &mut Session, p: &Value) -> Result<Value> {
// its outline, shared edges from every shape along them).
let in_union = picked.iter().any(|r| r.sources.contains(&i));
let mut rest = if in_union {
po::boolean(&sh.path, sh.rule, &union, FillRule::NonZero, po::BoolOp::Difference)
// What is left of it: its faces not merged or deleted, united. They share their
// edges with the merged faces exactly, where subtracting the merged shape left
// slivers of the outline along them (#569).
let kept: Vec<&po::Region> = map
.regions
.iter()
.enumerate()
.filter(|(k, (r, ..))| r.sources.contains(&i) && !touched.regions.contains(k))
.map(|(_, (r, ..))| r)
.collect();
if kept.is_empty() { PathData::default() } else { faces.merge(&kept) }
} else {
b::node_outline(leaf).map_or_else(|| sh.path.clone(), |o| o.0)
};
@@ -640,6 +651,11 @@ fn trace_params(p: &Value) -> Result<tr::TraceParams> {
serde_json::from_value(v).map_err(|e| bad("imageTrace.make", e.to_string()))
}
/// The most anchor points an Image Trace may make: a photo traced at high fidelity can make
/// millions, more than the canvas draws smoothly or a laptop has memory for, so the trace is
/// refused with advice instead (#525).
pub const MAX_TRACE_ANCHORS: usize = 2_000_000;
fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Value> {
const C: &str = "imageTrace.make";
let params = trace_params(p)?;
@@ -671,7 +687,7 @@ fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Value> {
};
let blob = s.doc()?.doc.images.get(&img.key).ok_or_else(|| EngineError::Other(format!("image data `{}` is missing", img.key)))?;
let raster = tr::Raster::decode(&blob.bytes).map_err(|e| EngineError::Other(e.to_string()))?;
let res = tr::trace(&raster, &params);
let res = tr::trace_within(&raster, &params, MAX_TRACE_ANCHORS).map_err(|e| EngineError::Other(e.to_string()))?;
// Pixel space of the decoded raster → the image object's pixel space → document.
let sx = img.width.max(1) as f64 / raster.width.max(1) as f64;
let sy = img.height.max(1) as f64 / raster.height.max(1) as f64;
@@ -127,6 +127,7 @@ fn node_refs(n: &Node, f: Visit) {
}
}
NodeKind::Image(im) => f(Ref::Name(Res::Image, &im.key)),
NodeKind::PlacedDocument(pl) => f(Ref::Name(Res::Image, &pl.key)),
NodeKind::SymbolInstance { symbol, .. } => f(Ref::Name(Res::Symbol, symbol)),
_ => {}
}
@@ -444,6 +445,7 @@ impl Relink {
}
}
NodeKind::Image(im) => self.name(Res::Image, &mut im.key),
NodeKind::PlacedDocument(pl) => self.name(Res::Image, &mut pl.key),
NodeKind::SymbolInstance { symbol, .. } => self.name(Res::Symbol, symbol),
_ => {}
}
+38 -2
View File
@@ -50,7 +50,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Create Text",
[],
None,
"{x, y, text, vertical?: bool = false, size?: pt, font?: family, style?, color?, area?: {width, height}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText)} → {id}",
"{x, y, text, vertical?: bool = false, size?: pt, font?: family, style?, color?, area?: {width, height}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id}",
has_doc,
text_create
),
@@ -188,7 +188,8 @@ fn polygon(s: &mut Session, p: &Value) -> Result<Value> {
let r = f64_req(p, "radius", "shape.polygon")?.abs();
let sides = p.get("sides").and_then(Value::as_u64).unwrap_or(6).clamp(3, 1000) as u32;
let rot = f64_or(p, "rotation", 0.0);
let live = LiveShape::Polygon { radius: r, sides, xf: Affine::translate(c.to_vec2()) * Affine::rotate(rot.to_radians()) };
let xf = Affine::translate(c.to_vec2()) * Affine::rotate(rot.to_radians());
let live = LiveShape::Polygon { radius: r, sides, xf, radii: vec![], kinds: vec![] };
add_art(s, "Polygon", path_kind(live.to_path(), Some(live)), None)
}
@@ -409,6 +410,7 @@ fn text_create(s: &mut Session, p: &Value) -> Result<Value> {
let mut t = TextObject::point(Point::new(x, y), text, new_type_style(s, p));
t.vertical = p.get("vertical").and_then(Value::as_bool).unwrap_or(false);
t.para = new_type_para();
new_type_alignment(s, p, "text.create", &mut t)?;
if let Some(a) = p.get("area") {
let w = f64_or(a, "width", 200.0);
let h = f64_or(a, "height", 100.0);
@@ -435,6 +437,40 @@ pub(crate) fn new_type_para() -> vectorcraft_doc::ParaStyle {
}
}
/// The leading model and character alignment new type starts with (`t`'s paragraph and runs):
/// `leadingModel` and `charAlign` from `p`, else em box top to top and em box centre while the
/// interface is in Japanese (#432), else the Roman baseline for both. Noted in the journal, so a
/// replay sets the same whatever the interface.
pub(crate) fn new_type_alignment(s: &mut Session, p: &Value, cmd: &str, t: &mut TextObject) -> Result<()> {
use vectorcraft_doc::{CharAlign, LeadingModel};
let japanese = s.japanese_interface();
let leading = match p.get("leadingModel").filter(|v| !v.is_null()) {
Some(v) => match v.as_str() {
Some("romanBaseline") => LeadingModel::RomanBaseline,
Some("emBoxTop") => LeadingModel::EmBoxTop,
_ => return Err(bad(cmd, "`leadingModel` must be \"romanBaseline\" or \"emBoxTop\"")),
},
None => {
let l = if japanese { LeadingModel::EmBoxTop } else { LeadingModel::RomanBaseline };
s.note_journal("leadingModel", json!(l));
l
}
};
let align = match super::textedit::char_align_param(p, cmd)? {
Some(a) => a,
None => {
let a = if japanese { CharAlign::EmBoxCenter } else { CharAlign::RomanBaseline };
s.note_journal("charAlign", json!(a));
a
}
};
t.para.leading_model = leading;
for r in &mut t.runs {
r.style.char_align = align;
}
Ok(())
}
/// The character style new type gets: `size`, `font`, `style` and `color` from `p`, else the
/// defaults, filled with the current fill unless that is None or white (black then).
pub(crate) fn new_type_style(s: &Session, p: &Value) -> CharStyle {
+1
View File
@@ -418,6 +418,7 @@ fn not_liquified(n: &Node) -> Option<&'static str> {
NodeKind::Mesh(_) => "meshes",
NodeKind::Envelope { .. } => "envelopes",
NodeKind::Repeat(_) => "repeats",
NodeKind::PlacedDocument(_) => "placed documents",
NodeKind::Blend { .. } => "blends",
_ => return None,
})
+3 -1
View File
@@ -49,13 +49,14 @@ pub const CATEGORIES: [(&str, &str); 11] = [
];
/// The object counts of `document.info` and their labels.
const OBJECT_LABELS: [(&str, &str); 16] = [
const OBJECT_LABELS: [(&str, &str); 17] = [
("paths", "Paths"),
("compoundPaths", "Compound Paths"),
("groups", "Groups"),
("clipGroups", "Clipping Masks"),
("textObjects", "Text Objects"),
("images", "Images"),
("placedDocuments", "Placed Documents"),
("symbolInstances", "Symbol Instances"),
("gradients", "Gradient Objects"),
("patterns", "Pattern Objects"),
@@ -252,6 +253,7 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
NodeKind::Envelope { .. } => Some("envelopes"),
NodeKind::Mesh(_) => Some("meshes"),
NodeKind::Repeat(_) => Some("repeats"),
NodeKind::PlacedDocument(_) => Some("placedDocuments"),
};
if let Some(k) = k {
*counts.entry(k).or_default() += 1;
+8 -5
View File
@@ -701,13 +701,16 @@ fn reshape_segment(s: &mut Session, p: &Value) -> Result<Value> {
return Err(EngineError::Other("no such segment".into()));
}
let n = sp.anchors.len();
// Moving both inner control points by v moves B(t) by 3t(1-t)·v.
// Moving both inner control points by v moves B(t) by 3t(1-t)·v. A smooth anchor stays
// smooth: its other handle turns with the moved one.
let v = dv / (3.0 * t * (1.0 - t));
let (i0, i1) = (seg % n, (seg + 1) % n);
let a = sp.anchors[i0];
sp.anchors[i0] = Anchor::with_handles(a.p, a.h_in, a.h_out + v);
let b = sp.anchors[i1];
sp.anchors[i1] = Anchor::with_handles(b.p, b.h_in + v, b.h_out);
if let Some(a) = sp.anchors.get_mut(i0) {
a.set_handle(true, a.h_out + v, false);
}
if let Some(b) = sp.anchors.get_mut(i1) {
b.set_handle(false, b.h_in + v, false);
}
Ok(())
})?;
ok()
+28 -4
View File
@@ -1,6 +1,7 @@
//! Object → Expand: live shapes, type and effects (Object), strokes (Stroke) and gradient fills
//! (Fill) into plain art in one undo step. A linear or radial gradient fill becomes a gradient mesh,
//! or solid strips / concentric ellipses, inside a clip group shaped like the object; a freeform
//! (Fill) into plain art in one undo step. Placed documents (Object) become editable copies of the
//! art they show, their resources joining the document. A linear or radial gradient fill becomes a
//! gradient mesh, or solid strips / concentric ellipses, inside a clip group shaped like the object; a freeform
//! gradient becomes a mesh shaped like the object. Create Gradient Mesh shares the sampling.
use std::sync::Arc;
@@ -36,7 +37,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Expand…",
["Object"],
None,
"{object?: true (type → outlines, live shapes → paths, effects baked, blends → groups of their steps, envelopes → their distorted content), fill?: true (gradient fills → `gradient` art), stroke?: true (strokes → filled outlines), gradient?: \"objects\" (default: `steps` solid strips, concentric ellipses for radial gradients) | \"mesh\" (a gradient mesh), both in a clip group shaped like the object (freeform gradients always become a mesh shaped like it), steps?: 1..1000 (255)} one undo step → {ids}",
"{object?: true (type → outlines, live shapes → paths, effects baked, blends → groups of their steps, envelopes → their distorted content, placed documents → editable copies of their art, as placing the file without link gives, its symbols, patterns, swatches and images joining the document), fill?: true (gradient fills → `gradient` art), stroke?: true (strokes → filled outlines), gradient?: \"objects\" (default: `steps` solid strips, concentric ellipses for radial gradients) | \"mesh\" (a gradient mesh), both in a clip group shaped like the object (freeform gradients always become a mesh shaped like it), steps?: 1..1000 (255)} one undo step → {ids}",
has_selection,
expand
),
@@ -55,6 +56,21 @@ pub fn specs() -> Vec<CommandSpec> {
]
}
/// Every placed document in `roots` of `d` (at any depth) replaced by an editable copy of the art it
/// shows, keeping its id and place; the resources the art uses join `d` (a name `d` uses for
/// something else gets a free variant).
fn expand_placed_under(d: &mut Document, roots: &[NodeId]) -> Result<()> {
let mut ids = vec![];
for n in roots.iter().filter_map(|r| d.node(*r)) {
n.walk(&mut |c| {
if matches!(c.kind, NodeKind::PlacedDocument(_)) {
ids.push(c.id);
}
});
}
ids.into_iter().try_for_each(|id| super::place::document::expand(d, id, C))
}
/// Expand Gradient To.
#[derive(Clone, Copy, Debug, PartialEq)]
enum GradientTo {
@@ -88,6 +104,8 @@ struct Expandable {
envelope: bool,
/// Live blends (Object expands them into groups of their steps).
blends: bool,
/// Placed documents (Object expands them into the art they show).
placed: bool,
}
impl Expandable {
@@ -101,6 +119,7 @@ impl Expandable {
e.effects |= !c.appearance.effects.is_empty();
e.envelope |= matches!(c.kind, NodeKind::Envelope { .. });
e.blends |= matches!(c.kind, NodeKind::Blend { .. });
e.placed |= matches!(c.kind, NodeKind::PlacedDocument(_));
e.stroke |= shape && !c.appearance.stroke_paint().is_none();
e.fill |= match &c.kind {
NodeKind::Text(t) => t.runs.iter().any(|r| matches!(r.style.fill, Paint::Gradient(_))),
@@ -112,7 +131,7 @@ impl Expandable {
}
fn object(&self) -> bool {
self.text || self.live || self.effects || self.envelope || self.blends
self.text || self.live || self.effects || self.envelope || self.blends || self.placed
}
}
@@ -135,6 +154,11 @@ fn expand(s: &mut Session, p: &Value) -> Result<Value> {
let from = s.doc()?.history.undo.len();
let rev0 = s.doc()?.revision;
let e = Expandable::of(&s.doc()?.doc, &selected_roots(s)?);
// Placed documents first: their art (type, strokes, gradients) expands below.
if object && e.placed {
let roots = selected_roots(s)?;
s.edit("Expand", |d, _| expand_placed_under(d, &roots))?;
}
// Blends first: what their steps hold (type, effects, strokes, gradients) expands below.
if object && e.blends {
let roots = selected_roots(s)?;
+22
View File
@@ -364,6 +364,22 @@ pub fn encode_with_warnings(doc: &Document, format: &str, p: &Value) -> Result<(
/// [`encode`], with every file the export writes.
pub fn encode_all(doc: &Document, format: &str, p: &Value) -> Result<Encoded> {
// Placed documents output their files' art (a native file keeps what it keeps: see
// `native::encode`).
if !matches!(format, "vectorcraft" | "template") {
let (full, warnings) = crate::cmd::place::document::full_documents(doc);
if !warnings.is_empty() {
let mut enc = encode_all_of(&full, format, p)?;
enc.warnings.extend(warnings);
return Ok(enc);
}
return encode_all_of(&full, format, p);
}
encode_all_of(doc, format, p)
}
/// [`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 mut enc = encode_files(doc, f, p)?;
// Formats that draw type: missing fonts come out in the fallback font (PDF and SVG say so
@@ -401,6 +417,12 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
"txt" => super::text::encode(doc, p)?,
"svg" | "svgz" => return super::svg::encode(doc, p, f.id == "svgz").map_err(|e| bad(C, e)),
"dxf" => return super::dxf::encode(doc, p, use_artboards),
// As Save As writes it (a PDF of every artboard carrying the native document).
"ai" => {
let mut q = p.clone();
super::save::ai_params(&mut q);
return super::save::encode_ai(C, f, doc, &q);
}
// EPS reads its own `useArtboards` (the art's bounds unless asked).
"eps" => return super::eps::encode(doc, p),
"emf" => return super::metafile::encode(doc, p, use_artboards, vectorcraft_metafile::Kind::Emf),
+20
View File
@@ -87,6 +87,26 @@ fn selected_part(n: &Node, keep: &HashSet<NodeId>) -> Option<Node> {
Some(out)
}
/// `doc` with only the art over `rect` (an artboard): objects whose visual bounds miss it are left
/// out, at any depth of layers and sublayers, and objects that reach it stay whole (the file's
/// bounds clip them), as DXF's crop leaves them. A clipping layer keeps every object, its clipping
/// path among them. An artboard's file then holds its own art, not a whole document of artboards.
pub(super) fn art_over(doc: &Document, rect: vectorcraft_geom::Rect) -> Document {
fn kept(n: &Arc<Node>, rect: vectorcraft_geom::Rect) -> Option<Arc<Node>> {
if matches!(n.kind, NodeKind::Layer { clip: false, .. }) {
let mut layer = Node::clone(n);
let children = layer.children_mut()?;
*children = children.iter().filter_map(|c| kept(c, rect)).collect();
return Some(Arc::new(layer));
}
let over = |b: vectorcraft_geom::Rect| b.x0 <= rect.x1 && rect.x0 <= b.x1 && b.y0 <= rect.y1 && rect.y0 <= b.y1;
n.visual_bounds().is_none_or(over).then(|| n.clone())
}
let mut d = doc.clone();
d.layers = doc.layers.iter().filter_map(|l| kept(l, rect)).collect();
d
}
/// `p` without its artboard choice, also inside its SVG options (for documents made of one
/// synthetic artboard, and for callers that pick the artboard themselves).
pub(super) fn without_artboards(p: &Value) -> Value {
+3 -3
View File
@@ -78,7 +78,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Open Document",
[],
None,
"{path} or {name, dataBase64}, PDF/.ai: pages?: \"2-3, 5\" (1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page) | false (one layer per page, without the art that is off; Save then asks for a name), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), DXF: dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its pixel size), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again). Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's <image> files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks)",
"{path} or {name, dataBase64}, PDF/.ai: pages?: \"2-3, 5\" (1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page) | false (one layer per page, without the art that is off; Save then asks for a name), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), DXF: dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its pixel size), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again). Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's <image> files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks)",
always,
load::open
),
@@ -465,8 +465,8 @@ pub const FORMATS: &[Format] = &[
extensions: &["ai"],
mime: "application/pdf",
read: true,
// Saved (Save As), not exported.
write: false,
// Save As writes it; exports write the same file.
write: true,
raster: false,
options: native::AI_OPTIONS,
},
+7
View File
@@ -127,6 +127,13 @@ pub(super) fn save_options(cmd: &str, f: &Format, doc: &Document, p: &Value) ->
/// The `.vectorcraft` file of `doc` with the options in `p`.
pub(super) fn encode(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result<Vec<u8>> {
let (mut so, extras) = save_options(cmd, f, doc, p)?;
// Include Linked Files keeps placed documents' files; older versions get their art.
let full = if so.include_linked || so.version < vectorcraft_format::VERSION {
crate::cmd::place::document::full_documents(doc).0
} else {
std::borrow::Cow::Borrowed(doc)
};
let doc = &*full;
if extras.preview {
so.preview = preview_png(doc)?;
}
+38 -23
View File
@@ -305,6 +305,35 @@ fn blank_pages(doc: &Document) -> Document {
/// Why a `.ai` file saved without PDF content looks empty elsewhere.
const NOT_PDF_COMPATIBLE: &str = "saved without PDF content: VectorCraft opens it as before, other apps show empty pages";
/// The encoder's params for a `.ai` file, from a save's or an export's: a PDF of every artboard
/// with the PDF options, always carrying the native document; Use Compression compresses the
/// PDF's content.
pub(super) fn ai_params(params: &mut Value) {
let Some(o) = params.as_object_mut() else { return };
o.extend([("preserveEditing".into(), json!(true)), ("range".into(), json!("all"))]);
if let Some(c) = o.get("compress").and_then(Value::as_bool) {
let compression = o.entry("compression").or_insert_with(|| json!({}));
if let Some(m) = compression.as_object_mut() {
m.insert("compressText".into(), json!(c));
}
}
}
/// Encode `doc` as a PDF-compatible `.ai` file (`params` as [`ai_params`] makes them) for command
/// `cmd`: its pages (blank with `pdfCompatible: false`, which it then notes), carrying the native
/// document. File › Save As writes it, and so do the exports (`document.export`, the CLI).
pub(super) fn encode_ai(cmd: &str, f: &Format, doc: &Document, params: &Value) -> Result<Encoded> {
let compatible = bool_or(params, "pdfCompatible", true);
let pages = doc.without_edit_modes();
let pages = if compatible { pages } else { std::borrow::Cow::Owned(blank_pages(&pages)) };
let native = || super::native::ai_native(cmd, f, doc, params);
let (bytes, mut warnings) = super::pdf::encode_carrying(cmd, &pages, params, native)?;
if !compatible {
warnings.insert(0, NOT_PDF_COMPATIBLE.to_string());
}
Ok(Encoded { warnings, ..Encoded::one(bytes) })
}
/// Snapshot the active document for `plan` (stamping File Info's dates when the file becomes the
/// document's own). Bad options fail here, before anything is encoded.
pub fn save_job(s: &mut Session, plan: SavePlan) -> Result<SaveJob> {
@@ -339,16 +368,8 @@ pub(crate) fn job_for(s: &Session, st: &DocState, plan: SavePlan) -> Result<Save
}
let boards = separate_boards(cmd, plan.format, &doc, &params)?;
let mut params = super::pdf::expand_preset(s, cmd, &params)?.into_owned();
if let (Some(o), "ai") = (params.as_object_mut(), plan.format.id) {
// A PDF of every artboard with the PDF options, always carrying the native document.
o.extend([("preserveEditing".into(), json!(true)), ("range".into(), json!("all"))]);
// Use Compression compresses the PDF's content.
if let Some(c) = o.get("compress").and_then(Value::as_bool) {
let compression = o.entry("compression").or_insert_with(|| json!({}));
if let Some(m) = compression.as_object_mut() {
m.insert("compressText".into(), json!(c));
}
}
if plan.format.id == "ai" {
ai_params(&mut params);
}
Ok(SaveJob { plan, doc, params, snapshot: st.doc.clone(), boards })
}
@@ -372,25 +393,14 @@ impl SaveJob {
let one = self.encode_one(&artboard_doc(&self.doc, b))?;
enc.files.extend(one.files.into_iter().map(|(_, bytes)| (Some(b), bytes)));
}
let pdf_less = self.plan.format.id == "ai" && !bool_or(&self.params, "pdfCompatible", true);
let notes = fidelity_warning(self.plan.format).into_iter().chain(pdf_less.then(|| NOT_PDF_COMPATIBLE.to_string()));
enc.warnings.splice(0..0, notes);
enc.warnings.splice(0..0, fidelity_warning(self.plan.format));
Ok(enc)
}
/// Encode one file of `doc` in the job's format.
fn encode_one(&self, doc: &Document) -> Result<Encoded> {
let (cmd, f) = (self.plan.mode.command(), self.plan.format);
let enc = if f.id == "ai" {
// The pages (blank without PDF content), carrying the native document.
let pages = doc.without_edit_modes();
let pages = if bool_or(&self.params, "pdfCompatible", true) { pages } else { std::borrow::Cow::Owned(blank_pages(&pages)) };
let native = || super::native::ai_native(cmd, f, doc, &self.params);
let (bytes, warnings) = super::pdf::encode_carrying(cmd, &pages, &self.params, native)?;
Encoded { warnings, ..Encoded::one(bytes) }
} else {
encode_all(doc, f.id, &self.params)?
};
let enc = if f.id == "ai" { encode_ai(cmd, f, doc, &self.params)? } else { encode_all(doc, f.id, &self.params)? };
if enc.files.len() != 1 {
return Err(bad(cmd, "Save writes one artboard: name one, or export several with document.export"));
}
@@ -450,12 +460,17 @@ impl SaveJob {
/// its own also ends its Data Recovery copy.
pub fn complete(self, s: &mut Session, uid: u64) {
let saved = self.plan.retargets() && self.plan.path.is_some();
// The other open documents that place this one show the new version.
let written = self.plan.path.clone().filter(|_| matches!(self.plan.format.id, "vectorcraft" | "template"));
if let Some(st) = s.document_mut(uid) {
self.finish(st);
}
if saved {
crate::cmd::recovery::forget(s, uid);
}
if let Some(path) = written {
crate::cmd::links::refresh_placed(s, uid, &path);
}
}
}
+1 -1
View File
@@ -161,7 +161,7 @@ impl Row {
return Err(bad(C, "each format is an object {format, scale?, suffix?}"));
}
let format = writable(C, Some(str_param(row, "format").unwrap_or("png")), None)?;
if matches!(format.id, "vectorcraft" | "template" | "txt" | "dxf" | "eps" | "emf" | "wmf") {
if matches!(format.id, "vectorcraft" | "template" | "ai" | "txt" | "dxf" | "eps" | "emf" | "wmf") {
return Err(bad(C, "Export for Screens writes png, png8, jpg, webp, gif, svg, svgz or pdf"));
}
// Vector formats have no pixel size: it doesn't apply and adds no @2x suffix (not even one
+13 -8
View File
@@ -19,7 +19,7 @@ pub const OPTIONS: &[FormatOption] = &[
name: "useArtboards",
ty: "boolean",
default: "true",
description: "false: one SVG of the bounds of all art instead of artboards (several artboards write one file each)",
description: "false: one SVG of the bounds of all art instead of artboards (several artboards write one file each; a named artboard's file holds only the art over it)",
},
FormatOption {
name: "styling",
@@ -125,8 +125,10 @@ pub fn options_map(p: &Value) -> Result<Map<String, Value>, String> {
Ok(m)
}
/// The writer options and the artboards (`None`: the art bounds) an SVG export of `doc` covers.
fn plan(doc: &Document, p: &Value) -> Result<(ExportOptions, Vec<Option<usize>>), String> {
/// The writer options and the artboards (`None`: the art bounds) an SVG export of `doc` covers,
/// and whether `p` named those artboards (else the first stands for the whole document, as Save
/// writes it).
fn plan(doc: &Document, p: &Value) -> Result<(ExportOptions, Vec<Option<usize>>, bool), String> {
let mut m = options_map(p)?;
// Fonts: unless chosen, Document Setup → Type → Export decides (appearance = outlines).
if !m.contains_key("outlineText") && doc.setup.export_text == vectorcraft_doc::ExportText::Appearance {
@@ -138,21 +140,24 @@ fn plan(doc: &Document, p: &Value) -> Result<(ExportOptions, Vec<Option<usize>>)
opts.check().map_err(|e| format!("SVG options: {e}"))?;
let n = doc.artboards.len();
if n == 0 || boards.use_artboards == Some(false) {
return Ok((opts, vec![None]));
return Ok((opts, vec![None], false));
}
let picked = boards.pick.resolve(n)?.unwrap_or_else(|| vec![0]);
Ok((opts, picked.into_iter().map(Some).collect()))
let named = boards.pick.resolve(n)?;
let chosen = named.is_some();
Ok((opts, named.unwrap_or_else(|| vec![0]).into_iter().map(Some).collect(), chosen))
}
/// Encode `doc` as SVG (or gzipped, SVGZ): one file per chosen artboard, with the images they
/// link to and the writer's warnings.
pub(super) fn encode(doc: &Document, p: &Value, compressed: bool) -> Result<Encoded, String> {
let (opts, boards) = plan(doc, p)?;
let (opts, boards, chosen) = plan(doc, p)?;
// Preserve editing embeds the native document (once, shared by every file).
let native = opts.preserve_editing.then(|| vectorcraft_format::save(doc, false));
let mut enc = Encoded::default();
for artboard in boards {
let mut out = vectorcraft_svg::export_full(doc, &ExportOptions { artboard, ..opts.clone() }, native.as_deref());
// A chosen artboard's file holds the art over it (#550).
let over = artboard.filter(|_| chosen).and_then(|b| doc.artboards.get(b)).map(|a| super::export::art_over(doc, a.rect));
let mut out = vectorcraft_svg::export_full(over.as_ref().unwrap_or(doc), &ExportOptions { artboard, ..opts.clone() }, native.as_deref());
let bytes = out.take_bytes();
for l in out.linked {
if !enc.linked.iter().any(|e| e.name == l.name) {
+2
View File
@@ -173,6 +173,7 @@ fn export_extensions_name_every_writable_format() {
"svg",
"svgz",
"pdf",
"ai",
"png",
"jpg",
"gif",
@@ -206,6 +207,7 @@ fn formats_query_lists_readers_writers_and_options() {
"svg",
"svgz",
"pdf",
"ai",
"png",
"jpg",
"gif",
@@ -118,6 +118,27 @@ fn ai_files_are_pdfs_that_save_and_reopen_editable() {
assert_eq!(s.doc().unwrap().path, None);
}
/// #526: the exports (`document.export`, the CLI's `--export` and `convert`) write `.ai` as Save
/// As does, leaving the document's own path alone.
#[test]
fn exports_write_ai_as_save_as_does() {
let mut s = rich();
let before = comparable(&s.doc().unwrap().doc);
let path = tmp("exported.ai");
let r = s.execute("document.export", &json!({"path": path})).unwrap();
assert_eq!(r["format"], "ai", "{r}");
let bytes = std::fs::read(&path).unwrap();
assert!(bytes.starts_with(b"%PDF") && vectorcraft_pdf::editing(&bytes).is_some_and(|e| e.intact), "PDF-compatible, carrying the document");
assert_eq!(s.doc().unwrap().path, None, "an export doesn't give the document a path");
let r = s.execute("document.open", &json!({"path": path})).unwrap();
assert_eq!((&r["format"], &r["restored"]), (&json!("ai"), &json!(true)), "{r}");
assert_eq!(comparable(&s.doc().unwrap().doc), before);
// Its options as Save As takes them; no path gives the bytes.
let r = s.execute("document.export", &json!({"format": "ai", "pdfCompatible": false})).unwrap();
assert!(r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().is_some_and(|w| w.contains("without PDF content"))), "{r}");
assert!(b64(&r).starts_with(b"%PDF"));
}
#[test]
fn ait_templates_open_their_document_untitled() {
let mut s = rich();
@@ -49,3 +49,28 @@ fn profile_and_embedded_fonts_reach_the_writer() {
assert!(s.execute("document.serialize", &json!({"format": "svg", "svg": {"profile": "svg2"}})).is_err(), "unknown profiles are refused");
assert!(s.execute("document.serialize", &json!({"format": "svg", "encoding": "ebcdic"})).is_err(), "unknown encodings are refused");
}
/// #550: an SVG of chosen artboards holds the art over each, not every artboard's art; with no
/// artboard named (as Save writes it) the whole document's art is there.
#[test]
fn a_chosen_artboard_s_svg_holds_only_its_own_art() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 3})).unwrap();
let x = |s: &Session, b: usize| s.doc().unwrap().doc.artboards[b].rect.x0;
let (first, third) = (x(&s, 0), x(&s, 2));
s.execute("shape.rectangle", &json!({"x": first + 10.0, "y": 10, "width": 30, "height": 30})).unwrap();
s.execute("shape.ellipse", &json!({"x": third + 10.0, "y": 10, "width": 30, "height": 30})).unwrap();
// A rectangle has straight sides only; the ellipse is curves.
let shapes = |svg: &str| (svg.matches("<path").count() + svg.matches("<rect").count(), svg.contains(" C") || svg.contains("<ellipse"));
let text = |v: &serde_json::Value| v["text"].as_str().unwrap().to_string();
let third_only = text(&s.execute("document.serialize", &json!({"format": "svg", "useArtboards": true, "range": "3"})).unwrap());
assert_eq!(shapes(&third_only), (1, true), "{third_only}");
let all = s.execute("document.serialize", &json!({"format": "svg", "useArtboards": true, "range": "all"})).unwrap();
let files: Vec<String> = all["files"].as_array().unwrap().iter().map(text).collect();
assert_eq!(files.iter().map(|f| shapes(f)).collect::<Vec<_>>(), [(1, false), (0, false), (1, true)]);
// Export for Screens names one artboard at a time the same way.
let screen = text(&s.execute("document.serialize", &json!({"format": "svg", "artboard": 0})).unwrap());
assert_eq!(shapes(&screen), (1, false));
let whole = text(&s.execute("document.serialize", &json!({"format": "svg"})).unwrap());
assert_eq!(shapes(&whole).0, 2, "nothing named: the whole document's art");
}
+2
View File
@@ -1185,6 +1185,8 @@ impl Scratch {
let art = self.doc.symbols.iter().find(|s| &s.name == symbol).map(|s| vectorcraft_render::instance_art(&s.art, n));
art.and_then(|a| effects::outline_art(n, Some(&a))).map(|g| carry(n, g))
}
// A placed document stays one: its art's resources aren't the document's.
NodeKind::PlacedDocument(_) => None,
NodeKind::Blend { .. } | NodeKind::Envelope { .. } | NodeKind::Repeat(_) => {
let hook: &dyn Fn(&Node) -> Option<Node> = &effects::outline_text;
Some(carry(n, vectorcraft_doc::live::expanded_group(n, Some(hook))))
+364 -118
View File
@@ -16,13 +16,17 @@
//! selects one (`links.goTo`), Embed keeps a linked file's pixels in the document
//! (`links.embed`) and Unembed writes an embedded image to a file it then links to
//! (`links.unembed`).
//!
//! Placed documents ([`PlacedDocument`], VectorCraft documents placed with Link) link to their
//! files the same way: checking, updating, relinking and finding them on open work alike, and they
//! are listed. Embed (Break Link) turns one into an editable copy of its art.
use std::collections::BTreeMap;
use std::path::{Component, Path};
use serde_json::{Value, json};
use vectorcraft_doc::links::{Align, Preserve, hash_bytes};
use vectorcraft_doc::{Appearance, Document, ImageBlob, ImageObject, LinkInfo, Node, NodeId, NodeKind, PlacementOptions};
use vectorcraft_doc::{Appearance, Document, ImageBlob, ImageObject, LinkInfo, Node, NodeId, NodeKind, PlacedDocument, PlacementOptions};
use vectorcraft_geom::{Affine, Rect, shapes};
use super::fileio::{self, RasterImage, absolute_path, file_created, file_stamp, read_file, write_file};
@@ -35,7 +39,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Check Links",
[],
None,
"{ids?: [image ids] (default: every linked image)} where each linked file is and whether it changed since it was read → {links: [{name, path, status: ok|modified|missing, ids, found?: path (found away from its path: relative to the document, or by name in its folder), preview: true (showing the low-resolution preview, not the file)}], missing, modified}",
"{ids?: [image or placed document ids] (default: every linked image and placed document)} where each linked file is and whether it changed since it was read → {links: [{name, path, status: ok|modified|missing, ids, found?: path (found away from its path: relative to the document, or by name in its folder), preview: true (showing the low-resolution preview, not the file)}], missing, modified}",
has_doc,
check
),
@@ -44,7 +48,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Update Links",
[],
None,
"{ids?: [image ids] (default: the linked images whose file was modified or is showing its preview)} read their linked files again; each image keeps its bounds. One undo step → {updated: [ids], missing: [ids]}",
"{ids?: [image or placed document ids] (default: the linked images whose file was modified or is showing its preview, and placed documents whose file was modified)} read their linked files again; each keeps its bounds. One undo step → {updated: [ids], missing: [ids]}",
has_doc,
update
),
@@ -53,7 +57,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Relink",
[],
None,
"{ids?: [image ids] (default: the selected images; with folder and nothing selected, every missing link), path | folder} link images to the file at path, or each to the file of its link's name in folder; embedded images become linked; each keeps its bounds. One undo step → {relinked: [ids], notFound: [file names]}",
"{ids?: [image or placed document ids] (default: the selected ones; with folder and nothing selected, every missing link), path | folder} link images (or placed documents, each showing the same artboard of the new file) to the file at path, or each to the file of its link's name in folder; embedded images become linked; each keeps its bounds. One undo step → {relinked: [ids], notFound: [file names]}",
has_doc,
relink
),
@@ -62,7 +66,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 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)}], 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), document?: true (a placed document: pageWidth and pageHeight in pt instead of pixels)}], missing, modified, embedded}",
has_doc,
list
),
@@ -71,7 +75,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Go To Link",
[],
None,
"{id?} select image `id` (default: the first selected image); the Links panel scrolls it into view → {id, bounds: [x0, y0, x1, y1]}",
"{id?} select image or placed document `id` (default: the first selected one); the Links panel scrolls it into view → {id, bounds: [x0, y0, x1, y1]}",
has_doc,
go_to
),
@@ -80,7 +84,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Embed Image",
[],
None,
"{ids?: [image ids] (default: the selected linked images)} keep the linked files' pixels in the document and drop the links (an image whose file can't be found and that shows the saved preview stays linked: relink it first). One undo step → {embedded: [ids], missing: [ids]}",
"{ids?: [image or placed document ids] (default: the selected linked ones)} break the links (the Links panel's Break Link): images keep the linked files' pixels in the document; a placed document becomes an editable copy of its art, as placing its file without link gives (its symbols, patterns, swatches and images joining the document). An image whose file can't be found and that shows the saved preview, or a placed document whose file can't be read or changed, stays linked: relink or update it first. One undo step → {embedded: [ids], missing: [ids]}",
has_doc,
embed
),
@@ -98,7 +102,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Link Info",
[],
None,
"{id?} an image's Link Info (default: the one selected) → image.info's fields (id, name, linked, link, colorMode, pixelWidth, pixelHeight, width, height) and status: ok|modified|missing|embedded, format, ppi: [x, y] (the file's), effectivePpi: [x, y] (at its placed size), scale: [x%, y%] (of its 100% size), rotation (degrees, counter-clockwise), placement: {preserve, align, clip}; linked images also fileName, location (its folder), page?, fileSize? (bytes), modified?, created? (ms since the Unix epoch)",
"{id?} an image's or placed document's Link Info (default: the one selected) → image.info's fields (id, name, linked, link, colorMode, pixelWidth, pixelHeight, width, height) and status: ok|modified|missing|embedded, format, ppi: [x, y] (the file's), effectivePpi: [x, y] (at its placed size), scale: [x%, y%] (of its 100% size), rotation (degrees, counter-clockwise), placement: {preserve, align, clip}; linked images also fileName, location (its folder), page?, fileSize? (bytes), modified?, created? (ms since the Unix epoch); a placed document has document: true, pageWidth and pageHeight (pt) instead of pixels, ppi and colorMode, and its scale is of its artboard's 100% size",
has_doc,
info
),
@@ -107,7 +111,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Placement Options",
[],
None,
"{ids?: [image ids] (default: the selected images), preserve?: transforms|bounds (default)|fileDimensions|fit|fill, align?: topLeft|top|topRight|left|center (default)|right|bottomLeft|bottom|bottomRight (where the new art sits; not for bounds), clip?: false (clip it to the old bounds where it is larger)} how a file read again (links.relink, links.update) takes each image's place: transforms keeps its scale (relative to each file's 100% size), rotation and position; bounds stretches it into the old bounds; fileDimensions puts it at 100%, unrotated; fit and fill scale it proportionally to fit inside or cover the old bounds. Without options → {placement} of the first image; else one undo step → {ids, placement}",
"{ids?: [image or placed document ids] (default: the selected ones), preserve?: transforms|bounds (default)|fileDimensions|fit|fill, align?: topLeft|top|topRight|left|center (default)|right|bottomLeft|bottom|bottomRight (where the new art sits; not for bounds), clip?: false (clip it to the old bounds where it is larger)} how a file read again (links.relink, links.update) takes each image's place: transforms keeps its scale (relative to each file's 100% size), rotation and position; bounds stretches it into the old bounds; fileDimensions puts it at 100%, unrotated; fit and fill scale it proportionally to fit inside or cover the old bounds. Without options → {placement} of the first image; else one undo step → {ids, placement}",
has_doc,
placement_options
),
@@ -134,22 +138,34 @@ impl Status {
}
}
/// The image objects that show one linked file as one content (same path, same image).
/// The image objects that show one linked file as one content (same path, same image), or the
/// placed documents that show one artboard of it.
struct Group {
link: LinkInfo,
key: String,
/// The objects in the layers (images in symbols and patterns share the content, not an id).
ids: Vec<NodeId>,
/// Placed documents: whether the art's bounds (not the artboard) are shown.
document: Option<bool>,
}
/// The linked images of `d` by file and content: those in the layers (only `ids` when given), then,
/// without `ids`, the ones only symbols and patterns show.
/// The linked object `n` as (link, content key, placed document's bounding).
fn linked(n: &Node) -> Option<(&LinkInfo, &str, Option<bool>)> {
match &n.kind {
NodeKind::Image(im) => Some((im.link.as_ref()?, &im.key, None)),
NodeKind::PlacedDocument(p) => Some((&p.link, &p.key, Some(p.bounding))),
_ => None,
}
}
/// The linked images and placed documents of `d` by file and content: those in the layers (only `ids` when
/// given), then, without `ids`, the ones only symbols and patterns show.
fn groups(d: &Document, ids: Option<&[NodeId]>) -> Vec<Group> {
let mut out: Vec<Group> = vec![];
let mut index: BTreeMap<(String, String), usize> = BTreeMap::new();
let mut add = |link: &LinkInfo, key: &str, id: Option<NodeId>| {
let i = *index.entry((link.path.clone(), key.to_string())).or_insert_with(|| {
out.push(Group { link: link.clone(), key: key.to_string(), ids: vec![] });
let mut index: BTreeMap<(String, String, bool), usize> = BTreeMap::new();
let mut add = |link: &LinkInfo, key: &str, document: Option<bool>, id: Option<NodeId>| {
let i = *index.entry((link.path.clone(), key.to_string(), document.is_some())).or_insert_with(|| {
out.push(Group { link: link.clone(), key: key.to_string(), ids: vec![], document });
out.len() - 1
});
if let (Some(id), Some(g)) = (id, out.get_mut(i)) {
@@ -157,19 +173,19 @@ fn groups(d: &Document, ids: Option<&[NodeId]>) -> Vec<Group> {
}
};
d.walk(|n| {
if let NodeKind::Image(im) = &n.kind
&& let Some(l) = &im.link
if let Some((l, key, document)) = linked(n)
&& ids.is_none_or(|ids| ids.contains(&n.id))
{
add(l, &im.key, Some(n.id));
add(l, key, document, Some(n.id));
}
});
if ids.is_none() {
d.visit_images(|_, im| {
if let Some(l) = &im.link {
add(l, &im.key, None);
add(l, &im.key, None, None);
}
});
d.visit_placed(|_, p| add(&p.link, &p.key, Some(p.bounding), None));
}
out
}
@@ -238,7 +254,7 @@ fn probe(g: &Group, dir: Option<&Path>) -> (Status, Option<Found>) {
let same = match &l.hash {
Some(h) => *h == hash_bytes(&bytes),
// Linked before links kept a hash: the image the file decodes to.
None => fileio::raster_image(&bytes).is_ok_and(|img| img.key == g.key),
None => g.document.is_none() && fileio::raster_image(&bytes).is_ok_and(|img| img.key == g.key),
};
f.bytes = Some(bytes);
(if same { Status::Ok } else { Status::Modified }, Some(f))
@@ -254,6 +270,15 @@ fn previewing(d: &Document, key: &str) -> bool {
d.images.get(key).is_none_or(ImageBlob::is_proxy)
}
/// Does group `g` of `d` show something other than its file: an image its preview, a placed
/// document nothing (its file's bytes are gone)?
fn stale(d: &Document, g: &Group) -> bool {
match g.document {
None => previewing(d, &g.key),
Some(_) => !d.images.contains_key(&g.key),
}
}
/// A linked file of a document (File → Package): its path, name and bytes.
pub(crate) struct LinkedFile {
pub path: String,
@@ -301,6 +326,51 @@ fn read_image(f: &mut Found, base: &LinkInfo) -> Result<FileRead> {
Ok((f.link(&bytes, base), fileio::raster_image(&bytes)?))
}
/// A linked file read for the objects that show it.
enum Read {
Image(FileRead),
/// A VectorCraft document read for placed documents: the link to it and what they show.
Document(LinkInfo, super::place::document::Source),
}
/// The file at `f` read for group `g`: its image, or the artboard `g` shows.
fn read_for(f: &mut Found, g: &Group, cmd: &str) -> Result<Read> {
let Some(bounding) = g.document else { return read_image(f, &g.link).map(Read::Image) };
let bytes = f.read()?;
let page = g.link.page.unwrap_or(1);
let src = super::place::document::source(&f.path, &bytes, Some(&f.path), page, bounding, cmd)?;
Ok(Read::Document(f.link(&bytes, &g.link), src))
}
/// Objects `ids` show what was read (see [`install`], [`install_document`]).
fn install_read(d: &mut Document, ids: &[NodeId], read: Read, keep_bounds: bool) -> Result<()> {
match read {
Read::Image(r) => install(d, ids, r, keep_bounds),
Read::Document(link, src) => install_document(d, ids, &link, &src, keep_bounds),
}
}
/// Placed documents `ids` show `src`, read from the file `link` points at, each placed as its
/// Placement Options say (`keep_bounds`: in its bounds, whatever they say).
fn install_document(d: &mut Document, ids: &[NodeId], link: &LinkInfo, src: &super::place::document::Source, keep_bounds: bool) -> Result<()> {
let mut clips = vec![];
let (w, h) = (src.frame.width(), src.frame.height());
for id in ids {
let Some(NodeKind::PlacedDocument(p)) = d.node(*id).map(|n| &n.kind) else { continue };
let o = if keep_bounds { PlacementOptions { preserve: Preserve::Bounds, ..p.placement } } else { p.placement };
let (xf, clip) = placed_xf(p.xf, (p.width, p.height), (1.0, 1.0), (w, h), (1.0, 1.0), o);
if let Some(n) = d.node_mut(*id)
&& let NodeKind::PlacedDocument(p) = &mut n.kind
{
let p: &mut PlacedDocument = p;
(p.key, p.width, p.height, p.xf, p.link) = (src.key.clone(), w, h, xf, link.clone());
}
clips.extend(clip.map(|c| (*id, c)));
}
super::place::document::store(d, src);
clips.into_iter().try_for_each(|(id, clip)| clip_image(d, id, clip))
}
/// Points per pixel of the file image `key` of `d` shows, at the resolution it declares (72 ppi
/// when it declares none, or when only its preview is loaded).
fn file_pt(d: &Document, key: &str) -> (f64, f64) {
@@ -318,9 +388,10 @@ type Clip = (Affine, (f64, f64));
/// The transform an image placed with `xf` showing `old` pixels (`old_pt`: points per pixel at
/// 100%) gives a new file of `new` pixels (`new_pt`), as Placement Options `o` say; and the clip
/// when `o.clip` and the new art overflows the old bounds.
fn placed_xf(xf: Affine, old: (u32, u32), old_pt: (f64, f64), new: (u32, u32), new_pt: (f64, f64), o: PlacementOptions) -> (Affine, Option<Clip>) {
let (ow, oh, nw, nh) = (old.0 as f64, old.1 as f64, new.0.max(1) as f64, new.1.max(1) as f64);
/// when `o.clip` and the new art overflows the old bounds. (A placed document's "pixels" are points,
/// one point each.)
fn placed_xf(xf: Affine, old: (f64, f64), old_pt: (f64, f64), new: (f64, f64), new_pt: (f64, f64), o: PlacementOptions) -> (Affine, Option<Clip>) {
let (ow, oh, nw, nh) = (old.0, old.1, new.0.max(1e-9), new.1.max(1e-9));
let [a, b, c, d, ..] = xf.as_coeffs();
// The bounds' frame: the transform without its scale (rotation, reflection and position).
let (su, sv) = (a.hypot(b), c.hypot(d));
@@ -388,7 +459,8 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, keep_bounds:
for id in ids {
let Some(NodeKind::Image(im)) = d.node(*id).map(|n| &n.kind) else { continue };
let o = if keep_bounds { PlacementOptions { preserve: Preserve::Bounds, ..im.placement } } else { im.placement };
let (xf, clip) = placed_xf(im.xf, (im.width, im.height), file_pt(d, &im.key), (img.width, img.height), new_pt, o);
let size = |w: u32, h: u32| (w as f64, h as f64);
let (xf, clip) = placed_xf(im.xf, size(im.width, im.height), file_pt(d, &im.key), size(img.width, img.height), new_pt, o);
if let Some(n) = d.node_mut(*id)
&& let NodeKind::Image(im) = &mut n.kind
{
@@ -436,11 +508,34 @@ pub fn resolve(d: &mut Document, doc_path: Option<&str>, update: bool) -> Resolv
let row = rows(std::iter::once(&g));
match probe(&g, folder(doc_path)) {
(Status::Missing, _) => out.missing.extend(row),
(Status::Modified, Some(mut f)) if update => match read_image(&mut f, &g.link).and_then(|read| install(d, &g.ids, read, false)) {
Ok(()) => out.updated.extend(row),
Err(_) => out.missing.extend(row),
},
(Status::Modified, Some(mut f)) if update => {
match read_for(&mut f, &g, "document.open").and_then(|read| install_read(d, &g.ids, read, false)) {
Ok(()) => out.updated.extend(row),
Err(_) => out.missing.extend(row),
}
}
(Status::Modified, _) => out.modified.extend(row),
// A placed document keeps its file's bytes: only lost ones are read again.
(Status::Ok, Some(mut f)) if g.document.is_some() => {
let read = if stale(d, &g) { Some(read_for(&mut f, &g, "document.open")) } else { None };
match read {
Some(Ok(read)) => {
if install_read(d, &g.ids, read, true).is_err() {
out.missing.extend(row);
}
}
Some(Err(_)) => out.missing.extend(row),
None => {
let link = match f.bytes.take() {
Some(b) => f.link(&b, &g.link),
None => LinkInfo { path: f.path.clone(), ..g.link.clone() },
};
if link != g.link {
set_links(d, &g.ids, &link);
}
}
}
}
(Status::Ok, Some(mut f)) => {
let preview = previewing(d, &g.key);
// Read when the images show the preview, or when the file's details changed.
@@ -471,17 +566,58 @@ pub fn resolve(d: &mut Document, doc_path: Option<&str>, update: bool) -> Resolv
out
}
/// Image objects `ids` link to `link`.
/// The link of linked object `n` (a linked image or a placed document) to change.
fn link_mut(n: &mut Node) -> Option<&mut LinkInfo> {
match &mut n.kind {
NodeKind::Image(im) => im.link.as_mut(),
NodeKind::PlacedDocument(p) => Some(&mut p.link),
_ => None,
}
}
/// Linked image objects (or placed documents) `ids` link to `link`.
fn set_links(d: &mut Document, ids: &[NodeId], link: &LinkInfo) {
for id in ids {
if let Some(n) = d.node_mut(*id)
&& let NodeKind::Image(im) = &mut n.kind
{
im.link = Some(link.clone());
if let Some(l) = d.node_mut(*id).and_then(link_mut) {
*l = link.clone();
}
}
}
/// Placed documents of the document saved at `path` (document `saved` of `s`) in the other open
/// documents: read again from the new file, each as one Update Links step of its document.
pub(crate) fn refresh_placed(s: &mut Session, saved: u64, path: &str) {
let path = absolute_path(path);
let targets: Vec<(usize, Vec<u64>)> = s
.documents()
.iter()
.enumerate()
.filter(|(_, st)| st.uid != saved)
.filter_map(|(i, st)| {
let mut ids = vec![];
st.doc.walk(|n| {
if let NodeKind::PlacedDocument(p) = &n.kind
&& p.link.path == path
{
ids.push(n.id.0);
}
});
(!ids.is_empty()).then_some((i, ids))
})
.collect();
if targets.is_empty() {
return;
}
// Each document is updated as the active one, without switching tools.
let back = s.active;
for (i, ids) in targets {
s.active = Some(i);
// A file that can't be read leaves what its objects show: links.check reports it.
let _ = update(s, &json!({ "ids": ids }));
}
s.active = back;
}
// ---------- relative paths ----------
/// `target` relative to folder `base` with `/` separators; `None` when they share no root (another
@@ -509,9 +645,7 @@ pub fn with_relative_paths(d: &Document, dest: &str) -> Option<Document> {
let dir = Path::new(&dest).parent()?;
let mut changes = vec![];
d.walk(|n| {
if let NodeKind::Image(im) = &n.kind
&& let Some(l) = &im.link
{
if let Some((l, _, _)) = linked(n) {
let r = relative_path(Path::new(&l.path), dir);
if r != l.relative {
changes.push((n.id, r));
@@ -523,10 +657,7 @@ pub fn with_relative_paths(d: &Document, dest: &str) -> Option<Document> {
}
let mut d = d.clone();
for (id, r) in changes {
if let Some(n) = d.node_mut(id)
&& let NodeKind::Image(im) = &mut n.kind
&& let Some(l) = &mut im.link
{
if let Some(l) = d.node_mut(id).and_then(link_mut) {
l.relative = r;
}
}
@@ -548,7 +679,7 @@ fn check(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(f) = found.filter(|f| f.path != g.link.path) {
row["found"] = json!(f.path);
}
if previewing(&st.doc, &g.key) {
if stale(&st.doc, g) {
row["preview"] = json!(true);
}
links.push(row);
@@ -564,9 +695,9 @@ fn update(s: &mut Session, p: &Value) -> Result<Value> {
match probe(&g, folder(st.path.as_deref())) {
(Status::Missing, _) | (_, None) => missing.extend(ids_json(&g.ids)),
// Unchanged and showing the file: nothing to read unless asked for by id.
(Status::Ok, Some(_)) if ids.is_none() && !previewing(&st.doc, &g.key) => {}
// Unreadable as an image counts as missing.
(_, Some(mut f)) => match read_image(&mut f, &g.link) {
(Status::Ok, Some(_)) if ids.is_none() && !stale(&st.doc, &g) => {}
// Unreadable as an image (or a document) counts as missing.
(_, Some(mut f)) => match read_for(&mut f, &g, "links.update") {
Ok(read) => reads.push((g.ids, read)),
Err(_) => missing.extend(ids_json(&g.ids)),
},
@@ -574,7 +705,7 @@ fn update(s: &mut Session, p: &Value) -> Result<Value> {
}
let updated: Vec<u64> = reads.iter().flat_map(|(ids, _)| ids_json(ids)).collect();
if !reads.is_empty() {
s.edit("Update Links", |d, _| reads.into_iter().try_for_each(|(ids, read)| install(d, &ids, read, false)))?;
s.edit("Update Links", |d, _| reads.into_iter().try_for_each(|(ids, read)| install_read(d, &ids, read, false)))?;
}
Ok(json!({ "updated": updated, "missing": missing }))
}
@@ -583,7 +714,14 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "links.relink";
let st = s.doc()?;
let folder_param = str_param(p, "folder");
let image = |id: &NodeId| st.doc.node(*id).and_then(|n| if let NodeKind::Image(im) = &n.kind { Some(im) } else { None });
// An image or a placed document, with its link.
let image = |id: &NodeId| {
st.doc.node(*id).and_then(|n| match &n.kind {
NodeKind::Image(im) => Some(im.link.as_ref()),
NodeKind::PlacedDocument(p) => Some(Some(&p.link)),
_ => None,
})
};
let ids: Vec<NodeId> = match ids_param(p, "ids") {
Some(ids) => ids,
None => {
@@ -599,7 +737,7 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
}
};
if let Some(id) = ids.iter().find(|id| image(id).is_none()) {
return Err(bad(C, format!("object {} is not an image", id.0)));
return Err(bad(C, format!("object {} is not an image or a linked file", id.0)));
}
if ids.is_empty() {
return Err(bad(C, "select the images to relink, or pass ids"));
@@ -611,7 +749,7 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
(Some(path), _) => files.push((ids, absolute_path(path))),
(None, Some(dir)) => {
for id in ids {
let Some(link) = image(&id).and_then(|im| im.link.as_ref()) else { continue };
let Some(link) = image(&id).flatten() else { continue };
let path = absolute_path(&Path::new(dir).join(link.name()).to_string_lossy());
match files.iter_mut().find(|(_, p)| *p == path) {
Some((ids, _)) => ids.push(id),
@@ -625,12 +763,34 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
let mut reads = vec![];
for (ids, path) in files {
let bytes = read_file(&path)?;
let img = fileio::raster_image(&bytes).map_err(|e| bad(C, format!("{path}: {e}")))?;
reads.push((ids, (link_info(&path, &bytes), img)));
let link = link_info(&path, &bytes);
// Images show the file; placed documents each show their artboard of it.
let mut images = vec![];
let mut documents: Vec<((u32, bool), Vec<NodeId>)> = vec![];
for id in ids {
match st.doc.node(id).map(|n| &n.kind) {
Some(NodeKind::PlacedDocument(pl)) => {
let k = (pl.page(), pl.bounding);
match documents.iter_mut().find(|(e, _)| *e == k) {
Some((_, ids)) => ids.push(id),
None => documents.push((k, vec![id])),
}
}
_ => images.push(id),
}
}
if !images.is_empty() {
let img = fileio::raster_image(&bytes).map_err(|e| bad(C, format!("{path}: {e}")))?;
reads.push((images, Read::Image((link.clone(), img))));
}
for ((page, bounding), ids) in documents {
let src = super::place::document::source(&path, &bytes, Some(&path), page, bounding, C)?;
reads.push((ids, Read::Document(LinkInfo { page: Some(page), ..link.clone() }, src)));
}
}
let relinked: Vec<u64> = reads.iter().flat_map(|(ids, _)| ids_json(ids)).collect();
if !reads.is_empty() {
s.edit("Relink", |d, _| reads.into_iter().try_for_each(|(ids, read)| install(d, &ids, read, false)))?;
s.edit("Relink", |d, _| reads.into_iter().try_for_each(|(ids, read)| install_read(d, &ids, read, false)))?;
}
not_found.sort();
not_found.dedup();
@@ -652,18 +812,6 @@ fn selected_images(st: &crate::DocState, keep: impl Fn(&ImageObject) -> bool) ->
st.selection.objects.iter().copied().filter(|id| image_of(&st.doc, *id).is_some_and(&keep)).collect()
}
/// `ids` (else the selected images `keep` accepts), checked to be images; an error when none.
fn images_param(st: &crate::DocState, p: &Value, cmd: &str, keep: impl Fn(&ImageObject) -> bool) -> Result<Vec<NodeId>> {
let ids = ids_param(p, "ids").unwrap_or_else(|| selected_images(st, keep));
if let Some(id) = ids.iter().find(|id| image_of(&st.doc, **id).is_none()) {
return Err(bad(cmd, format!("object {} is not an image", id.0)));
}
if ids.is_empty() {
return Err(bad(cmd, "select the images, or pass ids"));
}
Ok(ids)
}
/// `id`, else the first selected image.
fn image_param(st: &crate::DocState, p: &Value, cmd: &str) -> Result<NodeId> {
let id = id_param(p, "id").or_else(|| selected_images(st, |_| true).first().copied()).ok_or_else(|| bad(cmd, "select an image, or pass id"))?;
@@ -674,6 +822,35 @@ fn image_param(st: &crate::DocState, p: &Value, cmd: &str) -> Result<NodeId> {
}
}
/// The Placement Options of image or placed document `n`.
fn placement_mut(n: &mut Node) -> Option<&mut PlacementOptions> {
match &mut n.kind {
NodeKind::Image(im) => Some(&mut im.placement),
NodeKind::PlacedDocument(p) => Some(&mut p.placement),
_ => None,
}
}
/// The Placement Options of image or placed document `id` of `d`.
fn placement_of(d: &Document, id: NodeId) -> Option<PlacementOptions> {
match &d.node(id)?.kind {
NodeKind::Image(im) => Some(im.placement),
NodeKind::PlacedDocument(p) => Some(p.placement),
_ => None,
}
}
/// `id`, else the first selected image or placed document.
fn linked_param(st: &crate::DocState, p: &Value, cmd: &str) -> Result<NodeId> {
let first = || st.selection.objects.iter().copied().find(|id| placement_of(&st.doc, *id).is_some());
let id = id_param(p, "id").or_else(first).ok_or_else(|| bad(cmd, "select an image, or pass id"))?;
match placement_of(&st.doc, id) {
Some(_) => Ok(id),
None if st.doc.node(id).is_none() => Err(crate::EngineError::NoNode(id)),
None => Err(bad(cmd, format!("object {} is not an image or a linked file", id.0))),
}
}
/// Per linked image in the layers of `st`: its file's status, where it was found when away from
/// its path, and whether the image shows its preview (each file probed once).
fn statuses(st: &crate::DocState) -> BTreeMap<NodeId, (Status, Option<String>, bool)> {
@@ -681,7 +858,7 @@ fn statuses(st: &crate::DocState) -> BTreeMap<NodeId, (Status, Option<String>, b
for g in groups(&st.doc, None).iter().filter(|g| !g.ids.is_empty()) {
let (status, found) = probe(g, folder(st.path.as_deref()));
let found = found.map(|f| f.path).filter(|p| *p != g.link.path);
let preview = previewing(&st.doc, &g.key);
let preview = stale(&st.doc, g);
out.extend(g.ids.iter().map(|id| (*id, (status, found.clone(), preview))));
}
out
@@ -696,6 +873,12 @@ fn format_label(d: &Document, im: &ImageObject) -> &'static str {
.map_or("Image", |f| f.label)
}
/// A placed document's `links.list` fields: `format`, `document: true` and its artboard's size
/// (`pageWidth`, `pageHeight`, pt) instead of pixels.
fn document_row(p: &PlacedDocument) -> Value {
json!({ "format": "VectorCraft", "document": true, "pageWidth": p.width, "pageHeight": p.height })
}
/// Sort rank of a `links.list` status: missing, modified, ok, embedded.
fn status_rank(status: &str) -> usize {
["missing", "modified", "ok", "embedded"].iter().position(|s| *s == status).unwrap_or(4)
@@ -709,17 +892,17 @@ fn list(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(C, format!("show `{show}`: all, missing, modified or embedded")));
}
let statuses = statuses(st);
let mut images = vec![];
let mut objects = vec![];
st.doc.walk(|n| {
if let NodeKind::Image(im) = &n.kind {
images.push((n, im));
if matches!(n.kind, NodeKind::Image(_) | NodeKind::PlacedDocument(_)) {
objects.push(n);
}
});
// Top first, as the Layers panel lists them.
images.reverse();
objects.reverse();
let mut counts: BTreeMap<&str, usize> = BTreeMap::new();
let mut rows = vec![];
for (n, im) in images {
for n in objects {
let (status, found, preview) = match statuses.get(&n.id) {
Some((s, f, p)) => (s.as_str(), f.as_deref(), *p),
None => ("embedded", None, false),
@@ -728,17 +911,21 @@ fn list(s: &mut Session, p: &Value) -> Result<Value> {
if show != "all" && show != status {
continue;
}
let name = im.link.as_ref().map_or_else(|| n.display_name(), |l| l.name().to_string());
let mut row = json!({
"id": n.id.0,
"name": name,
"linked": im.link.is_some(),
"status": status,
"format": format_label(&st.doc, im),
"pixelWidth": im.width,
"pixelHeight": im.height,
});
if let Some(l) = &im.link {
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 }))
}
NodeKind::PlacedDocument(p) => (Some(&p.link), document_row(p)),
_ => continue,
};
let name = link.map_or_else(|| n.display_name(), |l| l.name().to_string());
if let Some(o) = row.as_object_mut() {
o.insert("id".into(), json!(n.id.0));
o.insert("name".into(), json!(name));
o.insert("linked".into(), json!(link.is_some()));
o.insert("status".into(), json!(status));
}
if let Some(l) = link {
row["path"] = json!(l.path);
if let Some(page) = l.page {
row["page"] = json!(page);
@@ -766,7 +953,7 @@ fn list(s: &mut Session, p: &Value) -> Result<Value> {
fn go_to(s: &mut Session, p: &Value) -> Result<Value> {
let st = s.doc()?;
let id = image_param(st, p, "links.goTo")?;
let id = linked_param(st, p, "links.goTo")?;
let b = st.doc.node(id).and_then(Node::geometric_bounds).unwrap_or_default();
s.select(|_, sel| sel.set([id]))?;
Ok(json!({ "id": id.0, "bounds": [b.x0, b.y0, b.x1, b.y1] }))
@@ -775,9 +962,29 @@ fn go_to(s: &mut Session, p: &Value) -> Result<Value> {
fn embed(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "links.embed";
let st = s.doc()?;
let ids = images_param(st, p, C, |im| im.link.is_some())?;
let kind = |id: &NodeId| st.doc.node(*id).map(|n| &n.kind);
let linked = |id: &NodeId| match kind(id) {
Some(NodeKind::Image(im)) => im.link.is_some(),
Some(NodeKind::PlacedDocument(_)) => true,
_ => false,
};
let ids = ids_param(p, "ids").unwrap_or_else(|| st.selection.objects.iter().copied().filter(linked).collect());
if let Some(id) = ids.iter().find(|id| !matches!(kind(id), Some(NodeKind::Image(_) | NodeKind::PlacedDocument(_)))) {
return Err(bad(C, format!("object {} is not an image or a placed document", id.0)));
}
if ids.is_empty() {
return Err(bad(C, "select the linked images or placed documents, or pass ids"));
}
// Placed documents become editable copies of their art: those whose file can be read.
let (mut documents, mut missing) = (vec![], vec![]);
for id in ids.iter().copied() {
let Some(NodeKind::PlacedDocument(p)) = kind(&id) else { continue };
let readable = st.doc.images.get(&p.key).is_some_and(|b| vectorcraft_doc::placed_document::full_bytes(p, b).is_some());
if readable { documents.push(id) } else { missing.push(id) }
}
let ids: Vec<NodeId> = ids.into_iter().filter(|id| matches!(kind(id), Some(NodeKind::Image(_)))).collect();
// Images showing their preview take their file's pixels first.
let (mut done, mut missing, mut reads) = (vec![], vec![], vec![]);
let (mut done, mut reads) = (vec![], vec![]);
for g in groups(&st.doc, Some(&ids)) {
if !previewing(&st.doc, &g.key) {
done.extend(g.ids);
@@ -794,21 +1001,20 @@ fn embed(s: &mut Session, p: &Value) -> Result<Value> {
_ => missing.extend(g.ids),
}
}
if !done.is_empty() {
if !done.is_empty() || !documents.is_empty() {
s.edit("Embed", |d, _| {
for (ids, read) in reads {
install(d, &ids, read, true)?;
}
for id in &done {
if let Some(n) = d.node_mut(*id)
&& let NodeKind::Image(im) = &mut n.kind
{
if let Some(Node { kind: NodeKind::Image(im), .. }) = d.node_mut(*id) {
im.link = None;
}
}
Ok(())
documents.iter().try_for_each(|id| super::place::document::expand(d, *id, C))
})?;
}
done.extend(documents);
Ok(json!({ "embedded": ids_json(&done), "missing": ids_json(&missing) }))
}
@@ -862,41 +1068,77 @@ fn placement_json(o: PlacementOptions) -> Value {
json!({ "preserve": o.preserve.id(), "align": o.align.id(), "clip": o.clip })
}
/// Link Info's fields of the linked file `l` (of object `id` of `st`) into `out`.
fn file_fields(st: &crate::DocState, id: NodeId, l: &LinkInfo, out: &mut Value) {
let status = groups(&st.doc, Some(&[id])).first().map_or(Status::Missing, |g| probe(g, folder(st.path.as_deref())).0);
let stamp = file_stamp(&l.path);
let folder_len = l.path.len().saturating_sub(l.name().len());
out["status"] = json!(status.as_str());
out["path"] = json!(l.path);
out["fileName"] = json!(l.name());
out["location"] = json!(l.path.get(..folder_len).unwrap_or_default().trim_end_matches(['/', '\\']));
for (k, v) in [
("page", l.page.map(u64::from)),
("fileSize", stamp.map(|s| s.0).or(l.size)),
("modified", stamp.and_then(|s| s.1).or(l.modified)),
("created", file_created(&l.path)),
] {
if let Some(v) = v {
out[k] = json!(v);
}
}
}
/// Scale (% of 100%, given points per unit at 100%) and counter-clockwise rotation of `xf`.
fn scale_rotation(xf: Affine, (px, py): (f64, f64)) -> (Value, Value) {
let [a, b, c, d, ..] = xf.as_coeffs();
// Counter-clockwise on the page (y points down). Adding 0 turns -0 into 0.
(json!([a.hypot(b) / px * 100.0, c.hypot(d) / py * 100.0]), json!((-b).atan2(a).to_degrees() + 0.0))
}
/// Link Info of placed document `id`.
fn placed_info(st: &crate::DocState, id: NodeId) -> Result<Value> {
let n = st.doc.node(id).ok_or(crate::EngineError::NoNode(id))?;
let NodeKind::PlacedDocument(pl) = &n.kind else { return Err(bad("links.info", format!("object {} is not a placed document", id.0))) };
let size = n.geometric_bounds().unwrap_or_default();
let (scale, rotation) = scale_rotation(pl.xf, (1.0, 1.0));
let mut out = document_row(pl);
let fields = [
("id", json!(id.0)),
("name", json!(n.display_name())),
("linked", json!(true)),
("link", json!(pl.link.path)),
("width", json!(size.width())),
("height", json!(size.height())),
("scale", scale),
("rotation", rotation),
("placement", placement_json(pl.placement)),
];
if let Some(o) = out.as_object_mut() {
o.extend(fields.into_iter().map(|(k, v)| (k.to_string(), v)));
}
file_fields(st, id, &pl.link, &mut out);
Ok(out)
}
fn info(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "links.info";
let id = image_param(s.doc()?, p, C)?;
let id = linked_param(s.doc()?, p, C)?;
if image_of(&s.doc()?.doc, id).is_none() {
return placed_info(s.doc()?, id);
}
let mut out = super::place::image_info(s, &json!({ "id": id.0 }))?;
let st = s.doc()?;
let im = image_of(&st.doc, id).ok_or_else(|| bad(C, format!("object {} is not an image", id.0)))?;
let (px, py) = file_pt(&st.doc, &im.key);
let [a, b, c, d, ..] = im.xf.as_coeffs();
out["effectivePpi"] = out["ppi"].take();
out["ppi"] = json!([72.0 / px, 72.0 / py]);
out["scale"] = json!([a.hypot(b) / px * 100.0, c.hypot(d) / py * 100.0]);
// Counter-clockwise on the page (y points down).
// Adding 0 turns -0 into 0.
out["rotation"] = json!((-b).atan2(a).to_degrees() + 0.0);
(out["scale"], out["rotation"]) = scale_rotation(im.xf, (px, py));
out["format"] = json!(format_label(&st.doc, im));
out["placement"] = placement_json(im.placement);
out["status"] = json!("embedded");
if let Some(l) = &im.link {
let status = groups(&st.doc, Some(&[id])).first().map_or(Status::Missing, |g| probe(g, folder(st.path.as_deref())).0);
let stamp = file_stamp(&l.path);
let folder_len = l.path.len().saturating_sub(l.name().len());
out["status"] = json!(status.as_str());
out["path"] = json!(l.path);
out["fileName"] = json!(l.name());
out["location"] = json!(l.path.get(..folder_len).unwrap_or_default().trim_end_matches(['/', '\\']));
for (k, v) in [
("page", l.page.map(u64::from)),
("fileSize", stamp.map(|s| s.0).or(l.size)),
("modified", stamp.and_then(|s| s.1).or(l.modified)),
("created", file_created(&l.path)),
] {
if let Some(v) = v {
out[k] = json!(v);
}
}
file_fields(st, id, l, &mut out);
}
Ok(out)
}
@@ -904,7 +1146,13 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
fn placement_options(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "links.placementOptions";
let st = s.doc()?;
let ids = images_param(st, p, C, |_| true)?;
let ids = ids_param(p, "ids").unwrap_or_else(|| st.selection.objects.iter().copied().filter(|id| placement_of(&st.doc, *id).is_some()).collect());
if let Some(id) = ids.iter().find(|id| placement_of(&st.doc, **id).is_none()) {
return Err(bad(C, format!("object {} is not an image or a linked file", id.0)));
}
if ids.is_empty() {
return Err(bad(C, "select the images, or pass ids"));
}
let choice = |k: &str| -> Result<Option<&str>> {
match p.get(k) {
None | Some(Value::Null) => Ok(None),
@@ -918,7 +1166,7 @@ fn placement_options(s: &mut Session, p: &Value) -> Result<Value> {
None | Some(Value::Null) => None,
Some(v) => Some(v.as_bool().ok_or_else(|| bad(C, "clip must be true or false"))?),
};
let first = ids.first().and_then(|id| image_of(&st.doc, *id)).map(|im| im.placement).unwrap_or_default();
let first = ids.first().and_then(|id| placement_of(&st.doc, *id)).unwrap_or_default();
if preserve.is_none() && align.is_none() && clip.is_none() {
return Ok(json!({ "placement": placement_json(first) }));
}
@@ -929,10 +1177,8 @@ fn placement_options(s: &mut Session, p: &Value) -> Result<Value> {
};
s.edit("Placement Options", |d, _| {
for id in &ids {
if let Some(n) = d.node_mut(*id)
&& let NodeKind::Image(im) = &mut n.kind
{
set(&mut im.placement);
if let Some(o) = d.node_mut(*id).and_then(placement_mut) {
set(o);
}
}
Ok(())
+1 -1
View File
@@ -48,7 +48,7 @@ mod pathops;
mod patterncmds;
pub mod pdfcmds;
pub mod perspgrid;
mod place;
pub(crate) mod place;
pub mod plugin;
pub mod prefscmds;
pub mod print;
+59 -53
View File
@@ -1,11 +1,13 @@
//! Object menu: transforms, arrange, group, lock/hide, compound paths, clipping masks, isolation,
//! align & distribute, object properties.
use std::collections::BTreeSet;
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_color::{BlendMode, Paint};
use vectorcraft_doc::{Appearance, Document, Knockout, Node, NodeId, NodeKind, OrientedBox, Scaling};
use vectorcraft_doc::corners::set_corners;
use vectorcraft_doc::{Appearance, Document, Knockout, LiveCorners, LiveShape, Node, NodeId, NodeKind, OrientedBox, Scaling};
use vectorcraft_geom::shapes::CornerKind;
use vectorcraft_geom::{Affine, FillRule, Point, Rect, Vec2};
@@ -157,7 +159,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Align",
["Window", "Align"],
None,
"{horizontal?: \"left\"|\"center\"|\"right\", vertical?: \"top\"|\"center\"|\"bottom\", to?: \"selection\"|\"artboard\"|\"key\", bounds?: \"preview\"|\"geometric\" (default: the Use Preview Bounds preference; preview bounds take in strokes)}",
"{horizontal?: \"left\"|\"center\"|\"right\", vertical?: \"top\"|\"center\"|\"bottom\", to?: \"selection\"|\"artboard\"|\"key\" (default: the key object when the selection has one, select.key, else the selection), bounds?: \"preview\"|\"geometric\" (default: the Use Preview Bounds preference; preview bounds take in strokes)}",
has_selection,
align
),
@@ -175,7 +177,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Distribute Spacing",
["Window", "Align"],
None,
"{axis: \"horizontal\"|\"vertical\", spacing?: pt, bounds?: \"preview\"|\"geometric\" (default: the Use Preview Bounds preference; preview bounds take in strokes)}",
"{axis: \"horizontal\"|\"vertical\", spacing?: pt (the key object, select.key, stays put and the others are spaced from it), bounds?: \"preview\"|\"geometric\" (default: the Use Preview Bounds preference; preview bounds take in strokes)}",
has_multi,
distribute_spacing
),
@@ -194,7 +196,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Live Shape Properties",
[],
None,
"{id?, ids?, radius?: pt, kind?: \"round\"|\"invertedRound\"|\"chamfer\", corners?: [0..3…], sides?: n} (Live Corners: radius and kind set a rectangle's corners: `corners` (0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left), else the corners with a Direct-Selected anchor, else all four; sides: a polygon's)",
"{id?, ids?, radius?: pt, kind?: \"round\"|\"invertedRound\"|\"chamfer\", corners?: [i…], sides?: n} (Live Corners on any path: radius and kind set its corners (anchors without handles between two straight sides): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared)",
has_selection,
set_live_shape
),
@@ -811,9 +813,15 @@ fn items_bounds(d: &Document, ids: &[NodeId], preview: bool) -> Vec<(NodeId, Rec
ids.iter().filter_map(|id| Some((*id, d.bounds_of(&[*id], preview)?))).collect()
}
/// What `object.align` aligns to: `to`, else the key object when there is one, else the
/// selection.
fn align_to<'a>(s: &Session, p: &'a Value) -> Option<&'a str> {
str_param(p, "to").or_else(|| s.doc().ok()?.selection.key.map(|_| "key"))
}
fn reference_rect(s: &Session, p: &Value, ids: &[NodeId], preview: bool) -> Result<Rect> {
let st = s.doc()?;
match str_param(p, "to") {
match align_to(s, p) {
Some("artboard") => {
let b = st.doc.bounds_of(ids, preview).unwrap_or_default();
let i = st.doc.artboard_at(b.center()).unwrap_or(0);
@@ -838,7 +846,7 @@ fn align(s: &mut Session, p: &Value) -> Result<Value> {
let d = &s.doc()?.doc;
items_bounds(d, &ids, preview)
.into_iter()
.filter(|(id, _)| Some(*id) != key || str_param(p, "to") != Some("key"))
.filter(|(id, _)| Some(*id) != key || align_to(s, p) != Some("key"))
.map(|(id, b)| {
let dx = match h {
Some("left") => r.x0 - b.x0,
@@ -924,22 +932,31 @@ fn distribute_spacing(s: &mut Session, p: &Value) -> Result<Value> {
let mut items = items_bounds(&s.doc()?.doc, &ids, preview);
items.sort_by(|a, b| if horiz { a.1.x0.total_cmp(&b.1.x0) } else { a.1.y0.total_cmp(&b.1.y0) });
let n = items.len();
let &[(_, first), .., (_, last)] = items.as_slice() else {
return Err(EngineError::Other("select two or more objects to distribute".into()));
};
let size = |r: &Rect| if horiz { r.width() } else { r.height() };
let start = |r: &Rect| if horiz { r.x0 } else { r.y0 };
let gap = match p.get("spacing").and_then(Value::as_f64) {
let spacing = p.get("spacing").and_then(Value::as_f64).filter(|g| g.is_finite());
let gap = match spacing {
Some(g) => g,
None => {
let span = if horiz { items[n - 1].1.x1 - items[0].1.x0 } else { items[n - 1].1.y1 - items[0].1.y0 };
let span = if horiz { last.x1 - first.x0 } else { last.y1 - first.y0 };
(span - items.iter().map(|i| size(&i.1)).sum::<f64>()) / (n - 1) as f64
}
};
let mut pos = start(&items[0].1);
let mut moves = vec![];
let mut pos = start(&first);
let mut deltas = vec![];
for (id, r) in &items {
let delta = pos - start(r);
moves.push((*id, if horiz { Vec2::new(delta, 0.0) } else { Vec2::new(0.0, delta) }));
deltas.push((*id, pos - start(r)));
pos += size(r) + gap;
}
// With a spacing (aligning to a key object) the key object stays where it is: the others
// are spaced from it.
let key = s.doc()?.selection.key;
let fixed = spacing.and_then(|_| deltas.iter().find(|(id, _)| Some(*id) == key)).map_or(0.0, |k| k.1);
let moves: Vec<(NodeId, Vec2)> =
deltas.into_iter().map(|(id, d)| (id, if horiz { Vec2::new(d - fixed, 0.0) } else { Vec2::new(0.0, d - fixed) })).collect();
s.edit("Distribute Spacing", |d, _| {
for (id, dv) in &moves {
if let Some(n) = d.node_mut(*id) {
@@ -1006,21 +1023,12 @@ fn expand_shape(s: &mut Session, _: &Value) -> Result<Value> {
ok()
}
/// The `corners` of `object.setLiveShape`: a mask of corner indices 0–3.
fn corners_param(p: &Value) -> Result<Option<[bool; 4]>> {
/// The `corners` of `object.setLiveShape`: anchor indices of a path's uncut outline.
fn corners_param(p: &Value) -> Result<Option<BTreeSet<usize>>> {
let Some(v) = p.get("corners").filter(|v| !v.is_null()) else { return Ok(None) };
let err = || {
bad(
"object.setLiveShape",
format!("`corners` must list corner indices 0–3 (0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left), not {v}"),
)
};
let mut mask = [false; 4];
for k in v.as_array().ok_or_else(err)? {
let slot = k.as_u64().and_then(|k| mask.get_mut(usize::try_from(k).ok()?)).ok_or_else(err)?;
*slot = true;
}
Ok(Some(mask))
let err = || bad("object.setLiveShape", format!("`corners` must list anchor indices (0, 1, 2…), not {v}"));
let list = v.as_array().ok_or_else(err)?;
list.iter().map(|k| k.as_u64().and_then(|k| usize::try_from(k).ok()).ok_or_else(err)).collect::<Result<_>>().map(Some)
}
fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
@@ -1035,39 +1043,37 @@ fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
})
.transpose()?;
let radius = p.get("radius").and_then(Value::as_f64);
let sides = p.get("sides").and_then(Value::as_u64);
s.edit("Live Shape", |d, sel| {
for id in &ids {
let Some(NodeKind::Path { path, live: Some(live), .. }) = d.node_mut(*id).map(|n| &mut n.kind) else { continue };
// Radii are document lengths and corners circular, also on a rectangle from a file
// that kept an uneven scale in its transform (#442).
live.fold_scale();
let partial = sel.anchors.get_mut(id);
let picked = corners.unwrap_or_else(|| live.picked_corners(partial.as_deref()));
let (layout, selected) = (live.anchor_corners(), partial.as_deref().map(|a| live.corners_of(a)));
match live {
vectorcraft_doc::LiveShape::Rectangle { radii, kinds, .. } => {
for ((_, r), k) in picked.iter().zip(radii.iter_mut()).zip(kinds.iter_mut()).filter(|((on, _), _)| **on) {
if let Some(radius) = radius {
*r = radius.max(0.0);
}
if let Some(kind) = kind {
*k = kind;
}
}
}
vectorcraft_doc::LiveShape::Polygon { sides, .. } => {
if let Some(n) = p.get("sides").and_then(Value::as_u64) {
*sides = n.clamp(3, 1000) as u32;
}
}
_ => {}
let Some(NodeKind::Path { path, live, .. }) = d.node_mut(*id).map(|n| &mut n.kind) else { continue };
if let (Some(l @ LiveShape::Polygon { .. }), Some(n)) = (live.as_mut(), sides) {
l.set_sides(n);
*path = l.to_path();
}
*path = live.to_path();
if radius.is_none() && kind.is_none() {
continue;
}
let partial = sel.anchors.get_mut(id);
// The corners to edit, the Direct-Selected ones and the anchor layout before the edit.
let Some(c) = LiveCorners::new(path, live.as_ref()) else { continue };
let picked = match &corners {
Some(k) if k.last().is_some_and(|k| *k >= c.base.anchor_count()) => {
let n = c.base.anchor_count();
let past: Vec<_> = k.range(n..).collect();
return Err(bad("object.setLiveShape", format!("object {id} has anchors 0–{} for `corners`, not {past:?}", n.saturating_sub(1))));
}
Some(k) => k.clone(),
None => c.picked(partial.as_deref()),
};
let (selected, layout) = (partial.as_deref().map(|a| c.corners_of(a)), c.sources().to_vec());
set_corners(path, live, &picked, radius, kind);
// Direct-Selected corners stay selected as they gain or lose anchors.
if let (Some(anchors), Some(selected)) = (partial, selected)
&& live.anchor_corners() != layout
&& let Some(c) = LiveCorners::new(path, live.as_ref())
&& c.sources() != layout
{
*anchors = live.corner_anchors(selected);
*anchors = c.anchors_of(&selected);
}
}
Ok(())
+2 -1
View File
@@ -67,6 +67,7 @@ fn refs(n: &mut Node, f: &mut impl FnMut(Ref)) {
}
}
NodeKind::Image(im) => f(Ref::Image(&mut im.key)),
NodeKind::PlacedDocument(pl) => f(Ref::Image(&mut pl.key)),
NodeKind::SymbolInstance { symbol, .. } => f(Ref::Symbol(symbol)),
_ => {}
}
@@ -129,7 +130,7 @@ fn copies(m: &Renames) -> Vec<(&str, &str)> {
/// Bring the resources `nodes` (art from `src`) use into `dst`, renaming on conflict, and point
/// `nodes` at the names they got.
pub(super) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) {
pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) {
let mut used = Used::default();
for n in nodes.iter_mut() {
refs(n, &mut |r| used.note(r));
+273
View File
@@ -0,0 +1,273 @@
//! Placed documents (`file.place` of a VectorCraft document from a file, with `link`): one
//! locked object showing an artboard of the document, a [`PlacedDocument`].
//!
//! The object keeps the file's bytes (in the document's images, like image data) and the link; the
//! art it shows is read from them the way placing the file without Link reads it
//! ([`document_art`]: the artboard's art, with the file's own linked images found), so Break Link
//! and Object › Expand ([`expand`]) give exactly that editable copy. The Links commands
//! ([`super::super::links`]) tell when the file changed and read it again.
//!
//! Each placed file also gets a preview ([`PREVIEW_PX_PER_PT`]; JPEG when opaque, else PNG), kept
//! as the blob's [`ImageBlob::proxy`]: a save writes only the preview (unless Include Linked
//! Files), as for linked images. The file is read again when it is needed ([`read_file_again`]:
//! output, or the screen zoomed past the preview), while it is unchanged, and output falls back to
//! the preview with a warning when it can't be ([`full_documents`]).
use std::borrow::Cow;
use std::collections::BTreeSet;
use std::sync::Arc;
use vectorcraft_doc::links::hash_bytes;
use vectorcraft_doc::placed_document::{PREVIEW_MAX, PREVIEW_PX_PER_PT, key_for};
use vectorcraft_doc::{Document, ImageBlob, LinkInfo, Node, NodeKind, PlacedDocument, PlacementOptions};
use vectorcraft_geom::{Affine, Rect};
use super::super::fileio;
use super::super::*;
/// The largest file placed (bytes).
pub(crate) const MAX_FILE: usize = 256 << 20;
/// The format ids of VectorCraft documents.
const NATIVE: [&str; 2] = ["vectorcraft", "template"];
/// The type a placed file's bytes are stored with.
const MIME: &str = "application/json";
/// Is `name` with `bytes` a VectorCraft document?
pub(crate) fn is_native(name: &str, bytes: &[u8]) -> bool {
fileio::detect(name, bytes).is_some_and(|f| NATIVE.contains(&f.id))
}
/// An artboard of a VectorCraft document, read as art to place.
pub(crate) struct DocumentArt {
/// The document, its layers taken: the art's resources.
pub doc: Document,
/// The art on the artboard (guides, hidden and template layers left out).
pub nodes: Vec<Node>,
/// The artboard the art is clipped to (`None`: the art's bounds are shown).
pub clip: Option<Rect>,
/// What is shown: the artboard, or the art's bounds.
pub frame: Rect,
pub warnings: Vec<String>,
}
/// Artboard `page` (1-based) of the VectorCraft document `name` (`bytes`, read from `path` when
/// there is one, so its linked images are found), clipped to the artboard unless `bounding`.
pub(crate) fn document_art(name: &str, bytes: &[u8], path: Option<&str>, page: u32, bounding: bool, cmd: &str) -> Result<DocumentArt> {
let file = fileio::file_name(name);
if !is_native(name, bytes) {
return Err(bad(cmd, format!("`{file}` isn't a VectorCraft document")));
}
if bytes.len() > MAX_FILE {
return Err(bad(cmd, format!("`{file}` is over {} MB", MAX_FILE >> 20)));
}
let mut l = fileio::load(name, bytes)?;
// Its linked images show their files; its placed documents stay as they are.
super::super::links::resolve(&mut l.doc, path, false);
l.doc.drop_edit_modes();
let n = l.doc.artboards.len();
let board = (page as usize).checked_sub(1).and_then(|i| l.doc.artboards.get(i)).map(|a| a.rect);
let board = board.ok_or_else(|| bad(cmd, format!("page {page}: `{file}` has {n} artboard(s)")))?;
let layers = std::mem::take(&mut l.doc.layers);
let nodes = super::on_artboard(&layers, board);
let frame = if bounding { nodes.iter().fold(None, |acc, n| vectorcraft_geom::union_opt(acc, n.visual_bounds())) } else { Some(board) };
let frame = frame.filter(|r| r.width() > 0.0 || r.height() > 0.0).ok_or_else(|| bad(cmd, format!("`{file}` has no art to place")))?;
Ok(DocumentArt { doc: l.doc, nodes, clip: (!bounding).then_some(board), frame, warnings: l.warnings })
}
/// `nodes` as one group, clipped to `clip` (its own ids: what drawing reads).
fn group(nodes: Vec<Node>, clip: Option<Rect>) -> Node {
let mut children: Vec<Arc<Node>> = nodes.into_iter().map(Arc::new).collect();
if let Some(r) = clip {
children.insert(0, Arc::new(super::clip_path(NodeId(0), r)));
}
Node::new(NodeId(0), NodeKind::Group { children, clip: clip.is_some() })
}
/// `p`'s file (`bytes`) read as the art it shows: how the document model reads placed documents
/// ([`vectorcraft_doc::placed_document::set_loader`]).
pub(crate) fn read_document(p: &PlacedDocument, bytes: &[u8]) -> Option<(Document, Node, Rect)> {
let a = document_art(p.link.name(), bytes, Some(&p.link.path), p.page(), p.bounding, "draw").ok()?;
Some((a.doc, group(a.nodes, a.clip), a.frame))
}
/// `p`'s file read again, while it is the file it was read from (how the document model gets it
/// when only the preview is stored, [`vectorcraft_doc::placed_document::set_file_reader`]).
pub(crate) fn read_file_again(p: &PlacedDocument) -> Option<Vec<u8>> {
let bytes = fileio::read_file(&p.link.path).ok()?;
if p.link.hash.as_ref().is_some_and(|h| *h != hash_bytes(&bytes)) {
return None;
}
Some(bytes)
}
/// A VectorCraft document read for placing linked.
#[derive(Clone)]
pub(crate) struct Source {
/// The file's bytes, with their preview.
pub blob: ImageBlob,
/// The blob's key ([`key_for`]).
pub key: String,
/// What is shown, in the file's coordinates: the artboard or the art's bounds.
pub frame: Rect,
pub warnings: Vec<String>,
}
/// The VectorCraft document `name` (`bytes`, from `path` when there is one) read for showing
/// artboard `page` (its art's bounds when `bounding`).
pub(crate) fn source(name: &str, bytes: &[u8], path: Option<&str>, page: u32, bounding: bool, cmd: &str) -> Result<Source> {
// The same document placed the same way is read once (placing it again is free).
let key = key_for(&hash_bytes(bytes), page, bounding);
if let Some(s) = lock_memo().iter().find(|s| s.key == key).cloned() {
return Ok(s);
}
let a = document_art(name, bytes, path, page, bounding, cmd)?;
let mut blob = ImageBlob::new(MIME, bytes.to_vec());
let shown = PlacedDocument {
link: LinkInfo { page: Some(page), ..LinkInfo::new(path.unwrap_or(name)) },
key: key.clone(),
bounding,
width: a.frame.width(),
height: a.frame.height(),
xf: Affine::IDENTITY,
placement: PlacementOptions::default(),
};
let art = group(a.nodes, a.clip);
blob.proxy = preview(&a.doc, &art, a.frame).map(Arc::new);
// Drawing it needn't read it again.
vectorcraft_doc::placed_document::prime(&shown, blob.bytes.clone(), (a.doc, art, a.frame));
let s = Source { blob, key, frame: a.frame, warnings: a.warnings };
let mut m = lock_memo();
if m.len() >= MEMO_SIZE {
m.remove(0);
}
m.push(s.clone());
Ok(s)
}
/// The most files remembered.
const MEMO_SIZE: usize = 32;
/// Files read lately for placing, by key.
static MEMO: std::sync::Mutex<Vec<Source>> = std::sync::Mutex::new(Vec::new());
fn lock_memo() -> std::sync::MutexGuard<'static, Vec<Source>> {
// Entries are only pushed and removed: a panic while held leaves it whole.
MEMO.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}
/// The preview of `art` (of document `doc`, showing `frame`): [`PREVIEW_PX_PER_PT`], at most
/// [`PREVIEW_MAX`] pixels a side; JPEG when opaque (inside its outer pixels), else PNG.
fn preview(doc: &Document, art: &Node, frame: Rect) -> Option<Vec<u8>> {
let k = PREVIEW_PX_PER_PT.min(PREVIEW_MAX as f64 / frame.width().max(frame.height()).max(1e-9));
let side = |v: f64| (v * k).round().clamp(1.0, PREVIEW_MAX as f64) as u32;
let (w, h) = (side(frame.width()), side(frame.height()));
let view = Affine::scale_non_uniform(w as f64 / frame.width().max(1e-9), h as f64 / frame.height().max(1e-9))
* Affine::translate((-frame.x0, -frame.y0));
let mut r = vectorcraft_render::Renderer::new();
let img = vectorcraft_render::placed_document::render_inside(&mut r, doc, &Arc::new(art.clone()), w as u16, h as u16, view)?;
// Premultiplied → straight.
let px = img
.pixels
.as_chunks::<4>()
.0
.iter()
.flat_map(|&[r, g, b, a]| {
let un = |c: u8| if a == 0 { 0 } else { ((c as u32 * 255 + a as u32 / 2) / a as u32).min(255) as u8 };
[un(r), un(g), un(b), a]
})
.collect();
let rgba = image::RgbaImage::from_raw(w, h, px)?;
let mut out = vec![];
// Opaque but for the edge's anti-aliasing (an artboard drawn to whole pixels) and compositing's
// rounding: JPEG.
let inner = |x: u32, y: u32| x > 0 && y > 0 && x + 1 < w && y + 1 < h;
if rgba.enumerate_pixels().all(|(x, y, p)| p[3] >= 250 || !inner(x, y)) {
let rgb = image::DynamicImage::ImageRgba8(rgba).to_rgb8();
image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, 80).encode_image(&rgb).ok()?;
} else {
rgba.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).ok()?;
}
Some(out)
}
/// `s` stored in `d` (objects showing the same thing share one blob).
pub(crate) fn store(d: &mut Document, s: &Source) {
d.images.entry(s.key.clone()).or_insert_with(|| s.blob.clone());
}
/// A new placed document of `d` showing `s` at 100%, where its art lies in the file.
pub(crate) fn node(d: &mut Document, s: &Source, link: LinkInfo, bounding: bool) -> Node {
store(d, s);
let placed = PlacedDocument {
link,
key: s.key.clone(),
bounding,
width: s.frame.width(),
height: s.frame.height(),
xf: Affine::translate((s.frame.x0, s.frame.y0)),
placement: PlacementOptions::default(),
};
Node::new(d.alloc_id(), NodeKind::PlacedDocument(Box::new(placed)))
}
/// `d` for output: the placed documents that keep only their previews get their files back,
/// else (their files gone or changed) output as their previews, with a warning.
pub(crate) fn full_documents(d: &Document) -> (Cow<'_, Document>, Vec<String>) {
let mut need: Vec<PlacedDocument> = vec![];
d.visit_placed(|_, p| {
if d.images.get(&p.key).is_some_and(ImageBlob::is_proxy) && !need.iter().any(|n| n.key == p.key) {
need.push(p.clone());
}
});
if need.is_empty() {
return (Cow::Borrowed(d), vec![]);
}
let mut out = d.clone();
let mut previews = BTreeSet::new();
for p in need {
let Some(blob) = d.images.get(&p.key) else { continue };
match vectorcraft_doc::placed_document::full_bytes(&p, blob) {
Some(bytes) => {
out.images.insert(p.key.clone(), ImageBlob { mime: MIME.into(), bytes, proxy: blob.proxy.clone() });
}
None => {
previews.insert(p.key);
}
}
}
let mut warnings = vec![];
if !previews.is_empty() {
warnings.push(format!(
"{} placed document(s) output as their previews: their files can't be found, or changed since they were read (relink or update them)",
previews.len()
));
out.placed_as_previews(&previews);
}
(Cow::Owned(out), warnings)
}
/// Placed document `id` of `d` replaced by an editable copy of its art, as placing its file
/// without Link gives (its resources joining `d`, renamed where `d` uses a name for something
/// else), keeping the object's id, place, name and transparency: Break Link and Object › Expand.
pub(crate) fn expand(d: &mut Document, id: NodeId, cmd: &str) -> Result<()> {
let n = d.node(id).cloned().ok_or(EngineError::NoNode(id))?;
let NodeKind::PlacedDocument(p) = &n.kind else { return Err(bad(cmd, format!("object {} is not a placed document", id.0))) };
let blob = d.images.get(&p.key).ok_or_else(|| bad(cmd, format!("object {} has lost its file's contents: relink it", id.0)))?;
let bytes = vectorcraft_doc::placed_document::full_bytes(p, blob)
.ok_or_else(|| bad(cmd, format!("{} can't be read, or changed since it was read: relink or update it first", p.link.path)))?;
let a = document_art(p.link.name(), &bytes, Some(&p.link.path), p.page(), p.bounding, cmd)?;
let m = p.art_xf(a.frame).ok_or_else(|| bad(cmd, format!("object {} has no size", id.0)))?;
let mut nodes = a.nodes;
super::adopt::adopt(d, &a.doc, &mut nodes);
let mut children: Vec<Arc<Node>> = nodes.iter().map(|n| Arc::new(d.reid(n))).collect();
if let Some(r) = a.clip {
children.insert(0, Arc::new(super::clip_path(d.alloc_id(), r)));
}
let art = super::transformed(Node::new(d.alloc_id(), NodeKind::Group { children, clip: a.clip.is_some() }), m);
let mut out = n.clone();
out.kind = art.kind;
let (par, index, _) = d.position(id).ok_or(EngineError::NoNode(id))?;
d.remove(id)?;
d.insert(par, index, out)?;
Ok(())
}
+44 -18
View File
@@ -16,13 +16,17 @@
//! (`crop: "bounding"`).
//! - A text file becomes area type, decoded and cleaned up with the Text Import Options (`text`,
//! [`text`]).
//! - A VectorCraft document placed from a file with Link (the default) becomes a placed document:
//! one locked object showing the artboard `page`, linked to the file and read again when it
//! changes ([`document`]); without Link, an editable copy of its art.
//!
//! The art lands centred on `at`, fitted into `rect`, or (Replace) where the replaced object was,
//! with its transform; Template puts it on a new template layer. The images, symbols, patterns and
//! swatches it uses join the document ([`adopt`]). `file.place.queue` loads the place cursor (the
//! `place` tool) with several files, which emits one `file.place` per click or drag.
mod adopt;
pub(crate) mod adopt;
pub(crate) mod document;
mod text;
use std::sync::Arc;
@@ -53,7 +57,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Place…",
["File"],
Some("Cmd+Shift+P"),
"{path | name+dataBase64, link?: true (a raster image keeps its file's path; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set), platform?: \"windows\" (Windows-1252) | \"mac\" (Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside, aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default) | \"bounding\" (the art's bounds) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at)} → {ids, name, format, linked, width, height, warnings}. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, PDF/.ai, EMF/WMF (clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it) and native documents as one group, with the images, symbols, patterns and swatches they use. One undo step; selects what it placed (unless on a template layer); never touches the clipboard",
"{path | name+dataBase64, link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set), platform?: \"windows\" (Windows-1252) | \"mac\" (Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside, aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default) | \"bounding\" (the art's bounds) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at)} → {ids, name, format, linked, width, height, warnings}. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, PDF/.ai, EMF/WMF (clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it) and native documents as one group, with the images, symbols, patterns and swatches they use. One undo step; selects what it placed (unless on a template layer); never touches the clipboard",
has_doc,
place
),
@@ -94,6 +98,9 @@ enum Art {
Image(RasterImage),
/// A text file's text, placed as area type filling the natural box.
Text(String),
/// A VectorCraft document placed linked: the file read, the link, and whether the art's
/// bounds (not the artboard) are shown.
Document(document::Source, LinkInfo, bool),
Vector {
/// The loaded document: the source of the art's resources.
src: Box<Document>,
@@ -157,6 +164,19 @@ fn load(p: &Value, cmd: &str, board: Option<Rect>) -> Result<Loaded> {
));
}
let crop = opts.crop != CropTo::Bounding;
// A VectorCraft document: placed linked from its file, else as an editable copy.
if matches!(format.id, "vectorcraft" | "template") {
let page = page as u32;
if let Some(path) = src.path.filter(|_| bool_or(p, "link", true)) {
let s = document::source(src.name, &src.bytes, Some(path), page, !crop, cmd)?;
let link = LinkInfo { page: Some(page), ..super::links::link_info(path, &src.bytes) };
let (natural, warnings) = (s.frame, s.warnings.clone());
return Ok(Loaded { name, format, art: Art::Document(s, link.clone(), !crop), natural, warnings, link: Some(link), board: None });
}
let a = document::document_art(src.name, &src.bytes, src.path, page, !crop, cmd)?;
let art = Art::Vector { src: Box::new(a.doc), nodes: a.nodes, clip: a.clip };
return Ok(Loaded { name, format, art, natural: a.frame, warnings: a.warnings, link: None, board: None });
}
if format.raster {
let img = fileio::raster_image(&src.bytes)?;
let (sx, sy) = pt_per_px(img.ppi);
@@ -176,7 +196,7 @@ fn load(p: &Value, cmd: &str, board: Option<Rect>) -> Result<Loaded> {
// Of the open options, only a DXF drawing's apply (the colour mode stays the file's).
let o = fileio::LoadOptions { dxf: opts.dxf, ..Default::default() };
let mut l = fileio::load_with(src.name, &src.bytes, &o)?;
// Linked images (a native document's) show their files, found from its folder.
// Linked images show their files, found from its folder.
super::links::resolve(&mut l.doc, src.path, false);
(l.doc, l.warnings)
}
@@ -190,22 +210,31 @@ fn load(p: &Value, cmd: &str, board: Option<Rect>) -> Result<Loaded> {
// The page placed is a PDF import's only one.
let index = if pdf { 0 } else { page - 1 };
let n = doc.artboards.len();
let board = doc.artboards.get(index).map(|a| a.rect).ok_or_else(|| {
let what = if matches!(format.id, "vectorcraft" | "template") { "artboard" } else { "page" };
bad(cmd, format!("page {page}: `{name}` has {n} {what}(s)"))
})?;
// A PDF import has one layer per page; a native document's (or an EPS file's) art is
// whatever lies on the artboard.
let pages: Vec<&Arc<Node>> = if pdf { layers.get(index).into_iter().collect() } else { layers.iter().collect() };
let on_board = |c: &&Arc<Node>| c.visual_bounds().is_some_and(|b| b.intersect(board).area() > 0.0 || board.contains(b.origin()));
let nodes = art_of(pages.into_iter().filter(|l| placeable(l)).flat_map(|l| l.children().into_iter().flatten()).filter(on_board));
(nodes, crop.then_some(board))
let board = doc.artboards.get(index).map(|a| a.rect).ok_or_else(|| bad(cmd, format!("page {page}: `{name}` has {n} page(s)")))?;
// A PDF import has one layer per page; an EPS file's art is whatever lies on the artboard.
let pages = if pdf { layers.get(index..=index).unwrap_or_default() } else { &layers[..] };
(on_artboard(pages, board), crop.then_some(board))
};
let natural = clip.or_else(|| nodes.iter().fold(None, |acc, n| vectorcraft_geom::union_opt(acc, n.visual_bounds())));
let natural = natural.filter(|r| r.width() > 0.0 || r.height() > 0.0).ok_or_else(|| bad(cmd, format!("`{name}` has no art to place")))?;
Ok(Loaded { name, format, art: Art::Vector { src: Box::new(doc), nodes, clip }, natural, warnings, link: None, board })
}
/// The placeable art of `layers` that lies on `board`.
fn on_artboard(layers: &[Arc<Node>], board: Rect) -> Vec<Node> {
let on_board = |c: &&Arc<Node>| c.visual_bounds().is_some_and(|b| b.intersect(board).area() > 0.0 || board.contains(b.origin()));
art_of(layers.iter().filter(|l| placeable(l)).flat_map(|l| l.children().into_iter().flatten()).filter(on_board))
}
/// A clipping path of rectangle `r`, with id `id`.
fn clip_path(id: NodeId, r: Rect) -> Node {
let mut c = Node::path(id, shapes::rectangle(r), Appearance::basic(Paint::None, Paint::None, 0.0));
if let NodeKind::Path { clipping, .. } = &mut c.kind {
*clipping = true;
}
c
}
/// A visible, non-template layer.
fn placeable(l: &Node) -> bool {
l.visible && !matches!(l.kind, NodeKind::Layer { template: true, .. })
@@ -243,15 +272,12 @@ fn build(d: &mut Document, l: Loaded, link: Option<LinkInfo>) -> Node {
Node::new(d.alloc_id(), NodeKind::Image(im))
}
Art::Text(t) => Node::new(d.alloc_id(), NodeKind::Text(Box::new(text::area_text(t, l.natural)))),
Art::Document(s, link, bounding) => document::node(d, &s, link, bounding),
Art::Vector { src, mut nodes, clip } => {
adopt::adopt(d, &src, &mut nodes);
let mut children: Vec<Arc<Node>> = nodes.iter().map(|n| Arc::new(d.reid(n))).collect();
if let Some(r) = clip {
let mut c = Node::path(d.alloc_id(), shapes::rectangle(r), Appearance::basic(Paint::None, Paint::None, 0.0));
if let NodeKind::Path { clipping, .. } = &mut c.kind {
*clipping = true;
}
children.insert(0, Arc::new(c));
children.insert(0, Arc::new(clip_path(d.alloc_id(), r)));
}
Node::new(d.alloc_id(), NodeKind::Group { children, clip: clip.is_some() })
}
+5 -2
View File
@@ -82,8 +82,11 @@ pub const UNITS: &[(&str, &str)] = &[
("feet", "Feet"),
];
const LINE_STYLE: &[(&str, &str)] = &[("lines", "Lines"), ("dots", "Dots")];
/// Performance › Graphics Processor (`gpuPreference`), read by the desktop app at startup.
pub const GPU_PREFERENCES: &[(&str, &str)] = &[("powerSaving", "Power Saving (integrated)"), ("highPerformance", "High Performance (discrete)")];
/// Performance › Graphics Processor (`gpuPreference`), read by the desktop app at startup. The
/// values are WebGPU's power preferences plus `automatic`; 0.5.0's default, `powerSaving`, reads as
/// `automatic` (#502).
pub const GPU_PREFERENCES: &[(&str, &str)] =
&[("automatic", "Automatic"), ("lowPower", "Power Saving (integrated)"), ("highPerformance", "High Performance (discrete)")];
const BLACK: &[(&str, &str)] = &[("accurate", "Display All Blacks Accurately"), ("rich", "Display All Blacks as Rich Black")];
const BLACK_OUT: &[(&str, &str)] = &[("accurate", "Output All Blacks Accurately"), ("rich", "Output All Blacks as Rich Black")];
+3
View File
@@ -118,6 +118,9 @@ fn print(s: &mut Session, p: &Value) -> Result<Value> {
let preset = given.or(Some(set.advanced.flattener_preset.as_str()).filter(|n| !n.trim().is_empty())).unwrap_or("medium");
set.advanced.flattener_preset = preset.to_string();
}
// Placed documents print their files' art.
let (full, _) = super::place::document::full_documents(doc);
let doc = &*full;
// Raster effects print as images at the document's raster effects resolution.
let flat = super::rasterfx::flatten_raster_effects(doc);
let doc = flat.as_ref().unwrap_or(doc);
+9 -1
View File
@@ -36,7 +36,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
toggle
),
cmd!("select.key", "Set Key Object", [], None, "{id?} (none clears)", has_doc, key),
cmd!(
"select.key",
"Set Key Object",
[],
None,
"{id?: a selected object (the Selection tool: a click on one object of a selection of several; on the key again: none)} the key object Align aligns to and Distribute Spacing spaces from; none clears it",
has_doc,
key
),
cmd!("select.anchors", "Select Anchors", [], None, "{id, anchors: [[subpath, anchor]…], mode: \"set\"|\"add\"|\"toggle\"}", has_doc, anchors),
cmd!(
"select.anchorsMany",
+2 -1
View File
@@ -45,7 +45,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Area / Path Type",
[],
None,
"{path: id, mode: \"area\"|\"onPath\", text?: \"\", vertical?: bool = false, at?: [x, y] (on-path start: nearest point), size?, font?, placeholder?: bool (placeholder text instead, as text.create)} turn a path into an area-type frame or a type-on-a-path baseline (the path's paint is dropped) → {id}",
"{path: id, mode: \"area\"|\"onPath\", text?: \"\", vertical?: bool = false, at?: [x, y] (on-path start: nearest point), size?, font?, placeholder?: bool (placeholder text instead, as text.create), leadingModel?, charAlign? (as text.create)} turn a path into an area-type frame or a type-on-a-path baseline (the path's paint is dropped) → {id}",
has_doc,
create_in_path
),
@@ -471,6 +471,7 @@ fn create_in_path(s: &mut Session, p: &Value) -> Result<Value> {
cached_bounds: None,
cached_baselines: Vec::new(),
};
super::create::new_type_alignment(s, p, C, &mut t)?;
if bool_or(p, "placeholder", false) {
super::typemenu::fill_with_placeholder(&mut t);
} else {
+28 -1
View File
@@ -261,6 +261,26 @@ fn attrs_param(p: &Value, kind: Kind, verb: &str) -> Result<Option<Map<String, V
}
}
/// The attributes of a new style made from nothing (no `attrs`, no text selected): while the
/// interface is in Japanese, new type's em box top-to-top leading (paragraph styles) and em box
/// centre alignment (character styles); else none (the defaults).
fn new_style_attrs(s: &Session, kind: Kind) -> Map<String, Value> {
if !s.japanese_interface() {
return Map::new();
}
let (set, default) = match kind {
Kind::Char => {
let st = CharStyle { char_align: vectorcraft_doc::CharAlign::EmBoxCenter, ..CharStyle::default() };
(to_attrs(&st), to_attrs(&CharStyle::default()))
}
Kind::Para => {
let st = ParaStyle { leading_model: vectorcraft_doc::LeadingModel::EmBoxTop, ..ParaStyle::default() };
(to_attrs(&st), to_attrs(&ParaStyle::default()))
}
};
set.into_iter().filter(|(k, v)| default.get(k) != Some(v)).collect()
}
// ---------- commands ----------
fn list(s: &mut Session, kind: Kind) -> Result<Value> {
@@ -275,7 +295,14 @@ fn new(s: &mut Session, p: &Value, kind: Kind) -> Result<Value> {
let c = kind.cmd("new");
let attrs = match attrs_param(p, kind, "new")? {
Some(a) => a,
None => selection_attrs(s, p, kind)?.unwrap_or_default(),
None => match selection_attrs(s, p, kind)? {
Some(a) => a,
None => {
let a = new_style_attrs(s, kind);
s.note_journal("attrs", Value::Object(a.clone()));
a
}
},
};
let d = &s.doc()?.doc;
let base = if kind == Kind::Char { "Character Style" } else { "Paragraph Style" };
+71 -1
View File
@@ -444,6 +444,73 @@ mod area_tests {
assert_eq!(old.burasagari, Burasagari::None);
}
/// #432: while the interface is in Japanese, new type (text.create, text.createInPath) starts
/// with em box top-to-top leading and em box centre alignment, and new styles made from nothing
/// carry them; params override; the values are journaled; imported text keeps the Roman
/// baseline.
#[test]
fn new_type_takes_the_japanese_defaults_while_the_interface_is_japanese() {
use vectorcraft_doc::{CharAlign, LeadingModel};
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
let made = |s: &mut Session, cmd: &str, p: Value| -> (LeadingModel, CharAlign) {
let id = s.execute(cmd, &p).unwrap()["id"].as_u64().unwrap();
match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind {
NodeKind::Text(t) => (t.para.leading_model, t.runs[0].style.char_align),
_ => panic!("text"),
}
};
let roman = (LeadingModel::RomanBaseline, CharAlign::RomanBaseline);
let japanese = (LeadingModel::EmBoxTop, CharAlign::EmBoxCenter);
let point = json!({"x": 10, "y": 50, "text": "雅楽"});
assert!(!s.japanese_interface());
assert_eq!(made(&mut s, "text.create", point.clone()), roman, "headless, `auto`: the Roman defaults");
s.ui_language = Some("ja".into());
assert_eq!(made(&mut s, "text.create", point.clone()), japanese);
assert_eq!(made(&mut s, "text.create", json!({"x": 10, "y": 90, "text": "笙", "area": {"width": 100, "height": 50}})), japanese);
// Journaled: a replay in another language does the same.
let (_, logged) = s.journal.last().unwrap().clone();
assert_eq!((logged["leadingModel"].as_str(), logged["charAlign"].as_str()), (Some("emBoxTop"), Some("emBoxCenter")));
// Params override.
assert_eq!(
made(&mut s, "text.create", json!({"x": 10, "y": 120, "text": "a", "leadingModel": "romanBaseline", "charAlign": "romanBaseline"})),
roman
);
assert!(s.execute("text.create", &json!({"x": 0, "y": 0, "text": "a", "leadingModel": "middle"})).is_err());
// Area type in a path.
let path = s.execute("shape.rectangle", &json!({"x": 200, "y": 200, "width": 100, "height": 80})).unwrap()["id"].clone();
assert_eq!(made(&mut s, "text.createInPath", json!({"path": path, "mode": "area", "text": "篳篥"})), japanese);
// A preference set to Japanese counts without a UI; another language doesn't.
s.ui_language = None;
s.prefs.interface_language = "ja".into();
assert_eq!(made(&mut s, "text.create", point.clone()), japanese);
s.ui_language = Some("en".into());
assert_eq!(made(&mut s, "text.create", point.clone()), roman);
// New styles made from nothing.
s.execute("select.set", &json!({"ids": []})).unwrap();
s.ui_language = Some("ja".into());
let style = |s: &mut Session, kind: &str| {
let name = s.execute(&format!("{kind}.new"), &json!({})).unwrap()["name"].as_str().unwrap().to_string();
let list = s.execute(&format!("{kind}.list"), &json!({})).unwrap();
list["styles"].as_array().unwrap().iter().find(|st| st["name"] == name.as_str()).unwrap()["attrs"].clone()
};
assert_eq!(style(&mut s, "paraStyle"), json!({"leading_model": "emBoxTop"}));
assert_eq!(style(&mut s, "charStyle"), json!({"charAlign": "emBoxCenter"}));
s.ui_language = Some("en".into());
assert_eq!(style(&mut s, "paraStyle"), json!({}));
// Imported text keeps the Roman baseline.
s.ui_language = Some("ja".into());
let svg = r#"<svg xmlns="http://www.w3.org/2000/svg" width="200" height="100"><text x="10" y="50">雅楽</text></svg>"#;
s.execute("document.open", &json!({"name": "t.svg", "dataBase64": vectorcraft_format::base64_encode(svg.as_bytes())})).unwrap();
let mut found = vec![];
s.doc().unwrap().doc.walk(|n| {
if let NodeKind::Text(t) = &n.kind {
found.push((t.para.leading_model, t.runs[0].style.char_align));
}
});
assert_eq!(found, [roman]);
}
#[test]
fn leading_model_is_set_per_paragraph_and_saved_only_when_top_to_top() {
use vectorcraft_doc::LeadingModel;
@@ -463,7 +530,10 @@ mod area_tests {
s.execute("text.setFormat", &json!({"leadingModel": "emBoxTop"})).unwrap();
let t = text(&s);
assert_eq!(t.para.leading_model, LeadingModel::EmBoxTop);
assert_ne!(t.cached_bounds, before, "the first line moves up to the frame's top");
// The fallback used without craft-fonts has no glyph metrics to move the first line.
if !vectorcraft_text::CRAFT_FONTS.is_empty() {
assert_ne!(t.cached_bounds, before, "the first line moves up to the frame's top");
}
assert_eq!(serde_json::to_value(&t.para).unwrap()["leading_model"], "emBoxTop");
s.execute("edit.undo", &json!({})).unwrap();
assert!(serde_json::to_value(&text(&s).para).unwrap().get("leading_model").is_none());
+39 -6
View File
@@ -397,6 +397,8 @@ pub struct Prefs {
pub units_stroke: String,
pub units_type: String,
pub units_asian_type: String,
/// Numbers Without Units Are Points: a number typed with no unit into a length field in picas
/// is read in points (on by default; the reference app dims it unless a unit is Picas).
pub numbers_without_units_are_points: bool,
pub identify_objects_by: String,
// Guides & Grid
@@ -444,10 +446,13 @@ pub struct Prefs {
pub gpu_performance: bool,
pub animated_zoom: bool,
/// Which graphics processor the desktop app asks for at startup (it takes effect after a
/// restart): `powerSaving` (the integrated GPU on hybrid-graphics laptops) or `highPerformance`
/// (the discrete one). The canvas is rasterized on the CPU and only composited on the GPU, so
/// the integrated GPU is plenty; presenting from the discrete GPU through the integrated one
/// made some hybrid laptops flicker (#306). Single-GPU machines are unaffected.
/// restart): `automatic`, `lowPower` (the integrated GPU on hybrid-graphics machines) or
/// `highPerformance` (the discrete one). The canvas is rasterized on the CPU and only
/// composited on the GPU, so the integrated GPU is plenty; presenting from the discrete GPU
/// through the integrated one made some hybrid laptops flicker (#306). Automatic is power
/// saving on Windows and macOS and the system's default GPU elsewhere, the one the desktop
/// runs on: a Wayland compositor may not show frames from another GPU (#502). Single-GPU
/// machines are unaffected.
pub gpu_preference: String,
pub history_states: u32,
pub real_time_drawing: bool,
@@ -629,7 +634,7 @@ impl Default for Prefs {
object_highlighting: true,
transform_tools_guides: true,
construction_guides: true,
construction_angles: s("90° & 45° Angles"),
construction_angles: s(vectorcraft_tools::guides::DEFAULT_CONSTRUCTION_ANGLES),
anchor_path_labels: true,
measurement_labels: true,
spacing_guides: true,
@@ -651,7 +656,7 @@ impl Default for Prefs {
interface_language: s("auto"),
gpu_performance: true,
animated_zoom: true,
gpu_preference: s("powerSaving"),
gpu_preference: s("automatic"),
history_states: 500,
real_time_drawing: true,
render_threads: -1,
@@ -716,6 +721,12 @@ pub struct Session {
/// Executed commands (for actions and debugging).
pub journal: Vec<(String, Value)>,
pub(crate) tool: Box<dyn Tool>,
/// While Cmd lends `tool` (a selection tool) for a drag: the tool it was lent to, which comes
/// back as it was at the release ([`Session::pointer`]).
pub(crate) lender: Option<Box<dyn Tool>>,
/// The selection tool chosen last (Selection, Direct Selection or Group Selection): the one Cmd
/// lends the other tools. None until one is chosen.
pub(crate) last_selection_tool: Option<&'static str>,
pub(crate) last_view: ViewInfo,
depth: u32,
/// Set when the active tool panicked (see [`guard`]); reported by the next tool event.
@@ -752,6 +763,10 @@ pub struct Session {
pub style_libraries: cmd::stylelib::Libraries,
/// URLs recently given in the Attributes panel (`attributes.set {url}`), newest first; not saved.
pub recent_urls: Vec<String>,
/// The language the UI is drawn in (a language code, never `auto`), set by the UI each frame;
/// `None` without one (headless), where an explicit `interfaceLanguage` preference counts.
/// Japanese gives new type the Japanese defaults ([`Session::japanese_interface`]).
pub ui_language: Option<String>,
/// Parameters the running top-level command resolved from the preferences or the clock, added
/// to its journal entry so a replay does the same ([`Session::note_journal`]).
journal_note: serde_json::Map<String, Value>,
@@ -786,6 +801,9 @@ impl Default for Session {
impl Session {
pub fn new() -> Self {
// Placed documents are read by the native format's loader.
vectorcraft_doc::placed_document::set_loader(cmd::place::document::read_document);
vectorcraft_doc::placed_document::set_file_reader(cmd::place::document::read_file_again);
Self {
docs: vec![],
active: None,
@@ -795,6 +813,8 @@ impl Session {
clipboard: Clipboard::default(),
journal: vec![],
tool: vectorcraft_tools::create("selection"),
lender: None,
last_selection_tool: None,
last_view: ViewInfo::default(),
depth: 0,
tool_panic: None,
@@ -812,6 +832,7 @@ impl Session {
freeform_point: None,
style_libraries: Default::default(),
recent_urls: vec![],
ui_language: None,
journal_note: Default::default(),
note_depth: 1,
batch_stash: None,
@@ -853,6 +874,8 @@ impl Session {
return;
}
let view = self.last_view;
// The switch goes on whatever the lent tool's last actions did, as for the deactivation.
let _ = self.give_back_tool(view);
let acts = self.with_tool_cx(view, |t, cx| t.deactivate(cx));
let _ = self.apply_actions(acts);
// A batch leaves its interaction open in the document it leaves, to keep or roll back with
@@ -981,6 +1004,12 @@ impl Session {
Ok(r)
}
/// Is the interface in Japanese? Then new type starts with em box top-to-top leading and em
/// box centre character alignment (#432).
pub fn japanese_interface(&self) -> bool {
self.ui_language.as_deref().unwrap_or(&self.prefs.interface_language).eq_ignore_ascii_case("ja")
}
/// Record `key: value` in the running top-level command's journal entry (or its interaction's
/// preview, or its step in a batch) unless its params give `key`: a value it resolved from the
/// preferences or the clock.
@@ -1424,6 +1453,8 @@ mod tests_perspgrid;
#[cfg(test)]
mod tests_place;
#[cfg(test)]
mod tests_placed_document;
#[cfg(test)]
mod tests_plugins;
#[cfg(test)]
mod tests_prefs;
@@ -1462,6 +1493,8 @@ mod tests_scalestrokes;
#[cfg(test)]
mod tests_slices;
#[cfg(test)]
mod tests_smartguides;
#[cfg(test)]
mod tests_strokegeom;
#[cfg(test)]
mod tests_strokegradient;
+31
View File
@@ -198,6 +198,37 @@ fn align_left() {
assert_eq!(s.doc().unwrap().doc.node(b).unwrap().geometric_bounds().unwrap().x0, 0.0);
}
/// #541: with the Selection tool, a click on one object of the selection makes it the key object:
/// aligning to the key moves the others to it, Distribute Spacing spaces them from it, and a click
/// on the key again lets it go.
#[test]
fn a_click_sets_the_key_object_that_align_and_spacing_keep_still() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
let b = rect(&mut s, 100.0, 30.0, 20.0, 20.0);
let c = rect(&mut s, 300.0, 60.0, 10.0, 10.0);
s.execute("select.set", &json!({"ids": [a.0, b.0, c.0]})).unwrap();
let v = ViewInfo::default();
s.select_tool("selection", v).unwrap();
let click = |s: &mut Session| {
for kind in [PointerKind::Down, PointerKind::Up] {
s.pointer(&PointerEvent::new(kind, 110.0, 40.0), v).unwrap();
}
};
click(&mut s);
assert_eq!(s.doc().unwrap().selection.key, Some(b));
assert_eq!(s.doc().unwrap().selection.objects.len(), 3, "the selection stays");
let x0 = |s: &Session, id| s.doc().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap().x0;
// With a key object, aligning aligns to it (the Control bar and Properties name no target).
s.execute("object.align", &json!({"horizontal": "left", "bounds": "geometric"})).unwrap();
assert_eq!((x0(&s, a), x0(&s, b), x0(&s, c)), (100.0, 100.0, 100.0), "the others moved to the key");
s.execute("edit.undo", &json!({})).unwrap();
s.execute("object.distributeSpacing", &json!({"axis": "horizontal", "spacing": 5, "bounds": "geometric"})).unwrap();
assert_eq!((x0(&s, a), x0(&s, b), x0(&s, c)), (85.0, 100.0, 125.0), "5 pt apart, the key still");
click(&mut s);
assert_eq!(s.doc().unwrap().selection.key, None, "a click on the key again lets it go");
}
#[test]
fn selection_tool_drag_is_one_undo_step() {
let mut s = session();
+64
View File
@@ -704,3 +704,67 @@ fn image_trace_object_remembers_its_settings() {
let id = st.selection.in_paint_order(&st.doc)[0];
assert!(st.doc.node(id).unwrap().trace.is_none());
}
/// #569: merging the regions of a rosette of unfilled ellipses (each off the centre, petals
/// overlapping) merges every region the drags touch into one shape whose outline is only the
/// merged area's border: no edge between merged regions stays in, as a stray line or a spur.
#[test]
fn shape_builder_merges_rosette_rings_cleanly() {
let mut s = session();
s.execute("paint.setFill", &json!({"none": true})).unwrap();
let c = [400.0, 320.0];
let mut petals = vec![];
for k in 0..8 {
let id =
s.execute("shape.ellipse", &json!({"x": c[0] - 60.0, "y": c[1] - 172.0, "width": 120, "height": 324})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
s.execute("object.rotate", &json!({"angle": 45.0 * f64::from(k), "origin": c})).unwrap();
petals.push(id);
}
s.execute("select.set", &json!({"ids": petals})).unwrap();
// Drags around the ring of petals, from its inside out; the outer ones miss the petals.
let mut merged = None;
for radius in [110.0, 150.0, 190.0, 230.0] {
let pts: Vec<[f64; 2]> = (0..=120)
.map(|i| {
let a = std::f64::consts::TAU * f64::from(i) / 120.0;
[c[0] + radius * a.cos(), c[1] + radius * a.sin()]
})
.collect();
if let Ok(r) = s.execute("shapeBuilder.merge", &json!({"points": pts})) {
merged = r["merged"].as_u64().map(NodeId);
}
}
let (ring, rule) = outline(&node(&s, merged.expect("the drags merged")));
let inside = |p: kurbo::Point| kurbo::Shape::winding(&ring.to_bezpath(), p) != 0;
for k in 0..8 {
let a = std::f64::consts::FRAC_PI_4 * f64::from(k) - std::f64::consts::FRAC_PI_2;
let tip = kurbo::Point::new(c[0] + 165.0 * a.cos(), c[1] + 165.0 * a.sin());
assert!(inside(tip), "petal {k}'s tip at {tip:?} is in the merged shape");
}
// What is left of the petals stays out of the merged area (a piece left over it is a stray
// outline inside it).
let merged = merged.unwrap();
for id in s.doc().unwrap().selection.objects.clone().into_iter().filter(|id| *id != merged) {
let (p, r) = outline(&node(&s, id));
let over = vectorcraft_pathops::boolean(&p, r, &ring, rule, vectorcraft_pathops::BoolOp::Intersect);
let a = vectorcraft_pathops::area(&over, FillRule::NonZero);
assert!(a < 1.0, "{id:?} overlaps the merged shape by {a} pt²");
}
// No outline is a sliver or carries a spur (2 × area / length: its mean width).
for id in s.doc().unwrap().selection.objects.clone() {
let (p, r) = outline(&node(&s, id));
for sp in &p.subpaths {
let one = PathData::new(vec![sp.clone()]);
let width = 2.0 * vectorcraft_pathops::area(&one, r) / one.length();
assert!(width > 1.0, "{id:?} has an outline {width:.3} pt wide on average, {:.1} pt long", one.length());
}
}
// The ring is one outline around the centre (the regions the drags missed aside): the
// petals' tips are no outlines of their own beside it, apart by a hairline.
let big = ring.subpaths.iter().filter(|sp| vectorcraft_pathops::area(&PathData::new(vec![(*sp).clone()]), rule) > 100.0).count();
assert_eq!(big, 2, "{:?}", ring.subpaths.iter().map(|sp| vectorcraft_pathops::area(&PathData::new(vec![sp.clone()]), rule)).collect::<Vec<_>>());
// An inner edge would be a second outline over the merged area: normalising would drop it.
let clean = vectorcraft_pathops::normalize(&ring, rule);
assert!((ring.length() - clean.length()).abs() < 1.0, "{} pt of outline, {} without inner edges", ring.length(), clean.length());
}
+141 -10
View File
@@ -57,6 +57,20 @@ fn click(s: &mut Session, tool: &str, x: f64, y: f64) -> Vec<UiRequest> {
drag(s, tool, &[(x, y)], Mods::default())
}
/// A gesture of the active tool, `m` held throughout: press at the first point, drag through the
/// others, release at the last. The undo steps it made.
fn gesture(s: &mut Session, pts: &[(f64, f64)], m: Mods) -> usize {
let v = view();
let undo = undo_steps(s);
s.pointer(&PointerEvent::new(PointerKind::Down, pts[0].0, pts[0].1).with_mods(m), v).unwrap();
for &(x, y) in &pts[1..] {
s.pointer(&PointerEvent::new(PointerKind::Drag, x, y).with_mods(m), v).unwrap();
}
let l = pts[pts.len() - 1];
s.pointer(&PointerEvent::new(PointerKind::Up, l.0, l.1).with_mods(m), v).unwrap();
undo_steps(s) - undo
}
/// A wavy stroke sampled every 2 pt.
fn wave(x0: f64, x1: f64, y: f64) -> Vec<(f64, f64)> {
let n = ((x1 - x0) / 2.0) as usize;
@@ -622,16 +636,6 @@ fn pen_with_alt_moves_one_handle_and_converts_anchors() {
let anchors = json!([{"x": 100, "y": 200}, {"x": 200, "y": 100, "in": [150, 100], "out": [250, 100]}, {"x": 300, "y": 200}]);
let id = NodeId(s.execute("path.create", &json!({"anchors": anchors})).unwrap()["id"].as_u64().unwrap());
s.select_tool("pen", v).unwrap();
let gesture = |s: &mut Session, pts: &[(f64, f64)], m: Mods| {
let undo = undo_steps(s);
s.pointer(&PointerEvent::new(PointerKind::Down, pts[0].0, pts[0].1).with_mods(m), v).unwrap();
for &(x, y) in &pts[1..] {
s.pointer(&PointerEvent::new(PointerKind::Drag, x, y).with_mods(m), v).unwrap();
}
let l = pts[pts.len() - 1];
s.pointer(&PointerEvent::new(PointerKind::Up, l.0, l.1).with_mods(m), v).unwrap();
undo_steps(s) - undo
};
// Alt-drag the out handle: it moves alone, the in handle stays.
assert_eq!(gesture(&mut s, &[(250.0, 100.0), (260.0, 130.0), (275.0, 165.0)], alt), 1);
assert!(!s.in_interaction());
@@ -659,3 +663,130 @@ fn pen_with_alt_moves_one_handle_and_converts_anchors() {
assert_eq!(path(&s, new).subpaths[0].anchors.len(), 3);
assert_eq!(paths(&s).len(), 2);
}
/// The anchor's handles point opposite ways.
fn smooth(a: vectorcraft_geom::Anchor) -> bool {
let (i, o) = (a.h_in - a.p, a.h_out - a.p);
(i.x * o.y - i.y * o.x).abs() < 1e-6 && i.x * o.x + i.y * o.y < 0.0
}
#[test]
fn pen_with_cmd_borrows_direct_selection_and_goes_on_drawing() {
// #494: Cmd (Ctrl) held with the Pen drags with the selection tool used last (Direct Selection
// until one is chosen): handles, segments and anchors of the path being drawn; released, the
// Pen goes on drawing that path. Through pointer events, so agents reach it too.
let (none, cmd) = (Mods::default(), Mods { cmd: true, ..Mods::default() });
let v = view();
let mut s = session();
s.select_tool("pen", v).unwrap();
gesture(&mut s, &[(100.0, 300.0)], none);
gesture(&mut s, &[(200.0, 300.0), (250.0, 300.0)], none);
let id = s.doc().unwrap().selection.objects[0];
assert_eq!(s.cursor(Point::new(250.0, 300.0), none, v), vectorcraft_tools::Cursor::Pen);
assert_eq!(s.cursor(Point::new(250.0, 300.0), cmd, v), vectorcraft_tools::Cursor::ArrowHollow, "Direct Selection's");
// The new anchor's outgoing handle: it moves, its incoming one turning with it.
s.pointer(&PointerEvent::new(PointerKind::Down, 250.0, 300.0).with_mods(cmd), v).unwrap();
assert_eq!(s.tool_id(), "directSelection");
s.pointer(&PointerEvent::new(PointerKind::Drag, 250.0, 260.0).with_mods(cmd), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 250.0, 260.0).with_mods(cmd), v).unwrap();
assert_eq!(s.tool_id(), "pen");
let a = path(&s, id).subpaths[0].anchors[1];
assert!(a.h_out == Point::new(250.0, 260.0) && smooth(a), "{a:?}");
// The segment between the two anchors bends, the smooth anchor staying smooth.
let before = path(&s, id).subpaths[0].anchors[1].h_in;
gesture(&mut s, &[(120.0, 300.0), (120.0, 270.0)], cmd);
let a = path(&s, id).subpaths[0].anchors[1];
assert!(a.h_in != before && smooth(a), "{a:?}");
assert_eq!(s.tool_id(), "pen");
// A plain click goes on drawing the same path.
gesture(&mut s, &[(300.0, 350.0)], none);
assert_eq!((paths(&s).len(), path(&s, id).subpaths[0].anchors.len()), (1, 3));
// A Cmd-click away from the art deselects: the path is done, the next click starts another.
gesture(&mut s, &[(600.0, 100.0)], cmd);
gesture(&mut s, &[(400.0, 500.0)], none);
assert_eq!(paths(&s).len(), 2);
assert_eq!(path(&s, id).subpaths[0].anchors.len(), 3);
// With the Selection tool chosen last, Cmd lends it.
s.select_tool("selection", v).unwrap();
s.select_tool("pen", v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Down, 600.0, 100.0).with_mods(cmd), v).unwrap();
assert_eq!(s.tool_id(), "selection");
s.pointer(&PointerEvent::new(PointerKind::Up, 600.0, 100.0).with_mods(cmd), v).unwrap();
assert_eq!(s.tool_id(), "pen");
// Choosing a tool mid-gesture keeps it: the Pen doesn't come back over it.
s.pointer(&PointerEvent::new(PointerKind::Down, 600.0, 100.0).with_mods(cmd), v).unwrap();
s.select_tool("rectangle", v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 600.0, 100.0), v).unwrap();
assert_eq!(s.tool_id(), "rectangle");
}
#[test]
fn reshaping_a_segment_keeps_smooth_anchors_smooth() {
// #494: the anchors at the ends of a dragged segment keep their kind: a smooth one's other
// handle turns with the moved one (at its length), a corner's stays.
let mut s = session();
let anchors = json!([{"x": 100, "y": 300}, {"x": 200, "y": 300, "in": [160, 300], "out": [240, 300]}, {"x": 300, "y": 300}]);
let id = NodeId(s.execute("path.create", &json!({"anchors": anchors})).unwrap()["id"].as_u64().unwrap());
s.execute("path.reshapeSegment", &json!({"id": id.0, "segment": 0, "t": 0.5, "dx": 0, "dy": -30})).unwrap();
let sp = &path(&s, id).subpaths[0];
let a = sp.anchors[1];
assert!(near(a.h_in, Point::new(160.0, 260.0)) && smooth(a), "{a:?}");
assert!((a.h_out.distance(a.p) - 40.0).abs() < 1e-9, "its length kept");
assert!(near(sp.anchors[0].h_out, Point::new(100.0, 260.0)) && !sp.anchors[0].has_in(), "the corner end: {:?}", sp.anchors[0]);
}
#[test]
fn pen_drag_from_the_first_anchor_closes_the_path() {
// #501: closing a path by dragging out of its first anchor flickered between a close and a new
// path, and released at the wrong moment left the shape open. The press decides: the drag
// shapes the closing curve, symmetric, and the release closes the path wherever it ends.
let none = Mods::default();
let v = view();
let mut s = session();
s.select_tool("pen", v).unwrap();
for (x, y) in [(100.0, 300.0), (200.0, 300.0), (200.0, 400.0)] {
gesture(&mut s, &[(x, y)], none);
}
let id = s.doc().unwrap().selection.objects[0];
let pts: Vec<(f64, f64)> = (0..=12).map(|i| (100.0 + 5.0 * f64::from(i), 300.0 - 4.0 * f64::from(i))).collect();
s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 300.0), v).unwrap();
for &(x, y) in &pts[1..] {
s.pointer(&PointerEvent::new(PointerKind::Drag, x, y), v).unwrap();
let p = path(&s, id);
assert!(p.subpaths[0].closed && paths(&s).len() == 1, "closed throughout the drag, at ({x}, {y})");
}
s.pointer(&PointerEvent::new(PointerKind::Up, 160.0, 252.0), v).unwrap();
assert!(!s.in_interaction());
let sp = &path(&s, id).subpaths[0];
assert!(sp.closed && sp.anchors.len() == 3, "{sp:?}");
let a = sp.anchors[0];
assert_eq!((a.h_in, a.h_out), (Point::new(40.0, 348.0), Point::new(160.0, 252.0)), "symmetric");
assert_eq!(paths(&s).len(), 1);
// The next click starts a new path.
gesture(&mut s, &[(500.0, 500.0)], none);
assert_eq!(paths(&s).len(), 2);
}
#[test]
fn pen_with_alt_converts_the_anchors_of_the_path_being_drawn() {
// #504: while drawing, Alt-click on a smooth anchor of the path makes it a corner and Alt-drag
// on a corner one pulls out smooth handles; the next click goes on drawing the path.
let (none, alt) = (Mods::default(), Mods { alt: true, ..Mods::default() });
let v = view();
let mut s = session();
s.select_tool("pen", v).unwrap();
gesture(&mut s, &[(100.0, 300.0)], none);
gesture(&mut s, &[(200.0, 300.0), (240.0, 300.0)], none);
gesture(&mut s, &[(300.0, 400.0)], none);
gesture(&mut s, &[(400.0, 300.0)], none);
let id = s.doc().unwrap().selection.objects[0];
assert!(smooth(path(&s, id).subpaths[0].anchors[1]));
assert_eq!(gesture(&mut s, &[(200.0, 300.0)], alt), 1);
let a = path(&s, id).subpaths[0].anchors[1];
assert!(!a.has_in() && !a.has_out(), "a corner: {a:?}");
assert_eq!(gesture(&mut s, &[(300.0, 400.0), (320.0, 400.0), (340.0, 400.0)], alt), 1);
let a = path(&s, id).subpaths[0].anchors[2];
assert!(smooth(a) && a.h_out == Point::new(340.0, 400.0), "smooth: {a:?}");
gesture(&mut s, &[(500.0, 400.0)], none);
assert_eq!((paths(&s).len(), path(&s, id).subpaths[0].anchors.len()), (1, 5));
}
+2 -1
View File
@@ -320,7 +320,8 @@ fn a_placed_document_brings_its_links_with_the_files_pixels() {
let doc_path = dir.file("part.vectorcraft");
save(&mut s, &doc_path);
let mut s = session();
s.execute("file.place", &json!({"path": doc_path})).unwrap();
// As an editable copy (placed linked, it stays one locked object).
s.execute("file.place", &json!({"path": doc_path, "link": false})).unwrap();
let doc = &s.doc().unwrap().doc;
let mut placed = vec![];
doc.visit_images(|_, im| placed.push(im.clone()));
+132 -3
View File
@@ -1,10 +1,11 @@
//! Live Corners on live rectangles: `object.setLiveShape` rounds the given corners, the
//! Direct-Selected ones or all four, sets corner kinds, and keeps selected corners selected.
//! Live Corners: `object.setLiveShape` rounds the given corners of a live rectangle, the
//! Direct-Selected ones or all four, sets corner kinds, and keeps selected corners selected; and
//! does the same on any path's corners: a star, a live polygon, a pen path (#511).
use std::collections::BTreeSet;
use serde_json::{Value, json};
use vectorcraft_doc::{AnchorRef, LiveShape, NodeKind};
use vectorcraft_doc::{AnchorRef, LiveCorners, LiveShape, NodeKind};
use vectorcraft_geom::Affine;
use vectorcraft_geom::shapes::CornerKind;
@@ -150,3 +151,131 @@ fn corners_of_a_non_square_rectangle_are_alike_circles() {
run(&mut s, json!({"radius": 8}));
assert_spans(&s, id, [8.0; 4]);
}
/// A selected five-pointed star at (200, 200) of radii 60 and 30: a plain path.
fn star(s: &mut Session) -> NodeId {
NodeId(s.execute("shape.star", &json!({"cx": 200, "cy": 200, "radius1": 60, "radius2": 30})).unwrap()["id"].as_u64().unwrap())
}
fn node_path(s: &Session, id: NodeId) -> (vectorcraft_geom::PathData, Option<LiveShape>) {
let NodeKind::Path { path, live, .. } = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("not a path") };
(path.clone(), live.clone())
}
/// The radius and kind every corner of `id` shares, and how many corners it has.
fn style(s: &Session, id: NodeId) -> (Option<f64>, Option<CornerKind>, usize) {
let c = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap();
let (r, k) = c.style(&c.all());
(r, k, c.corners.len())
}
/// The radius set on each of the first `N` corners of `id`.
fn radii<const N: usize>(s: &Session, id: NodeId) -> [f64; N] {
let c = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap();
std::array::from_fn(|k| c.radius(k))
}
/// #511: a star (a plain path) rounds all ten corners as one step, keeps them editable (a new
/// radius cuts the outline again rather than the cut path), and is the plain star again at 0.
#[test]
fn a_star_rounds_its_corners_and_keeps_them_live() {
let (mut s, _) = session();
let id = star(&mut s);
let (sharp, _) = node_path(&s, id);
assert_eq!(style(&s, id), (Some(0.0), Some(CornerKind::Round), 10));
let undo = s.doc().unwrap().history.undo.len();
run(&mut s, json!({"radius": 4}));
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
let (path, live) = node_path(&s, id);
assert_eq!(path.anchor_count(), 20);
assert!(matches!(&live, Some(LiveShape::Path { base, .. }) if *base == sharp), "{live:?}");
assert_eq!(style(&s, id), (Some(4.0), Some(CornerKind::Round), 10));
assert_eq!(s.doc().unwrap().doc.node(id).unwrap().kind_label(), "Path");
run(&mut s, json!({"radius": 6, "kind": "chamfer"}));
assert_eq!((node_path(&s, id).0.anchor_count(), style(&s, id)), (20, (Some(6.0), Some(CornerKind::Chamfer), 10)));
run(&mut s, json!({"radius": 0, "kind": "round"}));
assert_eq!(node_path(&s, id), (sharp, None));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(style(&s, id).0, Some(6.0));
}
/// Each corner stops at its own limit: its cut reaches halfway along its shorter side, so a
/// star's neighbouring corners meet without overlapping.
#[test]
fn star_corners_stop_at_their_own_limit() {
let (mut s, _) = session();
let id = star(&mut s);
run(&mut s, json!({"radius": 1000}));
let (path, live) = node_path(&s, id);
let Some(LiveShape::Path { base, .. }) = live else { panic!("live corners") };
// Every cut ends at the middle of a side: each side's two cuts meet there.
let sp = &base.subpaths[0];
for (i, a) in sp.anchors.iter().enumerate() {
let mid = a.p.midpoint(sp.anchors[(i + 1) % 10].p);
assert!(path.anchors().any(|(_, _, b)| b.p.distance(mid) < 1e-9), "a cut ends at {mid:?}");
}
assert_eq!(style(&s, id).0, Some(1000.0), "the radius set is kept; it draws as large as fits");
}
/// #511: Direct Selection picks one of the star's anchors: that corner alone rounds, and both of
/// its new anchors stay selected.
#[test]
fn a_direct_selected_star_anchor_rounds_its_corner_alone() {
let (mut s, _) = session();
let id = star(&mut s);
s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 0]], "mode": "set"})).unwrap();
run(&mut s, json!({"radius": 5}));
assert_eq!(node_path(&s, id).0.anchor_count(), 11);
// The top tip's cut ends the path and starts it.
assert_eq!(selected_anchors(&s, id), Some(anchors(&[0, 10])));
assert_eq!(radii::<2>(&s, id), [5.0, 0.0]);
// Explicit corners, as MCP and the widgets give them.
run(&mut s, json!({"id": id.0, "corners": [1, 3], "radius": 2}));
assert_eq!(radii::<4>(&s, id), [5.0, 2.0, 0.0, 2.0]);
// Past the outline's last anchor is an error, and nothing changes.
assert!(s.execute("object.setLiveShape", &json!({"id": id.0, "corners": [10], "radius": 1})).is_err());
assert_eq!(node_path(&s, id).0.anchor_count(), 13);
}
/// A live polygon stays live with cut corners, which keep their radius as its sides change and
/// stay circular when it is scaled unevenly (the radius scales by the mean scale).
#[test]
fn a_polygon_keeps_its_corners_through_sides_and_scales() {
let (mut s, _) = session();
let id = NodeId(s.execute("shape.polygon", &json!({"cx": 200, "cy": 200, "radius": 80, "sides": 6})).unwrap()["id"].as_u64().unwrap());
run(&mut s, json!({"radius": 10}));
let (path, live) = node_path(&s, id);
assert_eq!(path.anchor_count(), 12);
assert!(matches!(live, Some(LiveShape::Polygon { sides: 6, .. })));
run(&mut s, json!({"sides": 8}));
assert_eq!((node_path(&s, id).0.anchor_count(), style(&s, id)), (16, (Some(10.0), Some(CornerKind::Round), 8)));
s.execute("object.scale", &json!({"sx": 400, "sy": 100, "corners": true})).unwrap();
assert!(matches!(node_path(&s, id).1, Some(LiveShape::Polygon { .. })));
assert!((style(&s, id).0.unwrap() - 20.0).abs() < 1e-9);
// Every cut is a circle of that radius: its ends are as far from its centre.
let path = node_path(&s, id).0;
let c = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap();
for k in &c.corners {
let centre = k.on_bisector(20.0 / k.sin());
let ends = path.anchors().filter(|(_, _, a)| (a.p.distance(centre) - 20.0).abs() < 1e-6).count();
assert_eq!(ends, 2, "corner {} is circular", k.index);
}
}
/// #511: a pen path's corners round; its ends don't. An ellipse has no corners to round.
#[test]
fn a_pen_path_rounds_its_corners_but_not_its_ends() {
let (mut s, _) = session();
let pen = json!({"anchors": [{"x": 10, "y": 200}, {"x": 110, "y": 100}, {"x": 210, "y": 200}, {"x": 310, "y": 100}]});
let id = NodeId(s.execute("path.create", &pen).unwrap()["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
run(&mut s, json!({"radius": 8}));
let path = node_path(&s, id).0;
assert_eq!(path.anchor_count(), 6);
let sp = &path.subpaths[0];
assert_eq!((sp.anchors[0].p.x, sp.anchors[5].p.x), (10.0, 310.0), "the ends stay");
let e = NodeId(s.execute("shape.ellipse", &json!({"x": 0, "y": 0, "width": 50, "height": 30})).unwrap()["id"].as_u64().unwrap());
let before = node_path(&s, e);
run(&mut s, json!({"id": e.0, "radius": 8}));
assert_eq!(node_path(&s, e), before);
}
+481
View File
@@ -0,0 +1,481 @@
//! Placed documents: a VectorCraft document placed linked (`file.place`'s default for one read
//! from a file), drawn and output as vectors, saved with its preview, checked, updated and
//! relinked when the file changes, and turned into an editable copy (Break Link, Expand).
use serde_json::{Value, json};
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{Appearance, Document, Node, NodeKind, PlacedDocument};
use vectorcraft_geom::{Rect, shapes};
use super::tests_links::{BLUE, Folder, RED, centre_colour, near, open, save, session, write};
use super::*;
/// A VectorCraft document at `path`: one `w`×`h` artboard filled with `rgb` (and `extra` more
/// rectangles, which change the file's size).
fn source(path: &str, w: f64, h: f64, rgb: [u8; 3], extra: usize) {
let mut d = Document::new(w, h);
let layer = d.layers[0].id;
let [r, g, b] = rgb;
for i in 0..=extra {
let id = d.alloc_id();
let look = Appearance::basic(Paint::solid(Color::rgb8(r, g, b)), Paint::None, 0.0);
d.insert(Some(layer), i, Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, w, h)), look)).unwrap();
}
write(path, &vectorcraft_format::save_file(&d));
}
/// A document drawing symbol `Star` (a blue 100×50 rectangle) at `path`, titled `title` (tests
/// that remove the file give it content of its own: files read are cached by content).
fn star_source(path: &str, title: &str) {
let mut d = Document::new(100.0, 50.0);
d.title = title.into();
let layer = d.layers[0].id;
let art = Node::path(vectorcraft_doc::NodeId(900), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 50.0)), look(BLUE));
d.symbols.push(vectorcraft_doc::Symbol { name: "Star".into(), art: std::sync::Arc::new(art) });
let id = d.alloc_id();
d.insert(Some(layer), 0, Node::new(id, NodeKind::SymbolInstance { symbol: "Star".into(), xf: vectorcraft_geom::Affine::IDENTITY })).unwrap();
write(path, &vectorcraft_format::save_file(&d));
}
fn look(c: [u8; 3]) -> Appearance {
Appearance::basic(Paint::solid(Color::rgb8(c[0], c[1], c[2])), Paint::None, 0.0)
}
/// The active document gets a red symbol named `Star` of its own.
fn parent_star(s: &mut Session) {
let star = Node::path(vectorcraft_doc::NodeId(901), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), look(RED));
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc)
.symbols
.push(vectorcraft_doc::Symbol { name: "Star".into(), art: std::sync::Arc::new(star) });
}
/// Place `path` (linked: the default), centred on the artboard → its id.
fn place(s: &mut Session, path: &str) -> NodeId {
let r = s.execute("file.place", &json!({"path": path, "at": [200, 150]})).unwrap();
assert_eq!(r["linked"], true, "{r}");
NodeId(r["ids"][0].as_u64().unwrap())
}
fn placed(s: &Session, id: NodeId) -> PlacedDocument {
match &s.doc().unwrap().doc.node(id).unwrap().kind {
NodeKind::PlacedDocument(p) => (**p).clone(),
k => panic!("not a placed document: {k:?}"),
}
}
fn bounds(s: &Session, id: NodeId) -> Rect {
s.doc().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap()
}
fn decode(v: &Value) -> Vec<u8> {
vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap()
}
/// Images and paths in `bytes`, a PDF, read back.
fn pdf_contents(bytes: &[u8]) -> (usize, usize) {
// The page as drawn (not the VectorCraft document the PDF carries).
let (doc, _) = super::cmd::fileio::page_document(bytes, 0, &Default::default()).unwrap();
let (mut images, mut paths) = (0, 0);
doc.walk(|n| match n.kind {
NodeKind::Image(_) => images += 1,
NodeKind::Path { .. } | NodeKind::Compound { .. } => paths += 1,
_ => {}
});
(images, paths)
}
/// The JSON of a `.vectorcraft` file (the data after it left out).
fn file_json(bytes: &[u8]) -> Value {
let end = bytes.windows(vectorcraft_format::BLOB_MAGIC.len()).position(|w| w == vectorcraft_format::BLOB_MAGIC).unwrap_or(bytes.len());
serde_json::from_slice(&bytes[..end]).unwrap()
}
#[test]
fn a_document_places_linked_by_default_at_its_artboard_size() {
let dir = Folder::new("placed-basic");
let src = dir.file("logo.vectorcraft");
source(&src, 100.0, 50.0, RED, 0);
let mut s = session();
let id = place(&mut s, &src);
let p = placed(&s, id);
assert!((p.width - 100.0).abs() < 1e-6 && (p.height - 50.0).abs() < 1e-6, "{p:?}");
assert_eq!(bounds(&s, id), Rect::new(150.0, 125.0, 250.0, 175.0));
assert_eq!((p.link.path.as_str(), p.link.page), (src.as_str(), Some(1)));
let n = s.doc().unwrap().doc.node(id).unwrap();
assert_eq!((n.name.as_deref(), n.kind_label()), (Some("logo.vectorcraft"), "Placed Document"));
assert!(near(centre_colour(&s.doc().unwrap().doc), RED));
// It moves and scales like any object.
s.execute("object.move", &json!({"dx": 10, "dy": 0})).unwrap();
assert_eq!(bounds(&s, id), Rect::new(160.0, 125.0, 260.0, 175.0));
// Its art's bounds instead of the artboard.
let mut d = Document::new(100.0, 50.0);
let layer = d.layers[0].id;
let id2 = d.alloc_id();
d.insert(Some(layer), 0, Node::path(id2, shapes::rectangle(Rect::new(10.0, 10.0, 40.0, 30.0)), look(RED))).unwrap();
let small = dir.file("small.vectorcraft");
write(&small, &vectorcraft_format::save_file(&d));
let r = s.execute("file.place", &json!({"path": small, "crop": "bounding", "at": [200, 150]})).unwrap();
let p = placed(&s, NodeId(r["ids"][0].as_u64().unwrap()));
assert!(p.bounding && (p.width - 30.0).abs() < 1e-6 && (p.height - 20.0).abs() < 1e-6, "{p:?}");
}
#[test]
fn without_link_or_a_file_a_document_places_as_an_editable_copy() {
let dir = Folder::new("placed-copy");
let src = dir.file("logo.vectorcraft");
source(&src, 100.0, 50.0, RED, 0);
let mut s = session();
let data = vectorcraft_format::base64_encode(&std::fs::read(&src).unwrap());
for p in [json!({"path": src, "link": false}), json!({"name": "logo.vectorcraft", "dataBase64": data})] {
let r = s.execute("file.place", &p).unwrap();
assert_eq!(r["linked"], false, "{r}");
let n = s.doc().unwrap().doc.node(NodeId(r["ids"][0].as_u64().unwrap())).unwrap();
assert_eq!(n.kind_label(), "Clip Group", "{p}");
}
assert!(!s.doc().unwrap().doc.has_placed());
}
#[test]
fn a_placed_document_is_vectors_in_every_output() {
let dir = Folder::new("placed-outputs");
let src = dir.file("logo.vectorcraft");
source(&src, 100.0, 50.0, RED, 0);
let mut s = session();
place(&mut s, &src);
let svg = s.execute("document.serialize", &json!({"format": "svg"})).unwrap();
let text = svg["text"].as_str().unwrap();
assert!(!text.contains("<image") && (text.contains("<path") || text.contains("<rect")), "drawn as paths: {text}");
let (images, paths) = pdf_contents(&decode(&s.execute("document.serialize", &json!({"format": "pdf"})).unwrap()));
assert_eq!(images, 0, "no image in the PDF");
assert!(paths > 0);
let png = decode(&s.execute("document.serialize", &json!({"format": "png"})).unwrap());
let [r, g, b, _] = image::load_from_memory(&png).unwrap().to_rgba8().get_pixel(200, 150).0;
assert!(near([r, g, b], RED), "{:?}", [r, g, b]);
for format in ["eps", "emf", "dxf"] {
let out = s.execute("document.serialize", &json!({"format": format})).unwrap();
assert!(out.to_string().len() > 200, "{format}: {out}");
}
let info = s.execute("document.info", &json!({})).unwrap();
assert!(info.to_string().contains("\"placedDocuments\""), "{info}");
}
#[test]
fn the_preview_is_saved_so_the_document_shows_it_without_its_file() {
let dir = Folder::new("placed-saved");
let src = dir.file("logo.vectorcraft");
// Content of its own: files read are cached by content, and this one is removed.
source(&src, 100.0, 50.0, RED, 2);
let mut s = session();
let id = place(&mut s, &src);
let doc_path = dir.file("poster/poster.vectorcraft");
std::fs::create_dir_all(dir.file("poster")).unwrap();
save(&mut s, &doc_path);
let saved: Value = serde_json::from_slice(&std::fs::read(&doc_path).unwrap()).unwrap();
let kind = &saved["document"]["layers"][0]["kind"]["children"][0]["kind"];
assert_eq!(kind["type"], "placeddocument");
assert_eq!(kind["link"]["relative"], "../logo.vectorcraft");
let key = kind["key"].as_str().unwrap();
let entry = &saved["images"][key];
assert_eq!((entry["proxy"].as_bool(), entry["mime"].as_str()), (Some(true), Some("image/jpeg")), "the preview, as JPEG (opaque)");
// Include Linked Files keeps the file itself.
let full = file_json(&decode(&s.execute("document.serialize", &json!({"format": "vectorcraft", "includeLinked": true})).unwrap()));
assert_eq!((full["images"][key]["proxy"].clone(), full["images"][key]["mime"].as_str()), (Value::Null, Some("application/json")));
std::fs::remove_file(&src).unwrap();
let r = open(&mut s, &doc_path);
assert_eq!(r["missingLinks"].as_array().map(Vec::len), Some(1), "{r}");
assert_eq!(placed(&s, id).link.path, src);
assert!(near(centre_colour(&s.doc().unwrap().doc), RED), "shown from the saved preview");
assert_eq!(s.execute("links.check", &json!({})).unwrap()["missing"], 1);
// Output with the file gone: the preview, with a warning.
let png = s.execute("document.serialize", &json!({"format": "png"})).unwrap();
assert!(png["warnings"].to_string().contains("output as their previews"), "{png}");
let [r, g, b, _] = image::load_from_memory(&decode(&png)).unwrap().to_rgba8().get_pixel(200, 150).0;
assert!(near([r, g, b], RED), "{:?}", [r, g, b]);
// Saved for older apps: the art it shows (here its preview), as plain objects.
let old: Value =
serde_json::from_slice(&decode(&s.execute("document.serialize", &json!({"format": "vectorcraft", "version": 2})).unwrap())).unwrap();
let old = old["document"]["layers"][0]["kind"]["children"][0].to_string();
assert!(old.contains("\"image\"") && !old.contains("placeddocument"), "{old}");
}
#[test]
fn a_document_saved_with_previews_outputs_its_files_art() {
let dir = Folder::new("placed-preview-output");
let src = dir.file("logo.vectorcraft");
source(&src, 100.0, 50.0, RED, 0);
let mut s = session();
let id = place(&mut s, &src);
let doc_path = dir.file("poster.vectorcraft");
save(&mut s, &doc_path);
open(&mut s, &doc_path);
let key = placed(&s, id).key;
assert!(s.doc().unwrap().doc.images[&key].is_proxy(), "opened with the preview only");
assert!(near(centre_colour(&s.doc().unwrap().doc), RED));
// Output reads the file again: vectors, no warning.
let svg = s.execute("document.serialize", &json!({"format": "svg"})).unwrap();
assert_eq!(svg["warnings"], json!([]), "{}", svg["warnings"]);
let text = svg["text"].as_str().unwrap();
assert!(!text.contains("<image") && (text.contains("<path") || text.contains("<rect")), "vectors");
// So does saving with Include Linked Files, and the document stays as it was.
let full = file_json(&decode(&s.execute("document.serialize", &json!({"format": "vectorcraft", "includeLinked": true})).unwrap()));
assert_eq!(full["images"][&key]["mime"], "application/json");
assert!(s.doc().unwrap().doc.images[&key].is_proxy());
}
#[test]
fn a_changed_file_is_modified_and_update_links_reads_it_again() {
let dir = Folder::new("placed-update");
let src = dir.file("logo.vectorcraft");
source(&src, 100.0, 50.0, RED, 0);
let mut s = session();
let id = place(&mut s, &src);
s.execute("object.scale", &json!({"sx": 200})).unwrap();
let before = bounds(&s, id);
let c = s.execute("links.check", &json!({})).unwrap();
assert_eq!((c["modified"].as_u64(), c["links"][0]["status"].as_str()), (Some(0), Some("ok")), "{c}");
let list = s.execute("links.list", &json!({})).unwrap();
let row = &list["links"][0];
assert_eq!((row["format"].as_str(), row["document"].as_bool(), row["status"].as_str()), (Some("VectorCraft"), Some(true), Some("ok")), "{row}");
// A blue document, wider, and a different file size.
source(&src, 200.0, 50.0, BLUE, 1);
assert_eq!(s.execute("links.check", &json!({})).unwrap()["links"][0]["status"], "modified");
// Until updated, it shows (and outputs) the file as it read it.
let svg = s.execute("document.serialize", &json!({"format": "svg"})).unwrap();
assert_eq!(svg["warnings"], json!([]));
assert!(near(centre_colour(&s.doc().unwrap().doc), RED));
let u = s.execute("links.update", &json!({})).unwrap();
assert_eq!(u["updated"], json!([id.0]), "{u}");
assert_eq!(placed(&s, id).width, 200.0);
assert_eq!(bounds(&s, id), before, "keeps its bounds");
assert!(near(centre_colour(&s.doc().unwrap().doc), BLUE));
assert_eq!(s.execute("links.check", &json!({})).unwrap()["modified"], 0);
// One undo step.
s.execute("edit.undo", &json!({})).unwrap();
assert!(near(centre_colour(&s.doc().unwrap().doc), RED));
}
#[test]
fn update_links_on_open_reads_a_modified_file_again() {
let dir = Folder::new("placed-open");
let src = dir.file("logo.vectorcraft");
source(&src, 100.0, 50.0, RED, 0);
let mut s = session();
place(&mut s, &src);
let doc_path = dir.file("poster.vectorcraft");
save(&mut s, &doc_path);
source(&src, 100.0, 50.0, BLUE, 1);
// Ask When Modified (the default): reported, left as it was.
let r = open(&mut s, &doc_path);
assert_eq!(r["modifiedLinks"].as_array().map(Vec::len), Some(1), "{r}");
assert!(near(centre_colour(&s.doc().unwrap().doc), RED));
// Automatically: read again as the document opens.
s.execute("prefs.set", &json!({"key": "updateLinks", "value": "automatically"})).unwrap();
let r = open(&mut s, &doc_path);
assert_eq!(r["updatedLinks"].as_array().map(Vec::len), Some(1), "{r}");
assert!(near(centre_colour(&s.doc().unwrap().doc), BLUE));
}
#[test]
fn relink_points_a_placed_document_at_another_file() {
let dir = Folder::new("placed-relink");
let (a, b) = (dir.file("a.vectorcraft"), dir.file("b.vectorcraft"));
source(&a, 100.0, 50.0, RED, 0);
source(&b, 100.0, 50.0, BLUE, 0);
let mut s = session();
let id = place(&mut s, &a);
let r = s.execute("links.relink", &json!({"ids": [id.0], "path": b})).unwrap();
assert_eq!(r["relinked"], json!([id.0]), "{r}");
assert_eq!(placed(&s, id).link.path, b);
assert!(near(centre_colour(&s.doc().unwrap().doc), BLUE));
}
#[test]
fn a_placed_document_inside_a_placed_document_outputs_from_its_own_file() {
let dir = Folder::new("placed-nested");
let (logo, card) = (dir.file("logo.vectorcraft"), dir.file("card.vectorcraft"));
source(&logo, 100.0, 50.0, RED, 0);
// The card places the logo, and is saved with the logo's preview only.
let mut s = session();
place(&mut s, &logo);
save(&mut s, &card);
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
place(&mut s, &card);
assert!(near(centre_colour(&s.doc().unwrap().doc), RED));
// The logo inside is read from its file: vectors, not its preview.
let svg = s.execute("document.serialize", &json!({"format": "svg"})).unwrap();
let text = svg["text"].as_str().unwrap();
assert!(!text.contains("<image"), "the logo's file, not its preview: {text}");
assert_eq!(pdf_contents(&decode(&s.execute("document.serialize", &json!({"format": "pdf"})).unwrap())).0, 0);
}
#[test]
fn documents_that_place_each_other_dont_loop() {
let dir = Folder::new("placed-loop");
let (a, b) = (dir.file("a.vectorcraft"), dir.file("b.vectorcraft"));
source(&a, 100.0, 50.0, RED, 0);
// B places A; A then places B.
let mut s = session();
place(&mut s, &a);
save(&mut s, &b);
s.execute("document.open", &json!({"path": a})).unwrap();
place(&mut s, &b);
save(&mut s, &a);
s.execute("document.open", &json!({"path": b})).unwrap();
let u = s.execute("links.update", &json!({})).unwrap();
assert_eq!(u["updated"].as_array().map(Vec::len), Some(1), "{u}");
// Drawn and output a few levels deep, then their previews.
assert!(near(centre_colour(&s.doc().unwrap().doc), RED));
for format in ["svg", "pdf", "png"] {
s.execute("document.serialize", &json!({"format": format})).unwrap();
}
}
#[test]
fn what_cant_be_placed_linked_is_an_error() {
let dir = Folder::new("placed-errors");
let src = dir.file("logo.vectorcraft");
source(&src, 100.0, 50.0, RED, 0);
let mut s = session();
let place = |s: &mut Session, p: Value| s.execute("file.place", &p).unwrap_err().to_string();
let e = place(&mut s, json!({"path": src, "page": 2}));
assert!(e.contains("page 2") && e.contains("1 artboard"), "{e}");
let e = place(&mut s, json!({"path": src, "crop": "art"}));
assert!(e.contains("crop"), "{e}");
let empty = dir.file("empty.vectorcraft");
write(&empty, &vectorcraft_format::save_file(&Document::new(100.0, 50.0)));
let e = place(&mut s, json!({"path": empty, "crop": "bounding"}));
assert!(e.contains("no art to place"), "{e}");
// Junk params are errors, not crashes.
for v in [json!(null), json!(true), json!(-1), json!(1e308), json!("x"), json!([1, 2]), json!({"a": {"b": []}})] {
for k in ["link", "page", "crop", "at", "rect"] {
let _ = s.execute("file.place", &json!({"path": src, k: v}));
}
}
}
#[test]
fn a_placed_documents_resources_stay_its_own() {
let dir = Folder::new("placed-symbols");
let src = dir.file("badge.vectorcraft");
star_source(&src, "star");
let mut s = session();
parent_star(&mut s);
place(&mut s, &src);
assert!(near(centre_colour(&s.doc().unwrap().doc), BLUE), "the file's own Star");
let doc = &s.doc().unwrap().doc;
assert_eq!(doc.symbols.len(), 1, "nothing joins the document");
let prefix = vectorcraft_doc::placed_document::RESOURCE_PREFIX;
assert!(doc.images.keys().all(|k| !k.starts_with(prefix)));
let svg = s.execute("document.serialize", &json!({"format": "svg"})).unwrap();
assert!(!svg["text"].as_str().unwrap().contains("<image"));
// Nor its saves.
let saved = String::from_utf8(decode(&s.execute("document.serialize", &json!({"format": "vectorcraft"})).unwrap())).unwrap();
assert!(!saved.contains(prefix), "{saved}");
// Saved for older apps: the art and its resources, as plain objects.
let old = vectorcraft_format::load(&decode(&s.execute("document.serialize", &json!({"format": "vectorcraft", "version": 2})).unwrap())).unwrap();
assert!(!old.has_placed());
assert!(near(centre_colour(&old), BLUE));
}
#[test]
fn break_link_gives_the_editable_copy_placing_without_link_gives() {
let dir = Folder::new("placed-break");
let src = dir.file("badge.vectorcraft");
star_source(&src, "break");
let mut s = session();
parent_star(&mut s);
// The copy placing without Link gives.
let r = s.execute("file.place", &json!({"path": src, "link": false, "at": [200, 150]})).unwrap();
let copy = s.doc().unwrap().doc.node(NodeId(r["ids"][0].as_u64().unwrap())).unwrap().clone();
s.execute("edit.undo", &json!({})).unwrap();
let id = place(&mut s, &src);
let r = s.execute("links.embed", &json!({"ids": [id.0]})).unwrap();
assert_eq!(r["embedded"], json!([id.0]), "{r}");
let doc = &s.doc().unwrap().doc;
let n = doc.node(id).unwrap();
assert!(!doc.has_placed() && n.kind_label() == "Clip Group", "{}", n.kind_label());
assert_eq!((n.name.as_deref(), n.geometric_bounds()), (copy.name.as_deref(), copy.geometric_bounds()));
let kinds = |n: &Node| {
let mut k = vec![];
n.walk(&mut |c| k.push(c.kind_label()));
k
};
assert_eq!(kinds(n), kinds(&copy));
assert!(near(centre_colour(doc), BLUE), "the art as it showed");
let names: Vec<&str> = doc.symbols.iter().map(|s| s.name.as_str()).collect();
assert_eq!(names.len(), 2, "the file's Star joined, renamed: {names:?}");
assert_eq!(s.execute("links.list", &json!({})).unwrap()["links"], json!([]));
assert_eq!(s.doc().unwrap().history.undo.last().unwrap().label, "Embed");
s.execute("edit.undo", &json!({})).unwrap();
assert!(s.doc().unwrap().doc.has_placed());
// A file that can't be read stays linked.
std::fs::remove_file(&src).unwrap();
let doc_path = dir.file("poster.vectorcraft");
save(&mut s, &doc_path);
open(&mut s, &doc_path);
let r = s.execute("links.embed", &json!({"ids": [id.0]})).unwrap();
assert_eq!((r["embedded"].clone(), r["missing"].clone()), (json!([]), json!([id.0])), "{r}");
}
#[test]
fn expand_turns_a_placed_document_into_editable_art_with_its_resources() {
let dir = Folder::new("placed-expand");
let src = dir.file("badge.vectorcraft");
star_source(&src, "star");
let mut s = session();
parent_star(&mut s);
let id = place(&mut s, &src);
s.execute("object.scale", &json!({"sx": 200})).unwrap();
let before = bounds(&s, id);
s.execute("object.expand", &json!({})).unwrap();
let doc = &s.doc().unwrap().doc;
let n = doc.node(id).unwrap();
assert!(n.is_container() && !doc.has_placed(), "{:?}", n.kind_label());
let after = n.geometric_bounds().unwrap();
assert!((after.width() - before.width()).abs() < 0.5 && (after.height() - before.height()).abs() < 0.5, "{after:?} vs {before:?}");
assert!(near(centre_colour(doc), BLUE));
let saved = vectorcraft_format::save_file(doc);
assert!(near(centre_colour(&vectorcraft_format::load(&saved).unwrap()), BLUE), "saved with its resources");
let info = s.execute("object.expand.info", &json!({})).unwrap();
assert_eq!(info["object"], false, "nothing left to expand: {info}");
}
#[test]
fn saving_a_document_refreshes_the_open_documents_that_place_it() {
let dir = Folder::new("placed-refresh");
let src = dir.file("logo.vectorcraft");
source(&src, 100.0, 50.0, RED, 0);
let mut s = session();
let id = place(&mut s, &src);
let parent = s.active_index().unwrap();
// Open the file, recolour it and save it.
s.execute("document.open", &json!({"path": src})).unwrap();
s.execute("select.all", &json!({})).unwrap();
s.execute("paint.setFill", &json!({"color": "#1414e6"})).unwrap();
s.execute("document.save", &json!({})).unwrap();
let child = s.active_index().unwrap();
assert_ne!(parent, child);
let doc = &s.documents()[parent];
assert_eq!(doc.history.undo.last().unwrap().label, "Update Links");
assert!(near(centre_colour(&doc.doc), BLUE), "shows the saved version");
assert!(matches!(doc.doc.node(id).map(|n| &n.kind), Some(NodeKind::PlacedDocument(_))));
assert_eq!(s.active_index(), Some(child), "the saved document stays active");
}
#[test]
fn link_info_gives_the_artboards_size_not_pixels() {
let dir = Folder::new("placed-info");
let src = dir.file("logo.vectorcraft");
source(&src, 100.0, 50.0, RED, 0);
let mut s = session();
let id = place(&mut s, &src);
s.execute("object.scale", &json!({"sx": 200})).unwrap();
let i = s.execute("links.info", &json!({"id": id.0})).unwrap();
assert_eq!((i["pageWidth"].as_f64(), i["pageHeight"].as_f64(), i["document"].as_bool()), (Some(100.0), Some(50.0), Some(true)), "{i}");
assert!(i.get("pixelWidth").is_none() && i.get("ppi").is_none(), "no pixels: {i}");
assert_eq!(
(i["status"].as_str(), i["fileName"].as_str(), i["scale"].clone()),
(Some("ok"), Some("logo.vectorcraft"), json!([200.0, 200.0])),
"{i}"
);
}
+16 -13
View File
@@ -123,34 +123,37 @@ fn prefs_serde_round_trip_and_tolerates_missing_fields() {
assert_eq!(partial.corner_radius, 12.0);
}
/// Performance › Graphics Processor (#306): power saving by default, set by value or label, kept
/// through a save/load round trip, and a bad value is an error that changes nothing.
/// Performance › Graphics Processor (#306, #502): automatic by default, set by value or label,
/// kept through a save/load round trip, and a bad value (0.5.0's `powerSaving` among them) is an
/// error that changes nothing.
#[test]
fn gpu_preference_defaults_to_power_saving_and_validates() {
fn gpu_preference_defaults_to_automatic_and_validates() {
let mut s = Session::new();
assert_eq!(s.prefs.gpu_preference, "powerSaving");
assert_eq!(s.execute("prefs.get", &json!({"key": "gpuPreference"})).unwrap(), json!("powerSaving"));
assert_eq!(s.prefs.gpu_preference, "automatic");
assert_eq!(s.execute("prefs.get", &json!({"key": "gpuPreference"})).unwrap(), json!("automatic"));
s.execute("prefs.set", &json!({"key": "gpuPreference", "value": "highPerformance"})).unwrap();
assert_eq!(s.prefs.gpu_preference, "highPerformance");
s.execute("prefs.set", &json!({"key": "gpuPreference", "value": "Power Saving (integrated)"})).unwrap();
assert_eq!(s.prefs.gpu_preference, "powerSaving");
for bad in [json!("turbo"), json!(""), json!(1), json!(null), json!(["highPerformance"])] {
assert_eq!(s.prefs.gpu_preference, "lowPower");
s.execute("prefs.set", &json!({"key": "gpuPreference", "value": "automatic"})).unwrap();
assert_eq!(s.prefs.gpu_preference, "automatic");
for bad in [json!("powerSaving"), json!("turbo"), json!(""), json!(1), json!(null), json!(["highPerformance"])] {
assert!(s.execute("prefs.set", &json!({"key": "gpuPreference", "value": bad})).is_err(), "{bad}");
assert_eq!(s.prefs.gpu_preference, "powerSaving");
assert_eq!(s.prefs.gpu_preference, "automatic");
}
let p = Prefs { gpu_preference: "highPerformance".into(), ..Default::default() };
let p = Prefs { gpu_preference: "lowPower".into(), ..Default::default() };
let back: Prefs = serde_json::from_value(p.to_json()).unwrap();
assert_eq!(back.gpu_preference, "highPerformance");
assert_eq!(back.gpu_preference, "lowPower");
// Preference files written before the preference existed get the default.
let old: Prefs = serde_json::from_value(json!({"gpuPerformance": true})).unwrap();
assert_eq!(old.gpu_preference, "powerSaving");
assert_eq!(old.gpu_preference, "automatic");
let l = s.execute("prefs.list", &json!({})).unwrap();
let row = l.as_array().unwrap().iter().find(|e| e["key"] == "gpuPreference").unwrap().clone();
assert_eq!(row["category"], "Performance");
assert_eq!(row["options"], json!(["powerSaving", "highPerformance"]));
assert_eq!(row["options"], json!(["automatic", "lowPower", "highPerformance"]));
s.execute("prefs.set", &json!({"key": "gpuPreference", "value": "highPerformance"})).unwrap();
s.execute("prefs.reset", &json!({"category": "Performance"})).unwrap();
assert_eq!(s.prefs.gpu_preference, "powerSaving");
assert_eq!(s.prefs.gpu_preference, "automatic");
}
/// Selection & Anchor Display › Tolerance, Object Selection by Path Only and Command Click to
+109
View File
@@ -0,0 +1,109 @@
//! Smart Guides for the drawing tools, driven through the session (#506): where the Rectangle
//! tool's corners and the Pen's anchors land, and the guides they show.
use serde_json::json;
use vectorcraft_doc::NodeId;
use vectorcraft_geom::{Point, Rect};
use vectorcraft_tools::{Mods, Overlay, PointerEvent, PointerKind};
use super::*;
use crate::tooling::ViewInfo;
/// An 800 × 600 document with a 100 × 100 square at (100, 100), nothing selected.
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap();
s.execute("select.none", &json!({})).unwrap();
s
}
fn pointer(s: &mut Session, kind: PointerKind, x: f64, y: f64) {
s.pointer(&PointerEvent::new(kind, x, y), ViewInfo::default()).unwrap();
}
fn labels(s: &mut Session) -> Vec<(String, Point)> {
s.overlays(ViewInfo::default()).into_iter().filter_map(|o| if let Overlay::Label { text, p, .. } = o { Some((text, p)) } else { None }).collect()
}
/// The bounds of the object the last gesture made (it is selected).
fn made(s: &Session) -> Rect {
let d = s.doc().unwrap();
let id: NodeId = d.selection.objects[0];
d.doc.node(id).unwrap().geometric_bounds().unwrap()
}
#[test]
fn a_rectangle_corner_lands_on_another_objects_anchor() {
let mut s = session();
s.select_tool("rectangle", ViewInfo::default()).unwrap();
// Hovering near the square's corner already says where the press goes.
pointer(&mut s, PointerKind::Move, 302.0, 297.0);
pointer(&mut s, PointerKind::Move, 202.0, 203.0);
assert_eq!(labels(&mut s), [("anchor".to_string(), Point::new(200.0, 200.0))]);
pointer(&mut s, PointerKind::Down, 302.0, 297.0);
pointer(&mut s, PointerKind::Drag, 250.0, 250.0);
pointer(&mut s, PointerKind::Drag, 202.0, 203.0);
assert_eq!(labels(&mut s), [("anchor".to_string(), Point::new(200.0, 200.0))]);
let measure = s.overlays(ViewInfo::default()).into_iter().find_map(|o| if let Overlay::Measure { text, .. } = o { Some(text) } else { None });
assert!(measure.as_deref().is_some_and(|t| t.starts_with("W: 102") && t.contains("H: 100")), "{measure:?}");
pointer(&mut s, PointerKind::Up, 202.0, 203.0);
// The start lined up with the artboard's centre (y = 300), the corner on the anchor.
assert_eq!(made(&s), Rect::new(200.0, 200.0, 302.0, 300.0));
}
/// The corner being dragged never snaps to the rectangle's own preview: dragged slowly, it follows
/// the pointer instead of sticking where the last step left it.
#[test]
fn a_rectangle_does_not_snap_to_itself_while_drawn() {
let mut s = session();
s.select_tool("rectangle", ViewInfo::default()).unwrap();
pointer(&mut s, PointerKind::Down, 320.0, 420.0);
for x in 370..=380 {
pointer(&mut s, PointerKind::Drag, f64::from(x), 470.0 + f64::from(x - 370));
}
pointer(&mut s, PointerKind::Up, 380.0, 480.0);
assert_eq!(made(&s), Rect::new(320.0, 420.0, 380.0, 480.0));
}
#[test]
fn a_pen_anchor_lines_up_with_another_objects_centre() {
let mut s = session();
s.select_tool("pen", ViewInfo::default()).unwrap();
pointer(&mut s, PointerKind::Down, 300.0, 420.0);
pointer(&mut s, PointerKind::Up, 300.0, 420.0);
// Hovering: in line with the square's centre (150, 150), the guide running from it.
pointer(&mut s, PointerKind::Move, 151.5, 431.0);
let ov = s.overlays(ViewInfo::default());
assert!(ov.iter().any(|o| matches!(o, Overlay::Line { a, b, .. } if *a == Point::new(150.0, 150.0) && *b == Point::new(150.0, 431.0))), "{ov:?}");
assert_eq!(labels(&mut s), [("align".to_string(), Point::new(150.0, 431.0))]);
pointer(&mut s, PointerKind::Down, 151.5, 431.0);
pointer(&mut s, PointerKind::Up, 151.5, 431.0);
// Shift: along the 45° step from it, slid into line with the square's left side (x = 100).
s.pointer(&PointerEvent::new(PointerKind::Down, 103.0, 386.0).with_mods(Mods { shift: true, ..Mods::default() }), ViewInfo::default()).unwrap();
pointer(&mut s, PointerKind::Up, 103.0, 386.0);
let d = s.doc().unwrap();
let path = d.doc.node(d.selection.objects[0]).unwrap().path_data().unwrap();
let pts: Vec<Point> = path.subpaths[0].anchors.iter().map(|a| a.p).collect();
assert_eq!(pts[..2], [Point::new(300.0, 420.0), Point::new(150.0, 431.0)]);
assert!((pts[2] - Point::new(100.0, 381.0)).hypot() < 1e-9, "{pts:?}");
}
/// Preferences › Smart Guides › Construction Guides: on (the default), a Pen anchor near the
/// 45° guide through the last one lands on it; off, it stays where it was clicked.
#[test]
fn construction_guides_follow_the_preference() {
for on in [true, false] {
let mut s = session();
s.execute("prefs.set", &json!({"key": "constructionGuides", "value": on})).unwrap();
s.select_tool("pen", ViewInfo::default()).unwrap();
pointer(&mut s, PointerKind::Down, 500.0, 500.0);
pointer(&mut s, PointerKind::Up, 500.0, 500.0);
pointer(&mut s, PointerKind::Down, 561.0, 438.0);
pointer(&mut s, PointerKind::Up, 561.0, 438.0);
let d = s.doc().unwrap();
let last = d.doc.node(d.selection.objects[0]).unwrap().path_data().unwrap().subpaths[0].anchors[1].p;
let want = if on { Point::new(561.5, 438.5) } else { Point::new(561.0, 438.0) };
assert!((last - want).hypot() < 1e-9, "{on}: {last:?}");
}
}
+68 -6
View File
@@ -82,6 +82,7 @@ impl Session {
/// Switch to tool `id` without choosing it afresh (back from a temporary tool: a hidden
/// perspective grid stays hidden), finishing any pending tool work first.
pub fn switch_tool(&mut self, id: &str, view: ViewInfo) -> Result<()> {
self.give_back_tool(view)?;
if self.tool.id() == id {
return Ok(());
}
@@ -89,9 +90,47 @@ impl Session {
self.apply_actions(acts)?;
self.keep_tool_settings();
self.tool = self.make_tool(id);
if vectorcraft_tools::catalog::is_selection_tool(id) {
self.last_selection_tool = Some(self.tool.id());
}
Ok(())
}
/// The selection tool Cmd lends tool `id` for a drag: the one chosen last; until one is,
/// Direct Selection to the tools that edit anchors (the Pen) and Selection to the others.
/// None for the selection tools themselves and the view tools.
fn lent_tool(&self, id: &str) -> Option<&'static str> {
use vectorcraft_tools::catalog::{edits_anchors, is_selection_tool};
if is_selection_tool(id) || matches!(id, "hand" | "zoom" | "rotateView") {
return None;
}
Some(self.last_selection_tool.unwrap_or(if edits_anchors(id) { "directSelection" } else { "selection" }))
}
/// A press with Cmd held (Ctrl elsewhere) and any other tool than a selection tool: the
/// selection tool [`Self::lent_tool`] takes the gesture, pressing without Cmd (a plain click,
/// not Select Behind). The tool lent to stays as it was, unaware, until the release.
fn lend_selection_tool(&mut self, ev: &PointerEvent) -> PointerEvent {
if ev.kind != PointerKind::Down || !ev.mods.cmd || self.lender.is_some() {
return *ev;
}
let Some(id) = self.lent_tool(self.tool.id()) else { return *ev };
let lent = self.make_tool(id);
self.lender = Some(std::mem::replace(&mut self.tool, lent));
PointerEvent { mods: Mods { cmd: false, ..ev.mods }, ..*ev }
}
/// The lent selection tool's gesture is over: the tool it was lent to is back as it was (the
/// Pen goes on drawing its path).
pub(crate) fn give_back_tool(&mut self, view: ViewInfo) -> Result<()> {
let Some(lender) = self.lender.take() else { return Ok(()) };
let acts = self.with_tool_cx(view, |t, cx| t.deactivate(cx));
let r = self.apply_actions(acts);
self.keep_tool_settings();
self.tool = lender;
r.map(drop)
}
/// A fresh `id` tool with the options it keeps ([`settings`]): its last values, from this
/// session or a saved one.
pub(crate) fn make_tool(&self, id: &str) -> Box<dyn Tool> {
@@ -139,6 +178,7 @@ impl Session {
let (unit, stroke_unit) = (self.general_unit(), self.stroke_unit());
let cx = ToolContext {
doc: &st.doc,
revision: (st.uid, st.revision),
selection: &st.selection,
zoom: view.zoom,
isolation: st.isolation,
@@ -183,6 +223,11 @@ impl Session {
measurement_labels: self.prefs.measurement_labels,
transform_tools_guides: self.prefs.transform_tools_guides,
snapping_tolerance: self.prefs.snapping_tolerance,
construction_angles: if self.prefs.construction_guides {
vectorcraft_tools::guides::construction_angles(&self.prefs.construction_angles)
} else {
&[]
},
screen: view.screen,
plane_widget: self.prefs.perspective_widget.show.then_some(self.prefs.perspective_widget.position),
};
@@ -212,13 +257,19 @@ impl Session {
if let Some(r) = self.plane_widget_pointer(ev, view) {
return r;
}
let ev = &self.lend_selection_tool(ev);
let acts = self.with_tool_cx(view, |t, cx| t.pointer(cx, ev));
self.take_tool_panic()?;
// A gesture may change options (Alt-drag sizes a Liquify brush): keep them.
let r = self.take_tool_panic().and_then(|()| {
// A gesture may change options (Alt-drag sizes a Liquify brush): keep them.
if ev.kind == PointerKind::Up {
self.keep_tool_settings();
}
self.apply_actions(acts)
});
if ev.kind == PointerKind::Up {
self.keep_tool_settings();
self.give_back_tool(view)?;
}
self.apply_actions(acts)
r
}
/// A guide dragged out of a ruler, whatever the tool: a vertical one out of the left ruler, a
@@ -325,9 +376,20 @@ impl Session {
}
/// The pointer the active tool shows at `p` (General › Use Precise Cursors makes the drawing
/// tools' a crosshair, [`Cursor::precise`]).
/// tools' a crosshair, [`Cursor::precise`]). With Cmd held, the pointer of the selection tool a
/// press would borrow ([`Self::lend_selection_tool`]).
pub fn cursor(&mut self, p: Point, mods: Mods, view: ViewInfo) -> Cursor {
let c = self.with_tool_cx(view, |t, cx| t.cursor(cx, p, mods));
let lent = if mods.cmd && self.lender.is_none() { self.lent_tool(self.tool.id()) } else { None };
let c = match lent {
Some(id) => {
let lent = self.make_tool(id);
let own = std::mem::replace(&mut self.tool, lent);
let c = self.with_tool_cx(view, |t, cx| t.cursor(cx, p, Mods { cmd: false, ..mods }));
self.tool = own;
c
}
None => self.with_tool_cx(view, |t, cx| t.cursor(cx, p, mods)),
};
if self.prefs.use_precise_cursors { c.precise() } else { c }
}
+13 -2
View File
@@ -488,6 +488,10 @@ fn arb_rich_op() -> impl Strategy<Value = String> {
"/Sh0 sh",
"/Sh1 sh",
"BT /F1 12 Tf 10 10 Td (Hi there) Tj [(a) -900 (b)] TJ ET",
// Lines wrapped in a frame, digits set apart by gaps, glyph outlines stroked (#508).
"BT /F1 10 Tf 10 80 Td (Wrapped line ) Tj 0 -12 Td (and its next ) Tj 0 -12 Td (end.) Tj ET",
"BT /F1 10 Tf 10 40 Td (3) Tj 20 0 Td (5331) Tj 40 0 Td (0106) Tj ET",
"0.5 w 10 10 m 14 18 l 18 10 l h S",
"7 Tr",
"q 10 10 50 50 re W n",
"Q",
@@ -874,7 +878,8 @@ proptest! {
}
/// Hostile PostScript programs: operators in any order with any operands, opened and placed;
/// as Illustrator's too, its groups (`u` … `U`) unbalanced, deep and among clips.
/// 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.
#[test]
fn eps_hostile_programs_never_panic(tokens in prop::collection::vec(arb_ps_token(), 0..60), illustrator in any::<bool>()) {
let head = if illustrator { "%%Creator: Adobe Illustrator(R) 8.0\n%%EndComments\n/u {} def /U {} def" } else { "%%EndComments" };
@@ -948,7 +953,13 @@ fn arb_ps_token() -> impl Strategy<Value = String> {
"/T3 << /FontType 3 /FontMatrix [0.1 0 0 0.1 0 0] /FontBBox [0 0 9 9] /Encoding [/a /b] /BuildChar { pop pop 9 0 setcharwidth 0 0 5 5 rectfill } >> definefont setfont",
"/T4 << /FontType 3 /FontMatrix [1 0 0 1 0 0] /BuildGlyph { pop pop (x) show } /Encoding [/a] >> definefont setfont",
"glyphshow", "xshow", "xyshow", "awidthshow", "kshow", "/a", "[1 2 3]",
// Executable strings and integer keys (Illustrator 8's procsets).
// Several data sources reading one file in turn, and sources of uneven lengths.
"/f currentfile /ASCIIHexDecode filter def", "{f 3 string readstring pop}", "{f 0 string readstring pop}", "true 3 colorimage",
"3 2 8 [3 0 0 2 0 0] {f 5 string readstring pop} {(ab)} {f 1 string readstring pop} true 3 colorimage",
"<< /ImageType 1 /Width 3 /Height 2 /BitsPerComponent 4 /Decode [0 1 0 1 0 1 0 1] /ImageMatrix [3 0 0 2 0 0] /MultipleDataSources true /DataSource [(a) (bc) {f 2 string readstring pop} (d)] >>",
// Local VM restored: dictionary changes undone, saves restored twice.
"/a 1 def save /a 2 def", "restore", "save dup restore", "1 dict save exch /k 1 put", "cachestatus", "/n 0 def save /n n 1 add store",
// Executable strings and keys other than names (PLRM 3rd ed., `cvx`, `load`).
"(>>) cvx", "(1 2 add) cvx exec", "(x) cvx dup exec", "0 load", "1 { } def", "(mark) cvx cvlit"
])
.prop_map(str::to_string),
+44 -30
View File
@@ -635,33 +635,51 @@ impl Interp<'_> {
/// The bytes a data procedure gives, called until it gives an empty string or `n` bytes.
fn gather(&mut self, p: &Obj, n: usize) -> Res<Vec<u8>> {
let mut out = vec![];
while out.len() < n {
self.call(p.clone())?;
let s = self.pop_str()?;
let s = s.borrow();
if s.is_empty() {
break;
}
self.alloc(s.len())?;
out.extend_from_slice(&s);
}
out.truncate(n);
Ok(out)
Ok(self.read_sources(&[Source::Proc(p.clone())], n, n)?.pop().unwrap_or_default())
}
/// `n` bytes of image data from `src` (zeros past its end).
fn source_bytes(&mut self, src: &Source, n: usize) -> Res<Vec<u8>> {
let mut v = match src {
Source::File(f) => self.read(f, n)?,
Source::Str(s) if !s.is_empty() => s.iter().copied().cycle().take(n).collect(),
Source::Str(_) => vec![],
Source::Proc(p) => self.gather(p, n)?,
};
let mut v = self.read_sources(std::slice::from_ref(src), n, n)?.pop().unwrap_or_default();
v.resize(n, 0);
Ok(v)
}
/// Up to `n` bytes from each of `sources`, read in turn as an image reads several data sources
/// (PLRM 3rd ed., §4.10 "Images" and `image`/`colorimage` in chapter 8: the sources are read
/// in turn, the same amount from each): each procedure called once a round (its string,
/// whatever its length), each file and string giving `step` bytes a round, until each has
/// given `n` bytes or ended. Procedures that read one file get their own rows that way.
fn read_sources(&mut self, sources: &[Source], n: usize, step: usize) -> Res<Vec<Vec<u8>>> {
let mut out: Vec<Vec<u8>> = vec![vec![]; sources.len()];
let mut ended = vec![false; sources.len()];
while out.iter().zip(&ended).any(|(o, e)| o.len() < n && !e) {
for ((src, o), e) in sources.iter().zip(out.iter_mut()).zip(ended.iter_mut()) {
if *e || o.len() >= n {
continue;
}
let want = step.min(n - o.len());
let chunk = match src {
Source::File(f) => self.read(f, want)?,
// A string gives its bytes over and over.
Source::Str(s) => {
let at = o.len() % s.len().max(1);
s.get(at..).unwrap_or_default().iter().chain(s.iter().cycle()).take(want).copied().collect()
}
Source::Proc(p) => {
self.call(p.clone())?;
let s = self.pop_str()?.to_vec();
self.alloc(s.len())?;
s
}
};
*e = chunk.is_empty();
o.extend_from_slice(chunk.get(..chunk.len().min(n - o.len())).unwrap_or_default());
}
}
Ok(out)
}
/// `eexec`: an encrypted font program follows. It is skipped (type is drawn in the app's
/// fonts, by name): the font dictionary it would complete is defined as it is.
fn eexec(&mut self) -> Res {
@@ -743,7 +761,7 @@ impl Interp<'_> {
let Some(mut img) = self.decode_image(image)? else { return Ok(None) };
let Some(m) = self.decode_image(stencil)? else { return Ok(Some(img)) };
let (w, h, mw, mh) = (img.w as usize, img.h as usize, m.w as usize, m.h as usize);
for (i, px) in img.rgba.chunks_exact_mut(4).enumerate() {
for (i, px) in img.rgba.as_chunks_mut::<4>().0.iter_mut().enumerate() {
let (x, y) = (i % w, i / w);
// The mask's pixel over this one (in 64 bits: rows times rows overflow 32).
let at = (y as u64 * mh as u64 / h.max(1) as u64) * mw as u64 + x as u64 * mw as u64 / w.max(1) as u64;
@@ -849,16 +867,12 @@ impl Interp<'_> {
let multi = s.sources.len() > 1;
let row_bits = if multi { s.w * bpc } else { s.w * n * bpc };
let row = row_bits.div_ceil(8);
let planes: Vec<Vec<u8>> = if multi {
let mut v = vec![];
for src in &s.sources {
v.push(self.source_bytes(src, row * s.h)?);
}
v
} else {
let src = s.sources.first().ok_or(PsError::Ps("undefined", "DataSource".into()))?;
vec![self.source_bytes(src, row * s.h)?]
};
// Several sources are read in turn, a row at a time each (zeros past their ends).
let sources = if multi { &s.sources[..] } else { s.sources.get(..1).ok_or(PsError::Ps("undefined", "DataSource".into()))? };
let mut planes = self.read_sources(sources, row * s.h, if multi { row } else { row * s.h })?;
for p in &mut planes {
p.resize(row * s.h, 0);
}
let max = ((1u32 << bpc.min(16)) - 1) as f64;
let sample = |plane: &[u8], y: usize, i: usize| -> u32 {
let bit = y * row * 8 + i * bpc;
+68 -23
View File
@@ -49,6 +49,12 @@ pub(crate) struct Interp<'a> {
/// Bytes asked for so far (see [`MAX_MEMORY`]).
allocated: usize,
seed: u32,
/// The `save`s not restored yet, oldest first.
saves: Vec<SaveMark>,
/// What dictionary entries were before they changed since the oldest `save` (dictionary,
/// key, old value): `restore` puts them back, as restoring local VM does (PLRM 3rd ed.,
/// §3.7.3 "Save and Restore": composite objects get the values they had at the `save`).
journal: Vec<(DictRef, Key, Option<Obj>)>,
/// Where the error that is unwinding was raised (see [`Fault`]).
pub fault: Option<Fault>,
/// The width a Type 3 glyph procedure gave (`setcachedevice`, `setcharwidth`).
@@ -56,8 +62,8 @@ pub(crate) struct Interp<'a> {
pub g: GState,
pub saved: Vec<GState>,
pub out: Out,
/// The program is an Illustrator file's: its `u` … `U` (written at the top level, whatever
/// its prolog defines them as) are groups.
/// The program is in the legacy Illustrator format: its group operators `u` … `U` (at the top
/// level, whatever its prolog defines them as) are groups (see the module docs of `import`).
pub illustrator: bool,
}
@@ -72,6 +78,13 @@ pub(crate) struct Fault {
/// Most procedure names a [`Fault`] keeps.
const FAULT_PROCS: usize = 3;
/// Where a `save` was made: the graphics states saved and the journal's length then.
#[derive(Clone, Copy, Debug)]
struct SaveMark {
gstates: usize,
journal: usize,
}
fn new_dict() -> DictRef {
Rc::new(RefCell::new(Dict::new()))
}
@@ -143,6 +156,8 @@ impl<'a> Interp<'a> {
ops: 0,
allocated: 0,
seed: 1,
saves: vec![],
journal: vec![],
fault: None,
glyph_width: None,
g,
@@ -157,7 +172,7 @@ impl<'a> Interp<'a> {
loop {
let Some(o) = self.lex.next()? else { return Ok(()) };
let o = self.scanned(o, self.lex.immediate)?;
// An Illustrator group begins before its `u` runs (`Some(true)`) and ends after its `U`
// A group begins before its `u` runs (`Some(true)`) and ends after its `U`
// has (`Some(false)`).
let group = match &o {
Obj::Exec(name) if self.illustrator => match &**name {
@@ -190,6 +205,7 @@ impl<'a> Interp<'a> {
}
self.dicts.clear();
self.stack.clear();
self.journal.clear();
}
// ---------- the operand stack ----------
@@ -879,7 +895,7 @@ impl<'a> Interp<'a> {
}
Obj::Dict(d) => {
let key = k.key().ok_or(PsError::Ps("typecheck", String::new()))?;
insert(&d, key, v)?;
self.insert(&d, key, Some(v))?;
true
}
_ => return ps_err("typecheck", ""),
@@ -968,7 +984,7 @@ impl<'a> Interp<'a> {
let v = self.pop()?;
let k = self.pop()?.key().ok_or(PsError::Ps("typecheck", String::new()))?;
let d = self.dicts.last().cloned().ok_or(PsError::Ps("dictstackunderflow", String::new()))?;
insert(&d, k, v)?;
self.insert(&d, k, Some(v))?;
}
Load => {
let k = self.pop()?;
@@ -981,7 +997,7 @@ impl<'a> Interp<'a> {
let k = self.pop()?.key().ok_or(PsError::Ps("typecheck", String::new()))?;
let d = self.dicts.iter().rev().find(|d| d.borrow().contains_key(&k)).or(self.dicts.last()).cloned();
let d = d.ok_or(PsError::Ps("dictstackunderflow", String::new()))?;
insert(&d, k, v)?;
self.insert(&d, k, Some(v))?;
}
Known => {
let k = self.pop()?.key().ok_or(PsError::Ps("typecheck", String::new()))?;
@@ -1001,7 +1017,8 @@ impl<'a> Interp<'a> {
}
Undef => {
let k = self.pop()?.key().ok_or(PsError::Ps("typecheck", String::new()))?;
self.pop_dict()?.borrow_mut().remove(&k);
let d = self.pop_dict()?;
self.insert(&d, k, None)?;
}
CurrentDict => {
let d = self.dicts.last().cloned().ok_or(PsError::Ps("dictstackunderflow", String::new()))?;
@@ -1034,11 +1051,24 @@ impl<'a> Interp<'a> {
}
Save => {
self.gsave()?;
self.push(Obj::Save(self.saved.len()))?;
self.push(Obj::Save(self.saves.len()))?;
self.saves.push(SaveMark { gstates: self.saved.len(), journal: self.journal.len() });
}
Restore => {
let Obj::Save(level) = self.pop()? else { return ps_err("typecheck", "") };
while self.saved.len() >= level && !self.saved.is_empty() {
let Obj::Save(i) = self.pop()? else { return ps_err("typecheck", "") };
// A save restored already (or through an outer one) is no longer valid: §3.7.3,
// `invalidrestore`.
let mark = self.saves.get(i).copied().ok_or(PsError::Ps("invalidrestore", String::new()))?;
self.saves.truncate(i);
// The dictionaries as they were at the save, newest change undone first.
for (d, k, old) in self.journal.drain(mark.journal..).rev() {
let mut d = d.borrow_mut();
match old {
Some(v) => d.insert(k, v),
None => d.remove(&k),
};
}
while self.saved.len() >= mark.gstates && !self.saved.is_empty() {
self.grestore();
}
}
@@ -1083,9 +1113,12 @@ impl<'a> Interp<'a> {
self.push(Obj::Int(1 << 20))?;
}
}
// An empty font cache of a device's sizes, in `cachestatus`'s order (PLRM 3rd ed.,
// chapter 8): bytes used and most, fonts used and most, glyphs used and most, and the
// most bytes one cached glyph may take (positive on a real device: programs divide by it).
CacheStatus => {
for _ in 0..7 {
self.push(Obj::Int(0))?;
for v in [0, 1 << 20, 0, 1000, 0, 10_000, 25_000] {
self.push(Obj::Int(v))?;
}
}
StartJob => {
@@ -1143,7 +1176,9 @@ impl<'a> Interp<'a> {
}
Obj::Dict(d) => {
let from = self.pop_dict()?.borrow().clone();
d.borrow_mut().extend(from);
for (k, v) in from {
self.insert(&d, k, Some(v))?;
}
self.push(Obj::Dict(d))?;
}
_ => return ps_err("typecheck", "copy"),
@@ -1219,6 +1254,26 @@ impl<'a> Interp<'a> {
}
}
/// Put `v` under `k` in `d` (`None`: remove it), within [`MAX_ALLOC`] entries; while a `save`
/// is open the old value is kept for `restore`.
fn insert(&mut self, d: &DictRef, k: Key, v: Option<Obj>) -> Res {
let old = {
let mut dm = d.borrow_mut();
if v.is_some() && dm.len() >= MAX_ALLOC && !dm.contains_key(&k) {
return Err(PsError::Limit("a dictionary grew too large"));
}
match v {
Some(v) => dm.insert(k.clone(), v),
None => dm.remove(&k),
}
};
if !self.saves.is_empty() {
self.alloc(2 * std::mem::size_of::<Obj>())?;
self.journal.push((d.clone(), k, old));
}
Ok(())
}
// ---------- resources ----------
/// The resources of `category`.
@@ -1293,16 +1348,6 @@ impl<'a> Interp<'a> {
}
}
/// Put `v` under `k` in `d`, within [`MAX_ALLOC`] entries.
fn insert(d: &DictRef, k: Key, v: Obj) -> Res {
let mut d = d.borrow_mut();
if d.len() >= MAX_ALLOC && !d.contains_key(&k) {
return Err(PsError::Limit("a dictionary grew too large"));
}
d.insert(k, v);
Ok(())
}
/// An array or string index.
fn index(k: &Obj) -> Res<usize> {
match *k {
+9 -4
View File
@@ -11,9 +11,11 @@
//! - `text`: fonts by name and type as point type; Type 3 fonts' glyphs drawn by their procedures.
//! - `preview`: the previews a file carries, for when its PostScript can't be read.
//!
//! Clipped art comes in as clipping groups. In an Illustrator file (Illustrator 3–8, written with
//! the prolog that defines its operators), the groups it writes (`u` … `U`, nested) come in as
//! groups.
//! Clipped art comes in as clipping groups. In a file in the legacy Illustrator format (versions
//! 3–8, with the prolog that defines its operators), the group operators `u` … `U` (nested) come in
//! as groups. The format's published specification documents its header comments (`%AI…`,
//! `%%Creator`) and these operators: Adobe Illustrator File Format Specification, version 7.0
//! (1998), listed by PRONOM at https://www.nationalarchives.gov.uk/PRONOM/fmt/423.
//!
//! The page is the file's `%%BoundingBox` (`%%HiResBoundingBox` when it has one), the first page
//! of a PostScript file without one. A file whose program can't be read (an operator the
@@ -39,6 +41,8 @@ mod tests_fontnames;
mod tests_generators;
#[cfg(test)]
mod tests_illustrator;
#[cfg(test)]
mod tests_images;
use std::sync::Arc;
@@ -73,7 +77,8 @@ struct Dsc {
/// `llx lly urx ury` in PostScript's default space.
bbox: Option<[f64; 4]>,
pages: Option<u32>,
/// Written by Illustrator (or in its format): `%AI…` comments, or Illustrator the creator.
/// In the legacy Illustrator format: its header has `%AI…` comments or names the app as the
/// creator (see the module docs for the specification).
illustrator: bool,
}
+87 -119
View File
@@ -42,7 +42,7 @@ fn a85_flate(data: &[u8]) -> String {
}
/// Pixel `(x, y)` (straight RGBA) of the first image in `d`.
fn pixel(d: &Document, x: u32, y: u32) -> [u8; 4] {
pub(super) fn pixel(d: &Document, x: u32, y: u32) -> [u8; 4] {
let im = all(d)
.into_iter()
.find_map(|n| match &n.kind {
@@ -592,105 +592,52 @@ showpage"##;
assert!(near(bounds(&meshes[1]), Rect::new(150.0, 90.0, 190.0, 140.0)), "{:?}", bounds(&meshes[1]));
}
/// Illustrator's EPS (CS and later, through 2026): procsets that define helpers with
/// `bdf`/`ndf`/`ddf`, probe the level and version (`{version cvr} stopped`), switch VM with
/// `currentglobal`/`setglobal`, save and restore the whole graphics state through
/// `currentcolorrendering`, `rootfont`, the colour transfers, half-tone and flatness, set up
/// categories and keep fonts by VM (`gcheck`), while the art is drawn with procedures of their own.
/// A procset written as the PostScript Language Reference (3rd ed.) describes the Level 2 and 3
/// facilities programs probe before drawing: a resource category made from `Generic` and
/// resources defined and found in it (§3.9), local and global VM (`currentglobal`, `setglobal`,
/// `gcheck`, §3.7.2), `internaldict` (§8.2), a halftone dictionary (§7.4), the font cache
/// (`cachestatus`), `rootfont` and the colour rendering dictionary (§7.1), each guarded or
/// probed through `stopped` (§3.10), saving the state they change and drawing with procedures of
/// their own.
#[test]
fn illustrator_procsets_read_as_vectors() {
fn level_2_and_3_probes_read_as_vectors() {
let program = r##"%%BeginProlog
%%BeginResource: procset Adobe_AGM_Utils 1.0 0
systemdict /setpacking known { currentpacking true setpacking } if
userdict /Adobe_AGM_Utils 75 dict dup begin put
/bdf { bind def } bind def
/nd { null def } bdf
/xdf { exch def } bdf
/ddf { put } bdf
/xddf { 3 -1 roll put } bdf
/ndf { exch dup where { pop pop pop } { xdf } ifelse } def
/gx { get exec } bdf
/ps_level /languagelevel where { pop systemdict /languagelevel gx } { 1 } ifelse def
/level2 ps_level 2 ge def
/level3 ps_level 3 ge def
/ps_version { version cvr } stopped { -1 } if def
/set_gvm { currentglobal exch setglobal } bdf
/reset_gvm { setglobal } bdf
/makereadonlyarray { /packedarray where { pop packedarray } { array astore readonly } ifelse } bdf
/GSTATE 22 dict def
/get_gstate {
GSTATE begin
/clr_spc currentcolorspace def
mark currentcolor counttomark array astore /clr_comps xdf pop
/fnt rootfont def
/lw currentlinewidth def /lc currentlinecap def /lj currentlinejoin def /ml currentmiterlimit def
currentdash /dsh_o xdf /dsh_a xdf
/sa currentstrokeadjust def
/crd currentcolorrendering def
/op currentoverprint def
/bg currentblackgeneration cvlit def
/ucr currentundercolorremoval cvlit def
currentcolortransfer cvlit /gy_x xdf cvlit /b_x xdf cvlit /g_x xdf cvlit /r_x xdf
/ht currenthalftone def
/flt currentflat def
end
} def
/set_gstate {
GSTATE begin
clr_spc setcolorspace clr_comps aload pop setcolor
fnt setfont lw setlinewidth lc setlinecap lj setlinejoin ml setmiterlimit dsh_a dsh_o setdash
sa setstrokeadjust crd setcolorrendering op setoverprint
bg cvx setblackgeneration ucr cvx setundercolorremoval
r_x cvx g_x cvx b_x cvx gy_x cvx setcolortransfer
ht /HalftoneType get dup 9 eq exch 100 eq or { ht sethalftone } if
flt setflat
end
} def
/ct_tst { 1183615869 internaldict pop } stopped pop
currentdict readonly pop
/ExampleKit 40 dict def ExampleKit begin
/defp { bind def } bind def
% A category of our own, implemented by a copy of Generic's dictionary (§3.9.2).
/Generic /Category findresource dup length dict copy /ExampleShapes exch /Category defineresource pop
/Card << /W 80 /H 50 >> /ExampleShapes defineresource pop
% VM: a dictionary made in global VM, then the VM mode put back.
/wasglobal currentglobal def true setglobal /Shared 4 dict def wasglobal setglobal
/vm Shared gcheck { (global) } { (local) } ifelse def
% Probes that fail on some interpreters, inside stopped.
/hasinternal { 1183615869 internaldict } stopped { false } { pop true } ifelse def
/screen << /HalftoneType 1 /Frequency 85 /Angle 15 /SpotFunction { 180 mul cos exch 180 mul cos add 2 div } >> def
/oldscreen currenthalftone def
/rendering currentcolorrendering def
/cache [ cachestatus ] def
/frame { /h exch def /w exch def moveto w 0 rlineto 0 h rlineto w neg 0 rlineto closepath } defp
end
systemdict /setpacking known { setpacking } if
%%EndResource
%%BeginResource: procset Adobe_AGM_Core 2.0 0
userdict /Adobe_AGM_Core 200 dict dup begin put
/AGMCORE_str256 256 string def
/AGMCORE_deviceDPI 72 0 matrix defaultmatrix dtransform dup mul exch dup mul add sqrt def
/AGMCORE_distilling /product where { pop systemdict /setdistillerparams known product (Adobe PostScript Parser) ne and } { false } ifelse def
/AGMCORE_producing_seps currentpagedevice /Separations 2 copy known { get } { pop pop false } ifelse def
/AGMCORE_page_size currentpagedevice /PageSize get def
/Generic /Category findresource dup length dict copy /Category defineresource pop
/AGMCORE_mo { moveto } def /AGMCORE_li { lineto } def /AGMCORE_cv { curveto } def /AGMCORE_cp { closepath } def
/AGMCORE_rgb { setrgbcolor } def /AGMCORE_cmyk { setcmykcolor } def
/doc_setup { Adobe_AGM_Utils begin get_gstate end } def
/page_setup { Adobe_AGM_Utils begin set_gstate end } def
end
%%EndResource
%%BeginResource: procset Adobe_CoolType_Core 2.31 0
userdict /CT_Core 20 dict dup begin put
/GVMFonts 10 dict def /LVMFonts 10 dict def
/VMDictPut { dup gcheck { GVMFonts } { LVMFonts } ifelse 3 1 roll put } bind def
/copyfont { currentglobal exch dup gcheck setglobal dup length dict copy exch setglobal } bind def
end
%%EndResource
%%EndProlog
%%BeginSetup
Adobe_AGM_Core /doc_setup get exec
CT_Core begin /Body /Helvetica findfont copyfont VMDictPut end
ExampleKit begin
screen sethalftone
/Helvetica 12 selectfont
/face rootfont /FontName get def
%%EndSetup
%%Page: 1 1
%%BeginPageSetup
Adobe_AGM_Core /page_setup get exec
%%EndPageSetup
Adobe_AGM_Core begin
/mo { AGMCORE_mo } def /li { AGMCORE_li } def /cv { AGMCORE_cv } def /cp { AGMCORE_cp } def
0 0.94 0.94 0.12 AGMCORE_cmyk
10 140 mo 90 140 li 90 90 li 10 90 li cp fill
0.2 0.4 0.8 AGMCORE_rgb
100 20 mo 150 80 180 0 190 60 cv 2 setlinewidth stroke
0 setgray CT_Core /LVMFonts get /Body get 12 scalefont setfont 10 30 moveto (Art) show
gsave
0 0.94 0.94 0.12 setcmykcolor
10 90 /Card /ExampleShapes findresource dup /W get exch /H get frame fill
0.2 0.4 0.8 setrgbcolor 2 setlinewidth 100 20 moveto 150 80 180 0 190 60 curveto stroke
grestore
% Each probe answered as the reference says: draw only when it did.
vm length 5 eq hasinternal and rendering type /dicttype eq and cache length 7 eq and face /Helvetica eq and
{ 0 setgray 10 30 moveto (Art) show } if
oldscreen sethalftone
end
showpage"##;
let r = open("Adobe Illustrator(R) 30.0", program);
let r = open("Example Generator 1.0", program);
let d = &r.document;
let rect = all(d).into_iter().find(|n| fill(n).and_then(Paint::color) == Some(Color::cmyk(0.0, 0.94, 0.94, 0.12))).unwrap();
assert!(near(bounds(&rect), Rect::new(10.0, 10.0, 90.0, 60.0)), "{:?}", bounds(&rect));
@@ -950,44 +897,65 @@ fn hostile_patterns_glyphs_and_shadings_end() {
assert_eq!(objects(&r.document).len(), 1);
}
/// Illustrator 8 EPS (what stock art often comes as, #474): its gradient procset builds shading
/// dictionaries with `bd` … `ed`, where `ed` is an executable string (`(>>) cvx`, or a Level 1
/// dictionary builder), and its `discard` runs procedures it `load`s by integer keys.
/// Executable strings and keys other than names (#474): `cvx` makes a string executable, and
/// running it runs its text (PLRM 3rd ed. §3.3.1, `cvx`, `exec`); `load` takes any key (§8.2).
/// A program closes its shading dictionaries with an executable string (`>>` at Level 2 and up,
/// else a dictionary built with `counttomark`), and runs procedures it keeps under integer keys
/// through `stopped`.
#[test]
fn illustrator_8_gradients_and_executable_strings() {
fn executable_strings_and_integer_keys() {
let program = r##"%%BeginProlog
userdict /AGM_Gradient 20 dict dup begin put
/AGM_Gradient_private 201 dict def
/initialize {
AGM_Gradient begin AGM_Gradient_private begin
/bd systemdict /mark get def
/ed /languagelevel where { pop languagelevel 2 ge } { false } ifelse
{ (>>) } { (counttomark 2 idiv dup dict begin {def} repeat pop currentdict end) } ifelse cvx def
/ed1 (counttomark 2 idiv dup dict begin {def} repeat pop currentdict end) cvx def
end end
} def
userdict /discardDict 4 dict dup begin put
0 { 0 1 0 setrgbcolor } def
2 { 0 0 1 setrgbcolor } def
/ShadeKit 12 dict def ShadeKit begin
% A Level 1 way to make a dictionary of the pairs above a mark.
/pairs (counttomark 2 idiv dict begin { counttomark 0 eq { exit } if def } loop pop currentdict end) cvx def
/close /languagelevel where { pop languagelevel 2 ge } { false } ifelse { (>>) } { (pairs) } ifelse cvx def
/open /mark load def
/actions 3 dict def actions begin 0 { 0 1 0 setrgbcolor } def 1 { 1 0 0 setrgbcolor } def end
/act { actions 1 index known { actions begin load end stopped pop } { pop } ifelse } bind def
end
/gt38? false def
/discard { discardDict begin /endString exch def gt38? { 2 add } if load stopped pop end } bind def
%%EndProlog
initialize
AGM_Gradient begin AGM_Gradient_private begin
bd /ShadingType 3 /ColorSpace /DeviceRGB
/Function bd /FunctionType 2 /Domain [0 1] /C0 [1 1 0] /C1 [0 0.5 0] /N 1 ed
/Extend [true true] /Coords [50 50 0 50 50 40] ed
ShadeKit begin
open /ShadingType 3 /ColorSpace /DeviceRGB
/Function open /FunctionType 2 /Domain [0 1] /C0 [1 1 0] /C1 [0 0.5 0] /N 1 close
/Extend [true true] /Coords [50 50 0 50 50 40] close
gsave 10 10 80 80 rectclip shfill grestore
bd /Width 3 ed1 /Width get 3 eq { 0 (%AI5_EndPalette) discard 10 10 20 20 rectfill } if
end end
mark /Width 3 pairs /Width get 3 eq { 0 act 10 10 20 20 rectfill } if
2 act
end
(x) cvx xcheck (x) cvx cvlit xcheck not and { 50 50 10 10 rectfill } if
showpage"##;
let r = open("Adobe Illustrator(R) 8.0", program);
let r = open("Example Generator 1.0", program);
let d = &r.document;
let Some(Paint::Gradient(g)) = all(d).into_iter().find_map(|n| fill(&n).cloned()) else { panic!("no gradient") };
assert_eq!(g.gradient.kind, vectorcraft_color::GradientKind::Radial);
// `discard` ran the procedure under key 0 (green), not the one under 2.
// `act` ran the procedure under key 0 (green); there is none under key 2.
assert!(all(d).iter().any(|n| fill(n).and_then(Paint::color) == Some(Color::rgb(0.0, 1.0, 0.0))));
assert_eq!(objects(d).len(), 3);
}
/// `restore` puts local VM back as it was at the `save` (PLRM 3rd ed., §3.7.3 "Save and
/// Restore"): dictionaries get back the entries they had, whatever changed them. A program that
/// keeps a count of the saves it has open in a dictionary, and refuses to go past a depth, reads
/// to its end only if each `restore` puts the count back (part of #505: files with many images,
/// each drawn between `save` and `restore`).
#[test]
fn restore_puts_dictionaries_back() {
let r = read(
"/Depth 2 dict def Depth /open 0 put \
/enter { save Depth /open get 1 add dup 8 gt { rangecheck } if Depth exch /open exch put } def \
1 1 100 { pop enter 0 0 1 1 rectfill restore } for Depth /open get 0 eq { 10 10 5 5 rectfill } if",
);
clean(&r);
assert_eq!(objects(&r.document).len(), 101);
// `def`, `store`, `put`, `undef` and dictionary `copy` are undone, newest first.
super::tests::check(
"/a 1 def /d 2 dict def d /k 1 put save /a 2 def /b 3 def d /k 2 put d /k undef 1 dict dup /z 9 put d copy pop \
/a 4 store restore a 1 eq /b where not and d /k get 1 eq and d /z known not and",
);
// A save restored (itself, or through an outer one) is no longer valid: `invalidrestore`.
super::tests::check("save dup restore { restore } stopped");
super::tests::check("save save exch restore { restore } stopped");
// `cachestatus` gives a device's cache sizes; its last, the most bytes one cached glyph may
// take, is positive (chapter 8), and programs divide by it.
super::tests::check("cachestatus 7 1 roll 6 { pop } repeat 0 gt");
}
@@ -20,6 +20,9 @@ fn ai(header: &str, ugroup: &str, body: &str) -> Vec<u8> {
.into_bytes()
}
/// A legacy Illustrator format header: the reader takes `u` … `U` as groups only in files whose
/// header says they are in that format (`%AI…` comments or the creator, which the format's
/// published specification documents; see the `import` module docs).
const AI8: &str = "%%Creator: Adobe Illustrator(R) 8.0\n%AI5_FileFormat 4.0\n";
/// A triangle filled at `x`.
+130
View File
@@ -0,0 +1,130 @@
//! Image data read as the PostScript Language Reference (3rd ed.) defines it: several data sources
//! read in turn (§4.10 "Images", `image` and `colorimage` in chapter 8), rows padded to a whole
//! byte at every bit depth and odd widths (§4.10), and Flate predictors undone row by row (§3.13,
//! `FlateDecode` parameters) (#498).
use super::tests::read;
use super::tests_generators::pixel;
/// Each pixel of the first image, row by row.
fn pixels(r: &crate::Imported, w: u32, h: u32) -> Vec<[u8; 4]> {
assert!(!r.preview && r.warnings.is_empty(), "{:?}", r.warnings);
(0..h).flat_map(|y| (0..w).map(move |x| (x, y))).map(|(x, y)| pixel(&r.document, x, y)).collect()
}
/// A CMYK image whose four data sources are procedures reading one file, a row of one ink each:
/// the image operator calls them in turn, so each gets its own rows. Read one after the other,
/// the cyan source took the first four rows of all four inks and the image came out in
/// horizontal bands (#498).
#[test]
fn procedures_reading_one_file_are_read_in_turn() {
// 3 × 2 pixels; rows: C M Y K of row 0, then of row 1.
let rows = ["ff0000", "00ff00", "000000", "000000", "000000", "000000", "ffff00", "0000ff"];
let r = read(&format!(
"/DeviceCMYK setcolorspace 30 20 scale /f currentfile /ASCIIHexDecode filter def \
<< /ImageType 1 /Width 3 /Height 2 /BitsPerComponent 8 /Decode [0 1 0 1 0 1 0 1] /ImageMatrix [3 0 0 -2 0 2] \
/MultipleDataSources true /DataSource [ {{f 3 string readstring pop}} {{f 3 string readstring pop}} \
{{f 3 string readstring pop}} {{f 3 string readstring pop}} ] >> image\n{}>",
rows.concat()
));
let cyan = [0, 174, 239, 255];
let magenta = [236, 0, 140, 255];
let yellow = [255, 242, 0, 255];
let black = [35, 31, 32, 255];
let white = [255, 255, 255, 255];
let px = pixels(&r, 3, 2);
let near = |a: [u8; 4], b: [u8; 4]| a.iter().zip(b).all(|(x, y)| x.abs_diff(y) <= 40);
let want = [cyan, magenta, white, yellow, yellow, black];
assert!(px.iter().zip(want).all(|(a, b)| near(*a, b)), "{px:?}");
// The operand form: `{r} {g} {b} true 3 colorimage`, procedures reading one file.
let r = read(
"30 20 scale /f currentfile /ASCIIHexDecode filter def \
3 2 8 [3 0 0 -2 0 2] {f 3 string readstring pop} {f 3 string readstring pop} {f 3 string readstring pop} true 3 colorimage\n\
ff0000 00ff00 0000ff 102030 405060 708090>",
);
assert_eq!(pixels(&r, 3, 2), [[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255], [16, 64, 112, 255], [32, 80, 128, 255], [48, 96, 144, 255]]);
}
/// Separate strings and files as the sources: each is read for its own plane, whatever the row.
#[test]
fn separate_sources_keep_their_planes() {
let r = read("30 20 scale 3 2 8 [3 0 0 -2 0 2] <ff0000102030> <00ff00405060> <0000ff708090> true 3 colorimage");
assert_eq!(pixels(&r, 3, 2), [[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255], [16, 64, 112, 255], [32, 80, 128, 255], [48, 96, 144, 255]]);
}
/// Rows of an odd width at 1, 2, 4, 12 and 16 bits a sample start at a byte (their last byte
/// padded), in one source and in several.
#[test]
fn rows_of_every_depth_start_at_a_byte() {
// 3 pixels a row, two rows: 0, max, mid / max, 0, 0 (grey), each row padded.
let cases = [
(1, "a0 80"), // 101(00000) 100(00000)
(2, "cc c0"), // 11 00 11 (00), 11 00 00 (00)
(4, "f0 80 f0 00"), // f 0 8 (0), f 0 0 (0)
(12, "fff0008000 fff0000000"), // fff 000 800 (0), fff 000 000 (0)
(16, "ffff00008000 ffff00000000"),
];
for (bpc, data) in cases {
let data = data.replace(' ', "");
let r = read(&format!("30 20 scale 3 2 {bpc} [3 0 0 -2 0 2] <{data}> image"));
let px: Vec<u8> = pixels(&r, 3, 2).iter().map(|p| p[0]).collect();
let want: &[u8] = match bpc {
1 => &[255, 0, 255, 255, 0, 0],
2 => &[255, 0, 255, 255, 0, 0],
4 => &[255, 0, 136, 255, 0, 0],
12 => &[255, 0, 128, 255, 0, 0],
_ => &[255, 0, 128, 255, 0, 0],
};
assert_eq!(px, want, "{bpc} bits");
}
// Several 4-bit sources, odd width: each plane's rows padded on their own.
let r = read("30 20 scale 3 2 4 [3 0 0 -2 0 2] <f0f000f0> <0f00f000> <00f00ff0> true 3 colorimage");
let (on, off) = (255, 0);
let want = [[on, off, off], [off, on, off], [on, off, on], [off, on, off], [off, off, on], [on, off, on]];
assert_eq!(pixels(&r, 3, 2), want.map(|[r, g, b]| [r, g, b, 255]));
}
/// A PNG-predicted Flate image of an odd width: every row filter (None, Sub, Up, Average, Paeth)
/// undone on its own row.
#[test]
fn predicted_rows_of_an_odd_width() {
// 3 RGB pixels a row, five rows; each row predicted with its own filter.
let raw: Vec<[u8; 9]> = (0..5u8).map(|y| std::array::from_fn(|i| (i as u8).wrapping_mul(29).wrapping_add(y.wrapping_mul(53)))).collect();
let mut encoded = vec![];
let mut prev = [0u8; 9];
for (kind, row) in raw.iter().enumerate() {
encoded.push(kind as u8);
for i in 0..9 {
let a = if i >= 3 { row[i - 3] } else { 0 };
let b = prev[i];
let c = if i >= 3 { prev[i - 3] } else { 0 };
let pred = match kind {
1 => a,
2 => b,
3 => ((u16::from(a) + u16::from(b)) / 2) as u8,
4 => {
let p = i16::from(a) + i16::from(b) - i16::from(c);
let (pa, pb, pc) = ((p - i16::from(a)).abs(), (p - i16::from(b)).abs(), (p - i16::from(c)).abs());
if pa <= pb && pa <= pc {
a
} else if pb <= pc {
b
} else {
c
}
}
_ => 0,
};
encoded.push(row[i].wrapping_sub(pred));
}
prev = *row;
}
let r = read(&format!(
"/DeviceRGB setcolorspace 30 50 scale << /ImageType 1 /Width 3 /Height 5 /BitsPerComponent 8 /Decode [0 1 0 1 0 1] /ImageMatrix [3 0 0 -5 0 5] \
/DataSource currentfile /ASCII85Decode filter << /Predictor 15 /Colors 3 /Columns 3 >> /FlateDecode filter >> image\n{}",
crate::ps::ascii85(&crate::ps::deflate(&encoded))
));
let want: Vec<[u8; 4]> = raw.iter().flat_map(|row| (0..3).map(move |x| [row[3 * x], row[3 * x + 1], row[3 * x + 2], 255])).collect();
assert_eq!(pixels(&r, 3, 5), want);
}
+1 -1
View File
@@ -291,7 +291,7 @@ impl<'a> Scene<'a> {
}
}
// Live blends, envelopes, meshes and repeats are written as their evaluated art.
NodeKind::Blend { .. } | NodeKind::Envelope { .. } | NodeKind::Mesh(_) | NodeKind::Repeat(_) => {
NodeKind::Blend { .. } | NodeKind::Envelope { .. } | NodeKind::Mesh(_) | NodeKind::Repeat(_) | NodeKind::PlacedDocument(_) => {
let g = vectorcraft_effects::expand_live_deep(Some(self.doc), n);
for c in g.children().into_iter().flatten() {
self.node(c, false);
+100 -17
View File
@@ -23,7 +23,10 @@
//! Versions: v1 wrote anchors as `{p: {x, y}, in: {x, y}, out: {x, y}, kind}`; v2 as
//! `{p: [x, y], in?, out?, kind?}` with default-valued fields left out; v3 keeps the assigned colour
//! profiles in `document.color_profiles` (before: `document.unknown.colorProfiles`) and may be
//! compressed. Every version loads, and [`save_with`] writes any of them for older apps (under the
//! compressed; v4 may keep large data (images, placed documents, the PDF, profiles of at least
//! [`INLINE_MAX`] bytes) after the JSON instead of in it: the JSON is followed by [`BLOB_MAGIC`] and
//! the bytes, and such an entry says where they are (`"blob": [offset, length]`) instead of giving
//! `data`. Every version loads, and [`save_with`] writes any of them for older apps (under the
//! format name `drawcraft`, which every version reads). Readers reject files whose `version` is
//! newer than they support.
#![forbid(unsafe_code)]
@@ -42,8 +45,12 @@ use vectorcraft_doc::{Document, ImageBlob};
#[cfg(not(target_arch = "wasm32"))]
pub use atomic::{write_atomic, write_atomic_with};
/// v3: colour profiles as a document field, optional compression and preview (v1 and v2 files still load).
pub const VERSION: u32 = 3;
/// v4: large data after the JSON (v1 to v3 files still load).
pub const VERSION: u32 = 4;
/// Data this large or larger goes after the JSON (v4), not into it as base64.
pub const INLINE_MAX: usize = 8 << 10;
/// What separates the JSON from the data after it (v4).
pub const BLOB_MAGIC: &[u8] = b"\n\0VCBLOBS\0";
/// The oldest version [`save_with`] writes.
pub const MIN_VERSION: u32 = 1;
/// The first version whose readers open compressed files.
@@ -87,12 +94,69 @@ pub enum FormatError {
#[derive(Serialize, Deserialize)]
struct Image {
mime: String,
/// The bytes as base64, unless they come after the JSON (`blob`).
#[serde(default, skip_serializing_if = "String::is_empty")]
data: String,
/// Where the bytes are in the data after the JSON (v4): `[offset, length]`.
#[serde(default, skip_serializing_if = "Option::is_none")]
blob: Option<[u64; 2]>,
/// `data` is a linked image's preview ([`ImageBlob::proxy`]), not the file's bytes.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
proxy: bool,
}
impl Image {
/// Its bytes: the base64 `data`, or its part of `tail` (the data after the JSON).
fn bytes(&self, tail: &[u8]) -> Option<Vec<u8>> {
match self.blob {
Some([offset, len]) => {
let start = usize::try_from(offset).ok()?;
let end = start.checked_add(usize::try_from(len).ok()?)?;
tail.get(start..end).map(<[u8]>::to_vec)
}
None => base64_decode(&self.data),
}
}
}
/// Entries written for one file: large bytes go to the data after the JSON when the version keeps
/// them there.
struct Blobs {
tail: Vec<u8>,
outside: bool,
}
impl Blobs {
fn image(&mut self, mime: &str, bytes: &[u8], proxy: bool) -> Image {
if self.outside && bytes.len() >= INLINE_MAX {
let at = self.tail.len() as u64;
self.tail.extend_from_slice(bytes);
return Image { mime: mime.into(), data: String::new(), blob: Some([at, bytes.len() as u64]), proxy };
}
Image { mime: mime.into(), data: base64_encode(bytes), blob: None, proxy }
}
}
/// The MIME type of a preview's bytes (JPEG or PNG).
fn preview_mime(bytes: &[u8]) -> &'static str {
if bytes.starts_with(&[0xff, 0xd8]) { "image/jpeg" } else { vectorcraft_doc::links::PROXY_MIME }
}
/// The JSON of a file and the data after it (v4), split at [`BLOB_MAGIC`] after the first JSON
/// value.
fn split_tail(text: &[u8]) -> (&[u8], &[u8]) {
let mut values = serde_json::Deserializer::from_slice(text).into_iter::<serde::de::IgnoredAny>();
if values.next().is_some_and(|v| v.is_ok()) {
let end = values.byte_offset();
if let Some(rest) = text.get(end..)
&& rest.starts_with(BLOB_MAGIC)
{
return (text.get(..end).unwrap_or(text), rest.get(BLOB_MAGIC.len()..).unwrap_or_default());
}
}
(text, &[])
}
#[derive(Deserialize)]
struct File {
format: String,
@@ -173,6 +237,14 @@ pub fn save_with(doc: &Document, o: &SaveOptions) -> Result<Vec<u8>, FormatError
o.check()?;
let pretty = o.pretty && !o.compress;
let mut d = doc.without_edit_modes().into_owned();
// Older apps don't know placed documents: they get the art the objects show, with its
// resources. Otherwise resources only exporting adds are never saved.
if o.version < VERSION && d.has_placed() {
d = d.with_placed_art().into_owned();
d.placed_as_groups();
} else {
d.drop_placed_resources();
}
let linked = d.linked_only_images();
// The blobs go in the file's `images` (only those the document uses).
let blobs = std::mem::take(&mut d.images);
@@ -189,6 +261,7 @@ pub fn save_with(doc: &Document, o: &SaveOptions) -> Result<Vec<u8>, FormatError
// Images are only referenced by image objects' `key` (wherever the objects are: layers,
// symbols, patterns, masks, or foreign data).
let used = if blobs.is_empty() { HashSet::new() } else { string_members(&body, "key") };
let mut out_blobs = Blobs { tail: vec![], outside: o.version >= 4 };
let images: BTreeMap<&str, Image> = blobs
.iter()
.filter(|(k, _)| used.contains(k.as_str()))
@@ -196,20 +269,20 @@ pub fn save_with(doc: &Document, o: &SaveOptions) -> Result<Vec<u8>, FormatError
// Include Linked Files keeps the file's bytes whenever they are loaded.
let preview_only = linked.contains(k) && (!o.include_linked || b.is_proxy());
let image = match b.proxy.as_ref().filter(|_| preview_only) {
Some(p) => Image { mime: vectorcraft_doc::links::PROXY_MIME.into(), data: base64_encode(p), proxy: true },
None => Image { mime: b.mime.clone(), data: base64_encode(&b.bytes), proxy: false },
Some(p) => out_blobs.image(preview_mime(p), p, true),
None => out_blobs.image(&b.mime, &b.bytes, false),
};
(k.as_str(), image)
})
.collect();
let blob = |mime: &str, bytes: &[u8]| Image { mime: mime.into(), data: base64_encode(bytes), proxy: false };
let profiles: BTreeMap<&str, Image> = o.profiles.iter().map(|(name, icc)| (name.as_str(), blob(ICC_MIME, icc))).collect();
let pdf = o.pdf.as_deref().map(|p| blob("application/pdf", p));
let profiles: BTreeMap<&str, Image> = o.profiles.iter().map(|(name, icc)| (name.as_str(), out_blobs.image(ICC_MIME, icc, false))).collect();
let pdf = o.pdf.as_deref().map(|p| out_blobs.image("application/pdf", p, false));
let blob = |mime: &str, bytes: &[u8]| Image { mime: mime.into(), data: base64_encode(bytes), blob: None, proxy: false };
let carried = profiles.values().chain(&pdf).map(|i| i.data.len()).sum::<usize>();
let size = body.len() + images.values().map(|i| i.data.len()).sum::<usize>() + carried + 256;
let mut w = Envelope { out: Vec::with_capacity(size), pretty };
// Older apps only know the name from before the rename.
w.field("format", &if o.version < VERSION { LEGACY_EXTENSION } else { EXTENSION })?;
w.field("format", &if o.version < 3 { LEGACY_EXTENSION } else { EXTENSION })?;
w.field("version", &o.version)?;
w.field("generator", &format!("VectorCraft {}", env!("CARGO_PKG_VERSION")))?;
if let Some(png) = &o.preview {
@@ -223,7 +296,11 @@ pub fn save_with(doc: &Document, o: &SaveOptions) -> Result<Vec<u8>, FormatError
}
w.raw("document", &body);
w.field("images", &images)?;
let out = w.finish();
let mut out = w.finish();
if !out_blobs.tail.is_empty() {
out.extend_from_slice(BLOB_MAGIC);
out.extend_from_slice(&out_blobs.tail);
}
if !o.compress {
return Ok(out);
}
@@ -356,7 +433,8 @@ pub fn load_info(bytes: &[u8]) -> Result<(Document, FileInfo), FormatError> {
/// [`load`], with everything else the file carries.
pub fn load_file(bytes: &[u8]) -> Result<NativeFile, FormatError> {
let text = unpack(bytes)?;
let f: File = serde_json::from_slice(&text).map_err(|e| FormatError::NotVectorcraft(e.to_string()))?;
let (json, tail) = split_tail(&text);
let f: File = serde_json::from_slice(json).map_err(|e| FormatError::NotVectorcraft(e.to_string()))?;
if f.format != EXTENSION && f.format != LEGACY_EXTENSION {
return Err(FormatError::NotVectorcraft(format!("format is `{}`", f.format)));
}
@@ -365,7 +443,7 @@ pub fn load_file(bytes: &[u8]) -> Result<NativeFile, FormatError> {
}
let mut doc = f.document;
for (k, img) in f.images {
let bytes = base64_decode(&img.data).ok_or_else(|| FormatError::BadImage(k.clone()))?;
let bytes = img.bytes(tail).ok_or_else(|| FormatError::BadImage(k.clone()))?;
let mut blob = ImageBlob::new(img.mime, bytes);
// Until the linked file is read, the preview stands in for it.
if img.proxy {
@@ -382,7 +460,7 @@ pub fn load_file(bytes: &[u8]) -> Result<NativeFile, FormatError> {
doc.fix_next_id();
// Untrusted: capped, named and pointing at objects the file has.
doc.tidy_saved_selections();
let profiles = f.profiles.into_iter().filter_map(|(name, icc)| Some((name, base64_decode(&icc.data)?))).collect();
let profiles = f.profiles.into_iter().filter_map(|(name, icc)| Some((name, icc.bytes(tail)?))).collect();
Ok(NativeFile { doc, info: FileInfo { version: f.version, legacy: f.format == LEGACY_EXTENSION }, profiles })
}
@@ -393,19 +471,24 @@ struct Head {
pdf: Option<Image>,
}
fn head(bytes: &[u8]) -> Option<Head> {
serde_json::from_slice(&unpack(bytes).ok()?).ok()
/// The file's head and the data after its JSON.
fn head(bytes: &[u8]) -> Option<(Head, Vec<u8>)> {
let text = unpack(bytes).ok()?;
let (json, tail) = split_tail(&text);
Some((serde_json::from_slice(json).ok()?, tail.to_vec()))
}
/// The preview PNG embedded in a native file (`None`: it has none, or isn't a native file).
pub fn preview(bytes: &[u8]) -> Option<Vec<u8>> {
base64_decode(&head(bytes)?.preview?.data)
let (h, tail) = head(bytes)?;
h.preview?.bytes(&tail)
}
/// The PDF a native file saved with Create PDF-Compatible File carries (`None`: it has none, or
/// isn't a native file).
pub fn pdf_content(bytes: &[u8]) -> Option<Vec<u8>> {
base64_decode(&head(bytes)?.pdf?.data)
let (h, tail) = head(bytes)?;
h.pdf?.bytes(&tail)
}
/// Does this look like a `.vectorcraft` file (compressed or not)?
+1 -1
View File
@@ -55,7 +55,7 @@ fn compressed_files_load() {
assert!(!flate2_unpack(&packed).contains(&b'\n'));
// A legacy (v2, pre-rename) file compressed by hand opens too.
let text = String::from_utf8(plain.clone()).unwrap();
let legacy = text.replacen("\"format\":\"vectorcraft\",\"version\":3", "\"format\":\"drawcraft\",\"version\":2", 1);
let legacy = text.replacen(&format!("\"format\":\"vectorcraft\",\"version\":{VERSION}"), "\"format\":\"drawcraft\",\"version\":2", 1);
assert_ne!(legacy, text);
let legacy = gzip(legacy.as_bytes());
assert!(sniff(&legacy));
+78
View File
@@ -0,0 +1,78 @@
//! `.vectorcraft` v4: large data after the JSON (images, the PDF, profiles), small files still plain
//! JSON, older versions inline, damaged offsets refused.
// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness).
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::sync::Arc;
use serde_json::Value;
use vectorcraft_doc::{Document, ImageBlob, ImageObject, Node, NodeKind};
use vectorcraft_format::{BLOB_MAGIC, FormatError, INLINE_MAX, SaveOptions, load, load_file, pdf_content, save_with};
use vectorcraft_geom::Affine;
/// A document showing image `key` of `len` bytes.
fn doc_with_image(key: &str, len: usize) -> Document {
let mut d = Document::new(100.0, 100.0);
let bytes: Vec<u8> = (0..len).map(|i| (i * 7 % 251) as u8).collect();
d.images.insert(key.into(), ImageBlob::new("image/png", bytes));
let l = d.layers[0].id;
let id = d.alloc_id();
let im = ImageObject { key: key.into(), width: 10, height: 10, xf: Affine::IDENTITY, link: None, placement: Default::default() };
d.insert(Some(l), 0, Node::new(id, NodeKind::Image(im))).unwrap();
d
}
fn has_tail(bytes: &[u8]) -> bool {
bytes.windows(BLOB_MAGIC.len()).any(|w| w == BLOB_MAGIC)
}
#[test]
fn large_data_goes_after_the_json_and_reads_back() {
let d = doc_with_image("big", INLINE_MAX + 10);
let pdf = vec![b'%'; INLINE_MAX * 2];
for compress in [false, true] {
let o = SaveOptions { compress, pdf: Some(pdf.clone()), ..SaveOptions::default() };
let bytes = save_with(&d, &o).unwrap();
if !compress {
assert!(has_tail(&bytes), "a binary section");
// The JSON before it holds no base64 copy of the image.
assert!(bytes.len() < INLINE_MAX + 10 + pdf.len() + (32 << 10), "{} bytes", bytes.len());
}
let back = load(&bytes).unwrap();
assert_eq!(back.images["big"].bytes, d.images["big"].bytes, "compress {compress}");
assert_eq!(pdf_content(&bytes).unwrap(), pdf);
}
}
#[test]
fn small_files_stay_plain_json_and_older_versions_inline() {
let small = save_with(&doc_with_image("small", 100), &SaveOptions::default()).unwrap();
assert!(!has_tail(&small));
let v: Value = serde_json::from_slice(&small).unwrap();
assert_eq!(v["version"], 4);
let big = doc_with_image("big", INLINE_MAX + 10);
let v3 = save_with(&big, &SaveOptions { version: 3, ..SaveOptions::default() }).unwrap();
assert!(!has_tail(&v3), "version 3 keeps everything in the JSON");
let v: Value = serde_json::from_slice(&v3).unwrap();
assert_eq!((v["format"].as_str(), v["version"].as_u64()), (Some("vectorcraft"), Some(3)));
assert_eq!(load(&v3).unwrap().images["big"].bytes, big.images["big"].bytes);
}
#[test]
fn damaged_offsets_are_refused_not_a_crash() {
let d = doc_with_image("big", INLINE_MAX + 10);
let bytes = save_with(&d, &SaveOptions::default()).unwrap();
// The data cut short.
let cut = &bytes[..bytes.len() - 100];
assert!(matches!(load_file(cut), Err(FormatError::BadImage(_))));
// An offset past the end.
let text = String::from_utf8_lossy(&bytes);
let at = text.find("\"blob\":[").unwrap();
let mut damaged = bytes.clone();
damaged.splice(at..at + 8, b"\"blob\":[9".iter().copied());
assert!(load_file(&damaged).is_err());
// A missing section.
let json_only = &bytes[..bytes.windows(BLOB_MAGIC.len()).position(|w| w == BLOB_MAGIC).unwrap()];
assert!(load_file(json_only).is_err());
let _ = Arc::new(());
}
+283
View File
@@ -0,0 +1,283 @@
//! Live Corners on any path: the anchors where two straight sides meet at an angle, and the path
//! with those corners cut round, inverted round or chamfered. Rectangles cut theirs the same way.
use kurbo::{Point, Vec2};
use crate::path::{Anchor, AnchorKind, PathData, SubPath};
use crate::shapes::{CornerKind, KAPPA};
/// Lengths and radii at or below this are none at all.
const EPS: f64 = 1e-9;
/// Sides closer than this to straight on (or folded back), as the sine of their angle, make no corner.
const MIN_SINE: f64 = 1e-6;
/// A corner Live Corners can cut: an anchor without handles between two straight sides that
/// meet at an angle.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Corner {
/// The anchor's index in its path, counting the anchors of every subpath in order.
pub index: usize,
/// Where the sides meet.
pub at: Point,
/// Unit directions along the sides: towards the previous anchor, then towards the next one.
pub u: Vec2,
pub v: Vec2,
/// The sides' lengths, in the same order.
pub lu: f64,
pub lv: f64,
}
impl Corner {
/// The corner of anchor `i` of `sp`, whose index in the path is `index`; `None` when the
/// anchor is an end of an open subpath, has handles or is smooth, when a side curves or has
/// no length, or when the sides run straight on.
fn of(sp: &SubPath, i: usize, index: usize) -> Option<Self> {
let n = sp.anchors.len();
let (prev, next) = if sp.closed { ((i + n).checked_sub(1)? % n, (i + 1) % n) } else { (i.checked_sub(1)?, i + 1) };
let (a, prev, next) = (sp.anchors.get(i)?, sp.anchors.get(prev)?, sp.anchors.get(next)?);
if a.kind == AnchorKind::Smooth || a.has_in() || a.has_out() || prev.has_out() || next.has_in() {
return None;
}
let (du, dv) = (prev.p - a.p, next.p - a.p);
let (lu, lv) = (du.hypot(), dv.hypot());
if !(lu > EPS && lv > EPS && lu.is_finite() && lv.is_finite()) {
return None;
}
let c = Self { index, at: a.p, u: du / lu, v: dv / lv, lu, lv };
(c.sin() > MIN_SINE).then_some(c)
}
/// The cosine of the angle between the sides.
pub fn cos(&self) -> f64 {
self.u.dot(self.v)
}
/// The sine of the angle between the sides.
pub fn sin(&self) -> f64 {
self.u.cross(self.v).abs()
}
/// The angle between the sides, in degrees (90 at a rectangle's corners).
pub fn angle_deg(&self) -> f64 {
self.sin().atan2(self.cos()).to_degrees()
}
/// How far from the corner a round cut of radius `r` meets each side: r / tan(angle / 2).
pub fn setback(&self, r: f64) -> f64 {
r * (1.0 + self.cos()) / self.sin()
}
/// The largest radius the corner draws: its cut then reaches halfway along the shorter side,
/// so neighbouring corners at their largest meet without overlapping (half the shorter side
/// at a rectangle's corners).
pub fn max_radius(&self) -> f64 {
self.lu.min(self.lv) / 2.0 * self.sin() / (1.0 + self.cos())
}
/// The radius the corner is drawn with: `radius`, no larger than [`Corner::max_radius`], 0 when
/// negative or not a number.
pub fn fitted(&self, radius: f64) -> f64 {
radius.max(0.0).min(self.max_radius())
}
/// The point `k` along the bisector, measured in (u + v): the centre of a round cut of radius
/// `r` is at `k = r / sin`.
pub fn on_bisector(&self, k: f64) -> Point {
self.at + (self.u + self.v) * k
}
/// How much the radius grows when the centre of the round cut moves by `d`: `d`'s part along
/// the bisector, in radius units.
pub fn radius_change(&self, d: Vec2) -> f64 {
d.dot(self.u + self.v) * self.sin() / (2.0 + 2.0 * self.cos())
}
/// The two anchors replacing the corner when cut with `radius` (> 0, fitted): where the cut
/// meets the arriving side, then the leaving one.
fn cut(&self, radius: f64, kind: CornerKind) -> [Anchor; 2] {
let t = self.setback(radius);
let (start, end) = (self.at + self.u * t, self.at + self.v * t);
let (h_out, h_in) = match kind {
// An arc of `radius` tangent to both sides, turning by 180° less the angle.
CornerKind::Round => {
let h = radius * arc_handle(-self.cos());
(start - self.u * h, end - self.v * h)
}
// An arc centred on the corner through both ends, spanning the angle.
CornerKind::InvertedRound => {
let h = t * arc_handle(self.cos());
(start + square_to(self.u, self.v) * h, end + square_to(self.v, self.u) * h)
}
CornerKind::Chamfer => (start, end),
};
[Anchor { p: start, h_in: start, h_out, kind: AnchorKind::Corner }, Anchor { p: end, h_in, h_out: end, kind: AnchorKind::Corner }]
}
}
/// The unit direction square to unit `a`, on `b`'s side.
fn square_to(a: Vec2, b: Vec2) -> Vec2 {
let w = b - a * a.dot(b);
w / w.hypot()
}
/// The handle length, per unit of radius, of a cubic drawing a circular arc that spans an angle
/// whose cosine is `cos`: 4/3 · tan(angle / 4) ([`KAPPA`] for a quarter circle).
fn arc_handle(cos: f64) -> f64 {
if cos.abs() < 1e-12 {
return KAPPA;
}
let (sin_half, cos_half) = (((1.0 - cos) / 2.0).max(0.0).sqrt(), ((1.0 + cos) / 2.0).max(0.0).sqrt());
4.0 / 3.0 * sin_half / (1.0 + cos_half)
}
/// The corners of `path` Live Corners can cut, in anchor order.
pub fn path_corners(path: &PathData) -> Vec<Corner> {
let mut out = vec![];
let mut first = 0;
for sp in &path.subpaths {
out.extend((0..sp.anchors.len()).filter_map(|i| Corner::of(sp, i, first + i)));
first += sp.anchors.len();
}
out
}
/// `path` with each of its corners ([`path_corners`]) cut by the radius in `radii` and the kind in
/// `kinds` at its anchor index (missing: 0 and round), each radius no larger than fits
/// ([`Corner::fitted`]). A cut corner becomes two anchors; a closed subpath whose first corner
/// is cut starts where that cut ends, so the cut closes it. Also returns, per subpath, the
/// anchor index in `path` each anchor comes from.
pub fn cut_corners(path: &PathData, radii: &[f64], kinds: &[CornerKind]) -> (PathData, Vec<Vec<usize>>) {
let corners = path_corners(path);
let mut corners = corners.iter().peekable();
let (mut subpaths, mut sources) = (Vec::with_capacity(path.subpaths.len()), Vec::with_capacity(path.subpaths.len()));
let mut first = 0;
for sp in &path.subpaths {
let (mut anchors, mut from) = (Vec::with_capacity(sp.anchors.len()), Vec::with_capacity(sp.anchors.len()));
let mut closing = None;
for (i, a) in sp.anchors.iter().enumerate() {
let index = first + i;
let corner = corners.next_if(|c| c.index == index);
let radius = corner.map_or(0.0, |c| c.fitted(radii.get(index).copied().unwrap_or(0.0)));
match corner {
Some(c) if radius > EPS => {
let [start, end] = c.cut(radius, kinds.get(index).copied().unwrap_or_default());
if i == 0 && sp.closed {
closing = Some(start);
} else {
anchors.push(start);
from.push(index);
}
anchors.push(end);
from.push(index);
}
_ => {
anchors.push(*a);
from.push(index);
}
}
}
if let Some(a) = closing {
anchors.push(a);
from.push(first);
}
first += sp.anchors.len();
subpaths.push(SubPath::new(anchors, sp.closed));
sources.push(from);
}
(PathData::new(subpaths), sources)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::shapes;
use kurbo::Rect;
fn near(a: Point, b: Point) -> bool {
a.distance(b) < 1e-9
}
/// A five-pointed star's tips are acute corners, its inner corners obtuse: all ten cut, each
/// a circle of the radius tangent to both sides.
#[test]
fn a_star_has_ten_corners_cut_as_circles() {
let star = shapes::star(Point::new(100.0, 100.0), 50.0, 25.0, 5, 0.0);
let corners = path_corners(&star);
assert_eq!(corners.len(), 10);
let angles: Vec<_> = corners.iter().map(|c| c.angle_deg()).collect();
assert!(angles.iter().step_by(2).all(|a| *a < 90.0), "tips are acute: {angles:?}");
assert!(angles.iter().skip(1).step_by(2).all(|a| *a > 90.0), "inner corners are obtuse: {angles:?}");
let (cut, from) = cut_corners(&star, &[4.0; 10], &[]);
assert_eq!(cut.anchor_count(), 20);
assert_eq!(from, [vec![0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 0]]);
for c in &corners {
// Both ends of the cut lie `setback` along the sides, as far from the arc's centre as
// the radius, and that centre is `radius` from either side.
let t = c.setback(4.0);
let o = c.on_bisector(4.0 / c.sin());
for p in [c.at + c.u * t, c.at + c.v * t] {
assert!((p.distance(o) - 4.0).abs() < 1e-9);
assert!(cut.anchors().any(|(_, _, a)| near(a.p, p)), "{p:?} is an anchor");
}
}
}
#[test]
fn radii_stop_at_half_the_shorter_side_per_corner() {
let tri = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(0.0, 40.0)], true));
let corners = path_corners(&tri);
assert_eq!(corners.len(), 3);
for c in &corners {
let max = c.max_radius();
assert!((c.setback(max) - c.lu.min(c.lv) / 2.0).abs() < 1e-9);
assert_eq!(c.fitted(1e6), max);
assert_eq!(c.fitted(-3.0), 0.0);
assert_eq!(c.fitted(f64::NAN), 0.0);
}
// The right angle at (0, 0) takes up to 20, half its shorter side.
assert!((corners[0].max_radius() - 20.0).abs() < 1e-9);
}
#[test]
fn ends_curves_smooth_and_straight_anchors_are_no_corners() {
// An open zig-zag: its ends aren't corners, nor is the anchor its sides run straight on through.
let open = PathData::single(SubPath::polyline(
&[Point::new(0.0, 0.0), Point::new(50.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 50.0), Point::new(150.0, 80.0)],
false,
));
assert_eq!(path_corners(&open).iter().map(|c| c.index).collect::<Vec<_>>(), [2, 3]);
// A curve on either side, or handles on the anchor, leave it alone.
let mut sp = SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 100.0), Point::new(0.0, 100.0)], true);
sp.anchors[1].h_out = Point::new(110.0, 10.0);
let p = PathData::single(sp);
assert_eq!(path_corners(&p).iter().map(|c| c.index).collect::<Vec<_>>(), [0, 3]);
assert!(path_corners(&shapes::ellipse(Rect::new(0.0, 0.0, 10.0, 10.0))).is_empty());
// A second subpath counts on from the first one's anchors.
let two = PathData::new(vec![
SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(0.0, 10.0)], true),
SubPath::polyline(&[Point::new(50.0, 0.0), Point::new(60.0, 0.0), Point::new(50.0, 10.0)], true),
]);
let (cut, from) = cut_corners(&two, &[0.0, 0.0, 0.0, 1.0], &[]);
assert_eq!(from, [vec![0, 1, 2], vec![3, 4, 5, 3]]);
assert_eq!(cut.anchor_count(), 7);
}
/// Inverted round and chamfer cuts end where the round one does, at any angle.
#[test]
fn kinds_share_their_ends() {
let star = shapes::star(Point::new(0.0, 0.0), 50.0, 25.0, 5, 0.0);
let ends = |k: CornerKind| -> Vec<Point> { cut_corners(&star, &[3.0; 10], &[k; 10]).0.anchors().map(|(_, _, a)| a.p).collect() };
let round = ends(CornerKind::Round);
assert_eq!(ends(CornerKind::InvertedRound), round);
assert_eq!(ends(CornerKind::Chamfer), round);
// The inverted arc stays on the circle about the corner.
let c = path_corners(&star)[0];
let [s, e] = c.cut(3.0, CornerKind::InvertedRound);
let bez = kurbo::CubicBez::new(s.p, s.h_out, e.h_in, e.p);
let r = c.setback(3.0);
for t in [0.25, 0.5, 0.75] {
use kurbo::ParamCurve;
assert!((bez.eval(t).distance(c.at) - r).abs() < r * 1e-3);
}
}
}
+1
View File
@@ -9,6 +9,7 @@
pub mod arc;
pub mod bez;
pub mod corners;
pub mod hit;
pub mod path;
pub mod projective;
+11 -48
View File
@@ -62,52 +62,10 @@ pub fn fitted_corner_radius(w: f64, h: f64, radius: f64) -> f64 {
/// Rectangle whose corners (top-left, top-right, bottom-right, bottom-left, y down) each have
/// their own radius and kind, every radius clamped to half the shorter side. A corner without a
/// radius is one anchor, the others two (where the cut meets each side). Clockwise from the
/// top-left corner, its anchor on the top side first.
/// top-left corner, its anchor on the top side first. Cut as any path's corners are
/// ([`crate::corners::cut_corners`]).
pub fn rectangle_with_corners(r: Rect, radii: [f64; 4], kinds: [CornerKind; 4]) -> PathData {
PathData::single(SubPath::new(corner_anchors(r, radii, kinds).into_iter().map(|(_, a)| a).collect(), true))
}
/// The corner (index into `radii`) of each anchor of [`rectangle_with_corners`].
pub fn rectangle_anchor_corners(r: Rect, radii: [f64; 4]) -> Vec<usize> {
corner_anchors(r, radii, [CornerKind::Round; 4]).into_iter().map(|(k, _)| k).collect()
}
/// The anchors of [`rectangle_with_corners`], each with its corner.
fn corner_anchors(r: Rect, radii: [f64; 4], kinds: [CornerKind; 4]) -> Vec<(usize, Anchor)> {
let r = r.abs();
// Each corner, with the directions of the side arriving at it and of the side leaving it.
let corners = [
(Point::new(r.x0, r.y0), Vec2::new(0.0, -1.0), Vec2::new(1.0, 0.0)),
(Point::new(r.x1, r.y0), Vec2::new(1.0, 0.0), Vec2::new(0.0, 1.0)),
(Point::new(r.x1, r.y1), Vec2::new(0.0, 1.0), Vec2::new(-1.0, 0.0)),
(Point::new(r.x0, r.y1), Vec2::new(-1.0, 0.0), Vec2::new(0.0, -1.0)),
];
let mut out = Vec::with_capacity(8);
let mut top_left_start = None;
for (k, ((c, din, dout), (rad, kind))) in corners.into_iter().zip(radii.into_iter().zip(kinds)).enumerate() {
let rad = fitted_corner_radius(r.width(), r.height(), rad);
if rad <= 1e-9 {
out.push((k, Anchor::corner(c)));
continue;
}
// The cut runs from `start` on the arriving side to `end` on the leaving one.
let (start, end, h) = (c - din * rad, c + dout * rad, rad * KAPPA);
let (h_out, h_in) = match kind {
CornerKind::Round => (start + din * h, end - dout * h),
CornerKind::InvertedRound => (start + dout * h, end - din * h),
CornerKind::Chamfer => (start, end),
};
let start = Anchor { p: start, h_in: start, h_out, kind: AnchorKind::Corner };
let end = Anchor { p: end, h_in, h_out: end, kind: AnchorKind::Corner };
if k == 0 {
top_left_start = Some(start);
} else {
out.push((k, start));
}
out.push((k, end));
}
out.extend(top_left_start.map(|a| (0, a)));
out
crate::corners::cut_corners(&rectangle(r), &radii, &kinds).0
}
/// Ellipse inscribed in `r` with 4 smooth anchors (left, top, right, bottom).
@@ -244,6 +202,11 @@ pub fn polar_grid(r: Rect, concentric: u32, radial: u32) -> Vec<PathData> {
mod tests {
use super::*;
/// The corner (index into `radii`) of each anchor of [`rectangle_with_corners`].
fn corner_sources(r: Rect, radii: [f64; 4]) -> Vec<usize> {
crate::corners::cut_corners(&rectangle(r), &radii, &[]).1.concat()
}
#[test]
fn rect_is_4_corners_clockwise() {
let p = rectangle(Rect::new(0.0, 0.0, 100.0, 50.0));
@@ -293,7 +256,7 @@ mod tests {
a((x0, y0 + rad), (x0, y0 + rad), (x0, y0 + rad - k)),
];
assert_eq!(rounded_rectangle(r, rad).subpaths[0].anchors, want);
assert_eq!(rectangle_anchor_corners(r, [rad; 4]), [0, 1, 1, 2, 2, 3, 3, 0]);
assert_eq!(corner_sources(r, [rad; 4]), [0, 1, 1, 2, 2, 3, 3, 0]);
assert_eq!(rounded_rectangle(r, 0.0), rectangle(r));
}
@@ -305,11 +268,11 @@ mod tests {
let p = rectangle_with_corners(r, radii, [CornerKind::Round; 4]);
let pts: Vec<Point> = p.subpaths[0].anchors.iter().map(|a| a.p).collect();
assert_eq!(pts, [Point::new(0.0, 0.0), Point::new(90.0, 0.0), Point::new(100.0, 10.0), Point::new(100.0, 60.0), Point::new(0.0, 60.0)]);
assert_eq!(rectangle_anchor_corners(r, radii), [0, 1, 1, 2, 3]);
assert_eq!(corner_sources(r, radii), [0, 1, 1, 2, 3]);
let quarter = PI * 25.0;
assert!((p.subpaths[0].area() - (6000.0 - 100.0 + quarter)).abs() < 0.1, "a quarter circle off one corner");
// The top-left corner rounded: its top-side anchor first, its left-side one last.
assert_eq!(rectangle_anchor_corners(r, [10.0, 0.0, 0.0, 200.0]), [0, 1, 2, 3, 3, 0]);
assert_eq!(corner_sources(r, [10.0, 0.0, 0.0, 200.0]), [0, 1, 2, 3, 3, 0]);
// Inverted round cuts a quarter circle out; a chamfer cuts a triangle.
let inverted = rectangle_with_corners(r, radii, [CornerKind::InvertedRound; 4]);
assert!((inverted.subpaths[0].area() - (6000.0 - quarter)).abs() < 0.1);
+2
View File
@@ -49,6 +49,8 @@ mod tests_links;
#[cfg(test)]
mod tests_liquify;
#[cfg(test)]
mod tests_pen;
#[cfg(test)]
mod tests_persp;
#[cfg(test)]
mod tests_place;
+27
View File
@@ -588,3 +588,30 @@ fn type_preferences_apply_to_agents() {
assert_eq!(r["isError"], false, "{r}");
assert_eq!(style(&mut s, 6), (size + 4.0, tracking + 50.0));
}
/// The drawing tools snap to Smart Guides over MCP as with the mouse (#506): a Rectangle drawn
/// from near another object's corner starts on it, and a Pen anchor placed beside that object's
/// centre lines up with it.
#[test]
fn drawing_gestures_snap_to_smart_guides() {
let mut s = server();
let r = call(&mut s, 1, "run_command", json!({"command": "file.new", "params": {"width": 800, "height": 600}}));
assert_eq!(r["isError"], false, "{r}");
let r = call(&mut s, 2, "draw_shape", json!({"shape": "rectangle", "x": 100, "y": 100, "width": 100, "height": 100}));
assert_eq!(r["isError"], false, "{r}");
let bounds = |s: &mut Server, n: u64, events: Value, tool: &str| {
let r = call(s, n, "pointer_gesture", json!({"tool": tool, "events": events}));
assert_eq!(r["isError"], false, "{r}");
let id = serde_json::from_str::<Value>(&text_of(&r)).unwrap()["selection"][0].clone();
let doc: Value = serde_json::from_str(&text_of(&call(s, n + 1, "inspect_document", json!({})))).unwrap();
let made = doc["layers"][0]["children"].as_array().unwrap().iter().find(|c| c["id"] == id).expect("drawn").clone();
let b = &made["bounds"];
[&b["x"], &b["y"], &b["width"], &b["height"]].map(|v| v.as_f64().unwrap())
};
let events = json!([{"kind": "move", "x": 202, "y": 203}, {"kind": "down", "x": 202, "y": 203}, {"kind": "drag", "x": 330, "y": 341}, {"kind": "up", "x": 330, "y": 341}]);
assert_eq!(bounds(&mut s, 3, events, "rectangle"), [200.0, 200.0, 130.0, 141.0]);
let r = call(&mut s, 5, "run_command", json!({"command": "select.none", "params": {}}));
assert_eq!(r["isError"], false, "{r}");
let events = json!([{"kind": "down", "x": 300, "y": 420}, {"kind": "up", "x": 300, "y": 420}, {"kind": "move", "x": 151.5, "y": 431}, {"kind": "down", "x": 151.5, "y": 431}, {"kind": "up", "x": 151.5, "y": 431}]);
assert_eq!(bounds(&mut s, 6, events, "pen"), [150.0, 420.0, 150.0, 11.0]);
}
+1
View File
@@ -62,6 +62,7 @@ fn export_tool_lists_engine_formats_and_options() {
"svg",
"svgz",
"pdf",
"ai",
"png",
"jpg",
"gif",
+66
View File
@@ -0,0 +1,66 @@
//! The Pen over MCP, headless: `pointer_gesture` with the modifiers held as on the desktop.
use serde_json::{Value, json};
use crate::{Backend, Headless, call_tool};
fn text(r: &crate::ToolResult) -> Value {
assert!(!r.is_error, "{r:?}");
serde_json::from_str(r.content[0]["text"].as_str().unwrap()).unwrap()
}
/// A press at the first point, drags through the others, the release at the last.
fn gesture(pts: &[(f64, f64)]) -> Value {
let (first, last) = (pts[0], pts[pts.len() - 1]);
let mut events = vec![json!({"kind": "down", "x": first.0, "y": first.1})];
events.extend(pts[1..].iter().map(|(x, y)| json!({"kind": "drag", "x": x, "y": y})));
events.push(json!({"kind": "up", "x": last.0, "y": last.1}));
json!({ "events": events })
}
/// The anchors of each path, in paint order.
fn paths(h: &Headless) -> Vec<Vec<vectorcraft_geom::Anchor>> {
let mut v = vec![];
h.session.doc().unwrap().doc.walk(|n| {
if let Some(p) = n.path_data() {
v.push(p.subpaths.iter().flat_map(|s| s.anchors.clone()).collect());
}
});
v
}
/// #494: Cmd held at the press borrows Direct Selection from the Pen; the path goes on afterwards.
#[test]
fn cmd_with_the_pen_edits_the_path_being_drawn() {
let mut h = Headless::new();
h.call("engine.execute", json!({"command": "file.new", "params": {"width": 800, "height": 600}})).unwrap();
text(&call_tool(&mut h, "select_tool", &json!({"tool": "pen"})));
text(&call_tool(&mut h, "pointer_gesture", &gesture(&[(100.0, 300.0)])));
text(&call_tool(&mut h, "pointer_gesture", &gesture(&[(200.0, 300.0), (250.0, 300.0)])));
let mut drag = gesture(&[(250.0, 300.0), (250.0, 280.0), (250.0, 263.0)]);
drag["mods"] = json!({"cmd": true});
let r = text(&call_tool(&mut h, "pointer_gesture", &drag));
assert_eq!(r["tool"], "pen", "{r}");
assert_eq!(paths(&h)[0][1].h_out, vectorcraft_geom::Point::new(250.0, 263.0));
text(&call_tool(&mut h, "pointer_gesture", &gesture(&[(300.0, 350.0)])));
assert_eq!(paths(&h).iter().map(Vec::len).collect::<Vec<_>>(), [3], "the same path, three anchors");
}
/// #501: a drag out of the first anchor closes the path, shaping the closing curve.
#[test]
fn a_drag_from_the_first_anchor_closes_the_path() {
let mut h = Headless::new();
h.call("engine.execute", json!({"command": "file.new", "params": {"width": 800, "height": 600}})).unwrap();
text(&call_tool(&mut h, "select_tool", &json!({"tool": "pen"})));
for p in [(100.0, 300.0), (200.0, 300.0), (200.0, 400.0)] {
text(&call_tool(&mut h, "pointer_gesture", &gesture(&[p])));
}
let close: Vec<(f64, f64)> = (0..=12).map(|i| (100.0 + 5.0 * f64::from(i), 300.0 - 4.0 * f64::from(i))).collect();
text(&call_tool(&mut h, "pointer_gesture", &gesture(&close)));
let d = &h.session.doc().unwrap().doc;
let mut closed = vec![];
d.walk(|n| closed.extend(n.path_data().map(|p| p.is_closed())));
assert_eq!(closed, [true], "one path, closed");
let first = paths(&h)[0][0];
assert_eq!((first.h_in, first.h_out), (vectorcraft_geom::Point::new(40.0, 348.0), vectorcraft_geom::Point::new(160.0, 252.0)));
}
+1 -1
View File
@@ -189,7 +189,7 @@ impl<'a> Scene<'a> {
}
}
// Live blends, envelopes, meshes and repeats are written as their evaluated art.
NodeKind::Blend { .. } | NodeKind::Envelope { .. } | NodeKind::Mesh(_) | NodeKind::Repeat(_) => {
NodeKind::Blend { .. } | NodeKind::Envelope { .. } | NodeKind::Mesh(_) | NodeKind::Repeat(_) | NodeKind::PlacedDocument(_) => {
let g = vectorcraft_effects::expand_live_deep(Some(self.doc), n);
for c in g.children().into_iter().flatten() {
self.node(c, false);
+1 -1
View File
@@ -19,7 +19,7 @@ pub use edit::{
split_into_grid,
};
pub use offset::{Cap, Join, offset_path, outline_stroke, stroke_region};
pub use pathfinder::{PathfinderOp, Region, Shape, merge_regions, pathfinder, region_at, regions};
pub use pathfinder::{FaceMerger, PathfinderOp, Region, Shape, merge_regions, pathfinder, region_at, regions};
pub use planar::{BuilderArrangement, SHAPE_BUILDER_MAX_SEGMENTS, cut_out, encloses_area, interior_point, live_paint, shape_builder};
/// Errors from fallible operations.
+58 -1
View File
@@ -7,7 +7,7 @@ use kurbo::{BezPath, ParamCurve, ParamCurveNearest, Point, Shape as _};
use linesweeper::topology::ContourIdx;
use vectorcraft_geom::{FillRule, PathData};
use crate::boolean::{Arrangement, Multi, Seg, all_contours_to_path, contours_to_path, fill_bezpath, segs_to_subpath, unite_all};
use crate::boolean::{Arrangement, Multi, Seg, all_contours_to_path, contours_to_path, fill_bezpath, normalize_bez, segs_to_subpath, unite_all};
/// A filled shape in a Pathfinder stack. `key` identifies its paint (e.g. a hashed fill colour);
/// results carry the key of the object whose paint they keep.
@@ -264,6 +264,63 @@ pub fn merge_regions(regions: &[&Region]) -> PathData {
unite_all(&v)
}
/// Merges faces of the planar arrangement of a set of shapes (as [`regions`] gives them) into one
/// path, from the arrangement itself, made once for every merge of the set: the faces' contours
/// share their edges exactly, so the edges between merged faces vanish. Uniting the faces' tidied
/// outlines ([`merge_regions`]) could leave those edges in, as a hairline gap or a spur, where
/// neighbouring faces' outlines had been refit apart. Shapes with open paths (faces lines cut)
/// fall back to [`merge_regions`].
pub struct FaceMerger {
/// The arrangement (`None`: open paths, or the sweep failed) and the number of shapes.
arr: Option<Arrangement>,
shapes: usize,
}
impl FaceMerger {
pub fn new(shapes: &[Shape]) -> Self {
let has_open = shapes.iter().flat_map(|s| &s.path.subpaths).any(|sp| !sp.closed && sp.anchors.len() >= 2);
Self { arr: if has_open { None } else { arrangement(shapes) }, shapes: shapes.len() }
}
/// The union of `faces`.
pub fn merge(&self, faces: &[&Region]) -> PathData {
self.exact(faces).filter(|p| !p.is_empty()).unwrap_or_else(|| merge_regions(faces))
}
fn exact(&self, faces: &[&Region]) -> Option<PathData> {
let arr = self.arr.as_ref()?;
// Each face by its coverage and a point inside it.
let mut picks: Vec<(Vec<bool>, Point)> = Vec::with_capacity(faces.len());
for r in faces {
let mut mask = vec![false; self.shapes];
for &s in &r.sources {
*mask.get_mut(s)? = true;
}
picks.push((mask, crate::planar::interior_point(&r.path)?));
}
let mut raw = BezPath::new();
let mut done: Vec<&[bool]> = vec![];
for (mask, _) in &picks {
if done.contains(&mask.as_slice()) {
continue;
}
done.push(mask);
let c = arr.contours(|k| k == mask.as_slice());
for group in c.grouped() {
let mut face = BezPath::new();
for i in group {
face.extend(c[i].path.iter());
}
if picks.iter().any(|(m, p)| m == mask && face.winding(*p) != 0) {
raw.extend(face.iter());
}
}
}
let merged = normalize_bez(&raw, FillRule::NonZero).ok()?;
Some(all_contours_to_path(&merged, &arr.tidy))
}
}
/// Pathfinder Outline: split every shape's boundary at junctions of the arrangement.
fn outline_edges(arr: &Arrangement, shapes: &[Shape]) -> Vec<Shape> {
let junctions = arr.junctions();
+1 -1
View File
@@ -982,7 +982,7 @@ impl Exporter<'_> {
}
}
// Live blends/envelopes/meshes export their evaluated (expanded) form.
NodeKind::Blend { .. } | NodeKind::Envelope { .. } | NodeKind::Mesh(_) | NodeKind::Repeat(_) => {
NodeKind::Blend { .. } | NodeKind::Envelope { .. } | NodeKind::Mesh(_) | NodeKind::Repeat(_) | NodeKind::PlacedDocument(_) => {
let g = vectorcraft_effects::expand_live_deep(Some(self.doc), n);
for c in g.children().into_iter().flatten() {
self.node(s, c, page, false);
+74 -5
View File
@@ -23,7 +23,7 @@ use crate::import_color::{Colors, Native};
use crate::import_mask::{MaskSpec, contains, is_rectangle, luminance, mask_spec, white_cover};
use crate::import_scan::{MAX_NESTING, Ocgs, Scan, all_on, hides_forms, scan_page, tag_key};
use crate::import_shading::{clipped, extend_clip, fold_stop_opacity, mesh_shading, shading_gradient};
use crate::import_text::{Families, Look, Placement, TextLine, Upright};
use crate::import_text::{Families, LineFacts, Look, Placement, TextLine, Upright};
use crate::{CropTo, ImportOptions, ImportReport, PdfError, TextAs};
/// The name of the paths text imports as.
@@ -76,6 +76,33 @@ fn place_group(g: usize, ocgs: &Ocgs, slots: &mut Vec<Slot>, nesting: &mut Nesti
slots.push(Slot::Group(child));
}
/// The top-level group that group `g` is listed under (`g` itself when it isn't a sublayer).
fn top_group(g: usize, ocgs: &Ocgs) -> usize {
let mut top = g;
for _ in 0..=MAX_NESTING {
match ocgs.list.get(top).and_then(|o| o.parent) {
Some(parent) => top = parent,
None => break,
}
}
top
}
/// Merge the top-level groups a page marks (`page`, in the order it first marks each, its empty
/// ones too) into the stacking order of the pages before (`order`, bottom first; `known`: its
/// groups). A group new to it goes right below the first group the page marks after it that it
/// has: a layer whose art starts on a later page keeps its place among the others (#508).
fn merge_order(order: &mut Vec<usize>, known: &mut HashSet<usize>, page: &[usize]) {
let mut above = None;
for &g in page.iter().rev() {
if known.insert(g) {
let at = above.and_then(|a| order.iter().position(|&x| x == a)).unwrap_or(order.len());
order.insert(at, g);
}
above = Some(g);
}
}
/// The layer of group `g`, in `color`: its art and sublayers. `None` for a group that isn't read.
fn group_layer(
b: &mut Builder<'_>,
@@ -166,6 +193,8 @@ pub fn import_with_report(bytes: &[u8], opts: &ImportOptions) -> Result<ImportRe
let mut slots: Vec<Slot> = vec![];
let mut group_art: HashMap<usize, Vec<Arc<Node>>> = HashMap::new();
let mut nesting = Nesting::new();
// The top-level groups in the order the pages mark them, bottom first.
let (mut order, mut known) = (vec![], HashSet::new());
for (i, &number) in picked.iter().enumerate() {
let Some(page) = pages.get(number) else { continue };
// The chosen box sits at (x, 0); the page draws round it.
@@ -175,6 +204,11 @@ pub fn import_with_report(bytes: &[u8], opts: &ImportOptions) -> Result<ImportRe
let mut ctx = Context::new(xf, ab, &cache, pdf.xref(), settings.clone());
b.page = ab;
let scan = scan_page(page, &mut ocgs, all_on, &mut b.fonts);
if route {
let mut seen = HashSet::new();
let marked: Vec<usize> = scan.tags.iter().filter_map(|(_, g)| g.map(|g| top_group(g, &ocgs))).filter(|g| seen.insert(*g)).collect();
merge_order(&mut order, &mut known, &marked);
}
b.begin_page(scan);
interpret_page(page, &mut ctx, &mut b);
let mut parts = b.end_page();
@@ -239,8 +273,25 @@ pub fn import_with_report(bytes: &[u8], opts: &ImportOptions) -> Result<ImportRe
if placeholder {
return Err(PdfError::PlaceholderOnly);
}
// A group the pages mark but draw nothing in is an empty layer, as the editor had it.
for &g in &order {
if !nesting.contains_key(&g) {
slots.push(Slot::Group(g));
}
}
// The groups' layers stack as the pages mark them (the art outside them stays where it was
// drawn): a group that first paints on a later page doesn't go on top of the others.
let rank: HashMap<usize, usize> = order.iter().enumerate().map(|(i, &g)| (g, i)).collect();
let at: Vec<usize> = slots.iter().enumerate().filter(|(_, s)| matches!(s, Slot::Group(_))).map(|(i, _)| i).collect();
let mut stacked: Vec<usize> = slots.iter().filter_map(|s| if let Slot::Group(g) = s { Some(*g) } else { None }).collect();
stacked.sort_by_key(|g| rank.get(g).copied().unwrap_or(usize::MAX));
for (i, g) in at.into_iter().zip(stacked) {
if let Some(s) = slots.get_mut(i) {
*s = Slot::Group(g);
}
}
for (n, slot) in slots.into_iter().enumerate() {
let layer = match slot {
let mut layer = match slot {
Slot::Page(l) => *l,
// Sublayers take their top-level layer's colour.
Slot::Group(g) => match group_layer(&mut b, g, &ocgs, &nesting, &mut group_art, LayerColor::Preset((n % 27) as u8)) {
@@ -248,6 +299,9 @@ pub fn import_with_report(bytes: &[u8], opts: &ImportOptions) -> Result<ImportRe
None => continue,
},
};
if let Some(art) = layer.children_mut() {
crate::import_lines::rebuild(art, &b.lines);
}
doc.layers.push(Arc::new(layer));
}
for (k, blob) in b.images.drain() {
@@ -567,6 +621,8 @@ struct Builder<'p> {
nested: u32,
/// The last filled path: its node and its outline (a stroke of the same outline joins it).
last_fill: Option<(NodeId, BezPath)>,
/// What each line of type made tells beyond its text object ([`crate::import_lines`]).
lines: HashMap<NodeId, LineFacts>,
}
fn blend(b: hayro_interpret::BlendMode) -> BlendMode {
@@ -701,6 +757,7 @@ impl<'p> Builder<'p> {
pending: false,
nested: 0,
last_fill: None,
lines: HashMap::new(),
}
}
@@ -786,10 +843,11 @@ impl<'p> Builder<'p> {
let current = self.current_group();
let Some(f) = self.stack.last_mut() else { return };
f.children.push(n);
// A frame's art goes where its first art was drawn (a clip can end in a later group).
if root {
self.root_groups.push(group.or(current));
} else if f.group.is_none() {
f.group = group;
f.group = group.or(current);
}
}
@@ -955,9 +1013,10 @@ impl<'p> Builder<'p> {
}
fn flush_text(&mut self) {
let Some((t, opacity)) = self.text.take().and_then(TextLine::finish) else { return };
let Some((t, opacity, facts)) = self.text.take().and_then(TextLine::finish) else { return };
let mut n = Node::new(self.id(), NodeKind::Text(Box::new(t)));
n.opacity = opacity;
self.lines.insert(n.id, facts);
self.push_node(n);
}
@@ -1227,6 +1286,14 @@ impl<'p> Builder<'p> {
place(&mut line);
self.text = Some(line);
}
// Its ink: a stroke the file draws as outlines of the glyphs is told by it.
let mut ink = o.outline();
if let Some(line) = &mut self.text
&& !ink.elements().is_empty()
{
ink.apply_affine(m);
line.ink.push(ink.bounding_box());
}
true
}
}
@@ -1570,8 +1637,10 @@ impl<'a> Device<'a> for Builder<'_> {
if self.nested > 0 {
return;
}
if self.marked.pop().flatten().is_some() {
// The runs gathered within a layer's sequence are its art: finish them before it ends.
if self.marked.last().copied().flatten().is_some() {
self.flush();
}
self.marked.pop();
}
}
+254
View File
@@ -0,0 +1,254 @@
//! What a file's lines of type were, beyond what each line says on its own (#508). An editor
//! writes what PDF text can't say as more art next to the text, and the type it wrapped in a
//! frame as lines:
//! - a stroke added to a type object (above or below its characters) comes as the outline of each
//! glyph stroked, one path per glyph, right after the type (or right before it): it is the
//! type's stroke again, so the type stays one object;
//! - area type comes as a line of point type per line, each wrapped line ending in a space. Lines
//! in a row sharing a left edge, font, size and leading (and paragraph spacing) are one area
//! type object again, aligned left or justified, where laying its text out in the frame breaks
//! it where the file does: else, as where its font isn't installed, they stay lines.
use std::collections::HashMap;
use std::sync::Arc;
use kurbo::{Point, Rect, Shape};
use vectorcraft_color::BlendMode;
use vectorcraft_doc::{AppearanceItem, Justify, Node, NodeId, NodeKind, TextKind, TextObject, TextRun};
use vectorcraft_geom::shapes;
use crate::import_text::LineFacts;
/// Rebuild the type among `nodes` (and in their groups) from what its lines tell (`lines`).
pub(crate) fn rebuild(nodes: &mut Vec<Arc<Node>>, lines: &HashMap<NodeId, LineFacts>) {
if lines.is_empty() {
return;
}
for n in nodes.iter_mut() {
if n.children().is_some_and(|c| !c.is_empty())
&& let Some(children) = Arc::make_mut(n).children_mut()
{
rebuild(children, lines);
}
}
join_strokes(nodes, lines);
join_paragraphs(nodes, lines);
}
/// The stroke paths `nodes` draw when they are the outlines of the glyphs whose ink boxes are
/// `ink`, stroked one by one alike (no fill, mask or blending, fully opaque).
fn outline_stroke(nodes: &[Arc<Node>], ink: &[Rect]) -> Option<AppearanceItem> {
let first = nodes.first()?;
let [stroke @ AppearanceItem::Stroke(_)] = first.appearance.items.as_slice() else { return None };
let on_glyph = |n: &Node, r: &Rect| {
let tol = 0.01 * (r.width() + r.height()) + 0.01;
let NodeKind::Path { path, clipping: false, guide: false, live: None, .. } = &n.kind else { return false };
let b = path.to_bezpath().bounding_box();
n.appearance == first.appearance
&& n.mask.is_none()
&& n.opacity >= 0.999
&& n.blend == BlendMode::Normal
&& [(b.x0, r.x0), (b.y0, r.y0), (b.x1, r.x1), (b.y1, r.y1)].iter().all(|(a, b)| (a - b).abs() <= tol)
};
(nodes.len() == ink.len() && nodes.iter().zip(ink).all(|(n, r)| on_glyph(n, r))).then(|| stroke.clone())
}
/// Each type object among `nodes` whose glyphs' outlines are stroked by the paths right after it
/// (or right before it) takes that stroke above (or below) its characters, and the paths go.
fn join_strokes(nodes: &mut Vec<Arc<Node>>, lines: &HashMap<NodeId, LineFacts>) {
let mut i = 0;
while i < nodes.len() {
let ink = nodes
.get(i)
.filter(|n| matches!(n.kind, NodeKind::Text(_)) && n.appearance.items.is_empty())
.and_then(|n| lines.get(&n.id))
.map_or(&[][..], |f| f.ink.as_slice());
let k = ink.len();
if k > 0 {
if let Some(stroke) = nodes.get(i + 1..i + 1 + k).and_then(|after| outline_stroke(after, ink)) {
nodes.drain(i + 1..i + 1 + k);
if let Some(t) = nodes.get_mut(i) {
Arc::make_mut(t).appearance.items.push(stroke);
}
} else if let Some(stroke) = i.checked_sub(k).and_then(|from| nodes.get(from..i)).and_then(|before| outline_stroke(before, ink)) {
nodes.drain(i - k..i);
i -= k;
if let Some(t) = nodes.get_mut(i) {
let ap = &mut Arc::make_mut(t).appearance;
ap.items.insert(0, stroke);
ap.set_contents_at(1);
}
}
}
i += 1;
}
}
/// `n` as a line that can be part of area type: horizontal point type, with what its line told.
fn line<'a>(n: &'a Node, lines: &'a HashMap<NodeId, LineFacts>) -> Option<(&'a TextObject, &'a LineFacts)> {
let NodeKind::Text(t) = &n.kind else { return None };
let point = matches!(t.kind, TextKind::Point) && !t.vertical && n.mask.is_none() && !t.runs.is_empty();
point.then_some(())?;
Some((t, lines.get(&n.id)?))
}
/// Lines of type in a row that may be one area type object.
struct Block {
/// The step from a wrapped line's baseline to the next.
leading: f64,
/// The extra step after a line ending a paragraph.
space: f64,
/// Each line's baseline below the first (text space).
ys: Vec<f64>,
}
/// The lines from `nodes`' first on that share its left edge, angle, font and size, its look
/// (opacity, blending, appearance) and steps down by one leading after a wrapped line and by
/// another (the leading and paragraph spacing) after a line ending a paragraph: how many, and
/// the block they make unless none of them was wrapped (0 and `None`: the first isn't a line).
fn block(nodes: &[Arc<Node>], lines: &HashMap<NodeId, LineFacts>) -> (usize, Option<Block>) {
let Some((head, (t0, f0))) = nodes.first().and_then(|n| Some((n, line(n, lines)?))) else { return (0, None) };
let st = t0.first_style();
let size = st.size;
let inv = t0.xf.inverse();
let lin = |t: &TextObject| {
let [a, b, c, d, ..] = t.xf.as_coeffs();
[a, b, c, d]
};
let (mut ys, mut wraps) = (vec![0.0], f0.wraps);
let (mut leading, mut para): (Option<f64>, Option<f64>) = (None, None);
for n in nodes.iter().skip(1) {
let Some((t, f)) = line(n, lines) else { break };
let s = t.first_style();
let alike = n.opacity == head.opacity
&& n.blend == head.blend
&& n.appearance == head.appearance
&& s.font_family == st.font_family
&& s.font_style == st.font_style
&& (s.size - size).abs() <= size * 0.01
&& t.para == t0.para
&& lin(t).iter().zip(lin(t0)).all(|(a, b)| (a - b).abs() < 1e-6);
let at = inv * (t.xf * Point::ZERO);
let step = at.y - ys.last().copied().unwrap_or_default();
if !alike || at.x.abs() > size * 0.02 || !(step > size * 0.5 && step < size * 4.0) {
break;
}
let slot = if wraps { &mut leading } else { &mut para };
match *slot {
Some(s) if (s - step).abs() > size * 0.01 => break,
Some(_) => {}
None => *slot = Some(step),
}
ys.push(at.y);
wraps = f.wraps;
}
let count = ys.len();
let Some(leading) = leading else { return (count, None) };
let space = para.map_or(0.0, |p| p - leading);
(count, (space > -size * 0.01).then_some(Block { leading, space: space.max(0.0), ys }))
}
/// Lines `nodes` of block `b` as one area type object, aligned left or justified, when laying it
/// out breaks its lines where the file does.
fn area_type(nodes: &[Arc<Node>], lines: &HashMap<NodeId, LineFacts>, b: &Block) -> Option<TextObject> {
let texts: Vec<(&TextObject, &LineFacts)> = nodes.iter().map(|n| line(n, lines)).collect::<Option<_>>()?;
let (first, _) = texts.first()?;
let size = first.first_style().size;
// Each line's tracking (a line with spaces tracked apart was set by hand).
let trackings: Vec<f64> = texts
.iter()
.map(|(t, _)| {
let mut all = t.runs.iter().map(|r| r.style.tracking);
let one = all.next()?;
all.all(|x| x == one).then_some(one)
})
.collect::<Option<_>>()?;
let median = |mut v: Vec<f64>| {
v.sort_by(f64::total_cmp);
v.get(v.len() / 2).copied()
};
let wrapped: Vec<f64> = texts.iter().filter(|(_, f)| f.wraps).map(|(_, f)| f.length).collect();
let longest = |v: &[f64]| v.iter().copied().fold(0.0, f64::max);
let mut tries = vec![];
// Wrapped lines all as long: justified (a paragraph's last line aligned left), tracked as the
// lines that end paragraphs are (the others are spaced out).
let full = longest(&wrapped);
if wrapped.len() >= 2 && wrapped.iter().all(|l| (full - l).abs() <= size * 0.02) {
let ends: Vec<f64> = texts.iter().zip(&trackings).filter(|((_, f), _)| !f.wraps).map(|(_, t)| *t).collect();
let tracking = median(ends).or_else(|| trackings.iter().copied().reduce(f64::min))?;
tries.push((Justify::JustifyLeft, full, tracking));
}
let all: Vec<f64> = texts.iter().map(|(_, f)| f.length).collect();
tries.push((Justify::Left, longest(&all) + size * 0.02, median(trackings)?));
tries.into_iter().find_map(|(justify, width, tracking)| laid_out(&texts, b, justify, width, tracking))
}
/// The area type of lines `texts` (block `b`): `width` wide, aligned `justify`, its characters
/// tracked `tracking`; `None` when it doesn't lay out as the lines did.
fn laid_out(texts: &[(&TextObject, &LineFacts)], b: &Block, justify: Justify, width: f64, tracking: f64) -> Option<TextObject> {
let (first, _) = texts.first()?;
let size = first.first_style().size;
// Leading as set, unless it is Auto's (120% of the size).
let explicit =
(b.leading - size * 1.2).abs() > size * 1e-3 || texts.iter().any(|(t, _)| t.runs.iter().any(|r| (r.style.size - size).abs() > 1e-9));
let mut runs: Vec<TextRun> = vec![];
for (k, (t, f)) in texts.iter().enumerate() {
for r in &t.runs {
let mut style = r.style.clone();
style.tracking = tracking;
style.leading = explicit.then_some((b.leading * 1000.0).round() / 1000.0);
match runs.last_mut() {
Some(last) if last.style == style => last.text.push_str(&r.text),
_ => runs.push(TextRun { text: r.text.clone(), style }),
}
}
// A wrapped line's space, or the end of a paragraph.
if k + 1 < texts.len()
&& let Some(last) = runs.last_mut()
{
last.text.push(if f.wraps { ' ' } else { '\n' });
}
}
let mut t = (*first).clone();
t.runs = runs;
t.para.justify = justify;
t.para.space_before = b.space;
let last = b.ys.last().copied()?;
let db = vectorcraft_text::FontDb::global();
// The frame's top puts the first baseline where the file has it.
t.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, width, last + b.leading.max(size) + size)) };
let top = -vectorcraft_text::layout(db, &t).lines.first()?.baseline;
t.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, top, width, last + b.leading.max(size))) };
let laid = vectorcraft_text::layout(db, &t);
let plain = t.plain_text();
let same = !laid.overflow
&& laid.lines.len() == texts.len()
&& laid.lines.iter().zip(texts).zip(&b.ys).all(|((l, (line, f)), y)| {
let text = plain.get(l.start..l.end).unwrap_or_default();
text.trim() == line.plain_text().trim()
&& (l.baseline - y).abs() <= size * 0.05
&& (justify != Justify::JustifyLeft || !f.wraps || (l.x1 - f.length).abs() <= size * 0.05)
});
t.cached_bounds = Some(laid.bounds);
same.then_some(t)
}
/// Lines of point type in a row among `nodes` that were wrapped in a frame become one area type
/// object again (see [`area_type`]).
fn join_paragraphs(nodes: &mut Vec<Arc<Node>>, lines: &HashMap<NodeId, LineFacts>) {
let mut i = 0;
while i < nodes.len() {
let (count, b) = nodes.get(i..).map_or((0, None), |rest| block(rest, lines));
let area = b.filter(|_| count > 1).and_then(|b| area_type(nodes.get(i..i + count)?, lines, &b));
if let Some(area) = area
&& let Some(head) = nodes.get_mut(i)
{
Arc::make_mut(head).kind = NodeKind::Text(Box::new(area));
nodes.drain(i + 1..i + count);
i += 1;
} else {
// Lines that don't make area type: none of them starts it either.
i += count.max(1);
}
}
}
+116 -12
View File
@@ -9,9 +9,10 @@
use std::collections::HashMap;
use kurbo::{Affine, BezPath, Point, Vec2};
use kurbo::{Affine, BezPath, Point, Rect, Vec2};
use vectorcraft_color::Paint;
use vectorcraft_doc::{CharStyle, ParaDirection, TextKind, TextObject, TextRun};
use vectorcraft_text::TextLayout;
/// One glyph's placement: its baseline origin, advance direction, size and horizontal scale.
#[derive(Clone, Copy, Debug)]
@@ -103,6 +104,8 @@ pub(crate) struct TextLine {
next: Point,
/// The last glyph's origin.
last: Point,
/// Where the last glyph that isn't a space ends.
visible: Point,
/// The last glyph's baseline direction.
last_dir: Vec2,
/// Each glyph's baseline origin, then where the last one ends.
@@ -112,6 +115,24 @@ pub(crate) struct TextLine {
upright: Option<Upright>,
/// The glyphs make a column (vertical type), each below the last.
column: bool,
/// Each glyph's ink box as drawn (document space), in drawing order; glyphs without ink are
/// left out.
pub ink: Vec<Rect>,
/// The spaces read from gaps between glyphs: their byte offset in the text, and the gap from
/// the end of the glyph before to the start of the next (points).
gaps: Vec<(usize, f64)>,
}
/// What a finished line of type tells beyond its text object (see [`crate::import_lines`]).
#[derive(Clone, Debug, Default)]
pub(crate) struct LineFacts {
/// [`TextLine::ink`].
pub ink: Vec<Rect>,
/// Horizontal point type: it ended in a space (as a line an editor wrapped in a frame does).
pub wraps: bool,
/// Horizontal point type: how long the file set it, from its first glyph's origin to the end
/// of its last glyph that isn't a space (points, along the baseline).
pub length: f64,
}
/// The most a glyph on a curve turns from the one before it (about 20°).
@@ -119,7 +140,20 @@ const CURVE_TURN_COS: f64 = 0.94;
impl TextLine {
pub fn new(at: Placement, opacity: f32) -> Self {
Self { at, opacity, next: at.origin, last: at.origin, last_dir: at.dir, baseline: vec![], runs: vec![], upright: None, column: false }
Self {
at,
opacity,
next: at.origin,
last: at.origin,
visible: at.origin,
last_dir: at.dir,
baseline: vec![],
runs: vec![],
upright: None,
column: false,
ink: vec![],
gaps: vec![],
}
}
/// Add glyph `text` set vertically (`upright`) if it continues this column (or makes this
@@ -171,6 +205,7 @@ impl TextLine {
if self.column || self.upright.is_some() {
return false;
}
let bytes: usize = self.runs.iter().map(|(_, t)| t.len()).sum();
if let Some((last, run)) = self.runs.last_mut() {
let size = self.at.size.max(at.size);
let gap = (at.origin - self.next).dot(self.last_dir);
@@ -192,6 +227,9 @@ impl TextLine {
// A gap wider than a fifth of an em reads as a space.
if gap > size * 0.2 && !run.ends_with(' ') && !text.starts_with(' ') {
run.push(' ');
if on_line {
self.gaps.push((bytes, gap));
}
}
if last.takes(look) {
run.push_str(text);
@@ -202,6 +240,9 @@ impl TextLine {
self.runs.push((look.clone(), text.to_string()));
}
self.next = at.origin + at.dir * advance;
if !text.trim().is_empty() {
self.visible = self.next;
}
self.last = at.origin;
self.last_dir = at.dir;
self.baseline.push(at.origin);
@@ -247,10 +288,12 @@ impl TextLine {
true
}
/// The point type object and its opacity.
pub fn finish(mut self) -> Option<(TextObject, f32)> {
/// The point type object, its opacity and what else the line tells.
pub fn finish(mut self) -> Option<(TextObject, f32, LineFacts)> {
let mut facts = LineFacts { ink: std::mem::take(&mut self.ink), ..LineFacts::default() };
// Turned along a curve: type on a path through the glyphs.
let path = if self.curved() { self.baseline_path() } else { None };
facts.wraps = path.is_none() && self.upright.is_none() && self.runs.last().is_some_and(|(_, t)| t.ends_with(' '));
if let Some((_, last)) = self.runs.last_mut() {
last.truncate(last.trim_end().len());
}
@@ -272,7 +315,7 @@ impl TextLine {
t.kind = TextKind::OnPath { path: vectorcraft_geom::PathData::from_bezpath(&path), start: 0.0, end: None };
t.xf = Affine::IDENTITY;
t.cached_bounds = Some(vectorcraft_text::layout(db, &t).bounds);
return Some((t, self.opacity));
return Some((t, self.opacity, facts));
}
let (start, along) = match self.upright {
// Vertical point type (a column, or a single upright glyph) is anchored at the top
@@ -286,26 +329,87 @@ impl TextLine {
};
// Tracking that makes the line as long as in the file: the PDF placed each glyph, the
// layout sets them by their advances. Spread over the gaps between characters (tracking
// follows each character, the last one's past the end of the line).
let length = (self.next - start).dot(along);
// follows each character, the last one's past the end of the line). A horizontal line is
// measured to its last glyph that isn't a space: the spaces after it were dropped.
let length = (if t.vertical { self.next } else { self.visible } - start).dot(along);
if !t.vertical {
facts.length = length;
}
let laid = vectorcraft_text::layout(db, &t);
let natural: f64 = laid.glyphs.iter().map(|g| g.advance).sum();
let chars: usize = t.runs.iter().map(|r| r.text.chars().count()).sum();
let size = self.at.size;
let mut bounds = laid.bounds;
if chars > 1 && length.is_finite() && (length - natural).abs() > size * 0.01 {
let tracking = ((length - natural) / (chars - 1) as f64 / size * 1000.0).clamp(-1000.0, 1000.0).round();
for r in &mut t.runs {
r.style.tracking = tracking;
}
// The spaces read from gaps keep their own place only in text left in the file's order.
let total: usize = t.runs.iter().map(|r| r.text.len()).sum();
let gaps: Vec<(usize, f64)> =
if t.para.direction.is_none() { self.gaps.into_iter().filter(|(b, _)| *b < total).collect() } else { vec![] };
let (tracking, spaces) = spacing(&laid, &gaps, length - natural, chars, size);
t.runs = tracked(std::mem::take(&mut t.runs), tracking, &spaces);
// Tracked: laid out again for its bounds.
bounds = vectorcraft_text::layout(db, &t).bounds;
}
t.cached_bounds = Some(bounds);
Some((t, self.opacity))
Some((t, self.opacity, facts))
}
}
/// The tracking (thousandths of an em) that sets a line of `chars` characters, laid out untracked
/// as `laid`, `extra` points longer, as the file set it: the same after every character, except
/// the spaces read from gaps (`gaps`: byte offset, gap in points) where that would put the glyphs
/// after them more than a tenth of an em off (a barcode's digits, set in groups apart). Those take
/// their own tracking, given with their byte offsets.
fn spacing(laid: &TextLayout, gaps: &[(usize, f64)], extra: f64, chars: usize, size: f64) -> (f64, Vec<(usize, f64)>) {
let pairs = chars.saturating_sub(1).max(1) as f64;
// The space and the character before it take `need` (the gap less the space) between them;
// tracking gives them twice its share.
let space = |b: usize| laid.glyphs.iter().find(|g| g.byte == b).map(|g| g.advance);
let needs: Vec<(usize, f64)> = gaps.iter().filter_map(|&(b, gap)| Some((b, gap - space(b)?))).collect();
let mut own: Vec<(usize, f64)> = vec![];
let mut tracking = extra / pairs;
// Each space taken apart changes the others' share: until no more are.
loop {
let more: Vec<(usize, f64)> =
needs.iter().filter(|(b, need)| !own.iter().any(|(o, _)| o == b) && (need - 2.0 * tracking).abs() > size * 0.1).copied().collect();
if more.is_empty() {
break;
}
own.extend(more);
let rest = pairs - 2.0 * own.len() as f64;
tracking = if rest >= 1.0 { (extra - own.iter().map(|(_, need)| need).sum::<f64>()) / rest } else { 0.0 };
}
own.sort_by_key(|(b, _)| *b);
let em = |pts: f64| (pts / size * 1000.0).clamp(-1000.0, 1000.0).round();
(em(tracking), own.into_iter().map(|(b, need)| (b, em(need - tracking))).collect())
}
/// `runs` with tracking `tracking`, and each space at a byte offset of `spaces` (in order) a run
/// of its own with the tracking given with it.
fn tracked(runs: Vec<TextRun>, tracking: f64, spaces: &[(usize, f64)]) -> Vec<TextRun> {
let mut out = Vec::with_capacity(runs.len() + 2 * spaces.len());
let mut off = 0;
for r in runs {
let style = CharStyle { tracking, ..r.style };
let end = off + r.text.len();
let mut from = 0;
for &(b, own) in spaces.iter().filter(|(b, _)| (off..end).contains(b)) {
let at = b - off;
let (Some(before), Some(space)) = (r.text.get(from..at), r.text.get(at..at + 1)) else { continue };
if !before.is_empty() {
out.push(TextRun { text: before.to_string(), style: style.clone() });
}
out.push(TextRun { text: space.to_string(), style: CharStyle { tracking: own, ..style.clone() } });
from = at + 1;
}
if let Some(rest) = r.text.get(from..).filter(|t| !t.is_empty()) {
out.push(TextRun { text: rest.to_string(), style });
}
off = end;
}
out
}
fn round(v: f64) -> f64 {
(v * 1000.0).round() / 1000.0
}
+3
View File
@@ -48,6 +48,7 @@ mod images;
mod import;
mod import_color;
mod import_image;
mod import_lines;
mod import_mask;
mod import_scan;
mod import_shading;
@@ -231,6 +232,8 @@ mod tests_import_fidelity;
#[cfg(test)]
mod tests_import_layers;
#[cfg(test)]
mod tests_import_lines;
#[cfg(test)]
mod tests_import_options;
#[cfg(test)]
mod tests_layers;
+5 -3
View File
@@ -242,11 +242,13 @@ fn text_becomes_point_type() {
// The baseline origin, in y-down page space.
let o = t[0].xf * kurbo::Point::ORIGIN;
assert!((o.x - 10.0).abs() < 0.01 && (o.y - 70.0).abs() < 0.01, "{o:?}");
// A gap of an em between words reads as a space; another font on the line is another run.
// A gap of an em between words reads as a space, tracked on its own to keep the gap's width
// (#508); another font on the line is another run.
assert_eq!(text(&t[1]), "Next line in bold");
let runs: Vec<(&str, &str)> = t[1].runs.iter().map(|r| (r.text.as_str(), r.style.font_style.as_str())).collect();
assert_eq!(runs, [("Next line", "Regular"), (" in bold", "Bold")]);
assert_eq!(t[1].runs[1].style.fill.color(), Some(Color::rgb(0.0, 0.0, 1.0)));
assert_eq!(runs, [("Next", "Regular"), (" ", "Regular"), ("line", "Regular"), (" in bold", "Bold")]);
assert!(t[1].runs[1].style.tracking > t[1].runs[0].style.tracking + 100.0, "{:?}", t[1].runs);
assert_eq!(t[1].runs[3].style.fill.color(), Some(Color::rgb(0.0, 0.0, 1.0)));
assert!(!r.warnings.iter().any(|w| w.contains("outlines")), "{:?}", r.warnings);
// As outlines: paths, no type.
let r = open_with(&bytes, |o| o.text_as = TextAs::Outlines);
+203
View File
@@ -0,0 +1,203 @@
//! What a file's lines of type were (#508): the layer art ending a group's marked content belongs
//! to, layers ordered as the pages mark them, a stroke written as stroked glyph outlines, spaces
//! read from wide gaps, and lines wrapped in a frame rebuilt as area type.
use kurbo::{BezPath, PathEl, Point, Shape};
use serde_json::json;
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{AppearanceItem, CharStyle, Document, Justify, Node, NodeKind, TextKind, TextObject};
use vectorcraft_geom::{Affine, Rect, shapes};
use vectorcraft_testkit::pdf::{PdfPage, first_extra, pdf_with_catalog};
use crate::*;
const HELVETICA: &str = "/Font << /F1 << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> >>";
/// Groups "A" and "B" (A painted first) for a file of `pages` pages, and the catalog entries.
fn groups(pages: usize) -> ([String; 2], String, String) {
let (a, b) = (first_extra(pages), first_extra(pages) + 1);
let objs = ["<< /Type /OCG /Name (A) >>".to_string(), "<< /Type /OCG /Name (B) >>".to_string()];
let catalog = format!("/OCProperties << /OCGs [{a} 0 R {b} 0 R] /D << /Order [{b} 0 R {a} 0 R] >> >> ");
let resources = format!("/Properties << /MC0 {a} 0 R /MC1 {b} 0 R >> {HELVETICA}");
(objs, catalog, resources)
}
/// A file of 100 × 100 pt pages drawing `contents`, with groups A (`/MC0`) and B (`/MC1`).
fn layered(contents: &[&str]) -> Document {
let (objs, catalog, resources) = groups(contents.len());
let pages: Vec<PdfPage> = contents.iter().map(|c| PdfPage { resources: resources.clone(), ..PdfPage::new(100.0, 100.0, c) }).collect();
import(&pdf_with_catalog(&pages, &[&objs[0], &objs[1]], &catalog, None)).unwrap()
}
/// The layers' names, bottom first, and the kinds of their art.
fn layers(d: &Document) -> Vec<(String, Vec<&'static str>)> {
let kind = |n: &std::sync::Arc<Node>| match n.kind {
NodeKind::Text(_) => "text",
NodeKind::Group { .. } => "group",
_ => "path",
};
d.layers.iter().map(|l| (l.name.clone().unwrap_or_default(), l.children().map_or(vec![], |c| c.iter().map(kind).collect()))).collect()
}
fn texts(d: &Document) -> Vec<TextObject> {
let mut v = vec![];
d.walk(|n| {
if let NodeKind::Text(t) = &n.kind {
v.push((**t).clone());
}
});
v
}
fn named(layers: &[(&str, &[&'static str])]) -> Vec<(String, Vec<&'static str>)> {
layers.iter().map(|(n, k)| (n.to_string(), k.to_vec())).collect()
}
#[test]
fn type_ending_a_layers_marked_content_stays_in_its_layer() {
// The line is still being gathered when the group's sequence ends.
let d = layered(&["/OC /MC0 BDC 0 0 1 rg 0 0 10 10 re f BT /F1 12 Tf 10 50 Td (Lead) Tj ET EMC /OC /MC1 BDC EMC"]);
assert_eq!(layers(&d), named(&[("A", &["path", "text"]), ("B", &[])]));
}
#[test]
fn a_clip_ending_in_a_later_group_stays_with_its_art() {
// The clip opens in A, its art is drawn in A, and it closes after B's (empty) sequence.
let d = layered(&["/OC /MC0 BDC q 0 0 50 50 re W n 1 0 0 rg 40 40 20 20 re f EMC /OC /MC1 BDC EMC Q"]);
assert_eq!(layers(&d), named(&[("A", &["group"]), ("B", &[])]));
}
#[test]
fn layers_stack_as_the_pages_mark_them_when_one_first_paints_on_a_later_page() {
// A, the bottom layer, is empty on page 1 and has art on page 2 only.
let d = layered(&["/OC /MC0 BDC EMC /OC /MC1 BDC 1 0 0 rg 0 0 10 10 re f EMC", "/OC /MC0 BDC 0 0 1 rg 0 0 10 10 re f EMC /OC /MC1 BDC EMC"]);
assert_eq!(layers(&d), named(&[("A", &["path"]), ("B", &["path"])]));
// A group marked with no art on any page is an empty layer in its place.
let d = layered(&["/OC /MC0 BDC EMC /OC /MC1 BDC 1 0 0 rg 0 0 10 10 re f EMC"]);
assert_eq!(layers(&d), named(&[("A", &[]), ("B", &["path"])]));
}
/// A 100 × 100 pt page drawing `content` in Helvetica.
fn page(content: &str) -> Vec<u8> {
vectorcraft_testkit::pdf::pdf(&[PdfPage { resources: HELVETICA.into(), ..PdfPage::new(100.0, 100.0, content) }], None)
}
/// The outline of glyph `c` drawn at 24 pt from (x, 50), in PDF operators (y up), stroked.
fn outline(c: char, x: f64) -> String {
let opts = ImportOptions { text_as: TextAs::Outlines, ..Default::default() };
let d = import_with_report(&page(&format!("BT /F1 24 Tf {x} 50 Td ({c}) Tj ET")), &opts).unwrap().document;
let mut p: Option<BezPath> = None;
d.walk(|n| {
if let NodeKind::Path { path, .. } = &n.kind {
p = Some(path.to_bezpath());
}
});
let pt = |q: Point| format!("{:.3} {:.3}", q.x, 100.0 - q.y);
let ops: String = p
.unwrap()
.elements()
.iter()
.map(|e| match e {
PathEl::MoveTo(a) => format!("{} m ", pt(*a)),
PathEl::LineTo(a) => format!("{} l ", pt(*a)),
PathEl::QuadTo(a, b) => format!("{} {} {} c ", pt(*a), pt(*b), pt(*b)),
PathEl::CurveTo(a, b, c) => format!("{} {} {} c ", pt(*a), pt(*b), pt(*c)),
PathEl::ClosePath => "h ".into(),
})
.collect();
ops + "S "
}
#[test]
fn a_stroke_written_as_stroked_glyph_outlines_is_the_types_stroke() {
// "Hi": the H is 722 units wide in Helvetica.
let strokes = format!("0 0 1 RG 0.5 w {}{}", outline('H', 10.0), outline('i', 10.0 + 0.722 * 24.0));
let text = "BT 1 0 0 rg /F1 24 Tf 10 50 Td (Hi) Tj ET ";
for (content, below) in [(format!("{text}{strokes}"), false), (format!("{strokes}{text}"), true)] {
let d = import(&page(&content)).unwrap();
let art = d.layers[0].children().unwrap();
assert_eq!(art.len(), 1, "one object: {art:?}");
let NodeKind::Text(t) = &art[0].kind else { panic!("{:?}", art[0].kind) };
assert_eq!(t.plain_text(), "Hi");
assert_eq!(t.first_style().fill.color(), Some(Color::rgb(1.0, 0.0, 0.0)));
let ap = &art[0].appearance;
let [AppearanceItem::Stroke(st)] = ap.items.as_slice() else { panic!("{ap:?}") };
assert_eq!(st.paint.color(), Some(Color::rgb(0.0, 0.0, 1.0)));
assert!((st.width - 0.5).abs() < 1e-6);
assert_eq!(ap.contents_at(), usize::from(below), "a stroke drawn first paints below the characters");
}
// A stroke that isn't on the glyphs stays a path.
let d = import(&page(&format!("{text}0 0 1 RG 0.5 w {}", outline('H', 40.0)))).unwrap();
assert_eq!(d.layers[0].children().unwrap().len(), 2);
}
/// A 300 × 200 pt page with `lines` of (x, y from the top, size, text) in Source Sans 3.
fn source_sans(lines: &[(f32, f32, f32, &str)]) -> Vec<u8> {
crate::tests_live_text::text_pdf(lines, false)
}
#[test]
fn spaces_read_from_wide_gaps_keep_the_glyphs_after_them_in_place() {
// A barcode's digits in three groups, set apart by more than a space.
let (x1, x2) = (29.0, 69.0);
let bytes = source_sans(&[(20.0, 50.0, 10.0, "3"), (x1, 50.0, 10.0, "533121"), (x2, 50.0, 10.0, "010629")]);
let t = texts(&import(&bytes).unwrap());
assert_eq!(t.len(), 1);
assert_eq!(t[0].plain_text(), "3 533121 010629");
let laid = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t[0]);
let at = |byte: usize| (t[0].xf * laid.glyphs.iter().find(|g| g.byte == byte).unwrap().origin).x;
assert!((at(2) - f64::from(x1)).abs() < 0.05, "the second group starts where the file has it: {} vs {x1}", at(2));
assert!((at(9) - f64::from(x2)).abs() < 0.05, "the third group starts where the file has it: {} vs {x2}", at(9));
}
/// A document of area type `text` (Source Sans 3, 10 pt) `width` wide at (20, 30).
fn area_doc(text: &str, justify: Justify, width: f64, space_before: f64) -> Document {
let style = CharStyle { size: 10.0, fill: Paint::solid(Color::BLACK), ..Default::default() };
let mut t = TextObject::point(Point::ORIGIN, text, style);
t.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, width, 200.0)) };
t.xf = Affine::translate((20.0, 30.0));
t.para.justify = justify;
t.para.space_before = space_before;
let mut d = Document::new(300.0, 300.0);
let l = d.layers[0].id;
let n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t)));
d.insert(Some(l), 0, n).unwrap();
d
}
/// `d` exported (real text) and imported again.
fn round_trip(d: &Document) -> Document {
let settings: PdfSettings = serde_json::from_value(json!({"compression": {"compressText": false}, "advanced": {"outlineText": false}})).unwrap();
let bytes = export_with_report(d, &PdfOptions { settings, ..Default::default() }).unwrap().bytes;
import(&bytes).unwrap()
}
const PROSE: &str = "Stop losing your sinkers on the cast: the clip holds the lead until a snag pulls it free, \
so the fish swims on without the weight.\nIt works on every running rig and leaves the line clear.";
#[test]
fn lines_wrapped_in_a_frame_come_back_as_area_type() {
for (justify, space) in [(Justify::Left, 0.0), (Justify::JustifyLeft, 4.0)] {
let d = round_trip(&area_doc(PROSE, justify, 120.0, space));
let t = texts(&d);
assert_eq!(t.len(), 1, "{justify:?}: one object, not a line each: {:?}", t.iter().map(TextObject::plain_text).collect::<Vec<_>>());
assert_eq!(t[0].plain_text(), PROSE);
assert_eq!(t[0].para.justify, justify);
assert!((t[0].para.space_before - space).abs() < 0.01, "{}", t[0].para.space_before);
let TextKind::Area { frame } = &t[0].kind else { panic!("{:?}", t[0].kind) };
let w = frame.to_bezpath().bounding_box().width();
assert!(w <= 120.5 && w > 100.0, "{w}");
let origin = t[0].xf * Point::ZERO;
assert!((origin.x - 20.0).abs() < 0.05, "{origin:?}");
}
}
#[test]
fn lines_that_were_not_wrapped_stay_point_type() {
// A list: each line its own, none ending in a space.
let bytes = source_sans(&[(20.0, 50.0, 10.0, "Hooks"), (20.0, 62.0, 10.0, "Swivels"), (20.0, 74.0, 10.0, "Leads")]);
assert_eq!(texts(&import(&bytes).unwrap()).len(), 3);
// Wrapped lines whose breaks a frame doesn't give again (a line far short of the others).
let bytes = source_sans(&[(20.0, 50.0, 10.0, "One two three four five six "), (20.0, 62.0, 10.0, "a "), (20.0, 74.0, 10.0, "seven")]);
assert_eq!(texts(&import(&bytes).unwrap()).len(), 3);
}
+3 -3
View File
@@ -13,7 +13,7 @@ const SOURCE_SERIF: &[u8] = include_bytes!("../../../assets/fonts/SourceSerif4-R
/// A 300 × 200 pt page with `lines` of (x, y from the top, size, text) in Source Sans 3, and the
/// same rotated 90° when `rotated`.
fn text_pdf(lines: &[(f32, f32, f32, &str)], rotated: bool) -> Vec<u8> {
pub(crate) fn text_pdf(lines: &[(f32, f32, f32, &str)], rotated: bool) -> Vec<u8> {
let mut pdf = krilla::Document::new();
let mut page = pdf.start_page_with(PageSettings::from_wh(300.0, 200.0).unwrap());
let mut s = page.surface();
@@ -269,7 +269,7 @@ fn a_single_upright_glyph_comes_in_as_vertical_type_and_takes_no_horizontal_glyp
let mut line = TextLine::new(at(100.0, 100.0), 1.0);
assert!(line.push_upright(&look, at(100.0, 100.0), 1.0, Upright { top: Point::new(110.0, 82.0) }, "§"));
assert!(!line.push(&look, at(130.0, 100.0), 1.0, 10.0, "a"), "a horizontal glyph starts another line");
let (t, _) = line.finish().unwrap();
let (t, ..) = line.finish().unwrap();
assert!(t.vertical, "one upright glyph is vertical type");
assert_eq!(t.plain_text(), "§");
}
@@ -294,7 +294,7 @@ fn letter_spaced_vertical_type_keeps_its_characters_together() {
let y = 100.0 + 30.0 * i as f64;
assert!(line.push_upright(&look, at(y), 1.0, Upright { top: Point::new(110.0, y - 18.0) }, c));
}
let (t, _) = line.finish().unwrap();
let (t, ..) = line.finish().unwrap();
assert!(t.vertical);
assert_eq!(t.plain_text(), "§§§", "letter spacing isn't a space");
}
+2 -4
View File
@@ -139,10 +139,8 @@ impl Manifest {
return Err(Error::Manifest(format!("invalid parameter name {k:?}")));
}
match spec {
ParamSpec::Number { min, max, default } => {
if !(min.is_finite() && max.is_finite() && default.is_finite()) || min > max {
return Err(Error::Manifest(format!("parameter `{k}`: bad range")));
}
ParamSpec::Number { min, max, default } if !(min.is_finite() && max.is_finite() && default.is_finite()) || min > max => {
return Err(Error::Manifest(format!("parameter `{k}`: bad range")));
}
ParamSpec::Int { min, max, .. } if min > max => return Err(Error::Manifest(format!("parameter `{k}`: bad range"))),
ParamSpec::Choice { options, default } => {
+27 -1
View File
@@ -15,6 +15,7 @@ mod ink;
mod live;
mod paint;
mod pattern;
pub mod placed_document;
pub mod proof;
use std::collections::HashMap;
@@ -96,6 +97,9 @@ pub struct RenderOptions {
pub highlight_substitutions: bool,
/// Edge smoothing (raster export option).
pub anti_alias: AntiAlias,
/// Screen view: placed documents draw from cached bitmaps made in the background (see
/// [`placed_document`]); off, they draw exactly, read when needed.
pub progressive_placed: bool,
}
/// How edges are rasterized (raster export option).
@@ -160,6 +164,7 @@ impl Default for RenderOptions {
mask_view: None,
highlight_substitutions: false,
anti_alias: AntiAlias::Art,
progressive_placed: false,
}
}
}
@@ -580,6 +585,23 @@ impl Renderer {
self.render_node_thumbnail(doc, doc.node(id)?, size, None)
}
/// Render node `n` of `doc` (its resources) into `w`×`h` transparent pixels through `view`.
pub fn render_node(&mut self, doc: &Document, n: &Arc<Node>, w: u16, h: u16, view: Affine) -> Option<Rendered> {
let inv = view.inverse();
let visible = inv.transform_rect_bbox(Rect::new(0.0, 0.0, w as f64, h as f64));
let px = 1.0 / view.determinant().abs().sqrt().max(1e-12);
let mut ctx = single_threaded_context(w, h);
let opts = RenderOptions::default();
let frame = Frame { mt: false, doc, view, visible, px, opts: &opts, ink: Ink::Display };
(self.knockout, self.nested, self.backdrop) = (false, 0, None);
self.clip_paths.clear();
self.draw_arc(&mut ctx, &frame, n);
ctx.flush();
let mut pm = Pixmap::new(w, h);
ctx.render(&mut pm, &mut self.resources);
Some(Rendered { width: w as u32, height: h as u32, pixels: pm.data_as_u8_slice().to_vec() })
}
/// Render any node (also one outside the tree, e.g. opacity-mask art) fitted into
/// `size`×`size` pixels, optionally over a solid premultiplied background.
pub fn render_node_thumbnail(&mut self, doc: &Document, n: &Node, size: u32, background: Option<[u8; 4]>) -> Option<Rendered> {
@@ -916,7 +938,9 @@ impl Renderer {
self.draw_node(ctx, f, &art, true);
}
}
NodeKind::Blend { .. } | NodeKind::Envelope { .. } | NodeKind::Mesh(_) | NodeKind::Repeat(_) => self.draw_live_node(ctx, f, n),
NodeKind::Blend { .. } | NodeKind::Envelope { .. } | NodeKind::Mesh(_) | NodeKind::Repeat(_) | NodeKind::PlacedDocument(_) => {
self.draw_live_node(ctx, f, n)
}
}
}
@@ -1649,6 +1673,8 @@ mod tests_layeropts;
#[cfg(test)]
mod tests_objectfx;
#[cfg(test)]
mod tests_placed_document;
#[cfg(test)]
mod tests_setup;
#[cfg(test)]
mod tests_strokegradient;
+1
View File
@@ -143,6 +143,7 @@ impl Renderer {
/// Draw the evaluated content of a live node (no transparency group).
pub(crate) fn draw_live_body(&mut self, ctx: &mut RenderContext, f: &Frame, a: &Arc<Node>, cache: bool) {
match &a.kind {
NodeKind::PlacedDocument(p) => self.draw_placed(ctx, f, p),
NodeKind::Mesh(m) => self.draw_mesh(ctx, f, a, m, cache),
NodeKind::Blend { .. } | NodeKind::Envelope { .. } | NodeKind::Repeat(_) | NodeKind::Group { .. } | NodeKind::Layer { .. } => {
let items = self.live_expanded(f.doc, a, cache);
Loaded 100 of 192 files, more files were not shown because too many files have changed in this diff. Show more