Compare commits
41
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ba93f62bcb | ||
|
|
28846a98a0 | ||
|
|
4051a895d7 | ||
|
|
1e2cb082ba | ||
|
|
207bd09635 | ||
|
|
2023a47188 | ||
|
|
85319c972c | ||
|
|
94ecbec9fc | ||
|
|
cb61bdf61f | ||
|
|
d1d78e61da | ||
|
|
c26c4a2060 | ||
|
|
5e7af3f83c | ||
|
|
2418921760 | ||
|
|
e04b94938b | ||
|
|
afc45cdeb8 | ||
|
|
6d56195eda | ||
|
|
02072c310a | ||
|
|
92817d6ca1 | ||
|
|
857273001b | ||
|
|
48f07958a9 | ||
|
|
c6bea61ffc | ||
|
|
f31d6874aa | ||
|
|
c44572d272 | ||
|
|
1b43d8b8f9 | ||
|
|
2b321d240f | ||
|
|
2139c4d661 | ||
|
|
179a87d0a6 | ||
|
|
b832599a47 | ||
|
|
d7b4d85d3c | ||
|
|
af7a5239be | ||
|
|
c3279f1bcf | ||
|
|
4f07bd93b0 | ||
|
|
086d6287be | ||
|
|
0e6a47e72d | ||
|
|
f8004250fb | ||
|
|
03288f34dc | ||
|
|
aa4fa48751 | ||
|
|
165db95dd4 | ||
|
|
ac043129c8 | ||
|
|
8e753d746e | ||
|
|
b5759662c1 |
No files matched your search
Generated
+25
-25
@@ -4296,7 +4296,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft"
|
||||
version = "0.6.0"
|
||||
version = "0.7.0"
|
||||
dependencies = [
|
||||
"arboard",
|
||||
"block2 0.6.2",
|
||||
@@ -4320,7 +4320,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-brush"
|
||||
version = "0.6.0"
|
||||
version = "0.7.0"
|
||||
dependencies = [
|
||||
"kurbo 0.13.1",
|
||||
"serde",
|
||||
@@ -4332,7 +4332,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-cad"
|
||||
version = "0.6.0"
|
||||
version = "0.7.0"
|
||||
dependencies = [
|
||||
"image",
|
||||
"kurbo 0.13.1",
|
||||
@@ -4348,7 +4348,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-cli"
|
||||
version = "0.6.0"
|
||||
version = "0.7.0"
|
||||
dependencies = [
|
||||
"serde_json",
|
||||
"vectorcraft-color",
|
||||
@@ -4364,7 +4364,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-color"
|
||||
version = "0.6.0"
|
||||
version = "0.7.0"
|
||||
dependencies = [
|
||||
"kurbo 0.13.1",
|
||||
"moxcms",
|
||||
@@ -4376,7 +4376,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-doc"
|
||||
version = "0.6.0"
|
||||
version = "0.7.0"
|
||||
dependencies = [
|
||||
"image",
|
||||
"jpeg-encoder",
|
||||
@@ -4393,7 +4393,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-effects"
|
||||
version = "0.6.0"
|
||||
version = "0.7.0"
|
||||
dependencies = [
|
||||
"kurbo 0.13.1",
|
||||
"serde_json",
|
||||
@@ -4407,7 +4407,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-engine"
|
||||
version = "0.6.0"
|
||||
version = "0.7.0"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"image",
|
||||
@@ -4439,7 +4439,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-eps"
|
||||
version = "0.6.0"
|
||||
version = "0.7.0"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"image",
|
||||
@@ -4457,7 +4457,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-format"
|
||||
version = "0.6.0"
|
||||
version = "0.7.0"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"proptest",
|
||||
@@ -4471,7 +4471,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-geom"
|
||||
version = "0.6.0"
|
||||
version = "0.7.0"
|
||||
dependencies = [
|
||||
"kurbo 0.13.1",
|
||||
"proptest",
|
||||
@@ -4483,7 +4483,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-mcp"
|
||||
version = "0.6.0"
|
||||
version = "0.7.0"
|
||||
dependencies = [
|
||||
"image",
|
||||
"log",
|
||||
@@ -4502,7 +4502,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-metafile"
|
||||
version = "0.6.0"
|
||||
version = "0.7.0"
|
||||
dependencies = [
|
||||
"image",
|
||||
"kurbo 0.13.1",
|
||||
@@ -4516,7 +4516,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-pathops"
|
||||
version = "0.6.0"
|
||||
version = "0.7.0"
|
||||
dependencies = [
|
||||
"kurbo 0.13.1",
|
||||
"linesweeper",
|
||||
@@ -4528,7 +4528,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-pdf"
|
||||
version = "0.6.0"
|
||||
version = "0.7.0"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"flate2",
|
||||
@@ -4557,7 +4557,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-plugins"
|
||||
version = "0.6.0"
|
||||
version = "0.7.0"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -4571,7 +4571,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-render"
|
||||
version = "0.6.0"
|
||||
version = "0.7.0"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"gif",
|
||||
@@ -4596,7 +4596,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-svg"
|
||||
version = "0.6.0"
|
||||
version = "0.7.0"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"image",
|
||||
@@ -4620,7 +4620,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-testkit"
|
||||
version = "0.6.0"
|
||||
version = "0.7.0"
|
||||
dependencies = [
|
||||
"image",
|
||||
"kurbo 0.13.1",
|
||||
@@ -4637,7 +4637,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-text"
|
||||
version = "0.6.0"
|
||||
version = "0.7.0"
|
||||
dependencies = [
|
||||
"harfrust 0.13.3",
|
||||
"kurbo 0.13.1",
|
||||
@@ -4655,7 +4655,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-tools"
|
||||
version = "0.6.0"
|
||||
version = "0.7.0"
|
||||
dependencies = [
|
||||
"image",
|
||||
"kurbo 0.13.1",
|
||||
@@ -4670,7 +4670,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-trace"
|
||||
version = "0.6.0"
|
||||
version = "0.7.0"
|
||||
dependencies = [
|
||||
"image",
|
||||
"kurbo 0.13.1",
|
||||
@@ -4683,7 +4683,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-ui-egui"
|
||||
version = "0.6.0"
|
||||
version = "0.7.0"
|
||||
dependencies = [
|
||||
"egui",
|
||||
"egui_extras",
|
||||
@@ -4712,7 +4712,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-web"
|
||||
version = "0.6.0"
|
||||
version = "0.7.0"
|
||||
dependencies = [
|
||||
"eframe",
|
||||
"egui",
|
||||
@@ -5815,7 +5815,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee"
|
||||
|
||||
[[package]]
|
||||
name = "xtask"
|
||||
version = "0.6.0"
|
||||
version = "0.7.0"
|
||||
dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"]
|
||||
default-members = ["crates/*", "apps/vectorcraft", "apps/vectorcraft-cli", "xtask"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.6.0"
|
||||
version = "0.7.0"
|
||||
edition = "2024"
|
||||
license = "MIT OR Apache-2.0"
|
||||
rust-version = "1.95"
|
||||
|
||||
+11
-9
@@ -4,7 +4,7 @@ VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adob
|
||||
|
||||
This file tracks **how far we are and what's left**. Time estimates are wall-clock hours of continuous Claude Opus 5.5 agent work (including builds and the CI gate), given both for **one agent** and for **4–6 parallel agents** on disjoint crates. They are counted from the remaining work (see [Parity estimate](#parity-estimate)), calibrated against measured throughput, and updated as work lands.
|
||||
|
||||
_Last updated: 2026-10-09 (after 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 window (#493), panels, panel groups and the Tools panel undocking into flLine truncated
|
||||
_Last updated: 2026-10-09 (after placed documents (File › Place of a `.vectorcraft` file, linked), M4.14–M4.98, M8.1–M8.20, M14.4–M14.7, the MCP prompts, resource templates, completions and logging, the 2026-10-07 issue fixes, the Layers panel rework and the 2026-10-08 community contributions: Pen and shape-tool modifiers, path editing, Layers, Artboards, Swatches/Brushes and dialogs, Japanese composition and PDF text, Hebrew/Arabic type, interface languages (Spanish among them), the font menu, saved selections, MCP and EPS, the missing-font export warning (#319), open paths in the Shape Builder (#374), PDF/`.ai` import keeping strokes live and hidden and nested layers (#372), per-corner Live Corners (#381), SVG type opening at the size it draws at (#396), the Wayland clipboard with copied-file paste (#398), ruler guides that can be selected, moved and deleted (#414), two batches of Preferences options that were stored but unused (#394), skeleton reads with `document.find` for large documents over MCP (#416) and anchors dragged with Direct Selection snapping to points, segments and smart guides, clipped SVG layers opening as clipping layers (#420), PDF/`.ai` layers read on pages of tens of millions of operators (#419), Document Color Mode putting RGB greys on the black plate on request and converting pattern tiles (#421) and movable dialogs with Offset Path's Joins dropdown (#423) and numeric fields scrubbed by dragging their label (#400), stroke weight presets in the stroke unit (#426), the Appearance panel's Opacity popup (#430), type on a path brackets, flip and Type on a Path Options that keep the type in place (#429), Layers rows dragged with a ghost and dropped on the trash or New Layer (#435), tool flyouts opening on a right or corner press (#436), tool flyouts torn off into floating toolbars (#437), the Shape Builder's erase mode deleting edges too (#439), installed fonts registered outside the font folders and fonts installed while the app runs listed in the font menus (#443), alike circular corners on rectangles that aren't square (#442), tool cursors as OS cursors so the pointer no longer trails over the canvas (#444), artboards copied and pasted with their art (#446), guides dragged out of the rulers snapping to the art's side midpoints and the artboards, artboard guides (#451), the toolbar's double arrow and Window › Toolbars › Double Column switching between one and two columns in any window height (#455), the Smart Guides display options and Snapping Tolerance (#394), Font Size and Leading combo boxes with preset lists in the Character and Properties panels and the Control bar (#458), screenshots pasted from the clipboard on macOS, Windows and the web (#457), the Properties panel's Fill and Stroke matching the Control bar's, Illustrator's Window menu panel keys (Shift+F7 for Align…) and Alt-wheel zoom whatever the wheel preference (Discord feedback), the point/area type widget (Discord feedback), groups in legacy Illustrator .ai files (Discord feedback), a rotating desktop log file (#465), image controls in the Control bar and Properties panel: Image Trace with its presets, Mask, Crop Image, Embed/Unembed, and an Image Trace object's preset, Expand and Release (Discord feedback), the Pen working as the Anchor Point tool with Alt held over a selected path's handles and anchors, and anchor buttons that convert, connect and cut paths at the selected anchors (Discord feedback), Japanese hanging punctuation (burasagari, #463), Escape leaving Presentation Mode with no screen mode saved across restarts, documents dropped on the desktop app opening as tabs of their own and a note that an `.ai` file's art off its artboards isn't in the part read (#472), Add/Delete Anchor Point tool icons drawn from the Pen tool's (#479), EPS import running more of PostScript Level 3 (patterns, Type 3 fonts, mesh shadings, masked images, VM and resource probes), and a preview that stands in saying why (Discord feedback, #466, #469, #474), chords with modifiers recorded in Edit › Keyboard Shortcuts (#487), Type Object Selection by Path Only (#394), Anti-aliased Artwork (#394), Show Pixel Grid (#394), pen and touch taps pressed and lifted within one frame clicking where they tapped and the Linux/Wayland pen-tablet workaround (#491), bounding-box resizes landing on the other objects' anchors and centres with labels, and the Rotate, Scale, Shear and Reflect tools snapping their drags (#482), Shift-drag marquees that toggle the objects or anchors they reach and a Lasso whose Alt subtraction keeps the rest of the selection (#483), the mouse wheel stepping the focused numeric field, the dialogs' and preferences' drag values made such fields (#485), Show The Home Screen When No Documents Are Open (#394), Numbers Without Units Are Points (#394), Auto-Collapse Iconic Panels (#394), the Contextual Task Bar moved by its handle and its More Options menu pinning and resetting its position, a designed macOS DMG windoLine truncated
|
||||
|
||||
## Where we are
|
||||
|
||||
@@ -42,7 +42,7 @@ since 2026-10-01.
|
||||
| **Bundled content:** brush, symbol, style and swatch libraries | ~30% | Ours are original and generated in code, and far fewer than Illustrator ships; brush and symbol libraries are still missing |
|
||||
| **Performance** | unverified | Multithreaded, off-thread rendering and caches are in place. The last budget run (2026-10-01, loaded machine) measured 290 ms for a 50k-path fit against a 16 ms budget. Re-run `vectorcraft-cli perf` on an idle machine |
|
||||
| **Robustness** | good, new | ~2,840 tests, property tests, no panics in shipped code (lints, the `guard` safety net, import fuzzing), Data Recovery. Missing: a corpus of real-world files, Windows/Linux/browser QA |
|
||||
| **Platforms and 1.0 polish** | ~60% | The macOS app and the web build work, and Finder opens every readable format with the macOS app (#295, #354); on macOS the menus are in the system menu bar, laid out as a Mac app's, with the in-window menus as a fallback (`--in-window-menus`; verified on Windows and by cross-compilation, not yet by hand on a Mac); hybrid-graphics laptops render on the power-saving GPU by default on Windows and macOS (#306), and Linux on the GPU the desktop runs on, since a Wayland compositor may refuse frames from the other one; a window that fails on its GPU while starting up starts again on the next one instead of crashing (#502; the dual-GPU Wayland case is verified by unit tests and cross-compilation, not on such hardware); web drops land in the document they were dropped on (#359); desktop drops carry no pointer position (winit 0.30), so a dropped document opens as a tab of its own and a picture or text is placed in the middle of the view, while the web places anything dropped on the canvas and opens what is dropped off it, as Illustrator does (#472); a web page that loses its WebGPU device or WebGL context restarts its graphics with the same documents (#369); on Linux/Wayland the clipboard reads the compositor's own (data-control) and copied image files paste, but files can't be dropped on the window under Wayland until eframe moves to winit 0.31 (#398; the Wayland side is verified by compilation only); on Linux the Paste menu checks the system clipboard on a background thread, so a clipboard owner that never answers no longer freezes the window, while Windows and macOS keep their quick in-line check (#510; the X11 hang verified by the contributor, here by headless tests); on KDE Plasma 6.3+ under Wayland, pens and pen displays reach the app only under XWayland (`WAYLAND_DISPLAY=`) or with KWin's `KWIN_WAYLAND_EMULATE_TABLET=1`, since winit 0.30 has no Wayland tablet input (#491, not verified on hardware); Windows/Linux packaging and accessibility are pending; an experimental, unsupported Windows 7 x64 OpenGL build exists (community-contributed, not verified by maintainers) |
|
||||
| **Platforms and 1.0 polish** | ~60% | The macOS app and the web build work, and Finder opens every readable format with the macOS app (#295, #354); on macOS the menus are in the system menu bar, laid out as a Mac app's, with the in-window menus as a fallback (`--in-window-menus`; verified on Windows and by cross-compilation, not yet by hand on a Mac); hybrid-graphics laptops render on the power-saving GPU by default on Windows and macOS (#306), and Windows 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) |
|
||||
|
||||
@@ -102,7 +102,7 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist
|
||||
- Panels undock (#495): a dock tab, a panel icon or a popped-out panel's title dragged out of the dock floats that panel inside the window, and the strip right of the dock's tabs floats the whole tabbed group. A floating group moves by its title bar, a tab dragged out of it floats on its own, and dropped on another group's title bar or tabs it stacks with that group; dropped on the dock, which lights up under the pointer, its panels go back where they live (the tabbed group or the icon column), as its × and the panel menus' Float Panel / Dock Panel do (`window.panel.float`, `window.panel.dock`). The Tools panel floats by its title bar and docks again on the window's left edge. Floating panels and the Tools panel's position are kept with the preferences and in user workspaces, and clamped into a smaller window. Not done: panels in separate OS windows, docking a panel into a dock group it doesn't belong to, reordering tabs by dragging, collapsing a floating group to icons, resizing floating panels.
|
||||
- The dock's double arrow collapses Properties, Layers and Libraries to icons at the top of the icon column, popping out like the other icon panels, and expands them again (`window.collapseDock`, kept with the preferences and in saved workspaces). The icon column's own arrow (expanding the icon panels into a full column) is not done.
|
||||
- Localised UI: menus (in-window and native), panels, dialogs, toolbar and Preferences read from per-language catalogs (`crates/ui-egui/src/i18n`, see `docs/development.md`); Traditional Chinese (Taiwan), Simplified Chinese (mainland), Japanese, Spanish and Italian ship complete, and Czech and Brazilian Portuguese cover every menu label (and more), with system-locale detection on macOS, Windows, Linux and the web (the browser's languages, or `?lang=`), a VectorCraft ▸ Language menu and a Language preference. Names are never translated (fonts and their styles, layers, artboards, saved presets, user libraries, custom workspaces, recent files, plug-ins).
|
||||
- Native macOS menu bar, vector tool cursors, a ⌘K command palette, middle-button panning with any tool.
|
||||
- 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.
|
||||
@@ -112,8 +112,9 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist
|
||||
- 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).
|
||||
@@ -140,7 +141,7 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist
|
||||
- **Type:** Text Wrap, Type on a Path effects (Rainbow/Skew/3D Ribbon/Stair Step/Gravity) and Options (Flip, Align to Path, Spacing; OK keeps the type where it is), type on a path's start, centre and end brackets (Selection and Direct Selection drag them to set where the type runs, slide it along its path and, across the path, flip it: #429), Character and Paragraph Styles (override-preserving redefine), Area Type Options (rows/columns/inset/first baseline), threaded text across any closed shapes, Fit Headline. Area type resizes like Illustrator's type areas: a bounding-box handle drag (Selection tool) or Area Type Options Width/Height size the frame and the text reflows at its size (threads too); Direct Selection drags a frame corner or edge (`text.reshapeArea`). Point type still scales. The Selection tool shows the type widget beside selected type's bounding box (hollow on point type, filled on area type); double-clicking it converts between them (Type › Convert To Area Type / Convert To Point Type), keeping the text and its styles in place. Variable fonts list every named instance as a style of their family (Figtree Light to Black and their italics, Bahnschrift, Segoe UI Variable), and the instance chosen is shaped, drawn, outlined and measured at its axis settings; PDF and SVG embed it as that instance. Variation axis sliders are not done. Hebrew and Arabic are laid out right to left with the Unicode bidirectional algorithm (embedded Latin and numbers keep their direction, lines put in visual order after wrapping) in point, area and path type, with caret, selection and arrow keys in visual order; each paragraph's direction comes from its first strong character unless Paragraph Direction sets it (Paragraph panel with Show Indic Options, `text.setFormat {direction}`), and new type aligns to the start of its direction. SVG export outlines right-to-left text. Font Size and Leading are combo boxes in the Character and Properties panels (Font Size in the Control bar too, beside the Character link, font family and style): type, step with ↑/↓ or the spinner, scrub the label, or pick a preset (6–72 pt, shown in the type unit; Leading also Auto), each pick one undo step; Kerning and Tracking list -100…200; a size, leading, kerning or tracking the selected text doesn't share shows blank (#458).
|
||||
- **Interface languages, vertical type:** VectorCraft ▸ Language (or Preferences ▸ User Interface) picks Automatic (the system locale) or a registered language, persisted as `interfaceLanguage`. Translations come from per-language catalogs (`i18n/*.tsv`): Traditional and Simplified Chinese, Japanese, Spanish (neutral international Spanish, for every `es-*` locale) and Italian (every `it-*` locale) cover the whole interface, Czech and Brazilian Portuguese every menu label, Brazilian Portuguese the shell's `tl!` literals too (tested); Spanish and Italian also translate status-bar and error messages as they are shown (`@msg` templates, every message literal tested; the messages themselves stay English for agents); untranslated text stays English. Japanese and Chinese glyphs come from the craft-fonts build input (release builds) or the installed fonts, Czech, Spanish and Italian ones from the bundled UI fonts. The web app follows the browser's languages (or `?lang=`). The Basic toolbar's Type button holds Vertical Type in its flyout. Vertical Type, Vertical Area Type and Vertical Type on a Path create vertical text (columns right to left, upright CJK glyphs and marks with `vert` alternates, Latin and longer numbers on their side, two- and three-digit numbers set as tate-chu-yoko in one em of the column (kept whole when justified), upright glyphs centred on the column (tracked or justified too), point type's anchor on the first column's centre line); kinsoku (the strict set) applies to horizontal and vertical Japanese, and justified Japanese lines spread their room between characters (not inside Latin words); Paragraph panel › Mojikumi Set (shown with Preferences › Type › Show East Asian Options, `text.setFormat {mojikumi}`): None or Line-end Punctuation Half Width (new type's default, as in Illustrator; older documents and imported text keep None) shares one half-em space between consecutive punctuation, sets a closing mark ending a line half width and an opening bracket starting a wrapped line flush with its start, and puts a quarter em between Japanese and Latin letters or digits; Paragraph panel menu › Top-to-Top / Bottom-to-Bottom Leading measures leading from em box top to top (area type's first line touches the frame) or from baseline to baseline (new type in a Japanese interface starts top to top, with em box centre character alignment, #432); Paragraph panel menu › Burasagari None / Regular / Force (`text.setFormat {burasagari: "none"|"standard"|"forced"}`) hangs an East Asian comma or full stop (、。,.、。) ending an area type line outside it, Regular (new type's default) when it doesn't fit and Force always (the rest of the line then fills the measure; closing brackets and Latin punctuation don't hang); Character panel menu › Character Alignment (with the East Asian options; `text.setFormat` or `text.setRangeStyle {charAlign}`) lines characters smaller than the largest on their line up on the Roman baseline or the em box top/right, centre or bottom/left (ICF top and bottom not yet); Type ▸ Type Orientation switches existing text; caret, selection, hit testing and arrow keys follow the writing direction. Vertical text exports to PDF as real text and to SVG as outlines.
|
||||
- **Transparency:** opacity masks (clip/invert/disable/link), exported as SVG `<mask>` and PDF soft masks.
|
||||
- **Advanced art:** live Blends (steps/distance/smooth colour, editable spine, anchor-targeted Blend tool, faithful interpolation, knockout), Envelope Distort (warp/mesh/top object, Reset, full Envelope Options, mesh handles, Edit Contents; type, images, symbols, gradients, patterns and appearance distorted everywhere), Liquify tools with options and pen pressure, Puppet Warp with rotating pins, Perspective Grid with presets, movable planes and projected type (choosing a perspective tool shows the grid; Hide Grid hides it with the tool still chosen), Gradient Mesh, Shape Builder (stroke-only open paths and lines cut the regions they cross and enclose regions of their own; filled open paths count as closed; erase mode while Alt/Option is held: a minus pointer, red highlights of what will go, a click or drag deletes the regions touched, the pieces of open lines and the edges (outline pieces between the points where paths meet, opening their paths there) it passes over, one undo step, `shapeBuilder.merge {erase}` and `shapeBuilder.regions` edges over MCP), Live Paint (every path an edge, open lines included), Image Trace (12 presets, colour layers traced in parallel; a trace past two million anchor points or an image over 64 megapixels is refused with advice rather than running out of memory, and a selection too large to outline shows its bounds (#525); 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}`).
|
||||
@@ -157,9 +158,10 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist
|
||||
- `.vectorcraft` (lossless JSON, compressed, atomic saves, save down to v1), Save As with a format chooser, Save a Copy, Revert, templates, Data Recovery after a crash (browser tabs hold their copies with Web Locks too, so a background tab's copies are never taken for a crash's, and a tab repairs copies another removed when it resumes: #367), background save and export. The desktop app writes its warnings and errors (graphics adapter, a lost graphics device, panics the guard recovered from) to standard error and to `logs/vectorcraft.log` next to the preferences, the two previous runs kept and each file capped at 16 MiB, so a launch without a terminal still leaves something to attach to a bug report (#465).
|
||||
- SVG/SVGZ in and out with SVG Options, Preserve Editing, symbols, filters, rich text and physical units (SVG type under a transform or `viewBox` scale opens at the size it draws at, the scale moved into its size, leading, baseline shift and strokes, a stretch, skew or rotation kept as its transform: #396; a top-level group with a clip path, such as a clipped Inkscape layer, opens as a layer with a clipping mask, its name kept: #420); PDF and PDF-compatible `.ai` in and out (layers, with hidden ones kept hidden with their art and nested ones as sublayers, on pages of up to 64 million operators, art whose layer can't be told going to a hidden, non-printing layer rather than showing or printing: #419; strokes kept live, a fill and a stroke of one outline as one object; a type object's stroke written as each glyph's outline stroked back on the type, so it stays one editable object; lines wrapped in a frame (each wrapped line ending in a space, one left edge, leading and font) back as one area type object, left aligned or justified with its paragraph spacing, where laying it out breaks the lines where the file does; glyphs set apart by gaps wider than a space (a barcode's digit groups) keeping their places; layers stacked as the pages mark them even when one first paints on a later page, art ending a layer's marked content or a clip closing in a later layer kept in its own layer, and layers with no art kept empty: #508; masks, editable text with type set along a curve coming back as type on a path, each artboard's art on its own page only, an `.ai`'s white page under its layers left out rather than coming in as art, spot colours, presets, security, marks and bleed, ICC output intents, raster effects, subset fonts, PDF/X, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3). CMYK images keep their ink amounts from PDF import (and from placed CMYK TIFFs) to PDF export: a CMYK JPEG passes through unchanged, others stay CMYK (DeviceCMYK, or ICC-based CMYK in PDF/X-3/X-4) unless the Output settings convert them; the canvas shows them through the working CMYK profile (#320).
|
||||
- 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 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 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.
|
||||
- **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
|
||||
@@ -180,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** |
|
||||
@@ -219,8 +221,8 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale)
|
||||
| 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, 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 | 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 |
|
||||
|
||||
@@ -41,7 +41,7 @@ clipboard-win = { workspace = true }
|
||||
# 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", "NSEvent", "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"
|
||||
|
||||
@@ -4,9 +4,9 @@
|
||||
//! 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, and the power
|
||||
//! preference ([`power_preference`]) among the rest. eframe is handed [`selector`], which takes
|
||||
//! the first of that order.
|
||||
//! 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
|
||||
@@ -89,15 +89,17 @@ fn key(backend: Backend, vendor: u32, device: u32) -> String {
|
||||
|
||||
/// 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`, keeping the system's order among
|
||||
/// equals (all of it for [`PowerPreference::None`]).
|
||||
/// 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))
|
||||
(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()
|
||||
}
|
||||
@@ -361,7 +363,7 @@ mod tests {
|
||||
}
|
||||
|
||||
/// 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).
|
||||
/// 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![
|
||||
@@ -372,8 +374,25 @@ mod tests {
|
||||
gpu("Microsoft Basic Render Driver", Backend::Dx12, DeviceType::Cpu),
|
||||
];
|
||||
let order = adapter_order(&c, PowerPreference::LowPower, None, &[]);
|
||||
assert_eq!(order, [1, 3, 0, 2, 4]);
|
||||
assert_eq!(adapter_order(&c, PowerPreference::HighPerformance, None, &[]), [0, 2, 1, 3, 4]);
|
||||
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]
|
||||
|
||||
@@ -12,16 +12,83 @@
|
||||
//! - 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};
|
||||
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),
|
||||
@@ -48,10 +115,13 @@ pub struct MacMenu {
|
||||
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| {
|
||||
@@ -67,7 +137,7 @@ impl MacMenu {
|
||||
// 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 }
|
||||
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.
|
||||
@@ -146,6 +216,13 @@ fn append(sub: &Submenu, nodes: &[Node], entries: &mut Vec<Entry>) -> muda::Resu
|
||||
|
||||
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) {
|
||||
@@ -183,6 +260,7 @@ impl Backend for MacMenu {
|
||||
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 {
|
||||
@@ -207,6 +285,12 @@ impl Backend for MacMenu {
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -364,4 +448,40 @@ mod tests {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -68,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) {
|
||||
|
||||
@@ -25,3 +25,6 @@ sync_github_name = false
|
||||
[people.callmeBalloch]
|
||||
real_name = "Riccardo Balloch"
|
||||
sync_github_name = false
|
||||
|
||||
[people.mo0kid]
|
||||
sync_github_name = true
|
||||
@@ -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);
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -24,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;
|
||||
@@ -72,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};
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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()],
|
||||
}
|
||||
}
|
||||
|
||||
@@ -423,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 {
|
||||
@@ -642,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>`.
|
||||
@@ -715,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
|
||||
@@ -810,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() {
|
||||
@@ -972,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);
|
||||
}
|
||||
|
||||
@@ -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)));
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -26,6 +26,7 @@ pub fn needs_outline(n: &Node) -> bool {
|
||||
| NodeKind::Envelope { .. }
|
||||
| NodeKind::Mesh(_)
|
||||
| NodeKind::Repeat(_)
|
||||
| NodeKind::PlacedDocument(_)
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
};
|
||||
|
||||
@@ -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),
|
||||
_ => {}
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
})
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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)?;
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
|
||||
@@ -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)?;
|
||||
}
|
||||
|
||||
@@ -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, ¶ms)?;
|
||||
let mut params = super::pdf::expand_preset(s, cmd, ¶ms)?.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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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
@@ -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(())
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -159,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
|
||||
),
|
||||
@@ -177,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
|
||||
),
|
||||
@@ -813,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);
|
||||
@@ -840,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,
|
||||
@@ -926,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) {
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -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(())
|
||||
}
|
||||
@@ -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() })
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -530,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());
|
||||
|
||||
@@ -801,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,
|
||||
@@ -1450,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;
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
@@ -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()));
|
||||
|
||||
@@ -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(©));
|
||||
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}"
|
||||
);
|
||||
}
|
||||
@@ -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
@@ -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)?
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -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(());
|
||||
}
|
||||
@@ -62,6 +62,7 @@ fn export_tool_lists_engine_formats_and_options() {
|
||||
"svg",
|
||||
"svgz",
|
||||
"pdf",
|
||||
"ai",
|
||||
"png",
|
||||
"jpg",
|
||||
"gif",
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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 } => {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -52,7 +52,22 @@ pub(crate) fn set_paint(ctx: &mut RenderContext, p: &Paint, bounds: Rect, f: &Fr
|
||||
|
||||
/// Decode encoded image bytes into a premultiplied pixmap.
|
||||
pub fn decode_pixmap(bytes: &[u8]) -> Option<vello_cpu::Pixmap> {
|
||||
let img = image::load_from_memory(bytes).ok()?.to_rgba8();
|
||||
pixmap_of(image::load_from_memory(bytes).ok()?.to_rgba8())
|
||||
}
|
||||
|
||||
/// [`decode_pixmap`] shrunk to `w`×`h` pixels when the image is larger (never enlarged).
|
||||
pub fn decode_pixmap_fit(bytes: &[u8], w: u16, h: u16) -> Option<vello_cpu::Pixmap> {
|
||||
let img = image::load_from_memory(bytes).ok()?;
|
||||
let img = if img.width() > w as u32 || img.height() > h as u32 {
|
||||
img.resize_exact(w as u32, h as u32, image::imageops::FilterType::Triangle)
|
||||
} else {
|
||||
img
|
||||
};
|
||||
pixmap_of(img.to_rgba8())
|
||||
}
|
||||
|
||||
/// An RGBA image as a premultiplied pixmap.
|
||||
fn pixmap_of(img: image::RgbaImage) -> Option<vello_cpu::Pixmap> {
|
||||
let (w, h) = img.dimensions();
|
||||
if w == 0 || h == 0 || w > u16::MAX as u32 || h > u16::MAX as u32 {
|
||||
return None;
|
||||
|
||||
@@ -0,0 +1,359 @@
|
||||
//! Drawing placed documents ([`PlacedDocument`]).
|
||||
//!
|
||||
//! Exactly: the art read from the file ([`vectorcraft_doc::placed_document::read`]) drawn with its
|
||||
//! own resources, through a view that maps its artboard into the object's box (nothing is copied
|
||||
//! into the document).
|
||||
//!
|
||||
//! On screen ([`RenderOptions::progressive_placed`]): a placed document can't be edited, so what
|
||||
//! it shows is cached as a bitmap per file and zoom step (a power of two, in device pixels per
|
||||
//! point), shared by every object showing that file. A bitmap not made yet is made on a
|
||||
//! background worker while the frame shows another step's bitmap, or a light placeholder;
|
||||
//! [`generation`] changes when one is ready and [`busy`] says whether any is coming, so the screen
|
||||
//! can draw again. Past [`MAX_SIDE`] pixels, and in outline, proofing and ink frames, it is drawn
|
||||
//! exactly.
|
||||
//!
|
||||
//! A document opened with only its placed documents' previews ([`ImageBlob::is_proxy`]) shows them
|
||||
//! up to their resolution; past it the file is read again in the background
|
||||
//! ([`vectorcraft_doc::placed_document::full_bytes`]), the preview standing in until then (and for
|
||||
//! good when the file can't be found). Placed documents inside a placed document are drawn the
|
||||
//! same way, up to [`MAX_DEPTH`] deep; deeper ones show their previews.
|
||||
|
||||
use std::cell::Cell;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Arc, LazyLock, Mutex, MutexGuard, PoisonError};
|
||||
|
||||
use vectorcraft_doc::placed_document::MAX_DEPTH;
|
||||
use vectorcraft_doc::{ImageBlob, Node, PlacedDocument};
|
||||
use vectorcraft_geom::{Affine, Rect};
|
||||
use vello_cpu::{Pixmap, RenderContext, kurbo, peniko};
|
||||
|
||||
use crate::ink::Ink;
|
||||
use crate::{Frame, Renderer};
|
||||
|
||||
/// The longest side of a cached bitmap (pixels); larger steps draw exactly.
|
||||
pub const MAX_SIDE: f64 = 4096.0;
|
||||
/// The most bytes of bitmaps kept.
|
||||
const BUDGET: usize = 512 << 20;
|
||||
/// The smallest zoom step (device pixels per point).
|
||||
const MIN_STEP: f64 = 1.0 / 64.0;
|
||||
|
||||
/// A bitmap's identity: the file shown (its key) and the zoom step's bits.
|
||||
type BitmapKey = (String, u64);
|
||||
|
||||
struct Bitmap {
|
||||
pm: Arc<Pixmap>,
|
||||
step: f64,
|
||||
used: u64,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Bitmaps {
|
||||
map: HashMap<BitmapKey, Bitmap>,
|
||||
clock: u64,
|
||||
bytes: usize,
|
||||
}
|
||||
|
||||
static BITMAPS: LazyLock<Mutex<Bitmaps>> = LazyLock::new(Default::default);
|
||||
/// Bitmaps being made.
|
||||
static PENDING: LazyLock<Mutex<HashSet<BitmapKey>>> = LazyLock::new(Default::default);
|
||||
static GENERATION: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
|
||||
// The caches stay whole if a holder panicked (entries are only inserted and removed).
|
||||
m.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
/// Changes whenever a bitmap made in the background is ready: a screen showing placed documents
|
||||
/// draws again when it does.
|
||||
pub fn generation() -> u64 {
|
||||
GENERATION.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Are bitmaps being made in the background?
|
||||
pub fn busy() -> bool {
|
||||
!lock(&PENDING).is_empty()
|
||||
}
|
||||
|
||||
/// Is a bitmap of file `key` being made?
|
||||
#[cfg(test)]
|
||||
pub(crate) fn pending_for(key: &str) -> bool {
|
||||
lock(&PENDING).iter().any(|k| k.0 == key)
|
||||
}
|
||||
|
||||
/// The zoom step for `scale` device pixels per point: the power of two at or above it.
|
||||
pub(crate) fn step(scale: f64) -> Option<f64> {
|
||||
(scale.is_finite() && scale > 0.0).then(|| 2f64.powf(scale.log2().ceil()).max(MIN_STEP))
|
||||
}
|
||||
|
||||
impl Bitmaps {
|
||||
fn get(&mut self, k: &BitmapKey) -> Option<Arc<Pixmap>> {
|
||||
self.clock += 1;
|
||||
let clock = self.clock;
|
||||
let b = self.map.get_mut(k)?;
|
||||
b.used = clock;
|
||||
Some(b.pm.clone())
|
||||
}
|
||||
|
||||
/// The bitmap of another step of the same file, the nearest to `step`.
|
||||
fn nearest(&self, key: &str, step: f64) -> Option<(Arc<Pixmap>, f64)> {
|
||||
self.map
|
||||
.iter()
|
||||
.filter(|((k, _), _)| k == key)
|
||||
.min_by(|a, b| (a.1.step / step).log2().abs().total_cmp(&(b.1.step / step).log2().abs()))
|
||||
.map(|(_, b)| (b.pm.clone(), b.step))
|
||||
}
|
||||
|
||||
fn insert(&mut self, k: BitmapKey, pm: Pixmap, step: f64) {
|
||||
self.clock += 1;
|
||||
let size = pm.width() as usize * pm.height() as usize * 4;
|
||||
self.bytes += size;
|
||||
if let Some(old) = self.map.insert(k, Bitmap { pm: Arc::new(pm), step, used: self.clock }) {
|
||||
self.bytes = self.bytes.saturating_sub(old.pm.width() as usize * old.pm.height() as usize * 4);
|
||||
}
|
||||
while self.bytes > BUDGET && self.map.len() > 1 {
|
||||
let Some(k) = self.map.iter().min_by_key(|(_, b)| b.used).map(|(k, _)| k.clone()) else { break };
|
||||
if let Some(b) = self.map.remove(&k) {
|
||||
self.bytes = self.bytes.saturating_sub(b.pm.width() as usize * b.pm.height() as usize * 4);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a bitmap is made from.
|
||||
struct Job {
|
||||
key: BitmapKey,
|
||||
object: PlacedDocument,
|
||||
blob: ImageBlob,
|
||||
step: f64,
|
||||
}
|
||||
|
||||
/// Device pixels per point of `object`'s box its preview `bytes` have.
|
||||
fn preview_density(object: &PlacedDocument, bytes: &[u8]) -> f64 {
|
||||
vectorcraft_doc::placed_document::image_size(bytes).map_or(0.0, |(w, _)| w as f64 / object.width.max(1e-9))
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// How deep inside placed documents this thread is drawing.
|
||||
static DEPTH: Cell<usize> = const { Cell::new(0) };
|
||||
}
|
||||
|
||||
/// While alive: drawing inside a placed document, one level deeper.
|
||||
struct Inside;
|
||||
|
||||
impl Inside {
|
||||
fn enter() -> Self {
|
||||
DEPTH.with(|d| d.set(d.get() + 1));
|
||||
Inside
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Inside {
|
||||
fn drop(&mut self) {
|
||||
DEPTH.with(|d| d.set(d.get().saturating_sub(1)));
|
||||
}
|
||||
}
|
||||
|
||||
fn depth() -> usize {
|
||||
DEPTH.with(Cell::get)
|
||||
}
|
||||
|
||||
/// Render `art` of a placed document's file (`doc`, its resources) into `w`×`h` transparent
|
||||
/// pixels through `view`, the placed documents inside it one level deeper.
|
||||
pub fn render_inside(r: &mut Renderer, doc: &vectorcraft_doc::Document, art: &Arc<Node>, w: u16, h: u16, view: Affine) -> Option<crate::Rendered> {
|
||||
let _inside = Inside::enter();
|
||||
r.render_node(doc, art, w, h, view)
|
||||
}
|
||||
|
||||
/// `object`'s file (`blob`) as a bitmap of `step` device pixels per point of its box: from its
|
||||
/// preview when that is all there is and is fine enough, else from the file (read again when
|
||||
/// needed; the preview when it can't be).
|
||||
fn make(r: &mut Renderer, object: &PlacedDocument, blob: &ImageBlob, step: f64) -> Option<Pixmap> {
|
||||
let (w, h) = (pixels(object.width * step), pixels(object.height * step));
|
||||
let preview = if blob.is_proxy() { Some(blob.bytes.clone()) } else { blob.proxy.clone() };
|
||||
let full = match blob.is_proxy() {
|
||||
true if step <= preview_density(object, &blob.bytes) * 1.01 => None,
|
||||
true => vectorcraft_doc::placed_document::full_bytes(object, blob),
|
||||
false => Some(blob.bytes.clone()),
|
||||
};
|
||||
let read = full.and_then(|bytes| vectorcraft_doc::placed_document::read(object, &bytes));
|
||||
let Some(e) = read else { return crate::paint::decode_pixmap_fit(&preview?, w, h) };
|
||||
let f = e.frame;
|
||||
let (sx, sy) = (w as f64 / f.width(), h as f64 / f.height());
|
||||
let view = Affine::scale_non_uniform(sx, sy) * Affine::translate((-f.x0, -f.y0));
|
||||
let img = render_inside(r, &e.doc, &e.art, w, h, view)?;
|
||||
let data = img.pixels.as_chunks::<4>().0.iter().map(|&[r, g, b, a]| vello_cpu::color::PremulRgba8 { r, g, b, a }).collect();
|
||||
Some(Pixmap::from_parts(data, w, h))
|
||||
}
|
||||
|
||||
/// A bitmap side for `v` pixels (at least 1).
|
||||
fn pixels(v: f64) -> u16 {
|
||||
v.round().clamp(1.0, MAX_SIDE) as u16
|
||||
}
|
||||
|
||||
/// Make `job`'s bitmap and keep it.
|
||||
fn run(r: &mut Renderer, job: Job) {
|
||||
if let Some(pm) = make(r, &job.object, &job.blob, job.step) {
|
||||
lock(&BITMAPS).insert(job.key.clone(), pm, job.step);
|
||||
}
|
||||
lock(&PENDING).remove(&job.key);
|
||||
GENERATION.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod workers {
|
||||
use std::sync::mpsc::{Sender, channel};
|
||||
use std::sync::{Arc, LazyLock, Mutex};
|
||||
|
||||
use super::Job;
|
||||
|
||||
/// The queue the workers take jobs from; `None` when no worker could start.
|
||||
static QUEUE: LazyLock<Option<Mutex<Sender<Box<Job>>>>> = LazyLock::new(|| {
|
||||
let (tx, rx) = channel::<Box<Job>>();
|
||||
let rx = Arc::new(Mutex::new(rx));
|
||||
let n = std::thread::available_parallelism().map_or(2, |n| (n.get() / 2).clamp(1, 4));
|
||||
let mut started = 0;
|
||||
for i in 0..n {
|
||||
let rx = rx.clone();
|
||||
let spawned = std::thread::Builder::new().name(format!("vectorcraft-placed-{i}")).spawn(move || {
|
||||
let mut r = crate::Renderer::new();
|
||||
r.threads = 0;
|
||||
loop {
|
||||
let job = super::lock(&rx).recv();
|
||||
let Ok(job) = job else { break };
|
||||
// A panic loses this bitmap, not the worker.
|
||||
let key = job.key.clone();
|
||||
if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| super::run(&mut r, *job))).is_err() {
|
||||
super::lock(&super::PENDING).remove(&key);
|
||||
}
|
||||
}
|
||||
});
|
||||
started += usize::from(spawned.is_ok());
|
||||
}
|
||||
(started > 0).then(|| Mutex::new(tx))
|
||||
});
|
||||
|
||||
/// Hand `job` to a worker; back when there is none.
|
||||
pub(super) fn submit(job: Box<Job>) -> Result<(), Box<Job>> {
|
||||
match QUEUE.as_ref() {
|
||||
Some(q) => super::lock(q).send(job).map_err(|e| e.0),
|
||||
None => Err(job),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Make `job`'s bitmap in the background (here and now where there are no threads).
|
||||
fn schedule(job: Job) {
|
||||
if !lock(&PENDING).insert(job.key.clone()) {
|
||||
return;
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let job = match workers::submit(Box::new(job)) {
|
||||
Ok(()) => return,
|
||||
Err(job) => *job,
|
||||
};
|
||||
run(&mut Renderer::new(), job);
|
||||
}
|
||||
|
||||
/// The mean scale of `a`.
|
||||
fn mean_scale(a: Affine) -> f64 {
|
||||
a.determinant().abs().sqrt()
|
||||
}
|
||||
|
||||
impl Renderer {
|
||||
/// Draw placed document `p` in frame `f`: from a cached bitmap on screen, else exactly.
|
||||
pub(crate) fn draw_placed(&mut self, ctx: &mut RenderContext, f: &Frame, p: &PlacedDocument) {
|
||||
let plain = f.ink == Ink::Display && !f.opts.outline && f.opts.proof.is_none() && !f.opts.overprint_preview;
|
||||
if f.opts.progressive_placed && plain && depth() == 0 && self.draw_placed_bitmap(ctx, f, p) {
|
||||
return;
|
||||
}
|
||||
let Some(blob) = f.doc.images.get(&p.key) else { return };
|
||||
// The file's bytes: stored, read again already, or (inside another placed document, while
|
||||
// not too deep) read again now.
|
||||
let full = match depth() {
|
||||
0 => vectorcraft_doc::placed_document::full_bytes_cached(p, blob),
|
||||
d if d < MAX_DEPTH => vectorcraft_doc::placed_document::full_bytes(p, blob),
|
||||
_ => None,
|
||||
};
|
||||
let read = full.and_then(|bytes| vectorcraft_doc::placed_document::read(p, &bytes));
|
||||
let Some(e) = read else {
|
||||
// Only the preview: drawn scaled into the box.
|
||||
if blob.is_proxy()
|
||||
&& let Some(im) = p.preview_image(&blob.bytes)
|
||||
{
|
||||
self.draw_image(ctx, f, &im);
|
||||
}
|
||||
return;
|
||||
};
|
||||
let Some(m) = p.art_xf(e.frame) else { return };
|
||||
let k = mean_scale(m);
|
||||
if !k.is_finite() || k <= 1e-12 {
|
||||
return;
|
||||
}
|
||||
// The art in its own coordinates, with its own resources.
|
||||
let inner = Frame { doc: &e.doc, view: f.view * m, visible: m.inverse().transform_rect_bbox(f.visible), px: f.px / k, ..*f };
|
||||
let _inside = Inside::enter();
|
||||
self.draw_arc(ctx, &inner, &e.art);
|
||||
}
|
||||
|
||||
/// Draw `p` from its bitmap at this zoom step, or (while that is made) another step's, or a
|
||||
/// placeholder. False when bitmaps don't suit (too large).
|
||||
fn draw_placed_bitmap(&mut self, ctx: &mut RenderContext, f: &Frame, p: &PlacedDocument) -> bool {
|
||||
let m = f.view * p.xf;
|
||||
let Some(step) = step(mean_scale(m)) else { return false };
|
||||
if p.width * step > MAX_SIDE || p.height * step > MAX_SIDE {
|
||||
return false;
|
||||
}
|
||||
let Some(blob) = f.doc.images.get(&p.key).cloned() else { return true };
|
||||
let key = (p.key.clone(), step.to_bits());
|
||||
let (found, nearest) = {
|
||||
let mut b = lock(&BITMAPS);
|
||||
let found = b.get(&key);
|
||||
let nearest = if found.is_none() { b.nearest(&p.key, step) } else { None };
|
||||
(found, nearest)
|
||||
};
|
||||
let shown = match found {
|
||||
Some(pm) => Some(pm),
|
||||
None => {
|
||||
schedule(Job { key, object: p.clone(), blob, step });
|
||||
// Made here and now (no threads) or meanwhile another step's.
|
||||
let mut b = lock(&BITMAPS);
|
||||
b.get(&(p.key.clone(), step.to_bits())).or(nearest.map(|n| n.0))
|
||||
}
|
||||
};
|
||||
let rect = Rect::new(0.0, 0.0, p.width, p.height);
|
||||
match shown {
|
||||
Some(pm) => {
|
||||
let (sx, sy) = (p.width / pm.width().max(1) as f64, p.height / pm.height().max(1) as f64);
|
||||
ctx.set_paint(vello_cpu::Image { image: vello_cpu::ImageSource::Pixmap(pm), sampler: peniko::ImageSampler::default() });
|
||||
ctx.set_transform(m);
|
||||
ctx.set_paint_transform(Affine::scale_non_uniform(sx, sy));
|
||||
ctx.fill_rect(&kurbo::Rect::new(rect.x0, rect.y0, rect.x1, rect.y1));
|
||||
ctx.reset_paint_transform();
|
||||
}
|
||||
None => {
|
||||
// Coming: a light box where it will be.
|
||||
ctx.set_transform(m);
|
||||
ctx.set_paint(peniko::Color::from_rgba8(128, 128, 128, 40));
|
||||
ctx.fill_rect(&kurbo::Rect::new(rect.x0, rect.y0, rect.x1, rect.y1));
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn zoom_steps_are_powers_of_two_at_or_above_the_scale() {
|
||||
assert_eq!(step(1.0), Some(1.0));
|
||||
assert_eq!(step(1.2), Some(2.0));
|
||||
assert_eq!(step(0.3), Some(0.5));
|
||||
assert_eq!(step(5.0), Some(8.0));
|
||||
assert_eq!(step(1e-9), Some(MIN_STEP));
|
||||
assert_eq!(step(f64::NAN), None);
|
||||
assert_eq!(step(0.0), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
//! Placed documents on screen: drawn from bitmaps made in the background (a placeholder until
|
||||
//! then), the same as drawn exactly; exports draw them exactly at once.
|
||||
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, ImageBlob, LinkInfo, Node, NodeId, NodeKind, PlacedDocument};
|
||||
use vectorcraft_geom::shapes;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Every file reads as a 40×20 artboard filled blue; a file whose bytes start with `loop` also
|
||||
/// places itself (the same key) in its middle.
|
||||
fn blue_page(p: &PlacedDocument, bytes: &[u8]) -> Option<(Document, Node, Rect)> {
|
||||
let mut d = Document::new(40.0, 20.0);
|
||||
d.layers.clear();
|
||||
let blue = Appearance::basic(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), Paint::None, 0.0);
|
||||
let mut children = vec![Arc::new(Node::path(NodeId(1), shapes::rectangle(Rect::new(0.0, 0.0, 40.0, 20.0)), blue))];
|
||||
if bytes.starts_with(b"loop") {
|
||||
d.images.insert(p.key.clone(), ImageBlob::new("application/json", bytes.to_vec()));
|
||||
let me = PlacedDocument { xf: Affine::translate((10.0, 5.0)) * Affine::scale(0.5), ..p.clone() };
|
||||
children.push(Arc::new(Node::new(NodeId(2), NodeKind::PlacedDocument(Box::new(me)))));
|
||||
}
|
||||
Some((d, Node::new(NodeId(0), NodeKind::Group { children, clip: false }), Rect::new(0.0, 0.0, 40.0, 20.0)))
|
||||
}
|
||||
|
||||
/// A 100×100 document showing one placed file (`bytes` under `key`) in the box (10, 10)–(90, 50).
|
||||
fn doc_with(key: &str, bytes: &[u8]) -> Document {
|
||||
vectorcraft_doc::placed_document::set_loader(blue_page);
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
d.images.insert(key.into(), ImageBlob::new("application/json", bytes.to_vec()));
|
||||
let p = PlacedDocument {
|
||||
link: LinkInfo::new("/art/card.vectorcraft"),
|
||||
key: key.into(),
|
||||
bounding: false,
|
||||
width: 40.0,
|
||||
height: 20.0,
|
||||
xf: Affine::translate((10.0, 10.0)) * Affine::scale(2.0),
|
||||
placement: Default::default(),
|
||||
};
|
||||
let l = d.layers[0].id;
|
||||
d.insert(Some(l), 0, Node::new(NodeId(50), NodeKind::PlacedDocument(Box::new(p)))).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
fn doc(key: &str) -> Document {
|
||||
doc_with(key, format!("{{\"doc\": \"{key}\"}}").as_bytes())
|
||||
}
|
||||
|
||||
fn render(d: &Document, progressive: bool) -> Rendered {
|
||||
let opts = RenderOptions { background: Some([255, 255, 255, 255]), progressive_placed: progressive, ..Default::default() };
|
||||
Renderer::new().render(d, 100, 100, Affine::IDENTITY, &opts)
|
||||
}
|
||||
|
||||
/// Wait for the background bitmaps (at most 10 s).
|
||||
fn settle() {
|
||||
let t = std::time::Instant::now();
|
||||
while placed_document::busy() && t.elapsed().as_secs() < 10 {
|
||||
std::thread::sleep(std::time::Duration::from_millis(5));
|
||||
}
|
||||
assert!(!placed_document::busy(), "bitmaps still coming");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_placed_document_draws_exactly_with_its_own_art() {
|
||||
let d = doc("exact-1");
|
||||
let r = render(&d, false);
|
||||
assert_eq!(&r.pixel(50, 30)[..3], &[0, 0, 255], "blue inside the box");
|
||||
assert_eq!(&r.pixel(95, 95)[..3], &[255, 255, 255], "nothing outside");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn on_screen_a_placed_document_shows_a_placeholder_then_its_bitmap() {
|
||||
let d = doc("progressive-1");
|
||||
let generation = placed_document::generation();
|
||||
let first = render(&d, true);
|
||||
let shown = &first.pixel(50, 30)[..3];
|
||||
assert!(shown == [0, 0, 255] || shown != [255, 255, 255], "a placeholder or the art: {shown:?}");
|
||||
settle();
|
||||
assert!(placed_document::generation() > generation || shown == [0, 0, 255], "a bitmap was made");
|
||||
let later = render(&d, true);
|
||||
let exact = render(&d, false);
|
||||
assert_eq!(&later.pixel(50, 30)[..3], &[0, 0, 255]);
|
||||
for (x, y) in [(12, 12), (50, 30), (88, 48), (95, 95), (5, 5)] {
|
||||
let (a, b) = (later.pixel(x, y), exact.pixel(x, y));
|
||||
assert!(a.iter().zip(b).all(|(a, b)| a.abs_diff(b) <= 24), "at ({x}, {y}): {a:?} vs {b:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copies_of_one_placed_document_share_its_bitmap() {
|
||||
let mut d = doc("shared-1");
|
||||
let n = d.node(NodeId(50)).unwrap().clone();
|
||||
let l = d.layers[0].id;
|
||||
let mut copy = n.clone();
|
||||
copy.id = NodeId(51);
|
||||
copy.transform(Affine::translate((0.0, 45.0)), false);
|
||||
d.insert(Some(l), 1, copy).unwrap();
|
||||
render(&d, true);
|
||||
settle();
|
||||
let r = render(&d, true);
|
||||
assert!(!placed_document::pending_for("shared-1"), "nothing more to make");
|
||||
assert_eq!(&r.pixel(50, 30)[..3], &[0, 0, 255]);
|
||||
assert_eq!(&r.pixel(50, 75)[..3], &[0, 0, 255]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_placed_document_kept_as_its_preview_draws_the_preview() {
|
||||
let mut d = doc("preview-1");
|
||||
// Only the preview (a 20×10 green PNG) is there, and the file can't be read here.
|
||||
let img = image::RgbaImage::from_pixel(20, 10, image::Rgba([0, 200, 0, 255]));
|
||||
let mut png = vec![];
|
||||
img.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());
|
||||
d.images.insert("preview-1".into(), blob);
|
||||
let exact = render(&d, false);
|
||||
assert_eq!(&exact.pixel(50, 30)[..3], &[0, 200, 0], "the preview, in the box");
|
||||
assert_eq!(&exact.pixel(95, 95)[..3], &[255, 255, 255]);
|
||||
// On screen past the preview's resolution (it has 0.5 px a point; this is 2): still the preview.
|
||||
render(&d, true);
|
||||
settle();
|
||||
let shown = render(&d, true);
|
||||
assert_eq!(&shown.pixel(50, 30)[..3], &[0, 200, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_document_that_places_itself_draws_a_few_levels_deep_then_stops() {
|
||||
let d = doc_with("loop-1", b"loop");
|
||||
let t = std::time::Instant::now();
|
||||
let r = render(&d, false);
|
||||
assert!(t.elapsed().as_secs() < 10);
|
||||
assert_eq!(&r.pixel(50, 30)[..3], &[0, 0, 255]);
|
||||
// On screen too.
|
||||
render(&d, true);
|
||||
settle();
|
||||
assert_eq!(&render(&d, true).pixel(50, 30)[..3], &[0, 0, 255]);
|
||||
}
|
||||
@@ -343,7 +343,7 @@ impl Reuse {
|
||||
}
|
||||
}
|
||||
match &n.kind {
|
||||
NodeKind::Blend { .. } | NodeKind::Envelope { .. } | NodeKind::Mesh(_) | NodeKind::Repeat(_) => {
|
||||
NodeKind::Blend { .. } | NodeKind::Envelope { .. } | NodeKind::Mesh(_) | NodeKind::Repeat(_) | NodeKind::PlacedDocument(_) => {
|
||||
(self.turns, self.scales) = (false, false)
|
||||
}
|
||||
NodeKind::SymbolInstance { symbol, .. } => {
|
||||
@@ -1357,7 +1357,7 @@ impl Writer<'_> {
|
||||
(self.xf, self.instance_xf) = saved;
|
||||
}
|
||||
// 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);
|
||||
self.share_images(&g);
|
||||
self.node_body(&g);
|
||||
|
||||
@@ -98,11 +98,16 @@ fn native_roundtrip(doc: &Document) -> Result<(Value, Value), String> {
|
||||
}
|
||||
let mut lost = None;
|
||||
back.walk(|n| {
|
||||
if let NodeKind::Image(im) = &n.kind
|
||||
&& doc.images.contains_key(&im.key)
|
||||
&& !back.images.contains_key(&im.key)
|
||||
let key = match &n.kind {
|
||||
NodeKind::Image(im) => Some(&im.key),
|
||||
NodeKind::PlacedDocument(p) => Some(&p.key),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(key) = key
|
||||
&& doc.images.contains_key(key)
|
||||
&& !back.images.contains_key(key)
|
||||
{
|
||||
lost = Some(im.key.clone());
|
||||
lost = Some(key.clone());
|
||||
}
|
||||
});
|
||||
if let Some(k) = lost {
|
||||
|
||||
@@ -36,6 +36,9 @@ enum State {
|
||||
/// Shift-pressed on this selected object: released without a drag, it leaves the
|
||||
/// selection.
|
||||
deselect: Option<NodeId>,
|
||||
/// Pressed (no modifier) on this object of a selection of several: released without a
|
||||
/// drag, it becomes the key object that Align aligns to (the key again: no key).
|
||||
key: Option<NodeId>,
|
||||
},
|
||||
Scaling {
|
||||
handle: Handle,
|
||||
@@ -235,14 +238,14 @@ impl Tool for SelectionTool {
|
||||
&& cx.select_behind
|
||||
&& let Some(behind) = object_behind(cx, p)
|
||||
{
|
||||
self.state = State::Moving { start: p, began: false, deselect: None };
|
||||
self.state = State::Moving { start: p, began: false, deselect: None, key: None };
|
||||
return vec![Action::Exec("select.set".into(), json!({ "ids": [behind.0] }))];
|
||||
}
|
||||
match hit_test(cx.doc, p, cx.hit_options()) {
|
||||
Some(h) => {
|
||||
let top = h.top_object(cx.isolation);
|
||||
let mut out = vec![];
|
||||
let mut deselect = None;
|
||||
let (mut deselect, mut key) = (None, None);
|
||||
if m.shift {
|
||||
// A Shift-click takes a selected object out of the selection when it
|
||||
// is released; a Shift-drag moves the selection, constrained.
|
||||
@@ -253,8 +256,10 @@ impl Tool for SelectionTool {
|
||||
}
|
||||
} else if !cx.selection.contains(top) {
|
||||
out.push(Action::Exec("select.set".into(), json!({ "ids": [top.0] })));
|
||||
} else if cx.selection.objects.len() > 1 && !m.cmd && !m.alt {
|
||||
key = Some(top);
|
||||
}
|
||||
self.state = State::Moving { start: p, began: false, deselect };
|
||||
self.state = State::Moving { start: p, began: false, deselect, key };
|
||||
out
|
||||
}
|
||||
None => {
|
||||
@@ -276,7 +281,7 @@ impl Tool for SelectionTool {
|
||||
if let Some(snap) = &self.moving {
|
||||
(d, self.guides) = snap.snap(cx, start, d);
|
||||
}
|
||||
self.state = State::Moving { start, began: true, deselect: None };
|
||||
self.state = State::Moving { start, began: true, deselect: None, key: None };
|
||||
self.measure = cx.measurement_labels.then(|| (p, cx.offset_label(d.x, d.y)));
|
||||
out.push(Action::Preview("object.transform".into(), json!({ "matrix": matrix_json(Affine::translate(d)), "copy": m.alt })));
|
||||
out
|
||||
@@ -323,15 +328,18 @@ impl Tool for SelectionTool {
|
||||
self.state = State::Idle;
|
||||
b.finish()
|
||||
}
|
||||
(PointerKind::Up, State::Moving { began, deselect, .. }) => {
|
||||
(PointerKind::Up, State::Moving { began, deselect, key, .. }) => {
|
||||
self.state = State::Idle;
|
||||
self.measure = None;
|
||||
self.guides.clear();
|
||||
self.moving = None;
|
||||
match (began, deselect) {
|
||||
(true, _) => vec![Action::Commit],
|
||||
(false, Some(id)) => vec![Action::Exec("select.toggle".into(), json!({ "id": id.0 }))],
|
||||
(false, None) => vec![],
|
||||
match (began, deselect, key) {
|
||||
(true, ..) => vec![Action::Commit],
|
||||
(false, Some(id), _) => vec![Action::Exec("select.toggle".into(), json!({ "id": id.0 }))],
|
||||
// A click on the key object again: no key.
|
||||
(false, None, Some(id)) if cx.selection.key == Some(id) => vec![Action::Exec("select.key".into(), json!({}))],
|
||||
(false, None, Some(id)) => vec![Action::Exec("select.key".into(), json!({ "id": id.0 }))],
|
||||
(false, None, None) => vec![],
|
||||
}
|
||||
}
|
||||
(PointerKind::Up, State::Scaling { .. } | State::Rotating { .. }) => {
|
||||
@@ -540,6 +548,37 @@ mod tests {
|
||||
assert!(t.pointer(&cx2, &shift(PointerKind::Up, 150.0, 150.0)).is_empty());
|
||||
}
|
||||
|
||||
/// #541: a click on one object of a selection of several makes it the key object; a click on
|
||||
/// the key again lets it go. A drag moves them all, a lone object has no key.
|
||||
#[test]
|
||||
fn a_click_on_a_selected_object_makes_it_the_key() {
|
||||
let (d, id) = doc_with_area_type();
|
||||
let rect = d.layers[0].children().and_then(|c| c.first()).map(|n| n.id).unwrap();
|
||||
let p = paint();
|
||||
let click = |s: &Selection, x, y| {
|
||||
let c = cx(&d, s, &p);
|
||||
let mut t = SelectionTool::default();
|
||||
assert!(t.pointer(&c, &ev(PointerKind::Down, x, y)).is_empty());
|
||||
t.pointer(&c, &ev(PointerKind::Up, x, y))
|
||||
};
|
||||
let mut s = Selection::default();
|
||||
s.add(rect);
|
||||
s.add(id);
|
||||
assert_eq!(click(&s, 150.0, 150.0), vec![Action::Exec("select.key".into(), json!({"id": rect.0}))]);
|
||||
s.key = Some(rect);
|
||||
assert_eq!(click(&s, 150.0, 150.0), vec![Action::Exec("select.key".into(), json!({}))], "the key again: no key");
|
||||
// A drag moves the selection and leaves the key alone.
|
||||
let c = cx(&d, &s, &p);
|
||||
let mut t = SelectionTool::default();
|
||||
t.pointer(&c, &ev(PointerKind::Down, 150.0, 150.0));
|
||||
t.pointer(&c, &ev(PointerKind::Drag, 170.0, 150.0));
|
||||
assert_eq!(t.pointer(&c, &ev(PointerKind::Up, 170.0, 150.0)), vec![Action::Commit]);
|
||||
// One object selected: a click on it does nothing.
|
||||
let mut one = Selection::default();
|
||||
one.add(rect);
|
||||
assert!(click(&one, 150.0, 150.0).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marquee_selects() {
|
||||
let (d, id) = doc_with_rect();
|
||||
|
||||
@@ -230,7 +230,12 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
hidden: vec![],
|
||||
rot: v.rotation,
|
||||
anti_alias: app.session.prefs.anti_aliased_artwork,
|
||||
placed: vectorcraft_render::placed_document::generation(),
|
||||
};
|
||||
// Placed documents' bitmaps are being made: draw again when they are ready.
|
||||
if vectorcraft_render::placed_document::busy() {
|
||||
ui.ctx().request_repaint_after(std::time::Duration::from_millis(30));
|
||||
}
|
||||
if !app.canvas.worker_started {
|
||||
app.canvas.worker_started = true;
|
||||
if std::env::var_os("VECTORCRAFT_SYNC_RENDER").is_none() {
|
||||
@@ -265,6 +270,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
// General › Anti-aliased Artwork: off, edges are hard on screen (raster effects and
|
||||
// pattern tiles stay smooth), as in Illustrator.
|
||||
anti_alias: if app.session.prefs.anti_aliased_artwork { vectorcraft_render::AntiAlias::Art } else { vectorcraft_render::AntiAlias::None },
|
||||
progressive_placed: true,
|
||||
..opts
|
||||
};
|
||||
// Light documents render synchronously (no lag vs overlays); heavy ones go to the worker.
|
||||
@@ -1030,6 +1036,13 @@ fn node_outline(n: &Node) -> BezPath {
|
||||
bp.extend(vectorcraft_geom::shapes::rectangle(b).to_bezpath());
|
||||
}
|
||||
}
|
||||
// A placed document shows its box, turned with it.
|
||||
NodeKind::PlacedDocument(p) => {
|
||||
let [a, b, c, d] = p.corners();
|
||||
bp.move_to(a);
|
||||
[b, c, d].into_iter().for_each(|q| bp.line_to(q));
|
||||
bp.close_path();
|
||||
}
|
||||
// An envelope shows its mesh (or top object), not its content.
|
||||
NodeKind::Envelope { .. } => {
|
||||
if let Some((lines, _)) = vectorcraft_doc::live::envelope_overlay(c) {
|
||||
@@ -1041,6 +1054,9 @@ fn node_outline(n: &Node) -> BezPath {
|
||||
bp
|
||||
}
|
||||
|
||||
/// The width of the key object's outline (Align to Key Object), thicker than the selection's.
|
||||
const KEY_OUTLINE: f32 = 2.5;
|
||||
|
||||
/// The most anchor points the selection's outlines and anchors, and the hover highlight, are drawn
|
||||
/// for: an Image Trace of a photo selects hundreds of thousands of paths at once, whose outlines
|
||||
/// would make a mesh larger than the GPU takes in one buffer (#525).
|
||||
@@ -1391,6 +1407,18 @@ fn selection_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: &Xf) {
|
||||
if let Some((b, id)) = big_bounds.zip(st.selection.objects.first()) {
|
||||
stroke_path(p, &vectorcraft_geom::shapes::rectangle(b).to_bezpath(), xf, Stroke::new(1.0, c32(st.doc.layer_color(*id))));
|
||||
}
|
||||
// The key object (Align to Key Object): its outline drawn thicker, or its bounds when it has
|
||||
// too many paths to outline.
|
||||
if let Some((k, n)) = st.selection.key.and_then(|k| Some((k, st.doc.node(k)?))) {
|
||||
let outline = if too_many_anchors([n]) {
|
||||
n.geometric_bounds().map(|b| vectorcraft_geom::shapes::rectangle(b).to_bezpath())
|
||||
} else {
|
||||
Some(node_outline(n))
|
||||
};
|
||||
if let Some(bp) = outline {
|
||||
stroke_path(p, &bp, xf, Stroke::new(KEY_OUTLINE, c32(st.doc.layer_color(k))));
|
||||
}
|
||||
}
|
||||
for id in st.selection.objects.iter().filter(|_| !big) {
|
||||
let Some(n) = st.doc.node(*id) else { continue };
|
||||
let color = c32(st.doc.layer_color(*id));
|
||||
@@ -2077,6 +2105,23 @@ mod tests {
|
||||
assert!(points > 200 && squares > 200, "{points} outline points, {squares} squares");
|
||||
}
|
||||
|
||||
/// #541: the key object's outline is drawn thicker than the rest of the selection's.
|
||||
#[test]
|
||||
fn the_key_object_has_a_thicker_outline() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
let a = app.session.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 50, "height": 50})).unwrap()["id"].clone();
|
||||
let b = app.session.execute("shape.ellipse", &json!({"x": 200, "y": 100, "width": 60, "height": 40})).unwrap()["id"].clone();
|
||||
app.session.execute("select.set", &json!({"ids": [a, b]})).unwrap();
|
||||
let ctx = egui::Context::default();
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
let thick =
|
||||
|app: &mut VectorcraftApp| shapes(app, &ctx).iter().filter(|s| matches!(s, Shape::Path(ps) if ps.stroke.width == KEY_OUTLINE)).count();
|
||||
assert_eq!(thick(&mut app), 0, "no key yet");
|
||||
app.session.execute("select.key", &json!({"id": b})).unwrap();
|
||||
assert!(thick(&mut app) > 0, "the key's outline");
|
||||
}
|
||||
|
||||
/// One headless canvas frame → the shapes drawn, `Shape::Vec`s flattened.
|
||||
fn shapes(app: &mut VectorcraftApp, ctx: &egui::Context) -> Vec<Shape> {
|
||||
let (shapes, mut delta) = frame_output(app, ctx);
|
||||
|
||||
@@ -174,6 +174,9 @@ pub fn anchor_buttons(app: &mut VectorcraftApp, ui: &mut Ui, controls: AnchorCon
|
||||
}
|
||||
}
|
||||
|
||||
/// The room the Control bar's inline X/Y/W/H fields need; with less, only the Transform link shows.
|
||||
const INLINE_TRANSFORM_WIDTH: f32 = 440.0;
|
||||
|
||||
/// The Control bar (Window → Control), context-sensitive like Illustrator's.
|
||||
pub fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
@@ -280,9 +283,13 @@ pub fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
}
|
||||
}
|
||||
ui.separator();
|
||||
// Transform fields.
|
||||
// The Transform link opens the whole Transform panel (reference point, rotate,
|
||||
// shear, options) in a popover; X/Y/W/H follow inline while the bar has room.
|
||||
crate::panels::transform::link(app, ui);
|
||||
// The bounding box, rotated with rotated objects: its centre and its own sides.
|
||||
if let Some(b) = app.selection_box() {
|
||||
if let Some(b) = app.selection_box()
|
||||
&& ui.available_width() >= INLINE_TRANSFORM_WIDTH
|
||||
{
|
||||
let c = b.center();
|
||||
let link = app.session.prefs.constrain_proportions;
|
||||
for (k, lbl, v) in [("x", "X:", c.x), ("y", "Y:", c.y), ("width", "W:", b.rect.width()), ("height", "H:", b.rect.height())] {
|
||||
|
||||
@@ -17,8 +17,9 @@ use crate::{VectorcraftApp, io, widgets};
|
||||
pub(super) const SPEC: DialogSpec =
|
||||
DialogSpec { heading: |_| tl!("Export As").into(), body, confirm, ok: Some("Export…"), min_width: 380.0, ..DialogSpec::FORM };
|
||||
|
||||
/// The formats Export As writes (the native format is Save's).
|
||||
static FORMATS: LazyLock<Vec<&'static Format>> = LazyLock::new(|| fileio::FORMATS.iter().filter(|f| f.write && f.id != "vectorcraft").collect());
|
||||
/// The formats Export As writes (the native format and `.ai` are Save As's).
|
||||
static FORMATS: LazyLock<Vec<&'static Format>> =
|
||||
LazyLock::new(|| fileio::FORMATS.iter().filter(|f| f.write && !matches!(f.id, "vectorcraft" | "ai")).collect());
|
||||
/// Formats listed after them that can't be written (`fileio::unsupported` ids), greyed out.
|
||||
const UNAVAILABLE: [(&str, &str); 1] = [("dwg", "DWG (use DXF)")];
|
||||
static LABELS: LazyLock<Vec<&'static str>> = LazyLock::new(|| FORMATS.iter().map(|f| f.label).chain(UNAVAILABLE.iter().map(|u| u.1)).collect());
|
||||
|
||||
@@ -29,6 +29,9 @@ use crate::widgets::{self, Live};
|
||||
|
||||
pub(super) const SPEC: DialogSpec = DialogSpec::window(show, confirm);
|
||||
|
||||
/// The field holding the frame the popover was first drawn in.
|
||||
const OPENED: &str = "__opened";
|
||||
|
||||
/// What the popover edits: the selected stop of the gradient behind the active proxy (with all
|
||||
/// its stops), or the selected point of a freeform gradient.
|
||||
enum Target {
|
||||
@@ -131,12 +134,18 @@ fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
});
|
||||
})
|
||||
.response;
|
||||
if let (Some(tab), Some(d)) = (tab, app.ui.dialog.as_mut()) {
|
||||
d.fields.insert("tab".into(), json!(tab));
|
||||
// The frame it opened in (its first drawn).
|
||||
let frame = ctx.cumulative_frame_nr();
|
||||
let opened = d.fields.get(OPENED).and_then(Value::as_u64).unwrap_or(frame);
|
||||
if let Some(d) = app.ui.dialog.as_mut() {
|
||||
if let Some(tab) = tab {
|
||||
d.fields.insert("tab".into(), json!(tab));
|
||||
}
|
||||
d.fields.insert(OPENED.into(), json!(opened));
|
||||
}
|
||||
// The double-click that opened the popover lands on its chip, outside it: only a later click
|
||||
// elsewhere closes it.
|
||||
if resp.clicked_elsewhere() && !ctx.input(|i| i.pointer.button_double_clicked(egui::PointerButton::Primary)) {
|
||||
// The click that opened the popover (the Gradient panel's colour chip) or the double-click
|
||||
// (a stop's chip) lands outside it: only a later click elsewhere closes it (#577).
|
||||
if frame > opened && resp.clicked_elsewhere() && !ctx.input(|i| i.pointer.button_double_clicked(egui::PointerButton::Primary)) {
|
||||
app.ui.dialog = None;
|
||||
}
|
||||
}
|
||||
@@ -246,10 +255,18 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
// One context per test, so frames follow one another as in the app.
|
||||
static CTX: egui::Context = {
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
ctx
|
||||
};
|
||||
}
|
||||
|
||||
/// One headless frame of the dialog layer and the shortcuts.
|
||||
fn frame(app: &mut VectorcraftApp, events: Vec<egui::Event>) {
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
let ctx = CTX.with(Clone::clone);
|
||||
let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| {
|
||||
crate::shortcuts::handle(app, ui.ctx());
|
||||
super::super::show(app, ui.ctx());
|
||||
@@ -312,6 +329,25 @@ mod tests {
|
||||
assert!(app.ui.dialog.is_none(), "a click elsewhere closes it");
|
||||
}
|
||||
|
||||
/// #577: the Gradient panel's colour chip opens it with a click whose release lands in the
|
||||
/// frame it opens in, outside it: that click doesn't close it.
|
||||
#[test]
|
||||
fn the_click_that_opens_it_from_the_panel_keeps_it_open() {
|
||||
let mut app = app();
|
||||
let at = egui::pos2(5.0, 5.0);
|
||||
frame(&mut app, vec![egui::Event::PointerMoved(at), click(at, true)]);
|
||||
// The panel opens it while the click is released.
|
||||
app.ui.dialog = Some(Dialog::new("gradientStop", json!({"index": 1, "screen": [200.0, 200.0], "tab": "color"})));
|
||||
frame(&mut app, vec![click(at, false)]);
|
||||
for _ in 0..3 {
|
||||
frame(&mut app, vec![]);
|
||||
}
|
||||
assert!(app.ui.dialog.is_some(), "the opening click must not close it");
|
||||
let away = egui::pos2(5.0, 600.0);
|
||||
frame(&mut app, vec![egui::Event::PointerMoved(away), click(away, true), click(away, false)]);
|
||||
assert!(app.ui.dialog.is_none(), "a later click elsewhere closes it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_popover_closes_when_its_stop_goes_away() {
|
||||
let mut app = app();
|
||||
|
||||
@@ -3,7 +3,9 @@
|
||||
//! object) or loads the place cursor with several ([`crate::place::confirm`]).
|
||||
//!
|
||||
//! Fields: `files` (`[{path} | {name}]`), `link`, `template`, `replace`, and `__replace` (one file
|
||||
//! and one selected object: Replace applies), `__info` (a line per file).
|
||||
//! and one selected object: Replace applies), `__documents` and `__others` (VectorCraft documents
|
||||
//! from files are picked, other files are: what Link's tooltip explains), `__info` (a line per
|
||||
//! file).
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
@@ -72,12 +74,32 @@ fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
for (key, label, tip) in OPTIONS {
|
||||
let on = d.bool(key);
|
||||
let enabled = key != "replace" || d.bool("__replace");
|
||||
let resp = ui.scope(|ui| widgets::check(ui, tl!(label), on && enabled, enabled));
|
||||
if resp.inner {
|
||||
let tip = if key == "link" { link_tip(d) } else { tl!(tip).to_string() };
|
||||
if widgets::check_tip(ui, tl!(label), on && enabled, enabled, &tip) {
|
||||
d.fields.insert(key.into(), json!(!on));
|
||||
}
|
||||
resp.response.on_hover_text(tl!(tip));
|
||||
}
|
||||
});
|
||||
false
|
||||
}
|
||||
|
||||
/// Link's tooltip: what it does for the files picked (images, VectorCraft documents, or both), a
|
||||
/// line each.
|
||||
pub(crate) fn link_tip(d: &Dialog) -> String {
|
||||
let lines = match (d.bool("__documents"), d.bool("__others")) {
|
||||
(true, false) => {
|
||||
vec![
|
||||
tl!("On: one locked object showing the document, updated when it changes."),
|
||||
tl!("Off: an editable copy of its art, embedded in this document."),
|
||||
]
|
||||
}
|
||||
(true, true) => {
|
||||
vec![
|
||||
tl!("Images: link to the file instead of only embedding it."),
|
||||
tl!("VectorCraft documents: one locked object, updated when the file changes."),
|
||||
]
|
||||
}
|
||||
_ => vec![tl!("Keep a link to an image file instead of only embedding it")],
|
||||
};
|
||||
lines.join("\n")
|
||||
}
|
||||
@@ -360,7 +360,7 @@ mod tests {
|
||||
let f = &mut app.ui.dialog.as_mut().unwrap().fields;
|
||||
f.insert("decimals".into(), json!(1));
|
||||
f.insert("allArtboards".into(), json!(false));
|
||||
f.insert("range".into(), json!("2"));
|
||||
f.insert("range".into(), json!("1"));
|
||||
super::super::confirm(&mut app).unwrap();
|
||||
assert!(app.ui.dialog.is_none());
|
||||
let svg = text(&written, 0);
|
||||
|
||||
@@ -240,3 +240,29 @@ fn pdf_artboards_continue_in_the_save_pdf_dialog() {
|
||||
let pdf = vectorcraft_pdf::import(&written.borrow()[0].1).unwrap();
|
||||
assert_eq!(pdf.artboards.len(), 2, "one page per artboard in the range");
|
||||
}
|
||||
|
||||
/// #546, #550: Export As with Use Artboards and a range writes the chosen artboard alone in every
|
||||
/// format, each file holding that artboard's art (the ellipse is on artboard 1).
|
||||
#[test]
|
||||
fn export_as_writes_only_the_chosen_artboard_in_every_format() {
|
||||
for (format, ellipse) in [("svg", "<path"), ("dxf", "HATCH"), ("pdf", ""), ("png", "")] {
|
||||
for (range, on) in [("1", true), ("3", false)] {
|
||||
let (mut app, written) = app(3);
|
||||
app.run("file.exportAs", json!({"format": format})).unwrap();
|
||||
set(&mut app, "useArtboards", json!(true));
|
||||
set(&mut app, "all", json!(false));
|
||||
set(&mut app, "range", json!(range));
|
||||
confirm(&mut app).unwrap();
|
||||
// The format's own options, then the file.
|
||||
while app.ui.dialog.is_some() {
|
||||
frame(&mut app);
|
||||
confirm(&mut app).unwrap();
|
||||
}
|
||||
assert_eq!(names(&written), [format!("/out/Untitled-1.{format}")], "{format} {range}");
|
||||
if !ellipse.is_empty() {
|
||||
let text = String::from_utf8_lossy(&written.borrow()[0].1).into_owned();
|
||||
assert_eq!(text.contains(ellipse), on, "{format} {range}: {text}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -307,12 +307,10 @@ fn list(ui: &mut Ui, state_id: egui::Id, st: &mut MenuState, current: &str, samp
|
||||
widgets::dim_label(ui, tl!("No matching fonts"));
|
||||
return None;
|
||||
}
|
||||
// The rows: only those in view are laid out (there are thousands of families). The list fills
|
||||
// what the popup shows below the filters (its clip: the popup doesn't grow past its own size,
|
||||
// and a taller list would scroll inside a scrolling popup), down to the window's bottom.
|
||||
const BOTTOM_GAP: f32 = 12.0;
|
||||
let bottom = ui.clip_rect().bottom().min(ui.ctx().content_rect().bottom() - BOTTOM_GAP);
|
||||
let room = (bottom - ui.next_widget_position().y).max(120.0);
|
||||
// The rows: only those in view are laid out (there are thousands of families). The list is
|
||||
// the menu's one scrolling part, under the search field and filters (#555): it fills the
|
||||
// menu's room (its max rect) below them.
|
||||
let room = (ui.max_rect().bottom() - ui.next_widget_position().y).clamp(120.0, 600.0);
|
||||
let mut area = egui::ScrollArea::vertical().max_height(room).min_scrolled_height(room.min(row_h * rows.len() as f32));
|
||||
// The highlight in view: centred as the menu opens, scrolled just enough as the keys move it.
|
||||
if let Some(top) = st.highlight.map(|i| i as f32 * row_h) {
|
||||
|
||||
@@ -143,6 +143,7 @@
|
||||
Make Pixel Perfect Zarovnat na obrazové body
|
||||
Slice Řez
|
||||
Make Vytvořit
|
||||
Make and Expand Vytvořit a rozložit
|
||||
Release Uvolnit
|
||||
Create from Guides Vytvořit z vodítek
|
||||
Create from Selection Vytvořit z výběru
|
||||
@@ -199,8 +200,6 @@
|
||||
Merge Sloučit
|
||||
Gap Options… Možnosti mezer…
|
||||
Image Trace Vektorizace obrazu
|
||||
Make… Vytvořit…
|
||||
Make and Expand… Vytvořit a rozložit…
|
||||
Text Wrap Obtékání textu
|
||||
Text Wrap Options… Možnosti obtékání textu…
|
||||
Clipping Mask Ořezová maska
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -1369,7 +1369,6 @@
|
||||
Make a theme on Create and save it. Crea un tema en Crear y guárdalo.
|
||||
Make all bleed settings the same Usar el mismo valor en todos los sangrados
|
||||
Make and Expand Crear y expandir
|
||||
Make and Expand… Crear y expandir…
|
||||
Make Clipping Mask Crear máscara de recorte
|
||||
Make Compound Shape Crear forma compuesta
|
||||
Make Envelope Crear envolvente
|
||||
@@ -1382,7 +1381,6 @@
|
||||
Make with Top Object Crear con objeto superior
|
||||
Make with Warp… Crear con deformación…
|
||||
Make/Release Clipping Mask Crear/soltar máscara de recorte
|
||||
Make… Crear…
|
||||
Manage Workspaces Administrar espacios de trabajo
|
||||
Manage Workspaces… Administrar espacios de trabajo…
|
||||
Manually Manualmente
|
||||
@@ -2546,6 +2544,7 @@
|
||||
Character: Carácter:
|
||||
Character options Opciones de carácter
|
||||
Stroke options Opciones de trazo
|
||||
Transform options Opciones de transformación
|
||||
Stroke Weight Grosor de trazo
|
||||
Stroke: Trazo:
|
||||
Stroke: click for swatches, Shift-click for the color mixer Trazo: clic para muestras, Shift+clic para el mezclador de colores
|
||||
@@ -3118,6 +3117,7 @@ axis Both Ambos
|
||||
@msg Release Guides: no guides Soltar guías: no hay guías
|
||||
@msg Release: no layer to put the rectangle in Soltar: no hay ninguna capa donde poner el rectángulo
|
||||
@msg Replace Spine: select a blend and a path Reemplazar eje: selecciona una fusión y un trazado
|
||||
@msg select two or more objects to distribute selecciona dos o más objetos para distribuir
|
||||
@msg select paths or anchor points selecciona trazados o puntos de ancla
|
||||
@msg SVG parse error: {0} error al analizar el SVG: {0}
|
||||
@msg Save for Web: the image is empty Guardar para web: la imagen está vacía
|
||||
@@ -3593,3 +3593,8 @@ axis Both Ambos
|
||||
Zoom Zoom
|
||||
Bring All to Front Traer todo al frente
|
||||
Settings Ajustes
|
||||
Break Link Romper vínculo
|
||||
On: one locked object showing the document, updated when it changes. Activado: un objeto bloqueado que muestra el documento y se actualiza cuando este cambia.
|
||||
Off: an editable copy of its art, embedded in this document. Desactivado: una copia editable de su ilustración, incrustada en este documento.
|
||||
Images: link to the file instead of only embedding it. Imágenes: vincular al archivo en lugar de solo incrustarlo.
|
||||
VectorCraft documents: one locked object, updated when the file changes. Documentos de VectorCraft: un objeto bloqueado que se actualiza cuando cambia el archivo.
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -1369,7 +1369,6 @@
|
||||
Make a theme on Create and save it. Crea un tema nella scheda Crea e salvalo.
|
||||
Make all bleed settings the same Usa lo stesso valore per tutte le abbondanze
|
||||
Make and Expand Crea ed espandi
|
||||
Make and Expand… Crea ed espandi…
|
||||
Make Clipping Mask Crea maschera di ritaglio
|
||||
Make Compound Shape Crea forma composta
|
||||
Make Envelope Crea involucro
|
||||
@@ -1382,7 +1381,6 @@
|
||||
Make with Top Object Crea con oggetto superiore
|
||||
Make with Warp… Crea con alterazione…
|
||||
Make/Release Clipping Mask Crea/rilascia maschera di ritaglio
|
||||
Make… Crea…
|
||||
Manage Workspaces Gestisci aree di lavoro
|
||||
Manage Workspaces… Gestisci aree di lavoro…
|
||||
Manually Manualmente
|
||||
@@ -2546,6 +2544,7 @@
|
||||
Character: Carattere:
|
||||
Character options Opzioni carattere
|
||||
Stroke options Opzioni traccia
|
||||
Transform options Opzioni di trasformazione
|
||||
Stroke Weight Spessore traccia
|
||||
Stroke: Traccia:
|
||||
Stroke: click for swatches, Shift-click for the color mixer Traccia: fai clic per i campioni, Shift+clic per il miscelatore colori
|
||||
@@ -3118,6 +3117,7 @@ axis Both Entrambi
|
||||
@msg Release Guides: no guides Rilascia guide: nessuna guida
|
||||
@msg Release: no layer to put the rectangle in Rilascia: nessun livello in cui inserire il rettangolo
|
||||
@msg Replace Spine: select a blend and a path Sostituisci dorsale: seleziona una fusione e un tracciato
|
||||
@msg select two or more objects to distribute seleziona due o più oggetti da distribuire
|
||||
@msg select paths or anchor points seleziona tracciati o punti di ancoraggio
|
||||
@msg SVG parse error: {0} Errore di analisi SVG: {0}
|
||||
@msg Save for Web: the image is empty Salva per il web: l'immagine è vuota
|
||||
@@ -3593,3 +3593,8 @@ axis Both Entrambi
|
||||
Zoom Zoom
|
||||
Bring All to Front Porta tutto in primo piano
|
||||
Settings Impostazioni
|
||||
Break Link Interrompi collegamento
|
||||
On: one locked object showing the document, updated when it changes. Attivato: un unico oggetto bloccato che mostra il documento, aggiornato quando cambia.
|
||||
Off: an editable copy of its art, embedded in this document. Disattivato: una copia modificabile della sua grafica, incorporata in questo documento.
|
||||
Images: link to the file instead of only embedding it. Immagini: collega il file invece di incorporarlo soltanto.
|
||||
VectorCraft documents: one locked object, updated when the file changes. Documenti VectorCraft: un unico oggetto bloccato, aggiornato quando il file cambia.
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -233,8 +233,6 @@
|
||||
Image Trace 画像トレース
|
||||
Image Tracing 画像トレースオブジェクト
|
||||
Tracing Presets トレースプリセット
|
||||
Make… 作成…
|
||||
Make and Expand… 作成して拡張…
|
||||
Text Wrap テキストの回り込み
|
||||
Text Wrap Options… テキストの回り込みオプション…
|
||||
Clipping Mask クリッピングマスク
|
||||
@@ -2352,6 +2350,7 @@
|
||||
Character: 文字:
|
||||
Character options 文字オプション
|
||||
Stroke options 線オプション
|
||||
Transform options 変形オプション
|
||||
Stroke: 線:
|
||||
Style スタイル
|
||||
Style Name: スタイル名:
|
||||
@@ -3056,3 +3055,8 @@ axis Both 両方
|
||||
Bring All to Front すべてを手前に移動
|
||||
Settings 環境設定
|
||||
theme Appearance 外観
|
||||
Break Link リンクを解除
|
||||
On: one locked object showing the document, updated when it changes. オン:ドキュメントを表示するロックされた 1 つのオブジェクト。ドキュメントの変更時に更新されます。
|
||||
Off: an editable copy of its art, embedded in this document. オフ:アートの編集可能なコピーをこのドキュメントに埋め込みます。
|
||||
Images: link to the file instead of only embedding it. 画像:埋め込むだけでなく、ファイルにリンクします。
|
||||
VectorCraft documents: one locked object, updated when the file changes. VectorCraft ドキュメント:ロックされた 1 つのオブジェクト。ファイルの変更時に更新されます。
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -1242,13 +1242,11 @@
|
||||
Make a theme on Create and save it. Crie um tema em Criar e salve-o.
|
||||
Make all bleed settings the same Tornar todas as configurações de sangria iguais
|
||||
Make and Expand Criar e Expandir
|
||||
Make and Expand… Criar e Expandir…
|
||||
Make the bleed values differ Fazer os valores de sangria diferirem
|
||||
Make with Mesh… Criar com Malha…
|
||||
Make with Top Object Criar com Objeto Superior
|
||||
Make with Warp… Criar com Distorção…
|
||||
Make/Release Clipping Mask Criar/Liberar Máscara de Recorte
|
||||
Make… Criar…
|
||||
Manage Workspaces Gerenciar Espaços de Trabalho
|
||||
Manage Workspaces… Gerenciar Espaços de Trabalho…
|
||||
Manually Manualmente
|
||||
@@ -2248,6 +2246,7 @@
|
||||
Character: Caractere:
|
||||
Character options Opções de caractere
|
||||
Stroke options Opções de traçado
|
||||
Transform options Opções de transformação
|
||||
Stroke: Traçado:
|
||||
Style Estilo
|
||||
Style Name: Nome do Estilo:
|
||||
@@ -2644,3 +2643,8 @@
|
||||
Zoom Zoom
|
||||
Bring All to Front Trazer Todas para a Frente
|
||||
Settings Configurações
|
||||
Break Link Quebrar Vínculo
|
||||
On: one locked object showing the document, updated when it changes. Ativado: um objeto bloqueado que mostra o documento, atualizado quando ele muda.
|
||||
Off: an editable copy of its art, embedded in this document. Desativado: uma cópia editável da arte, incorporada neste documento.
|
||||
Images: link to the file instead of only embedding it. Imagens: vincular ao arquivo em vez de apenas incorporá-lo.
|
||||
VectorCraft documents: one locked object, updated when the file changes. Documentos do VectorCraft: um objeto bloqueado, atualizado quando o arquivo muda.
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -1351,7 +1351,6 @@
|
||||
Make a theme on Create and save it. 在“创建”中制作主题并存储。
|
||||
Make all bleed settings the same 使所有出血设置相同
|
||||
Make and Expand 创建并扩展
|
||||
Make and Expand… 制作并展开…
|
||||
Make Clipping Mask 制作剪切蒙版
|
||||
Make Compound Shape 创建复合形状
|
||||
Make Envelope 制作封套
|
||||
@@ -1364,7 +1363,6 @@
|
||||
Make with Top Object 用顶层对象创建
|
||||
Make with Warp… 用变形创建…
|
||||
Make/Release Clipping Mask 创建/释放剪切蒙版
|
||||
Make… 制作…
|
||||
Manage Workspaces 管理工作区
|
||||
Manage Workspaces… 管理工作区…
|
||||
Manually 手动
|
||||
@@ -2484,6 +2482,7 @@
|
||||
Character: 字符:
|
||||
Character options 字符选项
|
||||
Stroke options 描边选项
|
||||
Transform options 变换选项
|
||||
Stroke Weight 描边粗细
|
||||
Stroke: 描边:
|
||||
Stroke: click for swatches, Shift-click for the color mixer 描边:单击开启色板,按住 Shift 单击开启混色器
|
||||
@@ -3311,3 +3310,8 @@ axis Both 两者
|
||||
Hide VectorCraft 隐藏 VectorCraft
|
||||
Bring All to Front 前置全部窗口
|
||||
Settings 设置
|
||||
Break Link 断开链接
|
||||
On: one locked object showing the document, updated when it changes. 开启:以一个锁定对象显示文档,文档更改时随之更新。
|
||||
Off: an editable copy of its art, embedded in this document. 关闭:将其图稿的可编辑副本嵌入此文档。
|
||||
Images: link to the file instead of only embedding it. 图像:链接到文件,而不只是嵌入。
|
||||
VectorCraft documents: one locked object, updated when the file changes. VectorCraft 文档:一个锁定对象,文件更改时随之更新。
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -1387,7 +1387,6 @@
|
||||
Make a theme on Create and save it. 按一下「建立」即可製作主題並儲存。
|
||||
Make all bleed settings the same 將所有出血設定設為相同
|
||||
Make and Expand 製作並展開
|
||||
Make and Expand… 製作並展開…
|
||||
Make Clipping Mask 製作剪裁遮色片
|
||||
Make Compound Shape 製作複合形狀
|
||||
Make Envelope 製作封套
|
||||
@@ -1400,7 +1399,6 @@
|
||||
Make with Top Object 以最上層物件製作
|
||||
Make with Warp… 以彎曲製作…
|
||||
Make/Release Clipping Mask 製作/釋放剪裁遮色片
|
||||
Make… 製作…
|
||||
Manage Workspaces 管理工作區
|
||||
Manage Workspaces… 管理工作區…
|
||||
Manually 手動
|
||||
@@ -2566,6 +2564,7 @@
|
||||
Character: 字元:
|
||||
Character options 字元選項
|
||||
Stroke options 筆畫選項
|
||||
Transform options 變形選項
|
||||
Stroke Weight 筆畫寬度
|
||||
Stroke: 筆畫:
|
||||
Stroke: click for swatches, Shift-click for the color mixer 筆畫:按一下開啟色票,按住 Shift 按一下開啟混色器
|
||||
@@ -3086,3 +3085,8 @@ axis Both 兩者
|
||||
Zoom 縮放
|
||||
Bring All to Front 將全部移至最前
|
||||
Settings 設定
|
||||
Break Link 中斷連結
|
||||
On: one locked object showing the document, updated when it changes. 開啟:以單一鎖定物件顯示文件,文件變更時隨之更新。
|
||||
Off: an editable copy of its art, embedded in this document. 關閉:將其圖稿的可編輯副本內嵌在此文件中。
|
||||
Images: link to the file instead of only embedding it. 影像:連結至檔案,而不只是嵌入。
|
||||
VectorCraft documents: one locked object, updated when the file changes. VectorCraft 文件:單一鎖定物件,檔案變更時隨之更新。
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -277,6 +277,8 @@ pub struct CacheKey {
|
||||
pub rot: f64,
|
||||
/// General › Anti-aliased Artwork.
|
||||
pub anti_alias: bool,
|
||||
/// [`vectorcraft_render::placed_document::generation`]: placed documents' bitmaps made since.
|
||||
pub placed: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
|
||||
+79
-28
@@ -560,7 +560,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"links.editOriginal",
|
||||
"Edit Original",
|
||||
"",
|
||||
"{id?} open the file of linked image `id` (default: the selected linked image) in the system's default app for its type (Links panel, Edit › Edit Original) → {path}; edits saved there show after links.update",
|
||||
"{id?} open the file of linked image `id` (default: the selected linked image) in the system's default app for its type (Links panel, Edit › Edit Original); a placed document's file opens here in a new tab, and saving it updates the documents placing it → {path}; edits saved elsewhere show after links.update",
|
||||
),
|
||||
(
|
||||
"links.reveal",
|
||||
@@ -1837,8 +1837,8 @@ pub fn enabled(app: &VectorcraftApp, id: &str) -> bool {
|
||||
"ui.spotColors" => app.session.active().is_some(),
|
||||
"ui.menuDialog" => app.session.active().is_some_and(|d| !d.selection.is_empty()),
|
||||
"ui.dxfOptionsDialog" => app.session.active().is_some(),
|
||||
"links.editOriginal" | "links.reveal" => selected_image(app, |im| im.link.is_some()),
|
||||
"ui.placementOptionsDialog" => selected_image(app, |_| true),
|
||||
"links.editOriginal" | "links.reveal" => selected_image(app, |im| im.link.is_some()) || selected_placed(app),
|
||||
"ui.placementOptionsDialog" => selected_image(app, |_| true) || selected_placed(app),
|
||||
"ui.packageDialog" | "docInfo.save" => app.session.active().is_some(),
|
||||
"ui.epsOptionsDialog" => app.session.active().is_some(),
|
||||
"file.saveForWeb" | "file.saveForWeb.browser" => app.session.active().is_some(),
|
||||
@@ -1855,6 +1855,13 @@ pub fn enabled(app: &VectorcraftApp, id: &str) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// Is a placed document selected?
|
||||
fn selected_placed(app: &VectorcraftApp) -> bool {
|
||||
app.session.active().is_some_and(|st| {
|
||||
st.selection.objects.iter().any(|id| st.doc.node(*id).is_some_and(|n| matches!(n.kind, vectorcraft_doc::NodeKind::PlacedDocument(_))))
|
||||
})
|
||||
}
|
||||
|
||||
/// Is an image `keep` accepts selected?
|
||||
fn selected_image(app: &VectorcraftApp, keep: impl Fn(&vectorcraft_doc::ImageObject) -> bool) -> bool {
|
||||
app.session.active().is_some_and(|st| {
|
||||
@@ -2157,8 +2164,11 @@ pub fn menu_tree() -> Vec<(&'static str, Vec<Item>)> {
|
||||
sub(
|
||||
"Image Trace",
|
||||
vec![
|
||||
cp("Make…", "imageTrace.make", json!({"preset": "Black and White Logo"})),
|
||||
cp("Make and Expand…", "imageTrace.makeAndExpand", json!({"preset": "6 Colors"})),
|
||||
// Traced at once with the Default preset, as the Control bar's Image Trace
|
||||
// button does; other presets come from its arrow or the Image Trace panel
|
||||
// (#543: the "…" form asked for a preset's name in a text box).
|
||||
cp("Make", "imageTrace.make", json!({"preset": "Default"})),
|
||||
cp("Make and Expand", "imageTrace.makeAndExpand", json!({"preset": "Default"})),
|
||||
c("Release", "imageTrace.release"),
|
||||
c("Expand", "imageTrace.expand"),
|
||||
],
|
||||
@@ -2661,9 +2671,24 @@ pub fn ruler_menu_body(app: &VectorcraftApp, ui: &mut egui::Ui, clicked: &mut Op
|
||||
/// The in-window menu bar. Returns where its titles end (x): the bar itself takes the full width.
|
||||
pub fn menu_bar(app: &mut VectorcraftApp, ui: &mut egui::Ui) -> f32 {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let ctx = ui.ctx().clone();
|
||||
// The press that opens a menu takes the keyboard from a focused text field: the field and its
|
||||
// selection are kept while the menus are open, so their Select All, Cut, Copy and Paste act on
|
||||
// its text (#516), the frame after the click that chose them (that click takes the keyboard
|
||||
// from it again).
|
||||
type Field = (egui::Id, egui::text_edit::TextEditState);
|
||||
let (field_key, chosen_key) = (egui::Id::new("menu-bar-field"), egui::Id::new("menu-bar-field-event"));
|
||||
if let Some(((field, state), e)) = ctx.data(|d| d.get_temp::<(Field, egui::Event)>(chosen_key)) {
|
||||
ctx.data_mut(|d| d.remove::<(Field, egui::Event)>(chosen_key));
|
||||
state.store(&ctx, field);
|
||||
to_field(&ctx, field, e);
|
||||
}
|
||||
if let Some(field) = focused_text_field(&ctx).and_then(|id| Some((id, egui::TextEdit::load_state(&ctx, id)?))) {
|
||||
ctx.data_mut(|d| d.insert_temp::<Field>(field_key, field));
|
||||
}
|
||||
let mut clicked: Option<(String, Value)> = None;
|
||||
let tree = menu_tree();
|
||||
let end = egui::MenuBar::new()
|
||||
let (end, open) = egui::MenuBar::new()
|
||||
.ui(ui, |ui| {
|
||||
let mut titles = Vec::with_capacity(tree.len());
|
||||
for (i, (title, items)) in tree.iter().enumerate() {
|
||||
@@ -2674,12 +2699,21 @@ pub fn menu_bar(app: &mut VectorcraftApp, ui: &mut egui::Ui) -> f32 {
|
||||
};
|
||||
titles.push(ui.menu_button(text, |ui| menu_body(app, ui, items, &mut clicked)).response);
|
||||
}
|
||||
switch_on_hover(ui.ctx(), &titles);
|
||||
ui.cursor().min.x
|
||||
(ui.cursor().min.x, switch_on_hover(ui.ctx(), &titles))
|
||||
})
|
||||
.inner;
|
||||
let field = ctx.data(|d| d.get_temp::<Field>(field_key));
|
||||
if !open && focused_text_field(&ctx).is_none() {
|
||||
ctx.data_mut(|d| d.remove::<Field>(field_key));
|
||||
}
|
||||
if let Some((id, p)) = clicked {
|
||||
invoke(app, &id, p);
|
||||
match field.and_then(|f| Some((f, field_event(app, &id)?))) {
|
||||
Some(chosen) => {
|
||||
ctx.data_mut(|d| d.insert_temp(chosen_key, chosen));
|
||||
ctx.request_repaint();
|
||||
}
|
||||
None => invoke(app, &id, p),
|
||||
}
|
||||
}
|
||||
end
|
||||
}
|
||||
@@ -2692,29 +2726,25 @@ fn pointer_reaches_title(ctx: &egui::Context, title: &egui::Response, p: egui::P
|
||||
}
|
||||
|
||||
/// Like a native menu bar: while one top-level menu is open, moving the pointer onto another
|
||||
/// title opens that menu instead (egui alone needs a click on each title).
|
||||
fn switch_on_hover(ctx: &egui::Context, titles: &[egui::Response]) {
|
||||
/// title opens that menu instead (egui alone needs a click on each title). Returns whether a menu
|
||||
/// is open.
|
||||
fn switch_on_hover(ctx: &egui::Context, titles: &[egui::Response]) -> bool {
|
||||
let ids: Vec<egui::Id> = titles.iter().map(egui::Popup::default_response_id).collect();
|
||||
let Some(open) = ids.iter().position(|id| egui::Popup::is_id_open(ctx, *id)) else {
|
||||
return;
|
||||
return false;
|
||||
};
|
||||
// `Response::hovered` is false while a menu's popup is open, so hit-test the titles here.
|
||||
let Some(p) = ctx.pointer_hover_pos() else {
|
||||
return;
|
||||
};
|
||||
// Only a moving pointer switches: one resting on a title leaves the open menu alone.
|
||||
if ctx.input(|i| i.pointer.delta() == egui::Vec2::ZERO) {
|
||||
return;
|
||||
}
|
||||
let Some(i) = titles.iter().position(|title| pointer_reaches_title(ctx, title, p)) else {
|
||||
return;
|
||||
};
|
||||
if i != open
|
||||
let moving = ctx.input(|i| i.pointer.delta() != egui::Vec2::ZERO);
|
||||
if let Some(p) = ctx.pointer_hover_pos().filter(|_| moving)
|
||||
&& let Some(i) = titles.iter().position(|title| pointer_reaches_title(ctx, title, p))
|
||||
&& i != open
|
||||
&& let Some(id) = ids.get(i)
|
||||
{
|
||||
egui::Popup::open_id(ctx, *id);
|
||||
ctx.request_repaint();
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// A top-level menu's popup: as wide as its widest item (label plus shortcut), at least 230 pt;
|
||||
@@ -2859,13 +2889,21 @@ fn field_event(app: &mut VectorcraftApp, id: &str) -> Option<egui::Event> {
|
||||
/// Copy and Paste act on the field's text, as their keys do; everything else (and those commands
|
||||
/// with no field focused) goes to [`invoke`].
|
||||
pub fn invoke_from_system_menu(app: &mut VectorcraftApp, ctx: &egui::Context, id: &str, p: Value) {
|
||||
if ctx.text_edit_focused()
|
||||
&& let Some(e) = field_event(app, id)
|
||||
{
|
||||
ctx.input_mut(|i| i.events.push(e));
|
||||
return;
|
||||
match focused_text_field(ctx).and_then(|f| Some((f, field_event(app, id)?))) {
|
||||
Some((field, e)) => to_field(ctx, field, e),
|
||||
None => invoke(app, id, p),
|
||||
}
|
||||
invoke(app, id, p);
|
||||
}
|
||||
|
||||
/// The text field that has the keyboard, if any.
|
||||
fn focused_text_field(ctx: &egui::Context) -> Option<egui::Id> {
|
||||
ctx.memory(|m| m.focused()).filter(|&id| egui::TextEdit::load_state(ctx, id).is_some())
|
||||
}
|
||||
|
||||
/// Give text field `field` the keyboard (back) and event `e`, a [`field_event`], this frame.
|
||||
fn to_field(ctx: &egui::Context, field: egui::Id, e: egui::Event) {
|
||||
ctx.memory_mut(|m| m.request_focus(field));
|
||||
ctx.input_mut(|i| i.events.push(e));
|
||||
}
|
||||
|
||||
/// Invoke a menu/command id with UI side effects (dialogs for "…" commands that need input).
|
||||
@@ -3752,6 +3790,19 @@ mod tests {
|
||||
assert_eq!(pretty_shortcut(""), "");
|
||||
}
|
||||
|
||||
/// #543: Object › Image Trace › Make and Make and Expand trace with the Default preset at once,
|
||||
/// with no form asking for a preset's name.
|
||||
#[test]
|
||||
fn image_trace_make_traces_with_the_default_preset() {
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default());
|
||||
app.run("file.new", json!({})).unwrap();
|
||||
for cmd in ["imageTrace.make", "imageTrace.makeAndExpand"] {
|
||||
let e = menu_entries(&app).into_iter().find(|e| e.command.as_deref() == Some(cmd)).unwrap();
|
||||
assert_eq!(e.path, ["Object", "Image Trace"]);
|
||||
assert_eq!(click_target(&e.label, cmd, &e.params), (cmd.to_string(), json!({"preset": "Default"})), "{}", e.label);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expand_appearance_is_an_object_menu_item_only() {
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default());
|
||||
|
||||
@@ -52,9 +52,20 @@ pub const DISTRIBUTE: [(&str, &str, &str, &str); 6] = [
|
||||
("dc-dist-right", "Horizontal Distribute Right", "horizontal", "right"),
|
||||
];
|
||||
|
||||
/// Whether the selection has a key object.
|
||||
fn has_key(app: &VectorcraftApp) -> bool {
|
||||
app.session.active().is_some_and(|st| st.selection.key.is_some())
|
||||
}
|
||||
|
||||
/// What Align aligns to: the key object while there is one (a click on an object of the
|
||||
/// selection makes it the key), else the Align To choice.
|
||||
fn align_to(app: &VectorcraftApp, ctx: &egui::Context) -> AlignTo {
|
||||
if has_key(app) { AlignTo::Key } else { pstate(ctx, "align-to") }
|
||||
}
|
||||
|
||||
pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let n = selection_len(app);
|
||||
let to: AlignTo = pstate(ui.ctx(), "align-to");
|
||||
let to = align_to(app, ui.ctx());
|
||||
widgets::subheader(ui, tl!("Align Objects:"));
|
||||
ui.horizontal(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = 5.0;
|
||||
@@ -116,6 +127,10 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
] {
|
||||
if widgets::icon_button(ui, icon, tl!(tip), to == v, 28.0).clicked() {
|
||||
set_pstate(ui.ctx(), "align-to", v);
|
||||
// Aligning to the selection or the artboard lets go of the key object.
|
||||
if v != AlignTo::Key && has_key(app) {
|
||||
app.run("select.key", json!({})).ok();
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -132,8 +147,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
if menu_item(ui, tl!("Use Preview Bounds"), true, pb) {
|
||||
super::transform::set_pref(app, "usePreviewBounds", !pb);
|
||||
}
|
||||
let to: AlignTo = pstate(ui.ctx(), "align-to");
|
||||
if menu_item(ui, tl!("Cancel Key Object"), to == AlignTo::Key, false) {
|
||||
if menu_item(ui, tl!("Cancel Key Object"), align_to(app, ui.ctx()) == AlignTo::Key, false) {
|
||||
set_pstate(ui.ctx(), "align-to", AlignTo::Selection);
|
||||
app.run("select.key", json!({})).ok();
|
||||
}
|
||||
@@ -152,4 +166,21 @@ mod tests {
|
||||
assert_eq!(p["to"], "selection");
|
||||
assert_eq!(align_params(json!({}), AlignTo::Key, 1)["to"], "key");
|
||||
}
|
||||
|
||||
/// #541: while the selection has a key object Align aligns to it, whatever Align To says;
|
||||
/// choosing Align to Selection lets the key go.
|
||||
#[test]
|
||||
fn a_key_object_makes_align_align_to_it() {
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
|
||||
let a = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap()["id"].clone();
|
||||
let b = app.run("shape.rectangle", json!({"x": 80, "y": 50, "width": 30, "height": 30})).unwrap()["id"].clone();
|
||||
app.run("select.set", json!({"ids": [a, b]})).unwrap();
|
||||
let ctx = egui::Context::default();
|
||||
assert_eq!(align_to(&app, &ctx), AlignTo::Selection);
|
||||
app.run("select.key", json!({"id": b})).unwrap();
|
||||
assert_eq!(align_to(&app, &ctx), AlignTo::Key);
|
||||
app.run("select.key", json!({})).unwrap();
|
||||
assert_eq!(align_to(&app, &ctx), AlignTo::Selection, "no key: the choice again");
|
||||
}
|
||||
}
|
||||
@@ -83,10 +83,12 @@ fn cached(app: &mut VectorcraftApp, ctx: &egui::Context, o: &Options) -> Option<
|
||||
Some(c)
|
||||
}
|
||||
|
||||
/// The ids of the selected image objects.
|
||||
/// The ids of the selected image objects and placed documents.
|
||||
fn selected_images(app: &VectorcraftApp) -> Vec<u64> {
|
||||
let Some(st) = app.session.active() else { return vec![] };
|
||||
let image = |id: &NodeId| st.doc.node(*id).is_some_and(|n| matches!(n.kind, vectorcraft_doc::NodeKind::Image(_)));
|
||||
let image = |id: &NodeId| {
|
||||
st.doc.node(*id).is_some_and(|n| matches!(n.kind, vectorcraft_doc::NodeKind::Image(_) | vectorcraft_doc::NodeKind::PlacedDocument(_)))
|
||||
};
|
||||
st.selection.objects.iter().filter(|id| image(id)).map(|id| id.0).collect()
|
||||
}
|
||||
|
||||
@@ -170,6 +172,11 @@ pub(crate) fn open_file(app: &mut VectorcraftApp, p: &Value, reveal: bool) -> Re
|
||||
if info["status"] == "missing" {
|
||||
return Err(format!("{path} can't be found: relink it first"));
|
||||
}
|
||||
// A placed document's file opens here, in a new tab: saving it updates this document.
|
||||
if !reveal && info["document"] == true {
|
||||
app.run("document.open", json!({ "path": path }))?;
|
||||
return Ok(json!({ "path": path }));
|
||||
}
|
||||
if reveal { crate::io::reveal_path(app, &path) } else { crate::io::open_in_app(app, &path) }?;
|
||||
Ok(json!({ "path": path }))
|
||||
}
|
||||
@@ -293,11 +300,13 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
None => {}
|
||||
}
|
||||
if o.info {
|
||||
link_info(ui, cache.info.as_ref().map(|(_, i)| i));
|
||||
let units = app.session.general_unit();
|
||||
link_info(ui, cache.info.as_ref().map(|(_, i)| i), units);
|
||||
}
|
||||
let sel = selected_rows(&cache.list, &selected);
|
||||
let modified = ids(&sel, |r| status_is(r, "modified") || r["preview"] == true && !status_is(r, "missing"));
|
||||
let can_edit = sel.iter().any(|r| r["linked"] == true && !status_is(r, "missing"));
|
||||
let linked = ids(&sel, |r| r["linked"] == true);
|
||||
widgets::bottom_bar(ui, |ui| {
|
||||
let info = !o.info;
|
||||
if widgets::icon_button(ui, if o.info { "chevron-down" } else { "chevron-right" }, tl!("Show Link Info"), false, 24.0).clicked() {
|
||||
@@ -319,10 +328,24 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
if widgets::icon_button_enabled(ui, "link", tl!("Relink…"), false, !sel.is_empty() && can_pick(app), 24.0).clicked() {
|
||||
relink(app, ids(&sel, |_| true));
|
||||
}
|
||||
if widgets::icon_button_enabled(ui, "link-2-off", tl!("Break Link"), false, !linked.is_empty(), 24.0).clicked() {
|
||||
break_link(app, linked.clone());
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// Break Link (`links.embed`) of `ids`: images keep their files' pixels, placed documents become
|
||||
/// editable copies of their art.
|
||||
fn break_link(app: &mut VectorcraftApp, ids: Vec<u64>) {
|
||||
let r = app.run("links.embed", json!({ "ids": ids }));
|
||||
report(app, r, |v| {
|
||||
let missing = v["missing"].as_array().map_or(0, Vec::len);
|
||||
let n = v["embedded"].as_array().map_or(0, Vec::len);
|
||||
if missing == 0 { format!("Broke {n} link(s)") } else { format!("Broke {n} link(s); {missing} can't be read: relink or update them first") }
|
||||
});
|
||||
}
|
||||
|
||||
/// Pick-a-file actions need a file dialog (the desktop app).
|
||||
fn can_pick(app: &VectorcraftApp) -> bool {
|
||||
app.services.pick_open.is_some()
|
||||
@@ -344,7 +367,7 @@ pub(crate) fn date_label(ms: u64) -> String {
|
||||
}
|
||||
|
||||
/// The Link Info section: the details of `info` (`links.info`), or a hint.
|
||||
fn link_info(ui: &mut Ui, info: Option<&Value>) {
|
||||
fn link_info(ui: &mut Ui, info: Option<&Value>, units: vectorcraft_doc::Unit) {
|
||||
widgets::divider(ui);
|
||||
let Some(i) = info else {
|
||||
widgets::dim_label(ui, tl!("Select an image to see its Link Info."));
|
||||
@@ -365,9 +388,19 @@ fn link_info(ui: &mut Ui, info: Option<&Value>) {
|
||||
if let Some(l) = i["location"].as_str() {
|
||||
row(ui, tl!("Location"), l.into());
|
||||
}
|
||||
row(ui, tl!("PPI"), pair("ppi"));
|
||||
row(ui, tl!("Effective PPI"), pair("effectivePpi"));
|
||||
row(ui, tl!("Dimensions"), format!("{} × {} px", i["pixelWidth"], i["pixelHeight"]));
|
||||
// A placed document has no resolution: its rows are left out.
|
||||
for (label, k) in [(tl!("PPI"), "ppi"), (tl!("Effective PPI"), "effectivePpi")] {
|
||||
if i.get(k).is_some() {
|
||||
row(ui, label, pair(k));
|
||||
}
|
||||
}
|
||||
// Pixels, or a placed document's artboard size.
|
||||
let dims = match (i["pixelWidth"].as_u64(), i["pageWidth"].as_f64(), i["pageHeight"].as_f64()) {
|
||||
(Some(w), _, _) => format!("{w} × {} px", i["pixelHeight"].as_u64().unwrap_or(0)),
|
||||
(None, Some(w), Some(h)) => format!("{} × {}", units.format(w), units.format(h)),
|
||||
_ => String::new(),
|
||||
};
|
||||
row(ui, tl!("Dimensions"), dims);
|
||||
let scale: Vec<f64> = i["scale"].as_array().into_iter().flatten().filter_map(Value::as_f64).collect();
|
||||
if let [x, y] = scale[..] {
|
||||
row(ui, tl!("Scale"), format!("H: {x:.1}% V: {y:.1}%"));
|
||||
|
||||
@@ -13,6 +13,8 @@ use crate::widgets::{self, menu_item};
|
||||
use crate::{VectorcraftApp, icons};
|
||||
|
||||
pub const ANGLE_PRESETS: [f64; 9] = [-180.0, -135.0, -90.0, -45.0, 0.0, 45.0, 90.0, 135.0, 180.0];
|
||||
/// The shear angle's presets: steep enough to be useful, short of the degenerate ±90°.
|
||||
pub const SHEAR_PRESETS: [f64; 9] = [-60.0, -45.0, -30.0, -15.0, 0.0, 15.0, 30.0, 45.0, 60.0];
|
||||
|
||||
/// Proportional size: the other dimension when one changes with the link on.
|
||||
pub fn constrained(w: f64, h: f64, new_w: Option<f64>, new_h: Option<f64>) -> (f64, f64) {
|
||||
@@ -151,8 +153,10 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
ui.add_space(4.0);
|
||||
let icon = icons::icon(ui, "dc-shear", 16.0, t.icon).on_hover_text(tl!("Shear"));
|
||||
crate::scrub::note_label(ui, icon.rect);
|
||||
if let Some(a) = widgets::plain_field(ui, "xfp-shear", 0.0, "°", 1, 56.0)
|
||||
// Shear is relative: the field rests at 0° and a new value shears by it.
|
||||
if let Some(a) = widgets::spin_plain(ui, "xfp-shear", 0.0, "°", 2, 96.0, 15.0, -89.0, &SHEAR_PRESETS)
|
||||
&& a != 0.0
|
||||
&& a.abs() < 90.0
|
||||
{
|
||||
app.run("object.shear", json!({"angle": a, "axis": "horizontal", "origin": origin})).ok();
|
||||
}
|
||||
@@ -206,6 +210,17 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The Control bar's underlined "Transform" link: a click toggles the Transform panel in a
|
||||
/// popover under it, as the Stroke link does with the Stroke panel.
|
||||
pub fn link(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let resp = ui.link(egui::RichText::new(tl!("Transform")).size(12.0).color(t.text).underline()).on_hover_text(tl!("Transform options"));
|
||||
widgets::popover(&resp, resp.clicked(), |ui| {
|
||||
ui.set_width(300.0);
|
||||
show(app, ui);
|
||||
});
|
||||
}
|
||||
|
||||
/// The link between W and H (Transform panel, Properties panel, Control bar): one toggle, the
|
||||
/// `constrainProportions` preference, which the size fields pass on as `proportional`.
|
||||
pub fn constrain_link(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
|
||||
@@ -160,11 +160,20 @@ fn open_dialog(app: &mut VectorcraftApp, files: Vec<Value>) {
|
||||
"template": false,
|
||||
"replace": false,
|
||||
"__replace": files.len() == 1 && one_object,
|
||||
"__documents": files.iter().any(is_vectorcraft_file),
|
||||
"__others": !files.iter().all(is_vectorcraft_file),
|
||||
"__info": info,
|
||||
}),
|
||||
));
|
||||
}
|
||||
|
||||
/// Is dialog file entry `file` a VectorCraft document on disk (what Link places as one locked
|
||||
/// object)?
|
||||
fn is_vectorcraft_file(file: &Value) -> bool {
|
||||
let native = ["vectorcraft", vectorcraft_format::LEGACY_EXTENSION, "vctemplate"];
|
||||
file.get("path").and_then(Value::as_str).is_some_and(|p| native.contains(&fileio::extension(p).as_str()))
|
||||
}
|
||||
|
||||
/// The engine params naming `file` (a dialog file entry).
|
||||
fn source(app: &VectorcraftApp, file: &Value) -> Option<Value> {
|
||||
if let Some(path) = file.get("path").and_then(Value::as_str) {
|
||||
|
||||
@@ -270,3 +270,51 @@ fn menus_that_only_pick_a_font_leave_the_document_alone() {
|
||||
assert_eq!(picked(&mut app, Some(FontPick::Favorite("inter".into()))), None);
|
||||
assert!(app.ui.favorite_fonts.is_empty());
|
||||
}
|
||||
|
||||
/// #555: the menu's search field and filters stay at its top while the wheel scrolls the families,
|
||||
/// past the list's end too: the list is the menu's one scrolling part.
|
||||
#[test]
|
||||
fn the_search_field_stays_put_while_the_list_scrolls() {
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
let frame = |events: Vec<egui::Event>| {
|
||||
let input =
|
||||
egui::RawInput { events, screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, 500.0))), ..Default::default() };
|
||||
let mut at = egui::Pos2::ZERO;
|
||||
let mut out = ctx.run_ui(input, |ui| {
|
||||
// Low in the window, as in a panel at the bottom of the dock: the menu opens upwards.
|
||||
ui.add_space(390.0);
|
||||
at = ui.next_widget_position();
|
||||
font_menu(ui, "test-scroll", "Inter", 260.0, None, MenuLook::default());
|
||||
});
|
||||
out.textures_delta.clear();
|
||||
let search = out.shapes.iter().find_map(|s| match &s.shape {
|
||||
egui::Shape::Text(t) if t.galley.text() == "Search" => Some(t.pos),
|
||||
_ => None,
|
||||
});
|
||||
(at, search)
|
||||
};
|
||||
let (at, _) = frame(vec![]);
|
||||
let click = at + egui::vec2(40.0, 10.0);
|
||||
let button = |pressed| egui::Event::PointerButton { pos: click, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
|
||||
frame(vec![egui::Event::PointerMoved(click), button(true)]);
|
||||
frame(vec![button(false)]);
|
||||
let mut field = None;
|
||||
for _ in 0..5 {
|
||||
field = frame(vec![]).1;
|
||||
}
|
||||
let field = field.expect("the search field shows");
|
||||
let over_list = egui::pos2(field.x + 40.0, field.y + 120.0);
|
||||
for dy in [-400.0, -4000.0, -4000.0] {
|
||||
let wheel = egui::Event::MouseWheel {
|
||||
unit: egui::MouseWheelUnit::Point,
|
||||
delta: egui::vec2(0.0, dy),
|
||||
modifiers: Default::default(),
|
||||
phase: egui::TouchPhase::Move,
|
||||
};
|
||||
frame(vec![egui::Event::PointerMoved(over_list), wheel]);
|
||||
for _ in 0..10 {
|
||||
assert_eq!(frame(vec![]).1, Some(field), "the field stays where it was");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -242,3 +242,31 @@ fn the_window_menu_panel_keys() {
|
||||
app.ui.shortcut_overrides.clear();
|
||||
shortcut_editor::sync(&app.ui);
|
||||
}
|
||||
|
||||
/// Where `shapes` paint the text `s`.
|
||||
fn text_rect(shapes: &[Shape], s: &str) -> Option<Rect> {
|
||||
shapes.iter().find_map(|sh| match sh {
|
||||
Shape::Text(t) if t.galley.text() == s => Some(t.visual_bounding_rect()),
|
||||
Shape::Vec(v) => text_rect(v, s),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_transform_link_opens_the_transform_panel() {
|
||||
let mut app = app();
|
||||
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap();
|
||||
let ctx = context();
|
||||
frame(&mut app, &ctx, vec![], Modifiers::NONE, control_bar);
|
||||
let shapes = frame(&mut app, &ctx, vec![], Modifiers::NONE, control_bar);
|
||||
let link = text_rect(&shapes, "Transform").expect("the Control bar shows the Transform link");
|
||||
assert!(text_rect(&shapes, "Scale Corners").is_none());
|
||||
click(&mut app, &ctx, link.center(), Modifiers::NONE, control_bar);
|
||||
let shapes = frame(&mut app, &ctx, vec![], Modifiers::NONE, control_bar);
|
||||
for s in ["Scale Corners", "Scale Strokes & Effects", "0°"] {
|
||||
assert!(text_rect(&shapes, s).is_some(), "the popover shows {s}");
|
||||
}
|
||||
// A click outside closes it.
|
||||
click(&mut app, &ctx, Pos2::new(1300.0, 900.0), Modifiers::NONE, control_bar);
|
||||
assert!(text_rect(&frame(&mut app, &ctx, vec![], Modifiers::NONE, control_bar), "Scale Corners").is_none());
|
||||
}
|
||||
@@ -361,3 +361,40 @@ fn the_control_bars_mask_clips_the_image_and_selects_the_clipping_path() {
|
||||
let ids: Vec<u64> = group.children().unwrap().iter().map(|c| c.id.0).collect();
|
||||
assert_eq!((ids[1], st.selection.objects.iter().map(|i| i.0).collect::<Vec<_>>()), (img, vec![ids[0]]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_vectorcraft_document_places_linked_and_edit_original_opens_it() {
|
||||
let mut app = app();
|
||||
// A one-artboard document with a rectangle.
|
||||
let mut src = Session::new();
|
||||
src.execute("file.new", &json!({"width": 100, "height": 50})).unwrap();
|
||||
src.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 100, "height": 50})).unwrap();
|
||||
let bytes = vectorcraft_format::save_file(&src.active().unwrap().doc);
|
||||
let path = temp_file("badge.vectorcraft", &bytes);
|
||||
place_picked(&mut app, &path);
|
||||
let d = app.ui.dialog.as_ref().expect("the Place dialog");
|
||||
assert!(d.bool("link") && d.bool("__documents") && !d.bool("__others"), "Link on, for a document");
|
||||
// Link's tooltip says what it does for a document.
|
||||
assert!(crate::dialogs::place::link_tip(d).contains("editable copy"));
|
||||
crate::dialogs::confirm(&mut app).unwrap();
|
||||
let st = app.session.active().unwrap();
|
||||
let id = st.selection.objects[0];
|
||||
let vectorcraft_doc::NodeKind::PlacedDocument(p) = &st.doc.node(id).unwrap().kind else { panic!("not a placed document") };
|
||||
assert_eq!(p.link.path, path);
|
||||
// Edit Original opens the document in a new tab.
|
||||
let tabs = app.session.documents().len();
|
||||
app.run("links.editOriginal", json!({})).unwrap();
|
||||
assert_eq!(app.session.documents().len(), tabs + 1);
|
||||
assert_eq!(app.session.active().unwrap().path.as_deref(), Some(path.as_str()));
|
||||
// A PNG keeps the image tooltip; a PNG and a document, both.
|
||||
let pic = temp_file("pic.png", &png(10, 10, 72.0));
|
||||
place_picked(&mut app, &pic);
|
||||
let d = app.ui.dialog.as_ref().unwrap();
|
||||
assert!(!d.bool("__documents") && crate::dialogs::place::link_tip(d).contains("image file"));
|
||||
app.ui.dialog = None;
|
||||
let both = vec![pic.clone(), path.clone()];
|
||||
app.services.pick_open_multi = Some(Box::new(move || both.clone()));
|
||||
app.run("file.place", json!({})).unwrap();
|
||||
let d = app.ui.dialog.as_ref().unwrap();
|
||||
assert!(crate::dialogs::place::link_tip(d).contains("VectorCraft documents"));
|
||||
}
|
||||
@@ -171,3 +171,94 @@ fn cmd_a_on_the_canvas_selects_all_objects() {
|
||||
a.menu("select.all");
|
||||
assert_eq!(a.selected(), 2, "so does the menu's Select All");
|
||||
}
|
||||
|
||||
/// The copied texts of a frame's output.
|
||||
fn copied(out: &egui::FullOutput) -> Vec<String> {
|
||||
out.platform_output.commands.iter().filter_map(|c| if let egui::OutputCommand::CopyText(t) = c { Some(t.clone()) } else { None }).collect()
|
||||
}
|
||||
|
||||
/// #516: Ctrl/Cmd+C, X and V in a focused field (the window's own clipboard keys, which egui sends
|
||||
/// as Copy, Cut and Paste events) edit the field's text, never the art.
|
||||
#[test]
|
||||
fn the_clipboard_keys_in_a_focused_field_edit_its_text() {
|
||||
let mut a = App::new();
|
||||
a.app.run("window.panel", json!({"panel": "color"})).unwrap();
|
||||
for _ in 0..3 {
|
||||
a.frame(vec![]);
|
||||
}
|
||||
for text in ["37 pt", "FFFFFF"] {
|
||||
let (id, rect) = a.field(text);
|
||||
a.frame(vec![Event::PointerMoved(rect.center()), click(rect.center(), true)]);
|
||||
a.frame(vec![click(rect.center(), false)]);
|
||||
a.frame(vec![press(Key::A, Modifiers::COMMAND)]);
|
||||
assert!(a.ctx.memory(|m| m.has_focus(id)), "{text}: the field has the keyboard");
|
||||
let out = a.frame(vec![Event::Copy]);
|
||||
assert_eq!(copied(&out), [text], "Copy copies the field's text");
|
||||
assert!(a.app.session.clipboard.is_empty(), "{text}: no art copied");
|
||||
let out = a.frame(vec![Event::Cut]);
|
||||
assert_eq!(copied(&out), [text], "Cut cuts the field's text");
|
||||
a.frame(vec![Event::Paste("12".into())]);
|
||||
assert_eq!(a.ctx.data(|d| d.get_temp::<String>(id)).as_deref(), Some("12"), "Paste pastes into the field");
|
||||
assert_eq!(a.selected(), 1, "{text}: the art stays");
|
||||
a.frame(vec![press(Key::Escape, Modifiers::NONE)]);
|
||||
}
|
||||
}
|
||||
|
||||
/// The centre of the text `label` painted last (in the topmost layer) in a frame's output; with
|
||||
/// `title`, the first one painted (the menu bar's).
|
||||
fn text_at(out: &egui::FullOutput, label: &str, title: bool) -> Pos2 {
|
||||
let mut shapes: Box<dyn Iterator<Item = _>> = if title { Box::new(out.shapes.iter()) } else { Box::new(out.shapes.iter().rev()) };
|
||||
shapes
|
||||
.find_map(|s| match &s.shape {
|
||||
egui::Shape::Text(t) if t.galley.text().trim() == label => Some(Rect::from_min_size(t.pos, t.galley.size()).center()),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or_else(|| panic!("no {label:?} painted"))
|
||||
}
|
||||
|
||||
/// A click on `at` → the frame after it.
|
||||
fn click_at(a: &mut App, at: Pos2) -> egui::FullOutput {
|
||||
a.frame(vec![Event::PointerMoved(at), click(at, true)]);
|
||||
a.frame(vec![click(at, false)]);
|
||||
a.frame(vec![])
|
||||
}
|
||||
|
||||
/// The in-window menus' Select › All, Edit › Copy and Edit › Paste act on the text field that had the keyboard
|
||||
/// when the menu was opened (the click on the menu took it), and give it the keyboard back.
|
||||
#[test]
|
||||
fn the_in_window_edit_menu_acts_on_the_field_it_was_opened_from() {
|
||||
let mut a = App::new();
|
||||
// Text on the system clipboard.
|
||||
a.app.services.clipboard_read = Some(Box::new(|| Some("42 pt".into())));
|
||||
let (id, rect) = a.field("37 pt");
|
||||
a.frame(vec![Event::PointerMoved(rect.center()), click(rect.center(), true)]);
|
||||
a.frame(vec![click(rect.center(), false)]);
|
||||
let out = a.frame(vec![press(Key::End, Modifiers::NONE)]);
|
||||
let (edit, select) = (text_at(&out, "Edit", true), text_at(&out, "Select", true));
|
||||
let menu = |a: &mut App, title: Pos2, item: &str| {
|
||||
let out = click_at(a, title);
|
||||
assert!(!a.ctx.text_edit_focused(), "the menu took the keyboard");
|
||||
click_at(a, text_at(&out, item, false))
|
||||
};
|
||||
menu(&mut a, select, "All");
|
||||
assert!(a.ctx.memory(|m| m.has_focus(id)), "the field has the keyboard back");
|
||||
assert_eq!(a.field_selection(id), Some((0, 5)), "Select All selected the field's text");
|
||||
assert_eq!(a.selected(), 1, "not the art");
|
||||
a.frame(vec![press(Key::End, Modifiers::NONE)]);
|
||||
a.frame(vec![press(Key::A, Modifiers::COMMAND)]);
|
||||
a.frame(vec![]);
|
||||
let out = menu(&mut a, edit, "Copy");
|
||||
assert_eq!(copied(&out), ["37 pt"], "Copy copied the field's text");
|
||||
assert!(a.app.session.clipboard.is_empty(), "no art copied");
|
||||
// Art on the app's clipboard (Paste is enabled): the field still takes the text.
|
||||
a.app.run("edit.copy", json!({})).unwrap();
|
||||
a.frame(vec![press(Key::A, Modifiers::COMMAND)]);
|
||||
menu(&mut a, edit, "Paste");
|
||||
assert_eq!(a.ctx.data(|d| d.get_temp::<String>(id)).as_deref(), Some("42 pt"), "Paste pasted into the field");
|
||||
assert_eq!(a.selected(), 1, "nothing pasted on the canvas");
|
||||
// With no field focused, the menu's Select All selects the art.
|
||||
a.frame(vec![press(Key::Escape, Modifiers::NONE)]);
|
||||
a.frame(vec![]);
|
||||
menu(&mut a, select, "All");
|
||||
assert_eq!(a.selected(), 2);
|
||||
}
|
||||
@@ -655,11 +655,13 @@ pub(crate) fn combo<R>(
|
||||
.stroke(Stroke::new(1.0, t.input_border))
|
||||
.corner_radius(CornerRadius::same(3))
|
||||
.show(ui, |ui| {
|
||||
if searchable {
|
||||
return searchable_combo(ui, ui.id().with(id), current, width - 4.0, list);
|
||||
}
|
||||
egui::ComboBox::from_id_salt(ui.id().with(id))
|
||||
.selected_text(egui::RichText::new(current).size(12.0))
|
||||
.width(width - 4.0)
|
||||
.close_behavior(if searchable { egui::PopupCloseBehavior::CloseOnClickOutside } else { egui::PopupCloseBehavior::CloseOnClick })
|
||||
.height(if searchable { f32::INFINITY } else { ui.spacing().combo_height })
|
||||
.height(ui.spacing().combo_height)
|
||||
.show_ui(ui, list)
|
||||
.inner
|
||||
.flatten()
|
||||
@@ -667,6 +669,58 @@ pub(crate) fn combo<R>(
|
||||
.inner
|
||||
}
|
||||
|
||||
/// A dropdown whose list keeps its own search field and scrolling rows (the font menu): drawn as
|
||||
/// egui's combo box, but in a popup without the scroll area egui puts around a combo's list, so
|
||||
/// the field stays at the top and only the rows scroll (#555). A click outside closes it.
|
||||
fn searchable_combo<R>(ui: &mut Ui, id: egui::Id, current: &str, width: f32, list: impl FnOnce(&mut Ui) -> Option<R>) -> Option<R> {
|
||||
let popup = id.with("popup");
|
||||
let open = egui::Popup::is_id_open(ui.ctx(), popup);
|
||||
let pad = ui.spacing().button_padding;
|
||||
let icon = Vec2::splat(ui.spacing().icon_width);
|
||||
let galley = egui::WidgetText::from(egui::RichText::new(current).size(12.0)).into_galley(
|
||||
ui,
|
||||
Some(egui::TextWrapMode::Truncate),
|
||||
width - 2.0 * pad.x - ui.spacing().icon_spacing - icon.x,
|
||||
egui::TextStyle::Button,
|
||||
);
|
||||
let height = (galley.size().y.max(icon.y) + 2.0 * pad.y).max(ui.spacing().interact_size.y);
|
||||
let (rect, resp) = ui.allocate_exact_size(vec2(width, height), Sense::click());
|
||||
if ui.is_rect_visible(rect) {
|
||||
let v = if open { ui.visuals().widgets.open } else { *ui.style().interact(&resp) };
|
||||
ui.painter().rect(rect.expand(v.expansion), v.corner_radius, v.weak_bg_fill, v.bg_stroke, StrokeKind::Inside);
|
||||
let inner = rect.shrink2(pad);
|
||||
ui.painter().galley(egui::Align2::LEFT_CENTER.align_size_within_rect(galley.size(), inner).min, galley, v.text_color());
|
||||
// egui's combo arrow: a downward triangle.
|
||||
let arrow =
|
||||
Rect::from_center_size(egui::Align2::RIGHT_CENTER.align_size_within_rect(icon, inner).center(), vec2(icon.x * 0.7, icon.y * 0.45));
|
||||
ui.painter().add(egui::Shape::convex_polygon(
|
||||
vec![arrow.left_top(), arrow.right_top(), arrow.center_bottom()],
|
||||
v.fg_stroke.color,
|
||||
Stroke::NONE,
|
||||
));
|
||||
}
|
||||
// It opens below the button, or above it when there is more room there, and the list gets
|
||||
// the room left (the popup's frame aside).
|
||||
const GAP: f32 = 12.0;
|
||||
let screen = ui.ctx().content_rect();
|
||||
let frame = ui.spacing().menu_margin.sum().y + GAP;
|
||||
let (below, above) = (screen.bottom() - rect.bottom() - frame, rect.top() - screen.top() - frame);
|
||||
let (align, room) = if below >= above { (egui::RectAlign::BOTTOM_START, below) } else { (egui::RectAlign::TOP_START, above) };
|
||||
egui::Popup::menu(&resp)
|
||||
.id(popup)
|
||||
.width(rect.width())
|
||||
.align(align)
|
||||
.align_alternatives(&[])
|
||||
.close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside)
|
||||
.show(|ui| {
|
||||
ui.set_min_width(ui.available_width());
|
||||
ui.set_max_height(room);
|
||||
ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Extend);
|
||||
list(ui)
|
||||
})
|
||||
.and_then(|r| r.inner)
|
||||
}
|
||||
|
||||
/// A popover anchored to `resp`, opened and closed by `toggle` (usually `resp.clicked()`), and
|
||||
/// closed by Escape, a click outside it and outside any popup it opened, or a frame in which its
|
||||
/// anchor isn't shown. Use it instead of `egui::Popup::menu` when the popover holds dropdowns or
|
||||
@@ -806,18 +860,23 @@ pub fn opacity_blend(
|
||||
edit
|
||||
}
|
||||
|
||||
/// The 3×3 reference point locator. Returns a new index when clicked.
|
||||
/// The 3×3 reference point locator: nine squares, the eight outer ones joined by a line around
|
||||
/// the box (the centre one stands alone), the current one filled. Returns a new index when clicked.
|
||||
pub fn reference_point(ui: &mut Ui, current: usize) -> Option<usize> {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let size = 22.0;
|
||||
// 5 pt squares with 4 pt gaps; the origin is snapped to whole points so the 1 pt lines through
|
||||
// the squares' centres stay crisp.
|
||||
let (sq, step) = (5.0, 9.0);
|
||||
let size = 2.0 * step + sq;
|
||||
let (rect, _) = ui.allocate_exact_size(Vec2::splat(size), Sense::hover());
|
||||
let o = rect.min.round();
|
||||
let centre = |i: usize| o + Vec2::new(sq / 2.0 + (i % 3) as f32 * step, sq / 2.0 + (i / 3) as f32 * step);
|
||||
let line = Stroke::new(1.0, t.text_dim);
|
||||
ui.painter().rect_stroke(Rect::from_two_pos(centre(0), centre(8)), 0.0, line, StrokeKind::Middle);
|
||||
let mut out = None;
|
||||
let step = size / 2.0 - 2.5;
|
||||
ui.painter().rect_stroke(rect.shrink(4.5), 0.0, Stroke::new(1.0, t.text_dim), StrokeKind::Middle);
|
||||
for i in 0..9 {
|
||||
let c = Pos2::new(rect.left() + 3.0 + (i % 3) as f32 * step + 1.5, rect.top() + 3.0 + (i / 3) as f32 * step + 1.5);
|
||||
let r = Rect::from_center_size(c, Vec2::splat(5.0));
|
||||
let resp = ui.interact(r.expand(1.5), ui.id().with(("refpt", i)), Sense::click());
|
||||
let r = Rect::from_center_size(centre(i), Vec2::splat(sq));
|
||||
let resp = ui.interact(r.expand(2.0), ui.id().with(("refpt", i)), Sense::click());
|
||||
if resp.clicked() {
|
||||
out = Some(i);
|
||||
}
|
||||
@@ -825,7 +884,7 @@ pub fn reference_point(ui: &mut Ui, current: usize) -> Option<usize> {
|
||||
ui.painter().rect_filled(r, 0.0, t.text);
|
||||
} else {
|
||||
ui.painter().rect_filled(r, 0.0, t.panel);
|
||||
ui.painter().rect_stroke(r, 0.0, Stroke::new(1.0, t.text_dim), StrokeKind::Inside);
|
||||
ui.painter().rect_stroke(r, 0.0, Stroke::new(1.0, if resp.hovered() { t.text } else { t.text_dim }), StrokeKind::Inside);
|
||||
}
|
||||
}
|
||||
out
|
||||
@@ -903,8 +962,21 @@ pub fn check(ui: &mut Ui, label: &str, value: bool, enabled: bool) -> bool {
|
||||
check3(ui, label, Some(value), enabled)
|
||||
}
|
||||
|
||||
/// [`check`] with tooltip `tip` on the box and its label. Returns true when toggled.
|
||||
pub fn check_tip(ui: &mut Ui, label: &str, value: bool, enabled: bool, tip: &str) -> bool {
|
||||
let (clicked, resp) = check_row(ui, label, Some(value), enabled);
|
||||
resp.on_hover_text(tip);
|
||||
clicked
|
||||
}
|
||||
|
||||
/// Three-state [`check`]: `None` shows a dash (a neutral or mixed state). Returns true when clicked.
|
||||
pub fn check3(ui: &mut Ui, label: &str, value: Option<bool>, enabled: bool) -> bool {
|
||||
check_row(ui, label, value, enabled).0
|
||||
}
|
||||
|
||||
/// [`check3`], also returning the row's response (what a tooltip goes on: a widget around it never
|
||||
/// counts as hovered under the box).
|
||||
fn check_row(ui: &mut Ui, label: &str, value: Option<bool>, enabled: bool) -> (bool, Response) {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let (bx, resp, border) = choice_row(ui, label, enabled);
|
||||
let checked = value == Some(true);
|
||||
@@ -922,7 +994,7 @@ pub fn check3(ui: &mut Ui, label: &str, value: Option<bool>, enabled: bool) -> b
|
||||
}
|
||||
Some(false) => {}
|
||||
}
|
||||
enabled && resp.clicked()
|
||||
(enabled && resp.clicked(), resp)
|
||||
}
|
||||
|
||||
/// Radio button in the style of [`check`], with a disabled state. Returns true when clicked.
|
||||
|
||||
+1
-1
@@ -38,7 +38,7 @@ How the web shell (`apps/vectorcraft-web/src/web.rs`) differs from desktop:
|
||||
|
||||
The canvas is rasterized on the CPU (`vectorcraft-render`, vello_cpu); the GPU (wgpu, through eframe) only composites the canvas texture and draws the UI, so any GPU that can show the window will do. The desktop app picks the window's adapter itself (`apps/vectorcraft/src/gpu.rs`, eframe's `native_adapter_selector`) and logs every adapter it found and the one it uses.
|
||||
|
||||
- **Order:** adapters that report they can't present to the window are never tried; then the one `WGPU_ADAPTER_NAME` names; hardware before software (llvmpipe, WARP); the native backends (Vulkan, Metal, DX12) before OpenGL; then the power preference, keeping the system's order among equals.
|
||||
- **Order:** adapters that report they can't present to the window are never tried; then the one `WGPU_ADAPTER_NAME` names; hardware before software (llvmpipe, WARP); the native backends (Vulkan, Metal, DX12) before OpenGL; then the power preference; then, on Windows, where each GPU is listed under both, a GPU's DX12 adapter before its Vulkan one (Intel's Vulkan driver made the whole window flicker black, #545), keeping the system's order among equals. `WGPU_BACKEND=vulkan` still picks Vulkan.
|
||||
- **Preferences › Performance › Graphics Processor** (`gpuPreference`): `automatic` (the default), `lowPower` (Power Saving, the integrated GPU) or `highPerformance` (the discrete GPU). The adapter is chosen when the window opens, so a change applies after a restart.
|
||||
- **Automatic on Windows and macOS** is power saving: the system shows frames from any GPU, and presenting frames rendered on a discrete GPU through the integrated one made the window flicker on some hybrid laptops (#306).
|
||||
- **Automatic on Linux and the BSDs** keeps the system's order: Mesa's Vulkan device-select layer puts the GPU the desktop runs on first (the integrated one on hybrid laptops; `DRI_PRIME` and `MESA_VK_DEVICE_SELECT` steer it). A Wayland compositor may not accept frames from another GPU: on a desktop whose compositor ran on an NVIDIA GPU, rendering on the Ryzen's integrated GPU made KWin end the window's connection ("importing the supplied dmabufs failed") and 0.5.0 crashed at startup (#502).
|
||||
|
||||
+16
-3
@@ -251,7 +251,7 @@ colour group (one undo step).
|
||||
SVG Options: `export` to SVG takes them in `options`, flat or as `{"svg": {…}}`: `styling` (`presentation`,
|
||||
`style`, `entities`, `css`), `outlineText`, `images` (`embed`, or `link`: embedded images are written next to the
|
||||
SVG, or returned as `linked`), `objectIds` (`layerNames`, `minimal`, `unique`), `decimals` (1–7), `minify`,
|
||||
`responsive`, `useArtboards`, `range: "all"` (one SVG per artboard, listed in `files`), `preserveEditing` (the SVG
|
||||
`responsive`, `useArtboards`, `range: "all"` (one SVG per artboard, listed in `files`, each holding only the art over its artboard), `preserveEditing` (the SVG
|
||||
reopens as the full document), `metadata` and `fewerTspans` (one `<tspan>` per line of type). Unknown keys inside `svg` are rejected; `run_command document.formats`
|
||||
lists every option with its default. `encoding` is `utf8`, `utf16` (big-endian after a byte order mark) or `latin1`
|
||||
(ISO 8859-1, other characters as `&#x…;` references); `document.serialize` still answers `text`, plus `dataBase64`
|
||||
@@ -423,6 +423,8 @@ document exactly (`restored: true`); when another app changed the pages, or the
|
||||
imported instead and the first warning says why. Choosing a standard turns it off (PDF/A refuses it). Save to a `.ai`
|
||||
path (`document.save {path: "art.ai"}` or `{format: "ai"}`) writes a PDF-compatible file that always carries the
|
||||
document, takes the PDF options and keeps its path when reopened, so Save writes `.ai` again; a `.ait` opens untitled.
|
||||
`document.export` / `serialize` to `.ai` (and the CLI's `run --export x.ai` and `convert in.svg out.ai`) write the same file
|
||||
without giving the document a path.
|
||||
|
||||
Drive a tool like a mouse:
|
||||
|
||||
@@ -1424,8 +1426,11 @@ passed straight back to `file.new`. Print presets and sizes without `units` star
|
||||
|
||||
`file.place` puts another file's art into the active document as one undo step without touching the clipboard:
|
||||
a raster image at 100% of its physical size (the resolution its file declares, else 72 ppi; linked to its `path`
|
||||
unless `link: false`), an SVG as one group, a PDF/.ai page or a native document's artboard (`page`, `crop`) as one
|
||||
clipped group, with the images, symbols, patterns and swatches it uses. `at` centres it, `rect` fits it, `replace`
|
||||
unless `link: false`), an SVG as one group, a PDF/.ai page as one clipped group, with the images, symbols, patterns
|
||||
and swatches it uses. A VectorCraft document read from `path` is a placed document: one locked object showing its
|
||||
artboard `page` (or, with `crop: "bounding"`, its art's bounds), linked to the file and read again when it changes
|
||||
(see Linked images), and vectors in every output; with `link: false` (or from `dataBase64`) it is an editable copy
|
||||
of its art, as one clipped group. `at` centres it, `rect` fits it, `replace`
|
||||
swaps the selected object (keeping its place and transform), `template` puts it on a new template layer.
|
||||
`file.place.info` describes a file without placing it and `image.info` reports a placed image's link, colour mode and
|
||||
effective ppi. `file.place.queue` loads the place cursor (the `place` tool) with several files: headless, drive it
|
||||
@@ -1534,6 +1539,14 @@ in `updatedLinks`), each as `{name, path, ids}`. `links.check` reports every lin
|
||||
another file (or each at the file of its name in a folder); images keep their bounds, one undo step each. Without a
|
||||
file system (the web), linked images show their previews.
|
||||
|
||||
Placed documents (a `.vectorcraft` file placed linked) work the same way: the document keeps the file's bytes and a
|
||||
preview (JPEG or PNG, 1 px per point, at most 1024 px a side), and a save writes the preview (Include Linked Files:
|
||||
the file); output reads the file again, or uses the preview with a warning when it is gone or changed.
|
||||
`links.list` and `links.info` give them `document: true` and the artboard's `pageWidth` and `pageHeight` (pt).
|
||||
Saving the file in the app updates the open documents that place it. `links.embed` (the Links panel's Break Link)
|
||||
turns one into the editable copy placing without link gives, its symbols, patterns, swatches and images joining
|
||||
the document; so does `object.expand`.
|
||||
|
||||
```json
|
||||
{"name":"run_command","arguments":{"command":"links.check","params":{}}}
|
||||
{"name":"run_command","arguments":{"command":"links.relink","params":{"ids":[12],"path":"/new/photo.png"}}}
|
||||
|
||||
Reference in new issue
Block a user