Compare commits

..
Author SHA1 Message Date
bflatasticandClaude Opus 5.5 90d6785eb5 Part of #394: Animated Zoom, Large Tabs, Scale Cursor and anti-aliased bitmaps act
- Performance › Animated Zoom (with GPU Performance, which dims it when
  off): the Zoom tool dragged sideways zooms about the press (right in,
  left out) and held still zooms on (Alt: out); a click still steps. Off,
  a drag zooms to the area dragged across, now drawn as a marquee. The
  hint bar says which.
- User Interface › Large Tabs: taller document tabs with larger titles.
- User Interface › Scale Cursor Proportional to UI: off, the tool cursors
  keep their size whatever the UI Scaling (OS and painted cursors alike).
- File Handling › Display Bitmaps as Anti-aliased Images in Pixel
  Preview: off (the default), Pixel Preview samples images nearest-pixel
  (`RenderOptions::smooth_images`).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 11:22:43 +07:00
BFlat 01ad745e86 Merge pull request #668 from storytold/fix/663-recent-and-preset-dblclick
Part of #663: Home screen Recent Files; a double-clicked preset creates the document
2026-10-09 11:20:12 +07:00
bflatasticandClaude Opus 5.5 d8f6bacddb Part of #663: Home screen Recent Files; a double-clicked preset creates the document
- The Home screen lists the first six of File > Open Recent Files, each by name
  (a click opens it) and folder; one that can't be opened says so in the status
  bar. With none, there is no section.
- In New Document, a double-click on a preset card creates the document from
  it; a click still only chooses it. The Create buttons no longer overwrite a
  create asked for earlier in the frame.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 11:17:35 +07:00
BFlat fc74389b5a Merge pull request #660 from Haven-King/fix/text-engine-integration
Fix/text engine integration
2026-10-09 10:45:11 +07:00
BFlat 0891ffbf51 Merge pull request #659 from storytold/fix/449-two-finger-pan
Part of #449: two fingers dragged on a touch screen pan the canvas
2026-10-09 10:37:26 +07:00
bflatasticandClaude Opus 5.5 861a0759b0 Part of #449: two fingers dragged on a touch screen pan the canvas
A pinch already zoomed the canvas and a second finger already cancelled the
first finger's press, but dragging two fingers together did nothing: the
canvas only read wheel scrolls, and a touch screen sends touches. The fingers'
movement (egui's multi-touch translation) now scrolls the canvas under either
Zoom with Mouse Wheel setting, and zoom and scroll apply in the same frame, so
a pinch that also slides pans too. Trackpads send scrolls, so nothing counts
twice.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 10:34:22 +07:00
haven 992f6a0a4d M7: tests for the text engine features combined
Layout (vectorcraft-text tests_combos): every pair of ligatures under tracking,
the paragraph composer, vertical alignment, Shrink Text to Fit, per-paragraph
attributes and inline graphics, and all six at once. Commands
(vectorcraft-engine tests_textcombos): Auto Size and Shrink Text with inline
art, paragraphs, composer and alignment; editing and undo across them; a save
round trip with everything on.
2026-10-08 20:30:14 -07:00
haven 53e39884fc M7: Auto Size measures vertically aligned area type from the top
auto_height lays the text out in a very tall probe frame; with Center, Bottom
or Justify the lines moved down inside it and the frame grew to tens of
thousands of points.
2026-10-08 20:30:14 -07:00
haven abdc26d8d1 M7: Shrink Text to Fit scales inline art's baseline shift
The fit scaled each run's size, leading and baseline shift but not an inline
graphic's own shift (points), so shrunk symbols sat off the cap-height centre.
2026-10-08 20:30:14 -07:00
haven 56c975465c M7: inline art follows vertically aligned lines
align_vertically moved lines and glyphs but not TextLayout::inlines, so inline
symbols in a centred or bottom-aligned area stayed where top alignment put them.
The reflow path for non-rectangular frames also kept the previous pass's
inlines, drawing each symbol twice.
2026-10-08 20:30:14 -07:00
BFlat 2dcac5b48b Merge pull request #658 from storytold/fix/651-gpu-fallback-int
Fix #651: a dual-GPU Mac falls back to its other GPU
2026-10-09 10:29:33 +07:00
bflatasticandClaude Opus 5.5 dc39146d0d Fix #651: a dual-GPU Mac falls back to its other GPU
Metal reports no PCI ids, so both GPUs of a dual-GPU Mac had the adapter key
Metal:0000:0000. When the integrated GPU failed at start-up, the restart left
out both and the app quit, although the discrete GPU works. An adapter without
ids is now keyed by its name, so the restart leaves out only the one that
failed.

The failure itself was wgpu's indirect-call validation compute shader, which
OCLP-patched Metal on an Iris Pro can't compile. Nothing in VectorCraft or
egui draws indirectly, so that validation is off (WGPU_VALIDATION_INDIRECT_CALL=1
turns it back on).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 10:26:55 +07:00
BFlat 147fc113c3 Merge pull request #657 from storytold/pr/land-641
Land #653, #654, #656: Image Trace View modes, Palette and Create Strokes (part of #641)
2026-10-09 10:25:04 +07:00
bflatastic 66a5363629 Merge #656: Image Trace: Create Strokes
# Conflicts:
#	ROADMAP.md
#	crates/engine/src/cmd/buildcmds.rs
#	crates/engine/src/tests_build.rs
#	crates/mcp/src/prompts.rs
#	crates/trace/src/tests.rs
#	crates/ui-egui/src/panels/image_trace.rs
2026-10-09 10:16:02 +07:00
bflatastic eea4fe9e58 Merge #654: Image Trace: Palette (Limited, Full Tone, Automatic, Document Library)
# Conflicts:
#	ROADMAP.md
#	crates/engine/src/cmd/buildcmds.rs
#	crates/ui-egui/src/panels/image_trace.rs
2026-10-09 10:14:35 +07:00
bflatastic 13c37e0bf4 Merge #653: Image Trace: Advanced as a section that stays open, and View modes
# Conflicts:
#	ROADMAP.md
2026-10-09 10:13:04 +07:00
bflatasticandClaude Opus 5.5 438f90c751 Part of #641: Image Trace: Create Strokes
Advanced › Create: Fills and/or Strokes, with Stroke (the widest line, px).
With Strokes, each colour's 8-connected parts no wider than the stroke width
(chamfer distance transform) trace as open centre lines instead of filled
outlines: the line is thinned to one pixel (Zhang-Suen with each removal
re-checked, so two-pixel lines survive; staircase corners dropped), its
skeleton becomes runs between ends and junctions (junction pixels merged,
spurs pruned, runs through two-way junctions joined, rings closed), and each
run is simplified and fitted with curves. The stroke width is the line's mean
width (pixels over length). Traced lines get round caps and joins in the
document. Without Fills, wider areas become 1 px stroked outlines.
`imageTrace.make` takes fills, strokes and strokeWidth, and refuses neither
fills nor strokes and a non-positive width.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 10:11:09 +07:00
bflatasticandClaude Opus 5.5 4a81e549a2 Part of #641: Image Trace: Palette (Limited, Full Tone, Automatic, Document Library)
Color mode's colours now come from a Palette (`palette` in imageTrace.make's
params), shown in the Image Trace panel under Mode:
- Limited: the `colors` best colours (what Color did before; the default).
- Full Tone: median cut until no colour box spans more than 96 (Less) … 8
  (More) levels per channel, up to 256 colours, set by `colorDetail` 0-100
  (the panel's Colors slider for this palette).
- Automatic: flat art (90% of the pixels in a few tight colours) traces with
  exactly its colours, anything else as Full Tone.
- Document Library: the most used (at most `colors`) colours of the
  document's swatches or of a swatch library (`library`: "document" or a
  library id or name, chosen in the panel's Library list), used as they are;
  traced shapes fill with the swatch's own colour, its colour model kept.
  The library's colours are looked up at every trace, not saved.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 09:51:49 +07:00
bflatasticandClaude Opus 5.5 5be583d1f7 Part of #641: Image Trace: Advanced as a section that stays open, and View modes
- The Image Trace panel's Advanced options sit under a full-width collapsible
  header (widgets::section_toggle, also used by New Document's Advanced
  Options); whether it is open is kept with the UI preferences.
- View: Tracing Result, Tracing Result with Outlines, Outlines, Outlines with
  Source Image and Source Image, in the panel, the Control bar and the
  Properties panel. The view is saved in the Image Trace object's settings
  (`trace.view`), kept when it is traced again, set with the new
  `imageTrace.setView` command (or `view` on imageTrace.make) and drawn by the
  canvas only (RenderOptions::trace_views): exports, printing and Expand keep
  the tracing result.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 09:33:22 +07:00
BFlat 11fceda13e Merge pull request #650 from mateususa/fix/artboard-tool-delete-key
Artboard tool: Delete and Backspace delete the active artboard
2026-10-09 09:31:38 +07:00
BFlat ea814b3fac Merge pull request #652 from storytold/fix/649-dock-drop-zone
Fix #649: a panel dropped on the dock lights up where it goes
2026-10-09 09:27:11 +07:00
bflatasticandClaude Opus 5.5 b5e39048df Fix #649: a panel dropped on the dock lights up where it goes
Panels other than Properties, Layers and Libraries live in the dock's icon
column, not as tabs. Dragging one onto the dock lit up the whole dock, tabs
included, and the drop put it back as an icon, so it seemed to vanish. The
drop zone now lights up the icon column for such panels (the whole dock still
for the tabbed ones), and the dropped panel pops out of its icon.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 09:23:30 +07:00
mateususaandClaude Opus 5.5 762bd6b927 Artboard tool: Delete and Backspace delete the active artboard
The Artboard tool handled Delete/Backspace in Tool::key, but never claimed
the keys through Tool::claims_key. The UI only routes Delete/Backspace to a
tool that claims them, so the keypress went to the Clear shortcut instead
and the artboard stayed. The existing tests called the tool directly and
missed it.

The tool now claims Delete/Backspace while no drag is in progress and more
than one artboard exists. With only one artboard left, the keys stay with
the shortcut.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 19:19:59 -07:00
BFlat 033ceaff41 Merge pull request #648 from storytold/fix/svg-root-layer-name
Part of #372: SVG import names the one layer from the root element
2026-10-09 09:05:21 +07:00
bflatasticandClaude Opus 5.5 a2e4206155 Part of #372: SVG import names the one layer from the root element
Other editors export a document with a single layer without a layer group:
the layer's name goes on the root <svg> (id, or data-name) and its art sits
directly inside. Such a file opened as "Layer 1"; now its one layer takes the
root's name. Files whose top-level groups are the layers are unchanged, and an
Inkscape root's generated id (with inkscape:version) isn't taken as a name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 09:00:24 +07:00
BFlat 771981e2b1 Merge pull request #644 from dotCooCoo/feat/ase-import
Swatches: swatch exchange (.ase) files open as swatch libraries
2026-10-09 08:50:50 +07:00
BFlat c7aeaa637f Merge pull request: land #643 (fix #638)
Land #643 (fix #638: Layers panel lays out only rows in view, keeps open rows in the file)
2026-10-09 08:40:24 +07:00
bflatastic 965fc449e1 Merge #643: Fix #638: Layers panel lays out only the rows in view and keeps open rows in the file 2026-10-09 08:31:13 +07:00
bflatasticandClaude Opus 5.5 977e5d1967 Fix #638: Layers panel lays out only the rows in view and keeps open rows in the file
The panel laid out a row (with its thumbnail and several whole-document
lookups) for every open row each frame. A layer of 5,000 groups of 10 paths,
all open, took about 29 s a frame headless. Now the rows shown are listed once
per document change (with their layer colour and dimming worked out on the
way down) and ScrollArea::show_rows lays out only those in view: 0.4 ms a
frame. A row highlighted out of view is scrolled to.

The open rows move from UI state into the document's state
(DocState::layers_open, OpenRows): a document opens with only its top-level
layers open, and native files save the open rows (Document::layers_open,
written only when not the default, at save time like the view, so opening or
closing rows never marks the document modified).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 08:19:49 +07:00
BFlat b73e19eef2 Merge pull request: land #639 (part of #372)
Land #639 (part of #372: SVG import keeps wrapped layers, round-trips sublayers)
2026-10-09 07:45:18 +07:00
bflatastic 4792bd82a2 Merge #639: Part of #372: SVG import keeps wrapped layers and round-trips sublayers 2026-10-09 07:41:02 +07:00
bflatasticandClaude Opus 5.5 d5e6be1565 Part of #372: SVG import keeps wrapped layers and round-trips sublayers
Top-level groups already opened as layers named from data-name, else their
id. Now that also holds when one more id-less group wraps them (a transform
on all the art, or a <switch>'s chosen group), and hidden objects inside a
<switch> are kept (hidden) instead of dropped.

Nested groups stay groups unless something marks them as layers: the SVG
export now writes data-vc-layer="sublayer" on layers inside layers, and
import makes such a group (or an Inkscape layer group) a sublayer of the
layer holding it, in that layer's colour. A marked group anywhere else
stays a group.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 07:36:21 +07:00
BFlat a469568c7d Merge pull request #636 from HEOJUNFO/pixel-preview-pixels
View › Pixel Preview: show the document pixels the art rasterizes to
2026-10-09 06:57:47 +07:00
heojunfoandClaude Opus 5.5 53b4845f6f View › Pixel Preview: show the document pixels the art rasterizes to
Pixel Preview only switched the pixel grid on from 600%: the art was still
rendered for the screen and drawn with linear filtering, so curves and
strokes stayed smooth vectors. Now, while a document pixel is bigger than a
screen pixel, the canvas renders the visible document pixels one per point
(anti-aliased by coverage), uploads them with nearest filtering and places
them over the document rect they cover, turning with a rotated view.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-09 08:49:18 +09:00
BFlat 5f92f5eb7f Merge pull request: land #631, #632
Land #631 (ICF character alignment) and #632 (French interface)
2026-10-09 06:34:55 +07:00
dotCooCoo 67af21c6db Contributors: add dotCooCoo (Robert Lee) 2026-10-08 15:18:57 -07:00
dotCooCoo e0b1f55250 Swatches: swatch exchange (.ase) files open as swatch libraries
File › Open, Other Library… and the User Defined library folder read
.ase files. Colors keep their model, global and spot colors stay global
and spot, and color groups stay groups. The library readers take a
file's bytes. On the web, File › Open passes a swatch library file to
swatch.library.load as dataBase64 instead of as lossy UTF-8 text.

Swatch and group names in a library are now unique, in .gpl files too.
Add to Swatches puts each color group of a library into one document
group when the document already has a swatch with the group's name.
The library fuzz helpers fail when a command panics.
2026-10-08 15:18:57 -07:00
70 changed files with 4497 additions and 322 deletions

No files matched your search

+9 -9
View File
@@ -4,7 +4,7 @@ VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adob
This file tracks **how far we are and what's left**. Time estimates are wall-clock hours of continuous Claude Opus 5.5 agent work (including builds and the CI gate), given both for **one agent** and for **4–6 parallel agents** on disjoint crates. They are counted from the remaining work (see [Parity estimate](#parity-estimate)), calibrated against measured throughput, and updated as work lands.
_Last updated: 2026-10-09 (after placed documents (File › Place of a `.vectorcraft` file, linked), M4.14–M4.98, M8.1–M8.20, M14.4–M14.7, the MCP prompts, resource templates, completions and logging, the 2026-10-07 issue fixes, the Layers panel rework and the 2026-10-08 community contributions: Pen and shape-tool modifiers, path editing, Layers, Artboards, Swatches/Brushes and dialogs, Japanese composition and PDF text, Hebrew/Arabic type, interface languages (Spanish among them), the font menu, saved selections, MCP and EPS, the missing-font export warning (#319), open paths in the Shape Builder (#374), PDF/`.ai` import keeping strokes live and hidden and nested layers (#372), per-corner Live Corners (#381), SVG type opening at the size it draws at (#396), the Wayland clipboard with copied-file paste (#398), ruler guides that can be selected, moved and deleted (#414), two batches of Preferences options that were stored but unused (#394), skeleton reads with `document.find` for large documents over MCP (#416) and anchors dragged with Direct Selection snapping to points, segments and smart guides, clipped SVG layers opening as clipping layers (#420), PDF/`.ai` layers read on pages of tens of millions of operators (#419), Document Color Mode putting RGB greys on the black plate on request and converting pattern tiles (#421) and movable dialogs with Offset Path's Joins dropdown (#423) and numeric fields scrubbed by dragging their label (#400), stroke weight presets in the stroke unit (#426), the Appearance panel's Opacity popup (#430), type on a path brackets, flip and Type on a Path Options that keep the type in place (#429), Layers rows dragged with a ghost and dropped on the trash or New Layer (#435), tool flyouts opening on a right or corner press (#436), tool flyouts torn off into floating toolbars (#437), the Shape Builder's erase mode deleting edges too (#439), installed fonts registered outside the font folders and fonts installed while the app runs listed in the font menus (#443), alike circular corners on rectangles that aren't square (#442), tool cursors as OS cursors so the pointer no longer trails over the canvas (#444), artboards copied and pasted with their art (#446), guides dragged out of the rulers snapping to the art's side midpoints and the artboards, artboard guides (#451), the toolbar's double arrow and Window › Toolbars › Double Column switching between one and two columns in any window height (#455), the Smart Guides display options and Snapping Tolerance (#394), Font Size and Leading combo boxes with preset lists in the Character and Properties panels and the Control bar (#458), screenshots pasted from the clipboard on macOS, Windows and the web (#457), the Properties panel's Fill and Stroke matching the Control bar's, Illustrator's Window menu panel keys (Shift+F7 for Align…) and Alt-wheel zoom whatever the wheel preference (Discord feedback), the point/area type widget (Discord feedback), groups in legacy Illustrator .ai files (Discord feedback), a rotating desktop log file (#465), image controls in the Control bar and Properties panel: Image Trace with its presets, Mask, Crop Image, Embed/Unembed, and an Image Trace object's preset, Expand and Release (Discord feedback), the Pen working as the Anchor Point tool with Alt held over a selected path's handles and anchors, and anchor buttons that convert, connect and cut paths at the selected anchors (Discord feedback), Japanese hanging punctuation (burasagari, #463), Escape leaving Presentation Mode with no screen mode saved across restarts, documents dropped on the desktop app opening as tabs of their own and a note that an `.ai` file's art off its artboards isn't in the part read (#472), Add/Delete Anchor Point tool icons drawn from the Pen tool's (#479), EPS import running more of PostScript Level 3 (patterns, Type 3 fonts, mesh shadings, masked images, VM and resource probes), and a preview that stands in saying why (Discord feedback, #466, #469, #474), chords with modifiers recorded in Edit › Keyboard Shortcuts (#487), Type Object Selection by Path Only (#394), Anti-aliased Artwork (#394), Show Pixel Grid (#394), pen and touch taps pressed and lifted within one frame clicking where they tapped and the Linux/Wayland pen-tablet workaround (#491), bounding-box resizes landing on the other objects' anchors and centres with labels, and the Rotate, Scale, Shear and Reflect tools snapping their drags (#482), Shift-drag marquees that toggle the objects or anchors they reach and a Lasso whose Alt subtraction keeps the rest of the selection (#483), the mouse wheel stepping the focused numeric field, the dialogs' and preferences' drag values made such fields (#485), Show The Home Screen When No Documents Are Open (#394), Numbers Without Units Are Points (#394), Auto-Collapse Iconic Panels (#394), the Contextual Task Bar moved by its handle and its More Options menu pinning and resetting its position, a designed macOS DMG windoLine truncated
_Last updated: 2026-10-09 (after placed documents (File › Place of a `.vectorcraft` file, linked), M4.14–M4.98, M8.1–M8.20, M14.4–M14.7, the MCP prompts, resource templates, completions and logging, the 2026-10-07 issue fixes, the Layers panel rework and the 2026-10-08 community contributions: Pen and shape-tool modifiers, path editing, Layers, Artboards, Swatches/Brushes and dialogs, Japanese composition and PDF text, Hebrew/Arabic type, interface languages (Spanish among them), the font menu, saved selections, MCP and EPS, the missing-font export warning (#319), open paths in the Shape Builder (#374), PDF/`.ai` import keeping strokes live and hidden and nested layers (#372), per-corner Live Corners (#381), SVG type opening at the size it draws at (#396), the Wayland clipboard with copied-file paste (#398), ruler guides that can be selected, moved and deleted (#414), two batches of Preferences options that were stored but unused (#394), skeleton reads with `document.find` for large documents over MCP (#416) and anchors dragged with Direct Selection snapping to points, segments and smart guides, clipped SVG layers opening as clipping layers (#420), PDF/`.ai` layers read on pages of tens of millions of operators (#419), Document Color Mode putting RGB greys on the black plate on request and converting pattern tiles (#421) and movable dialogs with Offset Path's Joins dropdown (#423) and numeric fields scrubbed by dragging their label (#400), stroke weight presets in the stroke unit (#426), the Appearance panel's Opacity popup (#430), type on a path brackets, flip and Type on a Path Options that keep the type in place (#429), Layers rows dragged with a ghost and dropped on the trash or New Layer (#435), tool flyouts opening on a right or corner press (#436), tool flyouts torn off into floating toolbars (#437), the Shape Builder's erase mode deleting edges too (#439), installed fonts registered outside the font folders and fonts installed while the app runs listed in the font menus (#443), alike circular corners on rectangles that aren't square (#442), tool cursors as OS cursors so the pointer no longer trails over the canvas (#444), artboards copied and pasted with their art (#446), guides dragged out of the rulers snapping to the art's side midpoints and the artboards, artboard guides (#451), the toolbar's double arrow and Window › Toolbars › Double Column switching between one and two columns in any window height (#455), the Smart Guides display options and Snapping Tolerance (#394), Font Size and Leading combo boxes with preset lists in the Character and Properties panels and the Control bar (#458), screenshots pasted from the clipboard on macOS, Windows and the web (#457), the Properties panel's Fill and Stroke matching the Control bar's, Illustrator's Window menu panel keys (Shift+F7 for Align…) and Alt-wheel zoom whatever the wheel preference (Discord feedback), the point/area type widget (Discord feedback), groups in legacy Illustrator .ai files (Discord feedback), a rotating desktop log file (#465), image controls in the Control bar and Properties panel: Image Trace with its presets, Mask, Crop Image, Embed/Unembed, and an Image Trace object's preset, Expand and Release (Discord feedback), the Pen working as the Anchor Point tool with Alt held over a selected path's handles and anchors, and anchor buttons that convert, connect and cut paths at the selected anchors (Discord feedback), Japanese hanging punctuation (burasagari, #463), Escape leaving Presentation Mode with no screen mode saved across restarts, documents dropped on the desktop app opening as tabs of their own and a note that an `.ai` file's art off its artboards isn't in the part read (#472), Add/Delete Anchor Point tool icons drawn from the Pen tool's (#479), EPS import running more of PostScript Level 3 (patterns, Type 3 fonts, mesh shadings, masked images, VM and resource probes), and a preview that stands in saying why (Discord feedback, #466, #469, #474), chords with modifiers recorded in Edit › Keyboard Shortcuts (#487), Type Object Selection by Path Only (#394), Anti-aliased Artwork (#394), Show Pixel Grid (#394), pen and touch taps pressed and lifted within one frame clicking where they tapped and the Linux/Wayland pen-tablet workaround (#491), bounding-box resizes landing on the other objects' anchors and centres with labels, and the Rotate, Scale, Shear and Reflect tools snapping their drags (#482), Shift-drag marquees that toggle the objects or anchors they reach and a Lasso whose Alt subtraction keeps the rest of the selection (#483), the mouse wheel stepping the focused numeric field, the dialogs' and preferences' drag values made such fields (#485), Show The Home Screen When No Documents Are Open (#394), Numbers Without Units Are Points (#394), Auto-Collapse Iconic Panels (#394), the Contextual Task Bar moved by its handle and its More Options menu pinning and resetting its position, a designed macOS DMG windoLine truncated
## Where we are
@@ -109,7 +109,7 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist
- A canvas context menu: right-click selects the object under the pointer and lists what applies to the selection (Undo/Redo, clipboard, group, isolation, join, Remove Anchor Points when anchors are selected, masks, compound paths, guides, Transform, Arrange, Select, Export Selection), or the view commands on empty canvas.
- Save / Don't Save / Cancel before closing or quitting with unsaved documents (tabs, Close, Close All, Quit, window close).
- Four brightness themes, persistent preferences.
- Preferences that act (#394, in part): Show Tool Tips, Double Click To Isolate, Zoom with Mouse Wheel (the wheel zooms about the pointer, Shift-wheel scrolls up and down, Cmd/Ctrl-wheel sideways; Alt/Option-wheel and a trackpad pinch zoom about the pointer either way), Use Precise Cursors; Selection & Anchor Display › Tolerance (objects, anchors and handles), Object Selection by Path Only, Command Click to Select Objects Behind (cycling down the stack), Zoom to Selection, anchor Size, Highlight anchors on mouse over; Type › Number of Recent Fonts (up to 15); Guides & Grid › guide and grid Color and Style (lines or dots) and Grids In Back. Then Snap to Point (its distance, for moves, drawn points and reference points), Move Locked and Hidden Artwork with Artboard, Enable Rubber Band for the Pen and Curvature tools, Handles style, Show handles when multiple anchors are selected, Hide Corner Widget for angles greater than; General › Transform Pattern Tiles (the transforms' and dialogs' Transform Patterns) and Select Same Tint %; Type › Size/Leading, Tracking and Baseline Shift increments (`type.step`, Cmd+Shift+. and Cmd+Shift+, for the size, the Type tool's Alt+arrows), Enable Missing Glyph Protection and Fill New Type Objects With Placeholder Text. Then Smart Guides › Color, Alignment Guides, Anchor/Path Labels, Measurement Labels, Transform Tools, Object Highlighting (with Smart Guides on) and Snapping Tolerance (4 px by default, for every smart guide snap), then Construction Guides and their Angles (#506: a drawn point near a line at one of those angles through the point it leaves from lands on it). Then Type › Type Object Selection by Path Only (type is picked on the baseline of any of its lines, area type's frame or the path of type on a path, no longer anywhere in its bounds; the Type tools and the Eyedropper still take a click among the characters). Then General › Anti-aliased Artwork (off, the canvas draws the art with hard edges). Then Guides & Grid › Show Pixel Grid (Above 600% Zoom), a line at every document pixel over the art in Pixel Preview, turning with a rotated view as the document grid now does too. Then General › Show The Home Screen When No Documents Are Open (off, closing the last document leaves an empty window; the Home button still opens the screen). Then Units › Numbers Without Units Are Points (on by default: a number typed with no unit into a field in picas is read in points, a typed unit still wins; dimmed unless a unit is Picas). Then User Interface › Auto-Collapse Iconic Panels (off by default: on, a click away from a panel popped out of the icon column puts it away). They reach agents too (`prefs.set`, then `pointer_gesture` or `press_key`; `ui.wheel` on the control channel). About 30 stored options still do nothing yet (the rest of #394: Auto Size New Area Type, Show Font Names in English, Highlight Alternate Glyphs, Spacing Guides, performance, devices…).
- Preferences that act (#394, in part): Show Tool Tips, Double Click To Isolate, Zoom with Mouse Wheel (the wheel zooms about the pointer, Shift-wheel scrolls up and down, Cmd/Ctrl-wheel sideways; Alt/Option-wheel and a trackpad pinch zoom about the pointer either way), Use Precise Cursors; Selection & Anchor Display › Tolerance (objects, anchors and handles), Object Selection by Path Only, Command Click to Select Objects Behind (cycling down the stack), Zoom to Selection, anchor Size, Highlight anchors on mouse over; Type › Number of Recent Fonts (up to 15); Guides & Grid › guide and grid Color and Style (lines or dots) and Grids In Back. Then Snap to Point (its distance, for moves, drawn points and reference points), Move Locked and Hidden Artwork with Artboard, Enable Rubber Band for the Pen and Curvature tools, Handles style, Show handles when multiple anchors are selected, Hide Corner Widget for angles greater than; General › Transform Pattern Tiles (the transforms' and dialogs' Transform Patterns) and Select Same Tint %; Type › Size/Leading, Tracking and Baseline Shift increments (`type.step`, Cmd+Shift+. and Cmd+Shift+, for the size, the Type tool's Alt+arrows), Enable Missing Glyph Protection and Fill New Type Objects With Placeholder Text. Then Smart Guides › Color, Alignment Guides, Anchor/Path Labels, Measurement Labels, Transform Tools, Object Highlighting (with Smart Guides on) and Snapping Tolerance (4 px by default, for every smart guide snap), then Construction Guides and their Angles (#506: a drawn point near a line at one of those angles through the point it leaves from lands on it). Then Type › Type Object Selection by Path Only (type is picked on the baseline of any of its lines, area type's frame or the path of type on a path, no longer anywhere in its bounds; the Type tools and the Eyedropper still take a click among the characters). Then General › Anti-aliased Artwork (off, the canvas draws the art with hard edges). Then Guides & Grid › Show Pixel Grid (Above 600% Zoom), a line at every document pixel over the art in Pixel Preview, turning with a rotated view as the document grid now does too. Then General › Show The Home Screen When No Documents Are Open (off, closing the last document leaves an empty window; the Home button still opens the screen). Then Units › Numbers Without Units Are Points (on by default: a number typed with no unit into a field in picas is read in points, a typed unit still wins; dimmed unless a unit is Picas). Then User Interface › Auto-Collapse Iconic Panels (off by default: on, a click away from a panel popped out of the icon column puts it away). Then Performance › Animated Zoom (on, with GPU Performance, which it needs and which dims it when off: the Zoom tool dragged sideways zooms about the press, right in and left out, and held still zooms on, Alt out; off, a drag zooms to the area dragged across, now drawn as a marquee), User Interface › Large Tabs (taller document tabs) and Scale Cursor Proportional to UI (off, the tool cursors keep their size whatever the UI Scaling), and File Handling › Display Bitmaps as Anti-aliased Images in Pixel Preview (off by default: Pixel Preview draws images with each pixel taking its nearest image pixel). Type › Auto Size New Area Type works too (new area type gets Auto Size). They reach agents too (`prefs.set`, then `pointer_gesture` or `press_key`; `ui.wheel` on the control channel). About 20 stored options still do nothing yet (the rest of #394: Spacing Guides, Show Font Names in English, Highlight Alternate Glyphs, Display Print Size at 100% Zoom, Identify Objects By, East Asian Type units, Open Documents As Tabs, Real-time Drawing and Editing, GPU Performance beyond Animated Zoom, hyphenation, scratch disks, the legacy clipboard, Appearance of Black, Touch Workspace).
- 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.
@@ -134,18 +134,18 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist
- **Temporary tools:** Cmd with any other tool drags with the selection tool used last (Selection, Direct Selection or Group Selection). Held Space pans and Cmd+Space zooms (Cmd+Alt+Space out) whatever the tool.
- **Panel drag and drop:** art dragged off the canvas onto the Symbols panel becomes a symbol, onto the Swatches panel a pattern swatch and onto the Brushes panel an Art brush; a symbol dragged onto the canvas places an instance where it is dropped, and a brush dragged onto a path is applied to it.
- **Tool double-clicks:** double-clicking a tool's button opens its options: Hand fits the artboard in the window, Zoom shows 100 %, Rotate, Scale, Reflect and Shear open their Object › Transform dialogs, the Selection, Direct Selection and Group Selection tools the Move dialog (Enter opens these seven tools' dialogs too), Gradient, Eyedropper, Blend and the Liquify tools their panels or options, and the Pencil, Paintbrush, Smooth, Blob Brush and Eraser tools their Tool Options (Fidelity, fill, the tolerances, the brush size).
- **Layers panel:** every layer, sublayer, group and object is a clickable row at any depth: a click highlights it and makes its layer current (new art goes there), Shift-click a range, Ctrl/Cmd-click toggles. Sublayers are no longer treated as objects: clicks, marquees, Select All and the Select menu take the art inside them, and each sublayer selects in its own colour. Selection squares on rows with selected art (click selects a row's art, Shift adds or removes; dragging the square moves the selection to another row, Alt copies), the eye and lock on every row with drag-down-the-column (one undo step), Ctrl/Cmd-click an eye for per-layer Outline, Alt-click an eye or lock to hide or lock the other layers (again: show or unlock them all), triangles with Alt to open or close everything inside, drag and drop rows above, below or into layers and groups with a drop line (Alt copies) and a dimmed copy of the row under the pointer (dropped on the trash rows are deleted, on New Layer duplicated, as in Illustrator), inline rename, Delete key on highlighted rows. Buttons and the full panel menu: New Layer/Sublayer (Alt: options, Ctrl: on top), Duplicate, Delete, Options for Selection, clipping mask, isolation, Locate Object, Merge Selected, Flatten Artwork, Collect in New Layer, Release to Layers (Sequence and Build), Reverse Order, Template, Hide/Outline/Lock Others and Show/Preview/Unlock All, Paste Remembers Layers, Panel Options (row size, thumbnails per kind, Show Layers Only). Layer Options: name, colour (presets, each with a chip of its colour, or custom), Template, Lock, Show, Print, Preview (outline drawing and clicking) and Dim Images to %. Every operation is a command (`layer.move`, `layer.highlight`, `layer.merge`…) with validation against cycles and invalid nesting.
- **Layers panel:** every layer, sublayer, group and object is a clickable row at any depth: a click highlights it and makes its layer current (new art goes there), Shift-click a range, Ctrl/Cmd-click toggles. Sublayers are no longer treated as objects: clicks, marquees, Select All and the Select menu take the art inside them, and each sublayer selects in its own colour. Selection squares on rows with selected art (click selects a row's art, Shift adds or removes; dragging the square moves the selection to another row, Alt copies), the eye and lock on every row with drag-down-the-column (one undo step), Ctrl/Cmd-click an eye for per-layer Outline, Alt-click an eye or lock to hide or lock the other layers (again: show or unlock them all), triangles with Alt to open or close everything inside, drag and drop rows above, below or into layers and groups with a drop line (Alt copies) and a dimmed copy of the row under the pointer (dropped on the trash rows are deleted, on New Layer duplicated, as in Illustrator), inline rename, Delete key on highlighted rows. Buttons and the full panel menu: New Layer/Sublayer (Alt: options, Ctrl: on top), Duplicate, Delete, Options for Selection, clipping mask, isolation, Locate Object, Merge Selected, Flatten Artwork, Collect in New Layer, Release to Layers (Sequence and Build), Reverse Order, Template, Hide/Outline/Lock Others and Show/Preview/Unlock All, Paste Remembers Layers, Panel Options (row size, thumbnails per kind, Show Layers Only). Layer Options: name, colour (presets, each with a chip of its colour, or custom), Template, Lock, Show, Print, Preview (outline drawing and clicking) and Dim Images to %. Every operation is a command (`layer.move`, `layer.highlight`, `layer.merge`…) with validation against cycles and invalid nesting. A document opens with only its top-level layers open; the rows left open are saved in the native file (nothing is written for the default) and reopen that way. Only the rows scrolled into view are laid out, from a row list made once per change: a layer of 5,000 groups of 10 paths, all open, draws the panel in 0.4 ms a frame instead of about 29 s (#638).
- **Drawing aids:** Smart Guides and snapping (moving, with the Selection, Group Selection or Direct Selection tool, and resizing by the bounding-box handles with the Selection or Free Transform tool, Shift and Alt too: the dragged corner or side lands on the other objects' anchors and centres ("anchor", "center") or lines up with their edges and centres (a line and "align"); the Rotate, Scale, Shear and Reflect tools drag from the anchor they grab and snap the pointer the same way, so a corner dragged onto another object's anchor scales exactly onto it, #482; anchors dragged with Direct Selection: the one pressed on lands on other anchors, its own path's that stay put among them, on path segments or in line with them, the others following, Shift keeps 45° steps, and with Smart Guides off Snap to Point pulls it onto anchors; the Artboard tool snaps artboards, and their bleed, to other artboards, bleeds and art, the grid or whole pixels while moving, copying and resizing them, and the Transform panel shows and edits the active artboard's X/Y/W/H; drawn points, #506: hovering shows where the press goes, the point lands on the other objects' anchors, centres and paths ("anchor", "center", "path") or lines up with their anchors, edges and centres ("align"), the Pen's on the path being drawn too, near a construction guide through the anchor before it on that guide (Preferences › Smart Guides › Construction Guides and Angles), and with Shift kept to its 45° step or a square's diagonal it slides along that way into line; the targets are gathered once per document state, from the art in the window, and the anchors, centres and lines near the pointer are found by bisection, so hovering never rescans the document), guides dragged out of the rulers (#451: they snap as moved guides do, Shift to the ruler's ticks; with the Artboard tool they are artboard guides, which run across their artboard only and move, copy and delete with it, `guide.add {artboard}`) that the Selection, Direct Selection and Group Selection tools then pick and drag (#414: the selected guides highlight and move together, Alt copies them, Shift snaps the dragged one to the ticks, otherwise it snaps to pixels, the grid or the edges, centres (so the sides' midpoints) and anchors of the art and the artboards, or with Smart Guides off Snap to Point pulls it onto anchors; the arrow keys nudge them, Delete deletes them, dragging one back onto its ruler deletes it, Lock Guides and Hide Guides leave them alone; `guide.list`, `guide.select`, `guide.move` and `guide.remove` reach agents), a right-click on either ruler or the origin box to pick the document's units (the current one checked; `document.setUnits`, one undo step, #528), and Draw Normal / Behind / Inside modes.
- **Views:** the status bar's artboard navigator (first, previous, next, last; `view.goToArtboard`) goes to an artboard and fits it, and Fit Artboard in Window and Actual Size show the navigator's artboard. The Artboards panel highlights that active artboard: clicking a row makes it active (the Artboard tool's too, while it is chosen) as does clicking an artboard with the Artboard tool, double-clicking its number also fits it in the window and double-clicking its name renames it. Duplicate Artboards, or a row dragged onto New Artboard, copies the artboard with its art (#446). Escape leaves Presentation Mode, F from it goes back to Normal Screen Mode, and the screen mode isn't saved with the preferences: the app always starts in Normal Screen Mode with its menus and panels (#472).
- **Views:** the status bar's artboard navigator (first, previous, next, last; `view.goToArtboard`) goes to an artboard and fits it, and Fit Artboard in Window and Actual Size show the navigator's artboard. The Artboards panel highlights that active artboard: clicking a row makes it active (the Artboard tool's too, while it is chosen) as does clicking an artboard with the Artboard tool, double-clicking its number also fits it in the window and double-clicking its name renames it. Duplicate Artboards, or a row dragged onto New Artboard, copies the artboard with its art (#446). Escape leaves Presentation Mode, F from it goes back to Normal Screen Mode, and the screen mode isn't saved with the preferences: the app always starts in Normal Screen Mode with its menus and panels (#472). View › Pixel Preview shows the art as the document pixels it rasterizes to, one per point and hard-edged when magnified, turning with a rotated view (it used to draw the smooth vectors, with only the pixel grid over them).
- **Geometry and effects:**
- Pathfinder (10 exact curve booleans), Offset, Outline Stroke, Simplify, Clean Up, Split Into Grid, Divide Objects Below. Object › Path › Remove Anchor Points (`path.removeAnchors`) removes the direct-selected anchors without opening their paths (the Delete key still deletes them with their segments): the neighbours keep their handle directions and their facing handles are refitted so one cubic follows the two old segments, and straight sides stay straight. The Delete Anchor Point tool uses the same refit. The Control bar, the contextual task bar, the Properties quick actions and the canvas context menu offer it when anchors are selected. With anchors selected, the Control bar and the Properties panel also convert them to corner or smooth (`path.convertAnchors`), connect end points (Join) and cut the path at them (`path.cutAtAnchors`, also on the task bar and the context menu): a closed path opens there and an open one becomes one path per piece, each cut leaving one of its two coincident anchors selected so a drag pulls the path apart.
- Live effects with previewing dialogs: Distort & Transform, Path, Convert to Shape, 15 Warp styles, Round Corners, Scribble, Effect → Pathfinder (all 10 operations, live on groups; several loose objects are grouped first, in one undo step), Color Adjustments (Brightness/Contrast, Curves, Levels, Hue/Saturation, Shift to Color, Temperature/Tint, on vectors, live type and embedded images), and raster drop shadow, glows and feather. SVG and PDF export keep live effects (geometry baked; SVG raster effects as filters).
- **Type:** Text Wrap, Type on a Path effects (Rainbow/Skew/3D Ribbon/Stair Step/Gravity) and Options (Flip, Align to Path, Spacing; OK keeps the type where it is), type on a path's start, centre and end brackets (Selection and Direct Selection drag them to set where the type runs, slide it along its path and, across the path, flip it: #429), Character and Paragraph Styles (override-preserving redefine), paragraph attributes per paragraph (alignment, indents, spacing, hyphenation, hanging punctuation, tab stops, paragraph style, direction, mojikumi and leading model; the Paragraph, Tabs and Paragraph Styles panels act on the paragraphs the Type tool's selection or caret touches, Return continues the paragraph's style, threads and SVG keep them), Area Type Options (rows/columns/inset/first baseline, vertical Align Top/Center/Bottom/Justify per row/column, reflowing non-rectangular frames and text wrap), threaded text across any closed shapes, Fit Headline, the Every-line Composer for justified and ragged text (paragraph-wide breaks for an even rag, Single-line per object from the Paragraph panel menu or `text.setFormat {composer}`). Area type resizes like Illustrator's type areas: a bounding-box handle drag (Selection tool) or Area Type Options Width/Height size the frame and the text reflows at its size (threads too); Direct Selection drags a frame corner or edge (`text.reshapeArea`). Point type still scales. Auto Size: the frame height follows the text after every edit, in the same undo step (rectangular frames of horizontal type in one row; columns get the least height that holds them; a height set by hand or threading turns it off), and the "Auto Size New Area Type" preference gives it to new area type. Shrink Text to Fit (beyond Illustrator): overflowing area type scales its sizes, leading and baseline shifts down by the largest factor (in 0.1 pt steps of the first run, down to a minimum percentage) that fits, at layout time so every export sees it. `text.areaOptions` and `document.inspect` report overflow and the shrink factor. The Selection tool shows the type widget beside selected type's bounding box (hollow on point type, filled on area type); double-clicking it converts between them (Type › Convert To Area Type / Convert To Point Type), keeping the text and its styles in place. Variable fonts list every named instance as a style of their family (Figtree Light to Black and their italics, Bahnschrift, Segoe UI Variable), and the instance chosen is shaped, drawn, outlined and measured at its axis settings; PDF and SVG embed it as that instance. Variation axis sliders are not done. Beyond Illustrator: inline graphics (`text.insertInline`, Type ▸ Insert Inline Symbol) set a document symbol in a run of type as one character that flows, wraps and justifies like a glyph (InDesign-style inline objects, e.g. mana symbols in card rules text): sized to a multiple of the font size, centred on the cap height, opening up tall lines, following Redefine Symbol; a character of its run's size for Character Alignment and Top-to-Top leading, placed by the bidi reordering in right-to-left text (a neutral U+FFFC); drawn on the canvas, kept as live text plus a `<use>` in SVG and as vector art in PDF; Backspace removes it whole. Hebrew and Arabic are laid out right to left with the Unicode bidirectional algorithm (embedded Latin and numbers keep their direction, lines put in visual order after wrapping) in point, area and path type, with caret, selection and arrow keys in visual order; each paragraph's direction comes from its first strong character unless Paragraph Direction sets it (Paragraph panel with Show Indic Options, `text.setFormat {direction}`), and new type aligns to the start of its direction. SVG export outlines right-to-left text. Font Size and Leading are combo boxes in the Character and Properties panels (Font Size in the Control bar too, beside the Character link, font family and style): type, step with ↑/↓ or the spinner, scrub the label, or pick a preset (6–72 pt, shown in the type unit; Leading also Auto), each pick one undo step; Kerning and Tracking list -100…200; a size, leading, kerning or tracking the selected text doesn't share shows blank (#458).
- **Interface languages, vertical type:** VectorCraft ▸ Language (or Preferences ▸ User Interface) picks Automatic (the system locale) or a registered language, persisted as `interfaceLanguage`. Translations come from per-language catalogs (`i18n/*.tsv`): Traditional and Simplified Chinese, Japanese, Spanish (neutral international Spanish, for every `es-*` locale), French (every `fr-*` locale), Italian (every `it-*` locale) and Russian (every `ru-*` locale) cover the whole interface, Czech and Brazilian Portuguese every menu label, Brazilian Portuguese the shell's `tl!` literals too (tested); Spanish, French, Italian and Russian also translate status-bar and error messages as they are shown (`@msg` templates, every message literal tested; the messages themselves stay English for agents); untranslated text stays English. Japanese and Chinese glyphs come from the craft-fonts build input (release builds) or the installed fonts, Czech, Spanish, French, Italian and Russian ones from the bundled UI fonts. The web app follows the browser's languages (or `?lang=`). The Basic toolbar's Type button holds Vertical Type in its flyout. Vertical Type, Vertical Area Type and Vertical Type on a Path create vertical text (columns right to left, upright CJK glyphs and marks with `vert` alternates, Latin and longer numbers on their side, two- and three-digit numbers set as tate-chu-yoko in one em of the column (kept whole when justified), upright glyphs centred on the column (tracked or justified too), point type's anchor on the first column's centre line); kinsoku (the strict set) applies to horizontal and vertical Japanese, and justified Japanese lines spread their room between characters (not inside Latin words); Paragraph panel › Mojikumi Set (shown with Preferences › Type › Show East Asian Options, `text.setFormat {mojikumi}`): None or Line-end Punctuation Half Width (new type's default, as in Illustrator; older documents and imported text keep None) shares one half-em space between consecutive punctuation, sets a closing mark ending a line half width and an opening bracket starting a wrapped line flush with its start, and puts a quarter em between Japanese and Latin letters or digits; Paragraph panel menu › Top-to-Top / Bottom-to-Bottom Leading measures leading from em box top to top (area type's first line touches the frame) or from baseline to baseline (new type in a Japanese interface starts top to top, with em box centre character alignment, #432); Paragraph panel menu › Burasagari None / Regular / Force (`text.setFormat {burasagari: "none"|"standard"|"forced"}`) hangs an East Asian comma or full stop (、。,.、。) ending an area type line outside it, Regular (new type's default) when it doesn't fit and Force always (the rest of the line then fills the measure; closing brackets and Latin punctuation don't hang); Character panel menu › Character Alignment (with the East Asian options; `text.setFormat` or `text.setRangeStyle {charAlign}`) lines characters smaller than the largest on their line up on the Roman baseline, the em box top/right, centre or bottom/left, or the ICF (ideographic character face) top/right or bottom/left, from the font's BASE table or, without one, the average ink box of some ideographs and kana; Type ▸ Type Orientation switches existing text; caret, selection, hit testing and arrow keys follow the writing direction. Vertical text exports to PDF as real text and to SVG as outlines.
- **Transparency:** opacity masks (clip/invert/disable/link), exported as SVG `<mask>` and PDF soft masks.
- **Advanced art:** live Blends (steps/distance/smooth colour, editable spine, anchor-targeted Blend tool, faithful interpolation, knockout), Envelope Distort (warp/mesh/top object, Reset, full Envelope Options, mesh handles, Edit Contents; type, images, symbols, gradients, patterns and appearance distorted everywhere), Liquify tools with options and pen pressure, Puppet Warp with rotating pins, Perspective Grid with presets, movable planes and projected type (choosing a perspective tool shows the grid; Hide Grid hides it with the tool still chosen), Gradient Mesh, Shape Builder (stroke-only open paths and lines cut the regions they cross and enclose regions of their own; filled open paths count as closed; erase mode while Alt/Option is held: a minus pointer, red highlights of what will go, a click or drag deletes the regions touched, the pieces of open lines and the edges (outline pieces between the points where paths meet, opening their paths there) it passes over, one undo step, `shapeBuilder.merge {erase}` and `shapeBuilder.regions` edges over MCP), Live Paint (every path an edge, open lines included), Image Trace (12 presets, colour layers traced in parallel; a trace past two million anchor points or an image over 64 megapixels is refused with advice rather than running out of memory, and a selection too large to outline shows its bounds (#525); Object › Image Trace › Make and Make and Expand trace at once with the Default preset, #543; with an image selected the Control bar and the Properties panel show Image Trace, whose arrow traces with any preset, Mask (`object.maskImage`: a clipping path on the image's outline, selected so its handles crop), Crop Image and Embed or Unembed in place of Fill and Stroke; with an Image Trace object selected, its Preset (choosing another traces again), 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), View, the Image Trace panel and Expand, plus Release in Properties; the five View modes (Tracing Result, with Outlines, Outlines, Outlines with Source Image, Source Image) redraw a trace on screen without tracing again, are saved with it and `imageTrace.setView` sets them, while exports and Expand keep the result; the panel's Advanced section is a header that stays open or closed as it was left (part of #641); Color mode's Palette: Limited, Full Tone (as many colours as the tones need, Less … More), Automatic (flat art with its own colours, else Full Tone; a heuristic) and Document Library (the most used colours of the document's swatches or a swatch library, filled with the swatch colours as they are), part of #641; Advanced › Create: Fills and/or Strokes, where lines up to the Stroke width trace as stroked centre lines (distance transform, thinning, a skeleton graph with spurs pruned, curve fitting; one width per line; without Fills, wider areas become stroked outlines), part of #641), pattern swatches with pattern editing mode, live Repeat (radial/grid/mirror).
- **Paint and appearance (M3):**
- **Swatches:** names follow the colour model and are unique; Swatch Options (process/spot, Global, Gray/RGB/HSB/CMYK/Web, live preview); editing a global or spot swatch recolours every linked fill, stroke and text run in one undo step; multi-select and delete with confirmation; New Swatch and New Color Group dialogs (a group from the selected artwork's colours); swatches in colour groups convert, separate and count like any other. The Swatches panel selects ranges and whole groups, has a find field, and drags swatches to reorder, regroup or paint art; Add Used Colors, Select All Unused, Merge, Ungroup and Sort by Kind; a CMYK document keeps applied colours in CMYK. Swatch libraries: nine generated colour libraries and five gradient libraries in a library panel, saved 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.
- **Swatches:** names follow the colour model and are unique; Swatch Options (process/spot, Global, Gray/RGB/HSB/CMYK/Web, live preview); editing a global or spot swatch recolours every linked fill, stroke and text run in one undo step; multi-select and delete with confirmation; New Swatch and New Color Group dialogs (a group from the selected artwork's colours); swatches in colour groups convert, separate and count like any other. The Swatches panel selects ranges and whole groups, has a find field, and drags swatches to reorder, regroup or paint art; Add Used Colors, Select All Unused, Merge, Ungroup and Sort by Kind; a CMYK document keeps applied colours in CMYK. Swatch libraries: nine generated colour libraries and five gradient libraries in a library panel, saved as `.vcswatches`, `.gpl` or CSS, and loaded from `.vcswatches`, `.gpl` and swatch exchange (`.ase`) files (RGB, CMYK, Lab and Gray; global, spot and process; groups). Tints of global and spot colours ("Name 40%") stay linked and separate as a percentage of their plate. Spot colours can be defined in Lab (Spot Colors options). A built-in [Registration] swatch prints on every plate.
- **Colour:** a Color Picker (colour field, H/S/B/R/G/B channel slider, HSB/RGB/Lab/CMYK fields, hex, web-only snapping, out-of-gamut correction); the Color panel follows each colour's own model and Alt-click paints the other proxy; proxies look through groups and show "?" for mixed paint; Invert, Complement, Apply Last Color (`,`) and Apply Last Gradient (`.`) keep the colour model; every paint command feeds the recent colours. The Color Guide has 21 harmony rules, Steps and Variation options and Limit to Library. Adjust Color Balance (its Global mode shifts tints) and Saturate preview live; Edit Colors and Recolor also reach meshes, images and patterns. Recolor Artwork has colour reduction, five recolour methods, presets, Limit to Library, a colour-wheel Edit tab and Edit Color Group; a local Color Themes panel saves five-colour themes. Fill/Stroke chips open swatch and mixer popovers (the Properties panel has the Control bar's Fill and Stroke chips, Stroke link and weight spinner, with nothing selected too), panels have Illustrator's Window menu keys (Align Shift+F7, Transform Shift+F8, Pathfinder Cmd+Shift+F9, Layers F7, Character Cmd+T…; every panel can be given one in Edit › Keyboard Shortcuts), and Eyedropper Options pick up and apply chosen attributes (Alt and Shift+Alt, image pixels). Fills and strokes can overprint (Attributes panel, Overprint Black options), and CMYK documents blend in inks on screen, in PDF and when flattening. Document Color Mode converts the art, symbols, pattern tiles and swatches through the colour settings: Gray stays Gray, RGB greys separate into four-colour greys and a rich black as Illustrator does, or go on the black plate only with `grays: "black"` (also for `document.open {colorMode}`).
- **Gradients:** lossless, validated gradient params; gradients follow rotate, reflect, shear, non-uniform scale and distortions; the Gradient tool edits the fill or stroke of the active proxy, type included; an interactive on-canvas annotator (move, length/angle, rotate, add/move/delete/duplicate stops, midpoints, a stop popover, Delete and arrow keys). The Gradient panel has the Fill/Stroke proxy, a gradient-swatch dropdown with Save to Swatches, midpoint locations, Alt-drag to copy or swap stops, swatch drops on the ramp and a stop eyedropper; copied appearances and graphic styles place gradients on each target's own bounds; gradient handles snap and honour Constrain Angle. Gradient stops stay linked to global and spot swatches. Freeform gradients (points and lines) are edited on the canvas; radial gradients have an extent ellipse, an aspect handle and an off-centre focal point (SVG `fx`/`fy`, PDF two-point radials). A stroke's gradient runs within, along or across it. Object ▸ Expand turns gradients into N objects or a gradient mesh.
- **Strokes:** one stroke-geometry module shared by the canvas, SVG, PDF and Outline Stroke; dotted lines (zero-length dashes draw dots or squares); arrowheads with hollow outlines, tip-on-end or extend-past-end alignment and one opacity for line and head. SVG and PDF export arrowheads, width profiles, brushes and aligned strokes exactly as the canvas draws them; Outline Stroke and the live Outline Stroke effect outline every stroke item as drawn (dashes, heads, profiles, alignment); dashes can be fitted to corners and path ends; width profiles carry through dashes, and their corners take the join. The Stroke panel edits type's character strokes, follows the stroke units (its weight presets are round values in that unit: `0.25 mm`, `0.0625 in`, `1 px`, #426; fields show four decimals in mm, cm and inches, three in points), shows mixed values blank and opens from the Control bar. A width profile library, thirty more arrowheads, and Width Point Edit with multi-select and discontinuous points. Visual bounds and clicks cover the whole painted stroke. Scale Strokes & Effects, Scale Corners and Use Preview Bounds work everywhere, and new art inherits stroke options, a graphic style or the whole last appearance.
@@ -158,7 +158,7 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist
- **Fonts:** a font is found by any of its names (family and style in every language of its name table, legacy family/style pairs, PostScript name), so documents from other apps open with the font they name; Find Font and `text.fonts` say for each font whether it was found exactly, by another name, substituted or missing, and how many glyphs are missing. PDF and `.ai` import brings Japanese text back as live type: CID fonts without a ToUnicode map read through the standard CMaps, vertical columns (WMode 1) as vertical type, letter spacing as tracking; a glyph is live type only when the installed font (in the closest style of its family) draws the same glyph, and text in a font that isn't installed comes in as live type shown in the fallback font until the font is installed (exports that draw it — PDF, EPS, EMF/WMF, raster, SVG outlines or embedded fonts — warn that they wrote the fallback font; `textAs: outlines` keeps the PDF's embedded glyphs).
- **Files (M4):**
- `.vectorcraft` (lossless JSON, compressed, atomic saves, save down to v1), Save As with a format chooser, Save a Copy, Revert, templates, Data Recovery after a crash (browser tabs hold their copies with Web Locks too, so a background tab's copies are never taken for a crash's, and a tab repairs copies another removed when it resumes: #367), background save and export. The desktop app writes its warnings and errors (graphics adapter, a lost graphics device, panics the guard recovered from) to standard error and to `logs/vectorcraft.log` next to the preferences, the two previous runs kept and each file capped at 16 MiB, so a launch without a terminal still leaves something to attach to a bug report (#465).
- SVG/SVGZ in and out with SVG Options, Preserve Editing, symbols, filters, rich text and physical units (SVG type under a transform or `viewBox` scale opens at the size it draws at, the scale moved into its size, leading, baseline shift and strokes, a stretch, skew or rotation kept as its transform: #396; a top-level group with a clip path, such as a clipped Inkscape layer, opens as a layer with a clipping mask, its name kept: #420; hidden objects written hidden on Save and `convert`, and `data-*` attributes kept as the objects' own data: #522); PDF and PDF-compatible `.ai` in and out (layers, with hidden ones kept hidden with their art and nested ones as sublayers, on pages of up to 64 million operators, art whose layer can't be told going to a hidden, non-printing layer rather than showing or printing: #419; strokes kept live, a fill and a stroke of one outline as one object; a type object's stroke written as each glyph's outline stroked back on the type, so it stays one editable object; lines wrapped in a frame (each wrapped line ending in a space, one left edge, leading and font) back as one area type object, left aligned or justified with its paragraph spacing, where laying it out breaks the lines where the file does; glyphs set apart by gaps wider than a space (a barcode's digit groups) keeping their places; layers stacked as the pages mark them even when one first paints on a later page, art ending a layer's marked content or a clip closing in a later layer kept in its own layer, and layers with no art kept empty: #508; masks, editable text with type set along a curve coming back as type on a path, each artboard's art on its own page only, an `.ai`'s white page under its layers left out rather than coming in as art, spot colours, presets, security, marks and bleed, ICC output intents, raster effects, subset fonts, PDF/X, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3). CMYK images keep their ink amounts from PDF import (and from placed CMYK TIFFs) to PDF export: a CMYK JPEG passes through unchanged, others stay CMYK (DeviceCMYK, or ICC-based CMYK in PDF/X-3/X-4) unless the Output settings convert them; the canvas shows them through the working CMYK profile (#320).
- SVG/SVGZ in and out with SVG Options, Preserve Editing, symbols, filters, rich text and physical units (SVG type under a transform or `viewBox` scale opens at the size it draws at, the scale moved into its size, leading, baseline shift and strokes, a stretch, skew or rotation kept as its transform: #396; a top-level group with a clip path, such as a clipped Inkscape layer, opens as a layer with a clipping mask, its name kept: #420; hidden objects written hidden on Save and `convert`, and `data-*` attributes kept as the objects' own data: #522; top-level groups open as layers named from `data-name`, else the id, also when one more group (a transform on all the art, a `<switch>`) wraps them, hidden ones hidden, and a file whose art sits loose under a root `<svg>` with an id (or `data-name`), as one-layer exports write it, opens with its one layer named from it; nested groups stay groups, except the sublayers VectorCraft writes, marked `data-vc-layer`, and Inkscape sublayers, which open as sublayers in their layer's colour: #372); PDF and PDF-compatible `.ai` in and out (layers, with hidden ones kept hidden with their art and nested ones as sublayers, on pages of up to 64 million operators, art whose layer can't be told going to a hidden, non-printing layer rather than showing or printing: #419; strokes kept live, a fill and a stroke of one outline as one object; a type object's stroke written as each glyph's outline stroked back on the type, so it stays one editable object; lines wrapped in a frame (each wrapped line ending in a space, one left edge, leading and font) back as one area type object, left aligned or justified with its paragraph spacing, where laying it out breaks the lines where the file does; glyphs set apart by gaps wider than a space (a barcode's digit groups) keeping their places; layers stacked as the pages mark them even when one first paints on a later page, art ending a layer's marked content or a clip closing in a later layer kept in its own layer, and layers with no art kept empty: #508; masks, editable text with type set along a curve coming back as type on a path, each artboard's art on its own page only, an `.ai`'s white page under its layers left out rather than coming in as art, spot colours, presets, security, marks and bleed, ICC output intents, raster effects, subset fonts, PDF/X, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3). CMYK images keep their ink amounts from PDF import (and from placed CMYK TIFFs) to PDF export: a CMYK JPEG passes through unchanged, others stay CMYK (DeviceCMYK, or ICC-based CMYK in PDF/X-3/X-4) unless the Output settings convert them; the canvas shows them through the working CMYK profile (#320).
- 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).
@@ -215,7 +215,7 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale)
| Type core | 9 | 80% | Middle Eastern features beyond bidi layout and Paragraph Direction (Character Direction, digit types, kashidas, the Middle Eastern composers, editable bidirectional SVG text, a split caret where directions meet); Hyphenation… and Justification… options (Every-line Composer for justified and ragged text, per object, is done; it is tuned by eye, not yet compared side by side with Illustrator; mixed type sizes in a paragraph still break single-line), Optical Margin Alignment, paragraph spacing limit for vertically justified area type, hidden characters, paragraph attributes in the Type tool's copy and paste (the characters keep their styles, the paragraphs take the destination's), mixed-value display in the Paragraph panel for a selection across differing paragraphs, Transform Again after a type-area resize (it scales the type), partial selection of type-area anchors by marquee | 14–19 |
| Type advanced | 4 | 50% | CJK composition for vertical type (ruby, mojikumi beyond Line-end Punctuation Half Width — the other sets (and their paragraph-start bracket and indent rules), kinsoku sets and the Mojikumi Settings dialog —, proportional vertical metrics, manual tate-chu-yoko), variable font axis sliders (named instances are styles), tab leaders, spell check (open dictionary), Touch Type, Retype; vertical point/area/path type and Type Orientation have initial support (beyond parity, not scored: inline symbols in text) | 20–28 |
| Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | symbol libraries (original), dynamic symbols, envelope Anti-Alias/Preserve Shape output and warp point editing, brush interpolation in blends (M8 fidelity pass done) | 5–8 |
| Image Trace, graphs, image tools | 3 | 70% | graph Design/Column/Marker, Create Object Mosaic, Crop Image polish (an on-canvas crop box), Image Trace View modes (Outlines, Source Image) (Vector Halftone is done) | 6–10 |
| Image Trace, graphs, image tools | 3 | 70% | graph Design/Column/Marker, Create Object Mosaic, Crop Image polish (an on-canvas crop box), per-feature stroke/fill choice and varying widths in Image Trace's Create Strokes (Vector Halftone and the Image Trace View modes, Palette and Create Strokes are done) | 6–10 |
| Layers, artboards, document setup | 5 | 82% | Layers panel: a confirmation before deleting layers that hold art, Collect for Export, row context menus, the Layer Options dialog for several rows with mixed values, Paste Remembers Layers for sublayers, drag-scrolling a long panel while dragging rows; artboard presets/rearrange polish (Document Setup, New Document and the rest of the Layers panel are done) | 4–7 |
| View & navigation | 3 | 70% | New View/Edit Views, multiple windows/arrange, Snap to Pixel/Glyph (print tiling is done) | 9–14 |
| Guides, grids, smart guides, snapping, rulers | 3 | 84% | global/video rulers, Spacing Guides, Smart Guides' angle and distance readouts while drawing, Alt swapping a ruler guide's orientation, ruler guides selected together with art (marquee, Shift-click), ruler guides as Layers rows with their own lock and hide (#451: Lock Guides locks them all; Make Guides paths are Layers rows already) (dragging existing guides is done, #414; new guides snapping to side midpoints and artboards, and artboard guides, #451; the drawing tools snapping, with Construction Guides, #506) | 2–4 |
@@ -223,7 +223,7 @@ 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% | 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 |
| 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 20 Preferences options stored but not yet acted on (#394: Spacing Guides, Show Font Names in English, Highlight Alternate Glyphs, Display Print Size, Open Documents As Tabs, Real-time Drawing, hyphenation, Appearance of Black, 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 |
+37 -8
View File
@@ -22,8 +22,9 @@ use std::sync::{Arc, OnceLock};
use eframe::egui_wgpu::NativeAdapterSelectorMethod;
use eframe::wgpu::{self, Backend, DeviceType, PowerPreference};
/// The adapters a restart leaves out, those the window failed on, as comma-separated
/// `backend:vendor:device` keys (`Vulkan:1002:164e`). Set by the app itself when it starts again.
/// The adapters a restart leaves out, those the window failed on, as comma-separated [`key`]s
/// (`Vulkan:1002:164e`, `Metal:Intel Iris Pro Graphics`). Set by the app itself when it starts
/// again.
pub const SKIP_ENV: &str = "VECTORCRAFT_GPU_SKIP";
/// wgpu's variable for choosing an adapter by (part of) its name, any case.
@@ -60,7 +61,7 @@ pub fn power_preference(pref: Option<&str>, env: Option<PowerPreference>) -> Pow
/// One adapter, as [`adapter_order`] sees it.
#[derive(Clone, Debug)]
pub struct Candidate {
/// Identifies the adapter across a restart: `backend:vendor:device` ([`key`]).
/// Identifies the adapter across a restart ([`key`]).
pub key: String,
pub name: String,
pub backend: Backend,
@@ -73,7 +74,7 @@ impl Candidate {
fn new(adapter: &wgpu::Adapter, surface: Option<&wgpu::Surface<'_>>) -> Self {
let info = adapter.get_info();
Self {
key: key(info.backend, info.vendor, info.device),
key: key(info.backend, info.vendor, info.device, &info.name),
presents: surface.is_none_or(|s| adapter.is_surface_supported(s)),
name: info.name,
backend: info.backend,
@@ -83,8 +84,15 @@ impl Candidate {
}
/// `backend:vendor:device`, e.g. `Vulkan:1002:164e` (PCI ids, as `MESA_VK_DEVICE_SELECT` takes them).
fn key(backend: Backend, vendor: u32, device: u32) -> String {
format!("{backend:?}:{vendor:04x}:{device:04x}")
/// Metal reports no ids (`0000:0000` for every GPU), so an adapter without them is `backend:name`
/// (`Metal:Intel Iris Pro Graphics`): otherwise leaving out the one that failed would leave out
/// every GPU of a dual-GPU Mac (#651). Commas, which separate [`SKIP_ENV`]'s keys, become spaces.
fn key(backend: Backend, vendor: u32, device: u32, name: &str) -> String {
if vendor == 0 && device == 0 {
format!("{backend:?}:{}", name.replace(',', " ").trim())
} else {
format!("{backend:?}:{vendor:04x}:{device:04x}")
}
}
/// The order to try `candidates` in (their indices): only those that present to the window and
@@ -307,6 +315,27 @@ mod tests {
/// A restart leaves out the adapter the window failed on, so Power Saving on the machine of
/// #502 ends up on the NVIDIA GPU, and once every adapter failed there is nothing to try.
/// A dual-GPU Mac reports both GPUs under Metal with no PCI ids (#651): their keys still
/// differ, so when the integrated GPU fails, the restart renders on the discrete one.
#[test]
fn gpus_without_pci_ids_are_told_apart_by_name() {
let mac = |name: &str, device_type| Candidate {
key: key(Backend::Metal, 0, 0, name),
name: name.into(),
backend: Backend::Metal,
device_type,
presents: true,
};
let c = vec![mac("NVIDIA GeForce GT 750M", DeviceType::DiscreteGpu), mac("Intel Iris Pro Graphics", DeviceType::IntegratedGpu)];
assert_eq!((c[0].key.as_str(), c[1].key.as_str()), ("Metal:NVIDIA GeForce GT 750M", "Metal:Intel Iris Pro Graphics"));
let first = adapter_order(&c, PowerPreference::LowPower, None, &[]);
assert_eq!(names(&c, &first)[0], "Intel Iris Pro Graphics");
let skip = parse_skip(&c[first[0]].key);
assert_eq!(names(&c, &adapter_order(&c, PowerPreference::LowPower, None, &skip)), ["NVIDIA GeForce GT 750M"]);
// A comma in a name can't split the list.
assert_eq!(parse_skip(&key(Backend::Gl, 0, 0, "Mesa, llvmpipe")), ["Gl:Mesa llvmpipe"]);
}
#[test]
fn a_restart_tries_the_next_adapter() {
let c = issue_502();
@@ -433,8 +462,8 @@ mod tests {
fn skipped_adapters_parse_from_a_comma_separated_list() {
assert_eq!(parse_skip("Vulkan:1002:164e, Gl:10de:2f04,,"), ["Vulkan:1002:164e", "Gl:10de:2f04"]);
assert!(parse_skip("").is_empty());
assert_eq!(key(Backend::Vulkan, 0x1002, 0x164e), "Vulkan:1002:164e");
assert_eq!(key(Backend::Gl, 0x10de, 0x2f04), "Gl:10de:2f04");
assert_eq!(key(Backend::Vulkan, 0x1002, 0x164e, "AMD Radeon"), "Vulkan:1002:164e");
assert_eq!(key(Backend::Gl, 0x10de, 0x2f04, "NVIDIA"), "Gl:10de:2f04");
}
#[test]
+5
View File
@@ -423,6 +423,11 @@ fn main() -> std::process::ExitCode {
// Only adapters that can show the window, in the order `gpu` gives (#306, #502).
if let eframe::egui_wgpu::WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup {
create.native_adapter_selector = Some(gpu::selector(power, startup.clone()));
// Nothing draws or dispatches indirectly, so wgpu's check of indirect arguments only
// costs a compute shader at start-up, one some drivers can't compile (OCLP-patched
// Metal on an Iris Pro, #651). `WGPU_VALIDATION_INDIRECT_CALL=1` turns it back on.
create.instance_descriptor.flags =
(eframe::wgpu::InstanceFlags::from_build_config() - eframe::wgpu::InstanceFlags::VALIDATION_INDIRECT_CALL).with_env();
}
options
};
+4
View File
@@ -31,3 +31,7 @@ sync_github_name = true
[people.omd0]
sync_github_name = true
[people.dotCooCoo]
real_name = "Robert Lee"
sync_github_name = true
+332 -8
View File
@@ -1,6 +1,9 @@
//! Swatch library files: the native `.vcswatches` JSON (colour models, global, spot, gradients
//! and colour groups exactly), `.gpl` palettes (8-bit RGB; colour groups as `# Group:` comment
//! headers) and CSS custom properties (written only).
//! headers) and CSS custom properties (written only). Swatch exchange files (`.ase`) are read
//! only ([`read_bytes`]).
use std::collections::{HashMap, HashSet};
use serde::{Deserialize, Serialize};
@@ -58,6 +61,15 @@ struct NativeFile {
const NATIVE_FORMAT: &str = "vcswatches";
const GPL_HEADER: &str = "GIMP Palette";
const GPL_GROUP: &str = "# Group:";
const ASE_SIGNATURE: &[u8] = b"ASEF";
const ASE_GROUP_START: u16 = 0xC001;
const ASE_GROUP_END: u16 = 0xC002;
const ASE_COLOR: u16 = 0x0001;
/// The most colors and groups read from one `.ase` file.
const ASE_MAX_ENTRIES: usize = 100_000;
/// The most UTF-16 code units of a name that are kept.
const ASE_MAX_NAME: usize = 1024;
const ASE_CUT_SHORT: &str = "the swatch exchange file is cut short";
/// Write `lib` in `format`. Pattern swatches (their tiles live in a document) and None are left
/// out; `.gpl` keeps solid colours only, as 8-bit RGB.
@@ -199,16 +211,34 @@ pub fn sniff(text: &str) -> bool {
t.starts_with(GPL_HEADER) || (t.starts_with('{') && t.contains(NATIVE_FORMAT))
}
/// Read the bytes of a library file: a swatch exchange `.ase` file, else a `.vcswatches` or
/// `.gpl` library ([`read`]). `name` names it when the file doesn't.
pub fn read_bytes(bytes: &[u8], name: &str) -> Result<SwatchLibrary, String> {
if bytes.starts_with(ASE_SIGNATURE) {
return read_ase(bytes, name);
}
read(&String::from_utf8_lossy(bytes), name)
}
/// Are `bytes` a library [`read_bytes`] understands? Text that isn't valid UTF-8 is checked as
/// [`read_bytes`] reads it, with the invalid bytes replaced (its first KiB is enough).
pub fn sniff_bytes(bytes: &[u8]) -> bool {
bytes.starts_with(ASE_SIGNATURE)
|| std::str::from_utf8(bytes).is_ok_and(sniff)
|| sniff(&String::from_utf8_lossy(bytes.get(..1024).unwrap_or(bytes)))
}
/// `.gpl`: `Name:` names the library, `# Group: name` starts a colour group, other `#` lines and
/// headers (`Columns:`) are skipped, as are lines that aren't `r g b [name]`. Unnamed colours are
/// named by their values; repeated names get a number.
/// headers (`Columns:`) are skipped, as are lines that aren't `r g b [name]`. Unnamed colors are
/// named by their values and unnamed groups "Color Group"; a name a color or group already has gets
/// a number ([`UniqueNames`]).
fn read_gpl(text: &str, fallback: &str) -> SwatchLibrary {
let mut lib = SwatchLibrary { name: fallback.into(), ..Default::default() };
let mut names: Vec<String> = vec![];
let mut names = UniqueNames::default();
for line in text.lines().skip(1) {
let line = line.trim();
if let Some(g) = line.strip_prefix(GPL_GROUP) {
lib.groups.push(SwatchGroup { name: g.trim().to_string(), swatches: vec![] });
lib.groups.push(SwatchGroup { name: names.unique(group_name(g)), swatches: vec![] });
continue;
}
if let Some(n) = line.strip_prefix("Name:") {
@@ -221,9 +251,7 @@ fn read_gpl(text: &str, fallback: &str) -> SwatchLibrary {
let [r, g, b] = rgb[..] else { continue };
let rest = words[3..].join(" ");
let base = if rest.is_empty() { format!("R={r} G={g} B={b}") } else { rest };
let name = (1..).map(|i| if i == 1 { base.clone() } else { format!("{base} {i}") }).find(|n| !names.contains(n)).unwrap_or(base);
names.push(name.clone());
let w = Swatch { name, paint: Paint::solid(Color::rgb8(r, g, b)), global: false, spot: false };
let w = Swatch { name: names.unique(base), paint: Paint::solid(Color::rgb8(r, g, b)), global: false, spot: false };
match lib.groups.last_mut() {
Some(grp) => grp.swatches.push(w),
None => lib.swatches.push(w),
@@ -232,6 +260,184 @@ fn read_gpl(text: &str, fallback: &str) -> SwatchLibrary {
lib
}
/// `.ase`, from public descriptions of the format: the layout from
/// <https://www.selapa.net/swatches/colors/fileformats.php>, the component ranges from
/// <https://github.com/nsfmc/swatch>. After the signature come, big-endian, a `u16` major (1) and
/// minor version, a `u32` block count and the blocks, each a `u16` type, a `u32` body length and
/// the body. A group start's body is a name. A color's body is a name, a four-character model
/// (`RGB `, `CMYK`, `LAB `, `Gray`), its components as `f32` (3, 4, 3 and 1 of them) and a `u16`
/// color type (0 global, 1 spot, 2 process). RGB, CMYK and gray components run from 0 to 1 (a
/// gray level of 1 is white), Lab lightness from 0 to 1 and a and b from −128 to 127. A lightness
/// above 1 is read as L* itself. A name is a `u16` count of UTF-16 code units, the terminating zero
/// included, then the units.
///
/// Color groups become groups: a group start inside an open group ends that group, and a group
/// left open ends with the file. Blocks of other types and colors in other models are skipped.
/// Unnamed colors are named by their values and unnamed groups "Color Group"; a name a color or
/// group already has gets a number ([`UniqueNames`]). A truncated file, a major version other than
/// 1 or more than [`ASE_MAX_ENTRIES`] colors and groups is an error.
fn read_ase(bytes: &[u8], fallback: &str) -> Result<SwatchLibrary, String> {
let mut data = AseData(bytes);
data.bytes(ASE_SIGNATURE.len())?;
let (major, minor) = (data.u16()?, data.u16()?);
if major != 1 {
return Err(format!("swatch exchange version {major}.{minor} isn't supported (only 1.x)"));
}
let blocks = data.u32()?;
let mut lib = SwatchLibrary { name: fallback.into(), ..Default::default() };
let mut names = UniqueNames::default();
let (mut in_group, mut entries) = (false, 0usize);
for _ in 0..blocks {
let kind = data.u16()?;
let len = usize::try_from(data.u32()?).unwrap_or(usize::MAX);
let mut body = AseData(data.bytes(len)?);
if matches!(kind, ASE_GROUP_START | ASE_COLOR) {
entries += 1;
if entries > ASE_MAX_ENTRIES {
return Err(format!("the swatch exchange file holds more than {ASE_MAX_ENTRIES} colors and groups"));
}
}
match kind {
ASE_GROUP_START => {
lib.groups.push(SwatchGroup { name: names.unique(group_name(&body.name()?)), swatches: vec![] });
in_group = true;
}
ASE_GROUP_END => in_group = false,
ASE_COLOR => {
let Some(mut w) = ase_swatch(&mut body)? else { continue };
w.name = names.unique(std::mem::take(&mut w.name));
match lib.groups.last_mut().filter(|_| in_group) {
Some(g) => g.swatches.push(w),
None => lib.swatches.push(w),
}
}
// Other blocks are skipped.
_ => {}
}
}
Ok(lib)
}
/// The swatch of an `.ase` color block, `None` for a model other than RGB, CMYK, Lab and Gray.
/// Components are clamped to their ranges.
fn ase_swatch(body: &mut AseData) -> Result<Option<Swatch>, String> {
let name = body.name()?;
let unit = |v: f32| v.clamp(0.0, 1.0);
let color = match &body.array::<4>()? {
b"RGB " => {
let [r, g, b] = [body.f32()?, body.f32()?, body.f32()?];
Color::rgb(unit(r), unit(g), unit(b))
}
b"CMYK" => {
let [c, m, y, k] = [body.f32()?, body.f32()?, body.f32()?, body.f32()?];
Color::cmyk(unit(c), unit(m), unit(y), unit(k))
}
// Lightness is stored as a fraction of 100. Some writers store L* itself, which shows as a
// value above 1.
b"LAB " => {
let [l, a, b] = [body.f32()?, body.f32()?, body.f32()?];
let l = if l > 1.0 { l.min(100.0) } else { unit(l) * 100.0 };
Color::lab(l, a.clamp(-128.0, 127.0), b.clamp(-128.0, 127.0))
}
// A gray level (1 is white); a gray color holds its ink.
b"Gray" => Color::gray(1.0 - unit(body.f32()?)),
_ => return Ok(None),
};
// Some writers leave the color type out, which makes a process color.
let kind = if body.0.len() >= 2 { body.u16()? } else { 2 };
// Spot colors are global.
let (global, spot) = match kind {
0 => (true, false),
1 => (true, true),
_ => (false, false),
};
let name = if name.is_empty() { value_name(color) } else { name };
Ok(Some(Swatch { name, paint: Paint::solid(color), global, spot }))
}
/// A color's values in its own model, as new swatches are named ("C=10 M=20 Y=30 K=0",
/// "R=255 G=128 B=0", "Gray K=40", "L=52 a=70 b=-30").
fn value_name(c: Color) -> String {
let pct = |v: f32| (v * 100.0).round();
let byte = |v: f32| (v * 255.0).round();
match c {
Color::Cmyk { c, m, y, k } => format!("C={} M={} Y={} K={}", pct(c), pct(m), pct(y), pct(k)),
Color::Rgb { r, g, b } => format!("R={} G={} B={}", byte(r), byte(g), byte(b)),
Color::Gray { k } => format!("Gray K={}", pct(k)),
// `+ 0.0` turns a rounded -0 into 0.
Color::Lab { l, a, b } => format!("L={} a={} b={}", l.round() + 0.0, a.round() + 0.0, b.round() + 0.0),
}
}
/// `.ase` data, read field by field; reading past its end is an error.
struct AseData<'a>(&'a [u8]);
impl<'a> AseData<'a> {
fn bytes(&mut self, n: usize) -> Result<&'a [u8], String> {
let (head, rest) = self.0.split_at_checked(n).ok_or(ASE_CUT_SHORT)?;
self.0 = rest;
Ok(head)
}
fn array<const N: usize>(&mut self) -> Result<[u8; N], String> {
let (head, rest) = self.0.split_first_chunk::<N>().ok_or(ASE_CUT_SHORT)?;
self.0 = rest;
Ok(*head)
}
fn u16(&mut self) -> Result<u16, String> {
self.array().map(u16::from_be_bytes)
}
fn u32(&mut self) -> Result<u32, String> {
self.array().map(u32::from_be_bytes)
}
/// A component; one that isn't a finite number reads as 0.
fn f32(&mut self) -> Result<f32, String> {
let v = f32::from_be_bytes(self.array()?);
Ok(if v.is_finite() { v } else { 0.0 })
}
/// A name up to its terminating zero, trimmed. A block that ends before it has no name.
fn name(&mut self) -> Result<String, String> {
if self.0.is_empty() {
return Ok(String::new());
}
let n = usize::from(self.u16()?);
let (units, _) = self.bytes(n * 2)?.as_chunks::<2>();
let units: Vec<u16> = units.iter().take(ASE_MAX_NAME).map(|u| u16::from_be_bytes(*u)).take_while(|&u| u != 0).collect();
Ok(String::from_utf16_lossy(&units).trim().to_string())
}
}
/// A group's name as a file gives it, trimmed; "Color Group" when it has none.
fn group_name(name: &str) -> String {
let name = name.trim();
if name.is_empty() { "Color Group".into() } else { name.to_string() }
}
/// The swatch and group names a reader has handed out. Swatches and color groups share one set of
/// names, as in a document, and a name already taken gets the first free number ("Black 2").
#[derive(Default)]
struct UniqueNames {
taken: HashSet<String>,
/// The last number tried for each repeated name.
last: HashMap<String, usize>,
}
impl UniqueNames {
fn unique(&mut self, base: String) -> String {
if self.taken.insert(base.clone()) {
return base;
}
// Each pass tries the next number, and only finitely many names are taken.
let n = self.last.entry(base.clone()).or_insert(1);
loop {
*n += 1;
let name = format!("{base} {n}");
if self.taken.insert(name.clone()) {
return name;
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -294,6 +500,11 @@ mod tests {
assert_eq!(names, ["Sky Blue", "R=10 G=20 B=30", "Black", "Black 2"]);
assert_eq!(lib.swatches[0].paint.color(), Some(Color::rgb8(0, 128, 255)));
assert_eq!(read("GIMP Palette\n1 2 3 x\n", "Fallback").unwrap().name, "Fallback");
// Colors and groups share names; an unnamed group is "Color Group".
let lib = read("GIMP Palette\n0 0 0 Black\n# Group: Black\n1 1 1 Black\n# Group:\n", "x").unwrap();
let groups: Vec<(&str, Vec<&str>)> =
lib.groups.iter().map(|g| (g.name.as_str(), g.swatches.iter().map(|w| w.name.as_str()).collect())).collect();
assert_eq!(groups, [("Black 2", vec!["Black 3"]), ("Color Group", vec![])]);
}
#[test]
@@ -321,4 +532,117 @@ mod tests {
assert!(text.contains("--red: #000000;") && text.contains("--red-2: #000000;"));
assert!(read(&text, "x").is_err(), "CSS is written only");
}
/// A swatch exchange file of `blocks` (type, body).
fn ase(blocks: &[(u16, Vec<u8>)]) -> Vec<u8> {
let mut out = b"ASEF\0\x01\0\0".to_vec();
out.extend((blocks.len() as u32).to_be_bytes());
for (kind, body) in blocks {
out.extend(kind.to_be_bytes());
out.extend((body.len() as u32).to_be_bytes());
out.extend(body);
}
out
}
/// A name as `.ase` stores it.
fn ase_name(name: &str) -> Vec<u8> {
let units: Vec<u16> = name.encode_utf16().chain([0]).collect();
let mut out = (units.len() as u16).to_be_bytes().to_vec();
out.extend(units.iter().flat_map(|u| u.to_be_bytes()));
out
}
/// A color block: name, model, components and color type.
fn ase_color(name: &str, model: &[u8; 4], values: &[f32], kind: u16) -> (u16, Vec<u8>) {
let mut body = ase_name(name);
body.extend(model);
body.extend(values.iter().flat_map(|v| v.to_be_bytes()));
body.extend(kind.to_be_bytes());
(ASE_COLOR, body)
}
#[test]
fn ase_reads_color_models_kinds_and_groups() {
let bytes = ase(&[
ase_color("Sky", b"RGB ", &[0.0, 0.5, 1.0], 0),
ase_color("Ink", b"CMYK", &[1.0, 0.5, 0.0, 0.2], 1),
(ASE_GROUP_START, ase_name("Neutrals")),
ase_color("Mist", b"Gray", &[0.75], 2),
ase_color("Clay", b"LAB ", &[0.5, 20.0, -30.0], 2),
(ASE_GROUP_END, vec![]),
ase_color("Paper", b"RGB ", &[1.0, 1.0, 1.0], 2),
]);
assert!(sniff_bytes(&bytes));
let sw = |name: &str, color, global, spot| Swatch { name: name.into(), paint: Paint::solid(color), global, spot };
let expected = SwatchLibrary {
name: "Brand".into(),
swatches: vec![
sw("Sky", Color::rgb(0.0, 0.5, 1.0), true, false),
sw("Ink", Color::cmyk(1.0, 0.5, 0.0, 0.2), true, true),
sw("Paper", Color::WHITE, false, false),
],
groups: vec![SwatchGroup {
name: "Neutrals".into(),
swatches: vec![sw("Mist", Color::gray(0.25), false, false), sw("Clay", Color::lab(50.0, 20.0, -30.0), false, false)],
}],
};
assert_eq!(read_bytes(&bytes, "Brand").unwrap(), expected, "named after the file; 0 global, 1 spot, 2 process");
// A lightness above 1 is L* itself.
let deep = read_bytes(&ase(&[ase_color("Deep", b"LAB ", &[53.0, 20.0, -30.0], 2)]), "x").unwrap();
assert_eq!(deep.swatches[0].paint.color(), Some(Color::lab(53.0, 20.0, -30.0)));
// Text libraries read through the same call, also when they aren't valid UTF-8.
assert!(sniff_bytes(b"GIMP Palette\n1 2 3 x\n") && !sniff_bytes(b"ASE") && !sniff_bytes(&[0xff, 0xfe, 0]));
assert_eq!(read_bytes(b"GIMP Palette\n1 2 3 x\n", "F").unwrap().swatches.len(), 1);
let latin1 = b"GIMP Palette\n1 2 3 Caf\xe9\n";
assert!(sniff_bytes(latin1));
assert_eq!(read_bytes(latin1, "F").unwrap().swatches.len(), 1);
}
#[test]
fn ase_names_unnamed_and_repeated_entries_and_skips_other_blocks() {
let mut untyped = ase_color("Plain", b"RGB ", &[0.2, 0.4, 0.6], 2);
untyped.1.truncate(untyped.1.len() - 2);
let bytes = ase(&[
ase_color("Café 🎨", b"RGB ", &[1.0, 0.0, 0.0], 2),
ase_color("", b"CMYK", &[0.1, 0.2, 0.3, 0.0], 2),
ase_color(" Red ", b"RGB ", &[2.0, -1.0, f32::NAN], 0),
ase_color("Red", b"Gray", &[0.0], 2),
untyped,
ase_color("Hue", b"HSB ", &[0.1, 0.2, 0.3], 2),
(0x0042, vec![1, 2, 3]),
(ASE_GROUP_END, vec![]),
(ASE_GROUP_START, ase_name("")),
(ASE_GROUP_START, ase_name("Red")),
ase_color("Red", b"Gray", &[1.0], 2),
]);
let lib = read_bytes(&bytes, "x").unwrap();
let names: Vec<&str> = lib.swatches.iter().map(|w| w.name.as_str()).collect();
assert_eq!(names, ["Café 🎨", "C=10 M=20 Y=30 K=0", "Red", "Red 2", "Plain"], "an HSB color and an unknown block are skipped");
assert_eq!(lib.swatches[2].paint.color(), Some(Color::rgb(1.0, 0.0, 0.0)), "clamped, NaN read as 0");
assert!(lib.swatches[2].global && !lib.swatches[4].global, "without a color type: process");
// A group start ends the open group, and groups and colors share names.
let groups: Vec<(&str, Vec<&str>)> =
lib.groups.iter().map(|g| (g.name.as_str(), g.swatches.iter().map(|w| w.name.as_str()).collect())).collect();
assert_eq!(groups, [("Color Group", vec![]), ("Red 3", vec!["Red 4"])]);
assert_eq!(lib.groups[1].swatches[0].paint.color(), Some(Color::gray(0.0)), "gray level 1 is white");
}
#[test]
fn damaged_ase_files_are_errors() {
let good = ase(&[(ASE_GROUP_START, ase_name("G")), ase_color("Sky", b"RGB ", &[0.0, 0.5, 1.0], 0)]);
assert_eq!(read_bytes(&good, "x").unwrap().len(), 1);
for n in ASE_SIGNATURE.len()..good.len() {
assert!(read_bytes(&good[..n], "x").is_err(), "cut at {n}");
}
let mut v2 = good.clone();
v2[5] = 2;
assert!(read_bytes(&v2, "x").unwrap_err().contains("2.0"), "version 2.0");
// Too many colors, or too many groups (empty group starts take 6 bytes each).
let colors: Vec<(u16, Vec<u8>)> = (0..=ASE_MAX_ENTRIES).map(|_| ase_color("Gray", b"Gray", &[0.5], 2)).collect();
assert!(read_bytes(&ase(&colors), "x").unwrap_err().contains("more than"));
let groups: Vec<(u16, Vec<u8>)> = (0..=ASE_MAX_ENTRIES).map(|_| (ASE_GROUP_START, vec![])).collect();
assert!(read_bytes(&ase(&groups), "x").unwrap_err().contains("more than"));
assert_eq!(read_bytes(&ase(&groups[1..]), "x").unwrap().groups.len(), ASE_MAX_ENTRIES, "up to the limit");
}
}
+8
View File
@@ -40,6 +40,7 @@ pub mod slices;
pub mod style_libs;
pub mod swatches;
pub mod text;
pub mod trace;
use std::collections::BTreeMap;
use std::sync::Arc;
@@ -89,6 +90,7 @@ pub use text::{
ParaDirection, ParaStyle, PathAlign, PathEffect, ScriptMetrics, TabAlign, TabStop, TextKind, TextObject, TextRun, TextStyleDef, TextWrap,
VerticalAlign, WrapShape,
};
pub use trace::TraceView;
pub use vectorcraft_color as color;
pub use vectorcraft_geom as geom;
@@ -610,6 +612,11 @@ pub struct Document {
/// save time only, so changing the view never marks the document modified.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub last_view: Option<SavedView>,
/// The layers, sublayers and groups open in the Layers panel when the document was saved; they
/// reopen that way. `None`: the default, only the top-level layers open. Written at save time
/// only, like [`Document::last_view`].
#[serde(default, skip_serializing_if = "Option::is_none")]
pub layers_open: Option<Vec<NodeId>>,
/// Edit → Assign Profile: the profiles the document is tagged with (files before format v3
/// kept them in `unknown`, see [`Document::migrate_color_profiles`]).
#[serde(default, skip_serializing_if = "ColorProfiles::is_empty")]
@@ -702,6 +709,7 @@ impl Document {
metadata: DocMetadata::default(),
raster_effects: RasterEffectsSettings::default(),
last_view: None,
layers_open: None,
color_profiles: ColorProfiles::default(),
export_settings: Default::default(),
extra: Default::default(),
+2 -1
View File
@@ -463,7 +463,8 @@ pub struct Node {
/// Opacity mask (Transparency panel). Its art lives here, outside the layer tree.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub mask: Option<Box<OpacityMask>>,
/// Image Trace object: `{preset, params}` it was traced with (the Image Trace panel shows them).
/// Image Trace object: `{preset, params, view?}` it was traced with (the Image Trace panel shows
/// them; `view` is its [`crate::TraceView`] id, absent for the tracing result).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub trace: Option<Box<serde_json::Value>>,
/// Object → Text Wrap: area type below this object (in the same layer) flows around it.
+92
View File
@@ -0,0 +1,92 @@
//! Image Trace objects' View: how a live trace draws on screen.
//!
//! An Image Trace object is a group whose `trace` holds `{preset, params, view}` (see
//! `imageTrace.make`). The view is a viewing aid only: exports, printing and Expand always use the
//! tracing result, whatever it is set to.
use crate::node::Node;
/// Image Trace › View.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum TraceView {
/// The traced shapes as they are filled.
#[default]
Result,
/// The traced shapes, with their outlines over them.
ResultWithOutlines,
/// Only the traced shapes' outlines.
Outlines,
/// The source image, with the traced shapes' outlines over it.
OutlinesWithSource,
/// Only the source image.
Source,
}
impl TraceView {
/// Panel order.
pub const ALL: [Self; 5] = [Self::Result, Self::ResultWithOutlines, Self::Outlines, Self::OutlinesWithSource, Self::Source];
/// The id used in command params and in the saved `trace` object.
pub fn id(self) -> &'static str {
match self {
Self::Result => "tracingResult",
Self::ResultWithOutlines => "tracingResultWithOutlines",
Self::Outlines => "outlines",
Self::OutlinesWithSource => "outlinesWithSourceImage",
Self::Source => "sourceImage",
}
}
/// The view an id names (any case).
pub fn from_id(id: &str) -> Option<Self> {
Self::ALL.into_iter().find(|v| v.id().eq_ignore_ascii_case(id))
}
/// The view an Image Trace object's `trace` settings ask for (the tracing result when they
/// name none, or an unknown one).
pub fn of(trace: &serde_json::Value) -> Self {
trace.get("view").and_then(serde_json::Value::as_str).and_then(Self::from_id).unwrap_or_default()
}
/// Whether the source image shows.
pub fn shows_source(self) -> bool {
matches!(self, Self::OutlinesWithSource | Self::Source)
}
/// Whether the traced shapes show filled.
pub fn shows_result(self) -> bool {
matches!(self, Self::Result | Self::ResultWithOutlines)
}
/// Whether the traced shapes' outlines show.
pub fn shows_outlines(self) -> bool {
matches!(self, Self::ResultWithOutlines | Self::Outlines | Self::OutlinesWithSource)
}
}
impl Node {
/// The View of an Image Trace object (the tracing result for anything else, or an unknown id).
pub fn trace_view(&self) -> TraceView {
self.trace.as_deref().map(TraceView::of).unwrap_or_default()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ids_round_trip_and_unknown_views_show_the_result() {
for v in TraceView::ALL {
assert_eq!(TraceView::from_id(v.id()), Some(v));
assert_eq!(TraceView::from_id(&v.id().to_ascii_uppercase()), Some(v));
assert!(v.shows_result() || v.shows_outlines() || v.shows_source(), "{v:?} shows something");
}
let mut g = Node::group(crate::NodeId(1), vec![]);
assert_eq!(g.trace_view(), TraceView::Result);
g.trace = Some(Box::new(serde_json::json!({"view": "outlines"})));
assert_eq!(g.trace_view(), TraceView::Outlines);
g.trace = Some(Box::new(serde_json::json!({"view": "sepia"})));
assert_eq!(g.trace_view(), TraceView::Result);
}
}
+96 -7
View File
@@ -14,8 +14,8 @@ use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::appearance::{AppearanceItem, FillLayer, StrokeLayer};
use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, Selection};
use vectorcraft_doc::appearance::{AppearanceItem, FillLayer, LineCap, LineJoin, StrokeLayer};
use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, Selection, TraceView};
use vectorcraft_geom::{FillRule, PathData, Point, Rect, SubPath};
use vectorcraft_pathops as po;
use vectorcraft_tools::builder::{
@@ -120,7 +120,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Make",
["Object", "Image Trace"],
None,
"{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\", threshold: 0-255, colors: 2-256, paths: 0-100, corners: 0-100, noise: px, method: \"abutting\"|\"overlapping\", ignoreWhite, snapCurvesToLines}} → {id, paths, anchors, colors}",
"{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, automatic: flat art with its own colours, else fullTone, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), paths: 0-100, corners: 0-100, noise: px, method: \"abutting\"|\"overlapping\", ignoreWhite, snapCurvesToLines, fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult)} → {id, paths, anchors, colors}",
has_selection_or_ids,
|s, p| trace_make(s, p, false)
),
@@ -151,6 +151,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_selection_or_ids,
trace_expand
),
cmd!(
"imageTrace.setView",
"Image Trace View",
[],
None,
"{id?|ids?: Image Trace objects (default: selection), view: \"tracingResult\"|\"tracingResultWithOutlines\"|\"outlines\"|\"outlinesWithSourceImage\"|\"sourceImage\"} how they draw on screen; exports, printing and Expand keep the tracing result → {ids, view}",
has_selection_or_ids,
trace_set_view
),
cmd!(query "imageTrace.presets", "Image Trace Presets", [], None, "{} → {presets: [{name, params}]}", always, |_, _| {
Ok(json!({ "presets": tr::presets().into_iter().map(|(n, p)| json!({ "name": n, "params": p })).collect::<Vec<_>>() }))
}),
@@ -639,6 +648,13 @@ fn is_trace_group(n: &Node) -> bool {
&& n.children().is_some_and(|c| c.first().is_some_and(|i| matches!(i.kind, NodeKind::Image(_))))
}
/// The `view` param ([`TraceView`] id), if given.
fn view_param(cmd: &str, p: &Value) -> Result<Option<TraceView>> {
let Some(v) = p.get("view").filter(|v| !v.is_null()) else { return Ok(None) };
let ids = || TraceView::ALL.map(TraceView::id).join(", ");
v.as_str().and_then(TraceView::from_id).map(Some).ok_or_else(|| bad(cmd, format!("view must be one of {}", ids())))
}
fn trace_params(p: &Value) -> Result<tr::TraceParams> {
let name = str_param(p, "preset").unwrap_or("Default");
let base = tr::preset(name).ok_or_else(|| bad("imageTrace.make", format!("unknown preset `{name}` (see imageTrace.presets)")))?;
@@ -648,7 +664,38 @@ fn trace_params(p: &Value) -> Result<tr::TraceParams> {
for (k, val) in src {
o.insert(k.clone(), val.clone());
}
serde_json::from_value(v).map_err(|e| bad("imageTrace.make", e.to_string()))
let params: tr::TraceParams = serde_json::from_value(v).map_err(|e| bad("imageTrace.make", e.to_string()))?;
if !params.fills && !params.strokes {
return Err(bad("imageTrace.make", "Create needs fills, strokes or both"));
}
if !(params.stroke_width.is_finite() && params.stroke_width > 0.0) {
return Err(bad("imageTrace.make", "strokeWidth must be a positive number of pixels"));
}
Ok(params)
}
/// Document Library in Color mode: look the library's colours up into `params.swatches` → each
/// one as traced (sRGB) with the colour to fill with.
fn trace_library(s: &Session, params: &mut tr::TraceParams) -> Result<Vec<([u8; 3], Color)>> {
const C: &str = "imageTrace.make";
if params.mode != tr::Mode::Color || params.palette != tr::Palette::DocumentLibrary {
return Ok(vec![]);
}
let key = params.library.as_str();
let colors = super::swatchlib::library_colors(s, key)
.ok_or_else(|| bad(C, format!("no swatch library `{key}` (see swatch.library.list; \"document\": the document's swatches)")))?;
if colors.is_empty() {
return Err(bad(C, format!("`{key}` has no colours")));
}
let library: Vec<([u8; 3], Color)> = colors
.into_iter()
.map(|c| {
let [r, g, b, _] = c.to_rgba8(1.0);
([r, g, b], c)
})
.collect();
params.swatches = library.iter().map(|l| l.0).collect();
Ok(library)
}
/// The most anchor points an Image Trace may make: a photo traced at high fidelity can make
@@ -658,7 +705,8 @@ pub const MAX_TRACE_ANCHORS: usize = 2_000_000;
fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Value> {
const C: &str = "imageTrace.make";
let params = trace_params(p)?;
let mut params = trace_params(p)?;
let view = view_param(C, p)?;
let params_json = serde_json::to_value(&params).map_err(|e| EngineError::Other(e.to_string()))?;
// The preset's name if the parameters are exactly that preset's, else "Custom".
let named = str_param(p, "preset").unwrap_or("Default");
@@ -687,11 +735,14 @@ fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Value> {
};
let blob = s.doc()?.doc.images.get(&img.key).ok_or_else(|| EngineError::Other(format!("image data `{}` is missing", img.key)))?;
let raster = tr::Raster::decode(&blob.bytes).map_err(|e| EngineError::Other(e.to_string()))?;
let library = trace_library(s, &mut params)?;
let res = tr::trace_within(&raster, &params, MAX_TRACE_ANCHORS).map_err(|e| EngineError::Other(e.to_string()))?;
// Pixel space of the decoded raster → the image object's pixel space → document.
let sx = img.width.max(1) as f64 / raster.width.max(1) as f64;
let sy = img.height.max(1) as f64 / raster.height.max(1) as f64;
let xf = img.xf * vectorcraft_geom::Affine::scale_non_uniform(sx, sy);
// Document units per raster pixel (stroke widths).
let unit = xf.determinant().abs().sqrt();
let (npaths, anchors, colors) = (res.paths.len(), res.anchor_count(), res.palette.len());
let label = if expand { "Image Trace (Make and Expand)" } else { "Image Trace" };
let id = s.edit(label, |d, sel| {
@@ -714,14 +765,30 @@ fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Value> {
for tp in res.paths {
let path = tp.path.transformed(xf);
let mut n = shape_node(d, path, None);
n.appearance = fill_only(Paint::solid(Color::rgb8(tp.color[0], tp.color[1], tp.color[2])));
// A library colour fills with the swatch's own colour (its model kept).
let color = library.iter().find(|(rgb, _)| *rgb == tp.color).map_or_else(|| Color::rgb8(tp.color[0], tp.color[1], tp.color[2]), |l| l.1);
let paint = Paint::solid(color);
n.appearance = match tp.stroke {
// Traced lines: round ends and corners, as drawn lines have.
Some(width) => Appearance {
items: vec![AppearanceItem::Stroke(StrokeLayer {
cap: LineCap::Round,
join: LineJoin::Round,
..StrokeLayer::new(paint, width * unit)
})],
..Default::default()
},
None => fill_only(paint),
};
children.push(Arc::new(n));
}
let gid = d.alloc_id();
let mut g = Node::group(gid, children);
g.name = if expand { None } else { Some(TRACE_NAME.into()) };
if !expand {
g.trace = Some(Box::new(json!({ "preset": preset_label, "params": params_json })));
// Tracing again keeps the object's view unless another is asked for.
let view = view.unwrap_or_else(|| src.trace_view());
g.trace = Some(Box::new(json!({ "preset": preset_label, "params": params_json, "view": view.id() })));
}
let (par, idx, _) = d.position(target).ok_or(EngineError::NoNode(target))?;
d.remove(target)?;
@@ -741,6 +808,28 @@ fn trace_targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
Ok(v)
}
fn trace_set_view(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "imageTrace.setView";
let view = view_param(C, p)?.ok_or_else(|| bad(C, "view is required"))?;
let targets = trace_targets(s, p)?;
let d = &s.doc()?.doc;
if targets.iter().all(|g| d.node(*g).is_some_and(|n| n.trace_view() == view)) {
return Ok(json!({ "ids": ids_json(&targets), "view": view.id() }));
}
s.edit("Image Trace View", |d, _| {
for g in &targets {
let n = d.node_mut(*g).ok_or(EngineError::NoNode(*g))?;
if let Some(t) = n.trace.as_deref_mut().and_then(Value::as_object_mut) {
t.insert("view".into(), json!(view.id()));
} else {
n.trace = Some(Box::new(json!({ "preset": "Custom", "view": view.id() })));
}
}
Ok(())
})?;
Ok(json!({ "ids": ids_json(&targets), "view": view.id() }))
}
fn trace_release(s: &mut Session, p: &Value) -> Result<Value> {
let targets = trace_targets(s, p)?;
let ids = s.edit("Release Image Trace", |d, sel| {
+13 -7
View File
@@ -216,15 +216,20 @@ fn is_svg(f: &Format) -> bool {
matches!(f.id, "svg" | "svgz")
}
/// The document as written: native files carry the view to reopen at.
/// The document as written: native files carry the view to reopen at and the Layers panel's open
/// rows.
fn doc_to_save(st: &DocState, f: &Format) -> Arc<Document> {
if is_native(f) && st.doc.last_view != st.view {
let mut d = (*st.doc).clone();
d.last_view = st.view.clone();
Arc::new(d)
} else {
st.doc.clone()
if !is_native(f) {
return st.doc.clone();
}
let open = st.layers_open.saved(&st.doc);
if st.doc.last_view == st.view && st.doc.layers_open == open {
return st.doc.clone();
}
let mut d = (*st.doc).clone();
d.last_view = st.view.clone();
d.layers_open = open;
Arc::new(d)
}
/// What a format loses against a native file (reported whenever a save writes it).
@@ -274,6 +279,7 @@ fn artboard_doc(doc: &Document, i: usize) -> Document {
d.artboards = vec![a.clone()];
// It opens fitted to its artboard, not at the master file's view.
d.last_view = None;
d.layers_open = None;
for layer in &mut d.layers {
keep_on(layer, r);
}
+2 -2
View File
@@ -70,8 +70,8 @@ pub fn specs() -> Vec<CommandSpec> {
impl LibraryFile for StyleLibrary {
const EXTS: &'static [&'static str] = &[STYLES_EXT];
fn read(text: &str, stem: &str) -> std::result::Result<Self, String> {
style_libs::read(text, stem)
fn read(bytes: &[u8], stem: &str) -> std::result::Result<Self, String> {
style_libs::read(&String::from_utf8_lossy(bytes), stem)
}
fn name(&self) -> &str {
&self.name
+32 -17
View File
@@ -69,7 +69,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Other Library…",
["Window", "Swatch Libraries"],
None,
"{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} load a .vcswatches or .gpl library, or the swatches of any document VectorCraft opens (see document.formats), for the library panel (Window → Swatch Libraries lists it until the app quits) → {library: id, name, count}",
"{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} load a .vcswatches, .gpl or .ase (swatch exchange) library, or the swatches of any document VectorCraft opens (see document.formats), for the library panel (Window → Swatch Libraries lists it until the app quits) → {library: id, name, count}",
always,
load
),
@@ -98,23 +98,24 @@ struct Extra<L> {
pub trait LibraryFile: Sized {
/// The extensions of its files (lower case).
const EXTS: &'static [&'static str];
/// Read a library file whose name without the extension is `stem` (an unnamed library's name).
fn read(text: &str, stem: &str) -> std::result::Result<Self, String>;
/// Read the bytes of a library file whose name without the extension is `stem` (an unnamed
/// library's name).
fn read(bytes: &[u8], stem: &str) -> std::result::Result<Self, String>;
fn name(&self) -> &str;
}
impl LibraryFile for SwatchLibrary {
const EXTS: &'static [&'static str] = LIBRARY_EXTS;
fn read(text: &str, stem: &str) -> std::result::Result<Self, String> {
palette_io::read(text, stem)
fn read(bytes: &[u8], stem: &str) -> std::result::Result<Self, String> {
palette_io::read_bytes(bytes, stem)
}
fn name(&self) -> &str {
&self.name
}
}
/// The extensions of library files [`palette_io::read`] reads.
pub const LIBRARY_EXTS: &[&str] = &["vcswatches", "gpl"];
/// The extensions of library files [`palette_io::read_bytes`] reads.
pub const LIBRARY_EXTS: &[&str] = &["vcswatches", "gpl", "ase"];
impl<L: LibraryFile> Libraries<L> {
pub fn user_dir(&self) -> Option<&str> {
@@ -133,7 +134,7 @@ impl<L: LibraryFile> Libraries<L> {
let Some(dir) = self.user_dir.clone() else { return };
for path in library_files(&dir, L::EXTS) {
let file = file_name(&path);
let Some(lib) = read_file(&path).ok().and_then(|b| L::read(&String::from_utf8_lossy(&b), stem(&file)).ok()) else { continue };
let Some(lib) = read_file(&path).ok().and_then(|b| L::read(&b, stem(&file)).ok()) else { continue };
let info = LibraryInfo { id: format!("user/{file}"), name: lib.name().to_string(), category: "user" };
self.extra.push(Extra { info, path: Some(path), lib: Arc::new(lib) });
}
@@ -275,11 +276,18 @@ pub const DOCUMENT_SWATCHES: &str = "document";
/// [`DOCUMENT_SWATCHES`], of the active document's swatches and colour groups. `None` when there is
/// no such library (or document).
pub fn limit_palette(s: &Session, key: &str) -> Option<Palette> {
Some(Palette::new(library_colors(s, key)?))
}
/// The solid colours of library `key` (an id or name) or, for [`DOCUMENT_SWATCHES`], of the
/// active document's swatches and colour groups. `None` when there is no such library (or
/// document).
pub fn library_colors(s: &Session, key: &str) -> Option<Vec<Color>> {
let colors = |sw: &Swatch| sw.paint.color();
if key == DOCUMENT_SWATCHES {
return Some(Palette::new(s.active()?.doc.swatches_iter().filter_map(colors)));
return Some(s.active()?.doc.swatches_iter().filter_map(colors).collect());
}
Some(Palette::new(library(s, key)?.1.iter().filter_map(colors)))
Some(library(s, key)?.1.iter().filter_map(colors).collect())
}
/// The `limitTo` parameter's palette ([`limit_palette`]); `None` without one (or for "").
@@ -351,12 +359,11 @@ fn load(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "swatch.library.load";
let (info, lib) = s.swatch_libraries.load(p, C, |bytes, file| {
// A library file, or a document whose swatches become the library.
match std::str::from_utf8(bytes).ok().filter(|t| palette_io::sniff(t)) {
Some(t) => palette_io::read(t, stem(file)).map_err(|e| bad(C, e)),
None => {
let doc = super::fileio::load(file, bytes).map_err(|e| bad(C, e.to_string()))?.doc;
document_library(&doc, &[], stem(file).to_string(), C)
}
if palette_io::sniff_bytes(bytes) {
palette_io::read_bytes(bytes, stem(file)).map_err(|e| bad(C, e))
} else {
let doc = super::fileio::load(file, bytes).map_err(|e| bad(C, e.to_string()))?.doc;
document_library(&doc, &[], stem(file).to_string(), C)
}
})?;
Ok(json!({"library": info.id, "name": info.name, "count": lib.len()}))
@@ -417,12 +424,17 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
} else {
s.edit("Add to Swatches", |d, _| {
let mut out = vec![];
// Each library group goes into one document group: the group of that name the document
// already had, or one made here.
let before = d.swatch_groups.len();
let mut placed: Vec<(&str, usize)> = vec![];
for (group, w) in fresh {
let name = d.free_swatch_name(&w.name);
let sw = Swatch { name: name.clone(), ..(*w).clone() };
match group {
Some(g) => {
let i = match d.swatch_groups.iter().position(|x| x.name == *g) {
let found = placed.iter().find(|(n, _)| *n == g).map(|&(_, i)| i);
let i = match found.or_else(|| d.swatch_groups.iter().take(before).position(|x| x.name == *g)) {
Some(i) => i,
None => {
let name = d.free_swatch_name(g);
@@ -430,6 +442,9 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
d.swatch_groups.len() - 1
}
};
if found.is_none() {
placed.push((g, i));
}
d.swatch_groups[i].swatches.push(sw);
}
None => d.swatches.push(sw),
+2
View File
@@ -147,6 +147,8 @@ fn auto_height(t: &mut TextObject) -> bool {
let col_w = if cols > 1 { ((b.width() - t.area.gutter.max(0.0) * (cols - 1) as f64) / cols as f64).max(1.0) } else { b.width() };
with_size(&mut probe, col_w, tall);
probe.area.columns = 1;
// Measured from the top: aligned in the tall probe the lines would sit far below.
probe.area.vertical_align = vectorcraft_doc::VerticalAlign::Top;
let lay = vectorcraft_text::layout(db, &probe);
let inset = t.area.inset.max(0.0);
let Some(bottom) = lay.lines.iter().map(|l| l.baseline + l.descent).filter(|y| y.is_finite()).reduce(f64::max) else { return false };
+57 -1
View File
@@ -153,6 +153,8 @@ pub struct DocState {
pub recovery: Option<cmd::recovery::RecoveryCopy>,
/// View → Show Print Tiling, per document (view state: not saved, not undoable).
pub print_tiling: bool,
/// The rows open in the Layers panel (view state: not undoable; native files keep it).
pub layers_open: OpenRows,
/// Transform Again after a perspective move or scale (Perspective Selection tool): the
/// `perspective.transform` params it repeats. `None` once an ordinary transform follows.
pub last_perspective: Option<Value>,
@@ -160,11 +162,61 @@ pub struct DocState {
static NEXT_DOC_UID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
/// The rows open in the Layers panel: the layers, sublayers and groups that show what they hold.
/// A document opens with the ones it was saved with ([`Document::layers_open`]), else with only
/// its top-level layers open.
#[derive(Clone, Debug, Default)]
pub struct OpenRows {
ids: std::collections::HashSet<NodeId>,
/// Counts the changes, so views can keep what they work out from the open rows.
generation: u64,
}
impl OpenRows {
/// The rows `saved` in a file, else `doc`'s top-level layers.
fn new(doc: &Document, saved: Option<Vec<NodeId>>) -> Self {
let ids = match saved {
Some(ids) => ids.into_iter().collect(),
None => doc.layers.iter().map(|l| l.id).collect(),
};
Self { ids, generation: 0 }
}
pub fn contains(&self, id: NodeId) -> bool {
self.ids.contains(&id)
}
/// Open or close row `id`.
pub fn set(&mut self, id: NodeId, open: bool) {
let changed = if open { self.ids.insert(id) } else { self.ids.remove(&id) };
self.generation += u64::from(changed);
}
/// Changes so far: the same number means the same open rows.
pub fn generation(&self) -> u64 {
self.generation
}
/// What a native file keeps of the open rows: those of `doc` that hold others, in id order;
/// `None` when they are the default (only the top-level layers).
pub fn saved(&self, doc: &Document) -> Option<Vec<NodeId>> {
let mut ids = vec![];
doc.walk(|n| {
if n.children().is_some() && self.ids.contains(&n.id) {
ids.push(n.id);
}
});
ids.sort_unstable();
let mut layers: Vec<NodeId> = doc.layers.iter().map(|l| l.id).collect();
layers.sort_unstable();
(ids != layers).then_some(ids)
}
}
impl DocState {
pub fn new(mut doc: Document, path: Option<String>) -> Self {
let active_layer = doc.default_layer();
// The saved view lives here while the document is open (saves write it back).
// The saved view and open Layers rows live here while the document is open (saves write
// them back).
let view = doc.last_view.take();
let saved_open = doc.layers_open.take();
let layers_open = OpenRows::new(&doc, saved_open);
let doc = Arc::new(doc);
Self {
saved_doc: doc.clone(),
@@ -190,6 +242,7 @@ impl DocState {
recovered: false,
recovery: None,
print_tiling: false,
layers_open,
last_perspective: None,
}
}
@@ -956,6 +1009,7 @@ impl Session {
st.save_options = old.save_options.clone();
st.converted = old.converted;
st.view = old.view.clone();
st.layers_open = old.layers_open.clone();
let old = std::mem::replace(&mut self.docs[index], st);
if let Some(stash) = &mut self.batch_stash {
stash.push(old);
@@ -1532,6 +1586,8 @@ mod tests_swatchlib;
#[cfg(test)]
mod tests_targeting;
#[cfg(test)]
mod tests_textcombos;
#[cfg(test)]
mod tests_textedit;
#[cfg(test)]
mod tests_textimport;
+156 -1
View File
@@ -4,7 +4,7 @@ use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{ImageBlob, ImageObject, Node, NodeKind};
use vectorcraft_doc::{AppearanceItem, ImageBlob, ImageObject, LineCap, LineJoin, Node, NodeKind};
use vectorcraft_geom::{Affine, FillRule, PathData, Rect};
use vectorcraft_tools::{Mods, PointerEvent, PointerKind};
@@ -669,6 +669,82 @@ fn image_trace_make_and_expand_and_color_presets() {
assert!(s.execute("imageTrace.make", &json!({"params": {"mode": "rainbow"}})).is_err());
}
#[test]
fn image_trace_palettes_and_swatch_libraries() {
let mut s = session();
let quads = vectorcraft_trace::Raster::from_fn(60, 60, |x, y| match (x < 30, y < 30) {
(true, true) => [230, 20, 20, 255],
(false, true) => [20, 200, 30, 255],
(true, false) => [20, 30, 220, 255],
(false, false) => [250, 230, 10, 255],
});
add_image(&mut s, &quads, Affine::IDENTITY);
let fills = |s: &Session, id: &Value| -> Vec<Color> {
traced_paths(&node(s, NodeId(id.as_u64().unwrap()))).iter().filter_map(|n| n.appearance.fill_paint().color()).collect()
};
// Document Library: every fill is one of the document's swatch colours, as it is.
let r = s.execute("imageTrace.make", &json!({"preset": "6 Colors", "params": {"palette": "documentLibrary"}})).unwrap();
let doc = crate::cmd::swatchlib::library_colors(&s, "document").unwrap();
let got = fills(&s, &r["id"]);
assert!(!got.is_empty() && got.iter().all(|c| doc.contains(c)), "{got:?}");
let t = node(&s, NodeId(r["id"].as_u64().unwrap())).trace.unwrap();
assert_eq!((t["params"]["palette"].as_str(), t["params"]["library"].as_str()), (Some("documentLibrary"), Some("document")));
assert!(t["params"].get("swatches").is_none(), "looked up again at every trace");
// A swatch library by id: the web-safe colours.
let r = s
.execute(
"imageTrace.make",
&json!({"id": r["id"], "preset": "6 Colors", "params": {"palette": "documentLibrary", "library": "web-safe-216", "colors": 3}}),
)
.unwrap();
let got = fills(&s, &r["id"]);
assert!((1..=3).contains(&got.len()), "{got:?}");
assert!(got.iter().all(|c| c.to_rgba8(1.0)[..3].iter().all(|v| v % 51 == 0)), "{got:?}");
// Full Tone and Automatic keep the four flat colours.
let mut id = r["id"].clone();
for palette in ["fullTone", "automatic"] {
let r = s.execute("imageTrace.make", &json!({"id": id, "preset": "6 Colors", "params": {"palette": palette, "colorDetail": 50}})).unwrap();
assert_eq!(r["colors"], 4, "{palette}");
id = r["id"].clone();
}
let mut bad = |p: Value| s.execute("imageTrace.make", &json!({"preset": "6 Colors", "params": p})).is_err();
assert!(bad(json!({"palette": "documentLibrary", "library": "No Such Library"})));
assert!(bad(json!({"palette": "rainbow"})));
}
#[test]
fn image_trace_create_strokes_makes_stroked_centre_lines() {
let mut s = session();
// A 3 px wide horizontal line from x = 10 to 90 at y = 50, placed at 2× from (100, 100).
let r =
vectorcraft_trace::Raster::from_fn(100, 100, |x, y| if (10..90).contains(&x) && (49..52).contains(&y) { [0, 0, 0, 255] } else { [255; 4] });
add_image(&mut s, &r, Affine::translate((100.0, 100.0)) * Affine::scale(2.0));
let res = s.execute("imageTrace.make", &json!({"params": {"ignoreWhite": true, "strokes": true, "strokeWidth": 5}})).unwrap();
assert_eq!(res["paths"], 1);
let g = NodeId(res["id"].as_u64().unwrap());
let paths = traced_paths(&node(&s, g));
let line = &paths[0];
assert!(line.appearance.fill_paint().color().is_none(), "not filled");
let st = line.appearance.items.iter().find_map(|i| if let AppearanceItem::Stroke(st) = i { Some(st) } else { None }).expect("stroked");
assert!((st.width - 6.0).abs() < 1.0, "3 px at 2× is about 6 pt: {}", st.width);
assert_eq!((st.cap, st.join), (LineCap::Round, LineJoin::Round));
assert_eq!(st.paint, Paint::solid(Color::rgb8(0, 0, 0)));
let sp = &line.path_data().unwrap().subpaths[0];
assert!(!sp.closed);
let (a, b) = (sp.anchors[0].p, sp.anchors[sp.anchors.len() - 1].p);
assert!((a.y - 201.0).abs() < 1.5 && (b.y - 201.0).abs() < 1.5 && (a.x - b.x).abs() > 140.0, "{a:?} … {b:?}");
let t = node(&s, g).trace.unwrap();
assert_eq!((t["params"]["strokes"].as_bool(), t["params"]["strokeWidth"].as_f64()), (Some(true), Some(5.0)));
// Expand keeps the stroked line.
s.execute("imageTrace.expand", &json!({})).unwrap();
assert!(node(&s, g).children().unwrap()[0].appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(_))));
// Create needs Fills or Strokes, and a stroke width.
s.execute("edit.undo", &json!({})).unwrap();
for p in [json!({"fills": false, "strokes": false}), json!({"strokes": true, "strokeWidth": 0}), json!({"strokeWidth": -3})] {
assert!(s.execute("imageTrace.make", &json!({"id": g.0, "params": p})).is_err(), "{p}");
}
}
#[test]
fn image_trace_presets_query_and_errors() {
let mut s = session();
@@ -705,6 +781,85 @@ fn image_trace_object_remembers_its_settings() {
assert!(st.doc.node(id).unwrap().trace.is_none());
}
/// A black disc (r = 30 px) on light blue, 100 × 100 px, placed at 2× from (50, 50): traced in
/// Black and White with Ignore White, the blue drops out and one disc (r = 60 pt at (150, 150))
/// remains.
fn disc_on_blue(s: &mut Session) -> NodeId {
let r = vectorcraft_trace::Raster::from_fn(100, 100, |x, y| {
let (dx, dy) = (x as f64 + 0.5 - 50.0, y as f64 + 0.5 - 50.0);
if dx * dx + dy * dy <= 900.0 { [0, 0, 0, 255] } else { [170, 210, 255, 255] }
});
add_image(s, &r, Affine::translate((50.0, 50.0)) * Affine::scale(2.0));
let r = s.execute("imageTrace.make", &json!({"params": {"ignoreWhite": true}})).unwrap();
assert_eq!(r["paths"], 1);
NodeId(r["id"].as_u64().unwrap())
}
/// The document rendered as the canvas draws it (`trace_views`) or as exports do.
fn render_doc(s: &Session, trace_views: bool) -> vectorcraft_render::Rendered {
let opts = vectorcraft_render::RenderOptions { background: Some([255, 255, 255, 255]), trace_views, ..Default::default() };
vectorcraft_render::Renderer::new().render(&s.doc().unwrap().doc, 300, 300, Affine::IDENTITY, &opts)
}
#[test]
fn image_trace_view_is_stored_kept_and_validated() {
let mut s = session();
let g = disc_on_blue(&mut s);
assert_eq!(node(&s, g).trace.unwrap()["view"], "tracingResult");
let r = s.execute("imageTrace.setView", &json!({"view": "outlinesWithSourceImage"})).unwrap();
assert_eq!((ids(&r), r["view"].as_str()), (vec![g], Some("outlinesWithSourceImage")));
assert_eq!(node(&s, g).trace_view(), vectorcraft_doc::TraceView::OutlinesWithSource);
// Setting the view it has already adds no undo step.
let steps = s.doc().unwrap().history.undo.len();
s.execute("imageTrace.setView", &json!({"id": g.0, "view": "outlinesWithSourceImage"})).unwrap();
assert_eq!(s.doc().unwrap().history.undo.len(), steps);
// Tracing again keeps it, unless another one is asked for; it survives save and open.
let g = NodeId(s.execute("imageTrace.make", &json!({"id": g.0, "params": {"ignoreWhite": true, "noise": 30}})).unwrap()["id"].as_u64().unwrap());
assert_eq!(node(&s, g).trace_view(), vectorcraft_doc::TraceView::OutlinesWithSource);
let g = NodeId(s.execute("imageTrace.make", &json!({"id": g.0, "view": "SourceImage"})).unwrap()["id"].as_u64().unwrap());
let back = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap();
assert_eq!(back.node(g).unwrap().trace_view(), vectorcraft_doc::TraceView::Source);
// Bad views and other objects are refused.
assert!(s.execute("imageTrace.setView", &json!({"view": "sepia"})).is_err());
assert!(s.execute("imageTrace.setView", &json!({})).is_err());
assert!(s.execute("imageTrace.make", &json!({"view": 3})).is_err());
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
assert!(s.execute("imageTrace.setView", &json!({"id": a.0, "view": "outlines"})).is_err());
}
#[test]
fn image_trace_views_draw_on_screen_only_and_expand_to_the_result() {
let mut s = session();
let g = disc_on_blue(&mut s);
let dark = |p: [u8; 4]| p[0] < 60 && p[1] < 60 && p[2] < 60;
let white = |p: [u8; 4]| p[0] > 245 && p[1] > 245 && p[2] > 245;
let blue = |p: [u8; 4]| p[0] < 200 && p[2] > 245;
let (centre, beside) = ((150, 150), (70, 70));
let at = |img: &vectorcraft_render::Rendered, (x, y): (u32, u32)| img.pixel(x, y);
// The outline is a 1 px line where the disc's right side is (x = 210, anti-aliased).
let outlined = |img: &vectorcraft_render::Rendered| (205..=215).any(|x| img.pixel(x, 150)[0] < 128);
let mut expanded = None;
for view in vectorcraft_doc::TraceView::ALL {
s.execute("imageTrace.setView", &json!({"id": g.0, "view": view.id()})).unwrap();
let screen = render_doc(&s, true);
let (c, b) = (at(&screen, centre), at(&screen, beside));
assert_eq!(dark(c), view.shows_result() || view.shows_source(), "{view:?}: the disc's middle {c:?}");
assert_eq!(blue(b), view.shows_source(), "{view:?}: the image's background {b:?}");
assert!(view.shows_source() || white(b), "{view:?}: nothing beside the disc {b:?}");
if view == vectorcraft_doc::TraceView::Outlines {
assert!(outlined(&screen), "{view:?}: the disc's outline");
}
// Exports draw the tracing result whatever the view.
let export = render_doc(&s, false);
assert!(dark(at(&export, centre)) && white(at(&export, beside)), "{view:?}: export");
// Expand keeps the traced shapes, as traced, whatever the view.
s.execute("imageTrace.expand", &json!({"id": g.0})).unwrap();
let shapes: Vec<_> = node(&s, g).children().unwrap().iter().map(|c| (c.path_data().cloned(), c.appearance.clone())).collect();
assert_eq!(*expanded.get_or_insert_with(|| shapes.clone()), shapes, "{view:?}: expanded");
s.execute("edit.undo", &json!({})).unwrap();
}
}
/// #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.
+31
View File
@@ -260,6 +260,37 @@ fn the_saved_view_round_trips_without_dirtying() {
let _ = std::fs::remove_dir_all(d);
}
#[test]
fn open_layers_rows_round_trip_without_dirtying() {
let d = dir("open-rows");
let mut s = session();
let layer = s.doc().unwrap().doc.layers[0].id;
let a = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [a]})).unwrap();
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
// A document starts with its top-level layers open, and a file keeps nothing for that.
assert!(s.doc().unwrap().layers_open.contains(layer) && !s.doc().unwrap().layers_open.contains(g));
let native = path(&d, "rows.vectorcraft");
s.execute("document.save", &json!({"path": native})).unwrap();
let bytes = std::fs::read(&native).unwrap();
assert_eq!(vectorcraft_format::load(&bytes).unwrap().layers_open, None);
// Opening the group and closing the layer is view state: not an edit, kept by the file.
let st = s.doc_mut().unwrap();
st.layers_open.set(g, true);
st.layers_open.set(layer, false);
assert!(!s.doc().unwrap().is_dirty());
s.execute("document.save", &json!({"path": native})).unwrap();
assert_eq!(s.doc().unwrap().doc.layers_open, None, "only the written file carries it");
let mut again = session();
again.execute("document.open", &json!({"path": native})).unwrap();
let open = &again.doc().unwrap().layers_open;
assert!(open.contains(g) && !open.contains(layer));
// Older files (none saved) open with the top-level layers open.
let doc = vectorcraft_format::load(&vectorcraft_format::save(&vectorcraft_doc::Document::new(5.0, 5.0), false)).unwrap();
assert_eq!(doc.layers_open, None);
let _ = std::fs::remove_dir_all(d);
}
#[test]
fn save_plans_suggest_names_and_folders() {
let mut s = session();
+68
View File
@@ -197,6 +197,74 @@ fn another_documents_swatches_load_as_a_library() {
assert!(s.execute("swatch.library.load", &json!({"data": "hello", "name": "x.txt"})).is_err());
}
#[test]
fn swatch_exchange_files_load_add_and_list_as_user_libraries() {
let bytes = vectorcraft_testkit::ase::sample();
let mut s = session();
let r = run(&mut s, "swatch.library.load", json!({"dataBase64": vectorcraft_format::base64_encode(&bytes), "name": "Brand.ase"}));
assert_eq!((r["library"].as_str(), r["name"].as_str(), r["count"].as_u64()), (Some("loaded/Brand.ase"), Some("Brand"), Some(4)));
let g = run(&mut s, "swatch.library.get", json!({"library": r["library"]}));
let swatches = g["swatches"].as_array().unwrap();
let kinds: Vec<(&str, bool, bool)> =
swatches.iter().map(|w| (w["name"].as_str().unwrap(), w["global"].as_bool().unwrap(), w["spot"].as_bool().unwrap())).collect();
assert_eq!(kinds, [("Sky", true, false), ("Ink", true, true), ("Mist", false, false), ("Clay", false, false)]);
assert_eq!(swatches[3]["color"], json!({"model": "lab", "l": 50.0, "a": 20.0, "b": -30.0}));
// Added to the document, the spot color stays a spot color and the group stays a color group.
run(&mut s, "swatch.library.add", json!({"library": r["library"]}));
let d = doc(&s);
assert!(d.swatch("Ink").is_some_and(|w| w.spot && w.global));
assert_eq!(d.swatch_groups.iter().find(|g| g.name == "Neutrals").map(|g| g.swatches.len()), Some(2));
// A damaged file is an error from the swatch exchange reader, not from the document loader.
let cut = vectorcraft_format::base64_encode(&bytes[..bytes.len() - 1]);
let e = s.execute("swatch.library.load", &json!({"dataBase64": cut, "name": "Cut.ase"})).unwrap_err().to_string();
assert!(e.contains("cut short"), "{e}");
// `.ase` files in the user library folder are User Defined libraries.
let dir = temp_dir("ase");
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("Brand.ase"), &bytes).unwrap();
s.swatch_libraries.set_user_dir(Some(dir.to_string_lossy().to_string()));
let list = run(&mut s, "swatch.library.list", json!({}));
let user: Vec<(&str, u64)> = list["libraries"]
.as_array()
.unwrap()
.iter()
.filter(|l| l["category"] == "user")
.map(|l| (l["id"].as_str().unwrap(), l["count"].as_u64().unwrap()))
.collect();
assert_eq!(user, [("user/Brand.ase", 4)]);
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn a_library_group_stays_one_group_when_a_swatch_has_its_name() {
use vectorcraft_testkit::ase::{Block, ase};
let mut s = session();
assert!(doc(&s).swatch("Blue").is_some(), "a new document has a swatch named Blue");
let bytes = ase(&[
Block::GroupStart("Blue"),
Block::Color("Deep", b"RGB ", &[0.0, 0.0, 0.4], 2),
Block::Color("Pale", b"RGB ", &[0.6, 0.7, 1.0], 2),
Block::GroupEnd,
Block::GroupStart("Blue 2"),
Block::Color("Frost", b"RGB ", &[0.9, 0.95, 1.0], 2),
Block::GroupEnd,
]);
let r = run(&mut s, "swatch.library.load", json!({"dataBase64": vectorcraft_format::base64_encode(&bytes), "name": "Blues.ase"}));
run(&mut s, "swatch.library.add", json!({"library": r["library"]}));
let groups: Vec<(&str, Vec<&str>)> =
doc(&s).swatch_groups.iter().map(|g| (g.name.as_str(), g.swatches.iter().map(|w| w.name.as_str()).collect())).collect();
assert!(groups.contains(&("Blue 2", vec!["Deep", "Pale"])), "{groups:?}");
assert!(groups.contains(&("Blue 2 2", vec!["Frost"])), "the library's own Blue 2 stays apart: {groups:?}");
}
#[test]
fn text_libraries_sent_as_bytes_load_when_they_are_not_valid_utf8() {
let mut s = session();
let latin1 = vectorcraft_format::base64_encode(b"GIMP Palette\n237 28 36 Rouge fonc\xe9\n");
let r = run(&mut s, "swatch.library.load", json!({"dataBase64": latin1, "name": "Rouge.gpl"}));
assert_eq!(r["count"], 1);
}
#[test]
fn gradient_libraries_are_listed_and_gradient_swatches_rename_and_take_new_gradients() {
let mut s = session();
+310
View File
@@ -0,0 +1,310 @@
//! The text engine's newer features combined through commands: Auto Size and Shrink Text to Fit
//! with inline graphics, per-paragraph attributes, the paragraph composer and vertical
//! alignment; editing and undo across them; and a save round trip with all of them on.
//! (`vectorcraft_text`'s `tests_combos` covers the layout side.)
use serde_json::{Value, json};
use vectorcraft_doc::text::INLINE_CHAR;
use vectorcraft_doc::{AreaFit, Composer, Justify, NodeKind, TextKind, TextObject, VerticalAlign};
use vectorcraft_geom::Rect;
use super::*;
const STORY: &str = "The quick brown fox jumps over the lazy dog. A second sentence follows the first one here. Then a third one ends it.";
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
s
}
/// A symbol `name`: a circle `d` points across, its instance deleted.
fn circle_symbol(s: &mut Session, name: &str, d: f64) {
s.execute("shape.ellipse", &json!({"x": 600, "y": 500, "width": d, "height": d})).unwrap();
s.execute("symbol.new", &json!({"name": name})).unwrap();
s.execute("edit.clear", &json!({})).unwrap();
}
/// Area type at (40, 40), `w` × `h`, size 12, with `extra` area options; selected.
fn area(s: &mut Session, w: f64, h: f64, text: &str, extra: Value) -> NodeId {
let mut a = json!({"width": w, "height": h});
if let (Some(a), Some(e)) = (a.as_object_mut(), extra.as_object()) {
a.extend(e.clone());
}
let id = NodeId(s.execute("text.create", &json!({"x": 40, "y": 40, "size": 12, "area": a, "text": text})).unwrap()["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
id
}
fn text(s: &Session, id: NodeId) -> TextObject {
match &s.doc().unwrap().doc.node(id).unwrap().kind {
NodeKind::Text(t) => (**t).clone(),
k => panic!("not text: {k:?}"),
}
}
fn frame(s: &Session, id: NodeId) -> Rect {
match text(s, id).kind {
TextKind::Area { frame } => frame.bounds().unwrap(),
k => panic!("not area type: {k:?}"),
}
}
fn lay(t: &TextObject) -> vectorcraft_text::TextLayout {
vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t)
}
/// Auto Size's frame is tight: the text fits, and a point less overflows.
fn assert_tight(s: &Session, id: NodeId, what: &str) {
let t = text(s, id);
assert!(!lay(&t).overflow, "{what}: the frame holds the text");
let b = frame(s, id);
let mut less = t.clone();
less.area.fit = AreaFit::None;
less.kind = TextKind::Area {
frame: vectorcraft_geom::PathData::from_bezpath(&vectorcraft_geom::Shape::to_path(&Rect::new(b.x0, b.y0, b.x1, b.y1 - 1.0), 0.1)),
};
assert!(lay(&less).overflow, "{what}: a point less overflows ({b:?})");
}
fn undo(s: &mut Session) {
s.execute("edit.undo", &json!({})).unwrap();
}
fn redo(s: &mut Session) {
s.execute("edit.redo", &json!({})).unwrap();
}
fn query(s: &mut Session) -> Value {
s.execute("text.areaOptions", &json!({})).unwrap()
}
#[test]
fn auto_height_x_inline_graphics() {
let mut s = session();
circle_symbol(&mut s, "Tap", 10.0);
let id = area(&mut s, 200.0, 300.0, "Tap: add one mana.", json!({"fit": "autoHeight"}));
let one = frame(&s, id);
assert_tight(&s, id, "one line");
// Art taller than the line makes the line, and so the frame, taller: in the same undo step.
let n = s.doc().unwrap().history.undo.len();
s.execute("text.insertInline", &json!({"id": id.0, "at": 0, "symbol": "Tap", "scale": 3})).unwrap();
assert_eq!(s.doc().unwrap().history.undo.len(), n + 1);
let tall = frame(&s, id);
assert!(tall.height() > one.height() + 5.0, "{one:?} → {tall:?}");
assert_tight(&s, id, "tall art");
// Enough art to wrap: another line.
for _ in 0..12 {
s.execute("text.insertInline", &json!({"id": id.0, "at": 0, "symbol": "Tap", "scale": 1})).unwrap();
}
assert!(lay(&text(&s, id)).lines.len() > 1);
assert_tight(&s, id, "wrapped art");
// Deleting the art shrinks it back; undo restores each step exactly.
let wrapped = frame(&s, id);
let all = text(&s, id).plain_text().rfind(INLINE_CHAR).unwrap() + INLINE_CHAR.len_utf8();
s.execute("text.editRange", &json!({"id": id.0, "start": 0, "end": all})).unwrap();
assert_eq!(text(&s, id).plain_text(), "Tap: add one mana.");
assert_eq!(frame(&s, id), one);
undo(&mut s);
assert_eq!(frame(&s, id), wrapped);
for _ in 0..13 {
undo(&mut s);
}
assert_eq!(frame(&s, id), one);
redo(&mut s);
assert_eq!(frame(&s, id), tall);
}
#[test]
fn auto_height_x_paragraph_attrs() {
let mut s = session();
let id = area(&mut s, 200.0, 300.0, "One\nTwo", json!({"fit": "autoHeight"}));
let h0 = frame(&s, id).height();
// Space before on the second paragraph only: the frame grows by exactly that.
s.execute("text.setFormat", &json!({"ids": [id.0], "spaceBefore": 30, "start": 4, "end": 4})).unwrap();
let t = text(&s, id);
assert_eq!((t.para_at(0).space_before, t.para_at(1).space_before), (0.0, 30.0));
let h1 = frame(&s, id).height();
assert!((h1 - h0 - 30.0).abs() < 1e-6, "{h0} → {h1}");
assert_tight(&s, id, "space before");
// Return in the spaced paragraph: the new one inherits the spacing, the frame follows.
s.execute("text.editRange", &json!({"id": id.0, "start": 7, "end": 7, "insert": "\nThree"})).unwrap();
let t = text(&s, id);
assert_eq!(t.paragraph_styles().iter().map(|p| p.space_before).collect::<Vec<_>>(), [0.0, 30.0, 30.0]);
assert!(frame(&s, id).height() > h1 + 30.0);
assert_tight(&s, id, "three paragraphs");
// Merging paragraphs: the first one's attributes win, the frame shrinks.
s.execute("text.editRange", &json!({"id": id.0, "start": 3, "end": 4})).unwrap();
let t = text(&s, id);
assert_eq!(t.paragraph_styles().iter().map(|p| p.space_before).collect::<Vec<_>>(), [0.0, 30.0]);
assert_tight(&s, id, "merged");
undo(&mut s);
undo(&mut s);
assert!((frame(&s, id).height() - h1).abs() < 1e-9);
undo(&mut s);
assert!((frame(&s, id).height() - h0).abs() < 1e-9);
assert!(text(&s, id).paras.is_empty(), "back to one style for all");
}
#[test]
fn auto_height_x_composer() {
// Switching the composer of one paragraph rebreaks it; Auto Size follows either way.
let mut s = session();
let story = format!("{STORY} {STORY}\n{STORY}");
let id = area(&mut s, 130.0, 100.0, &story, json!({"fit": "autoHeight"}));
assert_tight(&s, id, "every-line");
for composer in ["singleLine", "everyLine", "singleLine"] {
s.execute("text.setFormat", &json!({"ids": [id.0], "composer": composer, "start": 0, "end": 0})).unwrap();
let t = text(&s, id);
assert_eq!(t.para_at(1).composer, Composer::EveryLine, "the second paragraph keeps its own");
assert_tight(&s, id, composer);
}
s.execute("text.setFormat", &json!({"ids": [id.0], "composer": "singleLine"})).unwrap();
s.execute("text.setStyle", &json!({"id": id.0, "justify": "justifyAll"})).unwrap();
assert!(text(&s, id).paragraph_styles().iter().all(|p| p.composer == Composer::SingleLine && p.justify == Justify::JustifyAll));
assert_tight(&s, id, "justified");
}
#[test]
fn auto_height_x_vertical_align() {
// An Auto Size frame has no space to spare: every alignment sets the lines as Top does, and
// the frame is as tall as with Top.
let mut s = session();
let id = area(&mut s, 160.0, 100.0, STORY, json!({"fit": "autoHeight"}));
let top_frame = frame(&s, id);
let top = lay(&text(&s, id));
for a in ["center", "bottom", "justify"] {
s.execute("text.areaOptions", &json!({"verticalAlign": a})).unwrap();
assert_eq!(frame(&s, id), top_frame, "{a}");
let l = lay(&text(&s, id));
for (li, l0) in l.lines.iter().zip(&top.lines) {
assert!((li.baseline - l0.baseline).abs() < 1e-6, "{a}: {} vs {}", li.baseline, l0.baseline);
}
assert_tight(&s, id, a);
}
// Editing with the alignment on keeps the frame tight.
s.execute("text.editRange", &json!({"id": id.0, "start": 0, "end": 0, "insert": format!("{STORY} ")})).unwrap();
assert_eq!(text(&s, id).area.vertical_align, VerticalAlign::Justify);
assert_tight(&s, id, "longer, justified");
}
#[test]
fn shrink_text_x_inline_graphics_and_paragraphs() {
let mut s = session();
circle_symbol(&mut s, "Dot", 8.0);
let id = area(&mut s, 160.0, 60.0, "Short rules.\nFlavor.", json!({"fit": "shrinkText", "fitMinPercent": 20}));
assert_eq!(query(&mut s)["fitScale"], 1.0);
// Inline art and per-paragraph spacing push it over; shrinking makes it fit.
s.execute("text.setFormat", &json!({"ids": [id.0], "spaceBefore": 12, "start": 13, "end": 13})).unwrap();
for i in 0..10 {
s.execute("text.insertInline", &json!({"id": id.0, "at": 0, "symbol": "Dot", "scale": 1.0 + i as f64 * 0.2})).unwrap();
s.execute("text.editRange", &json!({"id": id.0, "start": 0, "end": 0, "insert": "Add "})).unwrap();
}
let q = query(&mut s);
assert_eq!(q["overflow"], false, "{q}");
let f = q["fitScale"].as_f64().unwrap();
assert!((0.2..1.0).contains(&f), "{f}");
let t = text(&s, id);
assert_eq!(t.paragraph_count(), 2);
assert_eq!(t.para_at(1).space_before, 12.0, "inserting in the first paragraph keeps the second's attributes");
assert_eq!(t.runs[0].style.size, 12.0, "the stored size stays");
let l = lay(&t);
assert_eq!(l.inlines.len(), 10);
assert!(l.inlines.iter().all(|i| i.bounds.height() < 12.0 * 2.8 * f + 1e-6));
// Undo walks the fit back up.
for _ in 0..20 {
undo(&mut s);
}
assert_eq!(query(&mut s)["fitScale"], 1.0);
}
#[test]
fn paragraph_attrs_x_inline_editing() {
// An inline graphic opening a paragraph belongs to it: inserting it keeps the paragraph's
// attributes, deleting it with the paragraph break merges into the paragraph before.
let mut s = session();
circle_symbol(&mut s, "Tap", 10.0);
let id = area(&mut s, 300.0, 200.0, "Rules\nFlavor", json!({}));
s.execute("text.setStyle", &json!({"id": id.0, "justify": "center", "start": 6, "end": 6})).unwrap();
s.execute("text.setFormat", &json!({"ids": [id.0], "composer": "singleLine", "start": 6, "end": 6})).unwrap();
s.execute("text.insertInline", &json!({"id": id.0, "at": 6, "symbol": "Tap"})).unwrap();
let t = text(&s, id);
assert_eq!(t.plain_text(), format!("Rules\n{INLINE_CHAR}Flavor"));
assert_eq!((t.para_at(0).justify, t.para_at(1).justify), (Justify::Auto, Justify::Center));
assert_eq!(t.para_at(1).composer, Composer::SingleLine);
// The art's line is centred.
let l = lay(&t);
let g = &l.glyphs[l.inlines[0].glyph];
let line = &l.lines[g.line];
assert!(((line.x0 + line.x1) * 0.5 - 150.0).abs() < 1e-6, "centred in the 300 pt frame: {line:?}");
assert!((l.inlines[0].bounds.x0 - g.origin.x).abs() < 1e-6);
// Return just before the art: the new paragraph (holding the art) continues the centred one.
s.execute("text.editRange", &json!({"id": id.0, "start": 6, "end": 6, "insert": "Text\n"})).unwrap();
let t = text(&s, id);
assert_eq!(t.paragraph_styles().iter().map(|p| p.justify).collect::<Vec<_>>(), [Justify::Auto, Justify::Center, Justify::Center]);
undo(&mut s);
// Delete the break and the art together: one paragraph, the first one's attributes.
let end = 6 + INLINE_CHAR.len_utf8();
s.execute("text.editRange", &json!({"id": id.0, "start": 5, "end": end})).unwrap();
let t = text(&s, id);
assert_eq!(t.plain_text(), "RulesFlavor");
assert!(t.paras.is_empty() && t.para.justify == Justify::Auto && t.para.composer == Composer::EveryLine);
assert!(t.runs.iter().all(|r| r.inline.is_none()));
undo(&mut s);
let t = text(&s, id);
assert_eq!(t.plain_text(), format!("Rules\n{INLINE_CHAR}Flavor"));
assert_eq!(t.para_at(1).justify, Justify::Center);
assert_eq!(t.runs.iter().filter(|r| r.inline.is_some()).count(), 1);
}
#[test]
fn vertical_align_x_inline_graphics_in_the_document() {
// The art the renderer draws (the layout's inline placements) moves with centred lines.
let mut s = session();
circle_symbol(&mut s, "Tap", 10.0);
let id = area(&mut s, 300.0, 200.0, "Add one mana.", json!({}));
s.execute("text.insertInline", &json!({"id": id.0, "at": 0, "symbol": "Tap"})).unwrap();
let top = lay(&text(&s, id));
s.execute("text.areaOptions", &json!({"verticalAlign": "center"})).unwrap();
let l = lay(&text(&s, id));
let d = l.lines[0].baseline - top.lines[0].baseline;
assert!(d > 50.0, "{d}");
assert!((l.inlines[0].bounds.y0 - top.inlines[0].bounds.y0 - d).abs() < 1e-6, "{:?} vs {:?}", l.inlines[0].bounds, top.inlines[0].bounds);
// The cached bounds (hit testing, selection) include the moved art.
let cached = text(&s, id).cached_bounds.unwrap();
assert!(cached.contains(l.inlines[0].bounds.center()), "{cached:?}");
}
#[test]
fn every_feature_saves_and_reopens() {
let mut s = session();
circle_symbol(&mut s, "Tap", 10.0);
let id = area(
&mut s,
220.0,
70.0,
&format!(": Add one mana of any color. {STORY}\n{STORY}"),
json!({"verticalAlign": "center", "fit": "shrinkText", "fitMinPercent": 30}),
);
s.execute("text.insertInline", &json!({"id": id.0, "at": 0, "symbol": "Tap", "scale": 0.8, "shift": 0.5})).unwrap();
let flavor = text(&s, id).plain_text().find('\n').unwrap() + 1;
s.execute("text.setFormat", &json!({"ids": [id.0], "spaceBefore": 8, "composer": "singleLine", "start": flavor, "end": flavor})).unwrap();
s.execute("text.setStyle", &json!({"id": id.0, "justify": "justifyAll", "start": flavor, "end": flavor})).unwrap();
s.execute("text.setStyle", &json!({"id": id.0, "tracking": 20})).unwrap();
let t = text(&s, id);
let l = lay(&t);
assert!(!l.overflow && l.fit_scale < 1.0, "{}", l.fit_scale);
assert_eq!(l.inlines.len(), 1);
let doc = s.doc().unwrap().doc.clone();
let back = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap();
let NodeKind::Text(t2) = &back.node(id).unwrap().kind else { panic!("not text") };
let mut t2 = (**t2).clone();
// Resolved art bounds and layout caches aren't saved: resolve them as opening does.
back.resolve_text_inline(&mut t2);
assert_eq!(t2.runs, t.runs);
assert_eq!(t2.paragraph_styles(), t.paragraph_styles());
assert_eq!(t2.area, t.area);
let l2 = lay(&t2);
assert_eq!((l2.fit_scale, l2.lines.len()), (l.fit_scale, l.lines.len()));
assert_eq!(l2.inlines.iter().map(|i| i.bounds).collect::<Vec<_>>(), l.inlines.iter().map(|i| i.bounds).collect::<Vec<_>>());
}
+5 -2
View File
@@ -247,10 +247,13 @@ fn artboard_tool_moves_with_art_creates_and_deletes() {
assert_eq!(s.doc().unwrap().doc.artboards.len(), 2);
assert_eq!(s.tool_options()["active"], 1);
assert_eq!(s.doc().unwrap().doc.artboards[1].rect, Rect::new(1000.0, 0.0, 1200.0, 100.0));
// Delete it.
// Delete it: the tool takes the key ahead of the Clear shortcut (the UI only hands Delete to a
// tool that claims it).
assert!(s.tool_claims_key(ToolKey::Delete, ViewInfo::default()));
s.tool_key(ToolKey::Delete, Mods::default(), ViewInfo::default()).unwrap();
assert_eq!(s.doc().unwrap().doc.artboards.len(), 1);
// The last artboard can't be deleted.
// The last artboard can't be deleted, so Delete stays the shortcut's.
assert!(!s.tool_claims_key(ToolKey::Delete, ViewInfo::default()));
s.tool_key(ToolKey::Delete, Mods::default(), ViewInfo::default()).unwrap();
assert_eq!(s.doc().unwrap().doc.artboards.len(), 1);
}
+82 -17
View File
@@ -1,5 +1,5 @@
//! Untrusted files never crash the app: garbage, truncated, mutated and hostile SVG, PDF and DXF input,
//! mutated raster images placed with File → Place, and swatch (`.vcswatches`, `.gpl`), graphic style (`.vcstyles`) and flattener preset
//! mutated raster images placed with File → Place, and swatch (`.vcswatches`, `.gpl`, `.ase`), graphic style (`.vcstyles`) and flattener preset
//! (`.vcflattener`) libraries, and native files (compressed, damaged, saved for older versions),
//! must load as an error or as a document that then renders and exports, without a panic; nor may
//! bitmaps, PDF and text pasted from other apps, nor EMF and WMF pictures (damaged files, records
@@ -529,12 +529,21 @@ fn saved(cmd: &str, params: Value) -> String {
rich_session().execute(cmd, &params).unwrap()["data"].as_str().unwrap().to_string()
}
/// `r`, after failing the case if the command panicked. The engine's guard reports a panic as
/// `EngineError::Internal`.
fn no_panic(r: Result<Value, vectorcraft_engine::EngineError>) -> Result<Value, vectorcraft_engine::EngineError> {
if let Err(vectorcraft_engine::EngineError::Internal { cmd, msg }) = &r {
panic!("{cmd} panicked: {msg}");
}
r
}
/// Library file `data` loaded with `load`; what it holds is then used on the rich document
/// (`then`, given the load's result), which renders and exports.
fn survive_library(what: &str, load: &str, data: &str, then: impl FnOnce(&mut vectorcraft_engine::Session, &Value)) -> Result<(), TestCaseError> {
survive(what, || {
let mut s = rich_session();
let r = s.execute(load, &json!({"data": data, "name": "fuzz"})).ok()?;
let r = no_panic(s.execute(load, &json!({"data": data, "name": "fuzz"}))).ok()?;
then(&mut s, &r);
Some((*s.doc().ok()?.doc).clone())
})
@@ -542,27 +551,55 @@ fn survive_library(what: &str, load: &str, data: &str, then: impl FnOnce(&mut ve
fn swatches(what: &str, data: &str) -> Result<(), TestCaseError> {
survive_library(what, "swatch.library.load", data, |s, r| {
let _ = s.execute("swatch.library.add", &json!({"library": r["library"], "apply": "fill"}));
let _ = no_panic(s.execute("swatch.library.add", &json!({"library": r["library"], "apply": "fill"})));
})
}
fn styles(what: &str, data: &str) -> Result<(), TestCaseError> {
survive_library(what, "graphicStyle.loadLibrary", data, |s, r| {
let _ = s.execute("select.all", &json!({}));
let _ = s.execute("graphicStyle.addFromLibrary", &json!({"library": r["library"], "apply": true}));
let _ = no_panic(s.execute("select.all", &json!({})));
let _ = no_panic(s.execute("graphicStyle.addFromLibrary", &json!({"library": r["library"], "apply": true})));
})
}
fn flattener_presets(what: &str, data: &str) -> Result<(), TestCaseError> {
survive_library(what, "flattener.presets.import", data, |s, r| {
let _ = s.execute("select.all", &json!({}));
let _ = no_panic(s.execute("select.all", &json!({})));
if let Some(name) = r["imported"].get(0) {
let _ = s.execute("flattener.preview", &json!({"preset": name, "highlight": "allAffected"}));
let _ = s.execute("object.flattenTransparency", &json!({"preset": name, "lineArtPpi": 36, "gradientPpi": 36}));
let _ = no_panic(s.execute("flattener.preview", &json!({"preset": name, "highlight": "allAffected"})));
let _ = no_panic(s.execute("object.flattenTransparency", &json!({"preset": name, "lineArtPpi": 36, "gradientPpi": 36})));
}
})
}
/// Swatch exchange (`.ase`) bytes loaded as a swatch library, then added to the rich document.
fn swatch_exchange(what: &str, bytes: &[u8]) -> Result<(), TestCaseError> {
survive(what, || {
let mut s = rich_session();
let load = json!({"dataBase64": vectorcraft_format::base64_encode(bytes), "name": "fuzz.ase"});
let r = no_panic(s.execute("swatch.library.load", &load)).ok()?;
let _ = no_panic(s.execute("swatch.library.add", &json!({"library": r["library"], "apply": "fill"})));
Some((*s.doc().ok()?.doc).clone())
})
}
/// A random swatch exchange block (type, body). The body holds a name, a color model when the block
/// is a color, and random bytes for the rest.
fn arb_ase_block() -> impl Strategy<Value = (u16, Vec<u8>)> {
let kind = prop::sample::select(vec![0xC001u16, 0xC002, 0x0001, 0x0042]);
let model = prop::sample::select(vec![*b"RGB ", *b"CMYK", *b"LAB ", *b"Gray", *b"HSB "]);
(kind, "[ -~]{0,8}", model, prop::collection::vec(any::<u8>(), 0..24)).prop_map(|(kind, name, model, rest)| {
let units: Vec<u16> = name.encode_utf16().chain([0]).collect();
let mut body = (units.len() as u16).to_be_bytes().to_vec();
body.extend(units.iter().flat_map(|u| u.to_be_bytes()));
if kind == 0x0001 {
body.extend(model);
}
body.extend(rest);
(kind, body)
})
}
/// Characters that break JSON and GPL palettes.
fn arb_edit() -> impl Strategy<Value = (usize, char)> {
(0usize..20_000, prop::sample::select(vec!['{', '}', '[', ']', '"', ':', ',', '-', '9', 'e', '.', ' ', '\n', '#', 'n', 'x', '\t']))
@@ -596,6 +633,32 @@ proptest! {
let text = saved("flattener.presets.export", json!({"names": ["high", "medium", "low"]}));
flattener_presets("mutated flattener presets", &mutate_text(&text, cut, &edits))?;
}
#[test]
fn swatch_exchange_garbage_never_panics(blocks in prop::collection::vec(arb_ase_block(), 0..12), tail in prop::collection::vec(any::<u8>(), 0..16)) {
let mut bytes = b"ASEF\0\x01\0\0".to_vec();
bytes.extend((blocks.len() as u32).to_be_bytes());
for (kind, body) in &blocks {
bytes.extend(kind.to_be_bytes());
bytes.extend((body.len() as u32).to_be_bytes());
bytes.extend(body);
}
bytes.extend(tail);
swatch_exchange("swatch exchange garbage", &bytes)?;
}
#[test]
fn mutated_swatch_exchange_files_never_panic(cut in prop::option::of(0usize..200), edits in prop::collection::vec((0usize..200, any::<u8>()), 0..12)) {
let mut bytes = vectorcraft_testkit::ase::sample();
for (at, b) in edits {
let n = bytes.len();
bytes[at % n] = b;
}
if let Some(cut) = cut {
bytes.truncate(cut);
}
swatch_exchange("mutated swatch exchange file", &bytes)?;
}
}
/// A small image of each raster format Place reads, with resolution metadata where it has some.
@@ -704,8 +767,8 @@ proptest! {
fn pdf_presets(what: &str, data: &str) -> Result<(), TestCaseError> {
survive_library(what, "pdf.preset.import", data, |s, r| {
for name in r["imported"].as_array().into_iter().flatten() {
let _ = s.execute("document.exportPdf", &json!({"preset": name}));
let _ = s.execute("document.save", &json!({"format": "ai", "preset": name}));
let _ = no_panic(s.execute("document.exportPdf", &json!({"preset": name})));
let _ = no_panic(s.execute("document.save", &json!({"format": "ai", "preset": name})));
}
})
}
@@ -1219,14 +1282,14 @@ proptest! {
/// each one imported.
fn print_presets(what: &str, data: &str) -> Result<(), TestCaseError> {
survive_library(what, "print.presets.import", data, |s, r| {
let list = s.execute("print.presets.list", &json!({})).unwrap_or_default();
let list = no_panic(s.execute("print.presets.list", &json!({}))).unwrap_or_default();
for name in r["imported"].as_array().into_iter().flatten() {
let Some(p) = list["presets"].as_array().into_iter().flatten().find(|p| &p["name"] == name) else { continue };
let settings = json!({ "settings": p["settings"] });
let pages = s.execute("print.preview", &settings).ok().and_then(|v| v["pages"].as_u64());
let _ = s.execute("print.setup", &settings);
let pages = no_panic(s.execute("print.preview", &settings)).ok().and_then(|v| v["pages"].as_u64());
let _ = no_panic(s.execute("print.setup", &settings));
if pages.is_some_and(|n| n <= 8) {
let _ = s.execute("file.print", &settings);
let _ = no_panic(s.execute("file.print", &settings));
}
}
})
@@ -1256,9 +1319,11 @@ proptest! {
fn perspective_presets(what: &str, data: &str) -> Result<(), TestCaseError> {
survive_library(what, "perspective.presets.import", data, |s, r| {
for name in r["imported"].as_array().into_iter().flatten() {
let _ = s.execute("perspective.grid.preset", &json!({"name": name}));
let _ = s.execute("perspective.grid.define", &json!({"name": name, "gridline": 3}));
let _ = s.execute("perspective.draw", &json!({"command": "shape.rectangle", "params": {"x": 300, "y": 400, "width": 40, "height": 30}}));
let _ = no_panic(s.execute("perspective.grid.preset", &json!({"name": name})));
let _ = no_panic(s.execute("perspective.grid.define", &json!({"name": name, "gridline": 3})));
let _ = no_panic(
s.execute("perspective.draw", &json!({"command": "shape.rectangle", "params": {"x": 300, "y": 400, "width": 40, "height": 30}})),
);
}
})
}
+8 -3
View File
@@ -295,10 +295,15 @@ with the {effect} effect.
Method:
1. open_file the image: it becomes a document of its own pixel size.
2. imageTrace.make with the preset name, adjusting `params` — mode blackAndWhite, grayscale or
color, then threshold, colors, paths, corners, noise, method abutting or overlapping,
ignoreWhite, snapCurvesToLines. Run imageTrace.presets to see every preset with its numbers.
color (palette limited, fullTone for photos, automatic, or documentLibrary to trace with
the document's swatches or a swatch `library`), then threshold, colors (colorDetail for
fullTone and automatic), paths, corners, noise, method abutting or overlapping,
ignoreWhite, snapCurvesToLines; for line art, strokes: true (with strokeWidth, the widest
line in pixels) traces lines as stroked centre lines instead of filled outlines. Run
imageTrace.presets to see every preset with its numbers.
Lower paths and higher corners give the clean, logo-like result; high fidelity needs paths
near 90.
near 90. imageTrace.setView {view: \"outlinesWithSourceImage\"} draws the traced outlines
over the image on screen to compare them (screenshots show it; exports keep the result).
3. apply_effect {effect} on the traced shapes. Call apply_effect with no `effect` for the
catalogue and each effect's parameters.
4. set_paint over the traced shapes to give the artwork its own colours.
+37 -3
View File
@@ -21,7 +21,7 @@ pub mod proof;
use std::collections::HashMap;
use std::sync::Arc;
use vectorcraft_doc::{AppearanceItem, Document, Node, NodeId, NodeKind, StrokeAlign, StrokeLayer, TextObject};
use vectorcraft_doc::{AppearanceItem, Document, Node, NodeId, NodeKind, StrokeAlign, StrokeLayer, TextObject, TraceView};
use vectorcraft_geom::{Affine, BezPath, FillRule, Rect, Shape};
use vello_cpu::kurbo;
use vello_cpu::peniko::{self, BlendMode, Compose, Mix};
@@ -100,6 +100,12 @@ pub struct RenderOptions {
/// 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,
/// Screen view: Image Trace objects draw as their View asks (outlines, the source image…);
/// off, they draw their tracing result, as exports and printing do.
pub trace_views: bool,
/// Images are sampled smoothly when scaled or rotated; off, each pixel takes its nearest image
/// pixel (Pixel Preview with File Handling › Display Bitmaps as Anti-aliased Images off).
pub smooth_images: bool,
}
/// How edges are rasterized (raster export option).
@@ -165,6 +171,8 @@ impl Default for RenderOptions {
highlight_substitutions: false,
anti_alias: AntiAlias::Art,
progressive_placed: false,
trace_views: false,
smooth_images: true,
}
}
}
@@ -646,8 +654,10 @@ impl Renderer {
let b = match &a.kind {
NodeKind::Layer { children, clip: false, .. } | NodeKind::Group { children, clip: false } if !fx::has_object_fx(a) => {
let mut acc: Option<Rect> = None;
// An Image Trace object's hidden source image shows in some of its views.
let source = a.trace.is_some().then(|| children.first()).flatten();
for c in children {
if c.visible {
if c.visible || source.is_some_and(|s| Arc::ptr_eq(s, c)) {
acc = vectorcraft_geom::union_opt(acc, self.bounds_of(c));
}
}
@@ -883,6 +893,9 @@ impl Renderer {
/// What `n` draws inside its transparency group (`knockout`: its children knock each other out).
fn draw_content(&mut self, ctx: &mut RenderContext, f: &Frame, n: &Node, knockout: bool) {
match &n.kind {
NodeKind::Group { children, clip: false } if f.opts.trace_views && !f.opts.outline && n.trace_view() != TraceView::Result => {
self.draw_trace_view(ctx, f, children, n.trace_view(), knockout)
}
NodeKind::Layer { children, clip: false, .. } | NodeKind::Group { children, clip: false } => {
self.draw_children(ctx, f, children, knockout)
}
@@ -955,6 +968,25 @@ impl Renderer {
}
}
/// An Image Trace object's `children` (the hidden source image, then the traced shapes) as
/// `view` shows them on screen.
fn draw_trace_view(&mut self, ctx: &mut RenderContext, f: &Frame, children: &[Arc<Node>], view: TraceView, knockout: bool) {
let Some((source, shapes)) = children.split_first() else { return };
if view.shows_source() && matches!(source.kind, NodeKind::Image(_)) {
self.draw_node(ctx, f, source, true);
}
if view.shows_result() {
self.draw_children(ctx, f, shapes, knockout);
}
if view.shows_outlines() {
let opts = RenderOptions { outline: true, ..f.opts.clone() };
let frame = Frame { opts: &opts, ..*f };
for c in shapes {
self.draw_node(ctx, &frame, c, false);
}
}
}
/// The children of a group: as the elements of a knockout group when `knockout`.
fn draw_children(&mut self, ctx: &mut RenderContext, f: &Frame, children: &[Arc<Node>], knockout: bool) {
if knockout {
@@ -1391,7 +1423,9 @@ impl Renderer {
let pm = if outline { pm } else { self.ink_image(&cache_key, &pm, f.ink, f.doc.images.get(&im.key)) };
let sx = im.width as f64 / pm.width().max(1) as f64;
let sy = im.height as f64 / pm.height().max(1) as f64;
ctx.set_paint(vello_cpu::Image { image: vello_cpu::ImageSource::Pixmap(pm), sampler: peniko::ImageSampler::default() });
let quality = if f.opts.smooth_images { peniko::ImageQuality::Medium } else { peniko::ImageQuality::Low };
let sampler = peniko::ImageSampler { quality, ..Default::default() };
ctx.set_paint(vello_cpu::Image { image: vello_cpu::ImageSource::Pixmap(pm), sampler });
match area {
Some((bp, rule)) => {
ctx.set_transform(f.view);
+23
View File
@@ -362,3 +362,26 @@ fn invalid_dash_pattern_strokes_solid() {
assert_eq!(img.pixels, solid.pixels, "dash {pattern:?}");
}
}
/// An image drawn larger than its pixels samples smoothly, or with `smooth_images` off each screen
/// pixel takes its nearest image pixel (Pixel Preview with File Handling › Display Bitmaps as
/// Anti-aliased Images off, #394).
#[test]
fn images_take_their_nearest_pixel_without_smoothing() {
use vectorcraft_doc::{ImageBlob, ImageObject, NodeKind};
let img = image::RgbaImage::from_fn(2, 1, |x, _| image::Rgba(if x == 0 { [0, 0, 0, 255] } else { [255, 255, 255, 255] }));
let mut png = vec![];
img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
let mut d = Document::new(40.0, 20.0);
d.images.insert("bw".into(), ImageBlob::new("image/png", png));
let id = d.alloc_id();
let im = ImageObject { key: "bw".into(), width: 2, height: 1, xf: Affine::scale(20.0), link: None, placement: Default::default() };
d.insert(Some(d.layers[0].id), 0, Node::new(id, NodeKind::Image(im))).unwrap();
// How many pixels across the image are neither black nor white.
let greys = |smooth_images| {
let r = Renderer::new().render(&d, 40, 20, Affine::IDENTITY, &RenderOptions { smooth_images, ..Default::default() });
(0..40).filter(|x| (16..240).contains(&r.pixel(*x, 10)[0])).count()
};
assert!(greys(true) >= 4, "smooth: a ramp from black to white");
assert_eq!(greys(false), 0, "nearest: black, then white");
}
+12 -2
View File
@@ -68,6 +68,7 @@ fn write(doc: &Document, opts: &ExportOptions, native: Option<&[u8]>, id_prefix:
symbol_nest: 0,
fonts: Vec::new(),
shared_images: HashMap::new(),
layer_nest: 0,
};
w.assign_name_ids();
// Page Isolated Blending / Page Knockout Group: the page content is one isolated group.
@@ -266,6 +267,8 @@ struct Writer<'a> {
/// Images written once in the defs and drawn with `<use>`, by key and size: the pieces an
/// envelope cuts a distorted image into share its pixels.
shared_images: HashMap<(String, u32, u32), String>,
/// Layers being written inside one another (more than one: a sublayer).
layer_nest: usize,
}
/// The characters type uses from one face, under one `@font-face` description: the family the
@@ -545,8 +548,8 @@ impl Writer<'_> {
}
/// ` id="…"` for a named object, plus ` data-name="…"` with the name itself when the id had to
/// differ from it (spaces, punctuation, duplicates, the unique prefix).
/// The id of `n`'s element (with its name when the id isn't it), then the object's own data
/// as `data-*` attributes.
/// The id of `n`'s element (with its name when the id isn't it), a sublayer's mark
/// ([`crate::import::SUBLAYER`]), then the object's own data as `data-*` attributes.
fn id_attr(&self, n: &Node) -> String {
if self.anonymous {
return String::new();
@@ -556,6 +559,10 @@ impl Writer<'_> {
(Some(id), _) => format!(" id=\"{}\"", xml_escape(id)),
(None, _) => String::new(),
};
// A sublayer is marked as one, so import makes it a sublayer again, not a group.
if !out.is_empty() && n.is_layer() && self.layer_nest > 1 {
out.push_str(&format!(" {}=\"sublayer\"", crate::import::SUBLAYER));
}
for (k, v) in n.attrs.as_deref().map_or(&[][..], |a| a.data.as_slice()) {
// Names as XML takes them; ours (`name`, `vc-…`) are written by the export itself.
let valid = k.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.')) && k != "name" && !k.starts_with("vc-");
@@ -1215,6 +1222,8 @@ impl Writer<'_> {
/// An object, inside `<a>` when it links to a URL (Attributes panel).
fn node(&mut self, n: &Node) {
let layer = usize::from(n.is_layer());
self.layer_nest += layer;
match n.url().filter(|_| n.visible && !self.anonymous) {
Some(url) => {
self.line(&format!("<a xlink:href=\"{}\">", xml_escape(url)));
@@ -1225,6 +1234,7 @@ impl Writer<'_> {
}
None => self.node_body(n),
}
self.layer_nest -= layer;
}
fn node_body(&mut self, n: &Node) {
+105 -21
View File
@@ -8,7 +8,7 @@ use std::sync::Arc;
use usvg::roxmltree;
use vectorcraft_color::{BlendMode, Color, Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop, Paint};
use vectorcraft_doc::{
Appearance, AppearanceItem, Dash, Document, FillLayer, ImageBlob, ImageObject, LayerColor, LineCap, LineJoin, Node, NodeKind, PatternDef,
Appearance, AppearanceItem, Dash, Document, FillLayer, ImageBlob, ImageObject, LayerColor, LineCap, LineJoin, Node, NodeId, NodeKind, PatternDef,
StrokeLayer, Unit,
};
use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, Vec2, shapes};
@@ -33,6 +33,7 @@ pub(crate) fn import(svg: &str, opts: &ImportOptions) -> Result<(Document, Vec<S
let xml = roxmltree::Document::parse_with_options(svg, roxmltree::ParsingOptions { allow_dtd: true, ..Default::default() })
.map_err(|e| SvgError::Parse(e.to_string()))?;
let units = RootUnits::of(xml.root_element());
let root_name = root_layer_name(xml.root_element());
let mut warnings = found.warnings;
let (src, slots) = text::prepare(svg, &xml, units.dpi, &mut warnings);
let files = found.files;
@@ -65,6 +66,8 @@ pub(crate) fn import(svg: &str, opts: &ImportOptions) -> Result<(Document, Vec<S
files,
non_scaling: found.non_scaling,
data: found.data,
sublayers: found.sublayers,
sublayer_groups: HashSet::new(),
screen: (kx * ky).sqrt(),
};
if im.files.nested_text() {
@@ -74,22 +77,32 @@ pub(crate) fn import(svg: &str, opts: &ImportOptions) -> Result<(Document, Vec<S
// usvg wraps everything in an id-less group carrying the viewBox transform when needed.
let mut top = tree.root();
let mut base = Affine::scale_non_uniform(kx, ky) * aff(top.transform());
if let [usvg::Node::Group(g)] = top.children()
&& g.id().is_empty()
&& is_plain(g)
&& im.text_slot(g).is_none()
{
if let Some(g) = im.wrapper(top) {
base *= aff(g.transform());
top = g;
}
// Top-level `<g id>` elements become layers (as in the reference app); otherwise all art goes
// into "Layer 1". A clip path on one (as on an Inkscape layer, or our clipping layers) makes it
// a clipping layer. Top-level text joins the layer below it (the first layer if none is).
// Top-level `<g id>` elements become layers (as in the reference app), named from their
// labels (`data-name`…) else their ids; otherwise all art goes into "Layer 1". A clip path on
// one (as on an Inkscape layer, or our clipping layers) makes it a clipping layer. Top-level
// text joins the layer below it (the first layer if none is).
let is_layer = |im: &Importer, c: &usvg::Node| matches!(c, usvg::Node::Group(g) if !g.id().is_empty() && !made_up(g.id()) && !im.links.contains_key(g.id()) && !im.uses.contains_key(g.id()) && only_clips(g) && im.text_slot(g).is_none());
let is_text = |im: &Importer, c: &usvg::Node| matches!(c, usvg::Node::Group(g) if im.text_slot(g).is_some());
let layer_mode = top.children().iter().any(|c| is_layer(&im, c)) && top.children().iter().all(|c| is_layer(&im, c) || is_text(&im, c));
if layer_mode {
let layer_mode = |im: &Importer, top: &usvg::Group| {
top.children().iter().any(|c| is_layer(im, c)) && top.children().iter().all(|c| is_layer(im, c) || is_text(im, c))
};
// The layers may sit in more wrappers (a transform on all the art, a `<switch>`'s group).
if !layer_mode(&im, top) {
let (mut inner, mut ts) = (top, base);
while let Some(g) = im.wrapper(inner) {
ts *= aff(g.transform());
inner = g;
}
if layer_mode(&im, inner) {
(top, base) = (inner, ts);
}
}
if layer_mode(&im, top) {
im.doc.layers.clear();
let mut loose = vec![];
for c in top.children() {
@@ -129,16 +142,68 @@ pub(crate) fn import(svg: &str, opts: &ImportOptions) -> Result<(Document, Vec<S
im.doc.layers.push(Arc::new(l));
}
} else {
// An export of a one-layer document names the layer on the root element, its art (groups
// among it) loose inside: the one layer takes that name.
let children = im.children(top, base);
if let Some(l) = im.doc.layers.first_mut()
&& let Some(ch) = Arc::make_mut(l).children_mut()
{
*ch = children;
if let Some(l) = im.doc.layers.first_mut() {
let l = Arc::make_mut(l);
if let Some(ch) = l.children_mut() {
*ch = children;
}
if root_name.is_some() {
l.name = root_name;
}
}
}
if !im.sublayer_groups.is_empty() {
for l in &mut im.doc.layers {
promote_sublayers(Arc::make_mut(l), &im.sublayer_groups);
}
}
Ok((im.doc, im.warnings))
}
/// What marks a nested `<g>` as a sublayer rather than a group: our export writes it on the layers
/// it writes inside layers. (Inkscape's `inkscape:groupmode="layer"` counts too.)
pub(crate) const SUBLAYER: &str = "data-vc-layer";
/// The Inkscape namespace (its layers and their labels).
const INKSCAPE: &str = "http://www.inkscape.org/namespaces/inkscape";
/// The layer name on root element `root` (`<svg id="Main">`, or its `data-name`), as exports of
/// one-layer documents write it. An Inkscape root's id (`svg8`) is one Inkscape made up, not a name.
fn root_layer_name(root: XNode) -> Option<String> {
let id = root.attribute("id").filter(|_| root.attribute((INKSCAPE, "version")).is_none());
root.attribute("data-name").or(id).map(str::trim).filter(|n| !n.is_empty()).map(str::to_string)
}
/// Is element `g` a `<g>` marked as a layer ([`SUBLAYER`])? Only one with an id counts: the id (or
/// the label beside it) is its name.
fn marked_layer(g: XNode) -> bool {
g.tag_name().name() == "g"
&& g.attribute("id").is_some_and(|id| !id.is_empty())
&& (g.has_attribute(SUBLAYER) || g.attribute((INKSCAPE, "groupmode")) == Some("layer"))
}
/// Turn the groups made of elements marked as layers (`marked`, see [`marked_layer`]) right inside
/// layer `l` into its sublayers, in its colour, and theirs in turn. A marked group anywhere else
/// (in a group, a mask, a symbol) stays a group: only layers hold layers.
fn promote_sublayers(l: &mut Node, marked: &HashSet<NodeId>) {
let NodeKind::Layer { color, children, .. } = &mut l.kind else { return };
let color = *color;
for c in children.iter_mut().filter(|c| marked.contains(&c.id)) {
let c = Arc::make_mut(c);
let NodeKind::Group { children, clip } = &mut c.kind else { continue };
let mut sub = Node::layer(c.id, "", color);
sub.set_clips(*clip);
if let Some(ch) = sub.children_mut() {
*ch = std::mem::take(children);
}
c.kind = sub.kind;
promote_sublayers(c, marked);
}
}
/// SVG's initial `font-size` (`medium`) in user units.
pub(super) const DEFAULT_FONT_SIZE: f64 = 12.0;
@@ -214,6 +279,10 @@ struct Importer {
non_scaling: HashSet<String>,
/// The `data-*` attributes of elements, by id ([`user_data`]).
data: HashMap<String, Vec<(String, String)>>,
/// Ids of the `<g>` elements marked as layers ([`marked_layer`]).
sublayers: HashSet<String>,
/// The groups made of them, made sublayers where they sit in a layer ([`promote_sublayers`]).
sublayer_groups: HashSet<NodeId>,
/// Points per screen pixel (the root's user unit before its `viewBox`): what a non-scaling
/// stroke's width is measured in.
screen: f64,
@@ -326,6 +395,8 @@ struct Found {
non_scaling: HashSet<String>,
/// The `data-*` attributes of elements, by id ([`user_data`]).
data: HashMap<String, Vec<(String, String)>>,
/// Ids of the `<g>` elements marked as layers ([`marked_layer`]).
sublayers: HashSet<String>,
warnings: Vec<String>,
}
@@ -396,7 +467,7 @@ impl Edits {
fn prepass<'s>(svg: &'s str, opts: &ImportOptions) -> (Cow<'s, str>, Found) {
let mut found = Found::default();
// (`:` for prefixed elements such as `<svg:image>`.)
if !["<a", "display", "<use", ":use", "<image", ":image", vector_effect::NON_SCALING, "data-"].iter().any(|t| svg.contains(t)) {
if !["<a", "display", "<use", ":use", "<image", ":image", vector_effect::NON_SCALING, "data-", "groupmode"].iter().any(|t| svg.contains(t)) {
return (svg.into(), found);
}
let Ok(xml) = roxmltree::Document::parse_with_options(svg, roxmltree::ParsingOptions { allow_dtd: true, ..Default::default() }) else {
@@ -417,6 +488,7 @@ fn prepass<'s>(svg: &'s str, opts: &ImportOptions) -> (Cow<'s, str>, Found) {
}
}
}
found.sublayers = elements().filter(|g| marked_layer(*g)).filter_map(|g| g.attribute("id")).map(str::to_string).collect();
let symbols: HashSet<&str> = elements().filter(|n| n.tag_name().name() == "symbol").filter_map(|n| n.attribute("id")).collect();
for u in elements().filter(|n| n.tag_name().name() == "use") {
if let Some(sym) = href(u).and_then(|h| h.strip_prefix('#')).filter(|s| symbols.contains(s)) {
@@ -440,19 +512,20 @@ fn prepass<'s>(svg: &'s str, opts: &ImportOptions) -> (Cow<'s, str>, Found) {
/// The elements that are objects (what [`hidden_objects`] shows).
const OBJECTS: &[&str] = &["g", "a", "path", "rect", "circle", "ellipse", "line", "polyline", "polygon", "image", "text", "use"];
/// Show the undisplayed objects outside `<defs>` (and the like) for usvg, recording their ids.
/// Show the undisplayed objects outside `<defs>` (and the like) for usvg, recording their ids. The
/// objects in a `<switch>` count too (some apps wrap all their layers in one).
fn hidden_objects(svg: &str, xml: &roxmltree::Document, css: &css::Styles, edits: &mut Edits, ids: &mut HashSet<String>) {
let linked: HashSet<&str> = xml.descendants().filter_map(href).filter_map(|h| h.strip_prefix('#')).collect();
let mut todo: Vec<XNode> = xml.root_element().children().filter(XNode::is_element).collect();
while let Some(n) = todo.pop() {
let tag = n.tag_name().name();
if !OBJECTS.contains(&tag) || n.attribute("id").is_some_and(|id| linked.contains(id)) {
if n.attribute("id").is_some_and(|id| linked.contains(id)) {
continue;
}
if matches!(tag, "g" | "a") {
if matches!(tag, "g" | "a" | "switch") {
todo.extend(n.children().filter(XNode::is_element));
}
if css.own(n, "display").as_deref() != Some("none") {
if !OBJECTS.contains(&tag) || css.own(n, "display").as_deref() != Some("none") {
continue;
}
ids.insert(edits.id(svg, n));
@@ -498,7 +571,6 @@ fn link(n: &mut Node, url: &str) {
/// The names apps keep beside element ids, by id: `data-name`, `inkscape:label`, `serif:id` or
/// `aria-label` (the first one present).
fn labels(xml: &roxmltree::Document) -> HashMap<String, String> {
const INKSCAPE: &str = "http://www.inkscape.org/namespaces/inkscape";
const SERIF: &str = "http://www.serif.com/";
xml.descendants()
.filter_map(|n| {
@@ -609,6 +681,15 @@ impl Importer {
}
}
/// The child of `g` when it's all `g` holds and only wraps art: an id-less group that leaves
/// it as it is (but for a transform) and isn't a text.
fn wrapper<'g>(&self, g: &'g usvg::Group) -> Option<&'g usvg::Group> {
match g.children() {
[usvg::Node::Group(w)] if w.id().is_empty() && is_plain(w) && self.text_slot(w).is_none() => Some(w),
_ => None,
}
}
fn children(&mut self, g: &usvg::Group, acc: Affine) -> Vec<Arc<Node>> {
g.children().iter().filter_map(|c| self.node(c, acc)).map(Arc::new).collect()
}
@@ -853,6 +934,9 @@ impl Importer {
n.blend = blend(g.blend_mode());
n.isolate = g.isolate();
n.mask = mask;
if !is_text && self.sublayers.contains(g.id()) {
self.sublayer_groups.insert(n.id);
}
Some(n)
}
+188 -1
View File
@@ -1,6 +1,7 @@
//! Symbols export as one `<symbol>` def and a `<use>` per instance (instances the def can't stand
//! for get their own art), hidden layers and objects are kept hidden when asked and come back
//! hidden with their `data-*` attributes, clipped layers come in as clipping layers, and the
//! hidden with their `data-*` attributes, clipped layers come in as clipping layers, layers and
//! sublayers keep their names and nesting (a one-layer file's from its root element), and the
//! editing data notices edits made elsewhere.
// 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)]
@@ -350,6 +351,192 @@ fn hidden_groups_others_use_stay_hidden() {
assert_eq!((paths, hidden), (0, 0), "{:?}", d.layers);
}
/// The layer tree: each object by kind (layers and groups with their names), `(hidden)` when
/// hidden, its contents indented below it.
fn outline(d: &Document) -> Vec<String> {
fn walk(n: &Node, depth: usize, out: &mut Vec<String>) {
let name = n.children().map(|_| format!(" {}", n.name.as_deref().unwrap_or("-"))).unwrap_or_default();
let hidden = if n.visible { "" } else { " (hidden)" };
out.push(format!("{}{}{name}{hidden}", " ".repeat(depth), n.kind_label()));
for c in n.children().into_iter().flatten() {
walk(c, depth + 1, out);
}
}
let mut out = vec![];
for l in &d.layers {
walk(l, 0, &mut out);
}
out
}
/// Layers as other apps export them (#372): named top-level groups, one hidden; a hidden named
/// group and a hidden object inside a layer.
const EXPORTED_LAYERS: &str = r##"<svg xmlns="http://www.w3.org/2000/svg" width="400" height="300" viewBox="0 0 400 300">
<g id="Main">
<rect id="plainStroke" x="20" y="50" width="120" height="60" style="fill:none;stroke:#000;stroke-width:4"/>
<rect id="hiddenObject" x="200" y="50" width="60" height="60" style="display:none;fill:#fff;stroke:#000"/>
<g id="HiddenSub" style="display:none"><circle cx="45" cy="175" r="25" style="fill:#fff;stroke:#000"/></g>
</g>
<g id="Second" display="none"><rect x="10" y="10" width="5" height="5"/></g>
</svg>"##;
#[test]
fn top_level_groups_become_named_layers() {
let expected = ["Layer Main", " Path", " Path (hidden)", " Group HiddenSub (hidden)", " Path", "Layer Second (hidden)", " Path"];
let d = import(EXPORTED_LAYERS).unwrap();
assert_eq!(outline(&d), expected);
// A nested group stays a group: nothing in the file says it's a sublayer.
// `data-name` names the layer when the id can't (spaces, punctuation).
let named = EXPORTED_LAYERS.replace("<g id=\"Main\">", "<g id=\"Main_Art\" data-name=\"Main Art\">");
assert_eq!(import(&named).unwrap().layers[0].name.as_deref(), Some("Main Art"));
// Layers wrapped in more groups: a transform on all the art, or a `<switch>` choosing them.
let moved = EXPORTED_LAYERS.replace("<g id=\"Main\">", "<g transform=\"translate(5 5)\"><g id=\"Main\">").replace("</svg>", "</g></svg>");
let d = import(&moved).unwrap();
assert_eq!(outline(&d), expected, "{moved}");
let stroke = &d.layers[0].children().unwrap()[0];
assert_eq!(stroke.geometric_bounds().unwrap(), Rect::new(25.0, 55.0, 145.0, 115.0));
let switched = EXPORTED_LAYERS
.replace("<g id=\"Main\">", "<switch><foreignObject requiredExtensions=\"urn:example:none\" width=\"1\" height=\"1\"/><g><g id=\"Main\">")
.replace("</svg>", "</g></switch></svg>");
assert_eq!(outline(&import(&switched).unwrap()), expected, "{switched}");
// Art beside the groups puts everything in one layer, as before.
let loose = EXPORTED_LAYERS.replace("</svg>", "<rect x=\"1\" y=\"1\" width=\"2\" height=\"2\"/></svg>");
assert_eq!(import(&loose).unwrap().layers.iter().map(|l| l.name.as_deref()).collect::<Vec<_>>(), [Some("Layer 1")]);
}
/// Layer "Base" holding a path, a named group, a clipping sublayer and a hidden sublayer "Notes"
/// with a sublayer of its own; layer "Top" above it.
fn sublayered() -> Document {
let mut d = Document::new(100.0, 100.0);
let square = |d: &mut Document, x: f64| {
let ap = Appearance::basic(Paint::solid(Color::rgb8(200, 30, 30)), Paint::None, 0.0);
Arc::new(Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, x, x + 10.0, x + 10.0)), ap))
};
let layer = |children: Vec<Arc<Node>>, d: &mut Document, name: &str| {
let mut l = Node::layer(d.alloc_id(), name, vectorcraft_doc::LayerColor::Preset(3));
*l.children_mut().unwrap() = children;
l
};
let deep = layer(vec![square(&mut d, 60.0)], &mut d, "Deep");
let mut notes = layer(vec![square(&mut d, 50.0), Arc::new(deep)], &mut d, "Notes");
notes.visible = false;
let mut clip = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(20.0, 20.0, 30.0, 30.0)), Appearance::default());
if let NodeKind::Path { clipping, .. } = &mut clip.kind {
*clipping = true;
}
let mut window = layer(vec![Arc::new(clip), square(&mut d, 25.0)], &mut d, "Window");
window.set_clips(true);
let mut group = Node::group(d.alloc_id(), vec![square(&mut d, 30.0), square(&mut d, 40.0)]);
group.name = Some("Pair".into());
let art = vec![square(&mut d, 10.0), Arc::new(group), Arc::new(window), Arc::new(notes)];
let base = Arc::make_mut(&mut d.layers[0]);
base.name = Some("Base".into());
*base.children_mut().unwrap() = art;
let top = layer(vec![square(&mut d, 80.0)], &mut d, "Top");
d.layers.push(Arc::new(top));
d
}
#[test]
fn sublayers_round_trip() {
let d = sublayered();
let expected = [
"Layer Base",
" Path",
" Group Pair",
" Path",
" Path",
" Layer Window",
" Path",
" Path",
" Layer Notes (hidden)",
" Path",
" Layer Deep",
" Path",
"Layer Top",
" Path",
];
assert_eq!(outline(&d), expected);
let styles = [vectorcraft_svg::Styling::PresentationAttributes, vectorcraft_svg::Styling::InlineStyle, vectorcraft_svg::Styling::InternalCss];
for styling in styles {
// Saved with the hidden sublayer: the same tree comes back.
let kept = export(&d, &ExportOptions { hidden_layers: true, styling, ..Default::default() });
assert_eq!(kept.matches("data-vc-layer").count(), 3, "sublayers only: {kept}");
let back = import(&kept).unwrap();
assert_eq!(outline(&back), expected, "{kept}");
// A sublayer takes its layer's colour.
back.walk(|n| {
if let NodeKind::Layer { color, .. } = &n.kind
&& n.name.as_deref() != Some("Top")
{
assert_eq!(*color, vectorcraft_doc::LayerColor::Preset(0), "{:?}", n.name);
}
});
assert!(back.layers[0].children().unwrap()[2].clips());
assert_similar(&render_artboard(&back), &render_artboard(&d), 24.0, 0.002);
}
// Exported without hidden art, the visible sublayer still comes back as one.
let plain = import(&export(&d, &ExportOptions::default())).unwrap();
assert_eq!(
outline(&plain),
["Layer Base", " Path", " Group Pair", " Path", " Path", " Layer Window", " Path", " Path", "Layer Top", " Path"]
);
}
#[test]
fn a_root_element_names_the_one_layer() {
// A one-layer document exported with its art loose under the root, which carries the name.
let svg = r##"<svg version="1.1" id="Main" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 300">
<rect x="20" y="50" width="120" height="60" style="fill:none;stroke:#000;stroke-width:4"/>
<g id="HiddenSub" style="display:none;"><circle cx="45" cy="175" r="25"/></g>
</svg>"##;
assert_eq!(outline(&import(svg).unwrap()), ["Layer Main", " Path", " Group HiddenSub (hidden)", " Path"]);
// `data-name` when the id can't hold the name.
let named = svg.replace("id=\"Main\"", "id=\"Main_Art\" data-name=\"Main Art\"");
assert_eq!(import(&named).unwrap().layers[0].name.as_deref(), Some("Main Art"));
let names = |svg: &str| import(svg).unwrap().layers.iter().map(|l| l.name.clone().unwrap()).collect::<Vec<_>>();
// Not when the groups at the top are the layers.
assert_eq!(names(&svg.replace("<rect", "<g id=\"Art\"><rect").replace("stroke-width:4\"/>", "stroke-width:4\"/></g>")), ["Art", "HiddenSub"]);
// Nor from the id Inkscape gives its root.
let inkscape = svg.replace("id=\"Main\"", "id=\"svg8\" xmlns:inkscape=\"http://www.inkscape.org/namespaces/inkscape\" inkscape:version=\"1.3\"");
assert_eq!(names(&inkscape), ["Layer 1"]);
}
#[test]
fn marked_groups_are_sublayers_only_in_layers() {
// Inkscape marks its layers and sublayers; one marked group in a plain group stays a group.
let svg = r##"<svg xmlns="http://www.w3.org/2000/svg" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" width="100" height="100">
<g id="layer1" inkscape:groupmode="layer" inkscape:label="Base">
<rect x="1" y="1" width="5" height="5"/>
<g id="layer2" inkscape:groupmode="layer" inkscape:label="Sub" style="display:none">
<rect x="10" y="10" width="5" height="5"/>
<g id="layer3" inkscape:groupmode="layer" inkscape:label="Deeper"><rect x="20" y="10" width="5" height="5"/></g>
</g>
<g id="g1"><rect x="30" y="1" width="5" height="5"/><g id="layer4" data-vc-layer="sublayer"><rect x="40" y="1" width="5" height="5"/></g></g>
</g>
</svg>"##;
let d = import(svg).unwrap();
assert_eq!(
outline(&d),
[
"Layer Base",
" Path",
" Layer Sub (hidden)",
" Path",
" Layer Deeper",
" Path",
" Group g1",
" Path",
" Group layer4",
" Path",
]
);
// Art outside layers ("Layer 1" holds it): a marked group there is a sublayer of it.
let loose = svg.replace("</svg>", "<rect x=\"1\" y=\"1\" width=\"2\" height=\"2\"/></svg>");
let d = import(&loose).unwrap();
assert_eq!(outline(&d)[..4], ["Layer Layer 1", " Layer Base", " Path", " Layer Sub (hidden)"]);
}
#[test]
fn editing_data_notices_edits_made_elsewhere() {
let d = symbol_doc(2.0, &[Affine::translate((50.0, 50.0))]);
+61
View File
@@ -0,0 +1,61 @@
//! Hand-written swatch exchange (`.ase`) files for swatch library tests: version 1.0, big-endian,
//! with colors in each model and color type, and color groups.
/// One block of a swatch exchange file.
#[derive(Clone, Debug)]
pub enum Block<'a> {
/// A color group starts (its name).
GroupStart(&'a str),
/// The open color group ends.
GroupEnd,
/// A color: its name, model (`b"RGB "`, `b"CMYK"`, `b"LAB "` or `b"Gray"`), components and
/// color type (0 global, 1 spot, 2 process).
Color(&'a str, &'a [u8; 4], &'a [f32], u16),
}
/// A name: a `u16` count of UTF-16 code units, the terminating zero included, then the units.
fn name(out: &mut Vec<u8>, name: &str) {
let units: Vec<u16> = name.encode_utf16().chain([0]).collect();
out.extend(u16::try_from(units.len()).unwrap().to_be_bytes());
out.extend(units.iter().flat_map(|u| u.to_be_bytes()));
}
/// A swatch exchange file of `blocks`.
pub fn ase(blocks: &[Block]) -> Vec<u8> {
let mut out = b"ASEF\0\x01\0\0".to_vec();
out.extend(u32::try_from(blocks.len()).unwrap().to_be_bytes());
for b in blocks {
let mut body = vec![];
let kind: u16 = match b {
Block::GroupStart(n) => {
name(&mut body, n);
0xC001
}
Block::GroupEnd => 0xC002,
Block::Color(n, model, values, kind) => {
name(&mut body, n);
body.extend(*model);
body.extend(values.iter().flat_map(|v| v.to_be_bytes()));
body.extend(kind.to_be_bytes());
0x0001
}
};
out.extend(kind.to_be_bytes());
out.extend(u32::try_from(body.len()).unwrap().to_be_bytes());
out.extend(body);
}
out
}
/// A library of four colors: "Sky" (global RGB) and "Ink" (spot CMYK), then the group "Neutrals"
/// of the process colors "Mist" (Gray, 25% ink) and "Clay" (Lab 50, 20, −30).
pub fn sample() -> Vec<u8> {
ase(&[
Block::Color("Sky", b"RGB ", &[0.0, 0.5, 1.0], 0),
Block::Color("Ink", b"CMYK", &[1.0, 0.5, 0.0, 0.2], 1),
Block::GroupStart("Neutrals"),
Block::Color("Mist", b"Gray", &[0.75], 2),
Block::Color("Clay", b"LAB ", &[0.5, 20.0, -30.0], 2),
Block::GroupEnd,
])
}
+2
View File
@@ -10,6 +10,7 @@
//! - [`raster`]: rendering helpers and image comparison with a perceptual tolerance.
//! - [`geom`]: geometry assertions (approximate equality, curve sampling, Hausdorff distance).
//! - [`pdf`]: hand-written PDF files (page boxes, colour spaces, encryption) for import tests.
//! - [`ase`]: hand-written swatch exchange (`.ase`) files for swatch library tests.
//!
//! This crate may only be used as a dev-dependency (enforced by `cargo xtask layers`).
// Test support only (a dev-dependency of every crate that uses it): a failed setup or assertion
@@ -18,6 +19,7 @@
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
#![forbid(unsafe_code)]
pub mod ase;
pub mod fixtures;
pub mod geom;
pub mod invariants;
+21 -4
View File
@@ -206,14 +206,17 @@ fn shrink_to_fit(db: &FontDb, t: &TextObject, opts: &LayoutOptions, min: f64) ->
Some(best.unwrap_or_else(|| at(lo)))
}
/// `t` with every run's size, explicit leading and baseline shift scaled by `f` (auto leading
/// follows the size; paragraph spacing stays).
/// `t` with every run's size, explicit leading and baseline shift scaled by `f`, inline art's own
/// shift included (auto leading and the art's size follow the size; paragraph spacing stays).
fn scaled(t: &TextObject, f: f64) -> TextObject {
let mut s = t.clone();
for r in &mut s.runs {
r.style.size *= f;
r.style.leading = r.style.leading.map(|l| l * f);
r.style.baseline_shift *= f;
if let Some(a) = &mut r.inline {
a.baseline_shift *= f;
}
}
s
}
@@ -595,6 +598,15 @@ fn align_vertically(cx: &mut Ctx<'_>, paras: &[Range<usize>], t: &TextObject, re
g.origin.y += d;
}
}
// Inline art moves with its glyph's line.
for i in &mut cx.out.inlines {
let d = cx.out.glyphs.get(i.glyph).and_then(|g| offs.get(g.line)).copied().unwrap_or(0.0);
if d != 0.0 {
let m = Affine::translate((0.0, d));
i.xf = m * i.xf;
i.bounds = m.transform_rect_bbox(i.bounds);
}
}
return;
}
let laid_out = |out: &TextLayout| out.lines.last().map_or(0, |l| l.end);
@@ -624,12 +636,17 @@ fn align_vertically(cx: &mut Ctx<'_>, paras: &[Range<usize>], t: &TextObject, re
return;
}
let before = laid_out(&cx.out);
let prev = (std::mem::take(&mut cx.out.glyphs), std::mem::take(&mut cx.out.lines), std::mem::replace(&mut cx.out.overflow, false));
let prev = (
std::mem::take(&mut cx.out.glyphs),
std::mem::take(&mut cx.out.lines),
std::mem::take(&mut cx.out.inlines),
std::mem::replace(&mut cx.out.overflow, false),
);
flow(cx, paras, t, Some(regions));
if laid_out(&cx.out) < before {
// Text no longer fits (lines got narrower, or flow around a wrap object): undo the
// pass and try a smaller step.
(cx.out.glyphs, cx.out.lines, cx.out.overflow) = prev;
(cx.out.glyphs, cx.out.lines, cx.out.inlines, cx.out.overflow) = prev;
for (r, (shift, gap)) in regions.iter_mut().zip(saved) {
r.shift = shift;
r.gap = gap;
+2
View File
@@ -502,6 +502,8 @@ mod tests;
#[cfg(test)]
mod tests_bidi;
#[cfg(test)]
mod tests_combos;
#[cfg(test)]
mod tests_embed;
#[cfg(test)]
mod tests_fit;
+574
View File
@@ -0,0 +1,574 @@
//! The text engine's newer features combined, two at a time and all together: ligatures under
//! tracking, the paragraph composer, area type vertical alignment, Shrink Text to Fit,
//! per-paragraph attributes and inline graphics. Each feature has its own tests; these check that
//! one doesn't undo or skip another (as vertical alignment once left inline art behind).
use super::*;
use kurbo::Shape;
use vectorcraft_doc::{AreaFit, CharStyle, Composer, InlineArt, Justify, TextKind, TextRun, VerticalAlign};
use vectorcraft_geom::PathData;
const COPY: &str = "Typography is the craft of arranging type to make written language legible, readable and appealing when displayed. \
The arrangement of type involves selecting typefaces, point sizes, line lengths, line spacing and letter spacing.";
/// Words full of `fi` (Source Serif 4 ligates it).
const FI: &str = "fine fish finish first in fifty fields of fireflies, a fitting finale for the final fiddler";
/// Two lines that single-line and every-line composers break differently (see
/// `every_line_composer_balances_ragged_lines`).
const RAG: &str = "Destroy all creatures with toughness X or less.";
fn db() -> &'static FontDb {
FontDb::global()
}
fn sans(size: f64) -> CharStyle {
CharStyle { size, ..CharStyle::default() }
}
fn serif(size: f64, tracking: f64) -> CharStyle {
CharStyle { font_family: "Source Serif 4".into(), size, tracking, ..CharStyle::default() }
}
fn run(text: &str, style: CharStyle) -> TextRun {
TextRun::new(text, style)
}
/// A square symbol, `scale` × the run's size tall, raised `shift` points.
fn art(scale: f64, shift: f64) -> InlineArt {
InlineArt { scale, baseline_shift: shift, bounds: Some(Rect::new(-5.0, -5.0, 5.0, 5.0)), ..InlineArt::new("sym") }
}
fn sym(scale: f64, shift: f64, style: CharStyle) -> TextRun {
TextRun::inline(art(scale, shift), style)
}
/// Area type in `frame` holding `runs`.
fn area(runs: Vec<TextRun>, frame: Rect) -> TextObject {
let mut t = TextObject::point(Point::ZERO, "", sans(12.0));
t.runs = runs;
t.kind = TextKind::Area { frame: PathData::from_bezpath(&frame.to_path(0.1)) };
t.xf = Affine::IDENTITY;
t
}
/// `t` as Shrink Text to Fit lays it out at factor `f`, without fitting: sizes, explicit leading
/// and baseline shifts scaled (inline art's own shift too), paragraph spacing kept.
fn scaled_by(t: &TextObject, f: f64) -> TextObject {
let mut s = t.clone();
s.area.fit = AreaFit::None;
for r in &mut s.runs {
r.style.size *= f;
r.style.leading = r.style.leading.map(|l| l * f);
r.style.baseline_shift *= f;
if let Some(a) = &mut r.inline {
a.baseline_shift *= f;
}
}
s
}
fn line_texts(t: &TextObject, l: &TextLayout) -> Vec<String> {
let text = t.plain_text();
l.lines.iter().map(|li| text[li.start..li.end].trim_end().to_string()).collect()
}
/// Ligature clusters: glyphs standing for more than one character.
fn ligatures(l: &TextLayout) -> usize {
l.glyphs.iter().filter(|g| g.len > 1 && !g.outline.elements().is_empty()).count()
}
/// Every inline graphic drawn once, where its glyph is: left edge on the glyph's origin, the
/// scaled height, centred half the (scaled) cap height above the glyph's baseline plus its own
/// (scaled) shift.
fn assert_inlines_on_their_glyphs(t: &TextObject, l: &TextLayout, what: &str) {
let want = t.runs.iter().filter(|r| r.inline.is_some()).count();
assert_eq!(l.inlines.len(), want, "{what}: one placement per inline run");
let mut glyphs: Vec<usize> = l.inlines.iter().map(|i| i.glyph).collect();
glyphs.dedup();
assert_eq!(glyphs.len(), want, "{what}: no inline drawn twice");
for i in &l.inlines {
let g = &l.glyphs[i.glyph];
assert_eq!(g.run, i.run, "{what}");
let r = &t.runs[i.run];
let a = r.inline.as_ref().unwrap();
let size = r.style.size * l.fit_scale;
let face = db().face(&r.style.font_family, &r.style.font_style).unwrap();
let cap = face.cap_height * size / face.upem;
let b = i.bounds;
assert!((b.height() - a.scale * size).abs() < 1e-6, "{what}: height {} vs {}", b.height(), a.scale * size);
assert!((b.x0 - g.origin.x).abs() < 1e-6, "{what}: {b:?} vs origin {:?}", g.origin);
let centre = g.origin.y - cap * 0.5 - a.baseline_shift * l.fit_scale;
assert!((b.center().y - centre).abs() < 1e-6, "{what}: centre {} vs {centre} (line {})", b.center().y, g.line);
assert!(l.lines[g.line].glyph_start <= i.glyph && i.glyph < l.lines[g.line].glyph_end, "{what}");
assert!(l.bounds.contains(b.center()), "{what}: layout bounds {:?} miss {b:?}", l.bounds);
}
}
/// Space left below the last line of a one-cell frame.
fn slack(l: &TextLayout, frame: Rect) -> f64 {
let last = l.lines.last().unwrap();
frame.y1 - (last.baseline + last.descent)
}
fn baselines(l: &TextLayout) -> Vec<f64> {
l.lines.iter().map(|li| li.baseline).collect()
}
// ---------- ligatures under tracking × … ----------
#[test]
fn ligatures_x_composer() {
// Justified (where every-line spreads word space) and ragged, with tracking inside the limits
// (kept) and letterspaced (dropped), whichever composer breaks the lines.
for justify in [Justify::Left, Justify::JustifyLeft] {
for (tracking, kept) in [(0.0, true), (20.0, true), (100.0, false)] {
let mut counts = vec![];
for composer in [Composer::SingleLine, Composer::EveryLine] {
let mut t = area(vec![run(&FI.repeat(3), serif(12.0, tracking))], Rect::new(0.0, 0.0, 170.0, 1000.0));
t.para.justify = justify;
t.para.composer = composer;
let l = layout(db(), &t);
assert!(l.lines.len() > 3, "several lines to compose");
counts.push(ligatures(&l));
}
assert_eq!(counts[0], counts[1], "{justify:?} {tracking}: composers shape alike");
assert_eq!(counts[0] > 0, kept, "{justify:?} {tracking}: {counts:?}");
}
}
}
#[test]
fn ligatures_x_vertical_align() {
let frame = Rect::new(0.0, 0.0, 200.0, 400.0);
for tracking in [20.0, 100.0] {
let mut t = area(vec![run(FI, serif(12.0, tracking))], frame);
let top = layout(db(), &t);
for a in [VerticalAlign::Center, VerticalAlign::Bottom, VerticalAlign::Justify] {
t.area.vertical_align = a;
let l = layout(db(), &t);
let gids = |l: &TextLayout| l.glyphs.iter().map(|g| (g.gid, g.byte)).collect::<Vec<_>>();
assert_eq!(gids(&l), gids(&top), "{tracking} {a:?}: moving lines doesn't reshape them");
assert!(l.lines[0].baseline > top.lines[0].baseline + 1.0 || a == VerticalAlign::Justify, "{a:?}");
}
}
}
#[test]
fn ligatures_x_shrink_text() {
// Tracking is in 1/1000 em, so scaling the size doesn't move it across the limits.
let frame = Rect::new(0.0, 0.0, 150.0, 60.0);
for (tracking, features, kept) in [(40.0, vec![], true), (100.0, vec![], false), (100.0, vec!["liga".to_string()], true)] {
let st = CharStyle { features, ..serif(14.0, tracking) };
let mut t = area(vec![run(&FI.repeat(2), st)], frame);
t.area.fit = AreaFit::ShrinkText { min_percent: 10.0 };
let l = layout(db(), &t);
assert!(!l.overflow && l.fit_scale < 1.0, "{tracking}: {}", l.fit_scale);
assert_eq!(ligatures(&l) > 0, kept, "{tracking}");
assert_eq!(ligatures(&l), ligatures(&layout(db(), &scaled_by(&t, l.fit_scale))), "{tracking}");
}
}
#[test]
fn ligatures_x_paragraph_attrs() {
// Paragraph attributes don't touch shaping: a centred, indented, every-line paragraph keeps
// its ligatures and a letterspaced run in the next paragraph loses them.
let mut t = area(vec![run(&format!("{FI}\n"), serif(12.0, 10.0)), run(FI, serif(12.0, 120.0))], Rect::new(0.0, 0.0, 240.0, 600.0));
let mut second = t.para.clone();
second.justify = Justify::Center;
second.left_indent = 20.0;
second.space_before = 12.0;
t.set_paragraph_styles(vec![t.para.clone(), second]);
let l = layout(db(), &t);
let split = FI.len() + 1;
let ligs = |first: bool| l.glyphs.iter().filter(|g| g.len > 1 && (g.byte < split) == first).count();
assert!(ligs(true) > 0, "tracking 10 keeps them");
assert_eq!(ligs(false), 0, "tracking 120 drops them");
}
#[test]
fn ligatures_x_inline_graphics() {
// An inline graphic between ligated words neither breaks their ligatures nor takes them: its
// own letterspaced run tracks the art without touching its neighbours.
let st = serif(14.0, 0.0);
let runs = vec![run("fine fish ", st.clone()), sym(1.0, 0.0, serif(14.0, 200.0)), run(" first fifty", st.clone())];
let t = area(runs, Rect::new(0.0, 0.0, 400.0, 100.0));
let l = layout(db(), &t);
let without = area(vec![run("fine fish ", st.clone()), run(" first fifty", st.clone())], Rect::new(0.0, 0.0, 400.0, 100.0));
assert_eq!(ligatures(&l), ligatures(&layout(db(), &without)), "the same ligatures as without the art");
assert!(ligatures(&l) >= 4, "fi in fine, fish, first and fifty");
assert_inlines_on_their_glyphs(&t, &l, "between ligatures");
let g = &l.glyphs[l.inlines[0].glyph];
assert!((g.advance - (14.0 + 200.0 / 1000.0 * 14.0)).abs() < 1e-6, "art width plus its tracking: {}", g.advance);
}
// ---------- composer × … ----------
#[test]
fn composer_x_vertical_align() {
let w = natural_width(RAG, 12.0) * 0.9;
let frame = Rect::new(0.0, 0.0, w, 200.0);
for composer in [Composer::SingleLine, Composer::EveryLine] {
let mut t = area(vec![run(RAG, sans(12.0))], frame);
t.para.composer = composer;
let top = layout(db(), &t);
for a in [VerticalAlign::Center, VerticalAlign::Bottom, VerticalAlign::Justify] {
t.area.vertical_align = a;
let l = layout(db(), &t);
assert_eq!(line_texts(&t, &l), line_texts(&t, &top), "{composer:?} {a:?}: the same breaks");
let want = match a {
VerticalAlign::Center => slack(&top, frame) * 0.5,
_ => slack(&top, frame),
};
let moved = l.lines.last().unwrap().baseline - top.lines.last().unwrap().baseline;
assert!((moved - want).abs() < 1e-6, "{composer:?} {a:?}: last line moved {moved}, want {want}");
}
}
// And the two composers still differ there.
let breaks = |c: Composer| {
let mut t = area(vec![run(RAG, sans(12.0))], frame);
t.para.composer = c;
t.area.vertical_align = VerticalAlign::Center;
line_texts(&t, &layout(db(), &t))
};
assert_ne!(breaks(Composer::SingleLine), breaks(Composer::EveryLine));
}
#[test]
fn composer_x_shrink_text() {
// Each composer shrinks to the largest size at which its own breaks fit.
for justify in [Justify::Left, Justify::JustifyLeft] {
for composer in [Composer::SingleLine, Composer::EveryLine] {
let mut t = area(vec![run(COPY, sans(14.0))], Rect::new(0.0, 0.0, 180.0, 90.0));
t.para.composer = composer;
t.para.justify = justify;
t.area.fit = AreaFit::ShrinkText { min_percent: 20.0 };
let l = layout(db(), &t);
assert!(!l.overflow && l.fit_scale < 1.0, "{justify:?} {composer:?}");
let size = 14.0 * l.fit_scale;
assert!(layout(db(), &scaled_by(&t, (size + 0.1) / 14.0)).overflow, "{justify:?} {composer:?}: maximal at {size}");
let same = layout(db(), &scaled_by(&t, l.fit_scale));
assert_eq!(line_texts(&t, &same), line_texts(&t, &l), "{justify:?} {composer:?}");
}
}
}
#[test]
fn composer_x_paragraph_attrs() {
// Each paragraph breaks with its own composer.
let w = natural_width("Destroy all creatures with toughness X or", 12.0) + 2.0;
let mut t = area(vec![run(&format!("{RAG}\n{RAG}\n{RAG}"), sans(12.0))], Rect::new(0.0, 0.0, w, 400.0));
let p = |c: Composer| vectorcraft_doc::ParaStyle { composer: c, ..t.para.clone() };
t.set_paragraph_styles(vec![p(Composer::SingleLine), p(Composer::EveryLine), p(Composer::SingleLine)]);
let l = layout(db(), &t);
let greedy = ["Destroy all creatures with toughness X or", "less."];
let every = ["Destroy all creatures with toughness X", "or less."];
let want: Vec<&str> = [greedy, every, greedy].concat();
assert_eq!(line_texts(&t, &l), want);
// The object-wide override still wins over every paragraph.
let forced = layout_with(db(), &t, &LayoutOptions { composer: Some(Composer::SingleLine), ..Default::default() });
assert_eq!(line_texts(&t, &forced), [greedy, greedy, greedy].concat());
}
#[test]
fn composer_x_inline_graphics() {
// An inline graphic is a word's worth of box to the composers: each one breaks around it as
// around the letter it replaces, and the art follows its glyph to whichever line it lands on.
let st = sans(12.0);
let runs = |x: TextRun| vec![run("Destroy all creatures with toughness ", st.clone()), x, run(" or less.", st.clone())];
let with_art = runs(sym(0.7, 0.0, st.clone()));
let mut probe = area(with_art.clone(), Rect::new(0.0, 0.0, 10_000.0, 100.0));
probe.runs.truncate(2);
probe.runs.push(run(" or", st.clone()));
let w = layout(db(), &probe).lines[0].x1 + 2.0;
let sym_text = INLINE.to_string();
for (composer, first, second) in [
(Composer::SingleLine, format!("Destroy all creatures with toughness {sym_text} or"), "less."),
(Composer::EveryLine, format!("Destroy all creatures with toughness {sym_text}"), "or less."),
] {
let mut t = area(with_art.clone(), Rect::new(0.0, 0.0, w, 200.0));
t.para.composer = composer;
let l = layout(db(), &t);
assert_eq!(line_texts(&t, &l), [first.as_str(), second], "{composer:?}");
assert_inlines_on_their_glyphs(&t, &l, &format!("{composer:?}"));
}
}
const INLINE: char = vectorcraft_doc::text::INLINE_CHAR;
// ---------- vertical alignment × … ----------
#[test]
fn vertical_align_x_shrink_text() {
let frame = Rect::new(0.0, 0.0, 200.0, 100.0);
let mut t = area(vec![run(&COPY.repeat(2), sans(14.0))], frame);
t.area.fit = AreaFit::ShrinkText { min_percent: 10.0 };
let top = layout(db(), &t);
assert!(!top.overflow && top.fit_scale < 1.0);
for a in [VerticalAlign::Center, VerticalAlign::Bottom] {
t.area.vertical_align = a;
let l = layout(db(), &t);
assert_eq!(l.fit_scale, top.fit_scale, "{a:?}: aligning doesn't change the fit");
assert_eq!(line_texts(&t, &l), line_texts(&t, &top), "{a:?}");
let want = if a == VerticalAlign::Center { slack(&top, frame) * 0.5 } else { slack(&top, frame) };
for (b, b0) in baselines(&l).iter().zip(baselines(&top)) {
assert!((b - b0 - want).abs() < 1e-6, "{a:?}: {b} vs {b0} + {want}");
}
if a == VerticalAlign::Bottom {
assert!(slack(&l, frame).abs() < 1e-6, "the shrunk block sits on the bottom");
}
}
// Still overflowing at the minimum: aligned like any full frame (the same lines, moved by
// less than a line, inside the frame), at the same scale.
let frame = Rect::new(0.0, 0.0, 120.0, 40.0);
let mut t = area(vec![run(&COPY.repeat(4), sans(14.0))], frame);
t.area.fit = AreaFit::ShrinkText { min_percent: 90.0 };
let top = layout(db(), &t);
assert!(top.overflow && (top.fit_scale - 0.9).abs() < 1e-9);
for a in [VerticalAlign::Center, VerticalAlign::Bottom, VerticalAlign::Justify] {
t.area.vertical_align = a;
let l = layout(db(), &t);
assert!(l.overflow && l.fit_scale == top.fit_scale, "{a:?}");
assert_eq!(line_texts(&t, &l), line_texts(&t, &top), "{a:?}");
let first = &top.lines[0];
assert!(l.lines[0].baseline - first.baseline < first.ascent + first.descent, "{a:?}");
assert!(slack(&l, frame) >= -1e-6, "{a:?}");
}
}
#[test]
fn vertical_align_x_paragraph_attrs() {
// Per-paragraph spacing and alignment survive the move: lines keep their x and their
// paragraph gaps, and the block lands where the alignment puts it.
let frame = Rect::new(0.0, 0.0, 260.0, 500.0);
let mut t = area(vec![run(&format!("{COPY}\n{COPY}\n{COPY}"), sans(11.0))], frame);
let mut mid = t.para.clone();
mid.justify = Justify::Center;
mid.space_before = 18.0;
mid.left_indent = 24.0;
let mut last = t.para.clone();
last.justify = Justify::Right;
last.space_before = 6.0;
t.set_paragraph_styles(vec![t.para.clone(), mid, last]);
let top = layout(db(), &t);
for a in [VerticalAlign::Center, VerticalAlign::Bottom] {
t.area.vertical_align = a;
let l = layout(db(), &t);
assert_eq!(line_texts(&t, &l), line_texts(&t, &top));
let d = l.lines[0].baseline - top.lines[0].baseline;
assert!(d > 1.0, "{a:?}");
for (li, l0) in l.lines.iter().zip(&top.lines) {
assert!((li.baseline - l0.baseline - d).abs() < 1e-6, "{a:?}: every line moves alike");
assert!((li.x0 - l0.x0).abs() < 1e-6 && (li.x1 - l0.x1).abs() < 1e-6, "{a:?}: x stays");
}
for (g, g0) in l.glyphs.iter().zip(&top.glyphs) {
assert!((g.origin.x - g0.origin.x).abs() < 1e-6 && (g.origin.y - g0.origin.y - d).abs() < 1e-6);
}
}
// Justify: spacing is shared out on top of each paragraph's own space before, never less.
t.area.vertical_align = VerticalAlign::Justify;
let l = layout(db(), &t);
assert!(slack(&l, frame).abs() < 1e-6, "justified to the bottom");
for (pair, pair0) in l.lines.windows(2).zip(top.lines.windows(2)) {
assert!(pair[1].baseline - pair[0].baseline >= pair0[1].baseline - pair0[0].baseline - 1e-6);
}
}
#[test]
fn vertical_align_x_inline_graphics() {
// Inline art moves with its line however the lines are aligned, in one cell or several, in a
// rectangle or a frame the text flows into again.
let st = sans(12.0);
let mut runs = vec![];
for i in 0..6 {
runs.push(run(&format!("{} ", &COPY[i * 20..i * 20 + 20]), st.clone()));
runs.push(sym(1.0 + i as f64 * 0.1, i as f64 - 2.0, st.clone()));
if i == 2 {
runs.push(run("\n", st.clone()));
}
}
let mut tri = BezPath::new();
tri.move_to((0.0, 0.0));
tri.line_to((600.0, 0.0));
tri.line_to((300.0, 400.0));
tri.close_path();
for (name, frame, columns) in [
("rect", Rect::new(0.0, 0.0, 160.0, 400.0).to_path(0.1), 1),
("columns", Rect::new(0.0, 0.0, 400.0, 300.0).to_path(0.1), 2),
("triangle", tri, 1),
] {
for a in VerticalAlign::ALL {
let mut t = area(runs.clone(), Rect::ZERO);
t.kind = TextKind::Area { frame: PathData::from_bezpath(&frame) };
t.area.columns = columns;
t.area.vertical_align = a;
let l = layout(db(), &t);
assert!(!l.overflow, "{name} {a:?}");
assert_inlines_on_their_glyphs(&t, &l, &format!("{name} {a:?}"));
}
}
}
// ---------- Shrink Text to Fit × … ----------
#[test]
fn shrink_text_x_paragraph_attrs() {
// Shrinking scales the type, not each paragraph's spacing and indents: the fitted layout is
// the unfitted one at the scaled size.
let mut t = area(vec![run(&format!("{COPY}\n{COPY}"), sans(13.0))], Rect::new(0.0, 0.0, 220.0, 160.0));
let mut second = t.para.clone();
second.space_before = 14.0;
second.left_indent = 30.0;
second.first_line_indent = 12.0;
second.justify = Justify::JustifyLeft;
second.composer = Composer::SingleLine;
t.set_paragraph_styles(vec![t.para.clone(), second]);
t.area.fit = AreaFit::ShrinkText { min_percent: 10.0 };
let l = layout(db(), &t);
assert!(!l.overflow && l.fit_scale < 1.0);
let same = layout(db(), &scaled_by(&t, l.fit_scale));
assert_eq!(baselines(&l), baselines(&same));
assert_eq!(line_texts(&t, &l), line_texts(&t, &same));
// The second paragraph's indents are unscaled points.
let split = COPY.len() + 1;
let first_of_second = l.lines.iter().find(|li| li.start == split).unwrap();
assert!((first_of_second.x0 - 42.0).abs() < 1e-6, "{}", first_of_second.x0);
assert!(l.lines.iter().filter(|li| li.start > split).all(|li| (li.x0 - 30.0).abs() < 1e-6));
// A paragraph's space before alone can make the text overflow; shrinking still finds a fit.
let mut tall = t.clone();
tall.edit_paras(Some(1..2), |p| p.space_before = 100.0);
let l = layout(db(), &tall);
assert!(!l.overflow && l.fit_scale < layout(db(), &t).fit_scale);
}
#[test]
fn shrink_text_x_inline_graphics() {
// Inline art shrinks with the type, its shift included, and stays centred on the cap height.
let st = sans(14.0);
let mut runs = vec![];
for i in 0..8 {
runs.push(run(&COPY[i * 25..i * 25 + 25], st.clone()));
runs.push(sym(1.2, 1.5, st.clone()));
}
let mut t = area(runs, Rect::new(0.0, 0.0, 200.0, 80.0));
t.area.fit = AreaFit::ShrinkText { min_percent: 10.0 };
let l = layout(db(), &t);
assert!(!l.overflow && l.fit_scale < 1.0, "{}", l.fit_scale);
assert_inlines_on_their_glyphs(&t, &l, "shrunk");
let same = layout(db(), &scaled_by(&t, l.fit_scale));
for (i, i0) in l.inlines.iter().zip(&same.inlines) {
assert!((i.bounds.y0 - i0.bounds.y0).abs() < 1e-6 && (i.bounds.x0 - i0.bounds.x0).abs() < 1e-6, "{:?} vs {:?}", i.bounds, i0.bounds);
}
// Large art makes lines taller; shrinking still fits it.
for r in &mut t.runs {
if let Some(a) = &mut r.inline {
a.scale = 3.0;
}
}
let big = layout(db(), &t);
assert!(!big.overflow && big.fit_scale < l.fit_scale);
assert_inlines_on_their_glyphs(&t, &big, "shrunk, big art");
}
// ---------- paragraph attributes × inline graphics ----------
#[test]
fn paragraph_attrs_x_inline_graphics() {
// Inline art in paragraphs of each alignment and indent sits on its glyph, and an inline
// graphic opening a paragraph takes that paragraph's first-line indent.
let st = sans(12.0);
let runs = vec![
run("Left aligned ", st.clone()),
sym(1.0, 0.0, st.clone()),
run(" text.\n", st.clone()),
sym(1.0, 0.0, st.clone()),
run(" centred with art first\nright ", st.clone()),
sym(1.5, -1.0, st.clone()),
run(" aligned\nfull justified text with ", st.clone()),
sym(1.0, 0.0, st.clone()),
run(" in the middle of a long line that wraps", st.clone()),
];
let mut t = area(runs, Rect::new(0.0, 0.0, 200.0, 400.0));
let base = t.para.clone();
let with = |j: Justify, first: f64| vectorcraft_doc::ParaStyle { justify: j, first_line_indent: first, left_indent: 6.0, ..base.clone() };
t.set_paragraph_styles(vec![base.clone(), with(Justify::Center, 0.0), with(Justify::Right, 0.0), with(Justify::JustifyLeft, 18.0)]);
let l = layout(db(), &t);
assert_inlines_on_their_glyphs(&t, &l, "paragraphs");
let opening = &l.glyphs[l.inlines[1].glyph];
let line = &l.lines[opening.line];
assert!((opening.origin.x - line.x0).abs() < 1e-6, "the art opens its line");
assert!(((line.x0 + line.x1) * 0.5 - (6.0 + 200.0) * 0.5).abs() < 1e-6, "the centred paragraph: {line:?}");
let right = &l.lines[l.glyphs[l.inlines[2].glyph].line];
assert!((right.x1 - 200.0).abs() < 1e-6, "{right:?}");
let full = l.lines.iter().find(|li| li.start == t.plain_text().find("full").unwrap()).unwrap();
assert!((full.x0 - 24.0).abs() < 1e-6, "left indent + first-line indent: {full:?}");
}
// ---------- all of them ----------
/// One area type object with everything on: two paragraphs with their own attributes (the first
/// ragged every-line with inline symbols and lightly tracked ligatures, the second single-line,
/// justified and spaced away), centred vertically, shrunk to fit.
#[test]
fn every_feature_at_once() {
let rules = serif(14.0, 15.0);
let flavor = CharStyle { font_style: "Italic".into(), ..serif(14.0, 0.0) };
let mut runs = vec![];
for (i, words) in
["Sacrifice a fine fish", "First strike. When this finishes fighting, draw a card", "Fifty fireflies fill the field"].iter().enumerate()
{
runs.push(sym(0.8, 0.0, rules.clone()));
runs.push(run(&format!(": {words}. "), rules.clone()));
if i == 1 {
runs.push(sym(0.8, 0.5, rules.clone()));
runs.push(run(" Then fight again.", rules.clone()));
}
}
runs.push(run("\nThe finest fishers find their fortune in the fjords, if they first fix their nets.", flavor));
let frame = Rect::new(0.0, 0.0, 240.0, 110.0);
let mut t = area(runs, frame);
let mut flav = t.para.clone();
flav.space_before = 10.0;
flav.justify = Justify::JustifyLeft;
flav.composer = Composer::SingleLine;
t.para.composer = Composer::EveryLine;
t.set_paragraph_styles(vec![t.para.clone(), flav]);
t.area.fit = AreaFit::ShrinkText { min_percent: 30.0 };
let top = layout(db(), &t);
t.area.vertical_align = VerticalAlign::Center;
let l = layout(db(), &t);
assert!(!l.overflow && l.fit_scale < 1.0, "{}", l.fit_scale);
assert_eq!(l.fit_scale, top.fit_scale);
// Shrunk: the same as laying out the scaled text, then centring it.
let mut unfit = scaled_by(&t, l.fit_scale);
unfit.area.vertical_align = VerticalAlign::Top;
let plain = layout(db(), &unfit);
assert_eq!(line_texts(&t, &l), line_texts(&t, &plain));
let d = slack(&plain, frame) * 0.5;
assert!(d > 0.0);
for (b, b0) in baselines(&l).iter().zip(baselines(&plain)) {
assert!((b - b0 - d).abs() < 1e-6, "centred: {b} vs {b0} + {d}");
}
// Every symbol on its glyph; ligatures kept at tracking 15.
assert_inlines_on_their_glyphs(&t, &l, "everything");
assert_eq!(l.inlines.len(), 4);
assert!(ligatures(&l) >= 6, "{}", ligatures(&l));
// The flavor paragraph: justified (all but its last line fill the measure) and spaced away.
let split = t.plain_text().find('\n').unwrap() + 1;
let flavor_lines: Vec<&LineInfo> = l.lines.iter().filter(|li| li.start >= split).collect();
assert!(flavor_lines.len() >= 2);
for li in &flavor_lines[..flavor_lines.len() - 1] {
assert!((li.x1 - li.x0 - 240.0).abs() < 0.5, "justified: {li:?}");
}
// Deterministic.
let again = layout(db(), &t);
assert_eq!(baselines(&again), baselines(&l));
assert_eq!(again.inlines.iter().map(|i| i.bounds).collect::<Vec<_>>(), l.inlines.iter().map(|i| i.bounds).collect::<Vec<_>>());
}
/// The natural width of `s` set in one line at `size`.
fn natural_width(s: &str, size: f64) -> f64 {
let l = layout(db(), &TextObject::point(Point::ZERO, s, sans(size)));
l.lines[0].x1 - l.lines[0].x0
}
+30
View File
@@ -296,3 +296,33 @@ fn top_to_top_leading_spaces_inline_art_by_its_run() {
let (tall0, tall1) = lines(3.0);
assert!((small0 - tall0).abs() < 1e-6 && (small1 - tall1).abs() < 1e-6, "{small0} {small1} / {tall0} {tall1}");
}
#[test]
fn inline_art_moves_with_vertically_aligned_lines() {
use vectorcraft_doc::text::{AreaOptions, VerticalAlign};
// A rectangle (lines shift) and a triangle (text flows again lower down).
let rect = Rect::new(0.0, 0.0, 400.0, 400.0).to_path(0.1);
let mut tri = kurbo::BezPath::new();
tri.move_to((0.0, 0.0));
tri.line_to((800.0, 0.0));
tri.line_to((400.0, 400.0));
tri.close_path();
for frame in [rect, tri] {
for align in [VerticalAlign::Center, VerticalAlign::Bottom] {
let mut t = text("A", art(1.0), "B", 20.0);
t.kind = TextKind::Area { frame: PathData::from_bezpath(&frame) };
t.area = AreaOptions { vertical_align: align, ..AreaOptions::default() };
let l = layout(db(), &t);
assert_eq!(l.inlines.len(), 1, "{align:?}");
let g = inline_glyph(&l);
let line = &l.lines[g.line];
assert!(line.baseline > 100.0, "{align:?}: not aligned, baseline {}", line.baseline);
// Still centred on the cap height above its (moved) baseline.
let face = db().face("Source Sans 3", "Regular").unwrap();
let cap = face.cap_height * 20.0 / face.upem;
let b = l.inlines[0].bounds;
assert!((b.center().y - (line.baseline - cap * 0.5)).abs() < 1e-6, "{align:?}: {b:?} baseline {}", line.baseline);
assert!((b.x0 - g.origin.x).abs() < 1e-6, "{align:?}: {b:?}");
}
}
}
+13 -3
View File
@@ -259,10 +259,19 @@ impl Tool for ArtboardTool {
}
}
/// Delete/Backspace remove the active artboard ahead of the Clear shortcut, which would only
/// delete selected art; with one artboard left (it can't be deleted) they stay the shortcut's.
fn claims_key(&self, cx: &ToolContext, key: ToolKey) -> bool {
matches!(key, ToolKey::Delete | ToolKey::Backspace)
&& self.drag.is_none()
&& cx.doc.artboards.len() > 1
&& self.active < cx.doc.artboards.len()
}
fn key(&mut self, cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec<Action> {
match key {
ToolKey::Delete | ToolKey::Backspace if self.drag.is_none() => {
if cx.doc.artboards.len() <= 1 || self.active >= cx.doc.artboards.len() {
ToolKey::Delete | ToolKey::Backspace => {
if !self.claims_key(cx, key) {
return vec![];
}
let i = self.active;
@@ -522,7 +531,8 @@ mod tests {
let a = t.pointer(&cx, &ev(PointerKind::Up, 1100.0, 1050.0));
assert_eq!(a[0], Action::Exec("artboard.new".into(), json!({"x": 1000.0, "y": 1000.0, "width": 100.0, "height": 50.0})));
assert_eq!(a[1], Action::Notify("created".into()));
// Delete removes the active artboard.
// Delete removes the active artboard, ahead of the Clear shortcut.
assert!(t.claims_key(&cx, ToolKey::Delete) && t.claims_key(&cx, ToolKey::Backspace));
assert_eq!(t.key(&cx, ToolKey::Delete, Mods::default()), vec![Action::Exec("artboard.delete".into(), json!({"index": 1}))]);
assert_eq!(t.key(&cx, ToolKey::Escape, Mods::default()), vec![Action::SwitchTool("selection".into())]);
}
+379
View File
@@ -0,0 +1,379 @@
//! Create Strokes: the parts of a colour layer no wider than the Stroke width, traced as stroked
//! centre lines instead of filled outlines.
//!
//! 1. **Distance**: a chamfer (3-4) distance transform gives each pixel its distance to the nearest
//! pixel outside the layer.
//! 2. **Lines**: an 8-connected component whose widest point (twice its largest distance, less
//! one) is within the stroke width is a line; wider ones stay filled areas.
//! 3. **Skeleton**: the line is thinned to one pixel (Zhang–Suen, applied pixel by pixel so it
//! keeps its topology and two-pixel-wide lines don't vanish), then staircase corners that
//! don't connect anything are dropped.
//! 4. **Graph**: runs of skeleton pixels between ends and junctions (touching junction pixels
//! merged into one point) become polylines through the pixel centres; rings without ends
//! become closed ones. Short spurs that thinning leaves at junctions are pruned and the runs
//! on either side of a junction left with two of them are joined.
//! 5. **Curves**: each polyline is fitted like an outline ([`fit::fit_polyline`]); the stroke
//! width is the line's mean width (its pixel count over its length).
use std::collections::HashSet;
use vectorcraft_geom::{PathData, Point};
use crate::fit::{self, FitOptions};
/// One line of a colour layer: its centre lines and the width to stroke them with.
pub(crate) struct Line {
pub path: PathData,
/// Stroke width in pixels.
pub width: f64,
pub pixels: usize,
}
/// The lines of colour `label` in `labels` (`w` × `h`, row-major) no wider than `max_width`
/// pixels, and which pixels they cover (to leave out of the filled areas).
pub(crate) fn lines(labels: &[u16], label: u16, w: usize, h: usize, max_width: f64, o: &FitOptions) -> (Vec<bool>, Vec<Line>) {
let mut thin = vec![false; labels.len()];
let mut out = vec![];
if w == 0 || h == 0 || labels.len() != w * h {
return (thin, out);
}
let mask = |i: usize| labels.get(i) == Some(&label);
let dt = distance(&mask, w, h);
let mut seen = vec![false; w * h];
let mut stack = vec![];
for start in 0..w * h {
if !mask(start) || seen[start] {
continue;
}
let mut comp = vec![];
seen[start] = true;
stack.push(start);
while let Some(i) = stack.pop() {
comp.push(i);
for j in neighbours(i, w, h) {
if mask(j) && !seen[j] {
seen[j] = true;
stack.push(j);
}
}
}
let widest = 2.0 * f64::from(comp.iter().map(|&i| dt[i]).max().unwrap_or(0)) / 3.0 - 1.0;
if widest > max_width {
continue;
}
let Some(line) = trace_line(&comp, w, max_width, o) else { continue };
for &i in &comp {
thin[i] = true;
}
out.push(line);
}
(thin, out)
}
/// The 8 neighbours of pixel `i` inside the `w` × `h` image.
fn neighbours(i: usize, w: usize, h: usize) -> impl Iterator<Item = usize> {
let (x, y) = ((i % w) as i64, (i / w) as i64);
const AROUND: [(i64, i64); 8] = [(-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)];
AROUND.into_iter().filter_map(move |(dx, dy)| {
let (nx, ny) = (x + dx, y + dy);
(nx >= 0 && ny >= 0 && nx < w as i64 && ny < h as i64).then(|| ny as usize * w + nx as usize)
})
}
/// Chamfer 3-4 distance (3 per pixel step, saturating) of each pixel in `mask` to the nearest
/// pixel outside it; outside the image counts as outside.
fn distance(mask: &impl Fn(usize) -> bool, w: usize, h: usize) -> Vec<u16> {
let mut d = vec![0u16; w * h];
let at = |d: &[u16], x: i64, y: i64| {
if x < 0 || y < 0 || x >= w as i64 || y >= h as i64 { 0 } else { d.get(y as usize * w + x as usize).copied().unwrap_or(0) }
};
for y in 0..h {
for x in 0..w {
let i = y * w + x;
if mask(i) {
let (x, y) = (x as i64, y as i64);
let steps = [(x - 1, y, 3), (x - 1, y - 1, 4), (x, y - 1, 3), (x + 1, y - 1, 4)];
d[i] = steps.iter().map(|&(nx, ny, c)| at(&d, nx, ny).saturating_add(c)).min().unwrap_or(0);
}
}
}
for y in (0..h).rev() {
for x in (0..w).rev() {
let i = y * w + x;
if mask(i) {
let (xi, yi) = (x as i64, y as i64);
let steps = [(xi + 1, yi, 3), (xi + 1, yi + 1, 4), (xi, yi + 1, 3), (xi - 1, yi + 1, 4)];
let v = steps.iter().map(|&(nx, ny, c)| at(&d, nx, ny).saturating_add(c)).min().unwrap_or(0);
d[i] = d[i].min(v);
}
}
}
d
}
/// A grid around one line: its pixels with a one-pixel empty border.
struct Grid {
on: Vec<bool>,
w: usize,
h: usize,
/// Image position of grid pixel (0, 0).
x0: i64,
y0: i64,
}
impl Grid {
/// The 8 neighbours (N, NE, E, SE, S, SW, W, NW) of interior pixel `i`.
fn ring(&self, i: usize) -> [bool; 8] {
let w = self.w;
let g = |j: usize| self.on.get(j).copied().unwrap_or(false);
[g(i - w), g(i - w + 1), g(i + 1), g(i + w + 1), g(i + w), g(i + w - 1), g(i - 1), g(i - w - 1)]
}
fn interior(&self) -> impl Iterator<Item = usize> + use<> {
let (w, h) = (self.w, self.h);
(1..h.saturating_sub(1)).flat_map(move |y| (1..w.saturating_sub(1)).map(move |x| y * w + x))
}
fn neighbours(&self, i: usize) -> impl Iterator<Item = usize> + '_ {
let w = self.w;
[i - w, i - w + 1, i + 1, i + w + 1, i + w, i + w - 1, i - 1, i - w - 1].into_iter().filter(|&j| self.on.get(j).copied().unwrap_or(false))
}
fn degree(&self, i: usize) -> usize {
self.neighbours(i).count()
}
/// The centre of pixel `i` in image coordinates.
fn centre(&self, i: usize) -> Point {
Point::new((self.x0 + (i % self.w) as i64) as f64 + 0.5, (self.y0 + (i / self.w) as i64) as f64 + 0.5)
}
}
/// Zhang–Suen thinning. Each sub-iteration picks the pixels to remove from the same state, so the
/// skeleton stays centred; they are then removed one by one, each only if it still doesn't
/// disconnect anything, so a two-pixel-wide line thins to one pixel instead of vanishing.
fn thin(g: &mut Grid) {
let removable = |p: &[bool; 8]| {
let b = p.iter().filter(|v| **v).count();
let a = (0..8).filter(|&k| !p[k] && p[(k + 1) % 8]).count();
(2..=6).contains(&b) && a == 1
};
let mut picked = vec![];
loop {
let mut changed = false;
for step in 0..2 {
picked.clear();
for i in g.interior() {
if !g.on[i] {
continue;
}
let p = g.ring(i);
let (n, e, s, w) = (p[0], p[2], p[4], p[6]);
let side = if step == 0 { !(e && s && (n || w)) } else { !(n && w && (e || s)) };
if side && removable(&p) {
picked.push(i);
}
}
for &i in &picked {
if removable(&g.ring(i)) {
g.on[i] = false;
changed = true;
}
}
}
if !changed {
break;
}
}
// Staircase corners: a pixel whose neighbours stay connected without it (Yokoi's
// 8-connectivity number 1) and that doesn't end the line.
loop {
let mut changed = false;
for i in g.interior() {
if !g.on[i] || g.degree(i) < 2 {
continue;
}
let p = g.ring(i);
// x1 = E, x2 = NE, x3 = N, x4 = NW, x5 = W, x6 = SW, x7 = S, x8 = SE.
let x = [p[2], p[1], p[0], p[7], p[6], p[5], p[4], p[3]];
let off = |k: usize| !x[k % 8];
let c8: usize = [0, 2, 4, 6].iter().map(|&k| usize::from(off(k)) - usize::from(off(k) && off(k + 1) && off(k + 2))).sum();
if c8 == 1 {
g.on[i] = false;
changed = true;
}
}
if !changed {
break;
}
}
}
/// A run of skeleton pixels between two nodes (`None`: none, a ring).
#[derive(Clone)]
struct Run {
pts: Vec<Point>,
ends: [Option<usize>; 2],
closed: bool,
}
impl Run {
fn length(&self) -> f64 {
self.pts.windows(2).map(|p| p[0].distance(p[1])).sum::<f64>()
+ if self.closed { self.pts.first().zip(self.pts.last()).map_or(0.0, |(a, b)| a.distance(*b)) } else { 0.0 }
}
}
/// The centre lines of one line component (pixel indices of the `w`-wide image).
fn trace_line(comp: &[usize], w: usize, max_width: f64, o: &FitOptions) -> Option<Line> {
let xs = comp.iter().map(|&i| i % w);
let ys = comp.iter().map(|&i| i / w);
let (x0, x1, y0, y1) = (xs.clone().min()?, xs.max()?, ys.clone().min()?, ys.max()?);
let (gw, gh) = (x1 - x0 + 3, y1 - y0 + 3);
let mut g = Grid { on: vec![false; gw * gh], w: gw, h: gh, x0: x0 as i64 - 1, y0: y0 as i64 - 1 };
for &i in comp {
g.on[(i / w - y0 + 1) * gw + (i % w - x0 + 1)] = true;
}
thin(&mut g);
let skeleton: Vec<usize> = g.interior().filter(|&i| g.on[i]).collect();
if skeleton.len() < 2 {
return None;
}
// Nodes: line ends, and junctions with the junction pixels touching them.
let mut node = vec![usize::MAX; g.on.len()];
let mut centres: Vec<Point> = vec![];
for &i in &skeleton {
let d = g.degree(i);
if d == 2 || node[i] != usize::MAX {
continue;
}
let id = centres.len();
let mut members = vec![i];
node[i] = id;
if d > 2 {
let mut k = 0;
while let Some(&p) = members.get(k) {
k += 1;
for q in g.neighbours(p).collect::<Vec<_>>() {
if node[q] == usize::MAX && g.degree(q) > 2 {
node[q] = id;
members.push(q);
}
}
}
}
let sum = members.iter().fold(Point::ZERO, |s, &m| s + g.centre(m).to_vec2());
centres.push(Point::new(sum.x / members.len() as f64, sum.y / members.len() as f64));
}
// Runs from each node, then the rings left.
let mut used: HashSet<(usize, usize)> = HashSet::new();
let edge = |a: usize, b: usize| (a.min(b), a.max(b));
let mut runs: Vec<Run> = vec![];
for &p in skeleton.iter().filter(|&&i| node[i] != usize::MAX) {
for q in g.neighbours(p).collect::<Vec<_>>() {
if node[q] == node[p] || !used.insert(edge(p, q)) {
continue;
}
let mut pts = vec![centres[node[p]], g.centre(q)];
let (mut prev, mut cur) = (p, q);
while node[cur] == usize::MAX {
let Some(next) = g.neighbours(cur).find(|&n| n != prev && !used.contains(&edge(cur, n))) else { break };
used.insert(edge(cur, next));
pts.push(g.centre(next));
(prev, cur) = (cur, next);
}
let end = (node[cur] != usize::MAX).then_some(node[cur]);
if let (Some(e), Some(last)) = (end, pts.last_mut()) {
*last = centres[e];
}
runs.push(Run { pts, ends: [Some(node[p]), end], closed: false });
}
}
for &s in &skeleton {
if node[s] != usize::MAX || g.neighbours(s).any(|n| used.contains(&edge(s, n))) {
continue;
}
let mut pts = vec![g.centre(s)];
let (mut prev, mut cur) = (usize::MAX, s);
let mut closed = false;
while let Some(next) = g.neighbours(cur).find(|&n| n != prev && !used.contains(&edge(cur, n))) {
used.insert(edge(cur, next));
if next == s {
closed = true;
break;
}
pts.push(g.centre(next));
(prev, cur) = (cur, next);
}
runs.push(Run { pts, ends: [None, None], closed });
}
// The line's mean width: its pixels over its length (the skeleton stops about half a width
// short of each end).
let width = |runs: &[Run]| {
let length: f64 = runs.iter().map(Run::length).sum();
let px = comp.len() as f64;
((-length + (length * length + 4.0 * px).sqrt()) / 2.0).clamp(1.0, max_width.max(1.0))
};
let spur = width(&runs);
let runs = join(prune(runs, centres.len(), spur), centres.len());
let width = width(&runs);
let subs: Vec<_> = runs.iter().filter_map(|r| fit::fit_polyline(&r.pts, r.closed, o)).collect();
if subs.is_empty() {
return None;
}
Some(Line { path: PathData::new(subs), width, pixels: comp.len() })
}
/// The runs without the spurs thinning leaves: runs shorter than the line's `width` from a line end
/// to a junction that keeps at least two other runs.
fn prune(runs: Vec<Run>, nodes: usize, width: f64) -> Vec<Run> {
let mut degree = vec![0usize; nodes];
for e in runs.iter().flat_map(|r| r.ends.iter().flatten()) {
degree[*e] += 1;
}
let mut order: Vec<usize> = (0..runs.len()).collect();
order.sort_by(|a, b| runs[*a].length().total_cmp(&runs[*b].length()));
let mut keep = vec![true; runs.len()];
for i in order {
let r = &runs[i];
let [Some(a), Some(b)] = r.ends else { continue };
let (tip, fork) = if degree[a] == 1 { (a, b) } else { (b, a) };
if degree[tip] == 1 && degree[fork] >= 3 && r.length() < width.max(2.0) {
keep[i] = false;
degree[tip] -= 1;
degree[fork] -= 1;
}
}
runs.into_iter().zip(keep).filter_map(|(r, k)| k.then_some(r)).collect()
}
/// The runs joined through every node exactly two of them meet at (a run meeting itself closes).
fn join(runs: Vec<Run>, nodes: usize) -> Vec<Run> {
let mut runs: Vec<Option<Run>> = runs.into_iter().map(Some).collect();
for n in 0..nodes {
let at: Vec<(usize, usize)> = runs
.iter()
.enumerate()
.flat_map(|(i, r)| r.iter().flat_map(move |r| (0..2).filter(move |&k| r.ends[k] == Some(n)).map(move |k| (i, k))))
.collect();
let [(i, ki), (j, kj)] = at[..] else { continue };
if i == j {
if let Some(r) = runs[i].as_mut() {
r.pts.pop();
r.ends = [None, None];
r.closed = r.pts.len() >= 3;
}
continue;
}
let (Some(mut a), Some(mut b)) = (runs[i].take(), runs[j].take()) else { continue };
// a ends at n, b starts at n.
if ki == 0 {
a.pts.reverse();
a.ends.reverse();
}
if kj == 1 {
b.pts.reverse();
b.ends.reverse();
}
a.pts.extend(b.pts.into_iter().skip(1));
a.ends[1] = b.ends[1];
runs[i] = Some(a);
}
runs.into_iter().flatten().collect()
}
+43
View File
@@ -133,6 +133,49 @@ pub(crate) fn fit_loop(l: &Loop, o: &FitOptions) -> Option<SubPath> {
Some(sp)
}
/// Fit a centre line through `pts` (pixel-centre points in order) into a Bézier subpath: the
/// points within `polygon_tol` of it are dropped (Douglas–Peucker), then curves are fitted. A
/// `closed` line runs back to its first point.
pub(crate) fn fit_polyline(pts: &[Point], closed: bool, o: &FitOptions) -> Option<SubPath> {
let n = pts.len();
let first = *pts.first()?;
if n < 2 {
return None;
}
let mut ext = pts.to_vec();
let mut keep = vec![false; n + 1];
keep[0] = true;
if closed {
// Split the ring at its first point and the point farthest from it.
ext.push(first);
let far = (1..n).max_by(|&i, &j| pts[i].distance_squared(first).total_cmp(&pts[j].distance_squared(first))).unwrap_or(n / 2);
keep[far] = true;
rdp(&ext, 0, far, o.polygon_tol, &mut keep);
rdp(&ext, far, n, o.polygon_tol, &mut keep);
} else {
keep[n - 1] = true;
rdp(&ext, 0, n - 1, o.polygon_tol, &mut keep);
}
let mut poly: Vec<Point> = (0..n).filter(|&i| keep[i]).map(|i| pts[i]).collect();
if closed && poly.len() < 3 {
poly = pts.to_vec();
}
if poly.len() < if closed { 3 } else { 2 } {
return None;
}
let sp = SubPath::polyline(&poly, closed);
let fitted =
simplify_with(&PathData::single(sp), &SimplifyOptions { tolerance: o.fit_tol, corner_angle_deg: o.corner_angle, straight_lines: false });
let mut sp = fitted.subpaths.into_iter().next()?;
if sp.anchors.len() < 2 {
return None;
}
if o.snap_lines {
snap_to_lines(&mut sp, (o.fit_tol * 2.0).max(1.5));
}
Some(sp)
}
/// Retract the handles of curves that stay within `tol` of their chord.
fn snap_to_lines(sp: &mut SubPath, tol: f64) {
let n = sp.anchors.len();
+94 -11
View File
@@ -4,8 +4,11 @@
//! and classic colour quantisation), not from any existing implementation:
//!
//! 1. **Quantise** the image into a small palette: a luminance threshold (Black and White), 1-D
//! k-means over the luminance histogram (Grayscale), or median cut followed by weighted
//! k-means over a 15-bit colour histogram (Color). Transparent pixels are left out.
//! k-means over the luminance histogram (Grayscale), or, in Color, over a 15-bit colour
//! histogram as the [`Palette`] asks: median cut to a colour count followed by weighted k-means
//! (Limited), median cut until every colour box is tight (Full Tone), one of those two by
//! whether the image is flat art (Automatic), or the most used colours of a swatch library
//! (Document Library). Transparent pixels are left out.
//! 2. **Remove noise**: 4-connected same-colour components smaller than `noise` pixels are merged
//! into their most common neighbouring colour.
//! 3. **Follow boundaries**: for each colour layer, the pixel-crack edges between inside and
@@ -18,10 +21,15 @@
//! 5. **Curves**: the polygon is fitted with cubic Béziers (`vectorcraft_pathops::simplify_with`,
//! least squares with corner detection); optionally nearly-straight curves snap to lines.
//!
//! With **Create: Strokes**, the parts of a colour layer no wider than the stroke width are traced
//! as stroked centre lines instead (see `centerline`); without Fills, wider parts become stroked
//! outlines.
//!
//! Colour layers are traced either *abutting* (each colour's own area; shapes share edges) or
//! *overlapping* (stacked: each layer also covers every layer above it, so no hairline gaps).
#![forbid(unsafe_code)]
mod centerline;
mod contour;
mod fit;
mod mosaic;
@@ -34,7 +42,7 @@ use vectorcraft_geom::PathData;
pub use contour::{Component, Loop, trace_mask};
pub use mosaic::mosaic;
pub use quantize::{Quantized, TRANSPARENT, denoise, quantize};
pub use quantize::{FULL_TONE_MAX, Quantized, TRANSPARENT, denoise, quantize};
/// Errors decoding a raster.
#[derive(Debug, thiserror::Error)]
@@ -132,6 +140,28 @@ pub enum Method {
Overlapping,
}
/// Where Color mode's colours come from (the Palette popup).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum Palette {
/// The `colors` colours that best represent the image.
#[default]
#[serde(alias = "Limited")]
Limited,
/// As many colours as the image's tones need, up to [`FULL_TONE_MAX`] (photos, gradients):
/// `color_detail` sets how close two colours may be and stay apart.
#[serde(alias = "Full Tone")]
FullTone,
/// Flat art (a few colours cover nearly all of it) traces with exactly those colours, anything
/// else as Full Tone.
#[serde(alias = "Automatic")]
Automatic,
/// The most used colours of a swatch library ([`TraceParams::swatches`]), at most `colors` of
/// them, exactly as they are.
#[serde(alias = "library", alias = "Document Library")]
DocumentLibrary,
}
/// Image Trace parameters (the Image Trace panel).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
@@ -139,8 +169,20 @@ pub struct TraceParams {
pub mode: Mode,
/// Black and White: pixels darker than this (luminance 0–255) are black.
pub threshold: u8,
/// Palette size for Color, number of grays for Grayscale (2–256).
/// Color: where the colours come from.
pub palette: Palette,
/// Palette size for Color (Limited; at most this many for Document Library), number of grays
/// for Grayscale (2–256).
pub colors: u32,
/// Full Tone and Automatic: how many colours, 0 (few) – 100 (many).
pub color_detail: f64,
/// Document Library: the swatch library, `"document"` (the document's swatches) or a library id
/// or name. The caller looks its colours up into `swatches`.
pub library: String,
/// Document Library: the library's colours (sRGB). Not saved: they are looked up from
/// `library` at every trace.
#[serde(skip)]
pub swatches: Vec<[u8; 3]>,
/// Paths (fidelity) 0–100: higher follows the pixels more tightly.
pub paths: f64,
/// Corners 0–100: higher keeps more corners.
@@ -152,6 +194,12 @@ pub struct TraceParams {
pub ignore_white: bool,
/// Replace nearly-straight curves with straight lines.
pub snap_curves_to_lines: bool,
/// Create: trace areas as filled shapes.
pub fills: bool,
/// Create: trace lines no wider than `stroke_width` as stroked centre lines.
pub strokes: bool,
/// Stroke: the widest feature (px) traced as a stroke.
pub stroke_width: f64,
}
impl Default for TraceParams {
@@ -160,13 +208,20 @@ impl Default for TraceParams {
Self {
mode: Mode::BlackAndWhite,
threshold: 128,
palette: Palette::Limited,
colors: 6,
color_detail: 50.0,
library: "document".into(),
swatches: vec![],
paths: 50.0,
corners: 75.0,
noise: 25,
method: Method::Abutting,
ignore_white: false,
snap_curves_to_lines: false,
fills: true,
strokes: false,
stroke_width: 10.0,
}
}
}
@@ -250,7 +305,8 @@ pub fn presets() -> Vec<(&'static str, TraceParams)> {
PRESET_NAMES.iter().filter_map(|n| Some((*n, preset(n)?))).collect()
}
/// One traced shape: an outer contour plus its holes, filled with `color`.
/// One traced shape: an outer contour plus its holes, filled with `color`, or (with `stroke`)
/// lines stroked with it.
#[derive(Clone, Debug, PartialEq)]
pub struct TracedPath {
/// In pixel coordinates (x right, y down; the image spans `0..width × 0..height`).
@@ -258,6 +314,9 @@ pub struct TracedPath {
pub color: [u8; 3],
/// Filled pixel count of the component the path came from.
pub pixels: usize,
/// Create Strokes: the path is stroked this wide (px), not filled (centre lines, or the
/// outlines of wider areas without Fills).
pub stroke: Option<f64>,
}
/// The traced result, bottom-most path first.
@@ -357,15 +416,37 @@ impl Layers<'_> {
let (params, opts) = (self.params, &self.opts);
let color = *self.q.palette.get(ci)?;
let overlapping = params.method == Method::Overlapping;
let (w, h) = (self.w, self.h);
// Create Strokes: this colour's lines, left out of its areas.
let (thin, lines) = if params.strokes {
centerline::lines(&self.q.labels, u16::try_from(ci).unwrap_or(TRANSPARENT), w, h, params.stroke_width, opts)
} else {
(vec![], vec![])
};
let mask: Vec<bool> = self
.q
.labels
.iter()
.map(|&l| l != TRANSPARENT && if overlapping { self.rank.get(l as usize).is_some_and(|&lr| lr >= r) } else { l as usize == ci })
.enumerate()
.map(|(i, &l)| {
l != TRANSPARENT
&& !thin.get(i).copied().unwrap_or(false)
&& if overlapping { self.rank.get(l as usize).is_some_and(|&lr| lr >= r) } else { l as usize == ci }
})
.collect();
// Without Fills, areas are outlined with a 1 px stroke.
let area_stroke = (params.strokes && !params.fills).then_some(1.0);
let min_hole = params.noise.max(1) as i64;
let mut paths = vec![];
for comp in trace_mask(&mask, self.w, self.h) {
let mut add = |path: PathData, pixels: usize, stroke: Option<f64>| {
let n = path.anchor_count();
if self.anchors.fetch_add(n, Ordering::Relaxed).saturating_add(n) > self.max_anchors {
return false;
}
paths.push(TracedPath { path, color, pixels, stroke });
true
};
for comp in trace_mask(&mask, w, h) {
let Some(outer) = fit::fit_loop(&comp.outer, opts) else { continue };
let mut subs = vec![outer];
for hole in &comp.holes {
@@ -374,12 +455,14 @@ impl Layers<'_> {
}
subs.extend(fit::fit_loop(hole, opts));
}
let path = PathData::new(subs);
let n = path.anchor_count();
if self.anchors.fetch_add(n, Ordering::Relaxed).saturating_add(n) > self.max_anchors {
if !add(PathData::new(subs), comp.pixels, area_stroke) {
return None;
}
}
for line in lines {
if !add(line.path, line.pixels, Some(line.width)) {
return None;
}
paths.push(TracedPath { path, color, pixels: comp.pixels });
}
Some(paths)
}
+113 -15
View File
@@ -1,6 +1,6 @@
//! Colour reduction and noise removal.
use crate::{Mode, Raster, TraceParams};
use crate::{Mode, Palette, Raster, TraceParams};
/// Label of a transparent (untraced) pixel.
pub const TRANSPARENT: u16 = u16::MAX;
@@ -67,10 +67,8 @@ pub fn quantize(img: &Raster, params: &TraceParams) -> Quantized {
b.sum[2] += p[2] as u64;
}
}
let used: Vec<(usize, [f64; 3], f64)> =
bins.iter().enumerate().filter(|(_, b)| b.n > 0).map(|(i, b)| (i, b.mean(), b.n as f64)).collect();
let k = params.colors.clamp(2, 256) as usize;
let centers = kmeans_rgb(&used, k);
let used: Vec<Used> = bins.iter().enumerate().filter(|(_, b)| b.n > 0).map(|(i, b)| (i, b.mean(), b.n as f64)).collect();
let centers = color_palette(&used, params);
let mut lut = vec![0u16; 1 << 15];
for (i, c, _) in &used {
lut[*i] = nearest_rgb(&centers, *c) as u16;
@@ -187,12 +185,108 @@ fn nearest_rgb(centers: &[[f64; 3]], c: [f64; 3]) -> usize {
best.1
}
/// Median cut for the initial palette, then weighted k-means refinement over histogram bins.
fn kmeans_rgb(used: &[(usize, [f64; 3], f64)], k: usize) -> Vec<[f64; 3]> {
/// The most colours Full Tone (and Automatic on continuous-tone images) makes.
pub const FULL_TONE_MAX: usize = 256;
/// A histogram bin in use: its index, mean colour and pixel count.
type Used = (usize, [f64; 3], f64);
/// Color mode's palette for the histogram bins `used`, as `params.palette` asks.
fn color_palette(used: &[Used], params: &TraceParams) -> Vec<[f64; 3]> {
let k = params.colors.clamp(2, 256) as usize;
let detail = (params.color_detail / 100.0).clamp(0.0, 1.0);
// Full Tone: split until no colour box is wider than 96 (few colours) … 8 (many) levels per
// channel, which is one histogram bin.
let full_tone = || refine(used, centers(&median_cut(used, FULL_TONE_MAX, 96.0 - 88.0 * detail)));
match params.palette {
Palette::Limited => kmeans_rgb(used, k),
Palette::FullTone => full_tone(),
Palette::Automatic => match flat_colors(used, detail) {
Some(n) => kmeans_rgb(used, n),
None => full_tone(),
},
Palette::DocumentLibrary if !params.swatches.is_empty() => library_colors(used, &params.swatches, k),
// No library colours to use: as Limited.
Palette::DocumentLibrary => kmeans_rgb(used, k),
}
}
/// Automatic: how many colours flat art is made of, or `None` for continuous tone (photos,
/// gradients). Flat art has most of its pixels in a few tight colours (anti-aliased edges and
/// noise aside): the bins holding 90% of the pixels are few, and each colour's pixels sit mostly
/// in one bin. `detail` (0–1) lets smaller colour areas count as colours of their own.
fn flat_colors(used: &[Used], detail: f64) -> Option<usize> {
let total: f64 = used.iter().map(|u| u.2).sum();
if total <= 0.0 {
return Some(2);
}
let mut by_count: Vec<&Used> = used.iter().collect();
by_count.sort_by(|a, b| b.2.total_cmp(&a.2));
let mut covered = 0.0;
let main = by_count
.iter()
.take_while(|u| {
let before = covered;
covered += u.2;
before < 0.9 * total
})
.count();
if main > FLAT_BINS {
return None;
}
let boxes = median_cut(used, 64, 24.0);
let min_share = (0.04 - 0.035 * detail) * total;
let colours: Vec<&ColorBox> = boxes.iter().filter(|b| b.weight >= min_share).collect();
let weight: f64 = colours.iter().map(|b| b.weight).sum();
let peaks: f64 = colours.iter().map(|b| b.peak).sum();
(weight >= 0.9 * total && peaks >= 0.5 * weight && colours.len() <= 32).then_some(colours.len().max(2))
}
/// The most histogram bins flat art's main colours spread over (a few bins per colour).
const FLAT_BINS: usize = 96;
/// Document Library: the `k` swatches (at most) that the most pixels are nearest to.
fn library_colors(used: &[Used], swatches: &[[u8; 3]], k: usize) -> Vec<[f64; 3]> {
let mut all: Vec<[f64; 3]> = vec![];
for s in swatches {
let c = s.map(f64::from);
if !all.contains(&c) {
all.push(c);
}
}
let mut weight = vec![0.0; all.len()];
for (_, c, n) in used {
if let Some(w) = weight.get_mut(nearest_rgb(&all, *c)) {
*w += n;
}
}
let mut order: Vec<usize> = (0..all.len()).collect();
order.sort_by(|a, b| weight[*b].total_cmp(&weight[*a]).then(a.cmp(b)));
order.into_iter().take(k.max(1)).filter_map(|i| all.get(i).copied()).collect()
}
/// A median-cut box: its weighted mean colour, pixel count and the pixel count of its heaviest bin.
struct ColorBox {
mean: [f64; 3],
weight: f64,
peak: f64,
}
fn centers(boxes: &[ColorBox]) -> Vec<[f64; 3]> {
boxes.iter().map(|b| b.mean).collect()
}
/// Median cut to `k` colours, then weighted k-means refinement over histogram bins.
fn kmeans_rgb(used: &[Used], k: usize) -> Vec<[f64; 3]> {
refine(used, centers(&median_cut(used, k, 0.0)))
}
/// Median cut: repeatedly split the box with the largest weighted extent, while there are fewer
/// than `k` boxes and some box spans more than `spread` levels of a channel.
fn median_cut(used: &[Used], k: usize, spread: f64) -> Vec<ColorBox> {
if used.is_empty() {
return vec![[255.0; 3]];
return vec![ColorBox { mean: [255.0; 3], weight: 0.0, peak: 0.0 }];
}
// Median cut: repeatedly split the box with the largest weighted extent.
let mut boxes: Vec<Vec<usize>> = vec![(0..used.len()).collect()];
while boxes.len() < k {
let mut best: Option<(f64, usize, usize)> = None;
@@ -210,7 +304,7 @@ fn kmeans_rgb(used: &[(usize, [f64; 3], f64)], k: usize) -> Vec<[f64; 3]> {
wsum += used[i].2;
}
let (ch, range) = (0..3).map(|c| (c, hi[c] - lo[c])).fold((0, -1.0), |a, b| if b.1 > a.1 { b } else { a });
if range <= 0.0 {
if range <= spread.max(0.0) {
continue;
}
let score = range * wsum.sqrt();
@@ -235,21 +329,25 @@ fn kmeans_rgb(used: &[(usize, [f64; 3], f64)], k: usize) -> Vec<[f64; 3]> {
boxes.push(b);
boxes.push(tail);
}
let mut centers: Vec<[f64; 3]> = boxes
boxes
.iter()
.map(|b| {
let mut s = [0.0; 3];
let mut w = 0.0;
let (mut w, mut peak) = (0.0, 0.0f64);
for &i in b {
for (acc, v) in s.iter_mut().zip(used[i].1) {
*acc += v * used[i].2;
}
w += used[i].2;
peak = peak.max(used[i].2);
}
[s[0] / w, s[1] / w, s[2] / w]
ColorBox { mean: [s[0] / w, s[1] / w, s[2] / w], weight: w, peak }
})
.collect();
// Lloyd refinement.
.collect()
}
/// Lloyd refinement of `centers` over the bins `used`.
fn refine(used: &[Used], mut centers: Vec<[f64; 3]>) -> Vec<[f64; 3]> {
for _ in 0..12 {
let mut sum = vec![[0.0; 3]; centers.len()];
let mut cnt = vec![0.0; centers.len()];
+204
View File
@@ -1,4 +1,5 @@
use super::*;
use vectorcraft_geom::Point;
const BLACK: [u8; 4] = [0, 0, 0, 255];
const WHITE: [u8; 4] = [255, 255, 255, 255];
@@ -348,3 +349,206 @@ fn an_image_too_large_to_trace_is_refused_before_decoding() {
assert!(matches!(err, TraceError::TooLarge { width: 30_000, height: 30_000, .. }), "{err}");
assert!(matches!(Raster::decode(&png_header(64, 64)), Err(TraceError::Decode(_))), "a small header goes on to decoding");
}
/// Four flat colours with anti-aliased (blended) edges between the quadrants.
fn flat_quads() -> Raster {
const C: [[u8; 3]; 4] = [[220, 30, 30], [30, 200, 40], [30, 40, 210], [240, 220, 20]];
Raster::from_fn(100, 100, |x, y| {
let at = |x: u32, y: u32| C[usize::from(x >= 50) + 2 * usize::from(y >= 50)];
let (a, b) = (at(x, y), at(x.saturating_sub(1), y.saturating_sub(1)));
// Blend the pixels along the quadrant edges, as an anti-aliased picture has them.
let c: Vec<u8> = a.iter().zip(b).map(|(p, q)| ((u16::from(*p) + u16::from(q)) / 2) as u8).collect();
[c[0], c[1], c[2], 255]
})
}
/// A smooth two-dimensional colour gradient (continuous tone).
fn gradient() -> Raster {
Raster::from_fn(128, 128, |x, y| [(x * 2) as u8, (y * 2) as u8, (255 - x - y / 2) as u8, 255])
}
fn palette(img: &Raster, palette: Palette, colors: u32, color_detail: f64) -> Vec<[u8; 3]> {
let p = TraceParams { mode: Mode::Color, palette, colors, color_detail, noise: 4, ..TraceParams::default() };
trace(img, &p).palette
}
#[test]
fn palettes_parse_from_their_ids_and_names() {
for (id, want) in [
("limited", Palette::Limited),
("fullTone", Palette::FullTone),
("Automatic", Palette::Automatic),
("documentLibrary", Palette::DocumentLibrary),
("library", Palette::DocumentLibrary),
] {
let p: TraceParams = serde_json::from_value(serde_json::json!({ "palette": id })).unwrap();
assert_eq!(p.palette, want, "{id}");
}
assert_eq!(TraceParams::default().palette, Palette::Limited);
// The library's colours are looked up at every trace, not saved with the settings.
let v = serde_json::to_value(TraceParams { swatches: vec![[1, 2, 3]], ..TraceParams::default() }).unwrap();
assert!(v.get("swatches").is_none() && v["library"] == "document" && v["colorDetail"] == 50.0, "{v}");
}
#[test]
fn full_tone_follows_the_tones_the_image_has() {
// Flat art keeps its few colours (and the tones of its blended edges); a gradient gets many,
// more with more detail.
let flat = palette(&flat_quads(), Palette::FullTone, 6, 50.0);
assert!((4..=10).contains(&flat.len()), "flat art: {flat:?}");
let few = palette(&gradient(), Palette::FullTone, 6, 10.0).len();
let many = palette(&gradient(), Palette::FullTone, 6, 90.0).len();
assert!(few > 6 && many > few && many <= FULL_TONE_MAX, "{few} then {many} colours");
}
#[test]
fn automatic_traces_flat_art_with_its_colours_and_photos_in_full_tone() {
let flat = palette(&flat_quads(), Palette::Automatic, 2, 50.0);
assert_eq!(flat.len(), 4, "the four flat colours, whatever `colors` says: {flat:?}");
assert!(flat.iter().any(|c| c[0] > 200 && c[1] < 60 && c[2] < 60), "red is one of them: {flat:?}");
let tone = palette(&gradient(), Palette::Automatic, 2, 50.0);
assert_eq!(tone.len(), palette(&gradient(), Palette::FullTone, 2, 50.0).len(), "continuous tone: as Full Tone");
}
#[test]
fn document_library_uses_the_most_used_swatches_exactly() {
let swatches = vec![[255, 0, 0], [0, 255, 0], [0, 0, 255], [255, 255, 0], [0, 0, 0], [255, 255, 255]];
let p = |colors| TraceParams {
mode: Mode::Color,
palette: Palette::DocumentLibrary,
colors,
swatches: swatches.clone(),
noise: 4,
..TraceParams::default()
};
let hard = Raster::from_fn(100, 100, |x, y| match (x < 50, y < 50) {
(true, true) => [220, 30, 30, 255],
(false, true) => [30, 200, 40, 255],
(true, false) => [30, 40, 210, 255],
(false, false) => [240, 220, 20, 255],
});
let res = trace(&hard, &p(6));
let mut got = res.palette.clone();
got.sort_unstable();
assert_eq!(got, [[0, 0, 255], [0, 255, 0], [255, 0, 0], [255, 255, 0]], "the nearest swatch of each colour, as it is");
assert!(res.paths.iter().all(|t| swatches.contains(&t.color)));
// At most `colors` of them: the ones the most pixels are nearest to.
let two = trace(&hard, &p(2)).palette;
assert!(two.len() <= 2 && two.iter().all(|c| swatches.contains(c)), "{two:?}");
// Without library colours, it traces as Limited.
let none = TraceParams { swatches: vec![], ..p(4) };
assert_eq!(trace(&hard, &none).palette.len(), 4);
}
fn strokes(fills: bool) -> TraceParams {
TraceParams { strokes: true, fills, stroke_width: 6.0, noise: 4, ..bw() }
}
/// Endpoints (first and last anchor) of each open subpath of the stroked paths.
fn stroked(res: &TraceResult) -> Vec<(&TracedPath, &vectorcraft_geom::SubPath)> {
res.paths.iter().filter(|p| p.stroke.is_some()).flat_map(|p| p.path.subpaths.iter().map(move |s| (p, s))).collect()
}
#[test]
fn a_thin_line_traces_as_one_stroked_centre_line() {
// A 3 px wide diagonal line from (20, 20) to (180, 100).
let img = Raster::from_fn(200, 120, |x, y| {
let (px, py) = (x as f64 + 0.5, y as f64 + 0.5);
let t = (((px - 20.0) * 160.0 + (py - 20.0) * 80.0) / (160.0f64.powi(2) + 80.0f64.powi(2))).clamp(0.0, 1.0);
let (cx, cy) = (20.0 + 160.0 * t, 20.0 + 80.0 * t);
if (px - cx).hypot(py - cy) <= 1.5 { BLACK } else { WHITE }
});
let res = trace(&img, &strokes(true));
assert_eq!(res.paths.len(), 1, "{:?}", res.paths.iter().map(|p| p.stroke).collect::<Vec<_>>());
let p = &res.paths[0];
let width = p.stroke.expect("stroked");
assert!((2.0..=4.0).contains(&width), "width {width}");
assert_eq!(p.path.subpaths.len(), 1);
let sp = &p.path.subpaths[0];
assert!(!sp.closed);
let (a, b) = (sp.anchors[0].p, sp.anchors[sp.anchors.len() - 1].p);
let (a, b) = if a.x < b.x { (a, b) } else { (b, a) };
assert!(a.distance(Point::new(20.0, 20.0)) < 3.0 && b.distance(Point::new(180.0, 100.0)) < 3.0, "{a:?} … {b:?}");
// A straight line: a few anchors, all on it.
assert!(sp.anchors.len() <= 4, "{} anchors", sp.anchors.len());
// Without Create Strokes, the same line is a filled outline.
let filled = trace(&img, &bw());
assert!(filled.paths.iter().all(|p| p.stroke.is_none()) && filled.paths[0].path.subpaths[0].closed);
}
#[test]
fn a_thin_ring_traces_as_a_closed_centre_line() {
let img = Raster::from_fn(120, 120, |x, y| {
let d = (x as f64 + 0.5 - 60.0).hypot(y as f64 + 0.5 - 60.0);
if (d - 40.0).abs() <= 1.5 { BLACK } else { WHITE }
});
let res = trace(&img, &strokes(true));
let lines = stroked(&res);
assert_eq!(lines.len(), 1, "one ring");
let sp = lines[0].1;
assert!(sp.closed);
let len = PathData::single(sp.clone()).length();
let want = std::f64::consts::TAU * 40.0;
assert!((len - want).abs() / want < 0.05, "length {len} vs {want}");
}
#[test]
fn wide_areas_stay_filled_and_lines_cross_at_junctions() {
// A disc (r = 20) and, apart from it, a plus sign of 3 px wide bars.
let img = Raster::from_fn(200, 100, |x, y| {
let (px, py) = (x as f64 + 0.5, y as f64 + 0.5);
let disc = (px - 50.0).hypot(py - 50.0) <= 20.0;
let plus = ((px - 150.0).abs() <= 1.5 && (20.0..=80.0).contains(&py)) || ((py - 50.0).abs() <= 1.5 && (120.0..=180.0).contains(&px));
if disc || plus { BLACK } else { WHITE }
});
let res = trace(&img, &strokes(true));
let fills: Vec<_> = res.paths.iter().filter(|p| p.stroke.is_none()).collect();
assert_eq!(fills.len(), 1, "the disc");
let a = net_area(&fills[0].path);
assert!((a - std::f64::consts::PI * 400.0).abs() < 60.0, "disc area {a}");
let lines = stroked(&res);
assert!((2..=4).contains(&lines.len()), "{} centre lines", lines.len());
// The centre lines stop about half a width short of each end of the bars (their round caps
// cover it).
let total: f64 = lines.iter().map(|(_, s)| PathData::single((*s).clone()).length()).sum();
assert!((106.0..=120.0).contains(&total), "both bars' length: {total}");
let ends: Vec<Point> = lines.iter().flat_map(|(_, s)| [s.anchors[0].p, s.anchors[s.anchors.len() - 1].p]).collect();
for want in [Point::new(150.0, 20.0), Point::new(150.0, 80.0), Point::new(120.0, 50.0), Point::new(180.0, 50.0)] {
assert!(ends.iter().any(|e| e.distance(want) < 4.0), "a line ends near {want:?}: {ends:?}");
}
// Strokes only: the disc is outlined.
let res = trace(&img, &strokes(false));
assert!(res.paths.iter().all(|p| p.stroke.is_some()));
assert!(res.paths.iter().any(|p| p.stroke == Some(1.0) && p.path.subpaths[0].closed), "the disc's outline");
}
#[test]
fn create_settings_parse_with_defaults() {
let p: TraceParams = serde_json::from_value(serde_json::json!({ "strokes": true, "strokeWidth": 4 })).unwrap();
assert!(p.fills && p.strokes && p.stroke_width == 4.0);
let d = TraceParams::default();
assert!(d.fills && !d.strokes && d.stroke_width == 10.0);
}
#[test]
fn create_strokes_survives_noise_and_tiny_images() {
let mut seed = 0x9E37_79B9_7F4A_7C15u64;
let mut next = move || {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
seed
};
let noise: Vec<u8> = (0..120 * 120).flat_map(|_| if next() % 3 == 0 { BLACK } else { WHITE }).collect();
let noise = Raster::new(120, 120, noise);
for img in [noise, Raster::from_fn(1, 1, |_, _| BLACK), Raster::from_fn(3, 2, |x, _| if x == 1 { BLACK } else { WHITE })] {
for (fills, width) in [(true, 1.0), (false, 4.0), (true, 100.0)] {
for noise in [0, 1, 4] {
let p = TraceParams { strokes: true, fills, stroke_width: width, noise, ..TraceParams::default() };
for t in trace(&img, &p).paths {
assert!(t.stroke.is_none_or(|w| w.is_finite() && w >= 1.0), "{:?}", t.stroke);
}
}
}
}
}
+355 -46
View File
@@ -69,9 +69,17 @@ enum Drag {
center: Point,
middle: bool,
},
/// A Zoom tool drag without Animated Zoom: the area to zoom to.
ZoomBox {
start: Pos2,
},
/// A Zoom tool press with Animated Zoom ([`animated_zoom`]): dragged sideways it zooms about
/// `start`, held still (for `held` seconds so far) it zooms on, else it's a click.
ZoomScrub {
start: Pos2,
held: f32,
moved: bool,
},
RotateView {
start_angle: f64,
start_rot: f64,
@@ -218,6 +226,12 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
// Artwork raster.
let ppp = ui.ctx().pixels_per_point();
let (w, h) = ((rect.width() * ppp).round().max(1.0) as u32, (rect.height() * ppp).round().max(1.0) as u32);
// View › Pixel Preview: the art as it rasterizes, one pixel per point, while a document pixel
// is bigger than a screen pixel (below that the screen render already shows it).
let pixel = (app.ui.view.pixel_preview && v.zoom * ppp as f64 > 1.0).then(|| pixel_region(&xf)).flatten();
// File Handling › Display Bitmaps as Anti-aliased Images in Pixel Preview: off, images show
// their pixels as they rasterize, hard-edged.
let smooth_images = pixel.is_none() || app.session.prefs.anti_aliased_bitmaps;
let key = CacheKey {
doc: st.uid as usize,
revision: st.revision,
@@ -233,6 +247,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
rot: v.rotation,
anti_alias: app.session.prefs.anti_aliased_artwork,
placed: vectorcraft_render::placed_document::generation(),
pixel,
smooth_images,
};
// Placed documents' bitmaps are being made: draw again when they are ready.
if vectorcraft_render::placed_document::busy() {
@@ -248,16 +264,23 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
if let Some(done) = app.canvas.worker.as_mut().and_then(|w| w.poll())
&& done.key.doc == key.doc
{
upload(app, ui.ctx(), &done.img);
upload(app, ui.ctx(), &done.img, done.key.pixel.is_some());
app.canvas.key = Some(done.key);
app.perf.render_ms = done.ms;
app.canvas.last_ms = done.ms;
}
if app.canvas.key.as_ref() != Some(&key) || app.canvas.texture.is_none() {
let view = Affine::translate((w as f64 / 2.0, h as f64 / 2.0))
* Affine::rotate(v.rotation.to_radians())
* Affine::scale(v.zoom * ppp as f64)
* Affine::translate(-v.center.to_vec2());
let (w, h, view) = match pixel {
Some([x0, y0, x1, y1]) => ((x1 - x0) as u32, (y1 - y0) as u32, Affine::translate((-x0 as f64, -y0 as f64))),
None => (
w,
h,
Affine::translate((w as f64 / 2.0, h as f64 / 2.0))
* Affine::rotate(v.rotation.to_radians())
* Affine::scale(v.zoom * ppp as f64)
* Affine::translate(-v.center.to_vec2()),
),
};
let opts = vectorcraft_render::RenderOptions { outline: app.ui.view.outline, background: None, artboards: false, ..Default::default() };
let opts = vectorcraft_render::RenderOptions {
proof: vectorcraft_render::proof::active_proof(),
@@ -273,6 +296,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
// 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,
trace_views: true,
smooth_images,
..opts
};
// Light documents render synchronously (no lag vs overlays); heavy ones go to the worker.
@@ -284,7 +309,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
_ => {
let t0 = now_ms();
let img = app.canvas.renderer.render(&doc, w, h, view, &opts);
upload(app, ui.ctx(), &img);
upload(app, ui.ctx(), &img, pixel.is_some());
app.canvas.key = Some(key.clone());
app.perf.render_ms = now_ms() - t0;
app.canvas.last_ms = app.perf.render_ms;
@@ -293,14 +318,28 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
}
if let (Some(tex), Some(k)) = (&app.canvas.texture, &app.canvas.key)
&& k.doc == key.doc
&& (k.rot - v.rotation).abs() < 1e-9
{
// Reproject the last frame if it was rendered for a different view.
let old = Xf { rect, zoom: k.zoom, center: Point::new(k.cx, k.cy), rot: xf.rot };
let _ = k.rot;
let a = xf.to_screen(old.to_doc(rect.min));
let b = xf.to_screen(old.to_doc(rect.max));
painter.image(tex.id(), egui::Rect::from_min_max(a, b), egui::Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);
match k.pixel {
// Document pixels: placed over the document rect they cover, turning with the view.
Some([x0, y0, x1, y1]) => {
let q = xf.quad(Rect::new(x0 as f64, y0 as f64, x1 as f64, y1 as f64));
let mut mesh = egui::Mesh::with_texture(tex.id());
for (pos, uv) in q.into_iter().zip([pos2(0.0, 0.0), pos2(1.0, 0.0), pos2(1.0, 1.0), pos2(0.0, 1.0)]) {
mesh.vertices.push(egui::epaint::Vertex { pos, uv, color: Color32::WHITE });
}
mesh.add_triangle(0, 1, 2);
mesh.add_triangle(0, 2, 3);
painter.add(Shape::mesh(mesh));
}
None if (k.rot - v.rotation).abs() < 1e-9 => {
// Reproject the last frame if it was rendered for a different view.
let old = Xf { rect, zoom: k.zoom, center: Point::new(k.cx, k.cy), rot: xf.rot };
let a = xf.to_screen(old.to_doc(rect.min));
let b = xf.to_screen(old.to_doc(rect.max));
painter.image(tex.id(), egui::Rect::from_min_max(a, b), egui::Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);
}
None => {}
}
}
if let Some(look) = grid_look.filter(|_| !grids_in_back) {
grid(&painter, &xf, doc.grid.spacing, doc.grid.subdivisions, look);
@@ -412,15 +451,18 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
}
// Caps Lock gives precise (crosshair) cursors, like Illustrator; env opt-out for system cursors.
let custom = std::env::var_os("VECTORCRAFT_SYSTEM_CURSORS").is_none();
// User Interface › Scale Cursor Proportional to UI: the glyphs grow with UI Scaling;
// off, they keep their size.
let ui_scale = if app.session.prefs.scale_cursor_with_ui { 1.0 } else { ui.ctx().zoom_factor() };
match ui.input(|i| i.pointer.hover_pos()) {
// An OS cursor: the system moves it at once, where a painted one trails the pointer
// (#444). The system cursor stands in for cursors without a glyph.
Some(_) if custom && crate::cursors::OS_CURSORS => {
let ppp = ui.ctx().native_pixels_per_point().unwrap_or_else(|| ui.ctx().pixels_per_point());
let ppp = ui.ctx().pixels_per_point() / ui_scale;
ui.ctx().set_cursor_image(app.canvas.cursors.get(c, ppp));
cursor_icon(c)
}
Some(hp) if custom && crate::cursors::paint(&painter, c, hp) => egui::CursorIcon::None,
Some(hp) if custom && crate::cursors::paint(&painter, c, hp, 1.0 / ui_scale) => egui::CursorIcon::None,
_ => cursor_icon(c),
}
} else {
@@ -490,17 +532,15 @@ fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Response, rect:
prev.is_some_and(|prev| prev != m)
});
// Zoom around the pointer, or scroll ([`wheel`]).
// Zoom around the pointer, and scroll ([`wheel`]): fingers pinching on a touch screen may also
// slide.
if resp.hovered() {
if (factor - 1.0).abs() > 1e-6 {
if let (Some(p), Some(vm)) = (hover, app.view_mut()) {
let before = xf.to_doc(p);
vm.zoom = (vm.zoom * factor).clamp(0.0313, 640.0);
let nx = Xf { rect, zoom: vm.zoom, center: vm.center, rot: vm.rotation.to_radians() };
let after = nx.to_doc(p);
vm.center += before - after;
}
} else if scroll != egui::Vec2::ZERO
if (factor - 1.0).abs() > 1e-6
&& let (Some(p), Some(vm)) = (hover, app.view_mut())
{
zoom_about(vm, rect, p, vm.zoom * factor);
}
if scroll != egui::Vec2::ZERO
&& let Some(vm) = app.view_mut()
{
let d = Xf { rect, zoom: vm.zoom, center: vm.center, rot: vm.rotation.to_radians() }.delta_to_doc(scroll);
@@ -524,7 +564,7 @@ fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Response, rect:
ui.ctx().memory_mut(|mem| mem.stop_text_input());
app.ui.flyout = None;
let d = if zoom_mode {
Drag::ZoomBox { start: p }
if animated_zoom(&app.session.prefs) { Drag::ZoomScrub { start: p, held: 0.0, moved: false } } else { Drag::ZoomBox { start: p } }
} else if pan_mode {
Drag::Pan { start: p, center: v.center, middle: false }
} else if tool == "rotateView" {
@@ -571,7 +611,26 @@ fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Response, rect:
vm.rotation = vectorcraft_geom::normalize_deg(deg);
}
}
Drag::ZoomBox { .. } | Drag::Art | Drag::Gesture => {}
Drag::ZoomBox { start } => marquee(ui.painter(), egui::Rect::from_two_pos(start, p)),
Drag::ZoomScrub { start, held, moved } => {
let dt = ui.input(|i| i.unstable_dt).min(0.25);
let (held, moved) = (held + dt, moved || (p - start).length() > SCRUB_SLOP);
// Dragged sideways it zooms with the pointer, held still it zooms on (Alt: out).
let exponent = if moved {
f64::from(pointer.delta().x) * SCRUB_ZOOM
} else if held > HOLD_DELAY {
f64::from(dt) * HOLD_ZOOM * if m.alt { -1.0 } else { 1.0 }
} else {
0.0
};
if exponent != 0.0
&& let Some(vm) = app.view_mut()
{
zoom_about(vm, rect, start, vm.zoom * exponent.exp());
}
ui.data_mut(|dd| dd.insert_temp(drag_id(), Drag::ZoomScrub { start, held, moved }));
}
Drag::Art | Drag::Gesture => {}
Drag::Tool if drag_art_out(app, ui, resp, p, view) => {
ui.data_mut(|dd| dd.insert_temp(drag_id(), Drag::Art));
}
@@ -604,13 +663,17 @@ fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Response, rect:
vm.center = Point::new((a.x + b.x) / 2.0, (a.y + b.y) / 2.0);
vm.zoom = (rect.width() as f64 / (b.x - a.x)).min(rect.height() as f64 / (b.y - a.y)).clamp(0.0313, 640.0);
} else {
let before = xf.to_doc(p);
vm.zoom = crate::state::next_zoom(vm.zoom, !m.alt);
let nx = Xf { rect, zoom: vm.zoom, center: vm.center, rot: vm.rotation.to_radians() };
vm.center += before - nx.to_doc(p);
zoom_about(vm, rect, p, crate::state::next_zoom(vm.zoom, !m.alt));
}
}
}
// A click (not held, not dragged) steps the zoom as with the marquee.
Drag::ZoomScrub { held, moved: false, .. } if held <= HOLD_DELAY => {
if let Some(vm) = app.view_mut() {
zoom_about(vm, rect, p, crate::state::next_zoom(vm.zoom, !m.alt));
}
}
Drag::ZoomScrub { .. } => {}
Drag::Tool => {
let ev = PointerEvent { kind: PointerKind::Up, pos: xf.to_doc(p), mods: mods(m, space), pressure: pen_pressure(ui, false) };
dispatch(app, &ev, view);
@@ -646,14 +709,46 @@ fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Response, rect:
/// How much one point of wheel motion zooms (as `exp(points × WHEEL_ZOOM)`).
const WHEEL_ZOOM: f64 = 0.01;
/// Animated Zoom: how much one point of sideways drag zooms (100 points to the right double it).
const SCRUB_ZOOM: f64 = std::f64::consts::LN_2 / 100.0;
/// Animated Zoom: how far the pointer moves before a press is a drag, in points.
const SCRUB_SLOP: f32 = 3.0;
/// Animated Zoom: how long a press is held still before it zooms on, in seconds…
const HOLD_DELAY: f32 = 0.3;
/// …and how fast it zooms then (as `exp(seconds × HOLD_ZOOM)`: twice as close each second).
const HOLD_ZOOM: f64 = std::f64::consts::LN_2;
/// What the wheel and a pinch did over the canvas this frame: a zoom factor (about the pointer)
/// and a scroll (screen points the content moves). The wheel scrolls, Cmd- and Alt-wheel (Option
/// Performance › Animated Zoom, which needs GPU Performance as in Illustrator: the Zoom tool zooms
/// as it is dragged sideways or held, instead of zooming to the area dragged across.
pub(crate) fn animated_zoom(p: &vectorcraft_engine::Prefs) -> bool {
p.animated_zoom && p.gpu_performance
}
/// Zoom view `vm` of the canvas `rect` to `zoom` (clamped to the zoom range), keeping the document
/// point under screen point `p` where it is.
fn zoom_about(vm: &mut View, rect: egui::Rect, p: Pos2, zoom: f64) {
let before = Xf::new(rect, vm).to_doc(p);
vm.zoom = zoom.clamp(0.0313, 640.0);
vm.center += before - Xf::new(rect, vm).to_doc(p);
}
/// A dashed marquee around screen rectangle `r`.
fn marquee(p: &egui::Painter, r: egui::Rect) {
let pts = [r.left_top(), r.right_top(), r.right_bottom(), r.left_bottom(), r.left_top()];
for w in pts.windows(2) {
p.extend(Shape::dashed_line(&[w[0], w[1]], Stroke::new(1.0, Color32::from_gray(90)), 3.0, 3.0));
}
}
/// What the wheel, a pinch and a two-finger drag on a touch screen did over the canvas this frame:
/// a zoom factor (about the pointer) and a scroll (screen points the content moves). The wheel scrolls, Cmd- and Alt-wheel (Option
/// on the Mac) zoom. With General › Zoom with Mouse Wheel (`wheel_zooms`) the wheel and Alt-wheel
/// zoom, Shift-wheel scrolls up and down and Cmd/Ctrl-wheel sideways. `line` and `page`: points
/// per wheel line and page. `alt_turn`: the last wheel turn was an Alt-wheel one (kept by the
/// caller across frames).
fn wheel(i: &egui::InputState, wheel_zooms: bool, line: f32, page: f32, alt_turn: &mut bool) -> (f64, egui::Vec2) {
// Fingers on a touch screen pan the content with them (a trackpad sends scrolls instead).
let pan = i.multi_touch().map_or(egui::Vec2::ZERO, |t| t.translation_delta);
if !wheel_zooms {
// egui makes Cmd-wheel (and a pinch) its zoom and the rest a scroll it spreads over a few
// frames: the rest of an Alt-wheel turn zooms too, however soon Alt is let go.
@@ -662,14 +757,14 @@ fn wheel(i: &egui::InputState, wheel_zooms: bool, line: f32, page: f32, alt_turn
}
let (zoom, scroll) = (f64::from(i.zoom_delta()), i.smooth_scroll_delta);
return if *alt_turn && scroll != egui::Vec2::ZERO {
(zoom * (f64::from(scroll.x + scroll.y) * WHEEL_ZOOM).exp(), egui::Vec2::ZERO)
(zoom * (f64::from(scroll.x + scroll.y) * WHEEL_ZOOM).exp(), pan)
} else {
(zoom, scroll)
(zoom, scroll + pan)
};
}
// The wheel events themselves: egui's own handling turns Cmd-wheel into a zoom.
let mut zoom = i.multi_touch().map_or(1.0, |t| f64::from(t.zoom_delta));
let mut scroll = egui::Vec2::ZERO;
let mut scroll = pan;
for e in &i.events {
match e {
egui::Event::MouseWheel { unit, delta, modifiers, .. } => {
@@ -1605,13 +1700,7 @@ fn names_an_artboard(text: &str) -> bool {
fn draw_overlays(p: &egui::Painter, xf: &Xf, overlays: &[Overlay], t: &Tokens, look: HandleLook) {
for o in overlays {
match o {
Overlay::Marquee(r) => {
let sr = xf.rect_to_screen(*r);
let pts = [sr.left_top(), sr.right_top(), sr.right_bottom(), sr.left_bottom(), sr.left_top()];
for w in pts.windows(2) {
p.extend(Shape::dashed_line(&[w[0], w[1]], Stroke::new(1.0, Color32::from_gray(90)), 3.0, 3.0));
}
}
Overlay::Marquee(r) => marquee(p, xf.rect_to_screen(*r)),
Overlay::Path { path, color, width, dashed } => {
let s = Stroke::new(*width, c32(*color));
if *dashed {
@@ -1693,6 +1782,7 @@ fn home(app: &mut VectorcraftApp, ui: &mut Ui, rect: egui::Rect) {
app.run("file.open", json!({})).ok();
}
});
recent(app, ui);
ui.add_space(28.0);
ui.label(egui::RichText::new(tl!("Quickly start a new file")).font(theme::semibold(14.0)).color(t.text));
ui.add_space(10.0);
@@ -1713,18 +1803,64 @@ fn home(app: &mut VectorcraftApp, ui: &mut Ui, rect: egui::Rect) {
crate::community::links(app, ui);
}
/// The Home screen's Recent Files (#663): the first of File › Open Recent Files, each its name and
/// folder; a click opens it. Nothing when there are none.
fn recent(app: &mut VectorcraftApp, ui: &mut Ui) {
const SHOWN: usize = 6;
let files: Vec<String> = crate::io::recent_files(app).iter().take(SHOWN).cloned().collect();
if files.is_empty() {
return;
}
let t = Tokens::get(ui.ctx());
ui.add_space(28.0);
ui.label(egui::RichText::new(tl!("Recent Files")).font(theme::semibold(14.0)).color(t.text));
ui.add_space(8.0);
for path in files {
let p = std::path::Path::new(&path);
let name = p.file_name().map_or_else(|| path.clone(), |n| n.to_string_lossy().into_owned());
let folder = p.parent().map(|f| f.to_string_lossy().into_owned()).unwrap_or_default();
ui.horizontal(|ui| {
crate::icons::icon(ui, "history", 16.0, t.icon);
let r = ui.add(egui::Button::new(egui::RichText::new(&name).color(t.accent).size(13.0)).frame(false)).on_hover_text(&path);
ui.add(egui::Label::new(egui::RichText::new(&folder).size(12.0).color(t.text_dim)).truncate());
if r.clicked()
&& let Err(e) = crate::io::open_path(app, &path)
{
app.status(e);
}
});
}
}
fn kurbo_flatten(p: &BezPath, tol: f64, f: &mut impl FnMut(PathEl)) {
vectorcraft_geom::kurbo::flatten(p.elements().iter().copied(), tol, f);
}
fn upload(app: &mut VectorcraftApp, ctx: &egui::Context, img: &vectorcraft_render::Rendered) {
/// Upload the art's raster; Pixel Preview's document pixels keep hard edges when magnified.
fn upload(app: &mut VectorcraftApp, ctx: &egui::Context, img: &vectorcraft_render::Rendered, pixel: bool) {
let color = egui::ColorImage::from_rgba_premultiplied([img.width as usize, img.height as usize], &img.pixels);
let options = if pixel { egui::TextureOptions::NEAREST } else { egui::TextureOptions::LINEAR };
match &mut app.canvas.texture {
Some(tex) => tex.set(color, egui::TextureOptions::LINEAR),
None => app.canvas.texture = Some(ctx.load_texture("canvas", color, egui::TextureOptions::LINEAR)),
Some(tex) => tex.set(color, options),
None => app.canvas.texture = Some(ctx.load_texture("canvas", color, options)),
}
}
/// Pixel Preview: the whole document pixels (x0, y0, x1, y1) under the canvas, rotated view
/// included. None when the view is degenerate.
fn pixel_region(xf: &Xf) -> Option<[i64; 4]> {
let r = xf.rect;
let corners = [r.left_top(), r.right_top(), r.right_bottom(), r.left_bottom()].map(|p| xf.to_doc(p));
let (mut x0, mut y0, mut x1, mut y1) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
for p in corners {
(x0, y0, x1, y1) = (x0.min(p.x), y0.min(p.y), x1.max(p.x), y1.max(p.y));
}
let (x0, y0, x1, y1) = (x0.floor(), y0.floor(), x1.ceil(), y1.ceil());
// A document pixel is bigger than a screen pixel here, so the region is about canvas-sized.
let ok = [x0, y0, x1, y1].iter().all(|c| c.is_finite() && c.abs() < 1e9) && x1 > x0 && y1 > y0 && x1 - x0 <= 16384.0 && y1 - y0 <= 16384.0;
ok.then_some([x0 as i64, y0 as i64, x1 as i64, y1 as i64])
}
/// The Contextual Task Bar's area.
fn task_bar_id() -> egui::Id {
egui::Id::new("task-bar")
@@ -2249,6 +2385,56 @@ mod tests {
(v, out.textures_delta)
}
/// View › Pixel Preview: magnified, the art shows as the document pixels it rasterizes to (one
/// per point, hard-edged), not as smooth vectors; zoomed out or out of Pixel Preview the canvas
/// renders for the screen again.
#[test]
fn pixel_preview_shows_the_document_pixels() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
// Its 1 pt stroke covers a quarter of document pixel 99 and most of pixel 100.
app.session.execute("shape.rectangle", &json!({"x": 100.25, "y": 50, "width": 200, "height": 200})).unwrap();
app.canvas.worker_started = true; // render on this thread
let ctx = egui::Context::default();
// The art's raster uploaded by one frame: (width, height, hard-edged, pixels).
let upload = |app: &mut VectorcraftApp| {
let (_, mut delta) = frame_output(app, &ctx);
let art = app.canvas.texture.as_ref().unwrap().id();
let up = delta.set.iter().find(|e| e.0.eq(&art)).and_then(|e| e.1.last()).map(|d| {
let egui::ImageData::Color(img) = &d.image;
(img.width(), img.height(), d.options.magnification == egui::TextureFilter::Nearest, img.pixels.clone())
});
delta.clear();
up.expect("the art re-rendered")
};
let screen = upload(&mut app); // the first frame fits the view to the artboard
assert!(screen.0 > 600 && !screen.2, "out of Pixel Preview: the screen's pixels, smoothed");
app.ui.view.pixel_preview = true;
let view = app.view_mut().unwrap();
(view.zoom, view.center) = (8.0, Point::new(100.0, 150.0));
let (w, h, hard, px) = upload(&mut app);
assert!(hard, "hard-edged pixels");
assert!(w <= screen.0 / 8 + 2 && h <= screen.1 / 8 + 2, "one pixel per point: {w} × {h}");
let [x0, y0, x1, y1] = app.canvas.key.as_ref().and_then(|k| k.pixel).expect("the pixels rendered");
assert_eq!(((x1 - x0) as usize, (y1 - y0) as usize), (w, h));
// Each document pixel is one texel, anti-aliased by how much of it the art covers.
let alpha = |x: i64| px[((150 - y0) * w as i64 + x - x0) as usize].a();
assert!((40..=90).contains(&alpha(99)), "a quarter of pixel 99: {}", alpha(99));
assert!(alpha(100) > 200, "most of pixel 100: {}", alpha(100));
assert_eq!((alpha(98), alpha(101)), (0, 255));
// The pixels are placed over the document rect they cover.
let s = shapes(&mut app, &ctx);
let art = app.canvas.texture.as_ref().unwrap().id();
let Some(Shape::Mesh(mesh)) = s.iter().find(|s| matches!(s, Shape::Mesh(m) if m.texture_id == art)) else { panic!("the art") };
let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap());
let at = xf.to_screen(Point::new(x0 as f64, y0 as f64));
assert!((mesh.vertices[0].pos - at).length() < 0.01, "{:?} at {at:?}", mesh.vertices[0].pos);
// Zoomed out, a document pixel is no bigger than a screen pixel: rendered for the screen.
app.view_mut().unwrap().zoom = 0.5;
let (w, _, hard, _) = upload(&mut app);
assert!(w > 600 && !hard, "zoomed out: the screen's pixels");
}
/// General › Anti-aliased Artwork (#394): on (the default), the art's edges are smoothed on
/// screen; off, every pixel is either painted or not, and turning it either way re-renders.
#[test]
@@ -2283,6 +2469,28 @@ mod tests {
assert!(partial(&alphas(&mut app).expect("re-rendered")) > 50, "smooth again");
}
/// File Handling › Display Bitmaps as Anti-aliased Images in Pixel Preview (#394): off, Pixel
/// Preview draws images with each pixel taking its nearest image pixel; on, smoothly, as the
/// canvas always does out of Pixel Preview.
#[test]
fn pixel_preview_smooths_bitmaps_only_when_asked() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
app.canvas.worker_started = true; // render on this thread
let ctx = egui::Context::default();
let smooth = |app: &mut VectorcraftApp| {
let (_, mut delta) = frame_output(app, &ctx);
delta.clear();
app.canvas.key.as_ref().map(|k| k.smooth_images).unwrap()
};
assert!(smooth(&mut app), "out of Pixel Preview");
app.ui.view.pixel_preview = true;
app.view_mut().unwrap().zoom = 8.0;
assert!(!smooth(&mut app), "Pixel Preview, off by default");
app.run("prefs.set", json!({"key": "antiAliasedBitmaps", "value": true})).unwrap();
assert!(smooth(&mut app), "Pixel Preview, on");
}
/// Guides & Grid › Show Pixel Grid (Above 600% Zoom) (#394): in Pixel Preview at 600% zoom and
/// above, a line at every document pixel over the art; none below 600%, out of Pixel Preview,
/// or with the option off.
@@ -2565,6 +2773,107 @@ mod tests {
assert!((zoom - 1.0).abs() < 1e-9 && scroll.x < -1.0 && scroll.y == 0.0, "on: Cmd-wheel scrolls sideways ({zoom}, {scroll:?})");
}
/// Two fingers dragged together on a touch screen pan the canvas with them, under either
/// Zoom with Mouse Wheel setting, and draw nothing (#449).
#[test]
fn two_fingers_dragged_together_pan_the_canvas() {
for wheel_zooms in [false, true] {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
app.session.execute("prefs.set", &json!({"key": "zoomWithMouseWheel", "value": wheel_zooms})).unwrap();
app.select_tool("rectangle");
let ctx = egui::Context::default();
frame(&mut app, &ctx, vec![]);
let c = app.canvas_rect.unwrap().center();
let touch = |n: u64, phase, pos| egui::Event::Touch { device_id: egui::TouchDeviceId(1), id: egui::TouchId(n), phase, pos, force: None };
let fingers = |phase, d: egui::Vec2| vec![touch(1, phase, c - vec2(40.0, 0.0) + d), touch(2, phase, c + vec2(40.0, 0.0) + d)];
let before = *app.view().unwrap();
// egui-winit moves the pointer with the first finger, as here.
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(c - vec2(40.0, 0.0))]);
frame(&mut app, &ctx, fingers(egui::TouchPhase::Start, Vec2::ZERO));
for k in 1..=3 {
frame(&mut app, &ctx, fingers(egui::TouchPhase::Move, vec2(10.0, 8.0) * k as f32));
}
frame(&mut app, &ctx, fingers(egui::TouchPhase::End, vec2(30.0, 24.0)));
let after = *app.view().unwrap();
let moved = (after.center - before.center) * after.zoom;
assert!((after.zoom / before.zoom - 1.0).abs() < 1e-9, "no zoom: {wheel_zooms}");
assert!((moved.x + 30.0).abs() < 0.5 && (moved.y + 24.0).abs() < 0.5, "the content follows the fingers ({wheel_zooms}): {moved:?}");
assert_eq!(app.session.active().unwrap().doc.layers[0].children().unwrap().len(), 0, "nothing drawn");
}
}
/// Performance › Animated Zoom (#394): the Zoom tool dragged sideways zooms about where it was
/// pressed (right in, left out), held still it zooms on, and a click still steps. Off, or with
/// GPU Performance off, a drag zooms to the area dragged across.
#[test]
fn animated_zoom_scrubs_and_holds_else_the_zoom_tool_zooms_to_an_area() {
use egui::Event;
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
app.select_tool("zoom");
let ctx = egui::Context::default();
frame(&mut app, &ctx, vec![]);
let rect = app.canvas_rect.unwrap();
let at = rect.center() - vec2(100.0, 50.0);
let button = |pos, pressed| Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
// Press at `at`, move by `by` and hold for `frames` frames (a 60th of a second each), let go.
let press = |app: &mut VectorcraftApp, by: egui::Vec2, frames: usize| {
frame(app, &ctx, vec![Event::PointerMoved(at)]);
frame(app, &ctx, vec![button(at, true)]);
frame(app, &ctx, vec![Event::PointerMoved(at + by)]);
for _ in 0..frames {
frame(app, &ctx, vec![]);
}
frame(app, &ctx, vec![button(at + by, false)]);
};
let doc_at = |app: &VectorcraftApp, p: Pos2| Xf::new(rect, app.view().unwrap()).to_doc(p);
let pinned = doc_at(&app, at);
let z0 = app.view().unwrap().zoom;
press(&mut app, vec2(100.0, 0.0), 0);
let z1 = app.view().unwrap().zoom;
assert!((z1 / z0 - 2.0).abs() < 1e-6, "100 points right doubles the zoom: {z0} → {z1}");
assert!(doc_at(&app, at).distance(pinned) < 1e-6, "about the press");
press(&mut app, vec2(-100.0, 0.0), 0);
assert!((app.view().unwrap().zoom - z0).abs() < 1e-6, "and back to the left");
press(&mut app, vec2(0.0, 0.0), 0);
assert_eq!(app.view().unwrap().zoom, crate::state::next_zoom(z0, true), "a click steps");
let z2 = app.view().unwrap().zoom;
press(&mut app, vec2(0.0, 0.0), 40);
assert!(app.view().unwrap().zoom > z2 * 1.2, "held, it zooms on");
assert!(doc_at(&app, at).distance(pinned) < 1e-6, "about the press");
// Off (or without GPU Performance): the area dragged across fills the view.
for key in ["animatedZoom", "gpuPerformance"] {
app.run("prefs.reset", json!({})).unwrap();
app.run("prefs.set", json!({"key": key, "value": false})).unwrap();
app.view_mut().unwrap().zoom = z0;
press(&mut app, vec2(100.0, 50.0), 0);
let z = app.view().unwrap().zoom;
assert!((z - z0 * (rect.width() / 100.0).min(rect.height() / 50.0) as f64).abs() < 1e-6, "{key} off: {z0} → {z}");
}
}
/// User Interface › Large Tabs (#394): the document tabs are taller, so the canvas starts lower.
#[test]
fn large_tabs_make_the_document_tabs_taller() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
let canvas_top = |app: &mut VectorcraftApp| {
let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), ..Default::default() };
let mut out = ctx.run_ui(raw, |ui| {
crate::chrome::doc_tabs(app, ui);
show(app, ui);
});
out.textures_delta.clear();
app.canvas_rect.unwrap().top()
};
let small = canvas_top(&mut app);
app.run("prefs.set", json!({"key": "largeTabs", "value": true})).unwrap();
assert_eq!(canvas_top(&mut app) - small, 9.0, "44 points instead of 35");
}
#[test]
fn cmd_space_zooms_and_space_pans_whatever_the_tool() {
use egui::{Event, Modifiers};
+53 -6
View File
@@ -319,10 +319,12 @@ fn tab_title(d: &vectorcraft_engine::DocState, zoom: f64, outline: bool) -> Stri
format!("{}{} @ {} ({mode})", d.title(), if d.is_dirty() { "*" } else { "" }, zoom_label(zoom).replace('%', " %"))
}
/// Document tab strip: "Name* @ 66.67% (RGB/Preview)".
/// Document tab strip: "Name* @ 66.67% (RGB/Preview)". User Interface › Large Tabs makes the tabs
/// taller, with larger titles.
pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) {
let t = Tokens::get(ui.ctx());
let (strip, _) = ui.allocate_exact_size(vec2(ui.available_width(), 35.0), Sense::hover());
let (height, title_size) = if app.session.prefs.large_tabs { (44.0, 14.0) } else { (35.0, 12.5) };
let (strip, _) = ui.allocate_exact_size(vec2(ui.available_width(), height), Sense::hover());
ui.painter().rect_filled(strip, 0.0, t.tab_strip);
ui.painter().line_segment([strip.left_bottom(), strip.right_bottom()], Stroke::new(1.0, t.border));
let mut x = strip.left();
@@ -334,7 +336,7 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) {
let title = tab_title(d, zoom, app.ui.view.outline);
// On the Home screen no tab is the current one.
let is_active = Some(i) == active && app.ui.home.is_none();
let galley = ui.painter().layout_no_wrap(title, theme::semibold(12.5), if is_active { t.text_strong } else { t.text_dim });
let galley = ui.painter().layout_no_wrap(title, theme::semibold(title_size), if is_active { t.text_strong } else { t.text_dim });
let w = galley.size().x + 50.0;
let r = egui::Rect::from_min_size(egui::pos2(x, strip.top()), vec2(w, strip.height() - 1.0));
let resp = ui.interact(r, ui.id().with(("tab", i)), Sense::click());
@@ -517,6 +519,9 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) {
/// Contextual hint for the active tool: segments of (text, bold). Keys in bold segments are
/// written as shortcuts are ("Alt+Click"); [`hint_segments`] names them for the platform.
/// The hint of the Zoom tool with Performance › Animated Zoom on.
const ANIMATED_ZOOM_HINT: &str = "zoom.animated";
fn hint_for(tool: &str) -> Option<&'static [(&'static str, bool)]> {
Some(match tool {
"selection" => &[
@@ -588,6 +593,16 @@ fn hint_for(tool: &str) -> Option<&'static [(&'static str, bool)]> {
("Drag", true),
(" to zoom into an area", false),
],
ANIMATED_ZOOM_HINT => &[
("Click", true),
(" to zoom in | ", false),
("Alt+Click", true),
(" to zoom out | ", false),
("Drag", true),
(" right or left to zoom in or out | ", false),
("Hold", true),
(" to keep zooming", false),
],
"eyedropper" => &[
("Click", true),
(" an object to copy its attributes | ", false),
@@ -674,8 +689,8 @@ fn hint_for(tool: &str) -> Option<&'static [(&'static str, bool)]> {
/// can insist a complete language covers them.
pub fn hint_strings() -> Vec<&'static str> {
let mut v = Vec::new();
for tool in vectorcraft_tools::catalog::all_tools() {
for &(text, bold) in hint_for(tool.id).unwrap_or(&[]) {
for tool in vectorcraft_tools::catalog::all_tools().map(|t| t.id).chain([ANIMATED_ZOOM_HINT]) {
for &(text, bold) in hint_for(tool).unwrap_or(&[]) {
let text = if bold { text.rsplit_once('+').map_or(text, |(_, k)| k) } else { text };
if !text.is_empty() && !text.chars().all(|c| c.is_ascii_digit()) && !v.contains(&text) {
v.push(text);
@@ -729,7 +744,10 @@ pub fn hint_bar(app: &mut VectorcraftApp, ui: &mut Ui) {
ui.painter().text(r.center(), egui::Align2::CENTER_CENTER, "?", theme::semibold(11.0), t.text);
ui.add_space(6.0);
let mut job = egui::text::LayoutJob::default();
for (txt, bold) in hint_segments(app.session.tool_id()) {
let tool = app.session.tool_id();
// The Zoom tool's drag zooms to an area, or with Animated Zoom zooms as it goes.
let hint = if tool == "zoom" && crate::canvas::animated_zoom(&app.session.prefs) { ANIMATED_ZOOM_HINT } else { tool };
for (txt, bold) in hint_segments(hint) {
let font = if bold { theme::semibold(12.5) } else { egui::FontId::proportional(12.5) };
job.append(&txt, 0.0, egui::TextFormat { font_id: font, color: if bold { t.text_strong } else { t.text }, ..Default::default() });
}
@@ -832,4 +850,33 @@ mod tests {
s.execute("transparency.stopEditingOpacityMask", &json!({})).unwrap();
assert!(title(&s).ends_with("(RGB/Preview)"));
}
/// The Zoom tool's hint follows Performance › Animated Zoom (#394): a drag zooms as it goes,
/// or (off) zooms into the area dragged across.
#[test]
fn the_zoom_hint_follows_animated_zoom() {
fn texts(s: &egui::Shape, out: &mut String) {
match s {
egui::Shape::Text(t) => out.push_str(t.galley.text()),
egui::Shape::Vec(v) => v.iter().for_each(|s| texts(s, out)),
_ => {}
}
}
let mut app = crate::VectorcraftApp::new(Session::new(), Default::default());
app.select_tool("zoom");
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
let hint = |app: &mut crate::VectorcraftApp| {
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| super::hint_bar(app, ui));
out.textures_delta.clear();
let mut shown = String::new();
out.shapes.iter().for_each(|c| texts(&c.shape, &mut shown));
shown
};
let on = hint(&mut app);
assert!(on.contains(" right or left to zoom in or out") && on.contains("Hold"), "{on}");
app.run("prefs.set", json!({"key": "animatedZoom", "value": false})).unwrap();
let off = hint(&mut app);
assert!(off.contains(" to zoom into an area") && !off.contains("Hold"), "{off}");
}
}
+50 -4
View File
@@ -288,10 +288,19 @@ fn glyph(c: Cursor, p: Pos2) -> Option<Vec<Shape>> {
Some(std::mem::take(&mut ink.0))
}
/// Paint cursor `c` at `p` on the given (foreground) painter, where the window can't show it as an
/// OS cursor ([`OS_CURSORS`]). Returns false for cursors that stay system cursors.
pub fn paint(painter: &Painter, c: Cursor, p: Pos2) -> bool {
glyph(c, p).map(|shapes| painter.extend(shapes)).is_some()
/// Paint cursor `c` at `p`, `scale` times its size, on the given (foreground) painter, where the
/// window can't show it as an OS cursor ([`OS_CURSORS`]). Returns false for cursors that stay
/// system cursors.
pub fn paint(painter: &Painter, c: Cursor, p: Pos2, scale: f32) -> bool {
let place = egui::emath::TSTransform::new(p.to_vec2(), scale);
glyph(c, Pos2::ZERO)
.map(|shapes| {
painter.extend(shapes.into_iter().map(|mut s| {
s.transform(place);
s
}))
})
.is_some()
}
/// Does the window show the glyphs as OS cursors ([`Images`])? Not on macOS, which sizes a cursor
@@ -555,6 +564,43 @@ mod tests {
assert!(off.platform_output.cursor_image.is_none());
}
/// User Interface › Scale Cursor Proportional to UI (#394): off, the tool cursors keep their
/// size whatever the UI Scaling; on, they grow with it.
#[test]
fn tool_cursors_scale_with_the_ui_only_when_asked() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
app.run("prefs.set", json!({"key": "uiScaling", "value": 2.0})).unwrap();
let ctx = egui::Context::default();
for _ in 0..3 {
frame(&mut app, &ctx, vec![]);
}
assert_eq!(ctx.zoom_factor(), 2.0);
let over = app.canvas_rect.unwrap().center();
let shown =
|app: &mut VectorcraftApp, d: f32| frame(app, &ctx, vec![egui::Event::PointerMoved(over + vec2(d, 0.0))]).platform_output.cursor_image;
if OS_CURSORS {
assert_eq!(shown(&mut app, 0.0).unwrap(), app.canvas.cursors.get(Cursor::Arrow, 1.0).unwrap(), "off: its own size");
app.run("prefs.set", json!({"key": "scaleCursorWithUi", "value": true})).unwrap();
assert_eq!(shown(&mut app, 4.0).unwrap(), app.canvas.cursors.get(Cursor::Arrow, 2.0).unwrap(), "on: twice as big");
}
// Painted into the window (macOS, the web), the glyph is drawn at the scale asked for, its
// hotspot where the pointer is.
let painted = |scale: f32| {
let ctx = egui::Context::default();
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| {
let layer = egui::LayerId::new(egui::Order::Tooltip, egui::Id::new("probe"));
assert!(paint(&ui.ctx().layer_painter(layer), Cursor::Arrow, pos2(100.0, 100.0), scale));
});
out.textures_delta.clear();
out.textures_delta.clear();
out.shapes.iter().fold(egui::Rect::NOTHING, |r, c| r.union(c.shape.visual_bounding_rect()))
};
let (full, half) = (painted(1.0), painted(0.5));
assert!((half.height() * 2.0 - full.height()).abs() < 1.5 && full.height() > 15.0, "{full:?} {half:?}");
assert!(full.contains(pos2(100.0, 100.0)) && half.contains(pos2(100.0, 100.0)), "{full:?} {half:?}");
}
#[test]
fn arrow_hotspot_is_tip() {
let pts = arrow_points(pos2(10.0, 20.0));
+58 -17
View File
@@ -190,7 +190,7 @@ fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
ui.vertical(|ui| {
ui.set_width(640.0);
ui.set_min_height(HEIGHT - 32.0);
presets(app, ui, &mut d);
b.create |= presets(app, ui, &mut d);
});
});
egui::Frame::NONE.fill(t.panel_darker).inner_margin(egui::Margin::same(18)).show(ui, |ui| {
@@ -205,8 +205,9 @@ fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
b.finish(app, ctx, d);
}
/// The category tabs and the chosen category's preset cards.
fn presets(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) {
/// The category tabs and the chosen category's preset cards: a click chooses one, a double-click
/// also creates it (true then).
fn presets(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
let t = Tokens::get(ui.ctx());
let names: Vec<&str> = newdoc::category_names().collect();
let cat = names.iter().position(|n| n.eq_ignore_ascii_case(&d.str("category"))).unwrap_or(0);
@@ -227,20 +228,24 @@ fn presets(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) {
if list.is_empty() {
let hint = if cat == 1 { tl!("Presets you save with the Save Preset button appear here.") } else { tl!("Documents you create appear here.") };
ui.label(egui::RichText::new(hint).color(t.text_dim));
return;
return false;
}
let mut create = false;
egui::ScrollArea::vertical().id_salt(("newdoc-presets", cat)).max_height(HEIGHT - 110.0).auto_shrink([false, false]).show(ui, |ui| {
ui.horizontal_wrapped(|ui| {
ui.spacing_mut().item_spacing = egui::vec2(12.0, 12.0);
let (w, h, preset) = (d.f64("width", 0.0), d.f64("height", 0.0), d.str("preset"));
for s in &list {
let selected = d.fields.contains_key(APPLIED) && s.name == preset && s.width == w && s.height == h;
if preset_card(ui, s, selected).clicked() {
let card = preset_card(ui, s, selected);
if card.clicked() || card.double_clicked() {
apply(d, s);
}
create |= card.double_clicked();
}
});
});
create
}
/// Is `name` a built-in preset's? Those are ours (translated); Recent and Saved hold the names of
@@ -345,7 +350,7 @@ fn details(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, b: &mut
// Close and Create at the bottom right.
ui.add_space((HEIGHT - (ui.cursor().top() - top) - 28.0).max(12.0));
ui.allocate_ui_with_layout(egui::vec2(ui.available_width(), 28.0), egui::Layout::right_to_left(egui::Align::Center), |ui| {
b.create = widgets::primary_button(ui, tl!("Create")).clicked();
b.create |= widgets::primary_button(ui, tl!("Create")).clicked();
ui.add_space(8.0);
b.close = widgets::secondary_button(ui, tl!("Close")).clicked();
});
@@ -441,17 +446,8 @@ fn choice(ui: &mut egui::Ui, d: &mut Dialog, key: &str, options: &[(Value, Strin
/// The collapsible Advanced Options: Color Mode, Raster Effects and Preview Mode.
fn advanced(ui: &mut egui::Ui, d: &mut Dialog, label: f32, field: f32) {
let t = Tokens::get(ui.ctx());
let open = d.bool("advanced");
let resp = ui
.horizontal(|ui| {
let (r, _) = ui.allocate_exact_size(egui::vec2(14.0, 18.0), egui::Sense::hover());
crate::icons::paint(ui, if open { "chevron-down" } else { "chevron-right" }, r, t.icon);
ui.label(egui::RichText::new(tl!("Advanced Options")).color(t.text));
})
.response
.interact(egui::Sense::click());
if resp.clicked() {
if widgets::section_toggle(ui, tl!("Advanced Options"), open) {
d.fields.insert("advanced".into(), json!(!open));
}
if !open {
@@ -567,7 +563,7 @@ fn show_more(app: &mut VectorcraftApp, ctx: &egui::Context) {
ui.horizontal(|ui| {
templates = widgets::secondary_button(ui, tl!("Templates…")).on_hover_text(tl!("New from Template")).clicked();
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
b.create = widgets::primary_button(ui, tl!("Create Document")).clicked();
b.create |= widgets::primary_button(ui, tl!("Create Document")).clicked();
ui.add_space(8.0);
// Cancel goes back to New Document.
if widgets::secondary_button(ui, tl!("Cancel")).clicked() {
@@ -619,6 +615,51 @@ mod tests {
app.ui.dialog.as_ref().unwrap().fields.get(k).cloned().unwrap_or_default()
}
/// A double-click on a preset card creates the document from it (#663); a click only chooses it.
#[test]
fn a_double_clicked_preset_creates_the_document() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.newDialog", json!({})).unwrap();
set(&mut app, "category", json!("Mobile"));
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
// Frames 50 ms apart, so two clicks a frame apart make a double-click.
let mut time = 0.0;
let mut run = |app: &mut VectorcraftApp, events| {
time += 0.05;
let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 1000.0)));
let raw = egui::RawInput { screen_rect, events, time: Some(time), ..Default::default() };
let mut out = ctx.run_ui(raw, |ui| crate::dialogs::show(app, ui.ctx()));
out.textures_delta.clear();
out
};
run(&mut app, vec![]);
// The first card of the category, found by its size line.
let card = |app: &mut VectorcraftApp, run: &mut dyn FnMut(&mut VectorcraftApp, Vec<egui::Event>) -> egui::FullOutput| {
let out = run(app, vec![]);
let mut texts = vec![];
fn walk(s: &egui::Shape, out: &mut Vec<(String, egui::Rect)>) {
match s {
egui::Shape::Text(t) => out.push((t.galley.text().to_string(), t.visual_bounding_rect())),
egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, out)),
_ => {}
}
}
out.shapes.iter().for_each(|c| walk(&c.shape, &mut texts));
texts.into_iter().find(|(t, _)| t.starts_with("Phone 393")).map(|(_, r)| r.center()).unwrap()
};
let at = card(&mut app, &mut run);
let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
run(&mut app, vec![egui::Event::PointerMoved(at), press(true)]);
run(&mut app, vec![press(false)]);
assert!(app.ui.dialog.is_some() && app.session.documents().is_empty(), "a click only chooses it");
assert!(field(&app, "preset").as_str().is_some_and(|p| p == "Phone 393×852"), "{:?}", field(&app, "preset"));
run(&mut app, vec![press(true)]);
run(&mut app, vec![press(false)]);
assert!(app.ui.dialog.is_none(), "the double-click created it: {:?}", app.ui.status);
assert_eq!(app.session.documents().len(), 1);
}
#[test]
fn a_preset_fills_the_details_and_create_makes_the_document() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
+1
View File
@@ -151,6 +151,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
ui.ctx().data_mut(|d| {
d.insert_temp(column_left_id(), column.left());
d.insert_temp(floating::dock_rect_id(), dock);
d.insert_temp(floating::icons_rect_id(), column);
});
}
+39 -3
View File
@@ -70,6 +70,12 @@ pub(crate) fn dock_rect_id() -> Id {
}
/// The strip along the window's left edge where the Tools panel docks, as last laid out.
/// The icon column's bounds (egui temp memory, one frame old), where panels without a tab in the
/// tabbed group go back to when docked.
pub(crate) fn icons_rect_id() -> Id {
Id::new("floating-icons-rect")
}
pub(crate) fn tools_zone_id() -> Id {
Id::new("floating-tools-zone")
}
@@ -216,7 +222,13 @@ fn drop_target(app: &VectorcraftApp, ctx: &egui::Context, what: Moving, at: Pos2
return Some((Drop::Stack(first), head));
}
}
zone(dock_rect_id()).filter(|_| app.ui.dock && app.ui.screen_mode < 3).map(|r| (Drop::Dock, r))
let dock = zone(dock_rect_id()).filter(|_| app.ui.dock && app.ui.screen_mode < 3)?;
// Panels that aren't tabs of the tabbed group (or all of them, with it collapsed) go back to
// their icons: light up the icon column, where they land, rather than the tabs.
let tabbed = !app.ui.dock_collapsed
&& own.and_then(|i| app.ui.floating_panels.get(i)).is_some_and(|g| ids_of(g).into_iter().any(|p| DockTab::from_id(p).is_some()));
let lit = if tabbed { dock } else { ctx.data(|d| d.get_temp::<Rect>(icons_rect_id())).unwrap_or(dock) };
Some((Drop::Dock, lit))
}
/// Light up a drop zone: over the docked panels, under the floating ones (the moved one too).
@@ -262,7 +274,13 @@ pub fn track(app: &mut VectorcraftApp, ctx: &egui::Context) {
let ids = ids_of(g);
let active = ids.get(g.active).copied().unwrap_or(id);
match drop {
Drop::Dock => dock(&mut app.ui, &ids, active),
Drop::Dock => {
dock(&mut app.ui, &ids, active);
// One that went back to its icon pops out of it, so it doesn't seem to vanish.
if app.ui.dock_collapsed || DockTab::from_id(active).is_none() {
app.ui.open_panel = Some(active.to_string());
}
}
Drop::Stack(onto) => stack(&mut app.ui, &ids, active, onto),
}
}
@@ -607,7 +625,7 @@ mod tests {
h.hold(h.title("layers"), over);
assert!(h.group("layers").contains(over), "the group follows the pointer");
let target = drop_target(&h.app, &h.ctx, Moving::Panel("layers"), over);
assert_eq!(target.map(|t| t.0), Some(Drop::Dock), "the dock is the drop zone");
assert_eq!(target, Some((Drop::Dock, dock)), "the dock is the drop zone, lit whole: its tab comes back");
h.release(over);
assert!(h.groups().is_empty(), "docked: {:?}", h.groups());
assert_eq!((h.dock_tabs().len(), h.app.ui.dock_tab), (3, DockTab::Layers), "back in the dock, shown");
@@ -666,6 +684,24 @@ mod tests {
assert_eq!(h.icons().len(), count - 1, "Color is back in the column");
}
#[test]
fn a_panel_dropped_on_the_dock_lights_up_and_pops_out_of_its_icon() {
let mut h = Harness::new();
let count = h.icons().len();
h.drag(h.icons()[0].center(), pos2(500.0, 400.0));
assert_eq!(h.groups(), [["color"]]);
// Over the tabbed group: Color has no tab there, so the icon column lights up, not the tabs.
let (dock, column) = (h.temp_rect(dock_rect_id()), h.temp_rect(icons_rect_id()));
let over = h.dock_tabs()[1].center();
h.hold(h.title("color"), over);
assert_eq!(drop_target(&h.app, &h.ctx, Moving::Panel("color"), over), Some((Drop::Dock, column)));
assert!(column.width() < dock.width(), "the column, not the whole dock: {column:?} {dock:?}");
// Dropped, it's back in the column and pops out of its icon rather than vanishing.
h.release(over);
assert!(h.groups().is_empty());
assert_eq!((h.icons().len(), h.app.ui.open_panel.as_deref()), (count, Some("color")));
}
#[test]
fn a_popped_out_panel_dragged_by_its_title_floats() {
let mut h = Harness::new();
+18
View File
@@ -1152,6 +1152,11 @@
Ignore Ignorar
Ignore Artboards (all the art as one page) Ignorar mesas de trabajo (toda la ilustración como una página)
Ignore White Ignorar blanco
Palette: Paleta:
Limited Limitada
Full Tone Tono completo
Document Library Biblioteca del documento
Library: Biblioteca:
Image Imagen
Image Info Información de imagen
Image Map: Mapa de imagen:
@@ -1566,6 +1571,9 @@
No text selected No hay texto seleccionado
No Thumbnails Sin miniaturas
Noise Ruido
Create: Crear:
Fills Rellenos
Strokes Trazos
Nonbreaking Hyphen Guion de no separación
Nonbreaking Space Espacio de no separación
None Ninguno
@@ -2487,6 +2495,13 @@
Smooth Color Color suavizado
Smooth Tool Herramienta Suavizar
Snap Curves To Lines Ajustar curvas a líneas
View: Vista:
Tracing Result Resultado de calco
Tracing Result with Outlines Resultado de calco con contornos
Outlines Contornos
Outlines with Source Image Contornos con imagen de origen
Source Image Imagen de origen
Image Trace View Vista del calco de imagen
Snap Options Opciones de ajuste
Snap to Glyph Ajustar a glifo
Snap to Grid Ajustar a cuadrícula
@@ -2972,6 +2987,9 @@
to zoom in | para acercar |
to zoom out | para alejar |
to zoom into an area para acercar un área
Hold Mantener pulsado
right or left to zoom in or out | a la derecha o a la izquierda para acercar o alejar |
to keep zooming para seguir haciendo zoom
an object to copy its attributes | en un objeto para copiar sus atributos |
to apply the selection's to it | para aplicarle los de la selección |
to sample a color para muestrear un color
Can't render this file because it contains an unexpected character in line 2 and column 73.
+18
View File
@@ -1151,6 +1151,11 @@
Ignore Ignorer
Ignore Artboards (all the art as one page) Ignorer les plans de travail (toute l’illustration sur une page)
Ignore White Ignorer le blanc
Palette: Palette :
Limited Limitée
Full Tone Tons continus
Document Library Bibliothèque du document
Library: Bibliothèque :
Image Image
Image Info Informations sur l’image
Image Map: Image cliquable :
@@ -1563,6 +1568,9 @@
No text selected Aucun texte sélectionné
No Thumbnails Sans vignettes
Noise Bruit
Create: Créer :
Fills Fonds
Strokes Contours
Nonbreaking Hyphen Trait d’union insécable
Nonbreaking Space Espace insécable
None Aucun
@@ -2484,6 +2492,13 @@
Smooth Color Couleur lissée
Smooth Tool Outil Arrondi
Snap Curves To Lines Aimanter les courbes aux lignes
View: Affichage :
Tracing Result Résultat de la vectorisation
Tracing Result with Outlines Résultat de la vectorisation avec contours
Outlines Contours
Outlines with Source Image Contours avec l’image source
Source Image Image source
Image Trace View Affichage de la vectorisation de l’image
Snap Options Options de magnétisme
Snap to Glyph Aimanter au glyphe
Snap to Grid Aimanter à la grille
@@ -2969,6 +2984,9 @@
to zoom in | pour effectuer un zoom avant |
to zoom out | pour effectuer un zoom arrière |
to zoom into an area pour zoomer sur une zone
Hold Maintenir
right or left to zoom in or out | vers la droite ou la gauche pour effectuer un zoom avant ou arrière |
to keep zooming pour continuer le zoom
an object to copy its attributes | sur un objet pour copier ses attributs |
to apply the selection's to it | pour lui appliquer ceux de la sélection |
to sample a color pour prélever une couleur
Can't render this file because it contains an unexpected character in line 2 and column 73.
+18
View File
@@ -1151,6 +1151,11 @@
Ignore Ignora
Ignore Artboards (all the art as one page) Ignora tavole da disegno (tutta la grafica come una sola pagina)
Ignore White Ignora bianco
Palette: Palette:
Limited Limitata
Full Tone Tono continuo
Document Library Libreria del documento
Library: Libreria:
Image Immagine
Image Info Informazioni immagine
Image Map: Mappa immagine:
@@ -1566,6 +1571,9 @@
No text selected Nessun testo selezionato
No Thumbnails Nessuna miniatura
Noise Disturbo
Create: Crea:
Fills Riempimenti
Strokes Tracce
Nonbreaking Hyphen Trattino indivisibile
Nonbreaking Space Spazio indivisibile
None Nessuno
@@ -2487,6 +2495,13 @@
Smooth Color Colore graduale
Smooth Tool Strumento Smussa
Snap Curves To Lines Aggancia curve a linee
View: Vista:
Tracing Result Risultato ricalco
Tracing Result with Outlines Risultato ricalco con contorni
Outlines Contorni
Outlines with Source Image Contorni con immagine di origine
Source Image Immagine di origine
Image Trace View Vista del ricalco immagine
Snap Options Opzioni di aggancio
Snap to Glyph Aggancia a glifo
Snap to Grid Aggancia alla griglia
@@ -2972,6 +2987,9 @@
to zoom in | per ingrandire |
to zoom out | per ridurre |
to zoom into an area per ingrandire un'area
Hold Tieni premuto
right or left to zoom in or out | a destra o a sinistra per ingrandire o ridurre |
to keep zooming per continuare lo zoom
an object to copy its attributes | su un oggetto per copiarne gli attributi |
to apply the selection's to it | per applicargli quelli della selezione |
to sample a color per campionare un colore
Can't render this file because it contains an unexpected character in line 2 and column 73.
+18
View File
@@ -675,6 +675,9 @@
to transform | :変形 |
to zoom in | :拡大 |
to zoom into an area :範囲を拡大
Hold 長押し
right or left to zoom in or out | :右で拡大、左で縮小 |
to keep zooming :拡大または縮小し続ける
to zoom out | :縮小 |
while dragging to move perpendicular to the plane | :ドラッグ中に面と垂直に移動 |
(closest) (最も近い)
@@ -1410,6 +1413,11 @@
Ignore 無視
Ignore Artboards (all the art as one page) アートボードを無視 (すべてのアートを 1 ページとして扱う)
Ignore White 白を無視
Palette: パレット:
Limited 限定
Full Tone フルトーン
Document Library ドキュメントライブラリ
Library: ライブラリ:
Image Info 画像情報
Image Map: イメージマップ:
Image Size イメージサイズ
@@ -1696,6 +1704,9 @@
No symbols in this document このドキュメントにシンボルはありません
No text selected テキストが選択されていません
Noise ノイズ
Create: 作成:
Fills 塗り
Strokes 線
None なし
None. なし。
Normal 通常
@@ -2314,6 +2325,13 @@
Smooth スムーズ
Smooth Tool スムーズツール
Snap Curves To Lines 曲線を直線にスナップ
View: 表示:
Tracing Result トレース結果
Tracing Result with Outlines トレース結果(アウトライン付き)
Outlines アウトライン
Outlines with Source Image アウトライン(元画像付き)
Source Image 元画像
Image Trace View 画像トレースの表示
Snap Options スナップオプション
Snapping Tolerance スナップ許容値
Soft Light ソフトライト
Can't render this file because it contains an unexpected character in line 2 and column 73.
+3
View File
@@ -78,6 +78,9 @@
to transform | para transformar |
to zoom in | para ampliar |
to zoom into an area para ampliar uma área
Hold Manter pressionado
right or left to zoom in or out | para a direita ou a esquerda para ampliar ou reduzir |
to keep zooming para continuar o zoom
to zoom out | para reduzir |
while dragging to move perpendicular to the plane | ao arrastar para mover perpendicularmente ao plano |
(closest) (mais próximo)
Can't render this file because it contains an unexpected character in line 6 and column 47.
+18
View File
@@ -1149,6 +1149,11 @@
Ignore Игнорировать
Ignore Artboards (all the art as one page) Игнорировать монтажные области (весь рисунок как одна страница)
Ignore White Игнорировать белый
Palette: Палитра:
Limited Ограниченная
Full Tone Полутоновая
Document Library Библиотека документа
Library: Библиотека:
Image Изображение
Image Info Сведения об изображении
Image Map: Карта изображения:
@@ -1562,6 +1567,9 @@
No text selected Текст не выделен
No Thumbnails Без миниатюр
Noise Шум
Create: Создать:
Fills Заливки
Strokes Обводки
Nonbreaking Hyphen Неразрывный дефис
Nonbreaking Space Неразрывный пробел
None Нет
@@ -2483,6 +2491,13 @@
Smooth Color Сглаженный цвет
Smooth Tool Инструмент «Сглаживание»
Snap Curves To Lines Привязывать кривые к линиям
View: Просмотр:
Tracing Result Результат трассировки
Tracing Result with Outlines Результат трассировки с контурами
Outlines Контуры
Outlines with Source Image Контуры с исходным изображением
Source Image Исходное изображение
Image Trace View Просмотр трассировки изображения
Snap Options Параметры привязки
Snap to Glyph Привязать к глифу
Snap to Grid Привязать к сетке
@@ -2968,6 +2983,9 @@
to zoom in | для увеличения |
to zoom out | для уменьшения |
to zoom into an area для увеличения области
Hold Удерживать
right or left to zoom in or out | вправо или влево для увеличения или уменьшения |
to keep zooming для непрерывного масштабирования
an object to copy its attributes | в объект для копирования его атрибутов |
to apply the selection's to it | для применения атрибутов выделения к нему |
to sample a color для взятия образца цвета
Can't render this file because it contains an unexpected character in line 2 and column 73.
+18
View File
@@ -1140,6 +1140,11 @@
Ignore 忽略
Ignore Artboards (all the art as one page) 忽略画板 (所有图稿作为一页)
Ignore White 忽略白色
Palette: 调板:
Limited 有限
Full Tone 全色调
Document Library 文档库
Library: 库:
Image 图像
Image Info 图像信息
Image Map: 图像映射:
@@ -1541,6 +1546,9 @@
No text selected 未选择文字
No Thumbnails 无缩略图
Noise 杂色
Create: 创建:
Fills 填色
Strokes 描边
Nonbreaking Hyphen 不断行连字号
Nonbreaking Space 不断行空格
None 无
@@ -2424,6 +2432,13 @@
Smooth Color 平滑颜色
Smooth Tool 平滑工具
Snap Curves To Lines 将曲线对齐到直线
View: 视图:
Tracing Result 描摹结果
Tracing Result with Outlines 描摹结果(带轮廓)
Outlines 轮廓
Outlines with Source Image 轮廓(带源图像)
Source Image 源图像
Image Trace View 图像描摹视图
Snap Options 对齐选项
Snap to Glyph 靠齐字符
Snap to Grid 对齐网格
@@ -2912,6 +2927,9 @@
to zoom in | 以放大 |
to zoom out | 以缩小 |
to zoom into an area 以放大指定区域
Hold 按住
right or left to zoom in or out | 向右以放大、向左以缩小 |
to keep zooming 以持续缩放
an object to copy its attributes | 选择对象以复制其属性 |
to apply the selection's to it | 以将所选对象属性应用到它 |
to sample a color 以取样颜色
Can't render this file because it contains an unexpected character in line 2 and column 73.
+18
View File
@@ -1169,6 +1169,11 @@
Ignore 略過
Ignore Artboards (all the art as one page) 忽略工作區域 (所有圖稿視為單一頁面)
Ignore White 忽略白色
Palette: 調色盤:
Limited 有限
Full Tone 全色調
Document Library 文件資料庫
Library: 資料庫:
Image 影像
Image Info 影像資訊
Image Map: 影像地圖:
@@ -1583,6 +1588,9 @@
No text selected 未選取文字
No Thumbnails 無縮圖
Noise 雜訊
Create: 建立:
Fills 填色
Strokes 筆畫
Nonbreaking Hyphen 不斷行連字號
Nonbreaking Space 不斷行空格
None 無
@@ -2507,6 +2515,13 @@
Smooth Color 平滑顏色
Smooth Tool 平滑工具
Snap Curves To Lines 將曲線靠齊線條
View: 檢視:
Tracing Result 描圖結果
Tracing Result with Outlines 描圖結果(含外框)
Outlines 外框
Outlines with Source Image 外框(含來源影像)
Source Image 來源影像
Image Trace View 影像描圖檢視
Snap Options 靠齊選項
Snap to Glyph 靠齊字符
Snap to Grid 靠齊格點
@@ -2997,6 +3012,9 @@
to zoom in | 可放大 |
to zoom out | 可縮小 |
to zoom into an area 可放大至指定區域
Hold 按住
right or left to zoom in or out | 向右可放大、向左可縮小 |
to keep zooming 可持續縮放
an object to copy its attributes | 物件可複製其屬性 |
to apply the selection's to it | 可將選取範圍的屬性套用至該物件 |
to sample a color 可取樣顏色
Can't render this file because it contains an unexpected character in line 6 and column 47.
+2
View File
@@ -43,6 +43,8 @@ pub fn open_bytes(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Opti
if swatches || ext == vectorcraft_doc::style_libs::STYLES_EXT {
let p = match path {
Some(path) => serde_json::json!({ "path": path }),
// `.ase` swatch libraries are binary.
None if swatches => serde_json::json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(bytes)}),
None => serde_json::json!({"name": name, "data": String::from_utf8_lossy(bytes)}),
};
let load = if swatches { crate::panels::swatches::load_library } else { crate::panels::graphic_styles::load_library };
+5
View File
@@ -288,6 +288,11 @@ pub struct CacheKey {
pub anti_alias: bool,
/// [`vectorcraft_render::placed_document::generation`]: placed documents' bitmaps made since.
pub placed: u64,
/// View › Pixel Preview: the document pixels rendered (x0, y0, x1, y1), one per point, shown
/// with hard edges. None: the art is rendered for the screen.
pub pixel: Option<[i64; 4]>,
/// Images sampled smoothly ([`vectorcraft_render::RenderOptions::smooth_images`]).
pub smooth_images: bool,
}
#[derive(Clone, Copy, Debug, Default)]
+1 -1
View File
@@ -346,7 +346,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"window.swatchLibrary.other",
"Other Library…",
"",
"{path?} (default: pick a file) load a .vcswatches or .gpl library, or another document's swatches (engine: swatch.library.load), and open it in the library panel",
"{path?} (default: pick a file) load a .vcswatches, .gpl or .ase library, or another document's swatches (engine: swatch.library.load), and open it in the library panel",
),
(
"ui.saveSwatchLibrary",
+262 -23
View File
@@ -1,22 +1,57 @@
//! Image Trace panel: preset, mode, threshold or colour count, and the advanced fidelity options.
//! With an Image Trace object selected, changing a setting re-traces it (one undo step per change;
//! sliders apply when released). With an image selected, Trace makes a new Image Trace object.
//! Image Trace panel: preset, view, mode, palette (Color), threshold or colour count, and the
//! Advanced section (open or closed as it was last left): fidelity, method, and Create: Fills /
//! Strokes with the widest line stroked. With an Image Trace object selected, changing a setting
//! re-traces it (one undo step per change; sliders apply when released) and changing the view
//! redraws it without tracing again. With an image selected, Trace makes a new Image Trace object.
use egui::Ui;
use serde_json::{Value, json};
use vectorcraft_doc::{Node, NodeKind};
use vectorcraft_doc::{Node, NodeKind, TraceView};
use vectorcraft_engine::cmd::swatchlib::DOCUMENT_SWATCHES;
use super::{first_selected, pstate, set_pstate};
use super::{first_selected, library_panel, pstate, set_pstate, swatches};
use crate::VectorcraftApp;
use crate::widgets::{self, menu_item};
const MODES: [(&str, &str); 3] = [("blackAndWhite", "Black and White"), ("grayscale", "Grayscale"), ("color", "Color")];
/// Panel state: the preset name, the current parameters and the last result's counts.
/// Color mode's palettes (`palette` param ids), in panel order.
const PALETTES: [&str; 4] = ["limited", "fullTone", "automatic", "documentLibrary"];
/// Palette `id`, in the UI language.
fn palette_label(id: &str) -> &'static str {
match id {
"fullTone" => tl!("Full Tone"),
"automatic" => tl!("Automatic"),
"documentLibrary" => tl!("Document Library"),
_ => tl!("Limited"),
}
}
/// The name of Document Library's library `key` (the document's swatches or a swatch library); a
/// library that is gone shows its key.
fn library_label(app: &VectorcraftApp, key: &str) -> String {
match swatches::limit_name(app, key) {
Some(_) if key == DOCUMENT_SWATCHES => tl!(swatches::DOCUMENT_SWATCHES).to_string(),
Some(name) => library_panel::library_name(key, &name).to_string(),
None => key.to_string(),
}
}
/// Document Library's choices: the document's swatches, then the colour libraries (`current`
/// checked) → the key chosen.
fn library_list(app: &VectorcraftApp, ui: &mut Ui, current: &str) -> Option<String> {
let document = menu_item(ui, swatches::DOCUMENT_SWATCHES, true, current == DOCUMENT_SWATCHES).then(|| DOCUMENT_SWATCHES.to_string());
ui.separator();
library_panel::library_items(ui, &swatches::colour_libraries(app), Some(current)).or(document)
}
/// Panel state: the preset name, the current parameters, the view and the last result's counts.
#[derive(Clone, Default)]
struct TraceUi {
preset: String,
params: Value,
view: TraceView,
info: Option<(u64, u64, u64)>,
/// The selected Image Trace object's stored settings last adopted (so edits in progress
/// aren't overwritten until the object changes).
@@ -44,12 +79,44 @@ fn target(app: &VectorcraftApp) -> (bool, bool, Option<Value>) {
(is_trace(&n), matches!(n.kind, NodeKind::Image(_)), n.trace.map(|t| *t))
}
/// The preset of the one selected Image Trace object ("Custom" once its settings were changed).
pub(crate) fn selected_preset(app: &VectorcraftApp) -> Option<String> {
/// The one selected Image Trace object's preset ("Custom" once its settings were changed) and view.
pub(crate) fn selected_trace(app: &VectorcraftApp) -> Option<(String, TraceView)> {
let st = app.session.active()?;
let [id] = st.selection.objects[..] else { return None };
let n = st.doc.node(id).filter(|n| is_trace(n))?;
Some(n.trace.as_ref().and_then(|t| t["preset"].as_str()).unwrap_or("Custom").to_string())
Some((n.trace.as_ref().and_then(|t| t["preset"].as_str()).unwrap_or("Custom").to_string(), n.trace_view()))
}
/// Image Trace › View, in the UI language.
fn view_label(v: TraceView) -> &'static str {
match v {
TraceView::Result => tl!("Tracing Result"),
TraceView::ResultWithOutlines => tl!("Tracing Result with Outlines"),
TraceView::Outlines => tl!("Outlines"),
TraceView::OutlinesWithSource => tl!("Outlines with Source Image"),
TraceView::Source => tl!("Source Image"),
}
}
/// The View dropdown showing `current` → the view chosen.
fn view_dropdown(ui: &mut Ui, current: TraceView, width: f32) -> Option<TraceView> {
let labels = TraceView::ALL.map(view_label);
widgets::dropdown_names(ui, "trace-view", view_label(current), &labels, width).and_then(|i| TraceView::ALL.get(i).copied())
}
/// Show the selected Image Trace objects with `view` (no new trace).
fn set_view(app: &mut VectorcraftApp, view: TraceView) {
if let Err(e) = app.run("imageTrace.setView", json!({ "view": view.id() })) {
app.ui.status = e;
}
}
/// The selected Image Trace object's View row (Control bar, Properties).
pub(crate) fn view_row(app: &mut VectorcraftApp, ui: &mut Ui, current: TraceView, width: f32) {
widgets::dim_label(ui, tl!("View:"));
if let Some(v) = view_dropdown(ui, current, width) {
set_view(app, v);
}
}
/// Trace the selected image, or trace the selected Image Trace object again, with built-in `preset`.
@@ -94,12 +161,13 @@ pub(crate) fn preset_dropdown(app: &mut VectorcraftApp, ui: &mut Ui, current: &s
}
}
/// The Control bar for one selected Image Trace object: its preset, the Image Trace panel and
/// Expand. Whether it is one.
/// The Control bar for one selected Image Trace object: its preset, view, the Image Trace panel
/// and Expand. Whether it is one.
pub fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) -> bool {
let Some(preset) = selected_preset(app) else { return false };
let Some((preset, view)) = selected_trace(app) else { return false };
widgets::dim_label(ui, tl!("Preset:"));
preset_dropdown(app, ui, &preset, 150.0);
view_row(app, ui, view, 190.0);
if widgets::icon_button(ui, "image", tl!("Image Trace"), false, 24.0).clicked() {
app.ui.open_panel = Some("imageTrace".into());
}
@@ -112,7 +180,7 @@ pub fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) -> bool {
fn trace(app: &mut VectorcraftApp, st: &mut TraceUi) {
let preset = if st.preset == "Custom" { "Default" } else { st.preset.as_str() };
match app.run("imageTrace.make", json!({ "preset": preset, "params": st.params })) {
match app.run("imageTrace.make", json!({ "preset": preset, "params": st.params, "view": st.view.id() })) {
Ok(r) => st.info = Some((r["paths"].as_u64().unwrap_or(0), r["anchors"].as_u64().unwrap_or(0), r["colors"].as_u64().unwrap_or(0))),
Err(e) => app.ui.status = e,
}
@@ -143,6 +211,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
if let Some(t) = stored.filter(|t| *t != st.synced) {
st.preset = t["preset"].as_str().unwrap_or("Custom").to_string();
st.params = t["params"].clone();
st.view = TraceView::of(&t);
st.synced = t;
}
let mut retrace = false;
@@ -156,6 +225,15 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
retrace = true;
}
});
ui.horizontal(|ui| {
widgets::dim_label(ui, tl!("View:"));
if let Some(v) = view_dropdown(ui, st.view, 170.0) {
st.view = v;
if is_trace {
set_view(app, v);
}
}
});
ui.horizontal(|ui| {
widgets::dim_label(ui, tl!("Mode:"));
let mode = st.params["mode"].as_str().unwrap_or("blackAndWhite").to_string();
@@ -167,23 +245,49 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
retrace = true;
}
});
let bw = st.params["mode"].as_str() == Some("blackAndWhite");
let (key, label, range) = if bw {
("threshold", tl!("Threshold"), 0.0..=255.0)
} else {
("colors", if st.params["mode"] == "grayscale" { tl!("Grays") } else { tl!("Colors") }, 2.0..=256.0)
let mode = st.params["mode"].as_str().unwrap_or("blackAndWhite").to_string();
let palette = st.params["palette"].as_str().unwrap_or("limited").to_string();
if mode == "color" {
ui.horizontal(|ui| {
widgets::dim_label(ui, tl!("Palette:"));
let labels = PALETTES.map(palette_label);
if let Some(p) = widgets::dropdown_names(ui, "it-palette", palette_label(&palette), &labels, 170.0).and_then(|i| PALETTES.get(i)) {
st.params["palette"] = json!(p);
st.preset = "Custom".into();
retrace = true;
}
});
if palette == "documentLibrary" {
ui.horizontal(|ui| {
widgets::dim_label(ui, tl!("Library:"));
let key = st.params["library"].as_str().unwrap_or(DOCUMENT_SWATCHES).to_string();
if let Some(k) = widgets::combo(ui, "it-library", &library_label(app, &key), 170.0, false, |ui| library_list(app, ui, &key)) {
st.params["library"] = json!(k);
st.preset = "Custom".into();
retrace = true;
}
});
}
}
// Full Tone and Automatic: how many colours (Less … More); else a count or the threshold.
let (key, label, range, suffix) = match mode.as_str() {
"blackAndWhite" => ("threshold", tl!("Threshold"), 0.0..=255.0, ""),
"grayscale" => ("colors", tl!("Grays"), 2.0..=256.0, ""),
_ if matches!(palette.as_str(), "fullTone" | "automatic") => ("colorDetail", tl!("Colors"), 0.0..=100.0, "%"),
_ => ("colors", tl!("Colors"), 2.0..=256.0, ""),
};
let mut v = st.params[key].as_f64().unwrap_or(0.0);
let (changed, release) = slider(ui, label, &mut v, range, "");
let (changed, release) = slider(ui, label, &mut v, range, suffix);
if changed {
st.params[key] = json!(v.round() as u64);
st.params[key] = if key == "colorDetail" { json!(v.round()) } else { json!(v.round() as u64) };
st.preset = "Custom".into();
}
retrace |= release;
let open: bool = !pstate::<bool>(ui.ctx(), "it-advanced-closed");
if ui.add(egui::Button::new(format!("{} {}", if open { "▾" } else { "▸" }, tl!("Advanced"))).frame(false)).clicked() {
set_pstate(ui.ctx(), "it-advanced-closed", open);
ui.add_space(4.0);
let open = app.ui.image_trace_advanced;
if widgets::section_toggle(ui, tl!("Advanced"), open) {
app.ui.image_trace_advanced = !open;
}
if open {
for (key, label, range, suffix) in
@@ -207,6 +311,27 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
}
}
});
// Create: Fills and/or Strokes (one of them stays on), and the widest line stroked.
let create = |p: &Value, key: &str| p[key].as_bool().unwrap_or(key == "fills");
let strokes = create(&st.params, "strokes");
ui.horizontal(|ui| {
widgets::dim_label(ui, tl!("Create:"));
for (key, other, label) in [("fills", "strokes", tl!("Fills")), ("strokes", "fills", tl!("Strokes"))] {
let on = create(&st.params, key);
if widgets::check(ui, label, on, !on || create(&st.params, other)) {
st.params[key] = json!(!on);
st.preset = "Custom".into();
retrace = true;
}
}
});
let mut v = st.params["strokeWidth"].as_f64().unwrap_or(10.0);
let (changed, release) = ui.add_enabled_ui(strokes, |ui| slider(ui, tl!("Stroke"), &mut v, 1.0..=100.0, " px")).inner;
if changed {
st.params["strokeWidth"] = json!(v.round());
st.preset = "Custom".into();
}
retrace |= release;
for (key, label) in [("snapCurvesToLines", tl!("Snap Curves To Lines")), ("ignoreWhite", tl!("Ignore White"))] {
let on = st.params[key].as_bool().unwrap_or(false);
if widgets::check(ui, label, on, true) {
@@ -258,6 +383,119 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) {
#[cfg(test)]
mod tests {
use super::*;
use egui::{Event, PointerButton, Pos2, Rect, vec2};
/// One headless frame of the panel (and its menu) with `events`: the texts drawn, with where.
fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec<Event>) -> Vec<(String, Rect)> {
let screen = Rect::from_min_size(Pos2::ZERO, vec2(280.0, 700.0));
let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }, |ui| show(app, ui));
out.textures_delta.clear();
crate::tests_removeanchors::shapes_text(&out.shapes.iter().map(|c| c.shape.clone()).collect::<Vec<_>>())
}
/// Click the panel's `label` (the first one drawn).
fn click(app: &mut VectorcraftApp, ctx: &egui::Context, label: &str) {
let texts = frame(app, ctx, vec![]);
let at = texts.iter().find(|(t, _)| t == label).map(|(_, r)| r.center()).unwrap_or_else(|| panic!("no `{label}` in {texts:?}"));
let press = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() };
frame(app, ctx, vec![Event::PointerMoved(at), press(true)]);
frame(app, ctx, vec![press(false)]);
}
fn traced_app() -> VectorcraftApp {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
let img = image::RgbaImage::from_fn(20, 20, |x, _| image::Rgba(if x < 10 { [0, 0, 0, 255] } else { [255, 255, 255, 255] }));
let mut png = vec![];
img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
let data = vectorcraft_format::base64_encode(&png);
app.run("file.place", json!({"name": "half.png", "dataBase64": data, "link": false})).unwrap();
app.run("imageTrace.make", json!({"preset": "Default"})).unwrap();
app
}
#[test]
fn advanced_is_a_section_that_stays_as_it_was_left() {
let mut app = traced_app();
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
let has = |texts: &[(String, Rect)], s: &str| texts.iter().any(|(t, _)| t == s);
let texts = frame(&mut app, &ctx, vec![]);
assert!(app.ui.image_trace_advanced && has(&texts, "Advanced") && has(&texts, "Corners"), "open at first: {texts:?}");
click(&mut app, &ctx, "Advanced");
assert!(!app.ui.image_trace_advanced, "the header closes it");
assert!(!has(&frame(&mut app, &ctx, vec![]), "Corners"));
// Remembered with the UI preferences, across launches.
let saved: crate::state::UiState = serde_json::from_value(serde_json::to_value(&app.ui).unwrap()).unwrap();
assert!(!saved.image_trace_advanced);
let old: crate::state::UiState = serde_json::from_value(json!({})).unwrap();
assert!(old.image_trace_advanced, "open for preferences saved before the section existed");
click(&mut app, &ctx, "Advanced");
assert!(app.ui.image_trace_advanced && has(&frame(&mut app, &ctx, vec![]), "Corners"));
}
#[test]
fn the_view_dropdown_shows_and_sets_the_objects_view() {
let mut app = traced_app();
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
let texts = frame(&mut app, &ctx, vec![]);
assert!(texts.iter().any(|(t, _)| t == "View:") && texts.iter().any(|(t, _)| t == "Tracing Result"), "{texts:?}");
let steps = app.session.active().unwrap().history.undo.len();
click(&mut app, &ctx, "Tracing Result");
click(&mut app, &ctx, "Source Image");
assert_eq!(selected_trace(&app).map(|t| t.1), Some(TraceView::Source));
assert_eq!(app.session.active().unwrap().history.undo.len(), steps + 1, "one undo step, no new trace");
// Another object's view is shown when it is selected.
app.run("imageTrace.setView", json!({"view": "outlines"})).unwrap();
assert!(frame(&mut app, &ctx, vec![]).iter().any(|(t, _)| t == "Outlines"));
}
#[test]
fn the_palette_shows_in_color_mode_and_traces_again() {
let mut app = traced_app();
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
let has = |texts: &[(String, Rect)], s: &str| texts.iter().any(|(t, _)| t == s);
let palette = |app: &VectorcraftApp| target(app).2.map(|t| t["params"]["palette"].clone());
assert!(!has(&frame(&mut app, &ctx, vec![]), "Palette:"), "Black and White has no palette");
app.run("imageTrace.make", json!({"preset": "6 Colors"})).unwrap();
let texts = frame(&mut app, &ctx, vec![]);
assert!(has(&texts, "Palette:") && has(&texts, "Limited") && !has(&texts, "Library:"), "{texts:?}");
// Document Library traces again with the document's swatches, and names them.
click(&mut app, &ctx, "Limited");
click(&mut app, &ctx, "Document Library");
assert_eq!(palette(&app), Some(json!("documentLibrary")));
let texts = frame(&mut app, &ctx, vec![]);
assert!(has(&texts, "Library:") && has(&texts, "Document Swatches"), "{texts:?}");
// Full Tone's Colors is how many, Less (0%) … More (100%).
click(&mut app, &ctx, "Document Library");
click(&mut app, &ctx, "Full Tone");
assert_eq!(palette(&app), Some(json!("fullTone")));
let texts = frame(&mut app, &ctx, vec![]);
assert!(has(&texts, "50") && !has(&texts, "Library:"), "{texts:?}");
}
#[test]
fn create_strokes_traces_again_and_keeps_one_kind_on() {
let mut app = traced_app();
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
let create = |app: &VectorcraftApp| target(app).2.map(|t| (t["params"]["fills"].clone(), t["params"]["strokes"].clone()));
let texts = frame(&mut app, &ctx, vec![]);
for s in ["Create:", "Fills", "Strokes", "Stroke", "10"] {
assert!(texts.iter().any(|(t, _)| t == s), "{s}: {texts:?}");
}
// Fills alone can't be turned off.
click(&mut app, &ctx, "Fills");
assert_eq!(create(&app), Some((json!(true), json!(false))));
click(&mut app, &ctx, "Strokes");
assert_eq!(create(&app), Some((json!(true), json!(true))), "traced again with strokes");
click(&mut app, &ctx, "Fills");
assert_eq!(create(&app), Some((json!(false), json!(true))));
click(&mut app, &ctx, "Strokes");
assert_eq!(create(&app), Some((json!(false), json!(true))), "Strokes alone stays on");
}
#[test]
fn panel_and_menu_draw_headless() {
@@ -266,6 +504,7 @@ mod tests {
app.session.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap();
for _ in 0..2 {
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| {
show(&mut app, ui);
menu(&mut app, ui);
+182 -59
View File
@@ -24,13 +24,20 @@
//! on the trash clears it.
//!
//! While an opacity mask is edited the panel lists only its art, under an `<Opacity Mask>` entry.
//!
//! The rows open are the document's ([`OpenRows`], saved in native files): a document opens with
//! only its top-level layers open. The rows shown are listed once per document change, and only
//! those scrolled into view are laid out, so a document of many thousand objects costs no more
//! per frame than a small one.
use std::collections::HashSet;
use std::sync::Arc;
use egui::{Color32, Sense, Stroke, StrokeKind, Ui, vec2};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
use vectorcraft_engine::OpenRows;
use crate::theme::Tokens;
use crate::widgets::{Live, PanelDrag};
@@ -198,9 +205,97 @@ fn opens(n: &Node, opts: &PanelOptions) -> bool {
}
}
/// Whether `n` or anything in it has a name containing `q` (lowercase).
fn matches(n: &Node, q: &str) -> bool {
n.display_name().to_lowercase().contains(q) || n.children().is_some_and(|c| c.iter().any(|c| matches(c, q)))
/// One row of the panel.
#[derive(Clone)]
struct Row {
node: Arc<Node>,
/// Nesting level (0: a top-level layer).
depth: usize,
/// A clipping path: its group or layer clips.
clip_path: bool,
/// It holds rows ([`opens`]), and shows them.
opens: bool,
open: bool,
/// The colour of its layer (its own, for a layer).
colour: Color32,
/// Drawn dimmed: hidden itself or in a hidden layer or group, or a template layer.
dim: bool,
}
/// What the rows were listed from: listed again when any of it changes.
#[derive(Clone, PartialEq)]
struct RowsKey {
uid: u64,
revision: u64,
open: u64,
layers_only: bool,
query: String,
}
/// The rows the panel shows, top down: the layers (only the opacity mask's while one is edited)
/// with the rows of the open ones inside them. A search shows every row whose name, or the name of
/// anything inside it, contains `query` (lowercase).
fn list_rows(doc: &Document, open: &OpenRows, opts: &PanelOptions, query: &str) -> Vec<Row> {
let mask_layer = doc.mask_edit.map(|m| m.layer);
let mut out = vec![];
for l in doc.layers.iter().rev().filter(|l| mask_layer.is_none_or(|m| m == l.id)) {
push_rows(l, 0, false, (Color32::PLACEHOLDER, true), (open, opts, query), &mut out);
}
out
}
/// Add the rows of `n` and those open inside it to `out`; `(colour, shown)` are those of what holds
/// it (the layer's colour, and whether it is visible).
fn push_rows(
n: &Arc<Node>,
depth: usize,
clip_path: bool,
(colour, shown): (Color32, bool),
cx: (&OpenRows, &PanelOptions, &str),
out: &mut Vec<Row>,
) {
let (open_rows, opts, query) = cx;
if opts.layers_only && !n.is_layer() {
return;
}
let colour = match &n.kind {
NodeKind::Layer { color, .. } => {
let [r, g, b] = color.rgb();
Color32::from_rgb(r, g, b)
}
_ => colour,
};
let shown = shown && n.visible;
let opens = opens(n, opts);
let searching = !query.is_empty();
let open = opens && (searching || open_rows.contains(n.id));
let at = out.len();
out.push(Row { node: n.clone(), depth, clip_path, opens, open, colour, dim: !shown || n.is_template() });
if open && let Some(children) = n.children() {
for (i, c) in children.iter().enumerate().rev() {
push_rows(c, depth + 1, i == 0 && n.clips(), (colour, shown), cx, out);
}
}
// Searching, a row stays for its own name or for a row it keeps inside it.
if searching && out.len() == at + 1 && !n.display_name().to_lowercase().contains(query) {
out.truncate(at);
}
}
/// The rows of the active document as [`list_rows`] lists them, listed again only when the
/// document, its open rows, the search or Show Layers Only changed.
fn rows_of_doc(ui: &Ui, st: &vectorcraft_engine::DocState, opts: &PanelOptions, query: &str) -> Arc<Vec<Row>> {
let now =
RowsKey { uid: st.uid, revision: st.revision, open: st.layers_open.generation(), layers_only: opts.layers_only, query: query.to_string() };
let id = key("rows");
if let Some((was, rows)) = ui.data(|d| d.get_temp::<(RowsKey, Arc<Vec<Row>>)>(id))
&& was == now
{
return rows;
}
let rows = Arc::new(list_rows(&st.doc, &st.layers_open, opts, query));
ui.data_mut(|d| d.insert_temp(id, (now, rows.clone())));
rows
}
/// Everything one frame of the panel reads.
@@ -213,8 +308,6 @@ struct View<'a> {
opts: PanelOptions,
t: Tokens,
h: f32,
/// The search field's text, lowercase (empty: every row).
query: String,
column: Option<ColumnDrag>,
/// The row to scroll into view.
reveal: Option<NodeId>,
@@ -224,8 +317,6 @@ struct View<'a> {
#[derive(Default)]
struct Out {
actions: Vec<(String, Value)>,
/// The rows shown, top down.
order: Vec<NodeId>,
/// A row clicked with these modifiers (resolved once every row is listed).
click: Option<(NodeId, egui::Modifiers)>,
/// The column drag after this frame (`Some(None)`: it ended).
@@ -249,23 +340,25 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
d.insert_temp(shown_doc, st.uid);
});
}
let uid = st.uid;
let doc = st.doc.clone();
let rows = st.highlighted_rows();
// Rows highlighted anew (a click, Locate Object, a new layer): open the layers around them.
let seen: Vec<NodeId> = ui.data(|d| d.get_temp(key("seen"))).unwrap_or_default();
let mut reveal = None;
let expanded = app.ui.layers_expanded.entry(uid).or_insert_with(|| doc.layers.iter().map(|l| l.id.0).collect());
if rows != seen {
for r in &rows {
for a in doc.ancestry(*r).unwrap_or_default().split_last().map(|(_, a)| a.to_vec()).unwrap_or_default() {
expanded.insert(a.0);
let around: Vec<NodeId> =
rows.iter().flat_map(|r| doc.ancestry(*r).unwrap_or_default().split_last().map(|(_, a)| a.to_vec()).unwrap_or_default()).collect();
if let Some(st) = app.session.active_mut() {
for a in around {
st.layers_open.set(a, true);
}
}
reveal = rows.first().copied();
ui.data_mut(|d| d.insert_temp(key("seen"), rows.clone()));
}
let query = crate::widgets::search_field(ui, egui::Id::new("layers-search"), tl!("Search All")).trim().to_lowercase();
let Some(st) = app.session.active() else { return };
let list = rows_of_doc(ui, st, &app.ui.layers_panel, &query);
let view = View {
doc: &doc,
sel: st.selection.objects.iter().copied().collect(),
@@ -275,30 +368,31 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
opts: app.ui.layers_panel.clone(),
t,
h: app.ui.layers_panel.row(),
query,
column: ui.data(|d| d.get_temp(key("column"))),
reveal,
};
// While an opacity mask is edited only its art is listed.
let mask_layer = doc.mask_edit.map(|m| m.layer);
let mut out = Out::default();
ui.add_space(6.0);
let list_h = ui.available_height() - 34.0;
let list = egui::ScrollArea::vertical().max_height(list_h).auto_shrink([false, false]).show(ui, |ui| {
// Only the rows in view are laid out; one revealed out of view is scrolled to.
let revealed = reveal.and_then(|id| list.iter().position(|r| r.node.id == id));
let scrolled = ui.scope(|ui| {
ui.spacing_mut().item_spacing.y = 0.0;
let expanded = app.ui.layers_expanded.entry(uid).or_default();
for l in doc.layers.iter().rev().filter(|l| mask_layer.is_none_or(|m| m == l.id)) {
row(ui, &view, l, 0, false, expanded, &mut out);
}
egui::ScrollArea::vertical().max_height(list_h).auto_shrink([false, false]).show_rows(ui, view.h, list.len(), |ui, range| {
if let Some(i) = revealed.filter(|i| !range.contains(i)) {
let top = ui.max_rect().top() + (i as f32 - range.start as f32) * view.h;
ui.scroll_to_rect(egui::Rect::from_min_size(egui::pos2(ui.max_rect().left(), top), vec2(ui.max_rect().width(), view.h)), None);
}
for r in list.get(range).unwrap_or_default() {
row(ui, &view, r, &mut out);
}
})
});
let list_rect = list.inner_rect;
resolve_click(ui, &view, &mut out);
let expanded = app.ui.layers_expanded.entry(uid).or_default();
for (id, open) in out.toggle.drain(..) {
if open {
expanded.insert(id.0);
} else {
expanded.remove(&id.0);
let list_rect = scrolled.inner.inner_rect;
resolve_click(ui, &view, &list, &mut out);
if let Some(st) = app.session.active_mut() {
for (id, open) in out.toggle.drain(..) {
st.layers_open.set(id, open);
}
}
// The column drag: live while it lasts, one undo step when the button is released.
@@ -415,15 +509,16 @@ fn bottom_bar(app: &mut VectorcraftApp, ui: &mut Ui, view: &View, doc: &Document
/// Resolve the row clicked this frame: plain (highlight it), Ctrl/Cmd (toggle it) or Shift
/// (highlight the rows from the last one clicked down to it).
fn resolve_click(ui: &Ui, view: &View, out: &mut Out) {
fn resolve_click(ui: &Ui, view: &View, list: &[Row], out: &mut Out) {
let Some((id, m)) = out.click.take() else { return };
let anchor: Option<NodeId> = ui.data(|d| d.get_temp(key("anchor")));
ui.data_mut(|d| d.insert_temp(key("focus"), true));
let at = |id: NodeId| list.iter().position(|r| r.node.id == id);
if m.shift
&& let Some(a) = anchor.or(view.rows.last().copied())
&& let (Some(i), Some(j)) = (out.order.iter().position(|r| *r == a), out.order.iter().position(|r| *r == id))
&& let (Some(i), Some(j)) = (at(a), at(id))
{
let range: Vec<u64> = out.order.get(i.min(j)..=i.max(j)).unwrap_or_default().iter().map(|r| r.0).collect();
let range: Vec<u64> = list.get(i.min(j)..=i.max(j)).unwrap_or_default().iter().map(|r| r.node.id.0).collect();
out.actions.push(("layer.highlight".into(), json!({"ids": range, "mode": if m.command { "add" } else { "set" }})));
return;
}
@@ -447,19 +542,14 @@ fn takes(n: &Node, drag: &LayersDrag, doc: &Document) -> bool {
}
}
#[allow(clippy::too_many_arguments)]
fn row(ui: &mut Ui, view: &View, n: &Node, depth: usize, clip_path: bool, expanded: &mut HashSet<u64>, out: &mut Out) {
/// The widgets of row `item`.
fn row(ui: &mut Ui, view: &View, item: &Row, out: &mut Out) {
let n = &*item.node;
let (depth, clip_path, has_children, open, color) = (item.depth, item.clip_path, item.opens, item.open, item.colour);
let doc = view.doc;
let t = &view.t;
if !view.query.is_empty() && !matches(n, &view.query) {
return;
}
if view.opts.layers_only && !n.is_layer() {
return;
}
let h = view.h;
let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), h), Sense::click_and_drag());
out.order.push(n.id);
if view.reveal == Some(n.id) {
ui.scroll_to_rect(r, None);
}
@@ -470,7 +560,6 @@ fn row(ui: &mut Ui, view: &View, n: &Node, depth: usize, clip_path: bool, expand
n.walk(&mut |c| any |= c.id != n.id && view.sel.contains(&c.id));
any
});
let color = layer_colour(doc, n.id);
// Highlighted rows (else the current layer's).
let highlighted = if view.rows.is_empty() { n.is_layer() && Some(n.id) == view.current } else { view.rows.contains(&n.id) };
if highlighted {
@@ -490,9 +579,6 @@ fn row(ui: &mut Ui, view: &View, n: &Node, depth: usize, clip_path: bool, expand
colour_bar(ui, n, r, x, color);
x += 6.0 + depth as f32 * INDENT;
// Disclosure triangle; Alt opens or closes everything inside too.
let searching = !view.query.is_empty();
let has_children = opens(n, &view.opts);
let open = has_children && (searching || expanded.contains(&n.id.0));
if has_children {
let dr = egui::Rect::from_min_size(egui::pos2(x, r.center().y - 8.0), vec2(14.0, 16.0));
let dresp = ui.interact(dr, ui.id().with(("disc", n.id.0)), Sense::click());
@@ -548,8 +634,7 @@ fn row(ui: &mut Ui, view: &View, n: &Node, depth: usize, clip_path: bool, expand
} else {
painted_name(n, &name, crate::i18n::current())
};
let dim = !doc.is_visible(n.id) || n.is_template();
let text = painter.text(egui::pos2(x, r.center().y), egui::Align2::LEFT_CENTER, shown, font, if dim { t.text_dim } else { t.text });
let text = painter.text(egui::pos2(x, r.center().y), egui::Align2::LEFT_CENTER, shown, font, if item.dim { t.text_dim } else { t.text });
name_end = text.right();
// A clipping path's name is underlined, a masked object's with a dashed line.
if clip_path {
@@ -605,11 +690,6 @@ fn row(ui: &mut Ui, view: &View, n: &Node, depth: usize, clip_path: bool, expand
ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing);
}
drop_target(ui, view, n, r, x - 16.0, open, &resp, out);
if open && let Some(children) = n.children() {
for (i, c) in children.iter().enumerate().rev() {
row(ui, view, c, depth + 1, i == 0 && n.clips(), expanded, out);
}
}
}
/// Alt-clicking row `n`'s eye (`eye`) or lock: Hide Others or Lock Others, every top-level layer
@@ -951,15 +1031,9 @@ pub fn expand(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
v
}
};
let uid = st.uid;
let layers: Vec<u64> = st.doc.layers.iter().map(|l| l.id.0).collect();
let set = app.ui.layers_expanded.entry(uid).or_insert_with(|| layers.into_iter().collect());
let st = app.session.active_mut().ok_or("no document open")?;
for i in &ids {
if open {
set.insert(*i);
} else {
set.remove(i);
}
st.layers_open.set(NodeId(*i), open);
}
Ok(json!({ "count": ids.len() }))
}
@@ -1623,4 +1697,53 @@ mod tests {
assert_eq!(rows_of(&app), vec![sub]);
assert_eq!(app.session.active().unwrap().current_layer(), Some(sub));
}
/// A layer of 2,000 groups of 10 paths with every row open: one frame lays out only the rows
/// in view, and a row highlighted far below them is scrolled to.
#[test]
fn only_the_rows_in_view_are_laid_out() {
use vectorcraft_doc::Appearance;
use vectorcraft_geom::{Rect, shapes};
let mut d = Document::new(1000.0, 1000.0);
let mut groups = vec![];
let mut needle = None;
for g in 0..2000 {
let kids = (0..10)
.map(|k| {
let r = Rect::new(k as f64, g as f64 * 0.1, k as f64 + 1.0, g as f64 * 0.1 + 1.0);
let mut n = Node::path(d.alloc_id(), shapes::rectangle(r), Appearance::default());
if g == 0 && k == 0 {
n.name = Some("Needle".into());
needle = Some(n.id);
}
Arc::new(n)
})
.collect();
groups.push(Arc::new(Node::group(d.alloc_id(), kids)));
}
*Arc::make_mut(&mut d.layers[0]).children_mut().unwrap() = groups;
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.add_document(d, None);
expand(&mut app, &json!({})).unwrap();
let ctx = egui::Context::default();
// (shapes drawn, whether the needle's name is among them); a second passes per frame, so
// scrolling ends.
let mut time = 0.0;
let mut frame = |app: &mut VectorcraftApp| {
time += 1.0;
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(300.0, 800.0));
let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), time: Some(time), ..Default::default() }, |ui| show(app, ui));
out.textures_delta.clear();
let found = out.shapes.iter().any(|c| matches!(&c.shape, egui::Shape::Text(t) if t.galley.text() == "Needle"));
(out.shapes.len(), found)
};
let (shapes, found) = frame(&mut app);
// 22,001 rows; about 30 fit.
assert!(shapes < 1000 && !found, "{shapes} shapes");
let needle = needle.unwrap();
app.session.execute("layer.highlight", &json!({"ids": [needle.0], "mode": "set"})).unwrap();
let found = (0..4).any(|_| frame(&mut app).1);
assert_eq!(app.session.active().unwrap().highlighted_rows(), [needle]);
assert!(found, "the highlighted row is scrolled into view");
}
}
@@ -616,4 +616,16 @@ mod tests {
}
assert!(!builtin_library(&open.id) && builtin_library(vectorcraft_engine::cmd::swatchlib::DOCUMENT_SWATCHES));
}
#[test]
fn swatch_exchange_files_without_a_path_open_in_the_library_panel() {
// A file opened on the web has no path; open_bytes passes its bytes as dataBase64.
let mut app = app();
crate::io::open_bytes(&mut app, "Brand.ase", &vectorcraft_testkit::ase::sample(), None).unwrap();
let open = app.ui.library_panel.clone().unwrap();
assert_eq!(open.id, "loaded/Brand.ase");
let (_, lib) = SwatchLibraries::get(&app, &open.id).unwrap();
assert_eq!((lib.len(), lib.groups.len()), (4, 1));
assert_eq!(app.session.documents().len(), 1, "not opened as a document");
}
}
+5 -4
View File
@@ -44,8 +44,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
image_section(app, ui);
divider(ui);
}
if let Some(preset) = crate::panels::image_trace::selected_preset(app) {
trace_section(app, ui, &preset);
if let Some((preset, view)) = crate::panels::image_trace::selected_trace(app) {
trace_section(app, ui, &preset, view);
divider(ui);
}
if matches!(first.as_ref().map(|n| &n.kind), Some(NodeKind::Text(_))) {
@@ -162,13 +162,14 @@ fn image_section(app: &mut VectorcraftApp, ui: &mut Ui) {
}
/// The one selected Image Trace object: its preset (choosing another traces it again with that
/// one), Expand and Release.
fn trace_section(app: &mut VectorcraftApp, ui: &mut Ui, preset: &str) {
/// one), view, Expand and Release.
fn trace_section(app: &mut VectorcraftApp, ui: &mut Ui, preset: &str, view: vectorcraft_doc::TraceView) {
section_header(ui, tl!("Image Trace"));
ui.horizontal(|ui| {
dim_label(ui, tl!("Preset:"));
crate::panels::image_trace::preset_dropdown(app, ui, preset, ui.available_width());
});
ui.horizontal(|ui| crate::panels::image_trace::view_row(app, ui, view, ui.available_width()));
let w = (ui.available_width() - 6.0) / 2.0;
ui.horizontal(|ui| {
for (label, id) in [(tl!("Expand"), "imageTrace.expand"), (tl!("Release"), "imageTrace.release")] {
+4
View File
@@ -244,6 +244,10 @@ fn category_fields(ui: &mut egui::Ui, d: &mut Dialog, cat: &str) {
PrefKind::Bool if sp.key == "numbersWithoutUnitsArePoints" => {
ui.add_enabled_ui(picas_in_use(d), |ui| bool_row(ui, d, sp.key, sp.label));
}
// Performance › Animated Zoom needs GPU Performance: dimmed while it is off.
PrefKind::Bool if sp.key == "animatedZoom" => {
ui.add_enabled_ui(d.bool("gpuPerformance"), |ui| bool_row(ui, d, sp.key, sp.label));
}
PrefKind::Bool => bool_row(ui, d, sp.key, sp.label),
PrefKind::Num { min, max, unit } => {
labeled(ui, sp.label, |ui| {
+4 -4
View File
@@ -365,9 +365,9 @@ pub struct UiState {
/// Layers panel › Panel Options… (row size, thumbnails, Show Layers Only).
#[serde(default)]
pub layers_panel: crate::panels::layers::PanelOptions,
/// The Layers panel's open rows, per open document (`DocState::uid` → node ids).
#[serde(skip)]
pub layers_expanded: std::collections::HashMap<u64, std::collections::HashSet<u64>>,
/// The Image Trace panel's Advanced section is open (as it was last left).
#[serde(default = "yes")]
pub image_trace_advanced: bool,
/// The desktop window's size, position and maximized state, saved when the app quits and
/// restored at the next launch (the desktop host reads and writes it; none on the web).
#[serde(default, skip_serializing_if = "Option::is_none")]
@@ -521,7 +521,7 @@ impl Default for UiState {
dxf_import: Value::Null,
home: None,
layers_panel: Default::default(),
layers_expanded: Default::default(),
image_trace_advanced: true,
window: None,
}
}
+43
View File
@@ -90,3 +90,46 @@ fn cmd_n_opens_the_new_document_dialog() {
assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some("newDocument"));
assert_eq!(app.session.documents().len(), 1, "no document is made until the dialog's OK");
}
/// One Home screen frame (no document open) with `events`: the texts drawn and where.
fn home_texts(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec<egui::Event>) -> Vec<(String, egui::Rect)> {
fn walk(s: &egui::Shape, out: &mut Vec<(String, egui::Rect)>) {
match s {
egui::Shape::Text(t) => out.push((t.galley.text().to_string(), t.visual_bounding_rect())),
egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, out)),
_ => {}
}
}
let raw =
egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1000.0, 900.0))), events, ..Default::default() };
let mut out = ctx.run_ui(raw, |ui| canvas::show(app, ui));
out.textures_delta.clear();
let mut texts = vec![];
out.shapes.iter().for_each(|c| walk(&c.shape, &mut texts));
texts
}
/// The Home screen lists the first recent files (#663), each by name and folder; a click opens it,
/// and one that can't be opened says so. With none, there is no Recent Files section.
#[test]
fn home_lists_recent_files_and_a_click_opens_one() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default());
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
let has = |texts: &[(String, egui::Rect)], s: &str| texts.iter().any(|(t, _)| t == s);
assert!(!has(&home_texts(&mut app, &ctx, vec![]), "Recent Files"), "none: no section");
let dir = std::env::temp_dir().join("vectorcraft-home-recent");
let missing = dir.join("Gone.svg").to_string_lossy().into_owned();
app.ui.recent_files = (0..9).map(|i| dir.join(format!("Drawing {i}.svg")).to_string_lossy().into_owned()).collect();
app.ui.recent_files.insert(0, missing);
let texts = home_texts(&mut app, &ctx, vec![]);
assert!(has(&texts, "Recent Files") && has(&texts, "Gone.svg") && has(&texts, "Drawing 4.svg"), "{texts:?}");
assert!(!has(&texts, "Drawing 5.svg"), "the first six only");
assert!(has(&texts, &dir.to_string_lossy()), "with its folder");
let at = texts.iter().find(|(t, _)| t == "Gone.svg").map(|(_, r)| r.center()).unwrap();
let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
home_texts(&mut app, &ctx, vec![egui::Event::PointerMoved(at), press(true)]);
home_texts(&mut app, &ctx, vec![press(false)]);
assert!(app.session.documents().is_empty());
assert!(!app.ui.status.is_empty(), "a file that can't be opened says so");
}
+14 -5
View File
@@ -308,7 +308,8 @@ fn click_label(app: &mut VectorcraftApp, ctx: &egui::Context, label: &str) {
#[test]
fn the_control_bar_and_properties_trace_a_selected_image() {
use crate::panels::image_trace::{TRACE_BUTTON_W, selected_preset};
use crate::panels::image_trace::{TRACE_BUTTON_W, selected_trace};
let selected_preset = |app: &VectorcraftApp| selected_trace(app).map(|t| t.0);
use crate::tests_removeanchors::{at, click_control, control_frame, has, properties_frame};
let mut app = app();
let data = vectorcraft_format::base64_encode(&png(30, 30, 72.0));
@@ -332,19 +333,27 @@ fn the_control_bar_and_properties_trace_a_selected_image() {
app.run("edit.undo", json!({})).unwrap();
click_label(&mut app, &ctx, "Image Trace");
assert_eq!(selected_preset(&app).as_deref(), Some("Default"));
// An Image Trace object: its preset (another traces it again), the panel and Expand.
// An Image Trace object: its preset (another traces it again), view, the panel and Expand.
let bar = control_frame(&mut app, &ctx, vec![]);
for s in ["Image Tracing", "Preset:", "Default", "Expand"] {
for s in ["Image Tracing", "Preset:", "Default", "View:", "Tracing Result", "Expand"] {
assert!(has(&bar, s), "{s}");
}
assert!(has(&properties_frame(&mut app, 260.0), "Release"));
let props = properties_frame(&mut app, 260.0);
assert!(has(&props, "Release") && has(&props, "View:"));
// Another view redraws it without tracing again.
let traced = app.session.active().unwrap().selection.objects.clone();
click_control(&mut app, &ctx, at(&bar, "Tracing Result"));
click_label(&mut app, &ctx, "Outlines with Source Image");
assert_eq!(selected_trace(&app).map(|t| t.1), Some(vectorcraft_doc::TraceView::OutlinesWithSource));
assert_eq!(app.session.active().unwrap().selection.objects, traced, "the same object");
let bar = control_frame(&mut app, &ctx, vec![]);
click_control(&mut app, &ctx, at(&bar, "Default"));
click_label(&mut app, &ctx, "3 Colors");
assert_eq!(selected_preset(&app).as_deref(), Some("3 Colors"));
click_label(&mut app, &ctx, "Expand");
let st = app.session.active().unwrap();
let g = st.doc.node(st.selection.objects[0]).unwrap();
assert!(selected_preset(&app).is_none() && g.children().unwrap().iter().all(|c| !matches!(c.kind, NodeKind::Image(_))), "expanded");
assert!(selected_trace(&app).is_none() && g.children().unwrap().iter().all(|c| !matches!(c.kind, NodeKind::Image(_))), "expanded");
}
#[test]
+1 -1
View File
@@ -37,7 +37,7 @@ fn labels(items: &[Item]) -> Vec<&'static str> {
.collect()
}
fn shapes_text(shapes: &[Shape]) -> Vec<(String, Rect)> {
pub(crate) fn shapes_text(shapes: &[Shape]) -> Vec<(String, Rect)> {
fn walk(s: &Shape, v: &mut Vec<(String, Rect)>) {
match s {
Shape::Text(t) => v.push((t.galley.text().to_string(), Rect::from_min_size(t.pos, t.galley.size()))),
+1 -1
View File
@@ -78,7 +78,7 @@ fn slice_tool_cursors_are_drawn_in_code() {
let ctx = egui::Context::default();
let mut out = ctx.run_ui(Default::default(), |ui| {
for c in [vectorcraft_tools::Cursor::Slice, vectorcraft_tools::Cursor::SliceSelect] {
assert!(crate::cursors::paint(ui.painter(), c, egui::pos2(50.0, 50.0)), "{c:?}");
assert!(crate::cursors::paint(ui.painter(), c, egui::pos2(50.0, 50.0), 1.0), "{c:?}");
}
});
out.textures_delta.clear();
+1 -1
View File
@@ -12,7 +12,7 @@ fn the_width_tool_has_its_own_cursors() {
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| {
let painter = ui.painter().clone();
for c in [Cursor::Width, Cursor::WidthAdd, Cursor::WidthPoint] {
assert!(crate::cursors::paint(&painter, c, egui::pos2(50.0, 50.0)), "{c:?} is drawn");
assert!(crate::cursors::paint(&painter, c, egui::pos2(50.0, 50.0), 1.0), "{c:?} is drawn");
}
});
out.textures_delta.clear();
+15
View File
@@ -121,6 +121,21 @@ pub fn section_header(ui: &mut Ui, text: &str) {
ui.add_space(2.0);
}
/// A collapsible section's header across the panel: a chevron (down while `open`) and `text`;
/// a click anywhere on it toggles the section. Whether it was clicked.
pub fn section_toggle(ui: &mut Ui, text: &str, open: bool) -> bool {
let t = Tokens::get(ui.ctx());
let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 24.0), Sense::click());
if resp.hovered() {
ui.painter().rect_filled(rect, 3.0, t.hover);
}
let chevron = Rect::from_center_size(pos2(rect.left() + 8.0, rect.center().y), vec2(12.0, 12.0));
icons::paint(ui, if open { "chevron-down" } else { "chevron-right" }, chevron, if resp.hovered() { t.text_strong } else { t.icon });
ui.painter().text(pos2(rect.left() + 18.0, rect.center().y), egui::Align2::LEFT_CENTER, tl!(text), theme::semibold(12.5), t.text);
resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::CollapsingHeader, true, open, tl!(text)));
resp.on_hover_cursor(egui::CursorIcon::PointingHand).clicked()
}
/// Full-width 1 px divider with vertical margins.
pub fn divider(ui: &mut Ui) {
let t = Tokens::get(ui.ctx());
+1 -1
View File
@@ -154,7 +154,7 @@ Clicking a swatch there runs `swatch.library.add {library, names: [name], apply}
one with Alt), so one undo step adds and applies it; Shift/Cmd-clicks select swatches and colour groups for
Add to Swatches.
`window.swatchLibrary.other {path?}` loads a library file (or another document's swatches) and opens it there;
opening a `.vcswatches` or `.gpl` file with `app.open` does the same. `ui.saveSwatchLibrary {names?}` opens the
opening a `.vcswatches`, `.gpl` or `.ase` file with `app.open` does the same. `ui.saveSwatchLibrary {names?}` opens the
`saveSwatchLibrary` dialog (fields `name`, `format`: `vcswatches`/`gpl`/`css`, `user`: save to the user library
folder, `selectedOnly` with `names`); `ui.dialog.confirm` runs `swatch.library.save` (to a file it asks for a path).
+3 -2
View File
@@ -43,11 +43,12 @@ The canvas is rasterized on the CPU (`vectorcraft-render`, vello_cpu); the GPU (
- **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).
- 0.5.0 saved `powerSaving`, its default, for everyone; it reads as `automatic`.
- **If the window fails on its adapter while starting up** (an error from wgpu, or a panic inside wgpu or egui-wgpu during the first frames), the app starts again without that adapter and tries the next one, telling which in the status bar; the run that failed keeps its log as `vectorcraft.1.log`. On Unix the new app replaces the process (an AppImage stays mounted); on Windows it starts beside it. The adapters left out travel in `VECTORCRAFT_GPU_SKIP` (`backend:vendor:device`, such as `Vulkan:1002:164e`), one more on each restart, so the restarts end. When no adapter is left, the app logs why and exits with an error instead of panicking.
- **If the window fails on its adapter while starting up** (an error from wgpu, or a panic inside wgpu or egui-wgpu during the first frames), the app starts again without that adapter and tries the next one, telling which in the status bar; the run that failed keeps its log as `vectorcraft.1.log`. On Unix the new app replaces the process (an AppImage stays mounted); on Windows it starts beside it. Adapters are told apart by backend and PCI ids, or by name where the backend reports no ids (Metal lists every GPU of a dual-GPU Mac as `0000:0000`, #651). The adapters left out travel in `VECTORCRAFT_GPU_SKIP` (`backend:vendor:device`, such as `Vulkan:1002:164e`), one more on each restart, so the restarts end. When no adapter is left, the app logs why and exits with an error instead of panicking.
- **Environment variables** for when the choice still goes wrong, all read at startup and stronger than the preference:
- `WGPU_POWER_PREF`: `low`, `high` or `none` (the system's order).
- `WGPU_ADAPTER_NAME`: part of an adapter's name, any case (`WGPU_ADAPTER_NAME=nvidia`, `=radv`, `=intel`); the names are in the log.
- `WGPU_BACKEND`: the backends to use, such as `vulkan`, `dx12`, `metal` or `gl`.
- `WGPU_VALIDATION_INDIRECT_CALL=1`: turns wgpu's check of indirect draw arguments back on. VectorCraft draws nothing indirectly and turns it off, since the compute shader it needs fails to compile on some drivers (#651).
- On Linux with Mesa, `MESA_VK_DEVICE_SELECT=10de:2f04!` (vendor:device as `vulkaninfo --summary` or `lspci -nn` show it) leaves only that GPU to Vulkan, and `DRI_PRIME=1` picks the other GPU.
- Help › About and the control channel's `ui.inspect` (`graphicsAdapter`) show the adapter in use, and the app logs it at startup.
@@ -239,7 +240,7 @@ web build has no net at all.
Untrusted input has property tests that must never panic:
- `crates/engine/tests/import_fuzz.rs`: garbage, hostile and mutated SVG and PDF, and swatch
(`.vcswatches`, `.gpl`), graphic style (`.vcstyles`) and flattener preset (`.vcflattener`)
(`.vcswatches`, `.gpl`, `.ase`), graphic style (`.vcstyles`) and flattener preset (`.vcflattener`)
libraries, loaded and used, then rendered and exported.
- `crates/engine/tests/command_sweep.rs`: every command with junk parameters.
- `crates/format/tests/prop_format.rs`: garbage and mutated `.vectorcraft` files.
+4 -1
View File
@@ -740,7 +740,9 @@ swatch in the library panel does). `swatch.resetDefaults {replace?}` brings back
as a library (`.vcswatches` keeps colour models, global, spot, gradients and colour groups; `.gpl` is 8-bit RGB;
CSS writes custom properties); without `path` it returns `{data}`, and `user: true` saves into the user library
folder of the desktop app (listed as category `user`, User Defined). `swatch.library.load {path? | data? |
dataBase64?, name?}` loads a `.vcswatches` or `.gpl` file, or another document's swatches, as a library to add from.
dataBase64?, name?}` loads a `.vcswatches`, `.gpl` or swatch exchange (`.ase`) file, or another document's swatches,
as a library to add from. From an `.ase` file it reads RGB, CMYK, Lab and Gray colors as global, spot or process
swatches and keeps their color groups.
## Graphic style libraries
@@ -882,6 +884,7 @@ and `layerRows`, the rows highlighted in the panel.
dimImages, dimPercent; OK is one undo step), `ui.layersPanelOptions` opens Panel Options (`layersPanelOptions`:
layersOnly, rowSize small|medium|large|other, otherSize, thumbLayers, thumbGroups, thumbObjects), and
`ui.layersExpand {ids?, open?}` opens or closes rows as their triangles do (Alt-click: everything inside).
A document opens with only its top-level layers open; the open rows are saved in the native file and reopen that way.
```json
{"name":"run_command","arguments":{"command":"layer.newSublayer","params":{"name":"Shadows"}}}