Compare commits

...
Author SHA1 Message Date
bflatasticandClaude Opus 5.5 c71af3079c Part of gap 2: Effect › Video (De-Interlace, NTSC Colors)
Adds the Video group to the raster effects, after Sharpen:

- De-Interlace…: Eliminate Odd or Even Fields, Create New Fields by
  Duplication or Interpolation. The fields are the rows of the document's
  raster grid (Document Raster Effects Settings › Resolution, carried to
  the filters as PixelSpace::line) counted from the top of the page, so
  the result is the same at any zoom and moves with the page. A line
  taken out copies the line above (the one below at the top), or takes
  the average of the two.
- NTSC Colors (no options, applied at once): colours a composite
  television signal can't carry, with luma plus chroma past 110 % of white
  or luma minus chroma below -20 % in YIQ, have their chroma cut to fit,
  keeping their luma. Saturated yellow, cyan and pure red lose some
  saturation; legal colours stay as they are.

Catalogue rows with parameter docs, dialog dropdowns, menu, translations,
tests (effects, canvas, command sweep junk, menu) and ROADMAP.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 17:05:56 +07:00
BFlat 7fb2c47006 Merge pull request #939 from storytold/fix/811-identify-unnamed-glyphs
Fix #811: unnamed glyphs of an installed font stay in their type
2026-10-10 16:46:54 +07:00
bflatasticandClaude Opus 5.5 a61aa93c1c Fix #811: unnamed glyphs of an installed font stay in their type
In a PDF (or the PDF part of an .ai file), a glyph of a subset font that
no ToUnicode map, CID table or character map of the font program names
was drawn as outlines, so one text object came in split: "RADA" as the
type "ADA" plus the R's outline.

Such a glyph is now looked for in the installed face of the font's name:
the first character (of those single-byte fonts encode: ASCII, Latin-1,
Latin Extended-A, punctuation, the euro and trade mark signs, fi and fl)
whose glyph draws the same outline, point for point within 2/1000 em,
names it. A subset carries the font's own outlines, so an installed copy
of the same font finds every glyph. Other versions of the font, empty
glyphs and glyphs that are no character still keep their outlines, with
the warning as before. Results are cached per glyph.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 16:46:39 +07:00
BFlat 552945f4e7 Merge pull request #936 from storytold/fix/927-direct-marquee-type
Part of #927: Direct Selection marquees take the type they touch
2026-10-10 16:19:59 +07:00
bflatasticandClaude Opus 5.5 7bf002af2b Part of #927: Direct Selection marquees take the type they touch
A Direct Selection (or Group Selection) marquee only gathered the
anchors of paths, so type, images, symbols and other objects without
anchors to pick were never selected by it. They are now selected whole
when the marquee touches them, as with the Selection tool, next to the
path anchors it holds; locked and hidden objects stay out.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 16:19:44 +07:00
BFlat 3da4080b5e Merge pull request #935 from storytold/fix/918-place-psd
Fix #918: PSD and PSB files open and place as their merged image
2026-10-10 16:09:58 +07:00
bflatasticandClaude Opus 5.5 0eb4ce5e98 Fix #918: PSD and PSB files open and place as their merged image
File › Place and File › Open read PSD and PSB files: the merged image
every such document carries after its layers, which is what a linked PSD
shows. A placed PSD links like any image, so the Links panel updates and
relinks it, and it is sized by its ResolutionInfo resource.

The reader is written from the public file format specification. It
reads Bitmap, Grayscale, Duotone, Indexed, RGB, CMYK (through the colour
settings' CMYK) and Lab, at 1, 8, 16 and 32 bits per channel (32-bit
values are linear), raw, PackBits or zipped with or without prediction.
A document with transparency stores its merged image on white with the
alpha in the first extra channel. It comes back with straight colours,
also for 16- and 32-bit files, which say so in their Lr16/Lr32 block.
Multichannel files are refused with a message. The file is untrusted:
every read is bounds-checked and the image's size is checked against
the decode budget before anything is allocated.

PSB is a read-only format of its own, so exports never write a PSD under
a .psb name. The desktop packaging still doesn't associate either
extension with VectorCraft (UNASSOCIATED_EXTS): they belong to raster
editors. Layers (import options) are left for later.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 16:09:41 +07:00
BFlat be51213f0d Merge pull request #929 from haranishi/fix/eps-gradient-stop-cap
EPS import: bound the stitched-gradient builder
2026-10-10 16:06:43 +07:00
BFlat fe2d2ca173 Merge pull request #933 from storytold/fix/921-properties-gradient
Fix #921: the Properties panel's Gradient section with Type and Draw
2026-10-10 15:51:05 +07:00
bflatasticandClaude Opus 5.5 b3ed7df2a4 Fix #921: the Properties panel's Gradient section with Type and Draw
With the Gradient tool active, the Properties panel shows a Gradient
section: the type buttons (Linear, Radial, Freeform) and, for a
freeform gradient, Draw: Points or Lines as radio buttons. The Gradient
panel and the Properties panel share the type row and the draw mode
change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 15:50:23 +07:00
BFlat 93fb184939 Merge pull request #932 from storytold/fix/924-tab-leader-typing
Fix #924: the Tabs panel's Leader and Align On keep what is typed
2026-10-10 15:50:20 +07:00
bflatasticandClaude Opus 5.5 2ef32bb1a2 Fix #924: the Tabs panel's Leader and Align On keep what is typed
Both fields read their text from the tab stop again every frame, so each
keystroke was lost before Enter or a click away could apply it: the
field seemed to clear itself while typing. They now use the panels' text
field, which keeps the text being typed until it is committed. The
leader keeps spaces (". " for spaced dots), up to eight characters.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 15:49:49 +07:00
BFlat 5ccbbcca3f Merge pull request #931 from storytold/fix/925-links-on-focus
Fix #925: linked files changed in another app update when the window comes back
2026-10-10 15:49:46 +07:00
bflatasticandClaude Opus 5.5 11beb8fff1 Fix #925: linked files changed in another app update when the window comes back
Preferences › File Handling › Update Links only acted when a document
opened, so a linked image edited in another app while VectorCraft stayed
open kept its old pixels until Update Link in the Links panel, even with
Automatically chosen.

When the window comes back to the front, the active document's links
are now checked. With Automatically, changed files are read again; with
Ask When Modified, they are offered for update, once per change of a
file (keyed by path, size and modification time, since two saves can
share a time); with Manually, the Links panel shows them as modified.
Nothing is asked while a dialog is open.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 15:49:08 +07:00
BFlat 04eb5e52c8 Merge pull request #930 from storytold/feat/pixelate-effects
Part of gap 2: Effect › Pixelate (Color Halftone, Crystallize, Mezzotint, Pointillize)
2026-10-10 15:47:10 +07:00
bflatasticandClaude Opus 5.5 9bad0a24ca Part of gap 2: Effect › Pixelate (Color Halftone, Crystallize, Mezzotint, Pointillize)
Four Photoshop-style raster effects on the pixel-filter pipeline
(vectorcraft_effects::pixel::pixelate), under a new Effect › Pixelate
submenu between Blur and Sharpen in the Raster Effects section:

- Color Halftone (maxRadius 4..127, default 8; channel1..channel4 screen
  angles -360..360, defaults 108/162/90/45): each colour channel is
  screened at its angle in square cells sized so a dot of Max. Radius
  fills one; each cell's dot covers the share of the cell that is the
  channel's coverage-weighted mean there (white stays white, black
  black). RGB documents screen R, G, B (channels 1 to 3); CMYK documents
  screen C, M, Y, K inks (channels 1 to 4), also when they are drawn ink
  plane by ink plane (the K plane uses channel 4).
- Crystallize (cellSize 3..300, default 10): every pixel takes the
  colour at the nearest of one jittered point per cell (exact Voronoi
  over a 5 x 5 neighbourhood, pruned by distance).
- Mezzotint (type: Fine/Medium/Grainy/Coarse Dots, Short/Medium/Long
  Lines, Short/Medium/Long Strokes; default Fine Dots; a dropdown in the
  dialog): each channel is turned fully on or off against its own random
  threshold pattern, so the object becomes pure colours.
- Pointillize (cellSize 3..300, default 5): one dot of random size per
  cell at a jittered point, coloured by the softened object there and as
  opaque as the object at its centre, stacked in random order over a
  white canvas where the object is.

Lengths are in points (Scale Strokes & Effects scales them) and every
pattern lies in document space around the object's centre, so the
result is the same at any zoom or raster resolution, moves with the
object, and is identical on every redraw (hash noise of the pattern's
cell indices, no state). Work per pixel is bounded whatever the
parameters, which are clamped to their ranges and finite-checked; the
halftone's cell grid is capped by the raster's size and a screen finer
than 3 pixels leaves the image as it is (its average). PixelSpace gains
`channels` so the renderer tells the filters what the channels hold.

Catalogue rows with parameter docs, outsets and reaches for cropping,
menu entries, dialog labels (Max. Radius, Channel 1-4, Cell Size), the
Mezzotint Type dropdown, translations, and tests: parameters and
clamping, tone and coverage, CMYK inks, polygon crystals, pure-colour
mezzotints with ten distinct patterns, dots on a white canvas, the same
result at twice the resolution and when moved, the canvas, PDF and SVG
through the engine, the command sweep with junk parameters, the dialogs
and the menu.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 15:42:24 +07:00
BFlat 2d6014583a Merge pull request #923 from callmeBalloch/fix/artboard-artwork-movement
Fix artwork movement when editing artboard X/Y coordinates
2026-10-10 15:29:47 +07:00
Ikki NishiharaandClaude Sonnet 5.5 de3f53b24d EPS: bound the stitched-gradient builder
Cap the stops taken from a stitching function (1024), bound linear_points by
depth and by a shared visit count, and stop eval from copying the whole
Functions array on every call.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-10 17:29:45 +09:00
bflatasticandClaude Opus 5.5 f3f5e38bb6 ROADMAP: the #922 note joins the Last updated list
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 15:06:59 +07:00
Rick 934b65b42a M11: honor Move Artwork in artboard coordinate edits 2026-10-10 09:49:24 +02:00
BFlat e1599a16aa Merge pull request #799 from vbasky/feat/graph-series-palette
Colour graph series through Group Selection
2026-10-10 14:37:23 +07:00
bflatasticandClaude Opus 5.5 f21f8a89ce Graph series: find series art in one pass and ignore indices past the series
Painting looked up each selected object's graph by walking up through
parent_of, a search of the whole document per level, so a fill or stroke
change on a large selection grew with the square of the document. The
series art of every graph is now mapped in one pass, and documents with
no graph skip the lookup.

A series index comes from the file: one past the graph's series grew the
graph's series paints to that length. Such a group is no longer taken
for a series.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 14:33:41 +07:00
Vikram Bhaskaran 5c9ffc69e8 Colour graph series through Group Selection
Group Selection's fill and stroke on a graph series are kept on the graph,
separately per series, and reapplied when its data, type or size changes,
and through save, open and undo.
2026-10-10 14:33:40 +07:00
BFlat dd61dfa146 Merge pull request #920 from storytold/feat/885-transform-effect-dialog
Part of #885: the Transform effect's dialog takes Transform Each's controls
2026-10-10 14:32:55 +07:00
58 changed files with 3327 additions and 165 deletions

No files matched your search

+17 -15
View File
@@ -4,7 +4,7 @@ VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adob
This file tracks **how far we are and what's left**. Time estimates are wall-clock hours of continuous Claude Opus 5.5 agent work (including builds and the CI gate), given both for **one agent** and for **4–6 parallel agents** on disjoint crates. They are counted from the remaining work (see [Parity estimate](#parity-estimate)), calibrated against measured throughput, and updated as work lands.
_Last updated: 2026-10-10 (after placed documents (File › Place of a `.vectorcraft` file, linked), M4.14–M4.98, M8.1–M8.20, M14.4–M14.7, the MCP prompts, resource templates, completions and logging, the 2026-10-07 issue fixes, the Layers panel rework and the 2026-10-08 community contributions: Pen and shape-tool modifiers, path editing, Layers, Artboards, Swatches/Brushes and dialogs, Japanese composition and PDF text, Hebrew/Arabic type, interface languages (Spanish among them), the font menu, saved selections, MCP and EPS, the missing-font export warning (#319), open paths in the Shape Builder (#374), PDF/`.ai` import keeping strokes live and hidden and nested layers (#372), per-corner Live Corners (#381), SVG type opening at the size it draws at (#396), the Wayland clipboard with copied-file paste (#398), ruler guides that can be selected, moved and deleted (#414), two batches of Preferences options that were stored but unused (#394), skeleton reads with `document.find` for large documents over MCP (#416) and anchors dragged with Direct Selection snapping to points, segments and smart guides, clipped SVG layers opening as clipping layers (#420), PDF/`.ai` layers read on pages of tens of millions of operators (#419), Document Color Mode putting RGB greys on the black plate on request and converting pattern tiles (#421) and movable dialogs with Offset Path's Joins dropdown (#423) and numeric fields scrubbed by dragging their label (#400), stroke weight presets in the stroke unit (#426), the Appearance panel's Opacity popup (#430), type on a path brackets, flip and Type on a Path Options that keep the type in place (#429), Layers rows dragged with a ghost and dropped on the trash or New Layer (#435), tool flyouts opening on a right or corner press (#436), tool flyouts torn off into floating toolbars (#437), the Shape Builder's erase mode deleting edges too (#439), installed fonts registered outside the font folders and fonts installed while the app runs listed in the font menus (#443), alike circular corners on rectangles that aren't square (#442), tool cursors as OS cursors so the pointer no longer trails over the canvas (#444), artboards copied and pasted with their art (#446), guides dragged out of the rulers snapping to the art's side midpoints and the artboards, artboard guides (#451), the toolbar's double arrow and Window › Toolbars › Double Column switching between one and two columns in any window height (#455), the Smart Guides display options and Snapping Tolerance (#394), Font Size and Leading combo boxes with preset lists in the Character and Properties panels and the Control bar (#458), screenshots pasted from the clipboard on macOS, Windows and the web (#457), the Properties panel's Fill and Stroke matching the Control bar's, Illustrator's Window menu panel keys (Shift+F7 for Align…) and Alt-wheel zoom whatever the wheel preference (Discord feedback), the point/area type widget (Discord feedback), groups in legacy Illustrator .ai files (Discord feedback), a rotating desktop log file (#465), image controls in the Control bar and Properties panel: Image Trace with its presets, Mask, Crop Image, Embed/Unembed, and an Image Trace object's preset, Expand and Release (Discord feedback), the Pen working as the Anchor Point tool with Alt held over a selected path's handles and anchors, and anchor buttons that convert, connect and cut paths at the selected anchors (Discord feedback), Japanese hanging punctuation (burasagari, #463), Escape leaving Presentation Mode with no screen mode saved across restarts, documents dropped on the desktop app opening as tabs of their own and a note that an `.ai` file's art off its artboards isn't in the part read (#472), Add/Delete Anchor Point tool icons drawn from the Pen tool's (#479), EPS import running more of PostScript Level 3 (patterns, Type 3 fonts, mesh shadings, masked images, VM and resource probes), and a preview that stands in saying why (Discord feedback, #466, #469, #474), chords with modifiers recorded in Edit › Keyboard Shortcuts (#487), Type Object Selection by Path Only (#394), Anti-aliased Artwork (#394), Show Pixel Grid (#394), pen and touch taps pressed and lifted within one frame clicking where they tapped and the Linux/Wayland pen-tablet workaround (#491), bounding-box resizes landing on the other objects' anchors and centres with labels, and the Rotate, Scale, Shear and Reflect tools snapping their drags (#482), Shift-drag marquees that toggle the objects or anchors they reach and a Lasso whose Alt subtraction keeps the rest of the selection (#483), the mouse wheel stepping the focused numeric field, the dialogs' and preferences' drag values made such fields (#485), Show The Home Screen When No Documents Are Open (#394), Numbers Without Units Are Points (#394), Auto-Collapse Iconic Panels (#394), the Contextual Task Bar moved by its handle and its More Options menu pinning and resetting its position, a designed macOS DMG windoLine truncated
_Last updated: 2026-10-10 (after placed documents (File › Place of a `.vectorcraft` file, linked), M4.14–M4.98, M8.1–M8.20, M14.4–M14.7, the MCP prompts, resource templates, completions and logging, the 2026-10-07 issue fixes, the Layers panel rework and the 2026-10-08 community contributions: Pen and shape-tool modifiers, path editing, Layers, Artboards, Swatches/Brushes and dialogs, Japanese composition and PDF text, Hebrew/Arabic type, interface languages (Spanish among them), the font menu, saved selections, MCP and EPS, the missing-font export warning (#319), open paths in the Shape Builder (#374), PDF/`.ai` import keeping strokes live and hidden and nested layers (#372), per-corner Live Corners (#381), SVG type opening at the size it draws at (#396), the Wayland clipboard with copied-file paste (#398), ruler guides that can be selected, moved and deleted (#414), two batches of Preferences options that were stored but unused (#394), skeleton reads with `document.find` for large documents over MCP (#416) and anchors dragged with Direct Selection snapping to points, segments and smart guides, clipped SVG layers opening as clipping layers (#420), PDF/`.ai` layers read on pages of tens of millions of operators (#419), Document Color Mode putting RGB greys on the black plate on request and converting pattern tiles (#421) and movable dialogs with Offset Path's Joins dropdown (#423) and numeric fields scrubbed by dragging their label (#400), stroke weight presets in the stroke unit (#426), the Appearance panel's Opacity popup (#430), type on a path brackets, flip and Type on a Path Options that keep the type in place (#429), Layers rows dragged with a ghost and dropped on the trash or New Layer (#435), tool flyouts opening on a right or corner press (#436), tool flyouts torn off into floating toolbars (#437), the Shape Builder's erase mode deleting edges too (#439), installed fonts registered outside the font folders and fonts installed while the app runs listed in the font menus (#443), alike circular corners on rectangles that aren't square (#442), tool cursors as OS cursors so the pointer no longer trails over the canvas (#444), artboards copied and pasted with their art (#446), guides dragged out of the rulers snapping to the art's side midpoints and the artboards, artboard guides (#451), the toolbar's double arrow and Window › Toolbars › Double Column switching between one and two columns in any window height (#455), the Smart Guides display options and Snapping Tolerance (#394), Font Size and Leading combo boxes with preset lists in the Character and Properties panels and the Control bar (#458), screenshots pasted from the clipboard on macOS, Windows and the web (#457), the Properties panel's Fill and Stroke matching the Control bar's, Illustrator's Window menu panel keys (Shift+F7 for Align…) and Alt-wheel zoom whatever the wheel preference (Discord feedback), the point/area type widget (Discord feedback), groups in legacy Illustrator .ai files (Discord feedback), a rotating desktop log file (#465), image controls in the Control bar and Properties panel: Image Trace with its presets, Mask, Crop Image, Embed/Unembed, and an Image Trace object's preset, Expand and Release (Discord feedback), the Pen working as the Anchor Point tool with Alt held over a selected path's handles and anchors, and anchor buttons that convert, connect and cut paths at the selected anchors (Discord feedback), Japanese hanging punctuation (burasagari, #463), Escape leaving Presentation Mode with no screen mode saved across restarts, documents dropped on the desktop app opening as tabs of their own and a note that an `.ai` file's art off its artboards isn't in the part read (#472), Add/Delete Anchor Point tool icons drawn from the Pen tool's (#479), EPS import running more of PostScript Level 3 (patterns, Type 3 fonts, mesh shadings, masked images, VM and resource probes), and a preview that stands in saying why (Discord feedback, #466, #469, #474), chords with modifiers recorded in Edit › Keyboard Shortcuts (#487), Type Object Selection by Path Only (#394), Anti-aliased Artwork (#394), Show Pixel Grid (#394), pen and touch taps pressed and lifted within one frame clicking where they tapped and the Linux/Wayland pen-tablet workaround (#491), bounding-box resizes landing on the other objects' anchors and centres with labels, and the Rotate, Scale, Shear and Reflect tools snapping their drags (#482), Shift-drag marquees that toggle the objects or anchors they reach and a Lasso whose Alt subtraction keeps the rest of the selection (#483), the mouse wheel stepping the focused numeric field, the dialogs' and preferences' drag values made such fields (#485), Show The Home Screen When No Documents Are Open (#394), Numbers Without Units Are Points (#394), Auto-Collapse Iconic Panels (#394), the Contextual Task Bar moved by its handle and its More Options menu pinning and resetting its position, a designed macOS DMG windoLine truncated
## Where we are
@@ -35,10 +35,10 @@ since 2026-10-01.
|---|---|---|
| **Breadth:** menus, tools and panels exist | ~90% | 13 menu items still stubbed; every tool implemented except Touch Type; 51 panel modules |
| **Depth:** each feature behaves like Illustrator | ~69–75% | Strong: paint, appearance and colour (M3), Pathfinder and booleans, selection, drawing, files (M4). Weak: advanced type (~45%; inline symbols in text are beyond parity and don't raise it), brushes and symbols (in progress), raster effects (~20%) |
| **Large missing subsystems** | 0–20% | 3D & Materials (0%), Photoshop-style raster effects and the Effect Gallery (~4 of ~56 filters), SVG Filters, CJK composition (vertical type with kinsoku, tate-chu-yoko and the font's vertical metrics; ruby, mojikumi and proportional vertical metrics open), Variables (data merge), scripting |
| **Large missing subsystems** | 0–20% | 3D & Materials (0%), Photoshop-style raster effects and the Effect Gallery (~10 of ~56 filters), SVG Filters, CJK composition (vertical type with kinsoku, tate-chu-yoko and the font's vertical metrics; ruby, mojikumi and proportional vertical metrics open), Variables (data merge), scripting |
| **Interaction fidelity:** modifiers, cursors, small behaviours | ~30–40% | The dedicated pass hasn't started, and there has been no side-by-side session with Illustrator yet. A power user notices this first |
| **Look & feel** | ~75–80% | Measured against Illustrator 2026 screenshots (2026-10-02); the panels added since haven't been re-measured |
| **File interop** | ~85% | SVG/SVGZ, PDF and PDF-compatible `.ai`, EPS, DXF, EMF/WMF, raster formats, PSD export, Place and Links, Package, Print, clipboard flavours. Affinity documents (Affinity 1–3) open natively as editable art, checked against 51 pinned public files (33 current `.af`), with selected saved-thumbnail comparisons and every-board native/SVG/PDF/PSD checks for current files; Affinity export is missing and effects, adjustments and brushes don't import. Affinity isn't an Illustrator feature, so this doesn't raise the parity score. The editing copy inside an Illustrator EPS or `.ai` is read for its structure: layers, groups, names, hidden objects and type, colours, gradients, transparency, images and every artboard (see Out of scope for what it doesn't read yet); DWG has no open spec |
| **File interop** | ~85% | SVG/SVGZ, PDF and PDF-compatible `.ai`, EPS, DXF, EMF/WMF, raster formats, PSD export and PSD/PSB placement (merged image), Place and Links, Package, Print, clipboard flavours. Affinity documents (Affinity 1–3) open natively as editable art, checked against 51 pinned public files (33 current `.af`), with selected saved-thumbnail comparisons and every-board native/SVG/PDF/PSD checks for current files; Affinity export is missing and effects, adjustments and brushes don't import. Affinity isn't an Illustrator feature, so this doesn't raise the parity score. The editing copy inside an Illustrator EPS or `.ai` is read for its structure: layers, groups, names, hidden objects and type, colours, gradients, transparency, images and every artboard (see Out of scope for what it doesn't read yet); DWG has no open spec |
| **Bundled content:** brush, symbol, style and swatch libraries | ~30% | Ours are original and generated in code, and far fewer than Illustrator ships; brush and symbol libraries are still missing |
| **Performance** | unverified | Multithreaded, off-thread rendering and caches are in place. The last budget run (2026-10-01, loaded machine) measured 290 ms for a 50k-path fit against a 16 ms budget. Re-run `vectorcraft-cli perf` on an idle machine |
| **Robustness** | good, new | ~2,840 tests, property tests, no panics in shipped code (lints, the `guard` safety net, import fuzzing), Data Recovery. Missing: a corpus of real-world files, Windows/Linux/browser QA |
@@ -53,12 +53,13 @@ Ordered by how much each gap blocks someone from switching. Sizes are one-agent
1. **Interaction fidelity:** go tool by tool and panel by panel against `plan/illustrator/05-tools.md`,
`06-panels.md` and `09-shortcuts.md`, covering modifier keys, cursors, the Properties panel per context and
isolation mode. The Shaper’s rough-square recognition and shape orientation steps are corrected; Shaper Groups now retain editable originals for region merges/punches and separate fill/stroke edits; their construction-mode widget and gesture refinements remain. 60–90 h.
2. **Photoshop-style raster effects and the Effect Gallery:** about 51 filters (Artistic, Brush Strokes, Distort,
Pixelate, Sketch, Stylize, Texture, Video) and the Effect Gallery. The pixel-filter pipeline is in place
2. **Photoshop-style raster effects and the Effect Gallery:** about 45 filters (Artistic, Brush Strokes, Distort,
Sketch, Stylize, Texture) and the Effect Gallery. The pixel-filter pipeline is in place
(`vectorcraft_effects::pixel`: the object rendered offscreen, filtered in stack order with Gaussian Blur and
Feather, cached while panning, images in PDF/SVG/Expand Appearance) with Blur › Radial Blur and Smart Blur
(Normal mode only), Sharpen › Unsharp Mask and Stylize › Glowing Edges; each new filter is now one function, a catalogue row, menu and
translations. Parallelizes well across agents. 26–40 h.
(Normal mode only), Pixelate › Color Halftone, Crystallize, Mezzotint and Pointillize, Sharpen › Unsharp Mask,
Stylize › Glowing Edges and Video › De-Interlace and NTSC Colors; each new filter is now one function, a catalogue row, menu and translations. Parallelizes
well across agents. 23–36 h.
3. **3D and Materials:** Extrude & Bevel, Revolve, Inflate and Rotate with lighting and materials, using a software
renderer in its own crate (layering allows it below L6), with output in SVG/PDF as rasters or projected vectors.
The largest single gap. 50–80 h.
@@ -93,6 +94,7 @@ When a task lands, update this section, the parity table and "Shipped so far" in
grade by behaviour against `plan/illustrator/`, not by whether a menu item exists.
## Shipped so far
- **Architecture:** 19+ crates with enforced layering (`cargo xtask layers`). Every action is a command (~400 engine + ~50 UI). Undo is unlimited via structural sharing. `command.batch` runs several commands as one transaction.
- **Automation:**
- Actions panel (record/playback, persisted), generic parameter dialogs for every "…" command.
@@ -136,7 +138,7 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist
- **Live Corners:** drag a live rectangle's corner widgets (Selection or Direct Selection) to round all corners, with a radius readout; with Direct Selection, select corner anchors to show and round just those corners (#381). Each corner keeps its own radius and kind (Round, Inverted Round, Chamfer): Alt-click a widget to cycle the kind, double-click it for the Corners dialog, and the Properties and Transform radius fields set the selected corners (`object.setLiveShape {corners, radius, kind}`). Corners stay circular when the rectangle is scaled unevenly or along its own sides when rotated (the radius keeps its size, or scales by the mean scale with Scale Corners on); only a shear distorts them. On a rectangle that isn't square every corner is the same circle: a radius past half the shorter side stops there for all of them, the widgets sit on the corners as drawn and turn the edited corners red at that limit, CSS export writes the drawn radii, and rectangles saved stretched by older versions get circular corners when their corners are next set (#442). Live Corners work on any path's corners too, as on a rectangle's (#511): a star's, a live polygon's (which also shows them to the Selection tool, has a Corner Radius field in the Properties and Transform panels and keeps its radius as its sides change) and a pen path's, wherever two straight sides meet at an anchor. Direct Selection shows the widgets of every corner, or of the corners holding selected anchors; each corner is a circle tangent to both sides, drawn no larger than takes its cut halfway along its shorter side; a path keeps its uncut outline so its corners stay editable, and the same command, dialog, angle preference and View › Hide Corner Widget apply.
- **Pen:** Alt pressed in the middle of dragging out an anchor splits its handles and keeps the curve already shaped into it (only the outgoing handle follows the pointer); Space held while dragging out an anchor moves it, handles and all. A press on the first anchor of the path being drawn closes it whatever the drag then does: the drag shapes the closing curve (symmetric handles, Alt breaks them) and the release closes the path wherever it ends (#501). Clicking the last anchor of the path being drawn retracts its outgoing handle (convert cursor), and dragging from it pulls out a new one on its own. Auto Add/Delete: over a selected path, a click on a segment adds an anchor and a click on an anchor deletes it (add and delete cursors); Shift held, or Preferences › General › Disable Auto Add/Delete, starts a new path instead. Alt held over a handle end or an anchor of a selected path (the one being drawn too) works as the Anchor Point tool, with its convert cursor: dragging a handle moves it alone, clicking a smooth anchor makes it a corner, dragging an anchor pulls out new symmetric handles, dragging a segment reshapes it; drawing then goes on. Cmd (Ctrl) held drags with the selection tool chosen last, Direct Selection until one is (handles, anchors and segments of the path being drawn or another), and the Pen then goes on drawing its path while that stays selected; the pointer shows that tool's while Cmd is held. The same holds for agents (`pointer_gesture` with `mods.cmd`), as the borrowing now lives in the engine (#494).
- **Path editing (#494):** the handles shown are the handles that drag: Direct Selection drags those of a path selected as a whole (as the Pen leaves it), the Anchor Point tool and Pen+Alt no longer grab handles that Show handles when multiple anchors are selected hides, a handle shorter than the tolerance leaves its anchor to be picked, and the anchor tools pick within Selection & Anchor Display › Tolerance. A dragged segment keeps a smooth anchor at either end smooth. With Direct Selection, the Pen, the Curvature and the anchor tools, a path selected as a whole shows all its anchors selected, and the Control bar and the Properties panel offer Convert (corner, smooth) for them too; Remove and Cut wait for anchors direct-selected (#504). A handle drag gathers its snap targets once per drag (it took 21 ms per pointer move on a 20,000-path document, now 1 ms; `vectorcraft-cli perf` measures handle and segment drags on a 5,000-anchor path).
- **Graphs:** Column, Stacked Column, Bar, Stacked Bar, Line, Area, Scatter, Pie and Radar graph tools with Graph Data and Graph Type.
- **Graphs:** Column, Stacked Column, Bar, Stacked Bar, Line, Area, Scatter, Pie and Radar graph tools with Graph Data and Graph Type. A series starts in greyscale; Group Selection's fill and stroke are kept separately on the graph and reapplied when its data, type or size changes, and through save, open and undo. Graph Design, Column and Marker artwork remain open.
- **Other:** Eyedropper, Gradient annotator, Artboard (Alt-drag duplicates an artboard, and its art with Move/Copy Artwork with Artboard on; Copy, Cut and Paste take the artboard with its art, Paste right of the last artboard, Paste in Place where it was, into this or another document, #446; Object › Artboards › Rearrange All Artboards lays them out in a grid by row or by column, in one row or one column, left to right or right to left, from the menu, the Artboards panel or Properties' Rearrange All, #681; Scale Artwork with Artboard, in the Control bar and Properties beside Move Artwork with Artboard, resizes the artboard proportionally with the art fully inside it and its guides, strokes and corners per the Scale preferences, #602), Measure, Type, Hand, Zoom, Rotate View.
- **Editing type:** double-clicking type with a selection tool switches to the Type tool with the caret where it was clicked.
- **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.
@@ -169,7 +171,7 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist
- **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; 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; art reaching past a plain PDF's page clipped to its crop box, as PDF viewers show it, each such object in a clip group of its own (a PDF-compatible `.ai` opens whole: #675); 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). A masked CMYK image (`/SMask`, `/Mask` or a colour key) keeps its inks too, its alpha coming in as a greyscale opacity mask.
- 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). PDF export writes type as real, searchable text in embedded subset fonts by default, as Illustrator's PDF presets do (Convert Text to Outlines is an option; printer's marks stay shapes), so text-heavy PDFs stay small (#733). DXF export writes each fill as its outlines followed by its hatch, so laser and cutter software, which skips hatches, gets filled art and type too (#546).
- 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; PSD and PSB files open and place, linked or embedded, as their merged image in every colour mode and depth (#918). 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). PDF export writes type as real, searchable text in embedded subset fonts by default, as Illustrator's PDF presets do (Convert Text to Outlines is an option; printer's marks stay shapes), so text-heavy PDFs stay small (#733). DXF export writes each fill as its outlines followed by its hatch, so laser and cutter software, which skips hatches, gets filled art and type too (#546).
- Affinity documents in (AF.1–AF.4): `.af` (Affinity 3) and `.afdesign`/`.afphoto`/`.afpub` (Affinity 1 and 2, container versions 8–12) open and place as editable art: layers and sublayers, groups (pass-through or isolated), artboards (with their names and backgrounds) and Publisher pages side by side, curves with live corners, parametric shapes (rectangles with corner radii, ellipses, polygons, stars, pies, triangles, trapezoids), compound shapes, solid/linear/elliptical gradient fills and strokes (weight, dashes, alignment, scale-with-object), clipping by nesting, vector and pixel masks, artistic and frame text with fonts, sizes, tracking, leading and alignment, placed images (their original JPEG/PNG) and pixel layers (8/16-bit RGB, CMYK), opacity, visibility, locking and blend modes, at the document's resolution in points. Effects, adjustments, brushes and pressure profiles, transparency gradients, master pages, symbol instances (imported as their cached picture), special shapes (cloud, heart, cog…, imported as ellipses) and Affinity-only blend modes are named in the import warning. A file whose native data can't be read opens as its embedded preview with the reason, and that preview can't be placed. Save never writes back over the Affinity file and there is no Affinity export. AF.4 adds Affinity 3 artboard recognition and actual-outline clipping, source-backed JPEG/PNG raster tiles, Unicode text-run recovery, stored fallback/exact installed fonts, OpenType feature flags and compound-geometry limits. 51 public CC0/MIT/Apache-2.0 files (33 current `.af`), pinned and sha256-verified (`cargo xtask corpus --affinity`), test native retention and every-board native/SVG/PDF/PSD output for current files; selected files compare their saved thumbnails. No Affinity reopen or independent paired PSD oracle was available; [source audit and complex-font gaps](docs/affinity-validation.md); [scope, provenance and limits](crates/affinity/README.md).
- 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 (placed `.vectorcraft` documents packaged with their own linked files and fonts, relinked to the copies: #777), 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).
@@ -192,8 +194,8 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist
| M8 | Transform & distort (Puppet Warp, Liquify tools, Envelopes, Blends, Perspective Grid) | ✅ done (M8.1–M8.20 on 2026-10-06, fidelity pass): Liquify Tool Options with one shared brush, pen pressure, hold-to-apply, a safe scope and incremental strokes; tool options that last; Puppet Warp rotation, multi-select, Control bar and a rest-shape session that follows Undo; Width tool on compound paths; Envelope dialogs with preview, Reset with Warp/Mesh, full Envelope Options, type/images/symbols/appearance/gradients/patterns distorted on canvas and in every export, warps that keep their frame, Edit Contents, mesh handles and Control bar; Blend Options, anchor-targeted Blend tool, editable spine, keys picked on the canvas, faithful interpolation and knockout; Perspective Grid with Define Grid, presets, lock/snap/rulers, widgets, the 1–4 plane switch, movable planes, Perspective Selection scale/copy/perpendicular/Transform Again, and type and symbols truly projected with Edit Text. Left: Anti-Alias and Preserve Shape output, warp-envelope point editing, brush interpolation in blends, Free Transform/Scale/Reflect along a rotated box | 2–4 |
| M9 | Live effects (+ 3D & Materials) | 🟡 2D effects done incl. Effect → Pathfinder and Color Adjustments; SVG Filters, Document Raster Effects Settings, 3D pending | 86–135 |
| M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG `<pattern>`/PDF export) and live Repeat (radial/grid/mirror) done; brushes/symbols in progress | 23–37 |
| M11 | Artboards & views (artboard panel/tool, Trim View, middle-button pan, print tiling and the status bar's artboard navigator done; multiple windows, presentation polish) | 🟡 | 15–25 |
| M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (13 presets, 18 ms/1k² image; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, regenerate in place) done; graph Design/Column/Marker designs pending | 6–10 |
| M11 | Artboards & views (artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View, middle-button pan, print tiling and the status bar's artboard navigator done; multiple windows, presentation polish) | 🟡 | 15–25 |
| M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (13 presets, 18 ms/1k² image; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; graph Design/Column/Marker designs pending | 6–10 |
| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 | 18–27 |
| M14 | 1.0 polish (preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) | 🟡 Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed), workspaces, a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8); an experimental, unsupported Windows 7 x64 portable OpenGL build (not verified by maintainers); accessibility and broader Windows/Linux packaging/QA pending | 18–28 |
| — | Interaction fidelity pass (every tool's modifiers, Properties panel per context, isolation, nuance) | ⬜ | 60–90 |
@@ -221,16 +223,16 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale)
| Strokes, brushes, width profiles | 5 | 89% | Scatter, Art and Pattern Brush Options (Calligraphic and Bristle done), brush libraries (generated in code), pen pressure on macOS (the windowing layer reports none there), brushes driven by pen tilt, bearing and barrel rotation (6D art pens) | 10–18 |
| Appearance, transparency, graphic styles, masks | 5 | 98% | raster effect reach in preview bounds (flattener presets apply in PDF, EPS and print) | 1–2 |
| Live vector effects | 5 | 85% | Outline Object, Pathfinder Hard/Soft Mix and Trap, SVG Filters, the Transform effect's Transform Objects/Patterns and Scale Strokes & Effects options | 6–10 |
| Raster effects (Effect Gallery, Document Raster Effects Settings) | 4 | 25% | ~51 Photoshop-style filters (Artistic, Brush Strokes, Distort, Pixelate, Sketch, Stylize, Texture, Video), Smart Blur's Edge Only / Overlay Edge modes and the Effect Gallery; Document Raster Effects Settings, raster effects in PDF, the pixel-filter pipeline, Radial Blur, Smart Blur, Unsharp Mask and Glowing Edges are done | 26–40 |
| Raster effects (Effect Gallery, Document Raster Effects Settings) | 4 | 29% | ~45 Photoshop-style filters (Artistic, Brush Strokes, Distort, Sketch, Stylize, Texture), Smart Blur's Edge Only / Overlay Edge modes and the Effect Gallery; Document Raster Effects Settings, raster effects in PDF, the pixel-filter pipeline, Radial Blur, Smart Blur, Unsharp Mask, Glowing Edges, Pixelate (Color Halftone, Crystallize, Mezzotint, Pointillize) and Video (De-Interlace, NTSC Colors) are done | 23–36 |
| 3D and Materials | 4 | 0% | Extrude & Bevel, Revolve, Inflate, Rotate, lighting, materials (software renderer) | 50–80 |
| 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), custom kinsoku sets (beyond Hard, Soft and None) 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 | 72% | graph Design/Column/Marker, Create Object Mosaic, per-feature stroke/fill choice and varying widths in Image Trace's Create Strokes (Vector Halftone and the Image Trace View modes, Palette and Create Strokes are done) | 6–10 |
| Layers, artboards, document setup | 5 | 82% | Layers panel: a confirmation before deleting layers that hold art, Collect for Export, row context menus, the Layer Options dialog for several rows with mixed values, Paste Remembers Layers for sublayers, drag-scrolling a long panel while dragging rows; artboard preset polish (Rearrange All Artboards, Document Setup, New Document and the rest of the Layers panel are done) | 4–7 |
| Image Trace, graphs, image tools | 3 | 72% | graph Design/Column/Marker artwork (series colours set with Group Selection are done), Create Object Mosaic, per-feature stroke/fill choice and varying widths in Image Trace's Create Strokes (Vector Halftone and the Image Trace View modes, Palette and Create Strokes are done) | 6–10 |
| Layers, artboards, document setup | 5 | 82% | Layers panel: a confirmation before deleting layers that hold art, Collect for Export, row context menus, the Layer Options dialog for several rows with mixed values, Paste Remembers Layers for sublayers, drag-scrolling a long panel while dragging rows; artboard preset polish (Move Artwork for artboard X/Y edits, Rearrange All Artboards, Document Setup, New Document and the rest of the Layers panel are done) | 4–7 |
| View & navigation | 3 | 70% | New View/Edit Views, multiple windows/arrange, Snap to Pixel/Glyph (print tiling is done) | 9–14 |
| Guides, grids, smart guides, snapping, rulers | 3 | 85% | global/video rulers, Spacing Guides' distance readouts and spacing for resized or drawn art, Smart Guides' angle and distance readouts while drawing, Alt swapping a ruler guide's orientation, ruler guides selected together with art (marquee, Shift-click), ruler guides as Layers rows with their own lock and hide (#451: Lock Guides locks them all; Make Guides paths are Layers rows already) (dragging existing guides is done, #414; new guides snapping to side midpoints and artboards, and artboard guides, #451; the drawing tools snapping, with Construction Guides, #506; Spacing Guides for moves, #394; moves snapping to the grid, #740; ruler guides pulling drawn points with Smart Guides on, and "center" and "anchor" labels while hovering with the Selection tool, #812) | 2–4 |
| File formats | 6 | 85% | Affinity export, and the rest of Affinity import (effects, adjustments, brushes, master pages, live symbol instances), DWG (no open spec: DXF instead), PSD placement as layers, EPS checked against more real files users send (Inkscape files open as vectors; other generators' constructs are tested with programs written from the PostScript Language Reference only; CID-keyed CJK type and `CCITTFaxDecode` images not read), legacy `.ai` files saved without the prolog that defines their operators (their own operator set isn't read yet), the rest of Illustrator's editing data (appearances and live effects, symbols, pattern fills, brushes, placed files: #637), the remaining fidelity polish; EPS, DXF, EMF/WMF, TIFF, BMP, Targa, PSD export, SVGZ, PDF security, PDF/X, PDF layers, presets and Affinity import are done | 6–10 (existing scope; Affinity export unestimated) |
| File formats | 6 | 85% | Affinity export, and the rest of Affinity import (effects, adjustments, brushes, master pages, live symbol instances), DWG (no open spec: DXF instead), PSD placement as layers (Photoshop Import Options; the merged image is done), EPS checked against more real files users send (Inkscape files open as vectors; other generators' constructs are tested with programs written from the PostScript Language Reference only; CID-keyed CJK type and `CCITTFaxDecode` images not read), legacy `.ai` files saved without the prolog that defines their operators (their own operator set isn't read yet), the rest of Illustrator's editing data (appearances and live effects, symbols, pattern fills, brushes, placed files: #637), the remaining fidelity polish; EPS, DXF, EMF/WMF, TIFF, BMP, Targa, PSD export, SVGZ, PDF security, PDF/X, PDF layers, presets and Affinity import are done | 6–10 (existing scope; Affinity export unestimated) |
| Export for Screens, Asset Export, slices, Save for Web | 3 | 85% | polish only (all four are done) | 2–4 |
| Print, colour management, separations, flattener | 3 | 80% | print preview fidelity (flattener presets in PDF and print, overprint in PDF and composite print, Print dialog, presets, PostScript, marks, separations, Print Tiling, print overprint/flattener/bitmap options and printer profile are done) | 1–2 |
| Automation | 3 | 60% | Variables (data merge), scripting surface, batch | 8–12 |
+4 -3
View File
@@ -621,13 +621,14 @@ mod tests {
.collect()
}
/// Finder offers the app for every file File › Open reads (#295, #354), takes over no other
/// app's files, and hands them to the app rather than to AppKit's document machinery.
/// Finder offers the app for every file File › Open reads (#295, #354) but Photoshop documents
/// (`UNASSOCIATED_EXTS`), takes over no other app's files, and hands them to the app rather than
/// to AppKit's document machinery.
#[test]
fn the_macos_bundle_opens_every_readable_format() {
let plist = include_str!("../../../packaging/macos/Info.plist.in");
let declared = plist_extensions(plist);
for e in fileio::OPEN_EXTS {
for e in fileio::OPEN_EXTS.iter().filter(|e| !fileio::UNASSOCIATED_EXTS.contains(e)) {
assert!(declared.contains(e), "Info.plist.in doesn't declare .{e}");
}
for e in &declared {
+18
View File
@@ -64,12 +64,29 @@ impl GraphKind {
}
}
/// The fill and stroke captured from one series' generated marks. An absent paint keeps whatever
/// the generator draws for that part (greyscale for a series fill, the part's own stroke otherwise).
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct SeriesPaint {
#[serde(skip_serializing_if = "Option::is_none")]
pub fill: Option<vectorcraft_color::Paint>,
#[serde(skip_serializing_if = "Option::is_none")]
pub stroke: Option<vectorcraft_color::Paint>,
/// Stroke weight in points, kept with [`Self::stroke`].
#[serde(skip_serializing_if = "Option::is_none")]
pub stroke_width: Option<f64>,
}
/// Graph data and options. `rows` are categories (one per row of the Graph Data window), each
/// holding one value per series; `series` are the legend labels (the first row of the window).
/// Scatter graphs read each series as (y, x) column pairs, like Illustrator.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct GraphSpec {
/// Paint taken from the series' marks (Group Selection). One entry per series index; missing
/// entries keep the generator's own fill and stroke.
pub series_paints: Vec<SeriesPaint>,
pub kind: GraphKind,
/// The plot rectangle (the area the graph tool dragged), document points.
pub rect: Rect,
@@ -97,6 +114,7 @@ pub struct GraphSpec {
impl Default for GraphSpec {
fn default() -> Self {
Self {
series_paints: vec![],
kind: GraphKind::Column,
rect: Rect::new(0.0, 0.0, 200.0, 150.0),
series: vec![],
+1 -1
View File
@@ -65,7 +65,7 @@ pub use appearance::{
};
pub use assets::ExportAsset;
pub use corners::LiveCorners;
pub use graph::{GraphKind, GraphSpec};
pub use graph::{GraphKind, GraphSpec, SeriesPaint};
pub use hit::{Hit, HitKind};
pub use links::{LinkInfo, PlacementOptions};
pub use live::{BlendOrientation, BlendSpacing, BlendSpec, EnvelopeKind, GradientMesh, MeshPoint};
+5
View File
@@ -528,6 +528,10 @@ pub struct Node {
/// Graph object: the group's children are generated from this spec (Object → Graph).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub graph: Option<Box<crate::graph::GraphSpec>>,
/// Index of the graph series this generated group belongs to. Axes, the legend and other
/// children leave it unset, so a series named "Legend" or "Axes" is not mistaken for them.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub series_index: Option<u32>,
/// Editable Shaper composition; the original art is retained in its source child.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub shaper: Option<Box<crate::shaper::ShaperSpec>>,
@@ -595,6 +599,7 @@ impl Node {
trace: None,
wrap: None,
graph: None,
series_index: None,
shaper: None,
kind,
graphic_style: None,
+50 -2
View File
@@ -6,7 +6,8 @@
//! - **Geometry effects** (Distort & Transform, Path, Convert to Shape, Round Corners, Scribble,
//! Warp) rewrite a path: [`apply_geometry`] evaluates them in stack order.
//! - **Raster effects** (Drop Shadow, Inner/Outer Glow, Feather, Gaussian Blur, and the
//! Photoshop-style filters of [`pixel`]: Radial Blur, Smart Blur, Unsharp Mask and Glowing Edges) are described by
//! Photoshop-style filters of [`pixel`]: Radial Blur, Smart Blur, Color Halftone, Crystallize, Mezzotint, Pointillize,
//! Unsharp Mask and Glowing Edges) are described by
//! [`raster_effects`] and painted by the renderer; [`outset`] says how far they reach beyond
//! the geometry.
//! - **Stroke geometry** ([`stroke`]): arrowheads, dash patterns and width profiles, shared by the
@@ -27,7 +28,8 @@
//! renderer and the exporters.
//!
//! Everything is deterministic: "random" effects (Roughen, Tweak, Scribble) use a seeded hash
//! noise (`seed` parameter, default 0).
//! noise (`seed` parameter, default 0); the random Pixelate filters hash their pattern's cells,
//! anchored at the object's centre.
#![forbid(unsafe_code)]
mod adjust;
@@ -126,6 +128,8 @@ fn lengths_of(id: &str) -> Lengths {
"stylize.dropShadow" => always(&["x", "y", "blur"]),
"stylize.innerGlow" | "stylize.outerGlow" => always(&["blur"]),
"stylize.glowingEdges" => always(&["edgeWidth", "smoothness"]),
"pixelate.colorHalftone" => always(&["maxRadius"]),
"pixelate.crystallize" | "pixelate.pointillize" => always(&["cellSize"]),
_ => Lengths::default(),
}
}
@@ -139,6 +143,8 @@ const STYLIZE: &[&str] = &["Effect", "Stylize"];
const WARP: &[&str] = &["Effect", "Warp"];
const BLUR: &[&str] = &["Effect", "Blur"];
const SHARPEN: &[&str] = &["Effect", "Sharpen"];
const PIXELATE: &[&str] = &["Effect", "Pixelate"];
const VIDEO: &[&str] = &["Effect", "Video"];
const PATHFINDER: &[&str] = &["Effect", "Pathfinder"];
const PLUGINS: &[&str] = &["Effect", "Plug-ins"];
const ADJUST: &[&str] = &["Effect", "Color Adjustments"];
@@ -298,6 +304,48 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
"{edgeWidth: pt 1..14 (2), edgeBrightness: 0..20 (6), smoothness: pt 1..15 (5)} finds alpha-weighted Sobel edges and draws bright coloured outlines on black",
json!({"edgeWidth": 2.0, "edgeBrightness": 6.0, "smoothness": 5.0}),
),
r(
"pixelate.colorHalftone",
"Color Halftone…",
PIXELATE,
"{maxRadius: pt 4..127 (8; the radius of a dot at full strength, which fills its square cell), channel1: screen angle deg -360..360 (108), channel2: deg (162), channel3: deg (90), channel4: deg (45)} screens each colour channel (red, green, blue: channels 1 to 3; in CMYK documents cyan, magenta, yellow, black: 1 to 4) at its angle into dots whose area follows the channel's mean over their cell",
json!({"maxRadius": 8.0, "channel1": 108.0, "channel2": 162.0, "channel3": 90.0, "channel4": 45.0}),
),
r(
"pixelate.crystallize",
"Crystallize…",
PIXELATE,
"{cellSize: pt 3..300 (10)} redraws the object as polygon crystals of solid colour around random points about cellSize apart",
json!({"cellSize": 10.0}),
),
r(
"pixelate.mezzotint",
"Mezzotint…",
PIXELATE,
"{type: \"fineDots\"|\"mediumDots\"|\"grainyDots\"|\"coarseDots\"|\"shortLines\"|\"mediumLines\"|\"longLines\"|\"shortStrokes\"|\"mediumStrokes\"|\"longStrokes\" (\"fineDots\")} turns each colour channel fully on or off against a random pattern of dots, lines or strokes: fully saturated colours",
json!({"type": "fineDots"}),
),
r(
"pixelate.pointillize",
"Pointillize…",
PIXELATE,
"{cellSize: pt 3..300 (5)} redraws the object as randomly placed dots of its colours on a white canvas",
json!({"cellSize": 5.0}),
),
r(
"video.deinterlace",
"De-Interlace…",
VIDEO,
"{eliminate: \"odd\"|\"even\" (\"odd\"; which field lines are taken out), create: \"duplication\"|\"interpolation\" (\"duplication\"; a line taken out becomes a copy of the line above, or the average of the lines above and below)} the field lines are the rows of the document's raster grid (Document Raster Effects Settings › Resolution), numbered from 1 at the top of the page",
json!({"eliminate": "odd", "create": "duplication"}),
),
r(
"video.ntscColors",
"NTSC Colors",
VIDEO,
"{} makes colours a television signal can't carry (luma plus chroma past 110 % of white, or luma minus chroma below −20 %) less saturated, keeping their brightness",
json!({}),
),
];
v.extend([
g(
+87 -4
View File
@@ -1,5 +1,6 @@
//! Photoshop-style raster effects (Effect › Blur › Radial Blur and Smart Blur, Sharpen › Unsharp
//! Mask, and Stylize › Glowing Edges): filters over premultiplied RGBA8 pixels.
//! Photoshop-style raster effects (Effect › Blur › Radial Blur and Smart Blur, Pixelate › Color
//! Halftone, Crystallize, Mezzotint and Pointillize, Sharpen › Unsharp Mask, Stylize › Glowing
//! Edges, and Video › De-Interlace and NTSC Colors): filters over premultiplied RGBA8 pixels.
//!
//! - Every distance is in document units (points) and becomes pixels through the raster's
//! [`PixelSpace::px`], so an effect looks the same at any zoom and at any Document Raster Effects
@@ -10,15 +11,30 @@
mod blur;
mod edges;
mod pixelate;
mod sharpen;
mod video;
use serde_json::Value;
use vectorcraft_geom::{Affine, Point, Rect};
use crate::util::{num, text};
pub use pixelate::{MEZZOTINT_TYPES, Mezzotint};
/// The Photoshop-style effect ids (all raster effects, see [`crate::is_raster`]).
pub const PIXEL_EFFECTS: [&str; 4] = ["blur.radial", "blur.smart", "sharpen.unsharpMask", "stylize.glowingEdges"];
pub const PIXEL_EFFECTS: [&str; 10] = [
"blur.radial",
"blur.smart",
"pixelate.colorHalftone",
"pixelate.crystallize",
"pixelate.mezzotint",
"pixelate.pointillize",
"sharpen.unsharpMask",
"stylize.glowingEdges",
"video.deinterlace",
"video.ntscColors",
];
/// A Photoshop-style raster effect with its parameters read and clamped to their ranges. Lengths
/// are in document units.
@@ -36,6 +52,36 @@ pub enum PixelFx {
UnsharpMask { amount: f64, radius: f64, threshold: f64 },
/// Stylize › Glowing Edges: bright coloured Sobel outlines on black.
GlowingEdges { width: f64, brightness: f64, smoothness: f64 },
/// Pixelate › Color Halftone: each colour channel screened at its angle (`angles`° of channels
/// 1 to 4) into dots of up to `max_radius`, whose area follows the channel's strength.
ColorHalftone { max_radius: f64, angles: [f64; 4] },
/// Pixelate › Crystallize: polygons of solid colour around random points about `cell` apart.
Crystallize { cell: f64 },
/// Pixelate › Mezzotint: every colour channel fully on or off against a random pattern.
Mezzotint { kind: Mezzotint },
/// Pixelate › Pointillize: random dots about `cell` across of the object's colours on a white
/// canvas.
Pointillize { cell: f64 },
/// Video › De-Interlace: the odd (or `even`) field lines made again from the others, by
/// duplication or, with `interpolate`, by averaging.
DeInterlace { even: bool, interpolate: bool },
/// Video › NTSC Colors: colours a television signal can't carry made less saturated.
NtscColors,
}
/// What a raster's colour channels hold, for the filters that treat them apart (Color Halftone
/// screens each channel, Mezzotint thresholds each).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Channels {
/// Red, green and blue light.
#[default]
Rgb,
/// Screen colours of a CMYK document: treated as its cyan, magenta, yellow and black inks.
Cmyk,
/// The complemented C, M and Y inks (a CMYK document drawn ink plane by ink plane).
CmyPlane,
/// The complemented K ink, as a grey.
KPlane,
}
/// Where a raster's pixels lie in the document.
@@ -46,8 +92,14 @@ pub struct PixelSpace {
pub to_doc: Affine,
/// The size of a pixel in document units.
pub px: f64,
/// The object's centre (document coordinates): where Radial Blur blurs around.
/// The object's centre (document coordinates): where Radial Blur blurs around, and where the
/// Pixelate filters' patterns are anchored (so they move with the object).
pub center: Point,
/// What the colour channels hold.
pub channels: Channels,
/// The height of a line of the document's raster grid (document units: 72 / Document Raster
/// Effects Settings › Resolution), the fields De-Interlace works on.
pub line: f64,
}
/// Effect `id`'s parameters `p` (defaults merged in) as a [`PixelFx`]; `None` for other effects.
@@ -77,6 +129,19 @@ pub(crate) fn parse(id: &str, p: &Value) -> Option<PixelFx> {
brightness: num(p, "edgeBrightness", 6.0).clamp(0.0, 20.0),
smoothness: num(p, "smoothness", 5.0).clamp(1.0, 15.0),
},
"pixelate.colorHalftone" => PixelFx::ColorHalftone {
max_radius: num(p, "maxRadius", 8.0).clamp(4.0, 127.0),
angles: [("channel1", 108.0), ("channel2", 162.0), ("channel3", 90.0), ("channel4", 45.0)]
.map(|(k, d)| num(p, k, d).clamp(-360.0, 360.0)),
},
"pixelate.crystallize" => PixelFx::Crystallize { cell: num(p, "cellSize", 10.0).clamp(3.0, 300.0) },
"pixelate.mezzotint" => PixelFx::Mezzotint { kind: Mezzotint::parse(text(p, "type", "fineDots")) },
"pixelate.pointillize" => PixelFx::Pointillize { cell: num(p, "cellSize", 5.0).clamp(3.0, 300.0) },
"video.deinterlace" => PixelFx::DeInterlace {
even: text(p, "eliminate", "odd").eq_ignore_ascii_case("even"),
interpolate: text(p, "create", "duplication").eq_ignore_ascii_case("interpolation"),
},
"video.ntscColors" => PixelFx::NtscColors,
_ => return None,
})
}
@@ -94,6 +159,9 @@ impl PixelFx {
PixelFx::SmartBlur { radius, .. } => radius,
PixelFx::UnsharpMask { .. } => 0.0,
PixelFx::GlowingEdges { width, smoothness, .. } => width.max(smoothness * 3.0),
PixelFx::ColorHalftone { .. } | PixelFx::Mezzotint { .. } | PixelFx::DeInterlace { .. } | PixelFx::NtscColors => 0.0,
// A crystal's or dot's point inside the object reaches out by up to its cell.
PixelFx::Crystallize { cell } | PixelFx::Pointillize { cell } => 1.5 * cell,
}
}
@@ -105,6 +173,15 @@ impl PixelFx {
PixelFx::SmartBlur { radius, .. } => Some(radius),
PixelFx::UnsharpMask { radius, .. } => Some(3.0 * radius),
PixelFx::GlowingEdges { width, smoothness, .. } => Some(width.max(smoothness * 3.0)),
// The cells around the pixel's, and the cells around theirs.
PixelFx::ColorHalftone { max_radius, .. } => Some(3.0 * std::f64::consts::SQRT_2 * max_radius),
PixelFx::Crystallize { cell } => Some(1.5 * cell),
PixelFx::Mezzotint { .. } => Some(0.0),
// The dots' points, and the softened colour around them.
PixelFx::Pointillize { cell } => Some(2.5 * cell),
// The lines above and below.
PixelFx::DeInterlace { .. } => Some(video::MAX_LINE),
PixelFx::NtscColors => Some(0.0),
}
}
@@ -118,6 +195,12 @@ impl PixelFx {
PixelFx::SmartBlur { radius, threshold, samples } => blur::smart(px, w, h, to_px(radius), threshold, samples),
PixelFx::UnsharpMask { amount, radius, threshold } => sharpen::unsharp(px, w, h, amount, to_px(radius), threshold),
PixelFx::GlowingEdges { width, brightness, smoothness } => edges::glow(px, w, h, to_px(width), brightness, to_px(smoothness)),
PixelFx::ColorHalftone { max_radius, angles } => pixelate::color_halftone(px, w, h, space, max_radius, angles),
PixelFx::Crystallize { cell } => pixelate::crystallize(px, w, h, space, cell),
PixelFx::Mezzotint { kind } => pixelate::mezzotint(px, w, h, space, kind),
PixelFx::Pointillize { cell } => pixelate::pointillize(px, w, h, space, cell),
PixelFx::DeInterlace { even, interpolate } => video::deinterlace(px, w, h, space, even, interpolate),
PixelFx::NtscColors => video::ntsc(px),
}
}
}
+531
View File
@@ -0,0 +1,531 @@
//! Pixelate › Color Halftone, Crystallize, Mezzotint and Pointillize.
//!
//! Their patterns (screens, crystals, grains and dots) lie in document space around the object's
//! centre, so they keep their size at any zoom or resolution and move with the object. The random
//! ones hash the pattern's cell indices: every redraw gives the same result.
use std::sync::OnceLock;
use vectorcraft_geom::{Affine, Point};
use super::{Channels, PixelSpace, gaussian, to16};
use crate::util::noise;
/// Mezzotint's patterns, in its Type menu's order: (label, parameter value).
pub const MEZZOTINT_TYPES: [(&str, &str); 10] = [
("Fine Dots", "fineDots"),
("Medium Dots", "mediumDots"),
("Grainy Dots", "grainyDots"),
("Coarse Dots", "coarseDots"),
("Short Lines", "shortLines"),
("Medium Lines", "mediumLines"),
("Long Lines", "longLines"),
("Short Strokes", "shortStrokes"),
("Medium Strokes", "mediumStrokes"),
("Long Strokes", "longStrokes"),
];
/// A Mezzotint pattern ([`MEZZOTINT_TYPES`]): random dots, or horizontal lines or strokes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Mezzotint {
/// Dots `size` points across (smooth blobs when `smooth`), plus fine grain when `grainy`.
Dots { size: u8, smooth: bool, grainy: bool },
/// Horizontal streaks about `length` points long and `width` points thick.
Lines { length: u8, width: u8 },
}
/// The patterns of [`MEZZOTINT_TYPES`], in the same order.
const MEZZOTINT_KINDS: [Mezzotint; 10] = {
const fn dots(size: u8, smooth: bool, grainy: bool) -> Mezzotint {
Mezzotint::Dots { size, smooth, grainy }
}
const fn lines(length: u8, width: u8) -> Mezzotint {
Mezzotint::Lines { length, width }
}
[
dots(1, false, false),
dots(2, true, false),
dots(3, true, true),
dots(4, true, false),
lines(4, 1),
lines(8, 1),
lines(16, 1),
lines(6, 2),
lines(12, 2),
lines(24, 2),
]
};
impl Mezzotint {
/// Fine Dots, the first type.
pub const FINE_DOTS: Mezzotint = Mezzotint::Dots { size: 1, smooth: false, grainy: false };
/// The pattern of Type `value` (a [`MEZZOTINT_TYPES`] value, any case); Fine Dots otherwise.
pub fn parse(value: &str) -> Self {
MEZZOTINT_TYPES.iter().zip(MEZZOTINT_KINDS).find(|((_, v), _)| v.eq_ignore_ascii_case(value)).map_or(Self::FINE_DOTS, |(_, kind)| kind)
}
}
/// Seeds of the filters' noise ("PIXELATE" and a filter number).
const SEED: u64 = 0x5049_5845_4C41_5445;
/// A random number in [0, 1) for cell (`i`, `j`) of pattern `salt`; `k` picks one of several.
fn rand(salt: u64, i: i64, j: i64, k: u64) -> f64 {
0.5 * (noise(SEED ^ salt, i as u64, j as u64, k) + 1.0)
}
/// The cell holding coordinate `v` (in cells); `None` far beyond any raster (or not finite).
fn cell(v: f64) -> Option<i64> {
let f = v.floor();
(f.abs() < 1e15).then_some(f as i64)
}
/// Where a raster's pixels lie relative to the object's centre, in document units.
struct Place {
/// Pixel coordinates → document coordinates relative to the centre.
to_rel: Affine,
/// The other way.
to_px: Affine,
/// A pixel's size in document units.
px: f64,
w: usize,
h: usize,
}
impl Place {
fn new(space: &PixelSpace, w: usize, h: usize) -> Option<Self> {
let to_rel = Affine::translate(-space.center.to_vec2()) * space.to_doc;
let to_px = to_rel.inverse();
(to_rel.is_finite() && to_px.is_finite() && space.px.is_finite() && space.px > 0.0).then_some(Self { to_rel, to_px, px: space.px, w, h })
}
/// The centre of pixel (`x`, `y`).
fn at(&self, x: usize, y: usize) -> Point {
self.to_rel * Point::new(x as f64 + 0.5, y as f64 + 0.5)
}
/// The index of the pixel holding point `p`; `None` outside the raster.
fn index(&self, p: Point) -> Option<usize> {
let q = self.to_px * p;
(q.x >= 0.0 && q.y >= 0.0 && q.x < self.w as f64 && q.y < self.h as f64).then(|| q.y as usize * self.w + q.x as usize)
}
/// Run `f(x, y, pixel)` on every pixel.
fn each(&self, px: &mut [[u8; 4]], mut f: impl FnMut(usize, usize, &mut [u8; 4])) {
for (y, row) in px.chunks_exact_mut(self.w.max(1)).enumerate().take(self.h) {
for (x, p) in row.iter_mut().enumerate() {
f(x, y, p);
}
}
}
}
/// The cells around a pixel's cell, in the order they can hold its nearest random point: the
/// cell itself, its 8 neighbours, then the ring around them.
const AROUND: [(i64, i64); 25] = [
(0, 0),
(-1, 0),
(1, 0),
(0, -1),
(0, 1),
(-1, -1),
(1, -1),
(-1, 1),
(1, 1),
(-2, -2),
(-1, -2),
(0, -2),
(1, -2),
(2, -2),
(-2, -1),
(2, -1),
(-2, 0),
(2, 0),
(-2, 1),
(2, 1),
(-2, 2),
(-1, 2),
(0, 2),
(1, 2),
(2, 2),
];
/// What the cells [`AROUND`] one cell hold, made when first asked for and kept while consecutive
/// pixels stay in that cell.
struct Around<T> {
cell: Option<(i64, i64)>,
items: [Option<T>; 25],
}
impl<T: Copy> Around<T> {
fn new() -> Self {
Self { cell: None, items: [None; 25] }
}
/// Item `k` of [`AROUND`] cell (`i`, `j`): `make(cell i', j')`.
fn get(&mut self, (i, j): (i64, i64), k: usize, make: impl FnOnce(i64, i64) -> T) -> Option<T> {
if self.cell != Some((i, j)) {
self.cell = Some((i, j));
self.items = [None; 25];
}
let (di, dj) = AROUND.get(k)?;
let slot = self.items.get_mut(k)?;
Some(*slot.get_or_insert_with(|| make(i.wrapping_add(*di), j.wrapping_add(*dj))))
}
}
/// The random point of cell (`i`, `j`) of pattern `salt`, in cells.
fn point_in(salt: u64, i: i64, j: i64) -> Point {
Point::new(i as f64 + rand(salt, i, j, 0), j as f64 + rand(salt, i, j, 1))
}
/// Crystallize: every pixel takes the colour at the nearest of one random point per `cell` ×
/// `cell` square (a Voronoi diagram over a jittered grid): polygon crystals of solid colour.
pub(super) fn crystallize(px: &mut [[u8; 4]], w: usize, h: usize, space: &PixelSpace, cell_size: f64) {
let Some(place) = Place::new(space, w, h) else { return };
if !(cell_size.is_finite() && cell_size > 0.0) {
return;
}
let src = px.to_vec();
let mut around = Around::new();
// How far cell `c` lies from coordinate `t` (in cells) along one axis.
let gap = |c: i64, t: f64| (c as f64 - t).max(t - c as f64 - 1.0).max(0.0);
place.each(px, |x, y, out| {
let q = place.at(x, y);
let (u, v) = (q.x / cell_size, q.y / cell_size);
let (Some(i), Some(j)) = (cell(u), cell(v)) else { return };
let mut best = (f64::INFINITY, None);
for (k, (di, dj)) in AROUND.iter().enumerate() {
// A cell farther than the best point so far can't hold a nearer one.
let (ci, cj) = (i.wrapping_add(*di), j.wrapping_add(*dj));
if gap(ci, u).hypot(gap(cj, v)) >= best.0 {
continue;
}
if let Some(p) = around.get((i, j), k, |a, b| point_in(1, a, b)) {
let d = (p.x - u).hypot(p.y - v);
if d < best.0 {
best = (d, Some(p));
}
}
}
if let Some(p) = best.1 {
let at = Point::new(p.x * cell_size, p.y * cell_size);
*out = place.index(at).and_then(|i| src.get(i)).copied().unwrap_or([0; 4]);
}
});
}
/// One of Pointillize's dots: where (in cells), its radius (document units), its stacking order
/// and its colour (premultiplied, 0..1).
#[derive(Clone, Copy)]
struct Dot {
at: Point,
radius: f64,
z: f64,
colour: [f32; 4],
}
/// The smallest dot radius and the spread above it, in cells.
const DOT_RADIUS: (f64, f64) = (0.45, 0.25);
/// Pointillize: a dot at one random point per `cell` × `cell` square, of random size around the
/// cell's, coloured by the (softened) object there, over a white canvas where the object is.
pub(super) fn pointillize(px: &mut [[u8; 4]], w: usize, h: usize, space: &PixelSpace, cell_size: f64) {
let Some(place) = Place::new(space, w, h) else { return };
if !(cell_size.is_finite() && cell_size > 0.0) {
return;
}
// Each dot takes the colour around its centre, not of a single pixel there, and is as opaque
// as the object at its centre (whole dots on the object, none beside it).
let alpha: Vec<u8> = px.iter().map(|p| p[3]).collect();
let mut soft = to16(px);
gaussian(&mut soft, w, cell_size / place.px / 4.0);
let dot = |i: i64, j: i64| {
let at = point_in(2, i, j);
let k = place.index(Point::new(at.x * cell_size, at.y * cell_size));
let a = k.and_then(|k| alpha.get(k)).map_or(0.0, |a| f32::from(*a) / 255.0);
let colour = match k.and_then(|k| soft.get(k)) {
Some(p) if p[3] > 0 => {
let s = a / f32::from(p[3]);
[f32::from(p[0]) * s, f32::from(p[1]) * s, f32::from(p[2]) * s, a]
}
_ => [0.0; 4],
};
Dot { at, radius: (DOT_RADIUS.0 + DOT_RADIUS.1 * rand(2, i, j, 2)) * cell_size, z: rand(2, i, j, 3), colour }
};
let mut around = Around::new();
place.each(px, |x, y, out| {
let q = place.at(x, y);
let (u, v) = (q.x / cell_size, q.y / cell_size);
let (Some(i), Some(j)) = (cell(u), cell(v)) else { return };
// The dots covering the pixel (only the 3 × 3 cells around it reach it), bottom first.
let mut hits: [(f64, f32, [f32; 4]); 9] = [(0.0, 0.0, [0.0; 4]); 9];
let mut n = 0;
for k in 0..9 {
let Some(d) = around.get((i, j), k, dot) else { continue };
let dist = (d.at.x - u).hypot(d.at.y - v) * cell_size;
let cover = ((d.radius - dist) / place.px + 0.5).clamp(0.0, 1.0) as f32;
if cover > 0.0
&& d.colour[3] > 0.0
&& let Some(slot) = hits.get_mut(n)
{
*slot = (d.z, cover, d.colour);
n += 1;
}
}
let hits = hits.get_mut(..n).unwrap_or_default();
hits.sort_by(|a, b| a.0.total_cmp(&b.0));
let alpha = f32::from(out[3]) / 255.0;
let mut acc = [alpha; 4];
for (_, cover, c) in hits.iter() {
let keep = 1.0 - c[3] * cover;
for (a, v) in acc.iter_mut().zip(c) {
*a = v * cover + *a * keep;
}
}
let a = (acc[3].clamp(0.0, 1.0) * 255.0).round();
let v = |c: f32| (c.clamp(0.0, 1.0) * 255.0).round().min(a) as u8;
*out = [v(acc[0]), v(acc[1]), v(acc[2]), a as u8];
});
}
/// A pixel's colour as the channels the Pixelate filters treat apart (straight, 0..1; see
/// [`Channels`]), and how many of the four there are.
fn split(p: [u8; 4], channels: Channels) -> ([f32; 4], usize) {
let a = f32::from(p[3]);
let [r, g, b] = [p[0], p[1], p[2]].map(|v| if a > 0.0 { (f32::from(v) / a).min(1.0) } else { 0.0 });
match channels {
Channels::Rgb => ([r, g, b, 0.0], 3),
Channels::Cmyk => {
// A light black generation, as separations print: black ink takes over in the
// shadows, coloured inks build the midtones.
let k = (1.0 - r.max(g).max(b)).powi(2);
let ink = |v: f32| if k < 1.0 { ((1.0 - v - k) / (1.0 - k)).clamp(0.0, 1.0) } else { 0.0 };
([ink(r), ink(g), ink(b), k], 4)
}
Channels::CmyPlane => ([1.0 - r, 1.0 - g, 1.0 - b, 0.0], 3),
Channels::KPlane => ([1.0 - r, 0.0, 0.0, 0.0], 1),
}
}
/// The pixel of channel values `v` ([`split`]'s) at coverage `alpha` (premultiplied).
fn join(v: [f32; 4], channels: Channels, alpha: u8) -> [u8; 4] {
let [a, b, c, d] = v.map(|x| x.clamp(0.0, 1.0));
let rgb = match channels {
Channels::Rgb => [a, b, c],
Channels::Cmyk => [(1.0 - a) * (1.0 - d), (1.0 - b) * (1.0 - d), (1.0 - c) * (1.0 - d)],
Channels::CmyPlane => [1.0 - a, 1.0 - b, 1.0 - c],
Channels::KPlane => [1.0 - a; 3],
};
let al = f32::from(alpha);
let [r, g, b] = rgb.map(|x| (x * al).round().clamp(0.0, al) as u8);
[r, g, b, alpha]
}
/// Which of Color Halftone's four screen angles channel `i` of `channels` uses: the K plane's
/// only channel is the fourth (black) one.
fn angle_of(channels: Channels, i: usize) -> usize {
if channels == Channels::KPlane { 3 } else { i }
}
/// The share of a `1` × `1` square that a circle of radius `rho` around its centre covers.
fn circle_in_square(rho: f64) -> f64 {
let half = 0.5;
if rho <= half {
std::f64::consts::PI * rho * rho
} else if rho < std::f64::consts::FRAC_1_SQRT_2 {
// The circle less the four caps beyond the square's sides.
let cap = rho * rho * (half / rho).acos() - half * (rho * rho - half * half).sqrt();
std::f64::consts::PI * rho * rho - 4.0 * cap
} else {
1.0
}
}
/// The radius (in cells) of the dot that covers share `v` of its cell.
fn dot_radius(v: f64) -> f64 {
const STEPS: usize = 256;
static TABLE: OnceLock<[f64; STEPS + 1]> = OnceLock::new();
let table = TABLE.get_or_init(|| {
std::array::from_fn(|k| {
let target = k as f64 / STEPS as f64;
let (mut lo, mut hi) = (0.0, std::f64::consts::FRAC_1_SQRT_2);
for _ in 0..48 {
let mid = 0.5 * (lo + hi);
if circle_in_square(mid) < target {
lo = mid;
} else {
hi = mid;
}
}
hi
})
});
let x = if v.is_finite() { v.clamp(0.0, 1.0) * STEPS as f64 } else { 0.0 };
let k = (x.floor() as usize).min(STEPS - 1);
let (a, b) = (table.get(k).copied().unwrap_or(0.0), table.get(k + 1).copied().unwrap_or(0.0));
a + (b - a) * (x - k as f64)
}
/// One channel's halftone screen: square cells at an angle, each with the dot of its mean value.
struct Screen {
/// Document coordinates relative to the centre → cells.
to_cells: Affine,
/// The first cell's indices and the grid's size in cells.
origin: (i64, i64),
size: (usize, usize),
/// Per cell: the channel's sum (× coverage) and the coverage's (then the dot's radius in
/// document units, in `sums[k][0]`).
sums: Vec<[f32; 2]>,
}
impl Screen {
/// The screen at `angle`° with cells `side` wide over the raster `place` covers; `None` when
/// it would have more than `limit` cells.
fn new(place: &Place, angle: f64, side: f64, limit: usize) -> Option<Self> {
let to_cells = Affine::scale(1.0 / side) * Affine::rotate(angle.to_radians());
let corners = [(0.0, 0.0), (place.w as f64, 0.0), (0.0, place.h as f64), (place.w as f64, place.h as f64)];
let pts = corners.map(|(x, y)| to_cells * (place.to_rel * Point::new(x, y)));
let (lo, hi) = pts.iter().fold(((f64::INFINITY, f64::INFINITY), (f64::NEG_INFINITY, f64::NEG_INFINITY)), |(lo, hi), p| {
((lo.0.min(p.x), lo.1.min(p.y)), (hi.0.max(p.x), hi.1.max(p.y)))
});
let (i0, j0, i1, j1) = (cell(lo.0)?.checked_sub(1)?, cell(lo.1)?.checked_sub(1)?, cell(hi.0)?.checked_add(1)?, cell(hi.1)?.checked_add(1)?);
let gw = usize::try_from(i1.checked_sub(i0)?.checked_add(1)?).ok()?;
let gh = usize::try_from(j1.checked_sub(j0)?.checked_add(1)?).ok()?;
(gw.checked_mul(gh)? <= limit).then(|| Self { to_cells, origin: (i0, j0), size: (gw, gh), sums: vec![[0.0; 2]; gw * gh] })
}
/// The index of cell (`i`, `j`) in the grid.
fn slot(&self, i: i64, j: i64) -> Option<usize> {
let x = usize::try_from(i.checked_sub(self.origin.0)?).ok().filter(|x| *x < self.size.0)?;
let y = usize::try_from(j.checked_sub(self.origin.1)?).ok().filter(|y| *y < self.size.1)?;
Some(y * self.size.0 + x)
}
}
/// Color Halftone: each channel screened at its angle in square cells sized so that a dot of
/// `max_radius` fills one; each cell's dot covers the share of it that is the channel's mean
/// there (white stays white, black black). Coverage stays as it is.
pub(super) fn color_halftone(px: &mut [[u8; 4]], w: usize, h: usize, space: &PixelSpace, max_radius: f64, angles: [f64; 4]) {
let Some(place) = Place::new(space, w, h) else { return };
let side = max_radius * std::f64::consts::SQRT_2;
// Cells under 3 pixels can't show their dots: on average a screen is the image itself.
if !(side.is_finite() && side / place.px >= 3.0) {
return;
}
let channels = space.channels;
let n = split([0; 4], channels).1;
let limit = w.saturating_mul(h).saturating_add(4096);
let mut screens = Vec::with_capacity(n);
for i in 0..n {
let angle = angles.get(angle_of(channels, i)).copied().unwrap_or(0.0);
let Some(s) = Screen::new(&place, angle, side, limit) else { return };
screens.push(s);
}
// Each cell's mean of each channel, weighted by coverage.
place.each(px, |x, y, p| {
if p[3] == 0 {
return;
}
let (v, _) = split(*p, channels);
let a = f32::from(p[3]) / 255.0;
let q = place.at(x, y);
for (s, v) in screens.iter_mut().zip(v) {
let c = s.to_cells * q;
if let (Some(i), Some(j)) = (cell(c.x), cell(c.y))
&& let Some(sum) = s.slot(i, j).and_then(|k| s.sums.get_mut(k))
{
sum[0] += v * a;
sum[1] += a;
}
}
});
for s in &mut screens {
for sum in &mut s.sums {
let mean = if sum[1] > 1e-6 { f64::from(sum[0] / sum[1]) } else { 0.0 };
// Full strength fills the cell, corners too; none leaves no speck.
let radius = match mean {
m if m >= 254.5 / 255.0 => f64::INFINITY,
m if m <= 0.5 / 255.0 => 0.0,
m => dot_radius(m) * side,
};
sum[0] = radius as f32;
}
}
place.each(px, |x, y, p| {
if p[3] == 0 {
return;
}
let q = place.at(x, y);
let mut v = [0.0f32; 4];
for (s, out) in screens.iter().zip(v.iter_mut()) {
let c = s.to_cells * q;
let (Some(i), Some(j)) = (cell(c.x), cell(c.y)) else { continue };
// A dot reaches past its cell into the neighbours on the pixel's side only.
let (si, sj) = (if c.x - (i as f64) < 0.5 { -1 } else { 1 }, if c.y - (j as f64) < 0.5 { -1 } else { 1 });
for (di, dj) in [(0, 0), (si, 0), (0, sj), (si, sj)] {
let (ci, cj) = (i.wrapping_add(di), j.wrapping_add(dj));
let radius = s.slot(ci, cj).and_then(|k| s.sums.get(k)).map_or(0.0, |sum| f64::from(sum[0]));
if radius <= 0.0 {
continue;
}
let dist = (c.x - (ci as f64 + 0.5)).hypot(c.y - (cj as f64 + 0.5)) * side;
*out = out.max(((radius - dist) / place.px + 0.5).clamp(0.0, 1.0) as f32);
}
}
*p = join(v, channels, p[3]);
});
}
/// Mezzotint: every channel turned fully on or off where it is above or below a random threshold
/// pattern (each channel its own), so the image becomes dots or streaks of pure colours.
pub(super) fn mezzotint(px: &mut [[u8; 4]], w: usize, h: usize, space: &PixelSpace, kind: Mezzotint) {
let Some(place) = Place::new(space, w, h) else { return };
let channels = space.channels;
place.each(px, |x, y, p| {
if p[3] == 0 {
return;
}
let q = place.at(x, y);
let (mut v, n) = split(*p, channels);
for (c, value) in v.iter_mut().enumerate().take(n) {
let t = threshold(kind, 16 + c as u64, q);
*value = if f64::from(*value) > t { 1.0 } else { 0.0 };
}
*p = join(v, channels, p[3]);
});
}
/// Mezzotint's threshold in [0, 1) at point `q` (document units around the centre) of pattern
/// `salt`.
fn threshold(kind: Mezzotint, salt: u64, q: Point) -> f64 {
let smooth = |t: f64| t * t * (3.0 - 2.0 * t);
// Random values at whole coordinates, blended smoothly between them along x (and y).
let blend = |x: f64, y: f64, along_y: bool| {
let (Some(i), Some(j)) = (cell(x), cell(y)) else { return 0.5 };
let (fx, fy) = (smooth(x - i as f64), smooth(y - j as f64));
let at = |di: i64, dj: i64| rand(salt, i.wrapping_add(di), j.wrapping_add(dj), 0);
let top = at(0, 0) + (at(1, 0) - at(0, 0)) * fx;
if !along_y {
return top;
}
let bottom = at(0, 1) + (at(1, 1) - at(0, 1)) * fx;
top + (bottom - top) * fy
};
let grain = |size: f64| match (cell(q.x / size), cell(q.y / size)) {
(Some(i), Some(j)) => rand(salt, i, j, 1),
_ => 0.5,
};
match kind {
Mezzotint::Dots { size, smooth: false, .. } => grain(f64::from(size)),
Mezzotint::Dots { size, grainy, .. } => {
let s = f64::from(size);
let blob = blend(q.x / s, q.y / s, true);
if grainy { 0.5 * (blob + grain(1.0)) } else { blob }
}
Mezzotint::Lines { length, width } => {
let row = (q.y / f64::from(width)).floor();
blend(q.x / f64::from(length), row, false)
}
}
}
+259 -3
View File
@@ -7,7 +7,7 @@ use crate::{RasterFx, raster_effects};
/// A `w` × `h` raster whose pixels are document points (origin top-left).
fn space(w: usize, h: usize) -> PixelSpace {
PixelSpace { to_doc: Affine::IDENTITY, px: 1.0, center: Point::new(w as f64 / 2.0, h as f64 / 2.0) }
PixelSpace { to_doc: Affine::IDENTITY, px: 1.0, center: Point::new(w as f64 / 2.0, h as f64 / 2.0), channels: Channels::Rgb, line: 1.0 }
}
fn image(w: usize, h: usize, f: impl Fn(usize, usize) -> [u8; 4]) -> Vec<u8> {
@@ -224,7 +224,8 @@ fn lengths_are_document_units() {
let edge = |scale: usize| image(40 * scale, 4, move |x, _| grey(if x < 20 * scale { 100 } else { 150 }));
let run = |scale: usize| {
let mut d = edge(scale);
let s = PixelSpace { to_doc: Affine::scale(1.0 / scale as f64), px: 1.0 / scale as f64, center: Point::ZERO };
let s =
PixelSpace { to_doc: Affine::scale(1.0 / scale as f64), px: 1.0 / scale as f64, center: Point::ZERO, channels: Channels::Rgb, line: 1.0 };
fx("sharpen.unsharpMask", json!({"amount": 100, "radius": 2})).apply(&mut d, 40 * scale, 4, &s);
(0..40 * scale).filter(|x| at(&d, 40 * scale, *x, 2)[0] < 99).count()
};
@@ -253,7 +254,7 @@ fn gaussian_and_plane_blurs_keep_their_mass() {
fn pixel_timings() {
let (w, h) = (2000, 2000);
let src = image(w, h, |x, y| [(x % 256) as u8, (y % 256) as u8, ((x ^ y) % 256) as u8, 255]);
let s = PixelSpace { to_doc: Affine::IDENTITY, px: 1.0, center: Point::new(1000.0, 1000.0) };
let s = PixelSpace { to_doc: Affine::IDENTITY, px: 1.0, center: Point::new(1000.0, 1000.0), channels: Channels::Rgb, line: 1.0 };
let cases = [
("blur.radial", json!({"quality": "draft"})),
("blur.radial", json!({"quality": "good"})),
@@ -261,6 +262,12 @@ fn pixel_timings() {
("blur.smart", json!({"quality": "low"})),
("blur.smart", json!({"quality": "high", "radius": 30})),
("sharpen.unsharpMask", json!({"radius": 20})),
("pixelate.colorHalftone", json!({"maxRadius": 4})),
("pixelate.crystallize", json!({"cellSize": 3})),
("pixelate.crystallize", json!({"cellSize": 300})),
("pixelate.mezzotint", json!({"type": "grainyDots"})),
("pixelate.pointillize", json!({"cellSize": 3})),
("pixelate.pointillize", json!({"cellSize": 300})),
];
for (id, p) in cases {
let mut d = src.clone();
@@ -269,3 +276,252 @@ fn pixel_timings() {
println!("{id} {p}: {:?}", t.elapsed());
}
}
#[test]
fn pixelate_params_take_defaults_and_stay_in_range() {
assert_eq!(fx("pixelate.colorHalftone", json!({})), PixelFx::ColorHalftone { max_radius: 8.0, angles: [108.0, 162.0, 90.0, 45.0] });
assert_eq!(
fx("pixelate.colorHalftone", json!({"maxRadius": 1e9, "channel1": -1e9, "channel2": 30, "channel4": "x"})),
PixelFx::ColorHalftone { max_radius: 127.0, angles: [-360.0, 30.0, 90.0, 45.0] }
);
assert_eq!(fx("pixelate.colorHalftone", json!({"maxRadius": 0})), PixelFx::ColorHalftone { max_radius: 4.0, angles: [108.0, 162.0, 90.0, 45.0] });
assert_eq!(fx("pixelate.crystallize", json!({})), PixelFx::Crystallize { cell: 10.0 });
assert_eq!(fx("pixelate.crystallize", json!({"cellSize": -4})), PixelFx::Crystallize { cell: 3.0 });
assert_eq!(fx("pixelate.pointillize", json!({})), PixelFx::Pointillize { cell: 5.0 });
assert_eq!(fx("pixelate.pointillize", json!({"cellSize": 1e300})), PixelFx::Pointillize { cell: 300.0 });
assert_eq!(fx("pixelate.mezzotint", json!({})), PixelFx::Mezzotint { kind: Mezzotint::FINE_DOTS });
assert_eq!(fx("pixelate.mezzotint", json!({"type": "LONGSTROKES"})), PixelFx::Mezzotint { kind: Mezzotint::Lines { length: 24, width: 2 } });
for junk in [json!({"type": 7}), json!({"type": "nonsense"})] {
assert_eq!(fx("pixelate.mezzotint", junk), PixelFx::Mezzotint { kind: Mezzotint::FINE_DOTS });
}
// Every Type is a pattern of its own, documented in the catalogue.
let doc = crate::effect_info("pixelate.mezzotint").unwrap().params;
let kinds: Vec<Mezzotint> = MEZZOTINT_TYPES.iter().map(|(_, v)| Mezzotint::parse(v)).collect();
for (i, (_, v)) in MEZZOTINT_TYPES.iter().enumerate() {
assert!(doc.contains(&format!("\"{v}\"")), "{v}");
assert!(kinds.iter().skip(i + 1).all(|k| *k != kinds[i]), "{v}");
}
// Dots and crystals reach beyond the object; screens and grain stay on it.
let b = Rect::new(0.0, 0.0, 100.0, 50.0);
assert_eq!(fx("pixelate.crystallize", json!({"cellSize": 20})).outset(b), 30.0);
assert_eq!(fx("pixelate.pointillize", json!({"cellSize": 20})).outset(b), 30.0);
assert_eq!(fx("pixelate.colorHalftone", json!({})).outset(b), 0.0);
assert_eq!(fx("pixelate.mezzotint", json!({})).reach(), Some(0.0));
}
/// Fraction of `d`'s pixels for which `f` holds.
fn share(d: &[u8], f: impl Fn(&[u8; 4]) -> bool) -> f64 {
let px = d.as_chunks::<4>().0;
px.iter().filter(|p| f(p)).count() as f64 / px.len() as f64
}
#[test]
fn color_halftone_screens_midtones_into_dots_and_keeps_white_and_black() {
let (w, h) = (64, 64);
let halftone = fx("pixelate.colorHalftone", json!({}));
for v in [0, 255] {
let mut d = image(w, h, |_, _| grey(v));
halftone.apply(&mut d, w, h, &space(w, h));
assert_eq!(d, image(w, h, |_, _| grey(v)), "{v} stays");
}
// Mid grey: each channel's dots cover about half its screen, so the tone stays.
let mut d = image(w, h, |_, _| grey(128));
halftone.apply(&mut d, w, h, &space(w, h));
let px = d.as_chunks::<4>().0;
for c in 0..3 {
let mean = px.iter().map(|p| f64::from(p[c])).sum::<f64>() / px.len() as f64;
assert!((mean - 128.0).abs() < 16.0, "channel {c}: {mean}");
}
assert!(share(&d, |p| p[0] == 255) > 0.25 && share(&d, |p| p[0] == 0) > 0.25, "dots, not grey");
assert!(share(&d, |p| p[0] != p[1]) > 0.1, "the channels' screens lie at different angles");
assert!(px.iter().all(|p| p[3] == 255), "coverage stays");
// Transparency stays transparent.
let mut half = image(w, h, |x, _| if x < 32 { grey(160) } else { [0; 4] });
halftone.apply(&mut half, w, h, &space(w, h));
assert!((0..h).all(|y| (32..w).all(|x| at(&half, w, x, y) == [0; 4])));
// Dots are bigger where the image is brighter.
let mut ramp = image(w, h, |x, _| grey((x * 4) as u8));
halftone.apply(&mut ramp, w, h, &space(w, h));
let lit = |x0: usize| (0..h).flat_map(|y| (x0..x0 + 16).map(move |x| (x, y))).filter(|(x, y)| at(&ramp, w, *x, *y)[0] > 127).count();
assert!(lit(8) < lit(40), "{} < {}", lit(8), lit(40));
}
#[test]
fn color_halftone_screens_inks_in_cmyk_documents() {
let (w, h) = (64, 64);
let halftone = fx("pixelate.colorHalftone", json!({}));
let cmyk = PixelSpace { channels: Channels::Cmyk, ..space(w, h) };
// A neutral grey prints with all four inks: dots of each on white paper, black where they
// all overlap.
let mut d = image(w, h, |_, _| grey(128));
halftone.apply(&mut d, w, h, &cmyk);
assert!(share(&d, |p| *p == grey(255)) > 0.02 && share(&d, |p| *p == grey(0)) > 0.02);
for (ink, colour) in [("cyan", [0, 255, 255, 255]), ("magenta", [255, 0, 255, 255]), ("yellow", [255, 255, 0, 255])] {
assert!(share(&d, |p| *p == colour) > 0.0, "{ink} dots alone");
}
// White paper stays bare; pure cyan ink fills its cells.
let mut white = image(w, h, |_, _| grey(255));
halftone.apply(&mut white, w, h, &cmyk);
assert_eq!(white, image(w, h, |_, _| grey(255)));
let mut cyan = image(w, h, |_, _| [0, 255, 255, 255]);
halftone.apply(&mut cyan, w, h, &cmyk);
assert_eq!(cyan, image(w, h, |_, _| [0, 255, 255, 255]));
// Ink planes: the complemented K plane screens one grey channel at the black angle (45°,
// the same in every quarter turn).
let mut k = image(w, h, |_, _| grey(128));
halftone.apply(&mut k, w, h, &PixelSpace { channels: Channels::KPlane, ..space(w, h) });
assert!(k.as_chunks::<4>().0.iter().all(|p| p[0] == p[1] && p[1] == p[2]), "one grey channel");
assert!(share(&k, |p| p[0] == 255) > 0.25 && share(&k, |p| p[0] == 0) > 0.25);
let mut turned = image(w, h, |_, _| grey(128));
fx("pixelate.colorHalftone", json!({"channel4": 135})).apply(&mut turned, w, h, &PixelSpace { channels: Channels::KPlane, ..space(w, h) });
let mut other = image(w, h, |_, _| grey(128));
fx("pixelate.colorHalftone", json!({"channel4": 30})).apply(&mut other, w, h, &PixelSpace { channels: Channels::KPlane, ..space(w, h) });
assert_eq!(turned, k, "channel 4 sets the K plane's angle");
assert_ne!(other, k);
}
#[test]
fn crystallize_redraws_in_solid_polygons() {
let (w, h) = (48, 48);
let crystals = fx("pixelate.crystallize", json!({"cellSize": 6}));
// One colour stays that colour (away from the raster's edges, where crystals around points
// beyond it take the transparency there).
let mut d = image(w, h, |_, _| [200, 100, 50, 255]);
crystals.apply(&mut d, w, h, &space(w, h));
assert!((9..39).all(|y| (9..39).all(|x| at(&d, w, x, y) == [200, 100, 50, 255])));
// Two halves: every pixel takes one of the colours, and the border between them zigzags.
let (red, blue) = ([200, 0, 0, 255], [0, 0, 200, 255]);
let src = image(w, h, |x, _| if x < 24 { red } else { blue });
let mut d = src.clone();
crystals.apply(&mut d, w, h, &space(w, h));
assert!((9..39).all(|y| (9..39).all(|x| [red, blue].contains(&at(&d, w, x, y)))));
let crossed = (9..39).flat_map(|y| (9..39).map(move |x| (x, y))).filter(|(x, y)| at(&d, w, *x, *y) != at(&src, w, *x, *y)).count();
assert!(crossed > 10, "{crossed}");
let border: std::collections::BTreeSet<usize> = (9..39).map(|y| (9..39).find(|x| at(&d, w, *x, y) == blue).unwrap()).collect();
assert!(border.len() > 2, "{border:?}");
}
#[test]
fn mezzotint_turns_channels_fully_on_or_off() {
let (w, h) = (64, 64);
let grey_square = image(w, h, |x, y| if (8..56).contains(&x) && (8..56).contains(&y) { grey(128) } else { [0; 4] });
let mut seen = Vec::new();
for (_, kind) in MEZZOTINT_TYPES {
let f = fx("pixelate.mezzotint", json!({ "type": kind }));
for v in [0, 255] {
let mut d = image(w, h, |_, _| grey(v));
f.apply(&mut d, w, h, &space(w, h));
assert_eq!(d, image(w, h, |_, _| grey(v)), "{kind}: {v} stays");
}
let mut d = grey_square.clone();
f.apply(&mut d, w, h, &space(w, h));
let px = d.as_chunks::<4>().0;
assert!(px.iter().all(|p| p[..3].iter().all(|c| *c == 0 || *c == p[3])), "{kind}: pure colours");
let on = px.iter().filter(|p| p[3] > 0 && p[0] > 0).count() as f64 / (48.0 * 48.0);
assert!((0.25..0.75).contains(&on), "{kind}: {on}");
assert!(px.iter().any(|p| p[3] > 0 && p[0] != p[1]), "{kind}: each channel its own pattern");
assert!(d.iter().zip(&grey_square).skip(3).step_by(4).all(|(a, b)| a == b), "{kind}: coverage stays");
assert!(!seen.contains(&d), "{kind}: a pattern of its own");
seen.push(d);
}
}
#[test]
fn pointillize_paints_dots_on_a_white_canvas() {
let (w, h) = (80, 80);
let red = [200, 0, 0, 255];
let src = image(w, h, |x, y| if (20..60).contains(&x) && (20..60).contains(&y) { red } else { [0; 4] });
let mut d = src.clone();
fx("pixelate.pointillize", json!({})).apply(&mut d, w, h, &space(w, h));
let inside: Vec<[u8; 4]> = (26..54).flat_map(|y| (26..54).map(move |x| (x, y))).map(|(x, y)| at(&d, w, x, y)).collect();
let canvas = inside.iter().filter(|p| **p == grey(255)).count();
let dots = inside.iter().filter(|p| **p == red).count();
assert!(canvas > inside.len() / 20 && dots > inside.len() / 3, "{canvas} canvas, {dots} dots of {}", inside.len());
assert!(inside.iter().all(|p| p[3] == 255 && p[1] == p[2] && p[0] >= p[1]), "red over white only");
// Dots at the edges reach a little past the object; far from it stays transparent.
assert!((0..h).any(|y| (14..20).any(|x| at(&d, w, x, y)[3] > 0)));
assert!((0..h).all(|y| (0..10).all(|x| at(&d, w, x, y) == [0; 4])));
assert!(d.as_chunks::<4>().0.iter().all(|p| p[0] <= p[3] && p[1] <= p[3] && p[2] <= p[3]));
}
/// The patterns lie in document space around the object's centre: the same at twice the
/// resolution, and moving with the object.
#[test]
fn pixelate_patterns_follow_the_object_at_any_resolution() {
let (w, h) = (40, 40);
let art = |x: f64, y: f64| -> [u8; 4] {
if (8.0..32.0).contains(&x) && (8.0..32.0).contains(&y) { [(x * 6.0) as u8, (y * 6.0) as u8, 120, 255] } else { [0; 4] }
};
for (id, p) in [
("pixelate.colorHalftone", json!({"maxRadius": 4})),
("pixelate.crystallize", json!({"cellSize": 4})),
("pixelate.mezzotint", json!({"type": "coarseDots"})),
("pixelate.pointillize", json!({"cellSize": 4})),
] {
let f = fx(id, p);
let mut one = image(w, h, |x, y| art(x as f64 + 0.5, y as f64 + 0.5));
f.apply(&mut one, w, h, &space(w, h));
// Twice the pixels for the same art, averaged back down.
let mut two = image(2 * w, 2 * h, |x, y| art((x as f64 + 0.5) / 2.0, (y as f64 + 0.5) / 2.0));
let fine = PixelSpace { to_doc: Affine::scale(0.5), px: 0.5, ..space(w, h) };
f.apply(&mut two, 2 * w, 2 * h, &fine);
let down = image(w, h, |x, y| {
let q = [(0, 0), (1, 0), (0, 1), (1, 1)].map(|(dx, dy)| at(&two, 2 * w, 2 * x + dx, 2 * y + dy));
std::array::from_fn(|c| (q.iter().map(|p| u32::from(p[c])).sum::<u32>() / 4) as u8)
});
let diff = one.iter().zip(&down).map(|(a, b)| f64::from(a.abs_diff(*b))).sum::<f64>() / one.len() as f64;
assert!(diff < 24.0, "{id}: {diff}");
// The object and its raster 7 × 3 points further: the same pixels.
let moved = PixelSpace { to_doc: Affine::translate((7.0, 3.0)), center: Point::new(27.0, 23.0), ..space(w, h) };
let mut shifted = image(w, h, |x, y| art(x as f64 + 0.5, y as f64 + 0.5));
f.apply(&mut shifted, w, h, &moved);
assert_eq!(shifted, one, "{id}");
}
}
/// Video › De-Interlace: lines 1, 3, 5… (or 2, 4, 6…) are made again from the others, by copying
/// the line above or by averaging the lines above and below; the lines are the document's raster
/// rows, whatever the raster's own resolution.
#[test]
fn deinterlace_remakes_one_field_from_the_other() {
let (w, h) = (2, 6);
// Line n (from 1) is grey 40 n.
let src = image(w, h, |_, y| grey(40 * (y as u8 + 1)));
let run = |p: serde_json::Value, s: &PixelSpace| {
let mut d = src.clone();
fx("video.deinterlace", p).apply(&mut d, w, h, s);
(0..h).map(|y| at(&d, w, 1, y)[0]).collect::<Vec<_>>()
};
let s = space(w, h);
// Odd lines (1, 3, 5) copy the line above; line 1 has none, so it takes line 2.
assert_eq!(run(json!({}), &s), [80, 80, 80, 160, 160, 240]);
assert_eq!(run(json!({"eliminate": "even"}), &s), [40, 40, 120, 120, 200, 200]);
// Interpolated: the average of the lines around (one side at the edges).
assert_eq!(run(json!({"eliminate": "even", "create": "interpolation"}), &s), [40, 80, 120, 160, 200, 200]);
// Lines two pixels tall: lines 1 and 3 (pixels 0–1 and 4–5) copy their neighbour, row by row.
let coarse = PixelSpace { line: 2.0, ..space(w, h) };
assert_eq!(run(json!({}), &coarse), [120, 160, 120, 160, 120, 160]);
// A damaged space changes nothing.
assert_eq!(run(json!({}), &PixelSpace { line: f64::NAN, ..space(w, h) }), [40, 80, 120, 160, 200, 240]);
}
/// Video › NTSC Colors: saturated yellow and cyan lose saturation (their composite signal is too
/// strong) but keep their brightness; greys, dark colours and transparency stay as they are.
#[test]
fn ntsc_colors_tame_only_colours_too_strong_for_the_signal() {
let (w, h) = (5, 1);
let px = [[255, 255, 0, 255], [0, 255, 255, 255], [128, 128, 128, 255], [100, 20, 20, 255], [0, 0, 0, 0]];
let mut d: Vec<u8> = px.concat();
fx("video.ntscColors", json!({})).apply(&mut d, w, h, &space(w, h));
let luma = |p: [u8; 4]| 0.299 * f64::from(p[0]) + 0.587 * f64::from(p[1]) + 0.114 * f64::from(p[2]);
for (x, &a) in px.iter().enumerate() {
let b = at(&d, w, x, 0);
if x >= 2 {
assert_eq!(b, a, "{x}: unchanged");
continue;
}
let spread = |p: [u8; 4]| p[..3].iter().max().unwrap() - p[..3].iter().min().unwrap();
assert!(spread(b) < spread(a), "{x}: less saturated {b:?}");
assert!((luma(a) - luma(b)).abs() < 3.0, "{x}: as bright {a:?} {b:?}");
}
}
+74
View File
@@ -0,0 +1,74 @@
//! Effect › Video: De-Interlace and NTSC Colors.
use vectorcraft_geom::Point;
use super::PixelSpace;
/// The tallest field line De-Interlace reads across (document units): one pixel at the lowest
/// document raster resolution, 1 ppi.
pub(super) const MAX_LINE: f64 = 72.0;
/// De-Interlace: the odd (or, with `even`, the even) fields of the image are made again from the
/// others. The fields are the lines of the document's raster grid (each [`PixelSpace::line`]
/// tall, numbered from 1 at the top of the page): a line taken out becomes a copy of the line
/// above it (the one below at the top), or with `interpolate` the average of the two.
pub(super) fn deinterlace(px: &mut [[u8; 4]], w: usize, h: usize, space: &PixelSpace, even: bool, interpolate: bool) {
let line = space.line;
let to_px = space.to_doc.inverse();
if !(line.is_finite() && line > 0.0 && to_px.is_finite() && space.to_doc.is_finite()) {
return;
}
let src = px.to_vec();
// The pixel holding document point `q`.
let at = |q: Point| {
let p = to_px * q;
(p.x >= 0.0 && p.y >= 0.0 && p.x < w as f64 && p.y < h as f64).then(|| src.get(p.y as usize * w + p.x as usize).copied()).flatten()
};
for (i, out) in px.iter_mut().enumerate().take(w.saturating_mul(h)) {
let q = space.to_doc * Point::new((i % w) as f64 + 0.5, (i / w) as f64 + 0.5);
let k = (q.y / line).floor();
// Line k + 1: odd lines have an even k.
if !k.is_finite() || ((k as i64).rem_euclid(2) == 1) != even {
continue;
}
let (above, below) = (at(Point::new(q.x, q.y - line)), at(Point::new(q.x, q.y + line)));
let made = match (interpolate, above, below) {
(true, Some(a), Some(b)) => Some([0, 1, 2, 3].map(|c| (u16::from(a[c]) + u16::from(b[c])).div_ceil(2) as u8)),
(_, a, b) => a.or(b),
};
if let Some(v) = made {
*out = v;
}
}
}
/// NTSC Colors: colours a television's composite signal can't carry are made less saturated,
/// keeping their brightness. In YIQ, the luma plus the chroma's amplitude must stay within 110 %
/// of white and the luma minus it above −20 %; a colour past either has its chroma cut to fit.
pub(super) fn ntsc(px: &mut [[u8; 4]]) {
for p in px.iter_mut() {
let a = f32::from(p[3]) / 255.0;
if a <= 0.0 {
continue;
}
// Straight colour (the pixels are premultiplied).
let [r, g, b] = [p[0], p[1], p[2]].map(|v| (f32::from(v) / 255.0 / a).min(1.0));
let y = 0.299 * r + 0.587 * g + 0.114 * b;
let (i, q) = (0.596 * r - 0.274 * g - 0.322 * b, 0.211 * r - 0.523 * g + 0.312 * b);
let c = i.hypot(q);
let mut keep = 1.0f32;
if y + c > 1.1 {
keep = keep.min((1.1 - y) / c);
}
if y - c < -0.2 {
keep = keep.min((y + 0.2) / c);
}
if keep >= 1.0 || !keep.is_finite() {
continue;
}
let (i, q) = (i * keep.max(0.0), q * keep.max(0.0));
let rgb = [y + 0.956 * i + 0.621 * q, y - 0.272 * i - 0.647 * q, y - 1.106 * i + 1.703 * q];
let [r, g, b] = rgb.map(|v| (v.clamp(0.0, 1.0) * a * 255.0).round() as u8);
*p = [r, g, b, p[3]];
}
}
+19 -1
View File
@@ -318,7 +318,22 @@ fn require_targets(s: &Session, p: &Value, cmd: &str) -> Result<Vec<NodeId>> {
/// One undo step (`label`) running `f` on each of `ids` with the item a fill (`fill`) or stroke
/// edit aimed at `item` changes there (`None`: the topmost one; text then edits its characters).
/// Nothing targeted is not an edit.
pub(crate) fn edit_items(
s: &mut Session,
ids: &[NodeId],
item: ItemTarget,
cmd: &str,
label: &str,
fill: bool,
f: impl FnMut(&mut Node, Option<usize>) -> Result<()>,
) -> Result<()> {
edit_items_then(s, ids, item, cmd, label, fill, f, |_, _| Ok(()))
}
/// [`edit_items`], then `after` on the ids `f` changed, inside the same undo step.
#[allow(clippy::too_many_arguments)]
pub(crate) fn edit_items_then(
s: &mut Session,
ids: &[NodeId],
item: ItemTarget,
@@ -326,17 +341,20 @@ pub(crate) fn edit_items(
label: &str,
fill: bool,
mut f: impl FnMut(&mut Node, Option<usize>) -> Result<()>,
mut after: impl FnMut(&mut vectorcraft_doc::Document, &[NodeId]) -> Result<()>,
) -> Result<()> {
if ids.is_empty() {
return Ok(());
}
s.edit(label, |d, _| {
let mut changed = Vec::new();
for id in ids {
let Some(n) = d.node_mut(*id) else { continue };
let index = item.resolve(&n.appearance, fill, cmd)?;
f(n, index)?;
changed.push(*id);
}
Ok(())
after(d, &changed)
})
}
+39 -23
View File
@@ -8,7 +8,7 @@ use vectorcraft_geom::Affine;
use super::super::*;
use super::pdfimport::LoadOptions;
use super::{Format, SAVE_FORMATS, absolute_path, file_stamp, format, format_for_name, read_file};
use super::{Format, SAVE_FORMATS, absolute_path, file_stamp, format, format_for_name, psdread, read_file};
use crate::EngineError;
/// A file read into a document, with its format and non-fatal import notes.
@@ -76,6 +76,9 @@ pub fn detect(name: &str, bytes: &[u8]) -> Option<&'static Format> {
if let Some(kind) = vectorcraft_metafile::sniff(bytes) {
return format(kind.id());
}
if psdread::is_psd(bytes) {
return format(if psdread::is_psb(bytes) { "psb" } else { "psd" });
}
if let Some(f) = image::guess_format(bytes).ok().and_then(image_format) {
return Some(f);
}
@@ -355,37 +358,50 @@ const MAX_RASTER_ALLOC: u64 = if cfg!(target_arch = "wasm32") { 512 << 20 } else
/// Decode an image's header (and, for formats stored as PNG, its pixels). CMYK TIFFs are kept as
/// they are, with their ink amounts ([`ImageBlob::cmyk`]); CMYK TIFFs with an alpha channel, which
/// the decoder can't read, become RGBA in the active colour settings' CMYK.
/// the decoder can't read, become RGBA in the active colour settings' CMYK, as do CMYK Photoshop
/// documents, whose merged image is read ([`psdread`]).
pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> {
let ppi = super::ppi::resolution(bytes);
if psdread::is_psd(bytes) {
let cms = vectorcraft_color::cms::active();
return as_png(psdread::decode(bytes, MAX_RASTER_ALLOC, |c| cms.cmyk_to_srgb(c, false)).map_err(err)?, ppi);
}
let mut reader = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().map_err(err)?;
let mut limits = image::Limits::default();
limits.max_alloc = Some(MAX_RASTER_ALLOC);
reader.limits(limits);
let kind = reader.format().ok_or_else(|| err("not an image VectorCraft reads (see document.formats)"))?;
let f = image_format(kind).ok_or_else(|| err(format!("{kind:?} images can't be opened (see document.formats)")))?;
let ppi = super::ppi::resolution(bytes);
let cmyk = || ImageBlob::new(f.mime, bytes.to_vec()).cmyk().is_some();
let (bytes, mime, (width, height)) = if matches!(f.id, "png" | "jpg" | "gif" | "webp") || (f.id == "tiff" && cmyk()) {
(bytes.to_vec(), f.mime, reader.into_dimensions().map_err(err)?)
} else {
let cmyka = || {
let cms = vectorcraft_color::cms::active();
vectorcraft_doc::cmyk::cmyka_tiff_rgba(bytes, |c| cms.cmyk_to_srgb(c, false))
};
let img = match (f.id == "tiff").then(cmyka).flatten() {
Some(img) => img,
None => reader.decode().map_err(err)?.to_rgba8(),
};
let size = img.dimensions();
let mut png = Vec::new();
img.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).map_err(err)?;
// The stored PNG keeps the file's resolution.
let png = match ppi {
Some(r) => super::ppi::with_png_resolution(&png, r),
None => png,
};
(png, "image/png", size)
if matches!(f.id, "png" | "jpg" | "gif" | "webp") || (f.id == "tiff" && cmyk()) {
let (width, height) = reader.into_dimensions().map_err(err)?;
return stored(bytes.to_vec(), f.mime, (width, height), ppi);
}
let cmyka = || {
let cms = vectorcraft_color::cms::active();
vectorcraft_doc::cmyk::cmyka_tiff_rgba(bytes, |c| cms.cmyk_to_srgb(c, false))
};
let img = match (f.id == "tiff").then(cmyka).flatten() {
Some(img) => img,
None => reader.decode().map_err(err)?.to_rgba8(),
};
as_png(img, ppi)
}
/// `img` stored as a PNG that keeps the file's resolution.
fn as_png(img: image::RgbaImage, ppi: Option<(f64, f64)>) -> Result<RasterImage> {
let size = img.dimensions();
let mut png = Vec::new();
img.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).map_err(err)?;
let png = match ppi {
Some(r) => super::ppi::with_png_resolution(&png, r),
None => png,
};
stored(png, "image/png", size, ppi)
}
/// An image's encoded `bytes`, `width` × `height` pixels, ready to embed.
fn stored(bytes: Vec<u8>, mime: &'static str, (width, height): (u32, u32), ppi: Option<(f64, f64)>) -> Result<RasterImage> {
if width == 0 || height == 0 {
return Err(err("the image is empty"));
}
+15 -1
View File
@@ -34,6 +34,7 @@ pub mod pdf;
mod pdfimport;
pub mod pngtext;
pub mod ppi;
pub mod psdread;
mod save;
mod screens;
mod svg;
@@ -558,10 +559,12 @@ pub const FORMATS: &[Format] = &[
Format { id: "emf", label: "EMF", extensions: &["emf"], mime: "image/emf", read: true, write: true, raster: false, options: metafile::OPTIONS },
Format { id: "wmf", label: "WMF", extensions: &["wmf"], mime: "image/wmf", read: true, write: true, raster: false, options: metafile::OPTIONS },
Format { id: "tga", label: "Targa", extensions: &["tga"], mime: "image/x-tga", read: false, write: true, raster: true, options: TGA_OPTIONS },
Format { id: "psd", label: "PSD", extensions: &["psd"], mime: "image/x-psd", read: false, write: true, raster: true, options: PSD_OPTIONS },
Format { id: "psd", label: "PSD", extensions: &["psd"], mime: "image/x-psd", read: true, write: true, raster: true, options: PSD_OPTIONS },
// Affinity Photo's `.afphoto` opens by its content but isn't listed: Finder shouldn't offer a
// vector app for a raster editor's documents.
reader("affinity", "Affinity", &["af", "afdesign", "afpub"], "application/vnd.affinity", false),
// Photoshop's large document format: read like a PSD (its merged image), never written.
reader("psb", "PSB", &["psb"], "image/x-psb", true),
];
/// Every extension `document.open` reads (the "All readable files" filter of open dialogs).
@@ -581,6 +584,8 @@ pub const OPEN_EXTS: &[&str] = &[
"tif",
"tiff",
"bmp",
"psd",
"psb",
"vctemplate",
"dxf",
"emf",
@@ -591,6 +596,11 @@ pub const OPEN_EXTS: &[&str] = &[
"afpub",
];
/// Extensions in [`OPEN_EXTS`] the desktop packaging doesn't associate with VectorCraft: Photoshop
/// documents belong to raster editors, so Finder and file managers don't offer a vector app for
/// them (File › Open and Place still read them).
pub const UNASSOCIATED_EXTS: &[&str] = &["psd", "psb"];
/// The extension that picks each writable format when exporting (the format's first; PNG-8 shares
/// `.png` with PNG, so `.png` comes once), in [`FORMATS`] order.
pub fn export_extensions() -> Vec<&'static str> {
@@ -623,6 +633,8 @@ pub const PLACE_EXTS: &[&str] = &[
"tif",
"tiff",
"bmp",
"psd",
"psb",
"vctemplate",
"dxf",
"emf",
@@ -979,6 +991,8 @@ mod tests_tiffbmp;
mod tests_pdfx;
#[cfg(test)]
mod tests_psd;
#[cfg(test)]
mod tests_psdread;
#[cfg(test)]
mod tests_epsimport;
+5 -2
View File
@@ -1,6 +1,7 @@
//! Image resolution metadata (pixels per inch): PNG `pHYs`, JPEG JFIF density or EXIF, TIFF and
//! WebP EXIF resolution tags, BMP pixels per metre. Place sizes an image by it (72 ppi when the file
//! has none); images converted to PNG on import keep it as a `pHYs` chunk.
//! WebP EXIF resolution tags, BMP pixels per metre, a Photoshop document's ResolutionInfo. Place
//! sizes an image by it (72 ppi when the file has none); images converted to PNG on import keep it
//! as a `pHYs` chunk.
const INCH_M: f64 = 0.0254;
const INCH_CM: f64 = 2.54;
@@ -18,6 +19,8 @@ pub fn resolution(bytes: &[u8]) -> Option<(f64, f64)> {
webp(bytes)
} else if bytes.starts_with(b"BM") {
bmp(bytes)
} else if super::psdread::is_psd(bytes) {
super::psdread::resolution(bytes)
} else {
None
};
+370
View File
@@ -0,0 +1,370 @@
//! Reading Photoshop documents (PSD, and PSB, the large document format) for File › Open and
//! File › Place (#918): the merged image, the flattened picture every PSD carries after its layers,
//! as a linked PSD shows. Written from Adobe's public "Photoshop File Formats Specification"
//! (<https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/>). Layers aren't read.
//!
//! Every mode Photoshop saves a merged image in is read: Bitmap, Grayscale, Duotone (as its
//! grayscale data), Indexed, RGB, CMYK and Lab, at 1, 8, 16 and 32 bits per channel, stored raw,
//! PackBits-compressed or zipped. The merged image of a document with transparency is stored on
//! white with its alpha in the first extra channel: it comes back with straight colours. The file
//! is untrusted: every read is checked and the image's size is capped before anything is
//! allocated.
use std::io::Read;
use vectorcraft_color::cms::{Lab, lab::lab_to_srgb};
/// Photoshop's colour modes (the header's numbers), as far as the merged image is concerned.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Mode {
Bitmap,
Gray,
Indexed,
Rgb,
Cmyk,
Lab,
}
impl Mode {
/// The channels holding colour (an alpha channel may follow them).
fn colors(self) -> usize {
match self {
Mode::Bitmap | Mode::Gray | Mode::Indexed => 1,
Mode::Rgb | Mode::Lab => 3,
Mode::Cmyk => 4,
}
}
}
/// Is `bytes` a Photoshop document (PSD or PSB)?
pub fn is_psd(bytes: &[u8]) -> bool {
bytes.starts_with(b"8BPS") && matches!(bytes.get(4..6), Some([0, 1] | [0, 2]))
}
/// Is `bytes` a PSB, Photoshop's large document format?
pub fn is_psb(bytes: &[u8]) -> bool {
is_psd(bytes) && bytes.get(4..6) == Some(&[0, 2])
}
const TRUNCATED: &str = "the PSD file is cut short";
const DAMAGED: &str = "the PSD file's header is damaged";
/// Big-endian reads through `b`, each checked against its end.
struct Reader<'a> {
b: &'a [u8],
at: usize,
}
impl<'a> Reader<'a> {
fn new(b: &'a [u8]) -> Self {
Self { b, at: 0 }
}
fn take(&mut self, n: usize) -> Result<&'a [u8], String> {
let s = self.at.checked_add(n).and_then(|end| self.b.get(self.at..end)).ok_or(TRUNCATED)?;
self.at += n;
Ok(s)
}
fn array<const N: usize>(&mut self) -> Result<[u8; N], String> {
self.take(N)?.try_into().map_err(|_| TRUNCATED.to_string())
}
fn u8(&mut self) -> Result<u8, String> {
self.array::<1>().map(|[v]| v)
}
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 section length: 4 bytes in a PSD, 8 in a PSB.
fn length(&mut self, psb: bool) -> Result<usize, String> {
let n = if psb { self.array().map(u64::from_be_bytes)? } else { u64::from(self.u32()?) };
usize::try_from(n).map_err(|_| TRUNCATED.to_string())
}
/// A section: its length, then that many bytes.
fn section(&mut self, psb: bool) -> Result<&'a [u8], String> {
let n = self.length(psb)?;
self.take(n)
}
fn rest(&self) -> &'a [u8] {
self.b.get(self.at..).unwrap_or_default()
}
}
/// The fixed-size header and the sections before the image data.
struct Header<'a> {
psb: bool,
channels: usize,
width: u32,
height: u32,
depth: u16,
mode: Mode,
/// Colour mode data: an indexed image's palette (256 reds, then greens, then blues).
palette: &'a [u8],
/// The image resources.
resources: &'a [u8],
/// The layer and mask information.
layers: &'a [u8],
}
fn header<'a>(r: &mut Reader<'a>) -> Result<Header<'a>, String> {
if !is_psd(r.b) {
return Err("not a PSD file".into());
}
r.take(4)?;
let psb = r.u16()? == 2;
r.take(6)?;
let channels = usize::from(r.u16()?);
let height = r.u32()?;
let width = r.u32()?;
let depth = r.u16()?;
let mode = match r.u16()? {
0 => Mode::Bitmap,
// Duotone documents keep their grayscale data in the merged image.
1 | 8 => Mode::Gray,
2 => Mode::Indexed,
3 => Mode::Rgb,
4 => Mode::Cmyk,
9 => Mode::Lab,
7 => return Err("Multichannel PSD files can't be read: save it in RGB, CMYK or Grayscale mode".into()),
m => return Err(format!("the PSD file has an unknown colour mode ({m})")),
};
let max_side = if psb { 300_000 } else { 30_000 };
if !(1..=56).contains(&channels) || channels < mode.colors() || !(1..=max_side).contains(&width) || !(1..=max_side).contains(&height) {
return Err(DAMAGED.into());
}
let depth_ok = match mode {
Mode::Bitmap => depth == 1,
Mode::Indexed => depth == 8,
Mode::Cmyk | Mode::Lab => matches!(depth, 8 | 16),
Mode::Gray | Mode::Rgb => matches!(depth, 8 | 16 | 32),
};
if !depth_ok {
return Err(format!("{depth}-bit PSD files in this colour mode can't be read"));
}
let palette = r.section(false)?;
let resources = r.section(false)?;
let layers = r.section(psb)?;
Ok(Header { psb, channels, width, height, depth, mode, palette, resources, layers })
}
/// The resolution a Photoshop document declares (pixels per inch, across and down), from its
/// ResolutionInfo resource (1005).
pub fn resolution(bytes: &[u8]) -> Option<(f64, f64)> {
let mut r = Reader::new(bytes);
let h = header(&mut r).ok()?;
let mut r = Reader::new(h.resources);
while !r.rest().is_empty() {
r.take(4).ok()?;
let id = r.u16().ok()?;
// A Pascal string padded to an even size, length byte included.
let name = usize::from(r.u8().ok()?);
r.take(name + (name + 1) % 2).ok()?;
let size = usize::try_from(r.u32().ok()?).ok()?;
let data = r.take(size).ok()?;
r.take(size % 2).ok()?;
if id == 0x03ed {
let mut d = Reader::new(data);
// Fixed 16.16 values, each with its unit (1: per inch, 2: per centimetre) and the
// unit the size is shown in.
let mut axis = || -> Option<f64> {
let v = f64::from(d.u32().ok()?) / 65536.0;
let unit = d.u16().ok()?;
d.u16().ok()?;
Some(if unit == 2 { v * 2.54 } else { v })
};
return Some((axis()?, axis()?));
}
}
None
}
/// Does the merged image keep its transparency in the first extra channel? Yes when the layer
/// count is negative: in the layer info, or for 16- and 32-bit documents (whose layer info is
/// empty) in their `Lr16` / `Lr32` block.
fn merged_alpha(layers: &[u8], psb: bool) -> bool {
let count_negative = |info: &[u8]| info.get(..2).is_some_and(|c| i16::from_be_bytes([c[0], c[1]]) < 0);
let mut r = Reader::new(layers);
let Ok(info) = r.section(psb) else { return false };
if !info.is_empty() {
return count_negative(info);
}
// The global layer mask info, then tagged blocks: signature, key, length (8 bytes for the
// layer blocks of a PSB), data padded to 4 bytes.
if r.section(false).is_err() {
return false;
}
while r.rest().len() >= 12 {
let (Ok(_), Ok(key)) = (r.take(4), r.array::<4>()) else { return false };
let layer_block = matches!(&key, b"Lr16" | b"Lr32" | b"Layr");
let long = layer_block || matches!(&key, b"LMsk" | b"Mt16" | b"Mt32" | b"Mtrn" | b"Alph" | b"FMsk" | b"lnk2" | b"FEid" | b"FXid" | b"PxSD");
let Ok(data) = r.section(psb && long) else {
return false;
};
if layer_block {
return count_negative(data);
}
if r.take((4 - data.len() % 4) % 4).is_err() {
return false;
}
}
false
}
/// The most bytes one channel row may take (a PSB at 32 bits).
fn row_bytes(width: usize, depth: u16) -> usize {
if depth == 1 { width.div_ceil(8) } else { width * usize::from(depth / 8) }
}
/// Undo PackBits: `src` into `dst` (a row; a short or overlong run leaves the rest as it is).
fn unpack_bits(mut src: &[u8], dst: &mut [u8]) {
let mut at = 0;
while let Some((&n, rest)) = src.split_first() {
src = rest;
let n = n as i8;
if n >= 0 {
let len = usize::from(n.unsigned_abs()) + 1;
let (run, rest) = src.split_at(len.min(src.len()));
src = rest;
for &b in run {
if let Some(d) = dst.get_mut(at) {
*d = b;
}
at += 1;
}
} else if n != -128 {
let Some((&b, rest)) = src.split_first() else { break };
src = rest;
let len = usize::from(n.unsigned_abs()) + 1;
for d in dst.iter_mut().skip(at).take(len) {
*d = b;
}
at += len;
}
if at >= dst.len() {
break;
}
}
}
/// The first `channels` channels of the image data (after its compression method), each as
/// `height` rows of `row` bytes, one after the other.
fn channel_data(data: &[u8], h: &Header<'_>, channels: usize, row: usize) -> Result<Vec<u8>, String> {
let (rows, all) = (h.height as usize, h.channels);
let mut r = Reader::new(data);
let method = r.u16()?;
let wanted = channels * rows * row;
match method {
0 => r.take(wanted).map(<[u8]>::to_vec),
1 => {
// Every row's byte count (4 bytes each in a PSB), channel by channel: those of the
// channels read, then the others'.
let size = if h.psb { 4 } else { 2 };
let counts = r.take(channels * rows * size)?;
r.take((all - channels) * rows * size)?;
let counts = counts.chunks_exact(size).map(|c| c.iter().fold(0usize, |n, &b| n << 8 | usize::from(b)));
let mut out = vec![0; wanted];
for (dst, n) in out.chunks_exact_mut(row).zip(counts) {
unpack_bits(r.take(n)?, dst);
}
Ok(out)
}
2 | 3 => {
let mut out = Vec::new();
flate2::read::ZlibDecoder::new(r.rest())
.take(wanted as u64)
.read_to_end(&mut out)
.map_err(|e| format!("the PSD file's image data can't be read: {e}"))?;
if out.len() < wanted {
return Err(TRUNCATED.into());
}
if method == 3 {
// Each row stores the difference from the sample before it.
match h.depth {
8 => out.chunks_exact_mut(row).for_each(|r| (1..r.len()).for_each(|i| r[i] = r[i].wrapping_add(r[i - 1]))),
16 => out.chunks_exact_mut(row).for_each(|r| {
let mut prev = 0u16;
for s in r.as_chunks_mut::<2>().0 {
prev = prev.wrapping_add(u16::from_be_bytes(*s));
*s = prev.to_be_bytes();
}
}),
_ => return Err("zipped 32-bit PSD image data with prediction can't be read".into()),
}
}
Ok(out)
}
m => Err(format!("the PSD file's image data uses an unknown compression ({m})")),
}
}
/// sRGB's transfer curve, for 32-bit documents, whose values are linear.
fn srgb_encode(v: f32) -> f32 {
if v <= 0.003_130_8 { v * 12.92 } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 }
}
/// Sample `x` of a channel row, 0..1.
fn sample(row: &[u8], x: usize, depth: u16, linear: bool) -> f32 {
match depth {
1 => {
// Bitmap: a set bit is black.
let bit = row.get(x / 8).map_or(0, |b| (b >> (7 - x % 8)) & 1);
if bit == 1 { 0.0 } else { 1.0 }
}
16 => row.get(x * 2..x * 2 + 2).map_or(0.0, |s| f32::from(u16::from_be_bytes([s[0], s[1]])) / 65535.0),
32 => {
let v = row.get(x * 4..x * 4 + 4).map_or(0.0, |s| f32::from_be_bytes([s[0], s[1], s[2], s[3]]));
let v = if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 };
if linear { srgb_encode(v) } else { v }
}
_ => row.get(x).map_or(0.0, |&b| f32::from(b) / 255.0),
}
}
fn byte(v: f32) -> u8 {
(v.clamp(0.0, 1.0) * 255.0).round() as u8
}
/// A Photoshop document's merged image as straight RGBA. CMYK converts through `cmyk` (ink
/// amounts 0..1 → sRGB). Fails, without allocating, when the image would need more than
/// `max_alloc` bytes.
pub fn decode(bytes: &[u8], max_alloc: u64, cmyk: impl Fn([f32; 4]) -> [f32; 3]) -> Result<image::RgbaImage, String> {
let mut r = Reader::new(bytes);
let h = header(&mut r)?;
let colors = h.mode.colors();
let alpha = h.channels > colors && merged_alpha(h.layers, h.psb);
let channels = colors + usize::from(alpha);
let (w, rows) = (h.width as usize, h.height as usize);
let row = row_bytes(w, h.depth);
// The channels read and the RGBA image made of them.
let need = (channels as u64 * row as u64).saturating_add(4 * w as u64).saturating_mul(rows as u64);
if need > max_alloc {
return Err(format!("the PSD image is too large to read ({} × {} pixels)", h.width, h.height));
}
let data = channel_data(r.rest(), &h, channels, row)?;
let mut out = image::RgbaImage::new(h.width, h.height);
let linear = h.depth == 32;
for (y, line) in out.rows_mut().enumerate() {
let planes: Vec<&[u8]> = (0..channels).map(|c| data.get((c * rows + y) * row..(c * rows + y + 1) * row).unwrap_or_default()).collect();
for (x, px) in line.enumerate() {
let v = |c: usize| planes.get(c).map_or(0.0, |p| sample(p, x, h.depth, linear && c < colors));
let rgb = match h.mode {
Mode::Bitmap | Mode::Gray => [v(0); 3],
Mode::Indexed => {
let i = usize::from(byte(v(0)));
[0, 256, 512].map(|at| h.palette.get(at + i).map_or(0.0, |&c| f32::from(c) / 255.0))
}
Mode::Rgb => [v(0), v(1), v(2)],
// Inks are stored as 1 − amount.
Mode::Cmyk => cmyk([0, 1, 2, 3].map(|c| 1.0 - v(c))),
Mode::Lab => lab_to_srgb(Lab { l: v(0) * 100.0, a: v(1) * 255.0 - 128.0, b: v(2) * 255.0 - 128.0 }),
};
let a = if alpha { v(colors) } else { 1.0 };
// The merged image is stored on white: take the white back out.
let straight = |c: f32| if a <= 0.0 { 0.0 } else { (c - (1.0 - a)) / a };
let rgb = if alpha { rgb.map(straight) } else { rgb };
px.0 = [byte(rgb[0]), byte(rgb[1]), byte(rgb[2]), byte(a)];
}
}
Ok(out)
}
+1 -1
View File
@@ -77,7 +77,7 @@ fn psd_is_listed_with_its_options_and_writes_one_file_per_artboard() {
let psd = r["formats"].as_array().unwrap().iter().find(|f| f["id"] == "psd").unwrap().clone();
assert_eq!(
(psd["label"].as_str(), psd["write"].as_bool(), psd["read"].as_bool(), psd["raster"].as_bool()),
(Some("PSD"), Some(true), Some(false), Some(true))
(Some("PSD"), Some(true), Some(true), Some(true))
);
for k in ["colorModel", "layers", "maxEditability", "hiddenLayers", "embedIcc", "ppi", "antiAlias", "background"] {
assert!(psd["options"].get(k).is_some(), "psd takes {k}");
@@ -0,0 +1,244 @@
//! Reading Photoshop documents (#918): the merged image of every colour mode, depth and
//! compression, PSB files, transparency, the resolution, and damaged files refused without a panic.
use serde_json::{Value, json};
use super::psdread::{decode, is_psd, resolution};
use super::*;
/// A Photoshop document built from its parts: `version` 1 (PSD) or 2 (PSB), the header's fields,
/// then the colour mode data, resources, layer and mask section and image data as given.
#[allow(clippy::too_many_arguments)]
fn psd(
version: u16,
channels: u16,
(w, h): (u32, u32),
depth: u16,
mode: u16,
palette: &[u8],
resources: &[u8],
layers: &[u8],
image: &[u8],
) -> Vec<u8> {
let mut f = b"8BPS".to_vec();
f.extend(version.to_be_bytes());
f.extend([0; 6]);
f.extend(channels.to_be_bytes());
f.extend(h.to_be_bytes());
f.extend(w.to_be_bytes());
f.extend(depth.to_be_bytes());
f.extend(mode.to_be_bytes());
for part in [palette, resources] {
f.extend((part.len() as u32).to_be_bytes());
f.extend(part);
}
if version == 2 {
f.extend((layers.len() as u64).to_be_bytes());
} else {
f.extend((layers.len() as u32).to_be_bytes());
}
f.extend(layers);
f.extend(image);
f
}
/// Raw image data: the compression method (0), then the planes.
fn raw(planes: &[&[u8]]) -> Vec<u8> {
let mut d = vec![0, 0];
planes.iter().for_each(|p| d.extend(*p));
d
}
/// A layer and mask section whose layer info holds just the layer `count` (negative: the merged
/// image's first extra channel is its transparency).
fn layer_count(count: i16, psb: bool) -> Vec<u8> {
let mut s = if psb { 2u64.to_be_bytes().to_vec() } else { 2u32.to_be_bytes().to_vec() };
s.extend(count.to_be_bytes());
s
}
/// Straight sRGB through a naive CMYK conversion (tests don't depend on colour settings).
fn naive(c: [f32; 4]) -> [f32; 3] {
[0, 1, 2].map(|i| (1.0 - c[i]) * (1.0 - c[3]))
}
fn pixels(f: &[u8]) -> Vec<[u8; 4]> {
decode(f, 1 << 30, naive).unwrap().pixels().map(|p| p.0).collect()
}
#[test]
fn every_colour_mode_and_depth_reads() {
// Grayscale, 16 bits.
let g = psd(1, 1, (2, 1), 16, 1, &[], &[], &[], &raw(&[&[0, 0, 0xff, 0xff]]));
assert!(is_psd(&g));
assert_eq!(pixels(&g), [[0, 0, 0, 255], [255, 255, 255, 255]]);
// Bitmap: a set bit is black.
let b = psd(1, 1, (9, 1), 1, 0, &[], &[], &[], &raw(&[&[0b1000_0000, 0b1000_0000]]));
let px = pixels(&b);
assert_eq!((px[0], px[1], px[8]), ([0, 0, 0, 255], [255, 255, 255, 255], [0, 0, 0, 255]));
// Indexed: 256 reds, greens, blues.
let mut palette = vec![0; 768];
(palette[1], palette[257], palette[513]) = (10, 20, 30);
let i = psd(1, 1, (1, 1), 8, 2, &palette, &[], &[], &raw(&[&[1]]));
assert_eq!(pixels(&i), [[10, 20, 30, 255]]);
// RGB, 32 bits: linear values, shown through sRGB's curve.
let half = 0.5f32.to_be_bytes();
let r = psd(1, 3, (1, 1), 32, 3, &[], &[], &[], &raw(&[&half, &half, &1.0f32.to_be_bytes()]));
assert_eq!(pixels(&r), [[188, 188, 255, 255]]);
// CMYK, inks stored as 255 − amount: 100 % K is black, no ink white.
let c = psd(1, 4, (2, 1), 8, 4, &[], &[], &[], &raw(&[&[255, 255], &[255, 255], &[255, 255], &[0, 255]]));
assert_eq!(pixels(&c), [[0, 0, 0, 255], [255, 255, 255, 255]]);
// Lab: L 100, a 0, b 0 is white.
let l = psd(1, 3, (1, 1), 8, 9, &[], &[], &[], &raw(&[&[255], &[128], &[128]]));
assert!(pixels(&l)[0].iter().all(|&v| v >= 253), "{:?}", pixels(&l));
// Duotone keeps its grayscale data in the merged image.
assert_eq!(pixels(&psd(1, 1, (1, 1), 8, 8, &[0; 40], &[], &[], &raw(&[&[64]]))), [[64, 64, 64, 255]]);
}
#[test]
fn transparency_comes_back_straight_and_extra_channels_without_it_stay_out() {
// Half-transparent red, stored on white: (255, 127, 127) with alpha 128.
let planes: [&[u8]; 4] = [&[255], &[127], &[127], &[128]];
let with = psd(1, 4, (1, 1), 8, 3, &[], &[], &layer_count(-1, false), &raw(&planes));
let [r, g, b, a] = pixels(&with)[0];
assert!(r == 255 && g <= 1 && b <= 1 && a == 128, "{:?}", [r, g, b, a]);
// A flat document's extra channel is a saved selection, not transparency.
let flat = psd(1, 4, (1, 1), 8, 3, &[], &[], &[], &raw(&planes));
assert_eq!(pixels(&flat), [[255, 127, 127, 255]]);
// A 16-bit document says so in its Lr16 block (its layer info is empty).
let mut layers = 0u32.to_be_bytes().to_vec();
layers.extend(0u32.to_be_bytes());
layers.extend(b"8BIMLr16");
layers.extend(4u32.to_be_bytes());
layers.extend((-1i16).to_be_bytes());
layers.extend([0, 0]);
let wide: [&[u8]; 4] = [&[0xff, 0xff], &[0x7f, 0x7f], &[0x7f, 0x7f], &[0x80, 0x80]];
let deep = psd(1, 4, (1, 1), 16, 3, &[], &[], &layers, &raw(&wide));
let [r, g, _, a] = pixels(&deep)[0];
assert!(r == 255 && g <= 1 && a == 128, "{:?}", pixels(&deep));
}
#[test]
fn packbits_zip_and_psb_files_read() {
// PackBits in a PSB: 4-byte row counts, transparency from a negative layer count.
let mut rle = vec![0, 1];
for _ in 0..4 {
rle.extend(2u32.to_be_bytes());
}
for v in [200u8, 100, 50, 255] {
rle.extend([0xfe, v]); // a run of three
}
let big = psd(2, 4, (3, 1), 8, 3, &[], &[], &layer_count(-1, true), &rle);
assert_eq!(pixels(&big), [[200, 100, 50, 255]; 3]);
let mut s = Session::new();
let r = s.execute("document.open", &json!({"name": "big.psb", "dataBase64": vectorcraft_format::base64_encode(&big)})).unwrap();
assert_eq!(r["format"], "psb");
// Zipped with prediction, 16 bits: each sample is the difference from the one before.
let deltas: Vec<u8> = [0x1000u16, 0x1000, 0x1000].iter().flat_map(|d| d.to_be_bytes()).collect();
let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default());
std::io::Write::write_all(&mut z, &deltas).unwrap();
let mut zip = vec![0, 3];
zip.extend(z.finish().unwrap());
let px = pixels(&psd(1, 1, (3, 1), 16, 1, &[], &[], &[], &zip));
assert_eq!(px.iter().map(|p| p[0]).collect::<Vec<_>>(), [16, 32, 48]);
}
#[test]
fn the_resolution_resource_sizes_the_placed_image() {
// ResolutionInfo (1005): 300 ppi across, 118.11 per cm (300 ppi) down.
let mut res = b"8BIM".to_vec();
res.extend(0x03edu16.to_be_bytes());
res.extend([0, 0]); // an empty name, padded
res.extend(16u32.to_be_bytes());
res.extend((300u32 << 16).to_be_bytes());
res.extend([0, 1, 0, 1]);
res.extend(((118.11f64 * 65536.0) as u32).to_be_bytes());
res.extend([0, 2, 0, 1]);
let f = psd(1, 3, (300, 150), 8, 3, &[], &res, &[], &raw(&[&[9; 45_000], &[9; 45_000], &[9; 45_000]]));
let (x, y) = resolution(&f).unwrap();
assert!((x - 300.0).abs() < 1e-9 && (y - 300.0).abs() < 0.01, "{x} {y}");
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
let r = s.execute("file.place", &json!({"name": "photo.psd", "dataBase64": vectorcraft_format::base64_encode(&f)})).unwrap();
assert!(
(r["width"].as_f64().unwrap() - 72.0).abs() < 0.01 && (r["height"].as_f64().unwrap() - 36.0).abs() < 0.01,
"an inch by half an inch: {r}"
);
}
/// A 60 × 40 pt document: a red square on a transparent page, and a half-transparent blue one.
fn art() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 60, "height": 40})).unwrap();
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 30, "height": 40})).unwrap();
s.execute("select.none", &json!({})).unwrap();
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
s.execute("shape.rectangle", &json!({"x": 40, "y": 0, "width": 20, "height": 40})).unwrap();
s.execute("transparency.set", &json!({"opacity": 50})).unwrap();
s
}
fn exported(s: &mut Session, p: Value) -> Vec<u8> {
let r = s.execute("document.export", &p).unwrap();
vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap()
}
#[test]
fn psd_exports_open_and_place_again() {
let mut s = art();
let png = image::load_from_memory(&exported(&mut s, json!({"format": "png"}))).unwrap().to_rgba8();
for (options, what) in [(json!({}), "layered RGB"), (json!({"layers": false}), "flat RGB"), (json!({"colorModel": "gray"}), "grey")] {
let f = exported(&mut s, merge(json!({"format": "psd"}), options));
let back = decode(&f, 1 << 30, naive).unwrap();
assert_eq!(back.dimensions(), png.dimensions(), "{what}");
let (red, clear, blue) = (back.get_pixel(10, 20).0, back.get_pixel(35, 20).0, back.get_pixel(50, 20).0);
if what == "layered RGB" {
assert_eq!((red, clear[3]), ([255, 0, 0, 255], 0), "{what}");
assert!(blue[2] >= 250 && blue[0] <= 3 && (blue[3] as i32 - png.get_pixel(50, 20).0[3] as i32).abs() <= 1, "{what}: {blue:?}");
} else if what == "flat RGB" {
assert_eq!((red, clear), ([255, 0, 0, 255], [255, 255, 255, 255]), "{what}: flat files are on white");
} else {
assert!(red[0] == red[1] && red[3] == 255, "{what}: {red:?}");
}
// Open and Place take it by its content, whatever its name.
let r = s.execute("document.open", &json!({"name": "back.bin", "dataBase64": vectorcraft_format::base64_encode(&f)})).unwrap();
assert_eq!(r["format"], "psd", "{what}");
let d = &s.doc().unwrap().doc;
assert!((d.artboards[0].rect.width() - 60.0).abs() < 1e-6, "{what}");
}
let r = s.execute("document.formats", &json!({})).unwrap();
assert!(r["readable"].as_array().unwrap().iter().any(|v| v == "psd"));
assert!(PLACE_EXTS.contains(&"psd") && PLACE_EXTS.contains(&"psb") && OPEN_EXTS.contains(&"psb"));
}
#[test]
fn damaged_and_unsupported_files_are_refused_without_a_panic() {
let good = psd(2, 4, (3, 2), 8, 3, &[], &[], &layer_count(-1, true), &raw(&[&[1; 6], &[2; 6], &[3; 6], &[4; 6]]));
assert!(decode(&good, 1 << 30, naive).is_ok());
for n in 0..good.len() {
assert!(decode(&good[..n], 1 << 30, naive).is_err(), "cut at {n}");
let _ = resolution(&good[..n]);
}
// Every byte changed in turn: an error or an image, never a panic.
for i in 0..good.len() {
for v in [0, 1, 0x7f, 0x80, 0xff] {
let mut f = good.clone();
f[i] = v;
let _ = decode(&f, 1 << 30, naive);
let _ = resolution(&f);
}
}
// An image too large for the memory allowed is refused before anything is allocated.
let huge = psd(2, 3, (300_000, 300_000), 16, 3, &[], &[], &[], &[0, 0]);
assert!(decode(&huge, 1 << 30, naive).unwrap_err().contains("too large"));
// Multichannel, and depths a mode doesn't have.
assert!(decode(&psd(1, 2, (1, 1), 8, 7, &[], &[], &[], &raw(&[&[0], &[0]])), 1 << 30, naive).unwrap_err().contains("Multichannel"));
assert!(decode(&psd(1, 4, (1, 1), 32, 4, &[], &[], &[], &[0, 0]), 1 << 30, naive).is_err());
// A placed file with a damaged image reports it.
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let cut = &good[..good.len() - 3];
assert!(s.execute("file.place", &json!({"name": "cut.psd", "dataBase64": vectorcraft_format::base64_encode(cut)})).is_err());
}
+369 -19
View File
@@ -5,6 +5,7 @@
//! the spec. Editing the data or the type regenerates them in place, keeping any move/scale the
//! user applied to the graph since it was generated.
use std::collections::HashMap;
use std::sync::Arc;
use serde_json::{Value, json};
@@ -131,11 +132,26 @@ fn fmt_value(v: f64) -> String {
// ---------- generation ----------
/// Series colours: black, then greys (Illustrator's graphs start in greyscale too).
fn series_paint(i: usize) -> Paint {
/// Series colours: black, then greys (graphs start in greyscale).
fn default_series_color(i: usize) -> Color {
const LEVELS: [f32; 8] = [0.0, 0.55, 0.8, 0.3, 0.68, 0.15, 0.9, 0.42];
let l = LEVELS[i % LEVELS.len()];
Paint::solid(Color::rgb(l, l, l))
Color::rgb(l, l, l)
}
fn default_series_paint(i: usize) -> Paint {
Paint::solid(default_series_color(i))
}
/// Fill and stroke for one generated mark of series `i`. A stored fill is used only where the
/// generator paints with the series colour (`series_fill`). A stored stroke replaces that part's
/// own stroke, so a column's stroke stays a stroke and a line's markers do not repaint its line.
fn series_marks(g: &GraphSpec, i: usize, series_fill: bool, stroke: Paint, width: f64) -> (Paint, Paint, f64) {
let slot = g.series_paints.get(i);
let fill = if series_fill { slot.and_then(|p| p.fill.clone()).unwrap_or_else(|| default_series_paint(i)) } else { Paint::None };
let stroke = slot.and_then(|p| p.stroke.clone()).unwrap_or(stroke);
let width = if slot.is_some_and(|p| p.stroke.is_some()) { slot.and_then(|p| p.stroke_width).unwrap_or(width) } else { width };
(fill, stroke, width)
}
const LABEL_SIZE: f64 = 9.0;
@@ -177,6 +193,14 @@ impl Gen<'_> {
g.name = Some(name.into());
Arc::new(g)
}
/// A series group. Empty series are omitted by the caller; the index is stored on the group
/// so later paint edits find the series without counting siblings.
fn series(&mut self, name: &str, index: usize, children: Vec<Arc<Node>>) -> Arc<Node> {
let mut g = Node::group(self.d.alloc_id(), children);
g.name = Some(name.into());
g.series_index = u32::try_from(index).ok();
Arc::new(g)
}
}
fn polyline(pts: &[Point], closed: bool) -> PathData {
@@ -200,6 +224,7 @@ fn marker(p: Point, s: f64) -> PathData {
/// Build the graph's children.
fn generate(d: &mut Document, g: &GraphSpec) -> Vec<Arc<Node>> {
let mark = |i: usize, series_fill: bool, stroke: Paint, width: f64| series_marks(g, i, series_fill, stroke, width);
let mut b = Gen { d, out: vec![] };
let r = g.rect;
let nser = g.rows.iter().map(Vec::len).max().unwrap_or(0).max(1);
@@ -231,7 +256,8 @@ fn generate(d: &mut Document, g: &GraphSpec) -> Vec<Arc<Node>> {
bp.line_to(centre + vectorcraft_geom::Vec2::new(a0.cos(), a0.sin()) * rad);
arc.to_cubic_beziers(0.1, |p1, p2, p| bp.curve_to(p1, p2, p));
bp.close_path();
let n = b.path(PathData::from_bezpath(&bp), series_paint(s), Paint::solid(Color::WHITE), 0.5);
let (fill, stroke, w) = mark(s, true, Paint::solid(Color::WHITE), 0.5);
let n = b.path(PathData::from_bezpath(&bp), fill, stroke, w);
items.push(n);
a0 += sweep;
}
@@ -268,9 +294,11 @@ fn generate(d: &mut Document, g: &GraphSpec) -> Vec<Arc<Node>> {
b.out.push(ax);
for (s, items) in series.iter_mut().enumerate() {
let pts: Vec<Point> = (0..ncat).map(|c| at(c, val(c, s))).collect();
items.push(b.path(polyline(&pts, true), Paint::None, series_paint(s), 1.0));
let (fill, stroke, w) = mark(s, false, default_series_paint(s), 1.0);
items.push(b.path(polyline(&pts, true), fill, stroke, w));
for p in pts {
items.push(b.path(marker(p, 4.0), series_paint(s), Paint::None, 0.0));
let (fill, stroke, w) = mark(s, true, Paint::None, 0.0);
items.push(b.path(marker(p, 4.0), fill, stroke, w));
}
}
}
@@ -359,11 +387,13 @@ fn generate(d: &mut Document, g: &GraphSpec) -> Vec<Arc<Node>> {
let pts: Vec<Point> =
(0..ncat).map(|c| Point::new(r.x0 + (val(c, s + 1) - xl) / (xh - xl) * r.width(), vpos(val(c, s)))).collect();
if g.connect_points && pts.len() > 1 {
series[si].push(b.path(polyline(&pts, false), Paint::None, series_paint(si), 1.0));
let (fill, stroke, w) = mark(si, false, default_series_paint(si), 1.0);
series[si].push(b.path(polyline(&pts, false), fill, stroke, w));
}
if g.mark_points {
for p in &pts {
series[si].push(b.path(marker(*p, 5.0), series_paint(si), Paint::None, 0.0));
let (fill, stroke, w) = mark(si, true, Paint::None, 0.0);
series[si].push(b.path(marker(*p, 5.0), fill, stroke, w));
}
}
}
@@ -385,7 +415,8 @@ fn generate(d: &mut Document, g: &GraphSpec) -> Vec<Arc<Node>> {
} else {
Rect::new(a, v0.min(v1), a + bar, v0.max(v1))
};
items.push(b.path(shapes::rectangle(rect), series_paint(s), Paint::None, 0.0));
let (fill, stroke, w) = mark(s, true, Paint::None, 0.0);
items.push(b.path(shapes::rectangle(rect), fill, stroke, w));
}
}
}
@@ -405,7 +436,8 @@ fn generate(d: &mut Document, g: &GraphSpec) -> Vec<Arc<Node>> {
} else {
Rect::new(a, v0.min(v1), a + bar, v0.max(v1))
};
items.push(b.path(shapes::rectangle(rect), series_paint(s), Paint::solid(Color::WHITE), 0.25));
let (fill, stroke, w) = mark(s, true, Paint::solid(Color::WHITE), 0.25);
items.push(b.path(shapes::rectangle(rect), fill, stroke, w));
}
}
}
@@ -413,11 +445,13 @@ fn generate(d: &mut Document, g: &GraphSpec) -> Vec<Arc<Node>> {
for (s, items) in series.iter_mut().enumerate() {
let pts: Vec<Point> = (0..ncat).map(|c| Point::new(cat_mid(c), vpos(val(c, s)))).collect();
if g.connect_points && pts.len() > 1 {
items.push(b.path(polyline(&pts, false), Paint::None, series_paint(s), 1.0));
let (fill, stroke, w) = mark(s, false, default_series_paint(s), 1.0);
items.push(b.path(polyline(&pts, false), fill, stroke, w));
}
if g.mark_points {
for p in &pts {
items.push(b.path(marker(*p, 5.0), series_paint(s), Paint::None, 0.0));
let (fill, stroke, w) = mark(s, true, Paint::None, 0.0);
items.push(b.path(marker(*p, 5.0), fill, stroke, w));
}
}
}
@@ -429,7 +463,8 @@ fn generate(d: &mut Document, g: &GraphSpec) -> Vec<Arc<Node>> {
let above: Vec<f64> = (0..ncat).map(|c| below[c] + val(c, s)).collect();
let mut pts: Vec<Point> = (0..ncat).map(|c| Point::new(cat_mid(c), vpos(above[c]))).collect();
pts.extend((0..ncat).rev().map(|c| Point::new(cat_mid(c), vpos(below[c]))));
items.push(b.path(polyline(&pts, true), series_paint(s), Paint::solid(Color::WHITE), 0.25));
let (fill, stroke, w) = mark(s, true, Paint::solid(Color::WHITE), 0.25);
items.push(b.path(polyline(&pts, true), fill, stroke, w));
below = above;
}
}
@@ -448,16 +483,18 @@ fn generate(d: &mut Document, g: &GraphSpec) -> Vec<Arc<Node>> {
continue;
}
let y = r.y0 + s as f64 * (LABEL_SIZE * 1.8);
items.push(b.path(shapes::rectangle(Rect::new(x, y, x + 8.0, y + 8.0)), series_paint(s), Paint::None, 0.0));
let (fill, stroke, w) = mark(s, true, Paint::None, 0.0);
items.push(b.path(shapes::rectangle(Rect::new(x, y, x + 8.0, y + 8.0)), fill, stroke, w));
labels.push(b.text(Point::new(x + 12.0, y + 7.5), &label, Justify::Left));
}
}
for (s, items) in series.into_iter().enumerate() {
if !items.is_empty() {
let name = g.series.get(s).cloned().filter(|n| !n.is_empty()).unwrap_or_else(|| format!("Series {}", s + 1));
let grp = b.group(&name, items);
b.out.push(grp);
if items.is_empty() {
continue;
}
let name = g.series.get(s).cloned().filter(|n| !n.is_empty()).unwrap_or_else(|| format!("Series {}", s + 1));
let grp = b.series(&name, s, items);
b.out.push(grp);
}
if !labels.is_empty() {
let grp = b.group("Legend", labels);
@@ -540,6 +577,91 @@ fn spec_of(s: &Session, id: NodeId) -> Result<GraphSpec> {
s.doc()?.doc.node(id).and_then(|n| n.graph.as_deref().cloned()).ok_or(EngineError::NoNode(id))
}
/// Where a node inside a graph's generated series art belongs: the graph, the series group and
/// the series index stored on that group.
#[derive(Clone, Copy)]
struct SeriesRef {
graph: NodeId,
group: NodeId,
index: usize,
}
/// Every node in a graph's series groups (the groups too), found in one pass over the document.
/// Axes, the legend and groups whose index is past the graph's series (the index comes from the
/// file) are left out.
fn series_members(doc: &Document) -> HashMap<NodeId, SeriesRef> {
let mut out = HashMap::new();
doc.walk(|n| {
let Some(spec) = n.graph.as_deref() else { return };
let count = spec.rows.iter().map(Vec::len).max().unwrap_or(0).max(1);
for group in n.children().into_iter().flatten() {
let Some(index) = group.series_index.and_then(|i| usize::try_from(i).ok()).filter(|i| *i < count) else { continue };
let r = SeriesRef { graph: n.id, group: group.id, index };
group.walk(&mut |m| {
out.insert(m.id, r);
});
}
});
out
}
/// Group Selection on a graph series targets its constituent marks and legend swatch, not a
/// group-level appearance which the generated art does not inherit. Other ids pass through.
pub(crate) fn paint_targets(doc: &Document, ids: &[NodeId]) -> Vec<NodeId> {
let members = series_members(doc);
if members.is_empty() {
return ids.to_vec();
}
let mut out = Vec::new();
for id in ids {
match members.get(id).filter(|r| r.group == *id).and_then(|_| doc.node(*id)) {
Some(group) => group.walk(&mut |m| {
if matches!(m.kind, NodeKind::Path { .. }) {
out.push(m.id);
}
}),
None => out.push(*id),
}
}
out.sort_unstable();
out.dedup();
out
}
/// Copy the paint just applied to generated series art into that series' fill or stroke. Called
/// inside the same document edit, so the visible paint and future regeneration undo together.
/// Gradients, patterns and swatch links are kept as [`Paint`], not reduced to a solid colour.
pub(crate) fn capture_series_paints(doc: &mut Document, ids: &[NodeId], fill: bool) {
let members = series_members(doc);
if members.is_empty() {
return;
}
let captures: Vec<_> = ids
.iter()
.filter_map(|id| {
let r = members.get(id)?;
let node = doc.node(*id)?;
let paint = node.appearance.paint_at(None, fill)?.clone();
let width = (!fill).then(|| node.appearance.stroke_width());
Some((r.graph, r.index, paint, width))
})
.collect();
for (graph, index, paint, width) in captures {
let Some(spec) = doc.node_mut(graph).and_then(|n| n.graph.as_deref_mut()) else { continue };
// `index` is below the graph's series count (`series_members`).
if spec.series_paints.len() <= index {
spec.series_paints.resize(index + 1, vectorcraft_doc::SeriesPaint::default());
}
let Some(slot) = spec.series_paints.get_mut(index) else { continue };
if fill {
slot.fill = Some(paint);
} else {
slot.stroke = Some(paint);
slot.stroke_width = width;
}
}
}
fn set_data(s: &mut Session, p: &Value) -> Result<Value> {
let id = target(s, p, "graph.setData")?;
let mut spec = spec_of(s, id)?;
@@ -592,7 +714,8 @@ fn set_type(s: &mut Session, p: &Value) -> Result<Value> {
#[cfg(test)]
mod tests {
use serde_json::json;
use vectorcraft_doc::NodeKind;
use vectorcraft_color::Paint;
use vectorcraft_doc::{GraphKind, GraphSpec, NodeKind};
use crate::{NodeId, Session};
@@ -609,6 +732,11 @@ mod tests {
n.children().unwrap().iter().find(|c| c.name.as_deref() == Some(name)).unwrap_or_else(|| panic!("no {name}"))
}
/// The generated group stored for series `index`, not a sibling that happens to share its name.
fn series(n: &vectorcraft_doc::Node, index: u32) -> &vectorcraft_doc::Node {
n.children().unwrap().iter().find(|c| c.series_index == Some(index)).unwrap_or_else(|| panic!("no series {index}"))
}
#[test]
fn every_graph_type_generates_series_groups() {
let mut s = Session::new();
@@ -662,6 +790,228 @@ mod tests {
assert!(matches!(n.kind, NodeKind::Group { .. }));
}
#[test]
fn group_selection_paint_becomes_the_series_colour_and_survives_regeneration() {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
for ty in GraphKind::ALL {
let id = graph(&mut s, ty.id());
let series_id = group(s.doc().unwrap().doc.node(id).unwrap(), "2024").id;
s.execute("paint.setFill", &json!({"ids": [series_id.0], "color": "#ff0000"})).unwrap();
let spec = s.doc().unwrap().doc.node(id).unwrap().graph.as_deref().unwrap().clone();
let restored: GraphSpec = serde_json::from_value(serde_json::to_value(&spec).unwrap()).unwrap();
assert_eq!(spec, restored);
let red = Paint::solid(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0));
assert_eq!(spec.series_paints.first().and_then(|p| p.fill.clone()), Some(red.clone()), "{ty:?}");
let selected_group = group(s.doc().unwrap().doc.node(id).unwrap(), "2024");
assert!(selected_group.children().unwrap().iter().all(|n| n.appearance.fill_paint() == red), "{ty:?}");
s.execute("graph.setData", &json!({"rows": [[2, 3], [4, 5]]})).unwrap();
s.execute("graph.setType", &json!({"type": "line"})).unwrap();
let spec = s.doc().unwrap().doc.node(id).unwrap().graph.as_deref().unwrap();
assert_eq!(spec.series_paints.first().and_then(|p| p.fill.clone()), Some(red.clone()), "{ty:?}");
let series = group(s.doc().unwrap().doc.node(id).unwrap(), "2024").children().unwrap();
assert!(series.iter().any(|n| n.appearance.fill_paint() == red), "{ty:?}");
}
}
#[test]
fn painting_a_series_is_one_undoable_edit() {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let id = graph(&mut s, "column");
let series_id = group(s.doc().unwrap().doc.node(id).unwrap(), "2024").id;
s.execute("paint.setFill", &json!({"ids": [series_id.0], "color": "#e8573f"})).unwrap();
assert_eq!(
s.doc().unwrap().doc.node(id).unwrap().graph.as_ref().unwrap().series_paints[0].fill.as_ref().and_then(Paint::color).unwrap().to_hex(),
"#e8573f"
);
s.execute("edit.undo", &json!({})).unwrap();
assert!(s.doc().unwrap().doc.node(id).unwrap().graph.as_ref().unwrap().series_paints.is_empty());
assert_eq!(
group(s.doc().unwrap().doc.node(id).unwrap(), "2024").children().unwrap()[0].appearance.fill_paint().color(),
Some(super::default_series_color(0))
);
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(
s.doc().unwrap().doc.node(id).unwrap().graph.as_ref().unwrap().series_paints[0].fill.as_ref().and_then(Paint::color).unwrap().to_hex(),
"#e8573f"
);
}
#[test]
fn painting_one_bar_sets_the_colour_used_by_the_whole_series_on_rebuild() {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let id = graph(&mut s, "column");
let bar = group(s.doc().unwrap().doc.node(id).unwrap(), "2024").children().unwrap()[0].id;
s.execute("paint.setFill", &json!({"ids": [bar.0], "color": "#12ab34"})).unwrap();
s.execute("graph.setData", &json!({"rows": [[1, 2], [3, 4]]})).unwrap();
let node = s.doc().unwrap().doc.node(id).unwrap();
let green = vectorcraft_color::Color::rgb(18.0 / 255.0, 171.0 / 255.0, 52.0 / 255.0);
assert_eq!(node.graph.as_ref().unwrap().series_paints[0].fill.as_ref().and_then(Paint::color), Some(green));
assert!(group(node, "2024").children().unwrap().iter().all(|n| n.appearance.fill_paint().color() == Some(green)));
}
/// A series index read from a file past the graph's series is not a series: painting its art
/// paints the art alone and stores nothing (no allocation sized by the file).
#[test]
fn a_series_index_past_the_graphs_series_is_ignored() {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let id = graph(&mut s, "column");
let series_id = group(s.doc().unwrap().doc.node(id).unwrap(), "2024").id;
s.edit("Junk", |d, _| {
d.node_mut(series_id).unwrap().series_index = Some(u32::MAX);
Ok(())
})
.unwrap();
let bar = group(s.doc().unwrap().doc.node(id).unwrap(), "2024").children().unwrap()[0].id;
s.execute("paint.setFill", &json!({"ids": [bar.0, series_id.0], "color": "#12ab34"})).unwrap();
let node = s.doc().unwrap().doc.node(id).unwrap();
assert!(node.graph.as_ref().unwrap().series_paints.is_empty());
assert_eq!(group(node, "2024").children().unwrap()[0].appearance.fill_paint().color().map(|c| c.to_hex()), Some("#12ab34".into()));
}
#[test]
fn painting_a_line_series_stroke_sets_its_persistent_colour() {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let id = graph(&mut s, "line");
let series_id = group(s.doc().unwrap().doc.node(id).unwrap(), "2024").id;
s.execute("paint.setStroke", &json!({"ids": [series_id.0], "color": "#3751c8"})).unwrap();
let blue = vectorcraft_color::Color::rgb(55.0 / 255.0, 81.0 / 255.0, 200.0 / 255.0);
assert_eq!(
s.doc().unwrap().doc.node(id).unwrap().graph.as_ref().unwrap().series_paints[0].stroke.as_ref().and_then(Paint::color),
Some(blue)
);
assert!(s.doc().unwrap().doc.node(id).unwrap().graph.as_ref().unwrap().series_paints[0].fill.is_none());
s.execute("graph.setData", &json!({"rows": [[1, 2], [3, 4]]})).unwrap();
assert!(
group(s.doc().unwrap().doc.node(id).unwrap(), "2024")
.children()
.unwrap()
.iter()
.any(|n| n.appearance.stroke_paint().color() == Some(blue))
);
}
#[test]
fn series_colours_survive_native_save_open_and_export() {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let id = graph(&mut s, "column");
let first = group(s.doc().unwrap().doc.node(id).unwrap(), "2024").id;
let second = group(s.doc().unwrap().doc.node(id).unwrap(), "2025").id;
s.execute("paint.setFill", &json!({"ids": [first.0], "color": "#f00"})).unwrap();
s.execute("paint.setFill", &json!({"ids": [second.0], "color": "#008080"})).unwrap();
let dir = vectorcraft_testkit::temp_dir("graph-palette");
let path = dir.join("palette.vectorcraft");
s.execute("document.save", &json!({"path": path})).unwrap();
s.execute("document.open", &json!({"path": path})).unwrap();
let paints = &s.doc().unwrap().doc.node(id).unwrap().graph.as_ref().unwrap().series_paints;
assert_eq!(paints.iter().map(|p| p.fill.as_ref().and_then(Paint::color).unwrap().to_hex()).collect::<Vec<_>>(), vec!["#ff0000", "#008080"]);
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("graph.setData", &json!({"id": id.0, "rows": [[3, 4, 5]]})).unwrap();
let n = s.doc().unwrap().doc.node(id).unwrap();
let swatch = group(n, "2025").children().unwrap().last().unwrap();
assert_eq!(swatch.appearance.fill_paint().color().unwrap().to_hex(), "#008080");
let third = group(n, "Series 3").children().unwrap().first().unwrap();
assert_eq!(third.appearance.fill_paint().color().unwrap().to_hex(), "#cccccc");
let svg = s.execute("document.serialize", &json!({"format": "svg"})).unwrap();
let svg = svg["text"].as_str().unwrap();
assert!(svg.contains("#ff0000") && svg.contains("#008080"));
let png = dir.join("palette.png");
s.execute("document.export", &json!({"format": "png", "path": png})).unwrap();
let pixels = image::open(&png).unwrap().to_rgba8();
assert!(pixels.pixels().any(|p| p.0 == [255, 0, 0, 255]));
assert!(pixels.pixels().any(|p| p.0 == [0, 128, 128, 255]));
let old: GraphSpec = serde_json::from_value(json!({"rows": [[1.0]]})).unwrap();
assert!(old.series_paints.is_empty(), "older files keep the greyscale default");
}
#[test]
fn a_column_stroke_stays_a_stroke_and_a_marker_fill_does_not_recolour_its_line() {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let id = graph(&mut s, "column");
let series_id = group(s.doc().unwrap().doc.node(id).unwrap(), "2024").id;
s.execute("paint.setStroke", &json!({"ids": [series_id.0], "color": "#0000ff"})).unwrap();
s.execute("graph.setData", &json!({"rows": [[1, 2], [3, 4]]})).unwrap();
let spec = s.doc().unwrap().doc.node(id).unwrap().graph.as_deref().unwrap().clone();
let blue = Paint::solid(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0));
assert_eq!(spec.series_paints[0].stroke, Some(blue.clone()));
assert!(spec.series_paints[0].fill.is_none());
let bar = &group(s.doc().unwrap().doc.node(id).unwrap(), "2024").children().unwrap()[0];
assert_eq!(bar.appearance.fill_paint().color(), Some(super::default_series_color(0)));
assert_eq!(bar.appearance.stroke_paint(), blue);
let id = graph(&mut s, "line");
let marker = group(s.doc().unwrap().doc.node(id).unwrap(), "2024").children().unwrap()[1].id;
s.execute("paint.setFill", &json!({"ids": [marker.0], "color": "#ff0000"})).unwrap();
s.execute("graph.setData", &json!({"rows": [[1, 2], [3, 4]]})).unwrap();
let spec = s.doc().unwrap().doc.node(id).unwrap().graph.as_deref().unwrap().clone();
assert!(spec.series_paints[0].stroke.is_none());
let series = group(s.doc().unwrap().doc.node(id).unwrap(), "2024").children().unwrap();
assert_eq!(series[0].appearance.stroke_paint().color(), Some(super::default_series_color(0)));
assert_eq!(series[1].appearance.fill_paint().color(), Some(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0)));
}
#[test]
fn a_gradient_fill_survives_regeneration() {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let id = graph(&mut s, "column");
let series_id = group(s.doc().unwrap().doc.node(id).unwrap(), "2024").id;
s.execute(
"paint.setFill",
&json!({"ids": [series_id.0], "gradient": {"kind": "linear", "stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]}}),
)
.unwrap();
s.execute("graph.setData", &json!({"rows": [[2, 3], [4, 5]]})).unwrap();
let spec = s.doc().unwrap().doc.node(id).unwrap().graph.as_deref().unwrap().clone();
assert!(matches!(spec.series_paints[0].fill, Some(Paint::Gradient(_))));
let bar = &group(s.doc().unwrap().doc.node(id).unwrap(), "2024").children().unwrap()[0];
assert!(matches!(bar.appearance.fill_paint(), Paint::Gradient(_)));
}
#[test]
fn a_series_named_legend_keeps_its_own_index_and_an_empty_series_is_omitted() {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let csv = ",Legend,Axes\nQ1,3,2\nQ2,5,4";
let id = NodeId(s.execute("graph.create", &json!({"type": "column", "x": 0, "y": 0, "csv": csv})).unwrap()["id"].as_u64().unwrap());
let legend_id = {
let n = s.doc().unwrap().doc.node(id).unwrap();
let legend = series(n, 0);
assert_eq!(legend.name.as_deref(), Some("Legend"));
assert!(n.children().unwrap().iter().any(|c| c.name.as_deref() == Some("Legend") && c.series_index.is_none()));
assert!(n.children().unwrap().iter().any(|c| c.name.as_deref() == Some("Axes") && c.series_index.is_none()));
legend.id
};
s.execute("paint.setFill", &json!({"ids": [legend_id.0], "color": "#ff0000"})).unwrap();
s.execute("graph.setData", &json!({"csv": csv})).unwrap();
let n = s.doc().unwrap().doc.node(id).unwrap();
assert_eq!(n.graph.as_ref().unwrap().series_paints[0].fill.as_ref().and_then(Paint::color).unwrap().to_hex(), "#ff0000");
assert!(n.graph.as_ref().unwrap().series_paints.get(1).is_none_or(|p| p.fill.is_none()));
assert_eq!(series(n, 0).children().unwrap()[0].appearance.fill_paint().color().unwrap().to_hex(), "#ff0000");
assert_eq!(series(n, 1).name.as_deref(), Some("Axes"));
assert_ne!(series(n, 1).children().unwrap()[0].appearance.fill_paint().color().unwrap().to_hex(), "#ff0000");
let id = graph(&mut s, "pie");
s.execute("graph.setType", &json!({"id": id.0, "legend": false})).unwrap();
s.execute("graph.setData", &json!({"id": id.0, "csv": ",Keep,Drop\nQ1,4,0\nQ2,2,0"})).unwrap();
let n = s.doc().unwrap().doc.node(id).unwrap();
assert!(n.children().unwrap().iter().any(|c| c.name.as_deref() == Some("Keep")));
assert!(n.children().unwrap().iter().all(|c| c.name.as_deref() != Some("Drop")));
let keep = group(n, "Keep").id;
s.execute("paint.setFill", &json!({"ids": [keep.0], "color": "#00ff00"})).unwrap();
s.execute("graph.setData", &json!({"id": id.0, "rows": [[8, 0], [1, 0]]})).unwrap();
let n = s.doc().unwrap().doc.node(id).unwrap();
assert_eq!(group(n, "Keep").series_index, Some(0));
assert_eq!(n.graph.as_ref().unwrap().series_paints[0].fill.as_ref().and_then(Paint::color).unwrap().to_hex(), "#00ff00");
assert!(n.children().unwrap().iter().all(|c| c.name.as_deref() != Some("Drop")));
}
#[test]
fn csv_parsing() {
let (s, c, r) = super::parse_csv("\t2024\t2025\nQ1\t1\t2\nQ2\t3\t4\n");
+11 -6
View File
@@ -135,7 +135,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Artboard Options…",
["Window", "Artboards"],
None,
"{index, name?, x?, y?, width?, height?, scaleArt?: bool (Scale Artwork with Artboard: resized, the artboard takes the art fully inside it (locked and hidden art only with lockedAndHidden?: bool, default prefs moveLockedWithArtboard) and its guides from its old rectangle onto the new one, each side by its own ratio; strokes/corners/patterns as object.scale)} → null, or with scaleArt {scaled: the art scaled}",
"{index, name?, x?, y?, width?, height?, moveArt?: bool (default false; a position-only change moves the contained art with its artboard), scaleArt?: bool (Scale Artwork with Artboard: resized, the artboard takes the art fully inside it (locked and hidden art only with lockedAndHidden?: bool, default prefs moveLockedWithArtboard) and its guides from its old rectangle onto the new one, each side by its own ratio; strokes/corners/patterns as object.scale)} → null, or with scaleArt {scaled: the art scaled}",
has_doc,
artboard_set
),
@@ -771,8 +771,13 @@ fn artboard_set(s: &mut Session, p: &Value) -> Result<Value> {
// Artboard gathers it) and its guides from the old rectangle onto the new one.
let scale_art = bool_or(p, "scaleArt", false);
let fit = if scale_art && resized { rect_map(was, now) } else { None };
let art = if fit.is_some() {
// Locked and hidden art too? Noted in the journal, so a replay scales the same objects
// Position fields honor Move Artwork independently of Scale Artwork. A resize still
// leaves the art alone unless scaling was requested. Fit-to-art callers keep the default.
let delta = now.origin() - was.origin();
let moving = !resized && bool_or(p, "moveArt", false) && delta != vectorcraft_geom::Vec2::ZERO;
let transform = fit.or_else(|| moving.then(|| Affine::translate(delta)));
let art = if transform.is_some() {
// Locked and hidden art too? Noted in the journal, so a replay transforms the same objects
// whatever the preference is then.
let all = bool_or(p, "lockedAndHidden", s.prefs.move_locked_with_artboard);
s.note_journal("lockedAndHidden", json!(all));
@@ -792,7 +797,7 @@ fn artboard_set(s: &mut Session, p: &Value) -> Result<Value> {
a.name = n.to_string();
}
let id = a.id;
if let Some(xf) = fit {
if let Some(xf) = transform {
d.map_artboard_guides(id, xf);
for id in &art {
if let Some(n) = d.node_mut(*id) {
@@ -801,14 +806,14 @@ fn artboard_set(s: &mut Session, p: &Value) -> Result<Value> {
}
} else if !resized {
// Moved (not resized), it takes its guides along.
d.move_artboard_guides(id, now.origin() - was.origin());
d.move_artboard_guides(id, delta);
}
Ok(())
})?;
if !scale_art {
return ok();
}
Ok(json!({ "scaled": art.iter().map(|i| i.0).collect::<Vec<_>>() }))
Ok(json!({ "scaled": if fit.is_some() { art.iter().map(|i| i.0).collect::<Vec<_>>() } else { vec![] } }))
}
/// The map taking artboard rectangle `from` onto `to`, each side scaled by its own ratio. None
+37 -23
View File
@@ -4,7 +4,7 @@ use serde_json::{Value, json};
use vectorcraft_color::{BlendMode, Color, GradientPaint, Paint};
use vectorcraft_doc::{Appearance, CharStyle, Document, Node, NodeId, NodeKind};
use super::appearance::{ItemTarget, appearance_targets, edit_items, item_target};
use super::appearance::{ItemTarget, appearance_targets, edit_items, edit_items_then, item_target};
use super::gradient::{item_paint_bounds, place_paint, place_run_paint, run_paint_mut, run_stroke_weight, unplaced};
use super::*;
use crate::{DocState, EngineError};
@@ -385,30 +385,44 @@ fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool) -> Result<V
s.fill_active = fill;
}
let item = item_target(s, p, cmd)?.of_kind(s, fill);
let ids = item.targets(s, p)?;
edit_items(s, &ids, item, cmd, if fill { "Fill Color" } else { "Stroke Color" }, fill, |n, index| {
if index.is_none()
&& let NodeKind::Text(t) = &mut n.kind
{
let (xf, lb) = (t.xf, t.local_bounds());
for r in &mut t.runs {
if !fill && !paint.is_none() {
run_stroke_weight(&mut r.style);
let selected = item.targets(s, p)?;
let ids = super::graph::paint_targets(&s.doc()?.doc, &selected);
let label = if fill { "Fill Color" } else { "Stroke Color" };
edit_items_then(
s,
&ids,
item,
cmd,
label,
fill,
|n, index| {
if index.is_none()
&& let NodeKind::Text(t) = &mut n.kind
{
let (xf, lb) = (t.xf, t.local_bounds());
for r in &mut t.runs {
if !fill && !paint.is_none() {
run_stroke_weight(&mut r.style);
}
let (cur, b) = run_paint_mut(r, !fill, lb);
*cur = place_run_paint(&paint, p, xf, b);
}
let (cur, b) = run_paint_mut(r, !fill, lb);
*cur = place_run_paint(&paint, p, xf, b);
return Ok(());
}
return Ok(());
}
// A missing top fill or stroke is created first: a new stroke's weight sizes the box its
// gradient fits.
if n.appearance.paint_at(index, fill).is_none() {
n.appearance.set_paint_at(index, fill, Paint::None);
}
let placed = place_paint(&paint, p, item_paint_bounds(n, index, fill));
n.appearance.set_paint_at(index, fill, placed);
Ok(())
})?;
// A missing top fill or stroke is created first: a new stroke's weight sizes the box its
// gradient fits.
if n.appearance.paint_at(index, fill).is_none() {
n.appearance.set_paint_at(index, fill, Paint::None);
}
let placed = place_paint(&paint, p, item_paint_bounds(n, index, fill));
n.appearance.set_paint_at(index, fill, placed);
Ok(())
},
|d, changed| {
super::graph::capture_series_paints(d, changed, fill);
Ok(())
},
)?;
s.remember_paint(&paint);
ok()
}
+30
View File
@@ -127,6 +127,36 @@ fn a_placed_link_records_the_file_and_the_document_saves_only_a_preview() {
assert_eq!(saved["images"][&im.key]["proxy"], Value::Null, "an embedded image shows it too");
}
/// A flat `w`×`h` Photoshop document of one colour (raw RGB, no layers).
fn psd(w: u32, h: u32, rgb: [u8; 3]) -> Vec<u8> {
let mut f = b"8BPS\0\x01\0\0\0\0\0\0\0\x03".to_vec();
f.extend(h.to_be_bytes());
f.extend(w.to_be_bytes());
f.extend([0, 8, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
for v in rgb {
f.extend(std::iter::repeat_n(v, (w * h) as usize));
}
f
}
/// #918: a Photoshop document placed linked shows its merged image, and updates when it changes.
#[test]
fn a_linked_photoshop_document_places_and_updates() {
let dir = Folder::new("psd");
let pic = dir.file("art/photo.psd");
write(&pic, &psd(600, 300, RED));
let mut s = session();
let id = place(&mut s, &pic);
let link = image(&s, id).link.unwrap();
assert_eq!(link.path, pic);
assert!(near(centre_colour(&s.doc().unwrap().doc), RED));
write(&pic, &psd(400, 400, BLUE));
assert_eq!(s.execute("links.update", &json!({})).unwrap(), json!({"updated": [id.0], "missing": []}));
let im = image(&s, id);
assert_eq!((im.width, im.height), (400, 400));
assert!(near(centre_colour(&s.doc().unwrap().doc), BLUE));
}
#[test]
fn the_relative_path_finds_the_file_after_the_folder_moves() {
let a = Folder::new("move-a");
+39 -5
View File
@@ -1,6 +1,7 @@
//! The Photoshop-style raster effects (Effect › Blur › Radial Blur and Smart Blur, Sharpen ›
//! Unsharp Mask): applied and edited as commands, listed in the catalogue, drawn on the canvas,
//! and written to PDF and SVG as images of the effected object.
//! The Photoshop-style raster effects (Effect › Blur › Radial Blur and Smart Blur, Pixelate ›
//! Color Halftone, Crystallize, Mezzotint and Pointillize, Sharpen › Unsharp Mask): applied and
//! edited as commands, listed in the catalogue, drawn on the canvas, and written to PDF and SVG
//! as images of the effected object.
use serde_json::{Value, json};
use vectorcraft_doc::NodeKind;
@@ -16,6 +17,14 @@ const EFFECTS: [(&str, &str); 3] = [
("sharpen.unsharpMask", r#"{"amount": 300, "radius": 3}"#),
];
/// Effect › Pixelate, at their defaults.
const PIXELATE: [(&str, &str); 4] =
[("pixelate.colorHalftone", "{}"), ("pixelate.crystallize", "{}"), ("pixelate.mezzotint", "{}"), ("pixelate.pointillize", "{}")];
/// Effect › Video (NTSC Colors leaves the striped art's legal colours as they are: see
/// `ntsc_colors_draws_saturated_yellow_safer`).
const VIDEO: [(&str, &str); 1] = [("video.deinterlace", r#"{"create": "interpolation"}"#)];
/// A group of a red square and a darker red stripe across it; returns the group's id.
fn striped() -> (Session, u64) {
let mut s = Session::new();
@@ -52,6 +61,12 @@ fn listed_applied_edited_and_undone() {
let menus: Vec<Value> =
EFFECTS.iter().map(|(id, _)| list["catalog"].as_array().unwrap().iter().find(|e| e["id"] == *id).unwrap()["menu"].clone()).collect();
assert_eq!(menus, [json!(["Effect", "Blur"]), json!(["Effect", "Blur"]), json!(["Effect", "Sharpen"])]);
for (group, menu) in [(PIXELATE.as_slice(), "Pixelate"), (VIDEO.as_slice(), "Video"), ([("video.ntscColors", "{}")].as_slice(), "Video")] {
for (id, _) in group {
let e = list["catalog"].as_array().unwrap().iter().find(|e| e["id"] == *id).unwrap_or_else(|| panic!("{id} listed"));
assert_eq!((&e["raster"], &e["menu"]), (&json!(true), &json!(["Effect", menu])), "{id}");
}
}
// Junk parameters are stored as given and read clamped; the canvas still draws.
for (id, _) in EFFECTS {
s.execute("effect.apply", &json!({"effect": id, "ids": [g], "params": {"amount": 1e308, "radius": -1e308, "threshold": "x", "quality": 7}}))
@@ -71,7 +86,7 @@ fn listed_applied_edited_and_undone() {
#[test]
fn each_effect_changes_the_canvas_and_draws_the_same_twice() {
for (id, params) in EFFECTS {
for (id, params) in EFFECTS.into_iter().chain(PIXELATE).chain(VIDEO) {
let (mut s, g) = striped();
let plain = render(&s);
let params: Value = serde_json::from_str(params).unwrap();
@@ -100,7 +115,7 @@ fn spin_blur_reaches_past_the_corners() {
#[test]
fn pdf_and_svg_write_the_effected_object_as_an_image() {
for (id, params) in EFFECTS {
for (id, params) in EFFECTS.into_iter().chain(PIXELATE).chain(VIDEO) {
let (mut s, g) = striped();
let params: Value = serde_json::from_str(params).unwrap();
s.execute("effect.apply", &json!({"effect": id, "ids": [g], "params": params})).unwrap();
@@ -131,3 +146,22 @@ fn expand_appearance_makes_an_image() {
s.execute("effect.expandAppearance", &json!({"ids": [g]})).unwrap();
assert!(matches!(s.doc().unwrap().doc.node(NodeId(g)).unwrap().kind, NodeKind::Image(_)));
}
/// Video › NTSC Colors on the canvas: a saturated yellow, too strong for a television signal, draws
/// less saturated; the effect is listed and applies without options.
#[test]
fn ntsc_colors_draws_saturated_yellow_safer() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
let id = s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap();
s.execute("paint.setFill", &json!({"color": "#ffff00", "ids": [id]})).unwrap();
s.execute("paint.setStroke", &json!({"none": true, "ids": [id]})).unwrap();
let before = render(&s);
s.execute("effect.apply", &json!({"effect": "video.ntscColors", "ids": [id]})).unwrap();
let after = render(&s);
let px = |r: &Rendered| r.pixel(100, 100);
let (a, b) = (px(&before), px(&after));
assert_eq!(&a[..3], &[255, 255, 0]);
assert!(b[2] > 20 && b[0] < 255 && b[3] == 255, "less saturated: {b:?}");
assert_eq!(after.pixels, render(&s).pixels, "deterministic");
}
+46
View File
@@ -371,6 +371,52 @@ fn artboard_set_props_scales_art_only_when_asked_and_resized() {
assert!(s.execute("artboard.setProps", &json!({"index": 9, "width": 10, "scaleArt": true})).is_err());
}
/// Move Artwork is independent of scaling and takes only fully contained art and board guides.
#[test]
fn coordinate_moves_honor_move_art_and_keep_resize_behavior() {
let mut s = session();
let inside = rect(&mut s, 100.0, 100.0, 200.0, 100.0);
s.execute("stroke.set", &json!({"weight": 4})).unwrap();
let partly = rect(&mut s, 700.0, 500.0, 200.0, 200.0);
s.execute("guide.add", &json!({"vertical": true, "pos": 400, "artboard": 0})).unwrap();
s.execute("guide.add", &json!({"vertical": true, "pos": 400})).unwrap();
let before = s.doc().unwrap().doc.clone();
for scale in [false, true] {
let out = s.execute("artboard.setProps", &json!({"index": 0, "x": 30, "y": -10, "moveArt": true, "scaleArt": scale})).unwrap();
assert_eq!(bounds(&s, inside), Rect::new(130.0, 90.0, 330.0, 190.0));
assert_eq!(bounds(&s, partly), Rect::new(700.0, 500.0, 900.0, 700.0));
assert_eq!(stroke_width(&s, inside), 4.0);
assert_eq!(guide_positions(&s), vec![430.0, 400.0]);
assert_eq!(out, if scale { json!({"scaled": []}) } else { Value::Null });
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(*s.doc().unwrap().doc, *before);
}
for p in [json!({"index": 0, "x": 30, "moveArt": false}), json!({"index": 0, "x": 30, "width": 400, "moveArt": true})] {
s.execute("artboard.setProps", &p).unwrap();
assert_eq!(bounds(&s, inside), Rect::new(100.0, 100.0, 300.0, 200.0));
s.execute("edit.undo", &json!({})).unwrap();
}
}
#[test]
fn coordinate_moves_journal_the_locked_art_preference() {
let mut s = session();
let locked = rect(&mut s, 100.0, 100.0, 200.0, 100.0);
s.execute("object.lock", &json!({})).unwrap();
s.execute("artboard.setProps", &json!({"index": 0, "x": 30, "moveArt": true})).unwrap();
assert_eq!(bounds(&s, locked), Rect::new(100.0, 100.0, 300.0, 200.0));
s.execute("edit.undo", &json!({})).unwrap();
s.prefs.move_locked_with_artboard = true;
s.execute("artboard.setProps", &json!({"index": 0, "x": 30, "moveArt": true})).unwrap();
assert_eq!(bounds(&s, locked), Rect::new(130.0, 100.0, 330.0, 200.0));
let (id, p) = s.journal.last().unwrap().clone();
assert_eq!(p["lockedAndHidden"], true);
s.execute("edit.undo", &json!({})).unwrap();
s.prefs.move_locked_with_artboard = false;
s.execute(&id, &p).unwrap();
assert_eq!(bounds(&s, locked), Rect::new(130.0, 100.0, 330.0, 200.0));
}
/// Locked and hidden art scales only with Move Locked and Hidden Artwork with Artboard, as it
/// moves only with it.
#[test]
+39
View File
@@ -145,3 +145,42 @@ fn several_spreads_preserve_each_board_and_leave_room_between_spreads() {
assert_eq!(loaded.doc.artboards[0].rect, Rect::new(0.0, 0.0, 100.0, 60.0));
assert_eq!(loaded.doc.artboards[1].rect, Rect::new(136.0, 0.0, 236.0, 60.0));
}
/// Coordinate fields use setProps rather than the drag tool's artboard.move command.
#[test]
fn coordinate_edits_move_imported_clipping_groups_and_undo_together() {
use serde_json::json;
use vectorcraft_engine::Session;
use vectorcraft_geom::Vec2;
for current in [false, true] {
let child = shape(20, "Oversized", false, false, [-10.0, -10.0, 110.0, 70.0], IDENTITY, vec![]);
let mut first = shape(10, "First", true, false, [0.0, 0.0, 100.0, 60.0], IDENTITY, vec![child]);
if current {
let F::Def(_, _, fields) = &mut first else { panic!() };
fields.retain(|(t, _)| *t != tag(b"ABEn"));
fields.push(field(b"phrp", F::Def(18, vec![tag(b"aprp")], vec![])));
}
let second = shape(30, "Second", true, false, [0.0, 0.0, 40.0, 60.0], [1.0, 0.0, 200.0, 0.0, 1.0, 0.0], vec![]);
let loaded = vectorcraft_engine::cmd::fileio::load("synthetic.af", &document(vec![vec![first, second]], 72.0, Method::Zstd)).unwrap();
let mut s = Session::new();
s.add_document(loaded.doc, None);
let before = s.doc().unwrap().doc.clone();
let first_bounds = find(&before.layers, "First").unwrap().geometric_bounds().unwrap();
let second_node = find(&before.layers, "Second").unwrap().clone();
let child_bounds = find(&before.layers, "First").unwrap().children().unwrap()[1].geometric_bounds().unwrap();
let delta = Vec2::new(13.0, -7.0);
s.execute("artboard.setProps", &json!({"index": 0, "x": 13, "y": -7, "moveArt": true})).unwrap();
let after = s.doc().unwrap().doc.clone();
assert_eq!(after.artboards[0].rect, before.artboards[0].rect + delta);
let first = find(&after.layers, "First").unwrap();
assert_eq!(first.geometric_bounds().unwrap(), first_bounds + delta);
assert_eq!(first.children().unwrap()[1].geometric_bounds().unwrap(), child_bounds + delta);
assert_eq!(find(&after.layers, "Second").unwrap(), &second_node);
assert_eq!(after.artboards[1], before.artboards[1]);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(*s.doc().unwrap().doc, *before);
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(*s.doc().unwrap().doc, *after);
}
}
+6
View File
@@ -278,6 +278,12 @@ fn structured_junk() {
("effect.apply", json!({"effect": "blur.radial", "params": {"amount": 1e308, "method": 5, "quality": "best"}})),
("effect.apply", json!({"effect": "blur.smart", "params": {"radius": 1e308, "threshold": -1e308, "quality": null}})),
("effect.apply", json!({"effect": "sharpen.unsharpMask", "params": {"amount": -1, "radius": "1e999", "threshold": 1e308}})),
("effect.apply", json!({"effect": "pixelate.colorHalftone", "params": {"maxRadius": 1e308, "channel1": "1e999", "channel4": null}})),
("effect.apply", json!({"effect": "pixelate.crystallize", "params": {"cellSize": -1e308}})),
("effect.apply", json!({"effect": "pixelate.mezzotint", "params": {"type": 5}})),
("effect.apply", json!({"effect": "pixelate.pointillize", "params": {"cellSize": "NaN"}})),
("effect.apply", json!({"effect": "video.deinterlace", "params": {"eliminate": 7, "create": ["x"]}})),
("effect.apply", json!({"effect": "video.ntscColors", "params": {"junk": 1e308}})),
("effect.apply", json!({"effect": "no.such.effect"})),
("effect.remove", json!({"index": 99})),
("effect.setParams", json!({"index": 0, "params": null})),
+15 -2
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`, `.ase`), graphic style (`.vcstyles`) and flattener preset
//! mutated raster images (Photoshop documents among them) 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
@@ -945,6 +945,19 @@ fn raster_samples() -> Vec<(&'static str, Vec<u8>)> {
out.push((name, b));
}
out[0].1 = vectorcraft_engine::cmd::fileio::ppi::with_png_resolution(&out[0].1, (300.0, 150.0));
// A layered PSD with transparency (as VectorCraft exports it), and a PackBits PSB by hand.
let mut s = rich_session();
let r = s.execute("document.export", &json!({"format": "psd", "ppi": 2})).unwrap();
out.push(("a.psd", vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap()));
let mut psb = b"8BPS\0\x02\0\0\0\0\0\0\0\x04\0\0\0\x02\0\0\0\x03\0\x08\0\x03".to_vec();
psb.extend([0; 8]);
psb.extend(10u64.to_be_bytes());
psb.extend(2u64.to_be_bytes());
psb.extend((-1i16).to_be_bytes());
psb.extend([0, 1]);
psb.extend((0..8).flat_map(|_| 2u32.to_be_bytes()));
psb.extend((0..8u8).flat_map(|v| [0xfe, v * 30]));
out.push(("a.psb", psb));
out
}
@@ -954,7 +967,7 @@ proptest! {
/// Mutated image headers (resolution metadata, chunk and segment lengths) never crash reading
/// their resolution or placing them.
#[test]
fn mutated_images_place_without_panics(which in 0usize..4, cut in 0usize..400, edits in prop::collection::vec((0usize..120, any::<u8>()), 0..12)) {
fn mutated_images_place_without_panics(which in 0usize..6, cut in 0usize..4000, edits in prop::collection::vec((0usize..120, any::<u8>()), 0..12)) {
let (name, mut bytes) = raster_samples().swap_remove(which);
for (at, b) in edits {
if let Some(x) = bytes.get_mut(at) {
+37 -9
View File
@@ -34,6 +34,9 @@ const MAX_PATH: usize = 1 << 20;
const MAX_DRAWN: usize = 1 << 24;
/// Samples taken of a shading function that isn't a plain interpolation.
const SHADING_SAMPLES: usize = 32;
/// Most bounds of a stitched linear function that become a gradient's stops: past it, the
/// function is sampled like any other (each stop evaluates the whole function).
const MAX_STITCH_STOPS: usize = 1024;
pub(super) const FAR_AWAY: &str = "objects far outside the page were left out";
pub(super) const TOO_MUCH: &str = "the file draws more than VectorCraft reads: the rest was left out";
@@ -1007,8 +1010,10 @@ impl Interp<'_> {
let domain = nums(get("Domain"));
let (d0, d1) = (domain.first().copied().unwrap_or(0.0), domain.get(1).copied().unwrap_or(1.0));
let f = get("Function").ok_or(PsError::Ps("undefined", "Function".into()))?;
// Where the colour changes: the ends, and the bounds of stitched linear functions.
let ts: Vec<f64> = match linear_points(&f) {
// Where the colour changes: the ends, and the bounds of stitched linear functions (unless
// there are too many).
let mut visits = 0;
let ts: Vec<f64> = match linear_points(&f, 0, &mut visits).filter(|p| p.len() <= MAX_STITCH_STOPS) {
Some(mut pts) => {
pts.retain(|t| (d0.min(d1)..=d0.max(d1)).contains(t));
pts.iter().map(|t| if d1 != d0 { (t - d0) / (d1 - d0) } else { 0.0 }).chain([0.0, 1.0]).collect()
@@ -1085,16 +1090,21 @@ impl Interp<'_> {
Ok(c0.iter().zip(&c1).map(|(a, b)| a + x * (b - a)).collect())
}
Some(3.0) => {
let fs = get("Functions").and_then(|o| o.items().map(|i| i.to_vec())).unwrap_or_default();
// Read the pieces through the borrow and clone only the one we recurse into: a
// `Functions` array of millions (shared, or reached again through a cycle) must
// not be copied on every call and at every live recursion level.
let functions = get("Functions");
let fs = functions.as_ref().and_then(Obj::items);
let n = fs.map_or(0, Shared::len);
let bounds = nums(get("Bounds"));
let encode = nums(get("Encode"));
let (lo, hi) = (domain.first().copied().unwrap_or(0.0), domain.get(1).copied().unwrap_or(1.0));
let k = bounds.iter().take_while(|b| t >= **b).count().min(fs.len().saturating_sub(1));
let k = bounds.iter().take_while(|b| t >= **b).count().min(n.saturating_sub(1));
let a = if k == 0 { lo } else { bounds.get(k - 1).copied().unwrap_or(lo) };
let b = bounds.get(k).copied().unwrap_or(hi);
let (e0, e1) = (encode.get(2 * k).copied().unwrap_or(0.0), encode.get(2 * k + 1).copied().unwrap_or(1.0));
let u = if b != a { e0 + (t - a) / (b - a) * (e1 - e0) } else { e0 };
let g = fs.get(k).cloned().ok_or(PsError::Ps("rangecheck", "Functions".into()))?;
let g = fs.and_then(|fs| fs.get(k)).ok_or(PsError::Ps("rangecheck", "Functions".into()))?;
self.eval(&g, &[u], depth + 1)
}
_ => {
@@ -1621,16 +1631,34 @@ fn is_mesh(sh: &DictRef) -> bool {
}
/// Where a stitched function of linear interpolations changes slope (its bounds), when it is
/// one; `None` for functions that must be sampled.
fn linear_points(f: &Obj) -> Option<Vec<f64>> {
/// one; `None` for functions that must be sampled. `depth` bounds the nesting the same way
/// [`Interp::eval`] does (`> 8`) and `visits` (shared by the whole recursion, incremented on
/// every call) bounds the total nodes looked at. Both are needed: the depth limit alone stops a
/// function that refers to itself in a cycle, but not one that fans out through shared children
/// (1025 references to a child a few levels deep is 1025^levels nodes without the visit cap). A
/// well-formed stitch of linear pieces is one level, at most `MAX_STITCH_STOPS + 1` pieces, so it
/// costs at most `MAX_STITCH_STOPS + 2` visits and is never cut off.
fn linear_points(f: &Obj, depth: u32, visits: &mut usize) -> Option<Vec<f64>> {
*visits += 1;
if depth > 8 || *visits > 2 * (MAX_STITCH_STOPS + 1) {
return None;
}
let Obj::Dict(d) = f else { return None };
let d = d.borrow();
let num = |k: &str| d.get(&Key::name(k)).and_then(Obj::as_num);
match num("FunctionType")? {
2.0 if num("N").unwrap_or(1.0) == 1.0 => Some(vec![]),
3.0 => {
let fs = d.get(&Key::name("Functions"))?.items()?.to_vec();
if !fs.iter().all(|g| linear_points(g).is_some_and(|p| p.is_empty())) {
let items = d.get(&Key::name("Functions"))?.items()?;
// More pieces than the stop cap allows: sample the function instead (tested before
// `to_vec`, so a huge `Functions` array is not copied only to be rejected). Each stop
// runs [`Interp::eval`], which reads one piece, so a short `Bounds` with a huge
// `Functions` would still be O(stops * Functions) to find each piece without this.
if items.len() > MAX_STITCH_STOPS + 1 {
return None;
}
let fs = items.to_vec();
if !fs.iter().all(|g| linear_points(g, depth + 1, visits).is_some_and(|p| p.is_empty())) {
return None;
}
d.get(&Key::name("Bounds"))?.items().map(|i| i.borrow().iter().filter_map(Obj::as_num).collect())
+93
View File
@@ -897,6 +897,99 @@ fn hostile_patterns_glyphs_and_shadings_end() {
assert_eq!(objects(&r.document).len(), 1);
}
/// The stops of the gradient `body` draws, after asserting it came in cleanly as one gradient.
fn stitch_stops(body: &str) -> Vec<f32> {
let r = read(body);
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
let o = objects(&r.document);
let [node] = o.as_slice() else { panic!("{o:?}") };
let Some(Paint::Gradient(g)) = fill(node) else { panic!("{node:?}") };
g.gradient.stops.iter().map(|s| s.offset).collect()
}
/// A gradient stitched from linear pieces keeps their bounds as its stops up to the cap, and is
/// sampled past it. The cap is on the pieces; a well-formed stitch has one more piece than bounds.
#[test]
fn gradients_stitched_from_linear_pieces_keep_or_sample_their_stops() {
// `bounds` interior bounds at i / (bounds + 1), with one linear piece more than that.
let stitched = |bounds: usize| {
let pieces = bounds + 1;
format!(
"/F << /FunctionType 2 /Domain [0 1] /C0 [0] /C1 [1] /N 1 >> def \
<< /ShadingType 2 /ColorSpace /DeviceGray /Coords [0 0 100 0] /Function << /FunctionType 3 /Domain [0 1] \
/Functions [ {pieces} {{ F }} repeat ] /Bounds [ 1 1 {bounds} {{ {pieces} div }} for ] >> >> shfill"
)
};
// A few pieces: the bounds are kept exactly as stops (three bounds -> five stops with the ends).
assert_eq!(stitch_stops(&stitched(3)), vec![0.0, 0.25, 0.5, 0.75, 1.0]);
// At the cap (1024 bounds, 1025 pieces) the 1024 bounds and the two ends are all kept.
assert_eq!(stitch_stops(&stitched(1024)).len(), 1026);
// One past it (1025 bounds, 1026 pieces) the function is sampled instead.
assert_eq!(stitch_stops(&stitched(1025)).len(), 33);
}
/// A malformed stitching function with a single piece but thousands of bounds is sampled, not
/// turned into thousands of stops. This is the one case the stop-count `.filter` catches on its
/// own: the one piece is under the Functions-length guard, so only the bound count is out of range.
#[test]
fn a_stitching_function_with_one_piece_but_many_bounds_is_sampled() {
let stops = stitch_stops(
"/F << /FunctionType 2 /Domain [0 1] /C0 [0] /C1 [1] /N 1 >> def \
<< /ShadingType 2 /ColorSpace /DeviceGray /Coords [0 0 100 0] /Function << /FunctionType 3 /Domain [0 1] \
/Functions [ F ] /Bounds [ 1 1 2000 { 2001 div } for ] >> >> shfill",
);
// Base keeps all 2000 bounds (2002 stops); the fix samples.
assert_eq!(stops.len(), 33);
}
/// A short `Bounds` with a `Functions` array one past the cap is sampled: without the length
/// guard each of the ~1000 stops would read through the whole array to find its piece.
#[test]
fn a_gradient_with_a_functions_array_past_the_cap_is_sampled() {
let stops = stitch_stops(
"/F << /FunctionType 2 /Domain [0 1] /C0 [0] /C1 [1] /N 1 >> def \
<< /ShadingType 2 /ColorSpace /DeviceGray /Coords [0 0 100 0] /Function << /FunctionType 3 /Domain [0 1] \
/Functions [ 1026 { F } repeat ] /Bounds [ 1 1 1000 { 1001 div } for ] >> >> shfill",
);
// Base keeps the 1000 bounds (1002 stops); the fix samples.
assert_eq!(stops.len(), 33);
}
/// A stitching function (type 3) whose `Functions` array holds the function itself must not
/// recurse without end: `linear_points` (depth- and visit-bounded) and `eval` (depth-bounded)
/// both stop, so the shading raises an error instead of overflowing the stack (an abort
/// `vectorcraft_engine::guard` can't catch, and on wasm there is no net at all).
#[test]
fn a_stitching_function_that_refers_to_itself_is_rejected_not_crashed() {
let r = read(
"0 0 10 10 rectfill \
/F 5 dict def F /FunctionType 3 put F /Domain [0 1] put F /Bounds [] put F /Encode [0 1] put F /Functions [ F ] put \
<< /ShadingType 2 /ColorSpace /DeviceGray /Coords [0 0 100 0] /Function F >> shfill",
);
// Not an abort: the reader stops at the error, keeps the rectangle drawn before it, and leaves
// the rest of the program unread (see `import`: what follows the error is left out).
assert_eq!(objects(&r.document).len(), 1);
assert!(r.warnings.iter().any(|w| w.contains("read up to an error") && w.contains("Function")), "{:?}", r.warnings);
}
/// A stitching function need not point at itself to blow up: a `Functions` array of 1025
/// references to a child that holds 1025 references to a child ... is a tree of 1025^levels nodes
/// though it is tiny in memory (the children are shared). The shared visit counter stops
/// `linear_points` after about 2 * (MAX_STITCH_STOPS + 1) nodes, so it is sampled at once instead
/// of being walked; on the unmodified reader this explores ~1025^3 nodes.
#[test]
fn a_deeply_shared_stitching_function_is_sampled_not_walked() {
// leaf (linear) <- mid2[1025 leaf] <- mid1[1025 mid2] <- top[1025 mid1] (1000 bounds).
let stops = stitch_stops(
"/leaf << /FunctionType 2 /Domain [0 1] /C0 [0] /C1 [1] /N 1 >> def \
/mid2 << /FunctionType 3 /Domain [0 1] /Bounds [] /Functions [ 1025 { leaf } repeat ] >> def \
/mid1 << /FunctionType 3 /Domain [0 1] /Bounds [] /Functions [ 1025 { mid2 } repeat ] >> def \
/top << /FunctionType 3 /Domain [0 1] /Bounds [ 1 1 1000 { 1001 div } for ] /Functions [ 1025 { mid1 } repeat ] >> def \
<< /ShadingType 2 /ColorSpace /DeviceGray /Coords [0 0 100 0] /Function top >> shfill",
);
assert_eq!(stops.len(), 33);
}
/// Executable strings and keys other than names (#474): `cvx` makes a string executable, and
/// running it runs its text (PLRM 3rd ed. §3.3.1, `cvx`, `exec`); `load` takes any key (§8.2).
/// A program closes its shading dictionaries with an executable string (`>>` at Level 2 and up,
+58 -1
View File
@@ -503,6 +503,46 @@ fn matching_face(
best.map(|(_, f)| f)
}
/// The characters a glyph no mapping names is looked for among (#811): those single-byte fonts
/// encode (ASCII, Latin-1, Latin Extended-A, general punctuation, the euro and trade mark signs,
/// the fi and fl ligatures).
const IDENTIFIABLE: [std::ops::RangeInclusive<u32>; 6] =
[0x21..=0x7E, 0xA1..=0x17F, 0x2010..=0x2044, 0x20AC..=0x20AC, 0x2122..=0x2122, 0xFB01..=0xFB02];
/// The character whose glyph in installed `face` draws `embedded` (a glyph outline in thousandths
/// of an em, y up): the first of [`IDENTIFIABLE`] with the same outline, point for point. A subset
/// font embedded without a character map still carries the font's own outlines, so a glyph whose
/// subset code names nothing is found this way. `None` when no glyph matches (another version of
/// the font, or a glyph that is no character), and for empty glyphs, which every space draws.
pub(crate) fn identify_glyph(face: &vectorcraft_text::FontFace, embedded: &BezPath) -> Option<char> {
if embedded.elements().is_empty() {
return None;
}
let k = 1000.0 / face.units_per_em();
// Installed outlines are y-down in font units.
let to_pdf = Affine::new([k, 0.0, 0.0, -k, 0.0, 0.0]);
let db = vectorcraft_text::FontDb::global();
IDENTIFIABLE.iter().cloned().flatten().filter_map(char::from_u32).find(|c| {
let gid = face.glyph_for(*c);
gid != 0 && same_shape(embedded, &(to_pdf * db.outline(face, gid).as_ref().clone()))
})
}
/// Do outlines `a` and `b` draw the same segments, every point within 2/1000 em (closing
/// commands aside)?
fn same_shape(a: &BezPath, b: &BezPath) -> bool {
let drawn = |p: &BezPath| p.elements().iter().filter(|e| !matches!(e, PathEl::ClosePath)).copied().collect::<Vec<_>>();
let (a, b) = (drawn(a), drawn(b));
let near = |p: kurbo::Point, q: kurbo::Point| (p - q).hypot() <= 2.0;
a.len() == b.len()
&& a.iter().zip(&b).all(|(x, y)| match (x, y) {
(PathEl::MoveTo(p), PathEl::MoveTo(q)) | (PathEl::LineTo(p), PathEl::LineTo(q)) => near(*p, *q),
(PathEl::QuadTo(p1, p2), PathEl::QuadTo(q1, q2)) => near(*p1, *q1) && near(*p2, *q2),
(PathEl::CurveTo(p1, p2, p3), PathEl::CurveTo(q1, q2, q3)) => near(*p1, *q1) && near(*p2, *q2) && near(*p3, *q3),
_ => false,
})
}
/// The character of glyph `text` when its outline can be compared with an installed font's: a
/// single character, and not CJK punctuation set vertically (its vertical form differs).
fn comparable(text: &str, vertical: bool) -> Option<char> {
@@ -666,6 +706,9 @@ struct Builder<'p> {
/// Font (cache key) → the installed face that draws its glyphs, decided from its first glyph
/// that can be compared ([`matching_face`]); `None`: its glyphs differ, so it stays outlines.
matched: HashMap<u128, Option<Arc<vectorcraft_text::FontFace>>>,
/// (Font, glyph) → the character its outline matches in the installed face, for glyphs no
/// mapping names ([`Builder::identified_char`]).
identified: HashMap<(u128, u32), Option<char>>,
/// Per font: the installed version its type names, when it isn't the one its family and style
/// resolve to (see `CharStyle::font_version`).
versions: HashMap<u128, Option<String>>,
@@ -817,6 +860,7 @@ impl<'p> Builder<'p> {
cid_text: HashMap::new(),
font_chars: HashMap::new(),
matched: HashMap::new(),
identified: HashMap::new(),
versions: HashMap::new(),
mask: None,
masked: vec![],
@@ -1286,6 +1330,17 @@ impl<'p> Builder<'p> {
/// The family and style of font `key` (drawing glyph `o`): the installed face of its PostScript
/// name, else the available family its name reads as; whether it is available.
/// The character of glyph `glyph` of font `key` that no mapping names, found by its outline in
/// the installed face of the font's name ([`identify_glyph`]); cached per glyph.
fn identified_char(&mut self, key: u128, glyph: u32, o: &hayro_interpret::font::OutlineGlyph) -> Option<char> {
if let Some(c) = self.identified.get(&(key, glyph)) {
return *c;
}
let c = self.font_name(key, o).face.and_then(|f| identify_glyph(&f, &o.outline()));
self.identified.insert((key, glyph), c);
c
}
fn font_name(&mut self, key: u128, o: &hayro_interpret::font::OutlineGlyph) -> FontInfo {
if let Some(n) = self.font_names.get(&key) {
return n.clone();
@@ -1345,7 +1400,9 @@ impl<'p> Builder<'p> {
.font_chars
.entry(key)
.or_insert_with(|| o.font_data().and_then(|d| font_chars(d.data.as_ref().as_ref())).map(Arc::new));
(chars.as_ref().and_then(|m| m.get(&glyph)).map(|c| BfString::Char(*c)), false)
let named = chars.as_ref().and_then(|m| m.get(&glyph)).copied();
// Still unnamed: the installed font may draw the same outline (#811).
(named.or_else(|| self.identified_char(key, glyph, o)).map(BfString::Char), false)
}
}
}
+24 -8
View File
@@ -248,17 +248,33 @@ fn digits_unnamed(text: &str) -> Vec<u8> {
out
}
/// #708: a glyph whose ToUnicode value is U+FFFD isn't type showing "�". This subset font has no
/// character map of its own, so the digits keep their outlines, drawn as the file draws them, and
/// a warning names the font.
/// #708, #811: a glyph whose ToUnicode value is U+FFFD isn't type showing "�". This subset font
/// has no character map of its own, but the font is installed: each digit is found by its outline
/// there, so the whole text stays one type object, with no outlines left behind.
#[test]
fn glyphs_mapped_to_the_replacement_character_keep_their_outlines() {
fn unnamed_glyphs_of_an_installed_font_are_found_by_their_outline() {
let bytes = digits_unnamed("Tel 02-12345");
let report = import_with_report(&bytes, &ImportOptions { text_as: TextAs::Text, ..Default::default() }).unwrap();
let all = texts(&report.document).concat();
assert!(!all.contains('\u{FFFD}') && all.contains("Tel"), "no replacement characters: {all:?}");
assert!(ink(&report.document).width() > 50.0, "the digits are outlines");
assert!(report.warnings.iter().any(|w| w.contains("U+FFFD")), "{:?}", report.warnings);
assert_eq!(texts(&report.document), ["Tel 02-12345"]);
let mut paths = 0;
report.document.walk(|n| paths += usize::from(matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })));
assert_eq!(paths, 0, "no outlines left: {:?}", report.warnings);
assert!(!report.warnings.iter().any(|w| w.contains("U+FFFD")), "{:?}", report.warnings);
}
/// #811: an outline is named only by a glyph that draws it exactly; one moved off its place, or an
/// empty glyph (which every space draws), stays unnamed and keeps its outlines.
#[test]
fn glyphs_are_named_only_by_an_exact_outline() {
let db = FontDb::global();
let face = db.face("Source Sans 3", "Regular").unwrap();
let k = 1000.0 / face.units_per_em();
let pdf_space = |c: char| Affine::new([k, 0.0, 0.0, -k, 0.0, 0.0]) * db.outline(&face, face.glyph_for(c)).as_ref().clone();
for c in ['R', 'a', '7', '&', 'é'] {
assert_eq!(crate::import::identify_glyph(&face, &pdf_space(c)), Some(c));
}
assert_eq!(crate::import::identify_glyph(&face, &(Affine::translate((100.0, 0.0)) * pdf_space('R'))), None);
assert_eq!(crate::import::identify_glyph(&face, &BezPath::new()), None);
}
/// #708: where the embedded font program has a character map, a glyph's character comes from it.
+9 -1
View File
@@ -595,7 +595,15 @@ impl Renderer {
off.flush();
let mut pm = vello_cpu::Pixmap::new(wu, hu);
off.render(&mut pm, &mut self.resources);
let space = effects::PixelSpace { to_doc, px, center: content.reach.center() };
let channels = match f.ink {
Ink::Cmy => effects::pixel::Channels::CmyPlane,
Ink::K => effects::pixel::Channels::KPlane,
Ink::Display if f.doc.color_mode == vectorcraft_doc::ColorMode::Cmyk => effects::pixel::Channels::Cmyk,
Ink::Display => effects::pixel::Channels::Rgb,
};
// De-Interlace's field lines: the rows of the document's raster grid (1 to 2400 ppi).
let ppi = Some(f.doc.raster_effects_ppi).filter(|v| v.is_finite()).unwrap_or(72.0).clamp(1.0, 2400.0);
let space = effects::PixelSpace { to_doc, px, center: content.reach.center(), channels, line: 72.0 / ppi };
let (wz, hz) = (wu as usize, hu as usize);
for fx in chain {
match fx {
+30
View File
@@ -574,6 +574,14 @@ impl Tool for DirectSelectionTool {
}
}
});
// Objects without anchors to pick (type, images, symbols…) are selected whole when
// the marquee touches them, as with the Selection tool (#927).
for id in vectorcraft_doc::hit::marquee(cx.doc, r, cx.isolation, true) {
let whole = cx.doc.node(id).is_some_and(|n| !matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }));
if whole && !sel.iter().any(|(s, _)| *s == id) {
sel.push((id, vec![]));
}
}
sel.retain(|(id, _)| cx.doc.is_editable(*id));
let items: Vec<Value> = sel.iter().map(|(id, v)| json!({"id": id.0, "anchors": anchors_json(v)})).collect();
vec![Action::Exec("select.anchorsMany".into(), json!({"items": items, "mode": if toggle { "toggle" } else { "set" }}))]
@@ -838,6 +846,28 @@ mod tests {
let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 250.0, 150.0));
assert_eq!(a, vec![Action::Exec("select.anchorsMany".into(), json!({"items": [{"id": id.0, "anchors": [[0, 1]]}], "mode": "set"}))]);
}
/// #927: a marquee across type selects the type object whole, beside the anchors it holds.
#[test]
fn marquee_selects_type_it_touches() {
// The rectangle at (100, 100)–(200, 200) and area type at (300, 300).
let (d, text) = doc_with_area_type();
let rect = d.layers[0].children().and_then(|c| c.first()).map(|n| n.id).unwrap();
let s = Selection::default();
let p = paint();
let cx = cx(&d, &s, &p);
let mut t = DirectSelectionTool::new(false);
// From empty canvas across the type to inside the rectangle (its bottom-right corner).
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 450.0, 450.0));
t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 150.0, 150.0));
let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 150.0, 150.0));
let items = json!([{"id": rect.0, "anchors": [[0, 2]]}, {"id": text.0, "anchors": []}]);
assert_eq!(a, vec![Action::Exec("select.anchorsMany".into(), json!({"items": items, "mode": "set"}))]);
// Away from the type, only anchors.
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 150.0, 50.0));
let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 250.0, 150.0));
assert_eq!(a, vec![Action::Exec("select.anchorsMany".into(), json!({"items": [{"id": rect.0, "anchors": [[0, 1]]}], "mode": "set"}))]);
}
/// Shift-drag a marquee: the anchors inside toggle (#483), with Group Selection too.
#[test]
fn shift_marquee_toggles_anchors() {
@@ -35,5 +35,6 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
p[k] = json!(d.f64(k, 0.0));
}
}
p["moveArt"] = json!(crate::panels::artboards::move_art(app));
run_and_close(app, "artboard.setProps", p)
}
+3
View File
@@ -159,6 +159,9 @@ fn choices(effect: &str, key: &str) -> Option<form::Choices> {
("blur.radial", "method") => Some(&[("Spin", "spin"), ("Zoom", "zoom")]),
("blur.radial", "quality") => Some(&[("Draft", "draft"), ("Good", "good"), ("Best", "best")]),
("blur.smart", "quality") => Some(&[("Low", "low"), ("Medium", "medium"), ("High", "high")]),
("pixelate.mezzotint", "type") => Some(&vectorcraft_effects::pixel::MEZZOTINT_TYPES),
("video.deinterlace", "eliminate") => Some(&[("Odd Fields", "odd"), ("Even Fields", "even")]),
("video.deinterlace", "create") => Some(&[("Duplication", "duplication"), ("Interpolation", "interpolation")]),
("path.offsetPath", "joins") => Some(&[("Miter", "miter"), ("Round", "round"), ("Bevel", "bevel")]),
("distort.roughen" | "distort.zigZag", "points") => Some(&[("Smooth", "smooth"), ("Corner", "corner")]),
_ => None,
+6
View File
@@ -350,8 +350,14 @@ pub(super) fn humanize(k: &str) -> String {
"Sy" => "Vertical %".into(),
"Radius1" => "Radius 1".into(),
"Radius2" => "Radius 2".into(),
"Max Radius" => "Max. Radius:".into(),
"Channel1" => "Channel 1:".into(),
"Channel2" => "Channel 2:".into(),
"Channel3" => "Channel 3:".into(),
"Channel4" => "Channel 4:".into(),
"Include Cmy Blacks" => "Include Blacks with CMY:".into(),
"Align To Path" => "Align to Path:".into(),
"Create" => "Create New Fields by:".into(),
_ => format!("{s}:"),
}
}
+89 -1
View File
@@ -2,7 +2,8 @@
//! (`links.relink`), and with Apply to All the other missing files are looked for by name in its
//! folder; Ignore keeps the images showing their saved preview, and with Apply to All ignores the
//! rest. Afterwards, with Preferences › Update Links: Ask When Modified, the modified links are
//! offered for update (`links.update`).
//! offered for update (`links.update`). Files changed while the app was in the background are
//! checked when its window comes back to the front ([`after_focus`]).
//!
//! Fields: `missing` (`[{name, path, ids}]`, the one asked about first), `modified` (the ids of
//! images whose file was modified), `applyToAll`, `path` (the replacement file; picked when empty)
@@ -74,6 +75,39 @@ fn ask_update(app: &mut VectorcraftApp, ids: Vec<Value>) {
super::confirm::ask(app, tl!("Update Modified Links"), &detail, "links.update", json!({ "ids": ids }));
}
/// A linked file as last seen: its path, and its size and modification time when it exists.
pub(crate) type FileStamp = (String, Option<(u64, Option<std::time::SystemTime>)>);
/// The window came back to the front (#925): linked files of the active document changed
/// meanwhile are read again with Update Links: Automatically, offered for update with Ask When
/// Modified (once per change of a file), and left to the Links panel with Manually. Nothing is
/// asked while a dialog is open.
pub fn after_focus(app: &mut VectorcraftApp) {
if cfg!(target_arch = "wasm32") || app.session.prefs.update_links == "manually" || app.ui.dialog.is_some() || app.session.active().is_none() {
return;
}
let Ok(r) = app.session.execute("links.check", &json!({})) else { return };
let rows: Vec<Value> = r["links"].as_array().into_iter().flatten().filter(|l| l["status"] == "modified").cloned().collect();
if rows.is_empty() {
return;
}
if app.session.prefs.update_links == "automatically" {
// A failure shows in the status bar, as the Links panel's Update Link does.
let _ = app.run("links.update", json!({ "ids": ids(&rows) }));
return;
}
// The file each link reads (one found elsewhere after a move), its size and when it was last
// changed (two changes can share a time on file systems that keep it coarsely).
let stamp = |l: &Value| -> FileStamp {
let path = l["found"].as_str().or(l["path"].as_str()).unwrap_or_default().to_string();
let meta = std::fs::metadata(&path).ok();
let at = meta.as_ref().map(|m| (m.len(), m.modified().ok()));
(path, at)
};
let new: Vec<Value> = rows.into_iter().filter(|l| app.links_asked.insert(stamp(l))).collect();
ask_update(app, ids(&new));
}
fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
let t = Tokens::get(ui.ctx());
let missing = d.fields.get("missing").and_then(Value::as_array).map_or(&[][..], Vec::as_slice);
@@ -262,4 +296,58 @@ mod tests {
assert!(app.ui.dialog.is_none());
let _ = std::fs::remove_dir_all(dir);
}
/// #925: a linked file changed while the app was in the background follows Update Links when
/// the window comes back to the front.
#[test]
fn a_link_changed_in_the_background_follows_update_links_on_focus() {
let dir = std::env::temp_dir().join(format!("vectorcraft-focus-links-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.services.read = Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string())));
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
let pic = dir.join("a.png");
// Each version a different size, so no two share a length and modification time.
let mut version = 0;
let mut change = || {
version += 1;
let mut out = vec![];
image::RgbaImage::from_pixel(100 + version, 50, image::Rgba([40 * version as u8, 0, 0, 255]))
.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png)
.unwrap();
std::fs::write(&pic, out).unwrap();
};
change();
app.run("file.place", json!({"path": pic.to_string_lossy()})).unwrap();
let modified = |app: &mut VectorcraftApp| app.run("links.check", json!({})).unwrap()["modified"].as_u64().unwrap();
// The window coming to the front asks for the check.
let mut raw = egui::RawInput { events: vec![egui::Event::WindowFocused(true)], ..Default::default() };
app.raw_input_hook(&mut raw);
assert!(app.links_check);
// Ask When Modified (the default): asked once per change.
change();
after_focus(&mut app);
let d = app.ui.dialog.take().expect("asks");
assert_eq!(d.str("__command"), "links.update");
after_focus(&mut app);
assert!(app.ui.dialog.is_none(), "not twice for the same change");
change();
after_focus(&mut app);
assert!(app.ui.dialog.is_some(), "a new change asks again");
super::super::confirm(&mut app).unwrap();
assert_eq!(modified(&mut app), 0);
// Automatically: read again without asking.
app.run("prefs.set", json!({"key": "updateLinks", "value": "automatically"})).unwrap();
change();
after_focus(&mut app);
assert!(app.ui.dialog.is_none());
assert_eq!(modified(&mut app), 0);
// Manually: left to the Links panel.
app.run("prefs.set", json!({"key": "updateLinks", "value": "manually"})).unwrap();
change();
after_focus(&mut app);
assert!(app.ui.dialog.is_none());
assert_eq!(modified(&mut app), 1);
let _ = std::fs::remove_dir_all(dir);
}
}
+39 -1
View File
@@ -168,7 +168,15 @@ fn effect_preview_is_kept_as_one_undo_step() {
#[test]
fn raster_filter_dialogs_preview_and_apply() {
for (effect, key, value) in [("blur.radial", "method", "zoom"), ("blur.smart", "quality", "high"), ("sharpen.unsharpMask", "amount", "120")] {
for (effect, key, value) in [
("blur.radial", "method", "zoom"),
("blur.smart", "quality", "high"),
("sharpen.unsharpMask", "amount", "120"),
("pixelate.colorHalftone", "channel1", "30"),
("pixelate.crystallize", "cellSize", "20"),
("pixelate.mezzotint", "type", "longLines"),
("pixelate.pointillize", "cellSize", "12"),
] {
let mut app = app();
let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap();
app.run("select.all", json!({})).unwrap();
@@ -188,6 +196,13 @@ fn raster_filter_dialogs_preview_and_apply() {
let ranks: Vec<usize> = ["radius", "threshold", "quality"].iter().map(|k| super::effect::doc_rank(doc, k)).collect();
assert!(ranks.windows(2).all(|w| w[0] < w[1]), "{ranks:?}");
assert_eq!(super::effect::doc_rank(doc, "nope"), usize::MAX);
let doc = vectorcraft_effects::effect_info("pixelate.colorHalftone").unwrap().params;
let ranks: Vec<usize> = ["maxRadius", "channel1", "channel2", "channel3", "channel4"].iter().map(|k| super::effect::doc_rank(doc, k)).collect();
assert!(ranks.windows(2).all(|w| w[0] < w[1]) && ranks[4] < usize::MAX, "{ranks:?}");
// Labels as the dialogs show them.
assert_eq!(super::form::humanize("maxRadius"), "Max. Radius:");
assert_eq!(super::form::humanize("channel3"), "Channel 3:");
assert_eq!(super::form::humanize("cellSize"), "Cell Size:");
}
#[test]
@@ -446,3 +461,26 @@ fn the_transform_effect_dialog_has_its_controls_previews_them_and_shows_them_aga
let text = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx()));
assert!(text.lines().any(|l| l == "Reference Point"), "{text}");
}
#[test]
fn artboard_options_position_moves_art_only_with_the_tool_option_on() {
for move_art in [false, true] {
let mut app = app();
let id = app.run("shape.rectangle", json!({"x": 10, "y": 20, "width": 30, "height": 40})).unwrap()["id"].as_u64().unwrap();
app.select_tool("artboard");
app.session.set_tool_option("moveArt", &json!(move_art));
crate::dialogs::artboard_options::open(&mut app).unwrap();
app.ui.dialog.as_mut().unwrap().fields.insert("x".into(), json!(50));
// Draw the dialog once and confirm through its registry, as the OK button does.
frame(&mut app, Default::default());
let before = app.session.doc().unwrap().doc.clone();
super::confirm(&mut app).unwrap();
assert_eq!(app.session.doc().unwrap().doc.artboards[0].rect.x0, 50.0);
assert_eq!(
app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().geometric_bounds().unwrap().x0,
if move_art { 60.0 } else { 10.0 }
);
app.run("edit.undo", json!({})).unwrap();
assert_eq!(*app.session.doc().unwrap().doc, *before);
}
}
+8
View File
@@ -652,3 +652,11 @@
Smart Blur… Chytré rozostření…
Sharpen Zostření
Unsharp Mask… Maska rozostření…
Pixelate Pixelizace
Color Halftone… Barevný polotón…
Crystallize… Krystalizace…
Mezzotint… Mezzotinta…
Pointillize… Pointilismus…
Video Video
De-Interlace… Odstranit prokládání…
NTSC Colors Barvy NTSC
Can't render this file because it contains an unexpected character in line 2 and column 73.
+45
View File
@@ -21,6 +21,31 @@
Smart Blur… Desenfoque inteligente…
Sharpen Enfocar
Unsharp Mask… Máscara de enfoque…
Pixelate Pixelizar
Color Halftone… Semitono de color…
Crystallize… Cristalizar…
Mezzotint… Grabado a media tinta…
Pointillize… Puntillismo…
Color Halftone Semitono de color
Crystallize Cristalizar
Mezzotint Grabado a media tinta
Pointillize Puntillismo
Max. Radius Radio máx.
Channel 1 Canal 1
Channel 2 Canal 2
Channel 3 Canal 3
Channel 4 Canal 4
Cell Size Tamaño de celda
Fine Dots Puntos finos
Medium Dots Puntos medios
Grainy Dots Puntos granulados
Coarse Dots Puntos gruesos
Short Lines Líneas cortas
Medium Lines Líneas medias
Long Lines Líneas largas
Short Strokes Trazos cortos
Medium Strokes Trazos medios
Long Strokes Trazos largos
Radial Blur Desenfoque radial
Smart Blur Desenfoque inteligente
Unsharp Mask Máscara de enfoque
@@ -3836,3 +3861,23 @@ axis Both Ambos
@msg automation path rejected: cannot resolve {path}: {e} ruta de automatización rechazada: no se puede resolver {path}: {e}
@msg automation path rejected: parent traversal below a folder that doesn't exist: {path} ruta de automatización rechazada: sube (..) desde una carpeta que no existe: {path}
@msg automation path rejected: reserved device names are not allowed: {path} ruta de automatización rechazada: no se permiten nombres de dispositivo reservados: {path}
@msg Multichannel PSD files can't be read: save it in RGB, CMYK or Grayscale mode Los archivos PSD en modo Multicanal no se pueden leer: guárdalo en modo RGB, CMYK o Escala de grises
@msg not a PSD file no es un documento PSD
@msg the PSD file has an unknown colour mode ({m}) el archivo PSD tiene un modo de color desconocido ({m})
@msg the PSD file's image data uses an unknown compression ({m}) los datos de imagen del archivo PSD usan una compresión desconocida ({m})
@msg the PSD image is too large to read ({_1} × {_2} pixels) la imagen PSD es demasiado grande para leerla ({_1} × {_2} píxeles)
@msg zipped 32-bit PSD image data with prediction can't be read no se pueden leer datos de imagen PSD de 32 bits comprimidos en ZIP con predicción
@msg {depth}-bit PSD files in this colour mode can't be read los archivos PSD de {depth} bits en este modo de color no se pueden leer
@msg the PSD file is cut short el archivo PSD está incompleto
@msg the PSD file's header is damaged el encabezado del archivo PSD está dañado
@msg the PSD file's image data can't be read: {e} no se pueden leer los datos de imagen del archivo PSD: {e}
Video Video
De-Interlace… Desentrelazar…
De-Interlace Desentrelazar
NTSC Colors Colores NTSC
Eliminate Eliminar
Create New Fields by Crear campos nuevos por
Odd Fields Campos impares
Even Fields Campos pares
Duplication Duplicación
Interpolation Interpolación
Can't render this file because it contains an unexpected character in line 2 and column 73.
+45
View File
@@ -22,6 +22,31 @@
Smart Blur… Flou intelligent…
Sharpen Netteté
Unsharp Mask… Masque de netteté…
Pixelate Pixellisation
Color Halftone… Demi-teintes couleur…
Crystallize… Cristalliser…
Mezzotint… Manière noire…
Pointillize… Pointillisme…
Color Halftone Demi-teintes couleur
Crystallize Cristalliser
Mezzotint Manière noire
Pointillize Pointillisme
Max. Radius Rayon max.
Channel 1 Couche 1
Channel 2 Couche 2
Channel 3 Couche 3
Channel 4 Couche 4
Cell Size Taille de cellule
Fine Dots Points fins
Medium Dots Points moyens
Grainy Dots Points granuleux
Coarse Dots Gros points
Short Lines Lignes courtes
Medium Lines Lignes moyennes
Long Lines Lignes longues
Short Strokes Traits courts
Medium Strokes Traits moyens
Long Strokes Traits longs
Radial Blur Flou radial
Smart Blur Flou intelligent
Unsharp Mask Masque de netteté
@@ -3847,3 +3872,23 @@ axis Both Les deux
@msg automation path rejected: cannot resolve {path}: {e} chemin d’automatisation refusé : impossible de résoudre {path} : {e}
@msg automation path rejected: parent traversal below a folder that doesn't exist: {path} chemin d’automatisation refusé : remonte (..) depuis un dossier qui n’existe pas : {path}
@msg automation path rejected: reserved device names are not allowed: {path} chemin d’automatisation refusé : les noms de périphériques réservés ne sont pas autorisés : {path}
@msg Multichannel PSD files can't be read: save it in RGB, CMYK or Grayscale mode Les fichiers PSD en mode Multicouche ne peuvent pas être lus : enregistrez-le en mode RVB, CMJN ou Niveaux de gris
@msg not a PSD file ce n'est pas un document PSD
@msg the PSD file has an unknown colour mode ({m}) le fichier PSD a un mode colorimétrique inconnu ({m})
@msg the PSD file's image data uses an unknown compression ({m}) les données d'image du fichier PSD utilisent une compression inconnue ({m})
@msg the PSD image is too large to read ({_1} × {_2} pixels) l'image PSD est trop grande pour être lue ({_1} × {_2} pixels)
@msg zipped 32-bit PSD image data with prediction can't be read les données d'image PSD 32 bits compressées en ZIP avec prédiction ne peuvent pas être lues
@msg {depth}-bit PSD files in this colour mode can't be read les fichiers PSD {depth} bits dans ce mode colorimétrique ne peuvent pas être lus
@msg the PSD file is cut short le fichier PSD est tronqué
@msg the PSD file's header is damaged l'en-tête du fichier PSD est endommagé
@msg the PSD file's image data can't be read: {e} les données d'image du fichier PSD ne peuvent pas être lues : {e}
Video Vidéo
De-Interlace… Désentrelacement…
De-Interlace Désentrelacement
NTSC Colors Couleurs NTSC
Eliminate Supprimer
Create New Fields by Créer des trames par
Odd Fields Trames impaires
Even Fields Trames paires
Duplication Duplication
Interpolation Interpolation
Can't render this file because it contains an unexpected character in line 2 and column 73.
+45
View File
@@ -21,6 +21,31 @@
Smart Blur… Sfocatura intelligente…
Sharpen Nitidezza
Unsharp Mask… Maschera di contrasto…
Pixelate Effetto pixel
Color Halftone… Mezzetinte colore…
Crystallize… Cristallizza…
Mezzotint… Mezzatinta…
Pointillize… Puntinismo…
Color Halftone Mezzetinte colore
Crystallize Cristallizza
Mezzotint Mezzatinta
Pointillize Puntinismo
Max. Radius Raggio max.
Channel 1 Canale 1
Channel 2 Canale 2
Channel 3 Canale 3
Channel 4 Canale 4
Cell Size Dimensione cella
Fine Dots Punti fini
Medium Dots Punti medi
Grainy Dots Punti granulosi
Coarse Dots Punti grossi
Short Lines Linee corte
Medium Lines Linee medie
Long Lines Linee lunghe
Short Strokes Tratti corti
Medium Strokes Tratti medi
Long Strokes Tratti lunghi
Radial Blur Sfocatura radiale
Smart Blur Sfocatura intelligente
Unsharp Mask Maschera di contrasto
@@ -3836,3 +3861,23 @@ axis Both Entrambi
@msg automation path rejected: cannot resolve {path}: {e} percorso di automazione rifiutato: impossibile risolvere {path}: {e}
@msg automation path rejected: parent traversal below a folder that doesn't exist: {path} percorso di automazione rifiutato: risale (..) da una cartella che non esiste: {path}
@msg automation path rejected: reserved device names are not allowed: {path} percorso di automazione rifiutato: i nomi di dispositivo riservati non sono consentiti: {path}
@msg Multichannel PSD files can't be read: save it in RGB, CMYK or Grayscale mode I file PSD in modalità Multicanale non possono essere letti: salvalo in modalità RGB, CMYK o Scala di grigio
@msg not a PSD file non è un documento PSD
@msg the PSD file has an unknown colour mode ({m}) il file PSD ha un metodo colore sconosciuto ({m})
@msg the PSD file's image data uses an unknown compression ({m}) i dati immagine del file PSD usano una compressione sconosciuta ({m})
@msg the PSD image is too large to read ({_1} × {_2} pixels) l'immagine PSD è troppo grande per essere letta ({_1} × {_2} pixel)
@msg zipped 32-bit PSD image data with prediction can't be read i dati immagine PSD a 32 bit compressi ZIP con previsione non possono essere letti
@msg {depth}-bit PSD files in this colour mode can't be read i file PSD a {depth} bit in questo metodo colore non possono essere letti
@msg the PSD file is cut short il file PSD è troncato
@msg the PSD file's header is damaged l'intestazione del file PSD è danneggiata
@msg the PSD file's image data can't be read: {e} i dati immagine del file PSD non possono essere letti: {e}
Video Video
De-Interlace… Deinterlaccia…
De-Interlace Deinterlaccia
NTSC Colors Colori NTSC
Eliminate Elimina
Create New Fields by Crea nuovi campi per
Odd Fields Campi dispari
Even Fields Campi pari
Duplication Duplicazione
Interpolation Interpolazione
Can't render this file because it contains an unexpected character in line 2 and column 73.
+45
View File
@@ -3217,6 +3217,31 @@ theme Appearance 外観
Smart Blur… ぼかし (詳細)…
Sharpen シャープ
Unsharp Mask… アンシャープマスク…
Pixelate ピクセレート
Color Halftone… カラーハーフトーン…
Crystallize… 結晶化…
Mezzotint… メゾティント…
Pointillize… 点描…
Color Halftone カラーハーフトーン
Crystallize 結晶化
Mezzotint メゾティント
Pointillize 点描
Max. Radius 最大半径
Channel 1 チャンネル 1
Channel 2 チャンネル 2
Channel 3 チャンネル 3
Channel 4 チャンネル 4
Cell Size セルの大きさ
Fine Dots 細かい点
Medium Dots 中程度の点
Grainy Dots 粒状の点
Coarse Dots 粗い点
Short Lines 短い線
Medium Lines 中程度の線
Long Lines 長い線
Short Strokes 短いストローク
Medium Strokes 中程度のストローク
Long Strokes 長いストローク
Radial Blur ぼかし (放射状)
Smart Blur ぼかし (詳細)
Unsharp Mask アンシャープマスク
@@ -3828,3 +3853,23 @@ theme Appearance 外観
@msg automation path rejected: cannot resolve {path}: {e} 自動化のパスを拒否しました: {path} を解決できません: {e}
@msg automation path rejected: parent traversal below a folder that doesn't exist: {path} 自動化のパスを拒否しました: 存在しないフォルダーから上の階層 (..) へ移動しています: {path}
@msg automation path rejected: reserved device names are not allowed: {path} 自動化のパスを拒否しました: 予約済みのデバイス名は使用できません: {path}
@msg Multichannel PSD files can't be read: save it in RGB, CMYK or Grayscale mode マルチチャンネルの PSD ファイルは読み込めません:RGB、CMYK またはグレースケールモードで保存してください
@msg not a PSD file PSD ドキュメントではありません
@msg the PSD file has an unknown colour mode ({m}) PSD ファイルのカラーモードが不明です({m})
@msg the PSD file's image data uses an unknown compression ({m}) PSD ファイルの画像データの圧縮方式が不明です({m})
@msg the PSD image is too large to read ({_1} × {_2} pixels) PSD 画像が大きすぎて読み込めません({_1} × {_2} ピクセル)
@msg zipped 32-bit PSD image data with prediction can't be read 予測付き ZIP 圧縮の 32 bit PSD 画像データは読み込めません
@msg {depth}-bit PSD files in this colour mode can't be read このカラーモードの {depth} bit PSD ファイルは読み込めません
@msg the PSD file is cut short PSD ファイルが途中で切れています
@msg the PSD file's header is damaged PSD ファイルのヘッダーが破損しています
@msg the PSD file's image data can't be read: {e} PSD ファイルの画像データを読み込めません:{e}
Video ビデオ
De-Interlace… インターレース解除…
De-Interlace インターレース解除
NTSC Colors NTSC カラー
Eliminate 削除
Create New Fields by 新規フィールドの作成
Odd Fields 奇数フィールド
Even Fields 偶数フィールド
Duplication 複製
Interpolation 補間
Can't render this file because it contains an unexpected character in line 2 and column 73.
+8
View File
@@ -2713,3 +2713,11 @@
Smart Blur… Desfoque Inteligente…
Sharpen Nitidez
Unsharp Mask… Máscara de Nitidez…
Pixelate Pixelizar
Color Halftone… Meio-Tom Colorido…
Crystallize… Cristalizar…
Mezzotint… Meia-Tinta…
Pointillize… Pontilhar…
Video Vídeo
De-Interlace… Desentrelaçar…
NTSC Colors Cores NTSC
Can't render this file because it contains an unexpected character in line 6 and column 47.
+45
View File
@@ -19,6 +19,31 @@
Smart Blur… Умное размытие…
Sharpen Резкость
Unsharp Mask… Нерезкая маска…
Pixelate Пикселизация
Color Halftone… Цветные полутона…
Crystallize… Кристаллизация…
Mezzotint… Меццо-тинто…
Pointillize… Пуантилизм…
Color Halftone Цветные полутона
Crystallize Кристаллизация
Mezzotint Меццо-тинто
Pointillize Пуантилизм
Max. Radius Макс. радиус
Channel 1 Канал 1
Channel 2 Канал 2
Channel 3 Канал 3
Channel 4 Канал 4
Cell Size Размер ячейки
Fine Dots Мелкие точки
Medium Dots Средние точки
Grainy Dots Зернистые точки
Coarse Dots Крупные точки
Short Lines Короткие линии
Medium Lines Средние линии
Long Lines Длинные линии
Short Strokes Короткие штрихи
Medium Strokes Средние штрихи
Long Strokes Длинные штрихи
Radial Blur Радиальное размытие
Smart Blur Умное размытие
Unsharp Mask Нерезкая маска
@@ -3834,3 +3859,23 @@ axis Both Оба
@msg automation path rejected: cannot resolve {path}: {e} путь автоматизации отклонён: не удаётся определить {path}: {e}
@msg automation path rejected: parent traversal below a folder that doesn't exist: {path} путь автоматизации отклонён: переход вверх (..) из несуществующей папки: {path}
@msg automation path rejected: reserved device names are not allowed: {path} путь автоматизации отклонён: зарезервированные имена устройств недопустимы: {path}
@msg Multichannel PSD files can't be read: save it in RGB, CMYK or Grayscale mode Файлы PSD в режиме «Многоканальный» не читаются: сохраните его в режиме RGB, CMYK или «Градации серого»
@msg not a PSD file это не документ PSD
@msg the PSD file has an unknown colour mode ({m}) у файла PSD неизвестный цветовой режим ({m})
@msg the PSD file's image data uses an unknown compression ({m}) данные изображения файла PSD используют неизвестное сжатие ({m})
@msg the PSD image is too large to read ({_1} × {_2} pixels) изображение PSD слишком велико для чтения ({_1} × {_2} пикс.)
@msg zipped 32-bit PSD image data with prediction can't be read 32-битные данные изображения PSD со сжатием ZIP с предсказанием не читаются
@msg {depth}-bit PSD files in this colour mode can't be read {depth}-битные файлы PSD в этом цветовом режиме не читаются
@msg the PSD file is cut short файл PSD обрезан
@msg the PSD file's header is damaged заголовок файла PSD повреждён
@msg the PSD file's image data can't be read: {e} не удаётся прочитать данные изображения файла PSD: {e}
Video Видео
De-Interlace… Устранение чересстрочности…
De-Interlace Устранение чересстрочности
NTSC Colors Цвета NTSC
Eliminate Удалить
Create New Fields by Создать новые поля
Odd Fields Нечётные поля
Even Fields Чётные поля
Duplication Дублированием
Interpolation Интерполяцией
Can't render this file because it contains an unexpected character in line 2 and column 73.
+45
View File
@@ -20,6 +20,31 @@
Smart Blur… Розумне розмиття…
Sharpen Різкість
Unsharp Mask… Нерізка маска…
Pixelate Пікселізація
Color Halftone… Кольорові півтони…
Crystallize… Кристалізація…
Mezzotint… Меццо-тинто…
Pointillize… Пуантилізм…
Color Halftone Кольорові півтони
Crystallize Кристалізація
Mezzotint Меццо-тинто
Pointillize Пуантилізм
Max. Radius Макс. радіус
Channel 1 Канал 1
Channel 2 Канал 2
Channel 3 Канал 3
Channel 4 Канал 4
Cell Size Розмір комірки
Fine Dots Дрібні точки
Medium Dots Середні точки
Grainy Dots Зернисті точки
Coarse Dots Великі точки
Short Lines Короткі лінії
Medium Lines Середні лінії
Long Lines Довгі лінії
Short Strokes Короткі штрихи
Medium Strokes Середні штрихи
Long Strokes Довгі штрихи
Radial Blur Радіальне розмиття
Smart Blur Розумне розмиття
Unsharp Mask Нерізка маска
@@ -3819,3 +3844,23 @@ axis Both Обидві
@msg automation path rejected: cannot resolve {path}: {e} шлях автоматизації відхилено: не вдається визначити {path}: {e}
@msg automation path rejected: parent traversal below a folder that doesn't exist: {path} шлях автоматизації відхилено: перехід угору (..) з папки, якої не існує: {path}
@msg automation path rejected: reserved device names are not allowed: {path} шлях автоматизації відхилено: зарезервовані імена пристроїв не дозволені: {path}
@msg Multichannel PSD files can't be read: save it in RGB, CMYK or Grayscale mode Файли PSD у режимі «Багатоканальний» не читаються: збережіть його в режимі RGB, CMYK або «Відтінки сірого»
@msg not a PSD file це не документ PSD
@msg the PSD file has an unknown colour mode ({m}) файл PSD має невідомий колірний режим ({m})
@msg the PSD file's image data uses an unknown compression ({m}) дані зображення файлу PSD використовують невідоме стиснення ({m})
@msg the PSD image is too large to read ({_1} × {_2} pixels) зображення PSD завелике для читання ({_1} × {_2} пікс.)
@msg zipped 32-bit PSD image data with prediction can't be read 32-бітні дані зображення PSD зі стисненням ZIP із передбаченням не читаються
@msg {depth}-bit PSD files in this colour mode can't be read {depth}-бітні файли PSD у цьому колірному режимі не читаються
@msg the PSD file is cut short файл PSD обрізаний
@msg the PSD file's header is damaged заголовок файлу PSD пошкоджено
@msg the PSD file's image data can't be read: {e} не вдається прочитати дані зображення файлу PSD: {e}
Video Відео
De-Interlace… Усунення черезрядковості…
De-Interlace Усунення черезрядковості
NTSC Colors Кольори NTSC
Eliminate Вилучити
Create New Fields by Створити нові поля
Odd Fields Непарні поля
Even Fields Парні поля
Duplication Дублюванням
Interpolation Інтерполяцією
Can't render this file because it contains an unexpected character in line 659 and column 40.
+35
View File
@@ -3468,6 +3468,31 @@ axis Both 两者
Smart Blur… 智能模糊…
Sharpen 锐化
Unsharp Mask… 反锐化遮罩…
Pixelate 像素化
Color Halftone… 彩色半调…
Crystallize… 晶格化…
Mezzotint… 铜版雕刻…
Pointillize… 点彩…
Color Halftone 彩色半调
Crystallize 晶格化
Mezzotint 铜版雕刻
Pointillize 点彩
Max. Radius 最大半径
Channel 1 色版 1
Channel 2 色版 2
Channel 3 色版 3
Channel 4 色版 4
Cell Size 单元格大小
Fine Dots 细点
Medium Dots 中等点
Grainy Dots 颗粒点
Coarse Dots 粗点
Short Lines 短线
Medium Lines 中等线
Long Lines 长线
Short Strokes 短笔画
Medium Strokes 中等笔画
Long Strokes 长笔画
Radial Blur 径向模糊
Smart Blur 智能模糊
Unsharp Mask 反锐化遮罩
@@ -3479,3 +3504,13 @@ axis Both 两者
Draft 草稿
Good 良好
Best 最佳
Video 视频
De-Interlace… 逐行…
De-Interlace 逐行
NTSC Colors NTSC 颜色
Eliminate 消除
Create New Fields by 创建新场方式
Odd Fields 奇数场
Even Fields 偶数场
Duplication 复制
Interpolation 插值
Can't render this file because it contains an unexpected character in line 2 and column 73.
+35
View File
@@ -3246,6 +3246,31 @@ axis Both 兩者
Smart Blur… 智慧型模糊…
Sharpen 銳利化
Unsharp Mask… 反銳利化遮罩…
Pixelate 像素化
Color Halftone… 彩色半色調…
Crystallize… 結晶化…
Mezzotint… 網線銅版…
Pointillize… 點描…
Color Halftone 彩色半色調
Crystallize 結晶化
Mezzotint 網線銅版
Pointillize 點描
Max. Radius 最大半徑
Channel 1 色版 1
Channel 2 色版 2
Channel 3 色版 3
Channel 4 色版 4
Cell Size 單元大小
Fine Dots 細點
Medium Dots 中等點
Grainy Dots 顆粒點
Coarse Dots 粗點
Short Lines 短線
Medium Lines 中等線
Long Lines 長線
Short Strokes 短筆畫
Medium Strokes 中等筆畫
Long Strokes 長筆畫
Radial Blur 放射狀模糊
Smart Blur 智慧型模糊
Unsharp Mask 反銳利化遮罩
@@ -3257,3 +3282,13 @@ axis Both 兩者
Draft 草稿
Good 良好
Best 最佳
Video 視訊
De-Interlace… 反交錯…
De-Interlace 反交錯
NTSC Colors NTSC 色彩
Eliminate 消除
Create New Fields by 建立新圖場以
Odd Fields 奇數圖場
Even Fields 偶數圖場
Duplication 複製
Interpolation 內插
Can't render this file because it contains an unexpected character in line 6 and column 47.
+15 -1
View File
@@ -371,6 +371,12 @@ pub struct VectorcraftApp {
/// The look for fonts installed or removed while the app was in the background, running
/// ([`Self::refresh_installed_fonts`]): whether they were.
font_check: Option<std::sync::mpsc::Receiver<bool>>,
/// The window came back to the front: check the active document's linked files next frame
/// ([`dialogs::missing_links::after_focus`]).
pub(crate) links_check: bool,
/// The changed linked files already offered for update (path, size and modification time), so
/// coming back to the window doesn't ask about the same change twice.
pub(crate) links_asked: std::collections::HashSet<dialogs::missing_links::FileStamp>,
/// Keyboard pastes of something other than text (see [`shortcuts::PasteChord`]).
pub(crate) paste_chord: shortcuts::PasteChord,
/// Saves and exports running in the background (Preferences → File Handling).
@@ -468,6 +474,8 @@ impl VectorcraftApp {
clipboard_probe: None,
picks: picks::Picks::default(),
font_check: None,
links_check: false,
links_asked: Default::default(),
paste_chord: Default::default(),
background: Default::default(),
recovery: Default::default(),
@@ -881,6 +889,9 @@ impl VectorcraftApp {
self.system_paste = wanted && self.system_clipboard_pasteable();
}
self.poll_font_check(ctx);
if std::mem::take(&mut self.links_check) {
dialogs::missing_links::after_focus(self);
}
picks::poll(self, ctx);
background::poll(self);
if !self.background.jobs.is_empty() {
@@ -1014,7 +1025,10 @@ impl VectorcraftApp {
match e {
egui::Event::ModifiersChanged(m) => self.host_modifiers = *m,
egui::Event::WindowFocused(false) => self.host_modifiers = egui::Modifiers::NONE,
egui::Event::WindowFocused(true) => self.refresh_installed_fonts(),
egui::Event::WindowFocused(true) => {
self.refresh_installed_fonts();
self.links_check = true;
}
_ => {}
}
}
+2 -1
View File
@@ -3305,7 +3305,8 @@ fn font_items(english_names: bool) -> Vec<Item> {
/// The raster effects' submenus of the Effect menu (the Photoshop-style effects, below the
/// vector effects): (submenu, the catalogue's menu path of its effects).
const RASTER_MENUS: [(&str, &[&str]); 2] = [("Blur", &["Effect", "Blur"]), ("Sharpen", &["Effect", "Sharpen"])];
const RASTER_MENUS: [(&str, &[&str]); 4] =
[("Blur", &["Effect", "Blur"]), ("Pixelate", &["Effect", "Pixelate"]), ("Sharpen", &["Effect", "Sharpen"]), ("Video", &["Effect", "Video"])];
/// The Effect menu, built from the effects catalogue (vector effects), plus raster effects.
fn effect_menu() -> Vec<Item> {
+5
View File
@@ -30,6 +30,11 @@ pub(crate) fn scale_art(app: &VectorcraftApp) -> bool {
app.session.tool_id() == "artboard" && app.session.tool_options()["scaleArt"].as_bool().unwrap_or(false)
}
/// Whether position edits take their art along, matching the Artboard tool's move option.
pub(crate) fn move_art(app: &VectorcraftApp) -> bool {
app.session.tool_id() == "artboard" && app.session.tool_options()["moveArt"].as_bool().unwrap_or(true)
}
/// The active artboard (of `n`).
pub(crate) fn selected(app: &VectorcraftApp, n: usize) -> usize {
app.view().map_or(0, |v| v.artboard).min(n.saturating_sub(1))
+39 -13
View File
@@ -95,6 +95,43 @@ fn dragged_stops(origin: &[GradientStop], i: usize, offset: f32, copy: bool, ove
// ---------- shared edits ----------
/// The Type row: Linear, Radial and Freeform for the paint behind the active proxy (one of them
/// lit when it is a gradient). The Gradient panel's and the Properties panel's.
pub(crate) fn type_row(app: &mut VectorcraftApp, ui: &mut Ui) {
let kind = current(app).map(|g| g.gradient.kind);
ui.horizontal(|ui| {
widgets::dim_label(ui, tl!("Type:"));
for (k, icon, tip) in [
(GradientKind::Linear, "dc-grad-linear", tl!("Linear Gradient")),
(GradientKind::Radial, "dc-grad-radial", tl!("Radial Gradient")),
(GradientKind::Freeform, "dc-grad-freeform", tl!("Freeform Gradient")),
] {
if widgets::icon_button(ui, icon, tip, kind == Some(k), 24.0).clicked() {
edit(app, json!({"kind": k.label().to_lowercase()}), Live::Released);
}
}
});
}
/// Set how the Gradient tool adds the points of the freeform gradient behind the active proxy.
fn set_draw_mode(app: &mut VectorcraftApp, mode: FreeformMode) {
edit(app, json!({ "mode": mode.label().to_lowercase() }), Live::Released);
}
/// The Properties panel's Draw row for a freeform gradient: Points and Lines as radio buttons.
pub(crate) fn draw_radios(app: &mut VectorcraftApp, ui: &mut Ui) {
let Some(g) = current(app).filter(|g| g.gradient.kind == GradientKind::Freeform) else { return };
let mode = shown_points(&g).mode;
ui.horizontal(|ui| {
widgets::dim_label(ui, tl!("Draw:"));
for (m, label) in [(FreeformMode::Points, tl!("Points")), (FreeformMode::Lines, tl!("Lines"))] {
if widgets::radio(ui, label, mode == m, true) && mode != m {
set_draw_mode(app, m);
}
}
});
}
/// The gradient behind the active proxy.
fn current(app: &VectorcraftApp) -> Option<GradientPaint> {
match active_paint(app) {
@@ -184,18 +221,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
}
ui.add_space(4.0);
ui.vertical(|ui| {
ui.horizontal(|ui| {
widgets::dim_label(ui, tl!("Type:"));
for (k, icon, tip) in [
(GradientKind::Linear, "dc-grad-linear", tl!("Linear Gradient")),
(GradientKind::Radial, "dc-grad-radial", tl!("Radial Gradient")),
(GradientKind::Freeform, "dc-grad-freeform", tl!("Freeform Gradient")),
] {
if widgets::icon_button(ui, icon, tip, is_grad && kind == k, 24.0).clicked() {
edit(app, json!({"kind": k.label().to_lowercase()}), Live::Released);
}
}
});
type_row(app, ui);
if widgets::flat_button(ui, tl!("Edit Gradient"), 96.0).clicked() {
app.select_tool("gradient");
}
@@ -297,7 +323,7 @@ fn freeform_section(app: &mut VectorcraftApp, ui: &mut Ui, g: &GradientPaint) {
(FreeformMode::Lines, "spline", tl!("Lines: clicks add points joined by a line")),
] {
if widgets::icon_button(ui, icon, tip, mode == m, 24.0).clicked() && mode != m {
edit(app, json!({ "mode": m.label().to_lowercase() }), Live::Released);
set_draw_mode(app, m);
}
}
});
+74 -2
View File
@@ -40,6 +40,13 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
}
transform_section(app, ui);
divider(ui);
// The Gradient tool: the gradient's type and, for a freeform one, how clicks add points (#921).
if app.session.tool_id() == "gradient" {
section_header(ui, tl!("Gradient"));
super::gradient::type_row(app, ui);
super::gradient::draw_radios(app, ui);
divider(ui);
}
let is_image = n_sel == 1 && matches!(first.as_ref().map(|n| &n.kind), Some(NodeKind::Image(_)));
if is_image {
image_section(app, ui);
@@ -195,6 +202,7 @@ fn artboard_sections(app: &mut VectorcraftApp, ui: &mut Ui) {
let n = app.session.active().map_or(0, |d| d.doc.artboards.len());
let i = super::artboards::selected(app, n);
let scale_art = super::artboards::scale_art(app);
let move_art = super::artboards::move_art(app);
if let Some(ab) = app.session.active().and_then(|d| d.doc.artboards.get(i)).cloned() {
// Its name as it is (names are never translated).
ui.label(egui::RichText::new(&ab.name).size(13.0).color(Tokens::get(ui.ctx()).text));
@@ -207,7 +215,7 @@ fn artboard_sections(app: &mut VectorcraftApp, ui: &mut Ui) {
for (label, key, v) in [(l1, k1, v1), (l2, k2, v2)] {
dim_label(ui, label);
if let Some(v) = widgets::num_field(ui, ("ab", key, row), Some(v), units, fw) {
app.run("artboard.setProps", json!({"index": i, key: v, "scaleArt": scale_art})).ok();
app.run("artboard.setProps", json!({"index": i, key: v, "scaleArt": scale_art, "moveArt": move_art})).ok();
}
}
ui.end_row();
@@ -536,8 +544,12 @@ mod tests {
/// One frame of the panel with `events` → the texts painted, with their rects.
fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec<Event>) -> Vec<(String, Rect)> {
panel_frame(app, ctx, events, show)
}
fn panel_frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec<Event>, draw: fn(&mut VectorcraftApp, &mut Ui)) -> Vec<(String, Rect)> {
let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(300.0, 700.0))), events, ..Default::default() };
let mut out = ctx.run_ui(raw, |ui| show(app, ui));
let mut out = ctx.run_ui(raw, |ui| draw(app, ui));
out.textures_delta.clear();
out.shapes
.iter()
@@ -558,6 +570,31 @@ mod tests {
frame(app, ctx, vec![b(false)]);
}
/// #921: with the Gradient tool, a Gradient section: the type, and for a freeform gradient
/// Draw as Points or Lines radio buttons.
#[test]
fn the_gradient_tool_shows_the_gradient_type_and_draw() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 200, "height": 100})).unwrap();
let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap()["id"].as_u64().unwrap();
app.run("paint.setFill", json!({"gradient": {}})).unwrap();
let ctx = egui::Context::default();
let has = |texts: &[(String, Rect)], s: &str| texts.iter().any(|(t, _)| t == s);
let texts = frame(&mut app, &ctx, vec![]);
assert!(!has(&texts, "Gradient"), "only with the Gradient tool");
app.select_tool("gradient");
let texts = frame(&mut app, &ctx, vec![]);
assert!(has(&texts, "Gradient") && has(&texts, "Type:") && !has(&texts, "Draw:"), "{texts:?}");
app.run("paint.editGradient", json!({"kind": "freeform"})).unwrap();
frame(&mut app, &ctx, vec![]);
let texts = frame(&mut app, &ctx, vec![]);
assert!(has(&texts, "Draw:") && has(&texts, "Points") && has(&texts, "Lines"), "{texts:?}");
click(&mut app, &ctx, &texts, "Lines");
let fill = app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().appearance.fill_paint();
let vectorcraft_color::Paint::Gradient(g) = fill else { panic!("{fill:?}") };
assert_eq!(super::super::gradient::shown_points(&g).mode, vectorcraft_color::FreeformMode::Lines);
}
/// #696: the number fields are all as wide: the Transform fields, the rotation, the corner
/// radius, Opacity and the stroke weight.
#[test]
@@ -586,6 +623,41 @@ mod tests {
assert!(widths.iter().all(|w| (w - widths[0]).abs() < 1.0), "X, rotation, corner radius, opacity: {widths:?}");
}
/// Both panels forward the Move Artwork toggle when their actual X field is edited.
#[test]
fn artboard_coordinate_fields_move_art_in_properties_and_transform() {
for draw in [show as fn(&mut VectorcraftApp, &mut Ui), super::super::transform::show] {
for move_art in [false, true] {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 200, "height": 100})).unwrap();
let id = app.run("shape.rectangle", json!({"x": 10, "y": 20, "width": 30, "height": 40})).unwrap()["id"].as_u64().unwrap();
app.select_tool("artboard");
app.session.set_tool_option("moveArt", &json!(move_art));
let ctx = egui::Context::default();
panel_frame(&mut app, &ctx, vec![], draw);
let texts = panel_frame(&mut app, &ctx, vec![], draw);
let label = texts.iter().find(|(t, _)| t == "X:").unwrap().1;
let at = egui::pos2(label.right() + 40.0, label.center().y);
let press = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() };
panel_frame(&mut app, &ctx, vec![Event::PointerMoved(at), press(true)], draw);
panel_frame(&mut app, &ctx, vec![press(false)], draw);
panel_frame(
&mut app,
&ctx,
vec![Event::Key { key: egui::Key::ArrowUp, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }],
draw,
);
let d = &app.session.doc().unwrap().doc;
assert_eq!(d.artboards[0].rect.x0, 1.0, "the focused X field steps its position");
assert_eq!(d.node(vectorcraft_doc::NodeId(id)).unwrap().geometric_bounds().unwrap().x0, if move_art { 11.0 } else { 10.0 });
app.run("edit.undo", json!({})).unwrap();
let d = &app.session.doc().unwrap().doc;
assert_eq!(d.artboards[0].rect.x0, 0.0);
assert_eq!(d.node(vectorcraft_doc::NodeId(id)).unwrap().geometric_bounds().unwrap().x0, 10.0);
}
}
}
/// #530: Edit Artboards shows the active artboard, with New Artboard, Delete Artboard and Exit.
/// #775: type's Paragraph section has Hyphenate, and its checkbox turns it on.
#[test]
+64 -10
View File
@@ -141,22 +141,20 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
}
ui.end_row();
ui.label(egui::RichText::new(tl!("Leader:")).color(t.text));
let mut leader = stops.get(sel).map(|s| s.leader.clone()).unwrap_or_default();
if ui.add_enabled(stops.get(sel).is_some(), egui::TextEdit::singleline(&mut leader).desired_width(90.0)).lost_focus()
&& let Some(s) = stops.get_mut(sel)
&& s.leader != leader
{
// The fields keep what is typed until Enter or a click away commits it (#924).
let leader = stops.get(sel).map(|s| s.leader.clone()).unwrap_or_default();
let typed = ui.add_enabled_ui(stops.get(sel).is_some(), |ui| widgets::exact_text_field(ui, "tabs-leader", &leader, 90.0)).inner;
if let (Some(leader), Some(s)) = (typed, stops.get_mut(sel)) {
// Up to eight characters repeat in the leader.
s.leader = leader.chars().take(8).collect();
apply(app, &stops);
}
ui.end_row();
ui.label(egui::RichText::new(tl!("Align On:")).color(t.text));
let decimal = stops.get(sel).is_some_and(|s| s.align == TabAlign::Decimal);
let mut on = stops.get(sel).map(|s| s.align_on.to_string()).unwrap_or_else(|| ".".into());
if ui.add_enabled(decimal, egui::TextEdit::singleline(&mut on).desired_width(30.0)).lost_focus()
&& let (Some(s), Some(c)) = (stops.get_mut(sel), on.chars().next())
&& s.align_on != c
{
let on = stops.get(sel).map(|s| s.align_on.to_string()).unwrap_or_else(|| ".".into());
let typed = ui.add_enabled_ui(decimal, |ui| widgets::exact_text_field(ui, "tabs-align-on", &on, 30.0)).inner;
if let (Some(c), Some(s)) = (typed.and_then(|t| t.chars().next()), stops.get_mut(sel)) {
s.align_on = c;
apply(app, &stops);
}
@@ -305,6 +303,62 @@ mod tests {
assert_eq!(back[1]["align"], json!("decimal"));
}
/// #924: Leader and Align On keep what is typed, frame after frame, until Enter applies it
/// (spaces kept, eight characters at most).
#[test]
fn leader_and_align_on_keep_what_is_typed_until_enter() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({})).unwrap();
app.session.execute("text.create", &json!({"x": 10, "y": 20, "text": "a b", "area": {"width": 300, "height": 100}})).unwrap();
app.session.execute("text.tabs.set", &json!({"stops": [{"position": 50, "align": "decimal"}]})).unwrap();
let ctx = egui::Context::default();
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(320.0, 400.0));
// One frame with `events` → the texts painted and where.
let frame = |app: &mut VectorcraftApp, events: Vec<egui::Event>| {
let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }, |ui| show(app, ui));
out.textures_delta.clear();
out.shapes
.iter()
.filter_map(|c| match &c.shape {
egui::Shape::Text(t) => Some((t.galley.text().to_string(), t.visual_bounding_rect())),
_ => None,
})
.collect::<Vec<_>>()
};
let key = |key| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() };
let click = |at| {
[true, false].map(|pressed| egui::Event::PointerButton {
pos: at,
button: egui::PointerButton::Primary,
pressed,
modifiers: Default::default(),
})
};
let stop = |app: &VectorcraftApp| current(app).unwrap().1[0].clone();
for (label, typed, want) in [("Leader:", [". ", "_", "123456789"], ". _12345"), ("Align On:", [",", "", ""], ",")] {
let texts = frame(&mut app, vec![]);
let r = texts.iter().find(|(t, _)| t == label).unwrap_or_else(|| panic!("{label} in {texts:?}")).1;
let at = egui::pos2(r.right() + 30.0, r.center().y);
let [down, up] = click(at);
frame(&mut app, vec![egui::Event::PointerMoved(at), down]);
frame(&mut app, vec![up]);
// Select what is there, then type in pieces over several frames.
frame(
&mut app,
vec![egui::Event::Key { key: egui::Key::A, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND }],
);
for piece in typed.iter().filter(|p| !p.is_empty()) {
frame(&mut app, vec![egui::Event::Text(piece.to_string())]);
frame(&mut app, vec![]);
}
frame(&mut app, vec![key(egui::Key::Enter)]);
frame(&mut app, vec![]);
let s = stop(&app);
let got = if label == "Leader:" { s.leader } else { s.align_on.to_string() };
assert_eq!(got, want, "{label}");
}
}
/// Position Panel Above Text floats the panel over the text, its ruler's 0 on the frame's left
/// edge and a stop's mark over the column it sets, at any zoom (#729).
#[test]
+2 -1
View File
@@ -58,7 +58,8 @@ fn artboard_fields(app: &mut VectorcraftApp, ui: &mut Ui, index: usize, r: Rect)
let set = |app: &mut VectorcraftApp, x, y, w, h| {
let n = artboard_rect(r, refi, x, y, w, h, link);
let scale_art = crate::panels::artboards::scale_art(app);
let p = json!({"index": index, "x": n.x0, "y": n.y0, "width": n.width(), "height": n.height(), "scaleArt": scale_art});
let move_art = crate::panels::artboards::move_art(app);
let p = json!({"index": index, "x": n.x0, "y": n.y0, "width": n.width(), "height": n.height(), "scaleArt": scale_art, "moveArt": move_art});
if let Err(e) = app.run("artboard.setProps", p) {
app.status(e);
}
+28
View File
@@ -50,6 +50,34 @@ fn effect_menu_has_a_vector_effects_section() {
assert!(effect.iter().any(|i| matches!(i, Item::Header("Vector Effects"))));
}
#[test]
fn effect_menu_lists_the_pixelate_filters_between_blur_and_sharpen() {
let app = app();
let entries = menus::menu_entries(&app);
let pixelate: Vec<_> = entries.iter().filter(|e| e.path == ["Effect", "Pixelate"]).collect();
let labels: Vec<&str> = pixelate.iter().map(|e| e.label.as_str()).collect();
assert_eq!(labels, ["Color Halftone…", "Crystallize…", "Mezzotint…", "Pointillize…"]);
assert!(pixelate.iter().all(|e| e.command.as_deref() == Some("effect.dialog")));
let raster: Vec<&str> =
entries.iter().filter_map(|e| e.path.get(1).filter(|_| e.path.len() == 2 && e.path[0] == "Effect")).map(String::as_str).collect();
let at = |name: &str| raster.iter().position(|s| *s == name).unwrap();
assert!(at("Blur") < at("Pixelate") && at("Pixelate") < at("Sharpen"));
}
/// Effect › Video, after Sharpen: De-Interlace opens its dialog, NTSC Colors (no options) applies.
#[test]
fn effect_menu_lists_the_video_filters_last() {
let app = app();
let entries = menus::menu_entries(&app);
let video: Vec<_> = entries.iter().filter(|e| e.path == ["Effect", "Video"]).collect();
let items: Vec<(&str, Option<&str>)> = video.iter().map(|e| (e.label.as_str(), e.command.as_deref())).collect();
assert_eq!(items, [("De-Interlace…", Some("effect.dialog")), ("NTSC Colors", Some("effect.apply"))]);
let raster: Vec<&str> =
entries.iter().filter_map(|e| e.path.get(1).filter(|_| e.path.len() == 2 && e.path[0] == "Effect")).map(String::as_str).collect();
let at = |name: &str| raster.iter().position(|s| *s == name).unwrap();
assert!(at("Sharpen") < at("Video"));
}
#[test]
fn library_submenus_are_disabled_placeholders() {
let app = app();
+8
View File
@@ -364,6 +364,14 @@ pub fn text_field(ui: &mut Ui, id: impl std::hash::Hash + std::fmt::Debug, value
(resp.lost_focus() && buf.trim() != shown).then(|| buf.trim().to_string())
}
/// A one-line [`text_field`] that keeps the text exactly as typed, spaces included (a tab
/// leader such as ". "). Returns it when a change is committed (Enter or focus loss).
pub fn exact_text_field(ui: &mut Ui, id: impl std::hash::Hash + std::fmt::Debug, value: &str, width: f32) -> Option<String> {
let id = ui.id().with(id);
let (buf, resp, _) = recessed_text(ui, id, value, width, 1);
(resp.lost_focus() && buf != value).then_some(buf)
}
/// A form row: `label` in a column `label_width` wide, then what `add` draws.
pub fn label_row(ui: &mut Ui, label: &str, label_width: f32, add: impl FnOnce(&mut Ui)) {
ui.horizontal(|ui| {
+3 -1
View File
@@ -404,7 +404,9 @@ Missing linked files: `app.open` of a document whose linked images' files can't
folder; `ui.dialog.set {field: "discard", value: true}` then confirm ignores it (the images keep their preview), with
`applyToAll` the rest too. The next missing file is asked about after each answer; `ui.dialog.cancel` stops asking.
Then, with the preference `updateLinks: "askWhenModified"`, modified linked files are offered for update in a
`confirm` dialog whose `ui.dialog.confirm` runs `links.update`.
`confirm` dialog whose `ui.dialog.confirm` runs `links.update`. The same happens when the app's window comes back to
the front and a linked file of the active document changed meanwhile (asked once per change of a file); with
`"automatically"` the files are read again at once, with `"manually"` the Links panel shows them as modified.
Missing fonts: once the missing linked file questions are answered, or at once when there are none, `app.open` of a
document whose type uses fonts that aren't available (`text.missingFonts`) opens the `missingFonts` dialog, one document
+11 -4
View File
@@ -275,7 +275,7 @@ objects' fills or strokes differ (`fillMixed` / `strokeMixed`, drawn as a "?" pr
| `invoke_menu` | `{command, params?}` | Invokes a menu item by command id. Includes UI commands such as `view.*` and `window.*` in remote mode. |
| `open_panel` | `{panel}` | Remote only. `panel` is a panel id (`layers`, `swatches`, `colorGuide`, …, as `window.panel` takes) or its display label (`"Color Guide"`), in any case. |
| `screenshot` | `{path?, scale?, artboard?, window?}` | Returns MCP image content (`image/png`, base64) plus a text block. Renders the artboard; `window:true` captures the app window (remote only). With `path` the backend (the headless session or the app) writes the PNG there too. |
| `open_file` | `{path}` | Opens any readable file as a new active document: `.vectorcraft`/`.drawcraft`, `.vctemplate`, `.svg`/`.svgz`, `.pdf`/`.ai`, `.ait`, `.eps`, `.dxf`, `.emf`, `.wmf`, PNG, JPEG, GIF, WebP, TIFF, BMP (an image opens as a document of its pixel size). Templates (`.vctemplate`, `.ait`) open as a new untitled document. PDF, `.ai` and SVG files saved with Preserve Editing reopen as the document they carry. The reply is `document.open`'s: its `warnings` say what didn't come in as it was (an EPS whose PostScript can't be read opens as its preview, and the warning names the PostScript error, the operator and the procedure). `run_command document.formats` lists the formats. |
| `open_file` | `{path}` | Opens any readable file as a new active document: `.vectorcraft`/`.drawcraft`, `.vctemplate`, `.svg`/`.svgz`, `.pdf`/`.ai`, `.ait`, `.eps`, `.dxf`, `.emf`, `.wmf`, PNG, JPEG, GIF, WebP, TIFF, BMP, PSD/PSB (an image opens as a document of its pixel size; a Photoshop file as its merged image). Templates (`.vctemplate`, `.ait`) open as a new untitled document. PDF, `.ai` and SVG files saved with Preserve Editing reopen as the document they carry. The reply is `document.open`'s: its `warnings` say what didn't come in as it was (an EPS whose PostScript can't be read opens as its preview, and the warning names the PostScript error, the operator and the procedure). `run_command document.formats` lists the formats. |
| `save_file` | `{path?}` | Runs `document.save`: the document's own file in its own format (native `.vectorcraft` unless it was opened from or saved as SVG, PDF or a restorable `.ai`; then `warnings` say what that format loses). A path's extension picks the format (`.vectorcraft`, `.vctemplate`, `.pdf`, `.svg`, `.svgz`, `.ai`: a PDF carrying the native document, which reopens editable). |
| `export` | `{path?, format?, scale?, artboard?, range?, selection?, outlineText?, options?}` | `svg`, `svgz`, `pdf`, `eps`, `dxf`, `emf`, `wmf`, `png`, `jpg`, `webp`, `gif`, `png8` (an indexed `.png`), `tiff`, `bmp`, `tga`, `psd` (layered), `txt` (the document's text), `vectorcraft` or `template` (a native template). The tool's `format` enum and `document.formats` list them, generated from the engine's format table. When `format` is omitted, it comes from the path's extension. PDF writes one page per artboard: all of them, or `artboard` (0-based) / `range` (`"1-3, 5"`, 1-based); the other formats write one artboard. `options` carries more format options (e.g. `{"quality": 80}` for JPEG). `selection: true` exports the selected objects cropped to their bounds (the reply adds their `bounds`, and reports `format` and the encoder's `warnings` as a whole-document export does); `outlineText: true` writes SVG text as paths. Template layers are left out, live effects are kept, and exporting `vectorcraft` never changes the document's path. Without `path` the bytes come back as `dataBase64`. Both backends run the same `document.export` call. |
| `add_text` | `{text, x?, y?, width?, height?, path?, mode?, pathEffect?, size?, font?, color?}` | Point type at (x, y); area type with `width`/`height`; or `path` + `mode` (`area`/`onPath`) to flow text in or along a path, with `pathEffect` (`rainbow`, `skew`, `3dRibbon`, `stairStep`, `gravity`). |
@@ -1690,7 +1690,7 @@ passed straight back to `file.new`. Print presets and sizes without `units` star
`file.place` puts another file's art into the active document as one undo step without touching the clipboard:
a raster image at 100% of its physical size (the resolution its file declares, else 72 ppi; linked to its `path`
unless `link: false`), an SVG as one group, a PDF/.ai page as one clipped group, with the images, symbols, patterns
unless `link: false`; a Photoshop document as its merged image), an SVG as one group, a PDF/.ai page as one clipped group, with the images, symbols, patterns
and swatches it uses. A VectorCraft document read from `path` is a placed document: one locked object showing its
artboard `page` (or, with `crop: "bounding"`, its art's bounds), linked to the file and read again when it changes
(see Linked images), and vectors in every output; with `link: false` (or from `dataBase64`) it is an editable copy
@@ -1809,7 +1809,8 @@ the preview instead of the pixels, plus the path relative to the saved file. `do
the linked files again, looking for each at its path, then at its relative path and by name in the document's folder
(so a folder moved with its links still opens): the result lists `missingLinks` (their images show the preview),
`modifiedLinks` (left as they were; read again only with the preference `updateLinks: "automatically"`, then they are
in `updatedLinks`), each as `{name, path, ids}`. `links.check` reports every link's `status` (`ok`, `modified`,
in `updatedLinks`), each as `{name, path, ids}`. The desktop app also checks the active document's links when its window
comes back to the front, following the same preference. `links.check` reports every link's `status` (`ok`, `modified`,
`missing`), `links.update {ids?}` reads modified files again and `links.relink {ids?, path | folder}` points images at
another file (or each at the file of its name in a folder); images keep their bounds, one undo step each. Without a
file system (the web), linked images show their previews.
@@ -2288,7 +2289,13 @@ show) is the flat render. `maxEditability: true` turns layers and sublayers into
named as the Layers panel names it (text objects by their text); layers with a clipping mask, an opacity mask, an
appearance of their own or knockout stay one pixel layer. Hidden layers and objects are left out unless
`hiddenLayers: true` writes them as hidden layers. `layers: false` writes one flat image, on white where nothing is
drawn. Files are at most 30000 pixels a side; PSD files don't open in VectorCraft.
drawn. Files are at most 30000 pixels a side.
Photoshop documents (`.psd`, and `.psb`, the large document format) open and place as their merged image, the
flattened picture every Photoshop file carries (layers aren't read): Bitmap, Grayscale, Duotone, Indexed, RGB, CMYK
(converted with the colour settings' CMYK) and Lab, at 1, 8, 16 and 32 bits per channel, sized by their resolution.
A document with transparency keeps it. `file.place {path}` links the file like any image (`links.update` reads it
again when it changes); Multichannel files are refused.
```json
{"name":"export","arguments":{"path":"/tmp/poster.psd","options":{"ppi":300,"maxEditability":true}}}