Compare commits

...
Author SHA1 Message Date
Brandon Thomas 90e022b0c0 Merge pull request #102 from storytold/pr/release-0.2.0
Release: VectorCraft v0.2.0
2026-10-05 02:41:45 -04:00
Brandon ThomasandClaude Opus 5.5 8b50a2604d Release: VectorCraft v0.2.0
Bump the workspace version 0.1.1 -> 0.2.0 (cargo xtask version set 0.2.0).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 02:41:32 -04:00
BFlat 819a0cb9b4 Merge pull request #101 from storytold/pr/m4-svg-encoding-tiny
M4.97–M4.98: SVG encoding, Tiny 1.2, font subsets and freeform gradients
2026-10-05 13:35:39 +07:00
bflatasticandClaude Opus 5.5 33023c5a2b M4.98: freeform gradients export to SVG as images clipped to their shapes
SVG has no freeform shading: an object's freeform fill or stroke is now
written as an <image> of the colour field over its painted box, sampled
on the grid the canvas uses (twice the box's size in points), clipped to
the shape or to the stroke's outline, with the fill or stroke opacity and
blend mode on the group. Linked image mode writes the PNG next to the
SVG. Character paints keep the linear approximation (with a warning);
gradients along or across strokes stay vector slices. The grid sizing
moved to the colour crate so the canvas and the export share it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 13:25:16 +07:00
bflatasticandClaude Opus 5.5 fa3dcab411 M4.97: SVG Options choose the encoding, SVG Tiny 1.2 and embedded font subsets
SVG export writes UTF-8, UTF-16 (big-endian with a byte order mark) or
ISO 8859-1 (other characters as character references) and SVG/SVGZ
open in any of them. The Tiny 1.2 profile (simplified) writes
presentation attributes only and leaves out filters, masks, blend
modes and symbols with warnings. embedFonts embeds the fonts type uses
as @font-face subsets of the characters used, honouring the fonts'
fsType (whole when subsetting is forbidden, left out when embedding
is). New options: encoding, profile, embedFonts (SVG Options dialog,
document.formats); document.serialize also returns dataBase64 for
non-UTF-8 files.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 13:25:15 +07:00
BFlat eacc83e05b Merge pull request #100 from storytold/pr/m4-export-screens
M4.51–M4.52: Export for Screens downloads, zip and options
2026-10-05 13:24:40 +07:00
bflatasticandClaude Opus 5.5 c96bf40d18 M4.52: Export for Screens options: full document, bleed, sub-folders, sizes, presets, format settings
Artboards: All, a range or Full Document (one file per format: a PDF of
every artboard, other formats the bounds of all art), Include Bleed
(artboards grown by the document's bleed). Rows size files as a factor,
100w, 100h or 72ppi (suffixes @2x, @100w, @100h), and choose PNG, PNG 8,
JPG 100/80/50, WebP, GIF, SVG or PDF. Create Sub-folders (by size, by
format, or a row's own folder) and the presets Mobile 1x/2x/3x and
Density buckets (ldpi…xxxhdpi sub-folders). The gear opens Format
Settings: per-format options for every row of that format (the raster
and SVG options dialogs' rows, the PDF preset). Open Location after
Export shows the first file. The dialog has Artboards and Assets tabs.

The params of the last export are saved in the document
(Document.export_settings, not an undo step), read with
document.exportSettings, and the dialog reopens on them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 13:18:10 +07:00
bflatasticandClaude Opus 5.5 902d95173e M4.51: Export for Screens downloads on the web, picks folders, zips
document.exportForScreens takes zip: true to pack every file into one
store-only .zip (returned as dataBase64 without a folder, written there
with one); without a folder the files come back as base64. The engine's
Export for Screens moves to fileio/screens.rs, with a small ZIP writer
(fileio/zip.rs).

The dialog starts in the user's Desktop (else home, on every OS), has a
folder picker button (the Services.pick_folder the Links panel uses) and
stays open when the export fails. On the web it has no folder: OK reads
"Download" (DialogSpec.ok_label) and the files download, several as one
zip. file.exportForScreens with params goes through io::export_for_screens.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 13:18:10 +07:00
BFlat 8ab7237443 Merge pull request #99 from storytold/pr/m4-pdf-boxes-marks
M4.71–M4.72: PDF bleed and trim boxes, printer's marks
2026-10-05 13:17:15 +07:00
BFlat 522f05c540 Merge pull request #98 from storytold/pr/m4-pdf-import-fidelity
M4.61–M4.62: PDF import fidelity and layers
2026-10-05 13:17:00 +07:00
bflatasticandClaude Opus 5.5 b0e39d0912 M4.72: PDF export draws printer's marks in Registration around each page
document.exportPdf {marks} now draws trim marks (Roman or Japanese, at the
trim mark weight and offset, outside the bleed), a registration target at the
middle of each side, colour bars (process inks, their overprints, the
document's spot inks and black tints) and the page information (title,
artboard, export date in UTC). Marks print in [Registration] (/Separation
/All), the MediaBox grows to hold them and the art is clipped to the
BleedBox. The geometry is the shared vectorcraft_doc::marks::PrinterMarks
(built on TrimMarks) so print can draw the same marks. The "not drawn yet"
warning is gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 13:05:20 +07:00
bflatasticandClaude Opus 5.5 8fb1733f05 M4.71: PDF pages carry the bleed and trim boxes; non-printing layers are left out
document.exportPdf applies the bleed (the document's with bleed.useDocument,
else the custom values): each page's TrimBox is its artboard and its BleedBox
and MediaBox the artboard grown by the bleed, so art in the bleed is kept.
Layers whose Print option is off are left out unless includeNonPrinting (new
setting, Save PDF › General) or createLayers is on. The bleed warning is gone;
the Marks and Bleeds section shows the document's bleed when it is used.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 13:05:19 +07:00
bflatasticandClaude Opus 5.5 8046b9be84 M4.62: PDF/.ai layers from optional content: named layers with visibility, print state and lock; art that is off as hidden layers
Optional content groups become layers (in paint order, shared by every page)
with their name, default visibility, print usage and lock; art outside them
goes to a layer per page. Art that is off isn't lost: an update appended to
the file drops its /OCProperties so the interpreter draws every group, and
the marked-content sequences found walking the content (checked by tag) route
the art to its group's layer, which comes in hidden. A form hidden by its own
/OC keeps the file as it is. document.open layers: false keeps one layer per
page of only what shows (Save then asks for a name).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 13:05:12 +07:00
bflatasticandClaude Opus 5.5 a51083733e M4.61: PDF import fidelity: opacity masks, isolate/knockout, pattern swatches, editable text, gradient meshes, stop opacity and Extend
Luminosity soft masks become opacity masks (alpha masks as a white copy of
their art; backdrop colour gives Clip, an inverting transfer function Invert;
the PDF export's backdrop and Difference covers read back as the options; a
constant alpha mask is opacity). Transparency groups keep their /I and /K
flags (read by walking the content as the interpreter does). Tiling patterns
become pattern swatches (one per colour for uncoloured ones). Text becomes
point type, one object per line with a run per font and paint, fonts named
from the file (document.open textAs: text | outlines). Patch and triangle
mesh shadings become gradient meshes; gradients drawn through their grey
opacity mask get stop opacity back; shadings that don't extend clip the art.
A rectangular clip around all its art (a form's box) is dropped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 13:05:12 +07:00
BFlat 66e92bbd4c Merge pull request #97 from storytold/pr/m4-slices
M4.88–M4.89: slices and the Slice tools
2026-10-05 13:05:06 +07:00
bflatasticandClaude Opus 5.5 fbc7549c31 M4.89: Slice and Slice Selection tools draw, pick, move, resize and delete slices
The Slice tool (Shift+K) drags out a user slice (Shift square, Alt from the
centre, snapping to ruler guides) as one undo step through
object.slice.create. The Slice Selection tool selects slices (Shift
toggles, object.slice.select), moves them (object.slice.move; object
slices move their objects), resizes a user slice by its handles
(object.slice.setRect), opens Slice Options on a double click and deletes
with Delete (object.slice.delete). Hidden or locked slices can't be
picked. Both tools have cursors drawn in code.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 12:52:15 +07:00
bflatasticandClaude Opus 5.5 271b0c6c25 M4.88: Object → Slice makes, edits and lays out user, object and auto slices
Document.slices holds user slices, Node.slice makes an object an object
slice that follows its bounds, and Document.slices_clip_to_artboard picks
the region auto slices fill (the artboards, or the art and the slices).
Object → Slice: Make, Release, Create from Guides, Create from Selection,
Duplicate, Combine, Divide… (dialog), Delete All, Slice Options… (dialog)
and Clip to Artboard; View → Hide/Lock Slices; Select → Object → Slices;
slice.list reads the numbered layout. The canvas draws the slices in the
Slices preferences' line colour with their numbers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 12:52:15 +07:00
BFlat d767fa22e0 Merge pull request #96 from storytold/pr/m4-links-package
M4.63–M4.64: Links panel, Placement Options and Package
2026-10-05 12:49:30 +07:00
bflatasticandClaude Opus 5.5 8d8ca11e50 M4.64: File > Package collects the document, its linked files and fonts with a report; Document Info categories and Save
File > Package (saved documents; unsaved changes are saved first) writes
<folder>/<name>/<document>.vectorcraft, the linked files in Links/ (relinked in the
packaged copy), the fonts its type uses in Fonts/ (leaving out fonts whose licence
doesn't allow embedding) and <document> Report.txt, then offers Show Package. Without a
folder (the web, agents) the same files come back as a zip.

Document Info's flyout picks one category (document, objects, styles, spot colours,
patterns, gradients, symbols, fonts, font details, linked and embedded images) and Save…
writes the text report Package shares.

Engine: file.package {folder?, name?, copyLinks?, linksFolder?, relink?, copyFonts?,
report?}; document.info gains category, format: text and sections. Text: FontFace
path, fs_type and embeddable. UI: ui.packageDialog (dialog `package`), file.showPackage,
docInfo.save.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 12:40:05 +07:00
bflatasticandClaude Opus 5.5 2925e7f9b5 M4.63: Links panel with status, Relink, Go To, Update, Edit Original, Embed/Unembed, Link Info and Placement Options
The Links panel lists every image (thumbnail, name, page, missing/modified/embedded
badge) with Show filters, sorting and thumbnail sizes; its buttons and flyout relink
(to a file or a folder), go to, update, edit the original, embed and unembed, show in
folder and open Placement Options. Link Info shows format, colour space, location, ppi
and effective ppi, dimensions, scale, rotation, size and dates. Edit > Edit Original
and the Properties panel's image section reach the same commands.

Engine: links.list, links.goTo, links.embed, links.unembed, links.info and
links.placementOptions; links.relink and links.update now place the new file as the
image's Placement Options say (transforms, bounds, file dimensions, fit, fill, the
alignment point, clip to the old bounds). Model: ImageObject.placement.
UI: links.editOriginal, links.reveal, ui.placementOptionsDialog; Services.open_file
and pick_folder on the desktop.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 12:40:05 +07:00
BFlat 171de62fde Merge pull request #95 from storytold/pr/m4-native-format
M4.35–M4.36: native format v3 and background save
2026-10-05 12:37:53 +07:00
bflatasticandClaude Opus 5.5 db0a7ffd8b M4.36: Background Save and Export write a snapshot off the UI thread with status bar progress
- With Preferences > File Handling > Enable Background Save / Export on, File >
  Save, Save As, Save a Copy and exports encode and write a snapshot of the
  document on a worker thread; the call returns at once ({path, background}).
- The status bar shows a spinner and what is being written; ui.inspect lists
  the running jobs under `background`.
- The document takes the path and counts as saved as of the snapshot once the
  file is written: edits made meanwhile keep it modified.
- Quit and Close wait for running saves; the Save Changes dialog saves at once.
- The host gives a thread-safe writer (Services::write_shared, atomic on the
  desktop); without one (web, tests) everything runs at once as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 12:27:06 +07:00
bflatasticandClaude Opus 5.5 65cdc45ed9 M4.35: native files compress, save atomically, drop unused images, keep newer keys and save down to v1
- Format v3: optional gzip (Preferences > File Handling > Use Compression, or
  document.save {compress}); compressed files open by their magic bytes, legacy
  ones too.
- Every file write goes to a temporary file renamed over the target (engine
  writes and the desktop app's writer), so a failed save keeps the old file.
- Only the images the document uses are written.
- Document keys from newer versions are kept (Document.extra, flattened).
- Assigned colour profiles are a real field (Document.color_profiles),
  migrated from unknown.colorProfiles on load.
- document.save {version: 1|2} writes files older versions open; {preview}
  embeds a PNG of the first artboard of at most 256 px.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 12:27:02 +07:00
BFlat 7aee3bd487 Merge pull request #94 from storytold/pr/m4-svg-import-live
M4: SVG import keeps symbols, patterns and filters live; linked images, nested clips, reflected gradients (M4.41, M4.42)
2026-10-05 12:25:30 +07:00
bflatasticandClaude Opus 5.5 303fc3cbca M4.42: SVG import reads linked images from the SVG's folder, intersects nested clips, keeps hidden objects and expands reflected gradients
document.open {path} (and File > Place) find an SVG's relative <image>
links in its folder: raster files stay linked images (LinkInfo with size,
time and hash), SVG files and data: SVGs import as vector art, and a file
that can't be read becomes a placeholder in its box that keeps the link,
with a warning and a missingLinks row (Update Links / Relink read it
later). The SVG library itself reads no file unless given a reader.
Nested clip paths become clip groups in clip groups; undisplayed objects
(display:none) come back hidden; spreadMethod reflect and repeat are
expanded into stops over the painted area (matching resvg). Midpoint stops
and focal points keep folding back as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 12:12:06 +07:00
bflatasticandClaude Opus 5.5 0d75df4da8 M4.41: SVG import keeps symbols, patterns and blur/shadow filters live
<symbol> with <use> imports as a symbol (named after data-name or its id)
with one instance per <use>; a <use> that shows the symbol differently
(inherited paint, a viewport that cuts it) or that the canvas would paint
differently under its transform stays plain art. feGaussianBlur,
feDropShadow and the usual shadow chains (offset, blur, flood or colour
matrix, composite, merge) become Gaussian Blur, Drop Shadow, Outer/Inner
Glow and Feather effects; other filters are still reported. Export records
the symbol name and the shadow/glow blend mode so export -> import keeps
them. <pattern> keeps importing as a pattern swatch (now tested).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 12:11:27 +07:00
BFlat 3e8c8d6264 Merge pull request #93 from storytold/pr/m4-dxf-export
M4: DXF export (R12 to 2018) with DXF Options; DWG and PICT hints (M4.77)
2026-10-05 12:10:53 +07:00
bflatasticandClaude Opus 5.5 a17cc428d1 M4.77: DXF export (R12 to 2018) with DXF Options; DWG and PICT say what to use instead
New crates/cad (L3): a hand-written ASCII DXF writer. Layers become DXF
layers (hidden: off, locked, non-printing: not plotted), straight paths
LWPOLYLINE (POLYLINE before R14), curves cubic SPLINEs through every
anchor, fills solid HATCHes (outlines in R12), strokes lines with a
lineweight and a linetype per dash pattern, type TEXT or glyph outlines,
placed images IMAGE entities linked to PNG or JPEG files. Units and
scale ($INSUNITS), scaled lineweights, 8/16/256 indexed or true colour
(420), transparency (440), Preserve Appearance / Maximize Editability,
Alter Paths for Appearance, Outline Text.

document.export {format: dxf} and document.exportDxf; useArtboards
writes one drawing per artboard; selectedOnly (any export) writes the
selection in its layers. Export As lists DXF (then DXF Options,
ui.dxfOptionsDialog for agents, remembered between exports) and DWG
greyed out; document.formats lists DWG and PICT as unsupported with a
hint, and exporting or opening them answers with it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 12:00:17 +07:00
BFlat 448437fb76 Merge pull request #92 from storytold/pr/m4-pdf-fidelity
M4: PDF keeps raster effects everywhere, pattern strokes and freeform gradients; image resampling and compression (M4.58–M4.60)
2026-10-05 11:59:45 +07:00
bflatasticandClaude Opus 5.5 cfed319af4 M4.60: PDF export resamples and compresses images as the Compression settings say
Colour, greyscale and monochrome (black-and-white) images placed above the
threshold resolution are resampled to the target (average, subsample or
bicubic) and compressed with ZIP, JPEG at the chosen quality, or
automatically (JPEGs stay JPEG, the others lossless); images already as
asked are embedded unchanged. JPEG 2000, CCITT, Run Length and no
compression are written as ZIP with a warning when an image needs them;
images with transparency stay lossless. Images no longer ask viewers to
smooth them in PDF/A files.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 11:52:35 +07:00
bflatasticandClaude Opus 5.5 ffc60d5ff8 M4.59: pattern strokes and freeform gradients keep their look in PDF
Pattern strokes are written as the pattern's tiles clipped to the stroke's
outline (dashes, caps, profile, arrowheads and alignment included) instead
of mid-grey; freeform gradients on fills, strokes and type as an image of
their colour field at the document raster effects resolution, clipped to
what they paint, instead of their average colour. Both read back within
2% of the canvas at 150 ppi with no warning. Text strokes are covered for
cap, miter limit, dash array and alignment; knockout groups keep their
soft-masked form with a warning. The freeform box and grid sampling are
shared with the renderer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 11:52:35 +07:00
bflatasticandClaude Opus 5.5 e967c31be6 M4.58: raster effects in PDF on every kind of object
PDF export now renders the shadows, glows, blurs and feathers of groups,
layers, type, images, symbol instances, live objects and single fills and
strokes (and those inside opacity masks, symbol definitions and pattern
tiles) as images at the document raster effects resolution, instead of
leaving them out with a warning. Shadows and outer glows go under the
untouched vector art; a path whose fills or strokes carry effects is
written as one piece per fill and stroke. Expand Appearance shares the
image helpers (moved to rasterfx.rs); effect images now cover what the
renderer paints (members' shadows included).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 11:52:34 +07:00
BFlat 7051a65c65 Merge pull request #91 from storytold/pr/flaky-clock-and-port-tests
Tests: journal replays reproduce File Info's dates; the MCP connect test holds its own port
2026-10-05 11:49:35 +07:00
bflatasticandClaude Opus 5.5 7b30dd787b M1.9: the MCP connect-failure test holds its own closed port
remote_connect_fails_fast bound a port and dropped it, so another test or
process could take the port before the connect and make it succeed. It now
holds a socket bound without listening (socket2, a test-only dependency):
connections to it are refused and nothing else can bind it meanwhile. It
also checks the failure comes within 5 s.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 11:41:26 +07:00
bflatasticandClaude Opus 5.5 851ed15104 M4.55: a journal replay reproduces File Info's dates
File Info's dates come from the clock, so documents made or saved a second
apart differed: journal_replay_reproduces_document and
rich_fixture_satisfies_invariants_and_undoes_to_blank failed at random.
One approach for every clock-derived date: it is a command input that
defaults to now, and the journal records the value used.

- file.new takes created? and document.save / file.saveAs take modified?
  (Unix seconds, or null for none; default now), through date_param /
  clock_date on the one save path (save_with), so Save, Save As and the
  UI's save stamp alike; Save a Copy still leaves the dates.
- Their journal entries always record the date used, so replaying the
  journal makes the same document whenever it runs. Actions recorded from
  the journal (Session::journal_for_action) leave those dates out, so
  playing an action later dates the document then.
- Test fixtures date their documents fixtures::CREATED, and the MCP
  property test dates its local document as the headless one, so
  documents built at different moments compare equal.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 11:41:26 +07:00
BFlat 53f42797f3 Merge pull request #90 from storytold/pr/m4-jpeg-png8-gif-webp
M4: JPEG Options with CMYK and ICC, PNG-8 and GIF, WebP options, Export As Text, Save for Office (M4.48–M4.50)
2026-10-05 11:40:06 +07:00
bflatasticandClaude Opus 5.5 da18cf4234 M4.50: WebP options, Export As Text and Save for Office Documents
- WebP takes lossless and quality; there is no permissive pure-Rust lossy encoder yet, so
  lossless: false writes lossless with a warning (the WebP Options dialog says so).
- document.export {format: "txt", encoding: utf8|utf16, lineEndings: lf|crlf,
  selectionOnly}: the stories in stacking order (back to front), a thread once, hidden
  objects and template layers left out; UTF-16 is little-endian with a byte order mark.
  Export As → Text opens Text Export Options.
- File → Save for Office Documents… (document.exportForOffice {ppi, transparent, artboard,
  path}): the artboard as a PNG at 72/150/300 ppi on white or transparent, through a small
  dialog in the app.
document.formats' writable list and the MCP export tool's enum gain txt.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 11:27:22 +07:00
bflatasticandClaude Opus 5.5 ac77b52ad3 M4.49: PNG-8 and GIF export with a palette quantizer and dithering
document.export {format: "png8" | "gif"} reduces the art to a palette of at most `colors`
(2–256) entries: median cut over a 15-bit histogram refined by k-means (perceptual,
selective or adaptive weighting), or the web-safe, black-and-white or grey palettes; art
with that many colours or fewer keeps them exactly. Dithering is Floyd–Steinberg diffusion,
an 8×8 ordered pattern or noise, with an amount. Pixels under half opacity become one
transparent entry; partly transparent edges blend over the matte. PNG-8 is an indexed PNG
(PLTE, tRNS, 1–8 bits per pixel, Adam7); GIF is a GIF89a (optionally interlaced). Both are in
document.formats, Export As (PNG-8 / GIF Options dialogs) and Export for Screens.
document.formats' writable list and the MCP export tool's format enum gain gif and png8
(their tests list them).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 11:26:15 +07:00
bflatasticandClaude Opus 5.5 ba4ed2ff93 M4.48: JPEG Options — RGB/CMYK/gray, baseline/optimized/progressive, embedded ICC profiles and image maps
document.export {format: "jpg"} takes colorModel (rgb|cmyk|gray), quality 0–100, method
(baseline|optimized|progressive), scans (3–5), embedIcc and imageMap (none|client|server).
JPEGs are written with jpeg-encoder. CMYK files hold ink amounts drawn as the renderer's ink
planes, so CMYK colours keep their inks (black type stays black ink alone). Profiles are made
in code from the CMS (cms::icc_bytes): the RGB spaces from their primaries, the CMYK spaces as
Lab lookup tables sampled from their model, a grey with sRGB's tone curve, and loaded
profiles as loaded. Image maps write <stem>.html or <stem>.map beside the image for objects
with a URL and an Image Map shape. The JPEG Options dialog gains Color Model, Quality 0–10,
Method and Scans, Image Map and Embed ICC Profile; CMYK documents default to CMYK.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 11:25:09 +07:00
BFlat db9d937e1a Merge pull request #89 from storytold/pr/m4-save-pipeline
M4: Save As format chooser, Save keeps its format, Save a Copy, Revert, templates, File menu details (M4.14–M4.17)
2026-10-05 11:19:44 +07:00
bflatasticandClaude Opus 5.5 489bb84755 M4.17: File menu details: converted files, 30 recent files, one colour-mode command, Show in Folder, saved view
Older native files (.drawcraft or an older format version) open as
"<name> [Converted]" and Save asks for a .vectorcraft name instead of
overwriting them (preference appendConverted). Open Recent Files honours the
0-30 preference; empty slots are hidden (the native menu rebuilds when they,
saved views or User Defined libraries change). File > Document Color Mode is
one command, file.documentColorMode, converting through the colour settings;
choosing the current mode is not an edit, and object.convertDocumentColorMode
stays as an alias the command palette leaves out. New File > Show in Folder
(file.reveal; paths with spaces work on Windows). Native files store the view
they were saved with (Document.last_view, written at save time so it never
dirties the document) and reopen there.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 11:11:19 +07:00
bflatasticandClaude Opus 5.5 70e2726321 M4.16: Template safety: Templates folder, "<name> template", New from Template
Save as Template suggests "<name> template.vctemplate" in the Templates folder
(the new templatesFolder preference; default Documents/VectorCraft Templates,
created by the desktop save panel) and never the source path. New from
Template is an engine command (file.newFromTemplate {path} or {name,
dataBase64}) that opens any readable file as a new Untitled-N document; in the
app, bytes from an agent go straight to the engine, otherwise the open dialog
starts in the Templates folder with template types first. .ait and template
files keep opening untitled.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 11:07:15 +07:00
bflatasticandClaude Opus 5.5 9fae8c56ec M4.15: Revert as an engine command with a confirmation
file.revert reads and decodes the saved file first: if that fails the
document is left as it is, still modified. Otherwise Session::replace_document
swaps the content in the same tab (same place, path, format and uid; history
and selection cleared; saved state), so every tab keeps its zoom. It runs only
for saved, modified documents. In the app, Revert asks first with the shared
confirm dialog, whose OK runs file.revert {confirmed: true} on the engine.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 11:07:15 +07:00
bflatasticandClaude Opus 5.5 515ce2ac94 M4.14: Save As format chooser, Save writes back its own format, Save a Copy
Save As offers VectorCraft, VectorCraft Template, PDF, SVG and SVGZ and asks
for the chosen format's options before writing: SVG Options for SVG/SVGZ, the
Save PDF dialog for PDF (its OK finishes the save); on the web a Save As
dialog first names the file and picks the format. A document opened from or
saved as SVG/PDF remembers its format and options in one place
(DocState.format, save_options: the SVG options, or every Save PDF setting),
so Save writes it again; the result's warnings name what the format loses,
then the encoder's notes. Save a Copy writes "<name> copy.<ext>" and leaves
the path, title and modified state alone. Save is off for a clean saved
document, and Save as PDF... is in the File menu.

Engine: document.save, file.saveAs and file.saveCopy take {path?, format?,
options?, svg?} (SVG options also flat) and write linked images beside an
SVG; file.formatOptions reads a format's options. save_plan/save_with are the
one save path of every frontend, on the shared SVG encoder (one SVGZ path).
The template format is writable. Save panels get per-format filters, a folder
and a suggested name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 11:07:15 +07:00
BFlat ba6597b7b5 Merge pull request #88 from storytold/pr/m4-clipboard-flavours
M4: PNG, PDF, SVG and text clipboard formats in and out (M4.57)
2026-10-05 11:00:21 +07:00
bflatasticandClaude Opus 5.5 0968e34e7e M4.57: PNG, PDF and text clipboard flavours in and out
Copy and Cut also offer other apps a PNG of the copied objects, a PDF
with On Copy: PDF, and plain text when every copied object is type
(clipboard.flavours; clipboard.exportPng {scale?}, exportPdf,
exportText). Paste outside text editing takes what another app copied:
SVG, then PDF (clipboard.importPdf), then plain text as point text
(clipboard.importText), then a bitmap embedded at the view centre
(clipboard.importImage {dataBase64, mime?, center?}); pasting our own
copy keeps the lossless internal clipboard, and Cmd+V pastes a bitmap
that comes with no text. Services gains system_clipboard
(SystemClipboard: write, holds_ours, read, has): on Windows every
format at once, on macOS and Linux one (the text, else the PNG); the
web keeps SVG text only. With When pasting text: Keep Plain Text, text
the Type tool copied pastes without its formatting.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 10:52:01 +07:00
BFlat a560f74e17 Merge pull request #79 from storytold/pr/m4-pdf-editing-presets
M4: PDF and .ai reopen editable, Save As .ai; PDF presets and Edit > PDF Presets (M4.43, M4.44)
2026-10-05 10:42:27 +07:00
bflatasticandClaude Opus 5.5 9aa29aa0fd M4.44: PDF presets: built-ins in code, saved presets, Edit > PDF Presets
Built-in presets are generated in code (VectorCraft Default, High
Quality Print, Press Quality, Smallest File Size and PDF/X-1a, X-3,
X-4, the latter listed as not supported yet) and read-only. Saved
presets live with the preferences (Prefs.pdf_presets) and work as
`preset` wherever PDF options are taken: document.exportPdf,
pdfSettings, export/serialize as PDF and .ai saves.

pdf.preset.list / save / delete / export / import manage them
(.vcpdfpresets files; opening one imports it). The Save PDF dialog's
Save Preset… saves its settings under a name; Edit > PDF Presets…
(ui.pdfPresetsDialog) lists the presets with each one's description and
differences from the default, with New…, Edit… (the Save PDF dialog as
a preset editor, ui.pdfPresetDialog), Delete, Import… and Export….
document.pdfSettings now lists what differs from the chosen preset.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 10:40:22 +07:00
bflatasticandClaude Opus 5.5 0ffaa427d1 M4.43: PDFs and .ai files reopen editable; Save As writes PDF-compatible .ai
Preserve Editing (on in the VectorCraft Default preset) embeds the
native document in the PDF as an embedded file with a hash of the pages
it was written with. document.open of a PDF, .ai or .ait restores it
exactly (restored: true) and falls back to importing the artwork, with a
first warning saying why, when the pages were changed elsewhere or the
data can't be read; SVG and PDF share that fallback and its warnings.
The legacy drawcraft payload name is read too. vectorcraft_pdf gains
editing(), ImportReport.native and PdfOptions.native.

document.save / file.saveAs / Save a Copy write .ai (format "ai" or an
.ai path): every artboard as a PDF that always carries the document and
takes the PDF options; a restored .ai keeps its path so Save writes .ai
again, and .ait templates open their document untitled. The desktop
save dialog lists the formats Save writes. Choosing a standard turns
Preserve Editing off (PDF/A refuses it), Export for Screens and PDFs of
some artboards leave it out with a warning.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 10:34:15 +07:00
BFlat 4b956422c9 Merge pull request #78 from storytold/pr/m4-links-text-import
M4: linked images with previews, missing and modified links; Text Import Options (M4.53, M4.54)
2026-10-05 10:18:04 +07:00
bflatasticandClaude Opus 5.5 2724263d00 M4.54: Placing a text file asks for Text Import Options and sets it as area type
file.place of a .txt file takes `text: {characterSet: unicode|ansi, platform: windows|mac,
removeLineReturns, removeParagraphReturns, replaceSpaces}`: Unicode reads UTF-8 or UTF-16 by its
byte-order mark (other bytes as the platform's 8-bit set), ANSI reads Windows-1252 or Mac Roman;
CR LF, CR and LF all break lines; joining lines makes each block one paragraph, blank lines can
go, and runs of spaces can become tabs. The text becomes area type filling `rect`, the replaced
object's bounds, or the artboard less a 36 pt margin (type reflows rather than scaling), as one
undo step. The place cursor and file.place.info take text files too, and File → Place lists them.

In the app, placing a text file (the Place dialog, a drop, file.place without options) opens the
Text Import Options dialog. Its dropdown rows share a form helper with Document Setup.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 10:07:23 +07:00
bflatasticandClaude Opus 5.5 2e5ec7b251 M4.53: Linked images remember their file and keep a preview; missing links ask Replace or Ignore, modified ones follow Update Links
A linked image (`ImageObject.link`, now a LinkInfo: absolute path, path relative to the document,
size, modification time, hash, page; old path strings still load) keeps a low-resolution preview
(`ImageBlob.proxy`, at most 256 px a side) that a native save writes in place of the pixels of
images only linked images show. Opening a native document reads the linked files again, looking
for each at its path, then relative to the document and by name in its folder: missing files
show their preview, modified ones are read again only with Update Links: Automatically.
`document.open` reports `missingLinks`, `modifiedLinks` and `updatedLinks`.

links.check reports each link's status, links.update reads modified files again and
links.relink points images at another file or at same-named files in a folder (each keeps its
bounds; one undo step). In the app, a document opened without its linked files asks about each
(Replace…, Ignore, Apply to All), then offers to update modified links when the preference asks.
The renderer caches previews apart from the file's pixels; the Eyedropper samples previews in
the object's pixel space.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 10:07:10 +07:00
BFlat 0c65fe77f3 Merge pull request #77 from storytold/pr/m4-file-info-raster-settings
M4: File Info in SVG, PDF and PNG; Document Raster Effects Settings (M4.55, M4.56)
2026-10-05 10:05:40 +07:00
bflatasticandClaude Opus 5.5 94f0f1b0d2 M4.56: Document Raster Effects Settings with colour model, background, anti-alias, clipping mask and room around
document.rasterEffectsSettings now also takes and reports colorModel,
background, antiAlias, clippingMask, addAround and preserveSpotColors in one
undo step (Document.raster_effects, RasterEffectsSettings, next to the
existing raster_effects_ppi so old files load unchanged). The raster effect
images of PDF export and Expand Appearance get the extra room and are
finished by the settings (hard edges, grayscale or bitmap, opaque on
white, white only under the art with a clipping mask). Rasterize takes
them as defaults (params override), and its clipping mask puts the image
in a clip group with the art's outline. The settings have their own dialog
(rasterEffectsSettings, ui.rasterEffectsSettingsDialog) and Rasterize…
opens its options prefilled from them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 09:55:48 +07:00
bflatasticandClaude Opus 5.5 6a446b4fa3 M4.55: File Info with author, description, keyword chips, rating and copyright, written to SVG, PDF and PNG
file.info takes and reports the title, author, author title, description,
keywords, rating, copyright status, notice and URL in one undo step, plus
the read-only created (file.new) and modified (every save to a file) dates;
junk values are refused. Document.metadata (DocMetadata) round-trips
natively. PDF export writes author, subject and keywords to the info
dictionary and XMP, PNG export writes tEXt/iTXt chunks, SVG export writes
<desc> and, with the metadata option, every field as Dublin Core. The File
Info dialog (fileInfo, ui.fileInfoDialog) edits it with keyword chips and
star ratings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 09:55:47 +07:00
BFlat a908ba0190 Merge pull request #76 from storytold/pr/m4-clipboard-resources
M4: paste carries resources with a Swatch Conflict dialog; paste placement and Paste Remembers Layers (M4.22, M4.23)
2026-10-05 09:52:38 +07:00
BFlat cc03a47b7d Merge pull request #75 from storytold/pr/m4-pdf-import
M4: PDF import pages, Crop To and passwords; CMYK, Gray and spot colours kept (M4.45–M4.47)
2026-10-05 09:51:03 +07:00
bflatasticandClaude Opus 5.5 f346727dd8 M4.23: paste placement, Paste Remembers Layers and the Paste menu's enable rule
Paste (also without formatting) goes to the centre of the view
(edit.paste {center}); Paste in Front/Back with nothing selected go to
the top/bottom of the current layer, in order; Paste on All Artboards
keeps the objects' offset to the artboard they were copied from.
layer.pasteRemembersLayers {on?} (document flag paste_remembers_layers,
saved, document.inspect) pastes objects back into the layers they came
from by name, making missing ones; the Layers panel now has its menu
with the layer commands and the check item. The Paste menu items are
enabled while the system clipboard holds SVG (looked at once per frame
at most, a few times a second).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 09:45:34 +07:00
bflatasticandClaude Opus 5.5 ee2aa96dcd M4.22: pasting between documents carries the objects' resources
Copy keeps the copied objects with every document resource they use
(Session.clipboard: Clipboard {nodes, images, symbols, patterns,
swatches, graphic_styles, char_styles, para_styles, brushes,
source_artboard, source_layers, source_doc}), following symbols,
patterns, graphic styles and text styles into what they use. Every
edit.paste* brings them in within its undo step: identical resources are
reused, missing ones added, different ones of the same name added
renamed (an earlier paste's copy is reused) and the pasted objects
relinked, graphic style links by id. Global and spot swatches that
conflict ask Merge or Add (swatchConflict; clipboard.conflicts lists
them; the app's Swatch Conflict dialog asks one by one, with Apply to
All). Tint swatches, linked gradient stops, Lab spots and the target's
Spot Colors option are honoured; [Registration] is never copied.
Clipboard SVG exports them too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 09:45:34 +07:00
bflatasticandClaude Opus 5.5 e0895fd4ba M4.47: PostScript .ai and placeholder-only .ai files say why they can't open
A PostScript file (a .ai saved in an older format or without PDF
compatibility, or an .eps, plain or with a binary header) is refused by any
name with a clear message instead of a parse error (there is no PostScript
importer yet). An .ai whose pages are only placeholder text over the editor's
private data (PieceInfo AIPrivateData) is detected and refused with advice to
save it with PDF compatibility, instead of opening the placeholder.
vectorcraft-pdf: is_postscript(), PdfError::PostScript / PlaceholderOnly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 09:37:11 +07:00
bflatasticandClaude Opus 5.5 8765d335ec M4.46: PDF import keeps CMYK, Gray and spot colours
DeviceCMYK and CMYK ICC colours import as CMYK and a file painted mostly in
CMYK opens as a CMYK document (with CMYK default swatches); DeviceGray
imports as Gray; Separation and DeviceN inks become global spot swatches
(their 100 % colour from the alternate space: CMYK, RGB, Gray or Lab) that
the art links to at its tint, /All links to Registration and process
colorants make CMYK. Shading stops keep their model and ink links the same
way. Inks mixed in one DeviceN colour, or spaces that can't be told apart,
import as RGB (with a warning for the mix).

document.open takes colorMode (rgb | cmyk) to open any file in that mode,
converted as file.documentColorMode does (its conversion is now shared).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 09:37:11 +07:00
bflatasticandClaude Opus 5.5 e204341996 M4.45: PDF import and place options — pages, Crop To and password
Opening or placing a PDF or .ai with several pages or a password shows the
Import PDF / Place PDF dialog: a page preview with page navigation, Pages
(All or a range) when opening, Crop To (Bounding Box, Art, Crop, Trim, Bleed,
Media) and a password prompt for encrypted files.

- vectorcraft-pdf: ImportOptions.pages / crop / password, CropTo, info()
  (pages, sizes, rotation, boxes); NeedsPassword / WrongPassword / BadPage
  errors; images keyed by content so placed pages merge safely.
- document.open takes pages, page, cropTo (or crop) and password;
  document.pdfInfo (query) lists pages and boxes, reports needsPassword and
  renders a page thumbnail.
- file.place and file.place.info read only the page placed and take every
  PDF box as crop (art, trim, bleed, media besides crop and bounding) and a
  password; the UI's File > Place asks with the dialog when no page is given,
  keeping Link, Template and the other place params.
- testkit::pdf writes hand-made PDFs with page boxes and RC4 encryption.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 09:37:11 +07:00
BFlat e8af1f6576 Merge pull request #74 from storytold/pr/shortcut-test-isolation
Tests: shortcut overrides and workspace names no longer leak between parallel tests (M14.6)
2026-10-05 09:36:33 +07:00
bflatasticandClaude Opus 5.5 0e5425544a M14.6: shortcut overrides and workspace names no longer leak between parallel tests
global_override_reaches_shortcut_of_and_tools failed about once in a
hundred full ui-egui runs: the override and workspace-name mirrors
(read by menus and the shortcut dispatcher, which have no app access)
were process-wide, and every frame of any headless test running in
parallel synced its own default UI state into them, wiping the test's
overrides between its sync and its assertions.

- One `ui_mirror!` declares both mirrors: process-wide in the app, one
  per thread under cfg(test), so each test only sees the state of the
  app it drives.
- New test: a sync from another thread leaves this thread's overrides
  and workspace names alone (fails with a shared mirror).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 09:29:12 +07:00
BFlat d6ebecee39 Merge pull request #73 from storytold/pr/m4-export-as-png
M4: Export As with Use Artboards; PNG/JPEG/WebP resolution, background, anti-aliasing (M4.33, M4.34)
2026-10-05 09:28:45 +07:00
bflatasticandClaude Opus 5.5 950a941003 M4.33: Export As with Use Artboards (All or a range) and art bounds
File > Export > Export As... (file.exportAs) picks any writable format and Use Artboards: All
or a range writes one file per artboard, <file>-<artboard>.<ext> (a PDF keeps them as pages);
off, the export covers the bounds of the visible art (an artless document is refused before the
save dialog). The format's options dialog follows: PNG/JPEG/WebP Options, SVG Options, or Save
PDF for artboards as pages. document.export takes useArtboards for raster formats (true: one
file per chosen artboard, default all) and PDF (false: the art's bounds), and the app's exports
return every file written and the encoder's warnings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 09:14:42 +07:00
bflatasticandClaude Opus 5.5 157724279f M4.34: raster export options and PNG Options — resolution, background, anti-aliasing, interlacing
PNG is written by an in-code chunk writer with the resolution in pHYs and optional Adam7
interlacing (JPEG stores the resolution in JFIF). document.export takes ppi (72/150/300/other,
wins over scale), background (transparent, white, black or a colour) and antiAlias (none, art,
type: text snapped to whole pixels); Export for Screens rows take them too (plus one top-level
antiAlias, and a row's ppi names its @Nx suffix), and so does object.rasterize. Hard edges stay
hard in every offscreen pass (groups, masks, filters), whatever the thread count.
RenderOptions.anti_alias and render::encode::RasterExportOptions; PNG/JPEG/WebP Options dialog
(pngOptions/jpgOptions/webpOptions) after File > Export As PNG.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 09:14:11 +07:00
BFlat bba9d2ceb8 Merge pull request #72 from storytold/pr/m4-svg-symbols-editing
M4: SVG symbols as <symbol>/<use>, hidden layers, metadata; Preserve Editing round trip (M4.39, M4.40)
2026-10-05 09:12:13 +07:00
bflatasticandClaude Opus 5.5 74b5a904b7 M4.40: Preserve Editing SVGs reopen exactly, or as plain SVG once edited elsewhere
The editing data now sits in CDATA inside <metadata> with a hash of the
markup around that element (whitespace between tags and line endings
don't count). document.open restores the native document when the hash
matches (data written without a hash is trusted as before); when another
app changed the SVG, or the data can't be read, it imports the SVG and
says why in its warnings. vectorcraft_svg::editing reports the data and
whether it is intact; editing_data stays. Live effects, symbols and
patterns come back exactly; the import fuzz test now mutates saved SVGs
with editing data and hidden layers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 09:03:52 +07:00
bflatasticandClaude Opus 5.5 370c6e2fc0 M4.39: SVG symbols as <symbol>/<use>, hidden layers on Save, Dublin Core metadata
Symbol instances export as one <symbol> def per symbol and a <use> per
instance. An instance the def can't stand for exactly (stained by its fill,
or a transform under which the canvas paints differently: scaling with
strokes, effects or live objects, turning with effects or brushes, any move
with pattern paints or unlinked masks) is written as its own art, now
stained like the canvas and with its patterns and unlinked masks left on
the page. Symbols nested in themselves stop at a fixed depth.

New SVG option hiddenLayers keeps hidden layers as display:none groups;
document.save (and Save As / Save a Copy) turns it on unless told
otherwise, exports leave hidden layers out. Import shows display:none
layer groups to usvg and marks them hidden, so they reopen hidden
(groups a <use> refers to stay templates). File Info metadata goes through
one Dublin Core list. The symbol stain helper moves to vectorcraft-brush
so the renderer and the SVG writer share it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 09:03:52 +07:00
BFlat 4cccbc2c6e Merge pull request #71 from storytold/docs/mcp-fences
Docs: close the code blocks that made mcp.md sections render as code
2026-10-05 09:00:00 +07:00
bflatasticandClaude Opus 5.5 950984b3db Docs: close the code blocks that left mcp.md sections rendering as code
Three examples in docs/mcp.md (Flatten Transparency, Flattener Preview,
Object > Expand) had lost their closing fence in earlier merges, so every
section after them rendered inside a code block. The fences are balanced
again and no heading sits inside a block.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 08:51:44 +07:00
BFlat a31f212021 Merge pull request #70 from storytold/pr/m4-place
M4: Place as an engine command, drag and drop, the loaded place cursor (M4.24, M4.25)
2026-10-05 08:50:42 +07:00
bflatasticandClaude Opus 5.5 76b7d960f2 M4.25: Drop files on the canvas to place them; several placed files load the place cursor
Files dropped on the canvas of an open document are placed at the drop point (linked; Shift
embeds); dropped on the tab bar or with no document open they open and join Open Recent Files.
The canvas is outlined while files are dragged over it. On the web, drag events give the drop
point and the files arrive through the inbox.

File > Place picks several files. file.place.queue loads the place cursor (the `place` tool):
a click places the current file at 100% with its top-left corner there, a drag places it at the
dragged size with its aspect kept, the arrow keys cycle the files and Esc discards one; the
previous tool returns after the last. The cursor shows the file's thumbnail and a count badge.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 08:42:30 +07:00
bflatasticandClaude Opus 5.5 20e0935116 M4.24: File > Place as an engine command: images at their physical size, SVG/PDF/native as one group
file.place {path | name+dataBase64, link, template, replace, at, rect, page, crop} places a
file as one undo step without touching the clipboard. Raster images come in at 100% of the
resolution their file declares (PNG pHYs, JFIF/EXIF, TIFF, BMP; 72 ppi otherwise), linked to
their path by default; SVG becomes one group with its embedded images; a PDF/.ai page or a
native document's artboard becomes one clipped group. The images, symbols, patterns and
swatches the art uses join the document (renamed on conflict). Replace keeps the replaced
object's stacking place and transform; Template puts the art on a new locked template layer
below the current one. file.place.info and image.info report size, ppi and colour mode.

File > Place picks a file and opens the Place dialog (Link, Template, Replace); the web picks
through the inbox. The Control bar shows Linked File/Embedded, the file name, colour mode and
ppi of the selected image.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 08:42:30 +07:00
BFlat 26246980e3 Merge pull request #69 from storytold/pr/m4-document-setup-new-document
M4: Document Setup depth; New Document with preset categories, details column and More Settings (M4.20, M4.21)
2026-10-05 08:41:16 +07:00
bflatasticandClaude Opus 5.5 6afcacbd91 M4.21: New Document with preset categories, details column and More Settings
File > New opens a New Document dialog in the reference app's layout:
category tabs (Recent, Saved, Mobile, Web, Print, Film & Video, Art &
Illustration, Branding, Social) over cards of presets generated in code
(page-proportioned thumbnail, neutral name, size with units), and a
Preset Details column: name with Save Preset, width with the units
dropdown, height, portrait/landscape toggles, artboards, linked bleed,
Background Contents with its chip, collapsible Advanced Options (colour
mode, raster effects, preview mode), More Settings, Close and Create.
More Settings is the classic form of the same fields (profile and size
lists, artboard layout buttons, spacing and columns, Templates...).
Choosing a preset fills the fields; editing one makes them custom.

file.new takes every setting (preset, name, orientation, artboards with
artboardLayout {layout, columns, spacing, rightToLeft}, bleed,
backgroundContents, colorMode, rasterEffectsPpi, previewMode; sizes may
carry units). file.newPresets lists the categories; file.newPresets.save
and .delete keep user presets in the preferences; Recent remembers the
last sizes. Print presets and plain sizes start in Preferences > Units >
General, screen presets in pixels. Rearrange All Artboards shares the
grid layout code. The Home screen shows the same preset cards.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 08:34:09 +07:00
bflatasticandClaude Opus 5.5 d527349f5a M4.20: Document Setup with bleed, transparency grid, paper and type options
File > Document Setup is a tabbed dialog over one engine command,
document.setup (no params: a query; any keys: one undo step;
document.setUnits stays as the units alias).

- General: units, bleed (four sides with a link toggle), Edit Artboards,
  Show Images in Outline Mode (greyscale pixels under the frame),
  Highlight Substituted Fonts/Glyphs (pink boxes on screen only).
- Transparency: grid size and colour presets or custom colours, Simulate
  Colored Paper, the flattener preset (built-in or saved) and Discard
  White Overprint (Overprint Preview keeps white overprints visible).
- Type: language with its quotes, Use Typographer's Quotes for the Type
  tool and Smart Punctuation, superscript/subscript size and position and
  small caps size (Character panel position/smallCaps; changing the
  setup restyles the text in the same undo step), text export (SVG text
  as text or outlines by default).
- The canvas draws a red bleed outline and the grid in the document's
  colours and cell size as one textured quad, also in rotated views; a
  white Background Contents exports raster formats opaque.

Model: Document.setup (DocSetup, defaulted, skipped when default) and
CharStyle position/small_caps; old files load unchanged.
tests_transparencygrid's helper now finds the grid by its texture (the
grid is one textured mesh instead of per-cell rectangles).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 08:28:16 +07:00
BFlat 25df58e722 Merge pull request #68 from storytold/pr/m4-svg-export-options
M4: SVG Options, area type and gradients in SVG export, ids and names, SVGZ (M4.26–M4.30)
2026-10-05 08:04:25 +07:00
bflatasticandClaude Opus 5.5 96aba71759 M4.30: SVGZ read and write
svgz is a writable format with the SVG options (document.export,
serialize, save, Export for Screens): exactly the SVG export, gzipped.
SVGZ is recognised by its extension or the gzip magic bytes and opens,
places and pastes like SVG (clipboard.importSvg takes dataBase64 of SVG
or SVGZ); Export As SVG or Save As to a .svgz name writes it
compressed. Gzip lives in the svg crate (pure-Rust flate2, builds for
wasm) and unpacking stops at 512 MB.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 07:58:10 +07:00
bflatasticandClaude Opus 5.5 b75ed0877d M4.29: object ids and names survive the SVG round trip
Layer Names writes readable ids plus data-name with the original name
whenever the id differs; Minimal writes only the ids definitions need;
Unique prefixes every id and CSS class with a content hash, so SVGs
inlined in one page never collide. Import names objects and layers from
data-name, inkscape:label, serif:id or aria-label.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 07:57:44 +07:00
bflatasticandClaude Opus 5.5 32252c68ea M4.28: SVG gradient export fidelity
Character gradients on live type export as url(#…) spanning the
laid-out text (point, area, on-path and outlined type, as on the
canvas); character stroke gradients span the text grown by half the
weight. Identical gradients share one def, and a swatch gradient takes
the swatch's name as its id. Midpoints are written as extra stops marked
data-vc-midpoint, which import turns back into midpoints.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 07:56:54 +07:00
bflatasticandClaude Opus 5.5 1982ecf98d M4.27: area type and rich text in SVG export
Every laid-out line of type is written at its own position (wraps,
indents, tabs, hyphenation and all caps as on the canvas): a positioned
tspan per style run and, on justified lines, per word. Centred and
right-aligned lines are anchored at their centre or right end, so they
stay aligned in a viewer whose font differs. Leading comes from the
layout's baselines, baseline shift is written as dy, horizontal scale as
textLength, vertical scale as the size, tracking and manual kerning as
letter-spacing. The fewerTspans option (engine and dialog) writes one
positioned tspan per line.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 07:56:32 +07:00
bflatasticandClaude Opus 5.5 4a3859c69b M4.26: SVG Options in the engine, a dialog and MCP
document.export, serialize and save, and the Save As / Save a Copy UI
commands, take the SVG options flat or as svg: {…}: styling
(presentation, style, entities, css), outlineText, images (embed or
link; linked files are written next to the SVG), objectIds (layerNames,
minimal, unique), decimals 1–7, minify, responsive, useArtboards and
range "all" (one SVG per artboard), preserveEditing (the SVG reopens as
the full document) and metadata. Unknown keys are rejected and
document.formats lists every option with its default. Results carry the
SVG writer's warnings.

Save writes SVG to an .svg path and Save again reuses its options.
Export As SVG and Save As / Save a Copy to .svg open SVG Options (first
use: Internal CSS and Responsive, then the last-used choices) with a
read-only code view. Save a Copy no longer retargets the document.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 07:55:59 +07:00
BFlat 2df7edd8c9 Merge pull request #67 from storytold/pr/preferences-units
Preferences ▸ Units drive every length the UI shows and reads (M14.5)
2026-10-05 07:52:11 +07:00
bflatasticandClaude Opus 5.5 3b99df3b9a M14.5: Preferences > Units drive every length the UI shows and reads
The General unit is the active document's units: Preferences > Units >
General sets them (one undo step) and is the units new documents start
in (and the unit shown with no document open); Document Setup changes
only the document. The Transform panel, Properties, the Control bar, the
Info panel, rulers, the status bar, Align spacing, Tabs, paragraph
indents, Pattern Options, dialog distances (Move, shape sizes, path
dialogs, Artboard Options, effect distances, Transform Each, parameter
dialogs), New Document and the canvas measurement labels (smart-guide
sizes, moves, the Measure tool, the Live Corners radius) all follow it,
live. Units > Type drives font size, leading and baseline shift; Units >
Stroke also reaches the Appearance panel and the Magic Wand weight
tolerance. Typed units ("5 mm", "12 pt") work in any field; all ten
units are choices; length preferences show in their unit and accept a
unit; offset/simplify/grid/type-size params read typed units. Typed text
starting with a multi-byte character no longer panics the parser.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 07:43:41 +07:00
BFlat 0e31fc92a2 Merge pull request #66 from storytold/pr/m4-pdf-options
M4: PDF settings, Save PDF dialog, export warnings and Summary (M4.31, M4.32)
2026-10-05 07:30:01 +07:00
bflatasticandClaude Opus 5.5 a40bce615a M4.32: PDF warnings, Summary section, View PDF after Saving and status text
document.export and document.serialize return the encoder's warnings (PDF:
options not applied yet, features approximated or left out, overprint).
document.pdfSettings lists the options that differ from the defaults and
the warnings (includeDocument adds the active document's own from an
in-memory export); the dialog's Summary section shows both. View PDF after
Saving opens the written file as a file:// URL through Services.open_url;
the status line reports the notes. The PDF writer's raster-effects warning
now names what it leaves out (objects of a kind, fills, strokes) instead of
claiming raster effects are never exported.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 07:22:27 +07:00
bflatasticandClaude Opus 5.5 4304a7c0b1 M4.31: Save PDF dialog and document.exportPdf with PDF settings
PdfSettings (serde, camelCase) is the Save PDF model: Standard, Compatibility
PDF 1.4-2.0, General (Preserve editing, Thumbnails, Fast web view, View after
saving, Create layers), Compression, Marks and Bleeds, Output, Advanced and
Security. PdfOptions = settings + pages, title and date.

document.exportPdf {path?, preset?, artboard?|artboards?|range?, standard?,
compatibility?, ...sections} -> {path|dataBase64, bytes, warnings} applies the
options over the preset (null keeps the preset's value); PDF/X, passwords,
PDF/A-2b at 2.0 and out-of-range values are refused; options accepted but not
applied yet come back as warnings. document.export {format: pdf} and
document.formats take and list the same options.

The Save PDF dialog (file.export.pdf, ui.savePdfDialog) has Preset,
Standard and Compatibility on top and a section list; it runs the export
before asking for a path, so bad options never open a save dialog.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 07:22:27 +07:00
BFlat b0a8d78926 Merge pull request #65 from storytold/pr/m4-svg-import
M4: SVG import units and text fidelity (M4.18, M4.19)
2026-10-05 07:22:06 +07:00
bflatasticandClaude Opus 5.5 5c58ebcb32 M4.19: SVG text import fidelity — text keeps its place, group, clip and mask; textPath, per-character positions, weights, spacing, paints and CSS selectors survive
Each <text> is swapped for a placeholder group before usvg runs, so the text keeps its z-order,
parent group, clip, mask, opacity, link and <use> instances, and usvg resolves its gradient and
pattern paints (in text space). <textPath> becomes type on a path (startOffset, side, anchor),
vertical writing-mode type on a vertical path. Per-character x/y/dx/dy/rotate lists become line
breaks (bounded), kerning (absolute x measured against the layout), baseline shift and rotation;
baseline-shift, numeric and relative weights (style names), letter/word spacing, kerning and the
character stroke's cap, join, miter and dashes are kept. The style cascade supports type, #id,
multiple-class, attribute, descendant and child selectors with !important and specificity.
<pattern> paints become pattern swatches. The import fuzz covers the new attributes and CSS.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 07:20:10 +07:00
bflatasticandClaude Opus 5.5 bc17c1e635 M4.18: SVG import units — absolute lengths keep their physical size, px map 1:1 to pt, document units follow the file
A pixel (and a unitless user unit) is a point and absolute lengths convert at 72 pt per inch
(`font-size="12pt"` is 12 pt, `1in` is 72 pt); a root size in absolute units keeps the physical
size main already gave it (`210mm` opens as a 595.28 pt artboard, user units being CSS pixels of
it). The document's units follow the unit of the root width (pixels when it has none). Text font
sizes honour their units (em/ex/% relative to the parent size, CSS size keywords), as do text
positions, letter spacing, stroke widths and dashes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 07:09:06 +07:00
BFlat 39ce7b0e01 Merge pull request #30 from storytold/harden/no-panics
Robustness: VectorCraft never crashes — no panics in shipped code
2026-10-05 06:50:04 +07:00
bflatasticandClaude Opus 5.5 8ac84dde20 M14.4: robustness docs name the library fuzzing and main's brands gate
docs/development.md lists the library files import_fuzz now covers, and the
PR template's CI checklist includes `cargo xtask brands`, which main added
after the no-panics branch was cut.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 06:40:34 +07:00
bflatasticandClaude Opus 5.5 0744347065 M14.4: tests main gained follow the no-panic lint rules
As the branch does for older tests: `panic!("…")` instead of
`unreachable!()` in test code (clippy.toml only allows unwrap, expect and
panic there), and the integration tests main added (CLI file I/O, render
gradient text and stroke geometry, SVG export suites) opt out of the
unwrap/expect/panic lints. No test logic changed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 06:40:34 +07:00
bflatasticandClaude Opus 5.5 8d0fae610d M14.4: fuzz the library loaders and main's new SVG import paths
import_fuzz now also feeds garbage and mutated `.vcswatches`, `.gpl`,
`.vcstyles` and `.vcflattener` files through `swatch.library.load` /
`graphicStyle.loadLibrary` / `flattener.presets.import`, uses what loads
(adds and applies the swatches and styles, previews and flattens with the
presets) and renders and exports the result. The SVG generator gains `<a>`,
Lab colours, mask options (`mask-type`, `data-vectorcraft-mask`) and paint
attributes. `PROPTEST_CASES` now raises the case count as the file's docs
say (an explicit `cases: 64` used to override it).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 06:40:34 +07:00
bflatasticandClaude Opus 5.5 7fb07bb3db M14.4: as_chunks for the pixel loops main gained since the no-panics branch
Same treatment as the branch's `as_chunks` commit (Rust 1.99's
`chunks_exact_to_as_chunks` lint) for the flattener's coverage pass, the
CMYK ink compositor, the Flattener Preview highlight and four test helpers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 06:40:34 +07:00
bflatasticandClaude Opus 5.5 1a5f7f6441 M14.4: no panics in the shipped code main gained since the no-panics branch
The M3/M4 work added ten panic sites the new workspace lints deny:
- doc: the lens/taper width profiles fall back to a uniform profile
  instead of `expect` (the presets are a constant table, covered by tests).
- engine: `FlattenOptions::default` builds the medium preset directly
  (`builtin`), `apply` skips an empty group instead of `expect`, the
  writable-format fallback reports an error instead of `expect`, and the
  new-art template's stroke comes back as an `Option` (it always has one)
  instead of `expect`.
- tools: the freeform gradient drag returns no actions for a grab it never
  starts (was `unreachable!`), and the gradient tool's release takes the
  gesture with `if let` instead of `expect`.

Behaviour on the success paths is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 06:39:18 +07:00
Brandon ThomasandClaude Opus 5.5 3e323bfa2a Robustness: VectorCraft never crashes — no panics in shipped code
Shipped code no longer unwraps, expects or panics: every one of the 124
unwrap()/expect()/panic!/unreachable! sites outside tests now handles the
failure (Result/Option, ?, let-else, defaults) and reports errors to the user.

- Lints: workspace clippy denies unwrap_used, expect_used, panic, todo,
  unimplemented and unreachable; clippy.toml allows them in tests, and
  integration tests, examples and testkit opt out explicitly.
- Safety net (vectorcraft_engine::guard): a panic in a top-level command rolls
  the document back and returns EngineError::Internal; a panicking tool is
  reset; the MCP server answers with an internal error and keeps serving; the
  UI frame and each control request are guarded.
- APIs that hid failures now return them: Rendered::to_png/to_jpeg/to_webp
  return Result (JPEG/WebP errors used to write empty files),
  FontDb::face returns Option, Region::top returns Option.
- Fuzzing: engine/tests/import_fuzz.rs feeds garbage, hostile and mutated SVG
  and PDF through import → render → export (30k cases locally, no panics).
- Docs: AGENTS.md/CLAUDE.md rule, docs/development.md "Robustness" section,
  README pointer and a PR template checklist.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 06:28:59 +07:00
Brandon ThomasandClaude Opus 5.5 0f241aac9f clippy: as_chunks for fixed-size pixel and pair chunks (Rust 1.99 lint was red on main)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 06:24:06 +07:00
BFlat c4236e1bb2 Merge pull request #64 from storytold/pr/scale-strokes-off-by-default
M3: Scale Strokes & Effects is off by default
2026-10-05 06:17:50 +07:00
bflatasticandClaude Opus 5.5 a0b694dcd8 M3.66: Scale Strokes & Effects is off by default
New preferences start with Scale Strokes & Effects off, as in Illustrator:
scaling an object keeps its stroke weights, dashes and effect distances unless
the option (or `strokes: true`) is on. Preference files that already store the
option keep their value.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 06:17:36 +07:00
BFlat 5750786e63 Merge pull request #63 from storytold/docs/roadmap-m3-complete
Roadmap: M3 Paint & appearance complete
2026-10-05 05:57:37 +07:00
bflatasticandClaude Opus 5.5 b9fa2d27fd Roadmap: M3 complete (M3.7–M3.98)
M3 is done: the M3 row, the shipped list (swatches, colour, gradients, strokes,
appearance, masks, transparency, graphic styles, and the title bar) and the
colour, stroke and appearance parity rows cover everything that landed through
#62, with the few known gaps named. M6 notes the Boolean precision fix and M14
the custom title bar and content-sized dialogs. The totals are summed from the
rows again (they had drifted), and the method note records M3's measured pace.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 05:57:21 +07:00
BFlat bd7ed58376 Merge pull request #62 from storytold/pr/m3-gradient-on-strokes
M3: gradient within, along or across a stroke (M3.83)
2026-10-05 05:51:11 +07:00
bflatasticandClaude Opus 5.5 025d758abe M3.83: gradients within, along or across a stroke
The Gradient panel's Stroke buttons now work: with the Stroke proxy on a
linear or radial gradient they lay it within the stroke (placed on the
page, as before), along the path (start to end of each subpath) or across
it (left edge to right edge; inside/outside strokes span their visible
side). `paint.editGradient {stroke: true, strokeMode}` sets it (new art
too with nothing selected); `document.inspect` reports
strokeOptions.gradientMode. Model: StrokeLayer.gradient_mode (default
Within, not written).

Shared geometry in effects::stroke::gradient: ribs on the bisectors of
the flattened path (fans round sharp corners, widened under arrowheads,
following width profiles) cut slices each painted with a linear piece of
the gradient (Gradient::span). The canvas and raster export clip them to
the stroke's outline and arrowheads, grown a pixel and composited with
copy so there are no seams and translucent stops paint once. SVG and PDF
write the same slices clipped to the outline, with a warning (new
vectorcraft_svg::export_with_report). Outline Stroke and Expand make
gradient meshes clipped to the outline. Mesh quads now grow along their
edges so thin quads show no seams. Dashes, profiles and arrowheads keep
working in both modes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 05:47:54 +07:00
BFlat ccdb1b30f6 Merge pull request #61 from storytold/pr/eyedropper-test-flake
Tests: the eyedropper image-sampling test no longer flakes (colour settings changed by parallel tests)
2026-10-05 05:37:48 +07:00
bflatasticandClaude Opus 5.5 5a0e6be852 M3.52: stop the eyedropper image-sampling test from flaking
The engine unit tests share one process, and two colour-management tests
switched the process-wide Color Settings (the working RGB space to the wide
gamut profile, Black Point Compensation off) for a moment. Any test that
showed or rendered a colour at that moment saw it through the wrong profile:
clicking_an_image_samples_its_pixel read #008181 instead of #008080.

- Move the two tests that change the Color Settings to their own test
  binary (crates/engine/tests/color_settings.rs), so no unit test can see
  non-default settings.
- The image-sampling test compares the stored colour, not its display hex.
- every_command_survives_empty_params toggles the process-wide proof view
  (Proof Colors, Overprint Preview, Separations), so it now takes the
  colour-management test lock like the tests that read that view.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 05:36:57 +07:00
BFlat 0038e00382 Merge pull request #60 from storytold/pr/m3-color-guide-limit-themes
M3: Color Guide Limit to Library, Edit or Apply without art, Color Themes panel (M3.95, M3.96)
2026-10-05 05:11:50 +07:00
bflatasticandClaude Opus 5.5 be648089be M3.96: Color Themes panel with a local theme library
Window → Color Themes: the Create tab makes a five-colour theme on a
harmony wheel (a harmony rule from the selected colour, colours moving
together; or Custom, each on its own), with a brightness slider, hex
field, current-colour picker and name; the My Themes tab lists saved
themes to edit, add to Swatches as a colour group, or delete. Themes are
kept in the preferences (Prefs::color_themes; no online service).

Commands: colorTheme.list, colorTheme.save {colors | color + rule, name?,
replace?}, colorTheme.delete, colorTheme.addToSwatches. Harmony::theme
and move_on_wheel live in the colour crate; the wheel is now a shared
widget (widgets::harmony_wheel) used by Recolor Artwork's Edit tab too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 05:08:28 +07:00
bflatasticandClaude Opus 5.5 81582c8d4f M3.95: Color Guide Limit to Library and Edit or Apply Colors without art
The Color Guide's library button opens a Limit to Library popup (None,
Document Swatches, the colour libraries): every harmony colour and
variation snaps to the nearest colour there (CIEDE2000), cached per
inputs so the grid isn't re-snapped every frame. `color.harmony` takes
`limitTo`, `ui.colorGuideLimit` sets the panel's limit, and Recolor
Artwork's Limit to Library also offers the document's swatches (one
shared engine helper, swatchlib::limit_palette).

Edit or Apply Colors opens Recolor with the harmony colours limited to
the same library; with no art selected the colours are the rows and OK
saves them as a new colour group.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 05:08:15 +07:00
BFlat 96a1a02436 Merge pull request #59 from storytold/pr/m3-freeform-canvas-focal
M3: freeform editing on the canvas; radial extent, aspect and focal point (M3.97, M3.98)
2026-10-05 04:48:55 +07:00
bflatasticandClaude Opus 5.5 d8eff17b9f M3.98: radial annotator extent ellipse, aspect handle and off-centre focal point
Radial gradients show a dashed extent ellipse: its handle across the bar
sets the aspect ratio, the ellipse elsewhere rotates it, and the dot inside
the centre ring drags the focal point (GradientGeom.focal) for an off-centre
radial. paint.setGradientGeom takes aspect (%) and focal ([x,y] | null), and
start/end may be left out; the focal point keeps its place in the ellipse as
the vector, aspect and object transform. It renders as a two-point radial,
exports and imports as SVG fx/fy and PDF two-point radial shadings, expands
to off-centre rings, and travels in gradient params and the native format.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 04:43:43 +07:00
bflatasticandClaude Opus 5.5 b8793eeaef M3.97: freeform points drag out to delete, spread ring drags, Lines mode draws lines
With the Gradient tool on a freeform gradient the selected point shows its
spread as a dashed ring with a handle; dragging either sets the spread. A
point dragged out of the object is removed on release, and double-clicking a
point opens the gradientStop popover, which now edits the selected freeform
point (colour, opacity, spread). In Lines mode successive clicks draw one
smooth line (with a rubber band to the pointer); clicking an existing point
continues the line from it, and Escape or a click off the art ends it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 04:43:43 +07:00
BFlat 37acaebf95 Merge pull request #58 from storytold/pr/m3-width-tool-new-art
M3: Width tool depth and the new-art appearance template (M3.64, M3.65)
2026-10-05 04:43:28 +07:00
bflatasticandClaude Opus 5.5 faf006e135 M3.65: new-art appearance template (stroke options and graphic styles with nothing selected, New Art Has Basic Appearance)
With nothing selected, Stroke panel edits (stroke.set / stroke.setAdvanced: cap, join, dashes,
arrowheads, profile...) and a graphic style clicked in the Graphic Styles panel
(graphicStyle.apply, add too) set up the next object drawn: its stroke options, fills, strokes,
effects, opacity and blend mode, linked to the style. The Appearance panel's New Art Has Basic
Appearance (appearance.setNewArtBasic, preference newArtBasic, on by default) now works: off,
new art takes the whole appearance of the last selection. paint.default resets the template,
appearance.newArt reports it, and with nothing selected the Stroke panel shows its stroke and
the Appearance panel its rows. PaintDefaults gains the template appearance, opacity, blend
mode and style.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 04:38:09 +07:00
bflatasticandClaude Opus 5.5 b79262d4f4 M3.64: Width tool depth: Width Point Edit, multi-select, Alt-copy and discontinuous points
Double-clicking a width point opens Width Point Edit (Side 1, Side 2, Total Width, a link
keeping the sides equal, Adjust Adjoining Width Points, Delete; dialog `widthPoint`, also
`ui.widthPointEdit`). Shift-click selects several width points, which drag and widen together
as one undo step; Alt-dragging a point's centre copies it (`stroke.widthPoint.copy`); dropping a
point onto another makes a discontinuous point (two points at the same t), and the stroke's
width steps there. `stroke.widthPoint.set` takes `adjustAdjoining`, keeps a discontinuous point
when only its widths change, and `stroke.widthPoint.remove` takes `indices`. Flipping a profile
along the path swaps the sides of its steps; `document.inspect` reports `widthPoints`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 04:38:09 +07:00
BFlat d9740931a5 Merge pull request #57 from storytold/pr/m3-cmyk-blending
M3: blend modes and opacity composite inks in CMYK documents (M3.90)
2026-10-05 04:37:52 +07:00
bflatasticandClaude Opus 5.5 9537eca5f7 M3.90: blend modes and opacity composite inks in CMYK documents
A CMYK document that shows transparency is drawn once per ink plane
(complemented C, M, Y; complemented K as a grey) so every blend mode,
opacity, group, knockout and effect composites inks, PDF-style; the
planes' inks are shown through the working CMYK profile (cached 4-D XYZ
table). Cyan multiplied over magenta now shows C100 M100. Opacity masks
keep screen luminance; RGB colours and placed images are separated
first. RGB documents and opaque CMYK documents keep the screen-colour
path.

PDF export of CMYK documents writes its transparency groups with
/CS /DeviceCMYK (luminosity mask groups stay RGB) and puts top-level
transparency in a non-isolated page-wide group so it blends in CMYK too.
Flatten Transparency composites CMYK documents ink by ink and makes CMYK
regions. Non-separable modes no longer give NaN for greys.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 04:30:06 +07:00
BFlat 6ee994239d Merge pull request #56 from storytold/pr/m3-recolor
M3: Recolor Artwork reduction, methods, presets and Edit tab; Edit Color Group (M3.78, M3.79)
2026-10-05 04:28:14 +07:00
bflatasticandClaude Opus 5.5 fcc0f4ca0f M3.79: Edit or Apply Color Group opens Recolor Artwork on a colour group
Double-clicking a colour group's folder in the Swatches panel, or the options
button (Edit or Apply Color Group) while a group is selected, opens Recolor
Artwork on the group: without art the rows are the group's colours and OK
rewrites the group; with art selected the art is reduced to the group's size,
takes its colours, and art and group change in one undo step. New
swatch.editGroup {group, colors, rename?} rewrites a group in order (art linked
to its global swatches follows); recolor.apply takes group, groupColors and
rename.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 04:20:27 +07:00
bflatasticandClaude Opus 5.5 fca068a0a7 M3.78: Recolor Artwork with colour reduction, methods, presets and Limit to Library
Recolor Artwork keys colours by identity (model and exact values), so CMYK
colours stay CMYK and lookalikes stay apart. recolor.reduce groups the
selection's colours into rows (k-means in Lab, weighted by use; tints of a
global swatch share its row) with Preserve White/Black/Grays and Limit to
Library; recolor.apply maps rows by Exact, Preserve Tints, Scale Tints, Tints
and Shades or Hue Shift; recolor.randomize shuffles or varies new colours.
The dialog has Assign (rows with merge, separate, exclude, randomize, method,
library) and Edit (hue/saturation wheel with linked or unlinked handles,
brightness, harmony rules) tabs, and Edit Colors gains Recolor with Preset
(1/2/3 Color Job, Color Library). Colour parameters accept colour keys.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 04:20:27 +07:00
BFlat 0c950aae0e Merge pull request #55 from storytold/pr/ui-dialog-stretch-test
UI: test that no dialog stretches with the screen
2026-10-05 04:13:34 +07:00
bflatasticandClaude Opus 5.5 1aac138b4f M14.1: a test that no shared-frame dialog stretches with the screen
Fourteen dialog openers (swatch, colour, style, flattener, expand, effect and
parameter dialogs) are drawn on a 1000 pt and a 2000 pt tall screen; each
dialog must be the same height on both, so nothing inside one fills the
available height again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 04:10:34 +07:00
BFlat 321d8e78cf Merge pull request #54 from storytold/pr/m3-scale-strokes-preview-bounds
M3: Scale Strokes & Effects complete, Scale Corners, Use Preview Bounds (M3.66, M3.67)
2026-10-05 04:10:17 +07:00
bflatasticandClaude Opus 5.5 65f0f34cd3 M3.67: Use Preview Bounds measures strokes in transforms, the bounding box and Align
With Use Preview Bounds on, the Transform panel, Properties and Control bar
X/Y/W/H, the Selection tool's bounding box, Align, Distribute and
Distribute Spacing measure visual bounds (the whole stroke). setBounds sets
the visual box, scaling the path so that kept or scaled strokes land on
the typed size. object.align/distribute/distributeSpacing take
bounds?: "preview"|"geometric"; the Align flyout item shows and toggles the
preference through prefs.set.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 03:59:37 +07:00
bflatasticandClaude Opus 5.5 5afc78a100 M3.66: Scale Strokes & Effects scales dashes and effect distances; Scale Corners works
Scaling with Scale Strokes & Effects on now scales stroke weights, dash
lengths and dash offsets and every distance parameter of object, fill and
stroke effects (groups and layers too), from new length metadata in the
effects catalogue. Off, nothing painted changes size and type keeps its
character strokes' weight. Scale Corners off keeps live corner radii.
object.scale/transform/transformEach take strokes?/corners? (default: the
preferences) and journal the values they used. The Scale dialog and a new
Transform Each dialog get both checkboxes, kept as the preferences on OK;
the panels' toggles go through prefs.set.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 03:59:37 +07:00
BFlat f3397fadc6 Merge pull request #53 from storytold/pr/m3-lab-spots
M3: spot colours defined in Lab, Spot Colors options (M3.85)
2026-10-05 03:55:29 +07:00
BFlat b32284aeae Merge pull request #52 from storytold/pr/m3-attributes-registration
M3: Attributes panel; Registration colour, trim marks and live Crop Marks (M3.76, M3.77)
2026-10-05 03:54:53 +07:00
bflatasticandClaude Opus 5.5 ea61d34a93 M3.85: spot colours defined in Lab, with Spot Colors options for Lab values or CMYK equivalents
Colours gain a CIE Lab model (`Color::Lab {l,a,b}`, serde tag `lab`), handled through the
CMS (display, separation, conversions, gamut), tints (toward paper white), keep_model, harmonies,
recolouring, blends, Info and the Color panel. Swatch Options gets a Lab mode
(`swatch.edit {mode: "lab"}` / `{color: {l,a,b}}`), and colour params accept `{l,a,b}`.

Swatches panel → Spot Colors… (`ui.spotColors`, dialog `spotColors`) runs `swatch.spotOptions
{useLab}` (Document.spot_use_lab, default on): Lab spot colours show and separate from their Lab
values, or art linked to them takes their working-CMYK equivalents, as one undo step. PDF export
writes Lab spot inks as Separation spaces with a Lab alternate (tint function from paper white),
or a DeviceCMYK one with CMYK equivalents.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 03:46:57 +07:00
bflatasticandClaude Opus 5.5 c1df6f0621 M3.77: [Registration] swatch on every plate, trim marks on every artboard, Japanese marks and live Crop Marks
[Registration] is a built-in swatch that prints 100% on every plate: Separations
Preview shows it on each process and spot plate and PDF export writes it as
/Separation /All. It can't be edited, moved, duplicated, merged or deleted;
swatch.list shows it after None and the Swatches panel applies it as a swatch.
Object > Create Trim Marks strokes the marks in Registration and marks every
artboard when nothing is selected ({style?, allArtboards?}). The preference
japaneseCropMarks (General) switches to Japanese marks: double lines at the
trim and bleed edges plus centre marks. Effect > Crop Marks (cropMarks) is a
live effect whose marks follow the object; rendering, SVG/PDF export and
Expand Appearance draw them. The mark geometry lives in doc::marks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 03:46:04 +07:00
bflatasticandClaude Opus 5.5 4591c85845 M3.76: Attributes panel with overprint, centre point, path direction, fill rule, image map, URL and note
Window > Attributes (Cmd+F11) shows Overprint Fill/Stroke, Show/Don't Show
Center, Reverse Path Direction Off/On, the non-zero / even-odd fill rule,
Image Map, a URL field with recent URLs and a Browser button, and a note.
New commands attributes.set and path.setFillRule; path.reverse takes ids and
reversed; attributes.info reports every value. Objects keep the attributes in
Node.attrs. SVG export wraps linked objects in <a>, and import reads links
back. The canvas draws the centre point of selected objects that show it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 03:46:04 +07:00
BFlat 9fcefde3f9 Merge pull request #51 from storytold/pr/pathops-near-horizontal-edges
Pathops: Booleans keep their corners on almost-horizontal edges; deterministic property tests (M6.10)
2026-10-05 03:45:49 +07:00
bflatasticandClaude Opus 5.5 be7006ccf5 M6.10: Boolean operations hold their area identities on almost-horizontal edges
The sweep compares a curve with another segment over a y-span shorter than
its tolerance by bounding boxes only, so an edge rising by less than that
tolerance (e.g. a rectangle edge cut through a circle's cap, whose computed
intersection end sits ~1e-12 off the horizontal) was mis-ordered and the
result lost a corner: xor/difference/area disagreed by up to 10%. Every
sweep input now snaps on-curve y values within the tolerance to one level
(handles follow and are levelled with their anchor), so such edges become
exact horizontals, which the sweep handles exactly.

- tests/regressions.rs: the six minimal failures found by the properties,
  the root cause in isolation, and the self-crossing "star" polygon.
- The star-polygon strategy rejected no angular step of half a turn or
  more, so it sometimes drew self-crossing polygons (the shoelace failure).
- Property suites run from a fixed seed (PROPTEST_CASES / PROPTEST_RNG_SEED
  still override), so CI cannot fail at random.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 03:36:30 +07:00
BFlat bc59c53b5a Merge pull request #50 from storytold/pr/m3-object-expand
M3: Object > Expand dialog; gradient fills expand to objects or a mesh (M3.84)
2026-10-05 03:32:51 +07:00
bflatasticandClaude Opus 5.5 705976fd96 M3.84: Object > Expand dialog; gradient fills expand to a mesh or N objects
Object > Expand… opens a purpose-built dialog (Object, Fill and Stroke
checkboxes, disabled when the selection has nothing for them; Expand
Gradient To: Gradient Mesh or Specify N Objects, default 255). Every
option now does something:
- Object: type to outlines, live shapes to paths, effects baked.
- Stroke: strokes outlined into filled paths.
- Fill: linear/radial gradient fills become N solid rectangles or
  concentric ellipses, or a gradient mesh with lines where the colour
  changes, inside a clip group shaped like the object; freeform
  gradients become a mesh shaped like the object. Colours keep their
  stops' colour model. With Fill off gradient fills stay live.
object.expand {} defaults match the dialog (stroke now defaults on);
new query object.expand.info and UI command ui.expandDialog.
Create Gradient Mesh on a gradient-filled object takes the colours the
gradient paints at each point (GradientMesh::for_path_with, from_grid,
highlight).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 03:25:33 +07:00
BFlat 4757dd265c Merge pull request #49 from storytold/pr/m3-mask-view-clip-paint
M3: view only the mask, lossless SVG mask options, per-document transparency grid, paint on clipping paths (M3.86–M3.89)
2026-10-05 03:24:19 +07:00
bflatasticandClaude Opus 5.5 3b2f46137a M3.89: a clipping path's fill paints behind the clipped art, its stroke over it
Paint given to a clipping path (paint commands with its id) now shows: its
fill paints inside the clip behind the clipped art and its stroke over the
art, unclipped, on the canvas and in SVG and PDF. Node::clip_paint splits the
clipping path into its fills and its strokes (type: its characters' too) for
all three outputs; the renderer caches the parts per clipping path. Clip group
visual bounds take in the stroke. Make Clipping Mask still leaves the clipping
path unpainted, as the reference app does; Ungroup no longer wipes a painted
clipping path's appearance (Release already kept it).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 03:11:04 +07:00
bflatasticandClaude Opus 5.5 799b507564 M3.88: Show Transparency Grid is per-document engine view state
view.transparencyGrid {on?} -> {on} is now an engine command (DocState.
transparency_grid; not undoable, doesn't dirty the document), so agents can
turn the grid on headless and each open document keeps its own setting. The
menu item, its Show/Hide label, the shortcut and the Properties panel button
use the same id; the canvas draws the grid for the active document only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 03:11:04 +07:00
bflatasticandClaude Opus 5.5 1603729ec3 M3.87: SVG opacity masks keep their Clip and Invert options
Exported masks carry data-vectorcraft-mask="noclip invert" (the options that
differ from clipping, not inverted). Import restores the flags and the original
mask art, dropping the backdrop rectangle and inverting filter group that draw
the options in SVG; a single mask object comes back as itself, not wrapped in a
group. Masks from other apps import as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 03:11:04 +07:00
bflatasticandClaude Opus 5.5 03571affbd M3.86: Alt-click the mask thumbnail to view only the mask
transparency.viewOpacityMask {on?, id?} shows only the opacity mask on the
canvas as greyscale coverage (luminance, clip and invert applied; the rest of
the art hidden) and enters mask editing; called again it shows the artwork and
keeps editing. The Transparency panel's mask thumbnail runs it on Alt-click and
is outlined in the accent colour while the mask is viewed. The state is
DocState.mask_view (shown while that mask is edited: DocState::shown_mask) and
reaches the renderer as RenderOptions.mask_view.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 03:11:04 +07:00
BFlat cbdef4ea1f Merge pull request #48 from storytold/pr/m3-graphic-style-libraries
M3: graphic style libraries with .vcstyles save and load (M3.80)
2026-10-05 03:07:34 +07:00
bflatasticandClaude Opus 5.5 874a287958 M3.80: graphic style libraries in the library panel, with .vcstyles save and load
Window > Graphic Style Libraries and the Graphic Styles panel's library button open
read-only libraries of original styles generated in code (Shadows and Glows, Outlines
and Rules, Hand-Drawn, Gradient Finishes, Shape Effects, Blends and Transparency) in
the shared library panel. Clicking a style adds it and applies it to the selection as
one undo step (Alt: on top). Save Graphic Style Library writes .vcstyles JSON (styles
unlinked from swatches, with the patterns they paint with) to the user library folder
(User Defined) or a file; Other Library loads one, or another document's styles.

Commands: graphicStyle.libraries, graphicStyle.library, graphicStyle.addFromLibrary,
graphicStyle.saveLibrary, graphicStyle.loadLibrary; UI: window.graphicStyleLibrary
(.other), ui.saveGraphicStyleLibrary, window.userGraphicStyleLibrary1-10. The user and
loaded library bookkeeping is shared with swatch libraries.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 03:06:13 +07:00
BFlat 2b07aa2ac9 Merge pull request #47 from storytold/pr/m3-stroke-depth
M3: width profile library, thirty more arrowheads, whole-stroke bounds and hit-testing (M3.61–M3.63)
2026-10-05 02:59:27 +07:00
bflatasticandClaude Opus 5.5 c1dc860f1d M3.63: visual bounds and clicks take in the whole stroke
Paths and compound paths now measure their visual bounds along their shape:
the body (inside/outside alignment, the width profile's widest point), the
tips of the miter spikes the limit keeps, projecting caps' corners and the
arrowheads' reach. A rectangle's right-angle miters stay within half the
weight (Fit to Selected Art, Rasterize and all-art SVG export get tighter,
exact boxes); Appearance::outset is the conservative reach for anything else.
Clicks hit what the strokes paint: outside strokes outside the path (0.8 x the
weight out), inside ones inside, the profile's width where clicked, caps,
spikes and heads. Click culling keeps a cheap box (hit test 0.34 ms per click
on the 50k-path budget). The subpath/tangent helpers move from the stroke
geometry into vectorcraft_geom::bez so both share them; a cross-check test
holds every painted point of the real stroke geometry inside the bounds and
hittable.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 02:55:23 +07:00
bflatasticandClaude Opus 5.5 fdad11a99c M3.62: thirty more generated arrowheads with rendered previews
Arrowhead gains 30 original shapes generated in code, appended after the first
ten so saved names stay stable: Barbed, Half Arrow (left/right), Concave,
Double Arrow, Chevron, Feather, Swallowtail, Reverse Triangle, Triangle to Bar,
Kite, Leaf, Drop, Half Circle, Oval, Target, Tag (+ open), Diamond (open),
Hexagon (+ open), Star, Cross, Plus, Double Bar, Dot on Bar, Slash, Double
Slash, Bracket and Fork. Each is drawn in local units of the head's weight
inside the usual 4 x 4 box, with its own stop for the stroke under it.
Arrowhead::label() names them in the menus. The Stroke panel's arrowhead
dropdowns render every head as the canvas draws it (cached textures, a shared
widgets::doc_preview that the Brushes panel now uses too) in a scrolling list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 02:55:23 +07:00
bflatasticandClaude Opus 5.5 3e73ad8581 M3.61: width profile library: Add to Profiles, Delete Profile, Reset Profiles
The Stroke panel's Profile list now holds saved profiles next to the built-ins,
kept with the preferences (Prefs.width_profiles). Add to Profiles… names the
selected stroke's variable width, Delete Profile removes the selected stroke's
saved one (built-ins can't be deleted), Reset Profiles removes them all.
Three more generated built-ins (Pinch, Teardrop, Wave). The dropdown (Stroke
panel and Control bar) lists saved profiles and draws a custom profile's own
silhouette. Commands: stroke.widthProfile.add/delete/reset/list; stroke.set
{profile} takes a built-in id or a saved name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 02:55:21 +07:00
BFlat c73aa380e1 Merge pull request #46 from storytold/pr/m3-flattener-ui
M3: Flatten Transparency dialog, flattener presets, Flattener Preview panel (M3.92–M3.94)
2026-10-05 02:42:33 +07:00
bflatasticandClaude Opus 5.5 953024cc35 M3.94: Window > Flattener Preview shows what flattening would rasterize, outline and change
flattener.preview {highlight, overprints?, preset?|options?, ids?} reports, without changing the
document, the transparent and affected objects, patterns, outlined strokes and type, rasterized
complex regions, all rasterized areas and flat-colour regions (FlattenReport, worked out by the
flattener's own plan without rendering images). The panel previews a snapshot taken on Refresh,
greyed with the chosen highlight in red, zoomable (click, Alt-click, drag, double-click); its
Overprints, preset and options (Show Options) set how it flattens, and its menu saves them as a
preset. ui.flattenerPreview drives it; the settings persist with the UI state.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 02:36:43 +07:00
bflatasticandClaude Opus 5.5 1dc158cafe M3.93: Edit > Transparency Flattener Presets… manages built-in and saved flattener presets
Saved presets live in Prefs.flattener_presets (persisted with the preferences) beside the
built-in High, Medium and Low Resolution ones, which stay read-only. New commands:
flattener.presets.list / save / delete / import / export (a .vcflattener JSON file; opening one
imports it). Any saved preset name works as `preset` wherever flattener options are taken
(Session::flatten_options). The manager dialog lists the presets and edits the selected saved
one in place; the Flatten Transparency dialog lists saved presets and gains Save Preset….

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 02:36:28 +07:00
bflatasticandClaude Opus 5.5 936721fbf5 M3.92: Object > Flatten Transparency… opens a dialog with presets, options and a live preview
The dialog offers the built-in presets, the raster/vector balance, both resolutions and the
outline and preserve switches; Preview flattens on the canvas through the interaction and OK
keeps it as one undo step (object.flattenTransparency). The options editor is shared for the
preset manager and the Flattener Preview panel. Drivable as dialog `flattenTransparency`
through ui.flattenTransparencyDialog.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 02:35:27 +07:00
BFlat 3675156c4e Merge pull request #45 from storytold/pr/m3-tints-linked-stops
M3: tints of global and spot colours, gradient stops linked to swatches (M3.59, M3.60)
2026-10-05 02:34:12 +07:00
bflatasticandClaude Opus 5.5 7227e295ea M3.60: gradient swatches and stops linked to global and spot swatches
Applying a gradient swatch records it as the gradient's swatch (the Swatches panel highlights
it and the Gradient panel's swatch menu marks it). A stop given a global or spot swatch (and a
tint) in paint.editGradient / a gradient paint's stops, dropped from the Swatches panel or
picked in the stop popover stays linked: editing the swatch recolours it, in art and in
gradient swatches, deleting it unlinks it. Spot stops separate on their plate, and a gradient
whose stops are all tints of one spot ink (or paper white) exports to PDF as a Separation
shading; gradients mixing models are written in one colour space (the PDF writer requires it;
mixed models used to abort the export).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 02:29:19 +07:00
bflatasticandClaude Opus 5.5 b2ececc7b4 M3.59: tints of global and spot colours, tint swatches and Global colour balance
A colour linked to a global or spot swatch keeps a tint (Paint::Solid.tint, 1 by default and
left out of files at 100 %): paint.setFill/setStroke {swatch, tint} apply the swatch at that
percentage, swatch edits recolour every linked colour at its own tint, and Color::tinted
resolves it (CMYK and Gray inks scale, RGB mixes toward white). swatch.new saves a tint as a
tint swatch ("Ink 40%") linked to its base. Spot tints separate as that percentage of their
plate (Separations Preview, PDF Separation value) instead of an ink-ratio guess. Adjust Color
Balance's Global mode (tint) shifts the tints of linked colours. The Color panel shows Tint
mode (the swatch chip, its name and a T slider) for linked colours; the Swatches panel
highlights the tint swatch in use. Gradient stops get the same link and tint fields (the
swatch walks cover them), so GradientStop is no longer Copy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 02:29:17 +07:00
BFlat e94748dc17 Merge pull request #43 from storytold/pr/m3-targeting-expand-appearance
M3: target circles and full Expand Appearance (M3.69, M3.70)
2026-10-05 02:20:06 +07:00
bflatasticandClaude Opus 5.5 b4ba4ecf0a M3.70: Expand Appearance turns fills, strokes, effects and brushes into objects
effect.expandAppearance now expands the whole appearance: each visible fill becomes a
path of its own and each stroke its outline (a brushed stroke its brush art), grouped
in paint order under the object's id and transparency; geometry effects are baked and
raster effects become an embedded image (shadows below the art, blur/feather/inner glow
replacing it). Type with effects or its own fills is outlined, and a group's or layer's
own fills and strokes are expanded among its members. The command is enabled whenever
an appearance isn't basic. Builds on bake_leaf (effects::expand_leaf / expand_art) and
shares the raster-effect image code with PDF export.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 02:16:02 +07:00
bflatasticandClaude Opus 5.5 b768b4a53b M3.69: target circles target layers, groups and objects; drag them to move appearances
Clicking a Layers panel target circle runs `layer.target {id}`: a layer gets its art
selected and becomes the target (`Selection.target`) of the appearance, effect,
transparency and opacity-mask commands, which then edit the layer itself; the
Appearance panel lists it. Dragging a circle onto another runs
`appearance.transfer {source, target, copy?}` (Alt copies), dropping it on the trash
clears it. Filled dots also mark groups and layers with fills of their own, masked
objects get a dashed underline, and while an opacity mask is edited the panel lists
only an `<Opacity Mask>` entry and the tab says so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 02:15:41 +07:00
BFlat a2adf729a7 Merge pull request #42 from storytold/pr/m3-proxies-eyedropper
M3: Fill/Stroke chip popovers, panel shortcuts, Eyedropper Options and modes (M3.51, M3.52)
2026-10-05 02:15:06 +07:00
BFlat 6a9b658443 Merge pull request #41 from storytold/pr/custom-titlebar-dragon-icon
UI: custom title bar on Windows and Linux; the dragon icon as the brand mark
2026-10-05 02:14:15 +07:00
bflatasticandClaude Opus 5.5 303689c8f4 M3.52: Eyedropper Options with Picks Up / Applies trees, Alt and Shift+Alt modes, image sampling
Double-clicking the Eyedropper opens Eyedropper Options (dialog
eyedropperOptions): raster sample size (point, 3x3, 5x5) and Picks Up /
Applies trees (transparency; focal fill colour, transparency, overprint;
focal stroke colour, transparency, overprint, weight, cap, join, miter,
dash; character and paragraph attributes). The options live in the
preferences (Prefs::eyedropper, eyedropper.setOptions, prefs key
eyedropper) and replace the earlier appearance/transparency switches.

appearance.copyFrom takes pickUp/apply overrides, reverse (Alt-click:
the selection's attributes onto the clicked object) and append
(Shift+Alt-click: add the source's fills and strokes). Type copies font,
size and paragraph attributes to type. Clicking an image samples its
pixels; sampled colours keep their colour model.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 02:08:10 +07:00
bflatasticandClaude Opus 5.5 2e6662c93b M3.51: Fill/Stroke chips open swatch and mixer popovers; panel shortcuts; Recolor quick action
The Control bar and Properties Fill/Stroke chips show the proxies' paints
("?" for mixed selections) and open a popover with the Swatches panel body
(Shift-click or the toggle: the Color panel's mixer); a click brings the
chip's proxy forward through paint.toggleActive {fill}. The Properties
panel offers Recolor for multi-colour selections. Window panel shortcuts
(Color F6, Color Guide Shift+F3, Appearance Shift+F6, Graphic Styles
Shift+F5, Stroke Cmd+F10, Gradient Cmd+F9, Transparency Shift+Cmd+F10)
run window.panel {panel}, show in the Window menu and are editable.

paint.invert / paint.complement and the "?" state honour the Appearance
panel's active item; objects without bounds still show their paints.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 02:05:33 +07:00
bflatasticandClaude Opus 5.5 512e96e7c8 M14.3: the dragon app icon is the brand mark
The mark left of Home (and in the About box) is now the VectorCraft app icon,
the engraved dragon from assets/app-icon/ (128 px PNG, include_bytes!), decoded
once per context into a mipmapped texture and drawn at 22 pt with the icon's own
rounded corners. The old code-drawn gradient square with a pen nib is removed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 02:00:05 +07:00
bflatasticandClaude Opus 5.5 3c856caa65 M14.2: custom title bar on Windows and Linux
The window is undecorated off macOS and the app bar is the title bar: Minimize,
Maximize/Restore and Close caption buttons (46 pt, drawn in code, Close hover red)
at the far right, empty bar space drags the window and double-click toggles
maximize, and 5 pt invisible edge/corner zones resize it (off while maximized or
fullscreen). Close runs app.quit, so modified documents are asked about first.
The right-side group now fits the space after the menus: Discord drops out and
the search box becomes an icon at narrow widths, so nothing overlaps at 800 pt.
macOS and the web build are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 02:00:04 +07:00
BFlat 8dc6396971 Merge pull request #38 from storytold/pr/m3-graphic-styles-panel
M3: Graphic Styles panel depth, Tile Edge Color, Show Swatch Bounds (M3.71, M3.72)
2026-10-05 01:59:14 +07:00
bflatasticandClaude Opus 5.5 b36fd67bf4 M3.72: Tile Edge Color dialog and Show Swatch Bounds in pattern editing
Object > Pattern > Tile Edge Color... picks the colour of the tile edge
(a layer-colour preset or a custom colour), stored in the preference
patternTileEdgeColor and passed to the renderer. Pattern Options gains
Show Swatch Bounds: a dashed outline of the part of the tiling the swatch
repeats (the period of brick and hex tilings).

Commands: prefs.set {patternTileEdgeColor}, pattern.options
{showSwatchBounds}, ui.tileEdgeColor. Model: PatternDef.show_swatch_bounds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 01:50:25 +07:00
bflatasticandClaude Opus 5.5 d8b942c43d M3.71: Graphic Styles panel views, previews, merge, reorder and drag and drop
Thumbnail, Small List and Large List views; thumbnails rendered on a
square or on type and cached by a hash of each style's look. Merge
Graphic Styles (named in Graphic Style Options), drag to reorder, delete
asks first (Alt-click does not), the right button held on a style shows
it large on the selected object. Styles dragged onto art apply to the
object hit; art dragged off the canvas or the Appearance thumbnail dropped
on the panel becomes a new style. Override Character Color (on by
default) clears type's character fill and stroke when a style with fills
or strokes is applied. Control bar Style picker.

Commands: graphicStyle.merge, graphicStyle.move, graphicStyle.setOptions,
ui.mergeGraphicStyles. Prefs: overrideCharColor.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 01:50:13 +07:00
BFlat 1c18851728 Merge pull request #35 from storytold/pr/m3-flatten-transparency
M3: Flatten Transparency engine (M3.91)
2026-10-05 01:39:03 +07:00
bflatasticandClaude Opus 5.5 f75d7628c7 M3.91: Object > Flatten Transparency turns transparent art into opaque art that looks the same
object.flattenTransparency {preset?|options, ids?} splits the targets into groups of overlapping
objects. Groups with transparency become atomic regions (faces of the arrangement of every fill,
outlined stroke and clipping path) filled with the colour the renderer composites there: blend
modes, group opacity, isolated and non-isolated groups, knockout groups and knockout shapes, over
white or (Preserve Alpha) over nothing. Regions reached by gradients, patterns, images, opacity
masks or raster effects are rendered into one image per group, under the regions, clipped to
them with Clip Complex Regions. The raster/vector balance rasterizes whole groups past its region
budget (all at 0). Options and presets live in FlattenOptions; single visible paints keep their
colour and overprint; text and strokes can be outlined everywhere. One undo step.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 01:36:18 +07:00
563 changed files with 77593 additions and 5638 deletions

No files matched your search

+17
View File
@@ -0,0 +1,17 @@
## What and why
<!-- What does this change, and why? Link the issue if there is one. -->
## How it was tested
<!-- Tests added, and how you checked the behaviour (CLI, MCP, screenshots). -->
## Checklist
- [ ] `cargo xtask ci` passes (fmt, clippy, tests, assets, brands, layers, wasm).
- [ ] No panics in shipped code: no `unwrap()`, `expect()`, `panic!`, `unreachable!`, `todo!` or
`unimplemented!` outside tests, and no unchecked indexing on data from files, parameters or
messages. Errors are returned as `Result` and shown to the user
([why and how](https://github.com/storytold/vectorcraft/blob/main/docs/development.md#robustness-vectorcraft-never-crashes)).
- [ ] Clean-room: nothing copied from Adobe products or GPL/AGPL code ([AGENTS.md](https://github.com/storytold/vectorcraft/blob/main/AGENTS.md)).
- [ ] Every new asset has a row in `ASSETS.md`.
+9 -1
View File
@@ -24,11 +24,19 @@ Formerly **DrawCraft** (renamed 2026-10-01): old `.drawcraft` files and `"format
- Code and original assets are MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`, `NOTICE`). The ArtCraft logos in `docs/brand/` are trademarks, not open source, under `docs/brand/LICENSE-brand.txt`: never modify them or use them outside VectorCraft.
- Prefer art generated in code for defaults (swatches, brushes, symbols, patterns, cursors). If the provenance of an asset is unclear, don't add it.
- Reference screenshots of Illustrator stay local under the gitignored `plan/` and are never committed, published or used as assets.
- **Never crash: no panics in shipped code.** A crash loses the user's unsaved work. Files, pasted data, MCP and control messages, and command params are all untrusted input.
- Fallible work returns `Result` (or `Option`); callers handle it or propagate it with `?`. Failures reach the user as an error message (`EngineError` for commands, the crate's own error type or `String` below the engine), never as an abort.
- Workspace clippy lints ban these outside tests, so `cargo xtask ci` fails on them: `unwrap()`, `expect()`, `panic!`, `unreachable!`, `todo!`, `unimplemented!`. Use instead: `?`, `.ok_or(…)?`, `let … else { return … }`, `if let`, `unwrap_or` / `unwrap_or_default` / `unwrap_or_else`, `.first()` / `.last()` / `.split_last()`, and a real error for a match arm you believe is impossible.
- Don't panic implicitly either: use `.get(i)` instead of `v[i]` or `&s[a..b]` when the index comes from data. Don't divide integers by something that can be zero, cap sizes and counts read from input (allocations, images, loops), and check that floats are finite before casting them or looping on them.
- Don't silence errors just to satisfy the lint: use `let _ =` or `.ok()` only where ignoring the failure is the right behaviour, with a comment saying why.
- Tests may unwrap and panic (`#[test]`, `#[cfg(test)]`, `tests/`, `testkit`). Integration-test files start with an `#![allow(…)]` for that.
- `vectorcraft_engine::guard` is the last line of defence. Every entry point (commands, tool events, MCP requests, the UI frame, control requests) catches a panic, rolls the document back and reports an internal error. It exists for bugs and doesn't replace `Result`: wasm aborts on panic, so the web app has no safety net.
- Untrusted input is fuzzed (`engine/tests/import_fuzz.rs`, `engine/tests/command_sweep.rs`, `format/tests/prop_format.rs`, `mcp/tests/protocol_props.rs`). Extend these when you add an importer, a parser or a protocol method.
- **Everything is a command.** User-visible behaviour = a command in `crates/engine/src/cmd/*` (id, label, menu path, shortcut, params doc, `enabled`, `run`) + tests. Tools emit commands (Begin/Preview/Commit). UI-only commands live in `crates/ui-egui/src/menus.rs` (`UI_COMMANDS`). The control channel and MCP reach all of them.
- **Layering** is enforced by `cargo xtask layers`. Nothing below L6 depends on egui/eframe/winit/rfd.
- **The UI is thin**: panels read engine state and act through `app.run(id, params)`. Colours come from `theme::Tokens`.
- **Rust only** (no handwritten JS/TS). **Never break wasm** (`cargo xtask wasm`).
- **Quality gates** before every commit: `cargo xtask ci` (fmt, clippy -D warnings, tests, layers, wasm). One task id per commit (`M2.1: pen tool`).
- **Quality gates** before every commit: `cargo xtask ci` (fmt, clippy -D warnings including the no-panic lints, tests, layers, wasm). One task id per commit (`M2.1: pen tool`).
## Running and looking at the app
- `cargo run --release -p vectorcraft -- --control 7979 [file.svg|file.vectorcraft]` (sibling apps' agents use the same default port: if the log says it failed to bind, pick another port — otherwise your requests reach a different app).
+9
View File
@@ -99,12 +99,16 @@ Generated-in-code art is original and has no file to list. This covers the defau
| `assets/icons/dc-cap-butt.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-cap-round.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-cap-square.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-center-hide.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-center-show.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-clear.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-color-guide.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-crystallize.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-cube.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-dash-align.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-dash-exact.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-dir-off.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-dir-on.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-direct.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-dist-bottom.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-dist-hcenter.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
@@ -127,6 +131,9 @@ Generated-in-code art is original and has no file to list. This covers the defau
| `assets/icons/dc-grad-freeform.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-grad-linear.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-grad-radial.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-grad-stroke-across.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-grad-stroke-along.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-grad-stroke-within.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-gradient.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-graphic-styles.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-grid-view.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
@@ -182,6 +189,8 @@ Generated-in-code art is original and has no file to list. This covers the defau
| `assets/icons/dc-reverse.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-rotate-view.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-rounded-rect.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-rule-evenodd.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-rule-nonzero.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-scallop.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-screen-mode.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-selection.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
+9 -1
View File
@@ -24,11 +24,19 @@ Formerly **DrawCraft** (renamed 2026-10-01): old `.drawcraft` files and `"format
- Code and original assets are MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`, `NOTICE`). The ArtCraft logos in `docs/brand/` are trademarks, not open source, under `docs/brand/LICENSE-brand.txt`: never modify them or use them outside VectorCraft.
- Prefer art generated in code for defaults (swatches, brushes, symbols, patterns, cursors). If the provenance of an asset is unclear, don't add it.
- Reference screenshots of Illustrator stay local under the gitignored `plan/` and are never committed, published or used as assets.
- **Never crash: no panics in shipped code.** A crash loses the user's unsaved work. Files, pasted data, MCP and control messages, and command params are all untrusted input.
- Fallible work returns `Result` (or `Option`); callers handle it or propagate it with `?`. Failures reach the user as an error message (`EngineError` for commands, the crate's own error type or `String` below the engine), never as an abort.
- Workspace clippy lints ban these outside tests, so `cargo xtask ci` fails on them: `unwrap()`, `expect()`, `panic!`, `unreachable!`, `todo!`, `unimplemented!`. Use instead: `?`, `.ok_or(…)?`, `let … else { return … }`, `if let`, `unwrap_or` / `unwrap_or_default` / `unwrap_or_else`, `.first()` / `.last()` / `.split_last()`, and a real error for a match arm you believe is impossible.
- Don't panic implicitly either: use `.get(i)` instead of `v[i]` or `&s[a..b]` when the index comes from data. Don't divide integers by something that can be zero, cap sizes and counts read from input (allocations, images, loops), and check that floats are finite before casting them or looping on them.
- Don't silence errors just to satisfy the lint: use `let _ =` or `.ok()` only where ignoring the failure is the right behaviour, with a comment saying why.
- Tests may unwrap and panic (`#[test]`, `#[cfg(test)]`, `tests/`, `testkit`). Integration-test files start with an `#![allow(…)]` for that.
- `vectorcraft_engine::guard` is the last line of defence. Every entry point (commands, tool events, MCP requests, the UI frame, control requests) catches a panic, rolls the document back and reports an internal error. It exists for bugs and doesn't replace `Result`: wasm aborts on panic, so the web app has no safety net.
- Untrusted input is fuzzed (`engine/tests/import_fuzz.rs`, `engine/tests/command_sweep.rs`, `format/tests/prop_format.rs`, `mcp/tests/protocol_props.rs`). Extend these when you add an importer, a parser or a protocol method.
- **Everything is a command.** User-visible behaviour = a command in `crates/engine/src/cmd/*` (id, label, menu path, shortcut, params doc, `enabled`, `run`) + tests. Tools emit commands (Begin/Preview/Commit). UI-only commands live in `crates/ui-egui/src/menus.rs` (`UI_COMMANDS`). The control channel and MCP reach all of them.
- **Layering** is enforced by `cargo xtask layers`. Nothing below L6 depends on egui/eframe/winit/rfd.
- **The UI is thin**: panels read engine state and act through `app.run(id, params)`. Colours come from `theme::Tokens`.
- **Rust only** (no handwritten JS/TS). **Never break wasm** (`cargo xtask wasm`).
- **Quality gates** before every commit: `cargo xtask ci` (fmt, clippy -D warnings, tests, layers, wasm). One task id per commit (`M2.1: pen tool`).
- **Quality gates** before every commit: `cargo xtask ci` (fmt, clippy -D warnings including the no-panic lints, tests, layers, wasm). One task id per commit (`M2.1: pen tool`).
## Running and looking at the app
- `cargo run --release -p vectorcraft -- --control 7979 [file.svg|file.vectorcraft]` (sibling apps' agents use the same default port: if the log says it failed to bind, pick another port — otherwise your requests reach a different app).
Generated
+72 -21
View File
@@ -1885,6 +1885,12 @@ dependencies = [
"libc",
]
[[package]]
name = "jpeg-encoder"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b454d911ac55068f53495488d8ccd0646eaa540c033a28ee15b07838afafb01f"
[[package]]
name = "js-sys"
version = "0.3.106"
@@ -3543,6 +3549,16 @@ dependencies = [
"serde",
]
[[package]]
name = "socket2"
version = "0.6.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4"
dependencies = [
"libc",
"windows-sys 0.61.2",
]
[[package]]
name = "spirv"
version = "0.4.0+sdk-1.4.341.0"
@@ -4044,11 +4060,13 @@ dependencies = [
[[package]]
name = "vectorcraft"
version = "0.1.1"
version = "0.2.0"
dependencies = [
"arboard",
"clipboard-win",
"eframe",
"egui",
"image",
"log",
"muda",
"rfd",
@@ -4061,7 +4079,7 @@ dependencies = [
[[package]]
name = "vectorcraft-brush"
version = "0.1.1"
version = "0.2.0"
dependencies = [
"kurbo 0.13.1",
"serde",
@@ -4071,9 +4089,25 @@ dependencies = [
"vectorcraft-geom",
]
[[package]]
name = "vectorcraft-cad"
version = "0.2.0"
dependencies = [
"image",
"kurbo 0.13.1",
"serde_json",
"vectorcraft-brush",
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-effects",
"vectorcraft-geom",
"vectorcraft-pathops",
"vectorcraft-text",
]
[[package]]
name = "vectorcraft-cli"
version = "0.1.1"
version = "0.2.0"
dependencies = [
"serde_json",
"vectorcraft-color",
@@ -4089,7 +4123,7 @@ dependencies = [
[[package]]
name = "vectorcraft-color"
version = "0.1.1"
version = "0.2.0"
dependencies = [
"kurbo 0.13.1",
"moxcms",
@@ -4101,7 +4135,7 @@ dependencies = [
[[package]]
name = "vectorcraft-doc"
version = "0.1.1"
version = "0.2.0"
dependencies = [
"image",
"kurbo 0.13.1",
@@ -4115,7 +4149,7 @@ dependencies = [
[[package]]
name = "vectorcraft-effects"
version = "0.1.1"
version = "0.2.0"
dependencies = [
"kurbo 0.13.1",
"serde_json",
@@ -4128,7 +4162,7 @@ dependencies = [
[[package]]
name = "vectorcraft-engine"
version = "0.1.1"
version = "0.2.0"
dependencies = [
"flate2",
"image",
@@ -4139,6 +4173,7 @@ dependencies = [
"serde_json",
"thiserror 2.0.21",
"vectorcraft-brush",
"vectorcraft-cad",
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-format",
@@ -4155,8 +4190,9 @@ dependencies = [
[[package]]
name = "vectorcraft-format"
version = "0.1.1"
version = "0.2.0"
dependencies = [
"flate2",
"proptest",
"serde",
"serde_json",
@@ -4168,7 +4204,7 @@ dependencies = [
[[package]]
name = "vectorcraft-geom"
version = "0.1.1"
version = "0.2.0"
dependencies = [
"kurbo 0.13.1",
"proptest",
@@ -4180,11 +4216,13 @@ dependencies = [
[[package]]
name = "vectorcraft-mcp"
version = "0.1.1"
version = "0.2.0"
dependencies = [
"image",
"log",
"proptest",
"serde_json",
"socket2",
"vectorcraft-doc",
"vectorcraft-engine",
"vectorcraft-format",
@@ -4197,7 +4235,7 @@ dependencies = [
[[package]]
name = "vectorcraft-pathops"
version = "0.1.1"
version = "0.2.0"
dependencies = [
"kurbo 0.13.1",
"linesweeper",
@@ -4209,7 +4247,7 @@ dependencies = [
[[package]]
name = "vectorcraft-pdf"
version = "0.1.1"
version = "0.2.0"
dependencies = [
"hayro-interpret",
"hayro-syntax",
@@ -4217,6 +4255,8 @@ dependencies = [
"krilla",
"kurbo 0.13.1",
"log",
"serde",
"serde_json",
"smallvec",
"thiserror 2.0.21",
"vectorcraft-brush",
@@ -4230,9 +4270,12 @@ dependencies = [
[[package]]
name = "vectorcraft-render"
version = "0.1.1"
version = "0.2.0"
dependencies = [
"flate2",
"gif",
"image",
"jpeg-encoder",
"log",
"proptest",
"serde_json",
@@ -4249,13 +4292,16 @@ dependencies = [
[[package]]
name = "vectorcraft-svg"
version = "0.1.1"
version = "0.2.0"
dependencies = [
"flate2",
"image",
"kurbo 0.13.1",
"proptest",
"resvg",
"serde",
"serde_json",
"skrifa 0.47.0",
"svgtypes 0.16.1",
"thiserror 2.0.21",
"usvg 0.48.1",
@@ -4270,7 +4316,7 @@ dependencies = [
[[package]]
name = "vectorcraft-testkit"
version = "0.1.1"
version = "0.2.0"
dependencies = [
"image",
"kurbo 0.13.1",
@@ -4287,20 +4333,22 @@ dependencies = [
[[package]]
name = "vectorcraft-text"
version = "0.1.1"
version = "0.2.0"
dependencies = [
"harfrust 0.13.3",
"kurbo 0.13.1",
"log",
"skrifa 0.47.0",
"subsetter",
"vectorcraft-doc",
"vectorcraft-geom",
]
[[package]]
name = "vectorcraft-tools"
version = "0.1.1"
version = "0.2.0"
dependencies = [
"image",
"kurbo 0.13.1",
"serde",
"serde_json",
@@ -4313,7 +4361,7 @@ dependencies = [
[[package]]
name = "vectorcraft-trace"
version = "0.1.1"
version = "0.2.0"
dependencies = [
"image",
"kurbo 0.13.1",
@@ -4326,13 +4374,15 @@ dependencies = [
[[package]]
name = "vectorcraft-ui-egui"
version = "0.1.1"
version = "0.2.0"
dependencies = [
"egui",
"egui_extras",
"image",
"log",
"serde",
"serde_json",
"vectorcraft-cad",
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-effects",
@@ -4342,13 +4392,14 @@ dependencies = [
"vectorcraft-pdf",
"vectorcraft-render",
"vectorcraft-svg",
"vectorcraft-testkit",
"vectorcraft-text",
"vectorcraft-tools",
]
[[package]]
name = "vectorcraft-web"
version = "0.1.1"
version = "0.2.0"
dependencies = [
"eframe",
"egui",
@@ -5328,7 +5379,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee"
[[package]]
name = "xtask"
version = "0.1.1"
version = "0.2.0"
dependencies = [
"serde_json",
]
+15 -2
View File
@@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"]
default-members = ["crates/*", "apps/vectorcraft", "apps/vectorcraft-cli", "xtask"]
[workspace.package]
version = "0.1.1"
version = "0.2.0"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.90"
@@ -29,6 +29,7 @@ vectorcraft-engine = { path = "crates/engine" }
vectorcraft-ui-egui = { path = "crates/ui-egui" }
vectorcraft-mcp = { path = "crates/mcp" }
vectorcraft-testkit = { path = "crates/testkit" }
vectorcraft-cad = { path = "crates/cad" }
# foundation
kurbo = { version = "0.13", features = ["serde"] }
@@ -38,6 +39,8 @@ serde = { version = "1", features = ["derive", "rc"] }
serde_json = { version = "1", features = ["float_roundtrip"] }
log = "0.4"
proptest = "1"
# tests: a TCP port bound without listening (connections to it are refused)
socket2 = "0.6"
# rendering / formats
vello_cpu = "0.2"
@@ -48,6 +51,8 @@ skrifa = "0.47"
harfrust = "0.13"
linesweeper = "0.4"
flate2 = { version = "1", default-features = false, features = ["rust_backend"] }
jpeg-encoder = { version = "0.6", default-features = false, features = ["std"] }
gif = { version = "0.14", default-features = false, features = ["std", "raii_no_panic"] }
# ui
egui = "0.36"
@@ -56,6 +61,7 @@ eframe = { version = "0.36", default-features = false }
egui_kittest = "0.36"
rfd = "0.17"
arboard = { version = "3.6", default-features = false }
clipboard-win = "5.4"
webbrowser = "1"
[workspace.lints.rust]
@@ -63,7 +69,14 @@ unsafe_code = "deny"
[workspace.lints.clippy]
dbg_macro = "warn"
todo = "warn"
# VectorCraft never crashes: shipped code returns `Result`/`Option` instead of panicking (see
# AGENTS.md › Robustness). Tests may unwrap (clippy.toml).
unwrap_used = "deny"
expect_used = "deny"
panic = "deny"
todo = "deny"
unimplemented = "deny"
unreachable = "deny"
[profile.dev.package."*"]
opt-level = 2
+3
View File
@@ -23,3 +23,6 @@ list (author, source, license) is in ASSETS.md.
Rust dependencies (vello_cpu, kurbo, peniko, skrifa, harfrust, usvg, linesweeper, egui, eframe, …) are
fetched through crates.io under their own permissive licenses (mostly MIT and/or Apache-2.0; also
BSD, ISC, Zlib, BSL-1.0 and Unicode-3.0).
JPEG export uses the jpeg-encoder crate (MIT OR Apache-2.0, and the IJG License): this software is
based in part on the work of the Independent JPEG Group.
+3 -2
View File
@@ -173,8 +173,9 @@ milestones, and honest time-to-parity estimates.
and `apps/{vectorcraft, vectorcraft-cli, vectorcraft-web}`. The egui frontend is its own crate, so
the UI can be swapped without touching the engine.
Agent and contributor rules (clean-room, the asset policy, quality gates) are in
[`AGENTS.md`](AGENTS.md). Every bundled asset is listed with its licence in [`ASSETS.md`](ASSETS.md).
Agent and contributor rules (clean-room, the asset policy, no panics in shipped code, quality gates) are in
[`AGENTS.md`](AGENTS.md); [`docs/development.md`](docs/development.md#robustness-vectorcraft-never-crashes)
explains how VectorCraft avoids crashing. Every bundled asset is listed with its licence in [`ASSETS.md`](ASSETS.md).
## The Crafting Apps
+28 -27
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-04._
_Last updated: 2026-10-05._
## Where we are
@@ -12,10 +12,10 @@ _Last updated: 2026-10-04._
|---|---|
| Infrastructure (engine, command registry, history, render, formats, MCP, web, packaging, tests) | **~90%** |
| Look & feel vs Illustrator 2026 default workspace (measured) | **~75–80%** |
| Feature surface vs full Illustrator (weighted, see below) | **~67%** |
| Feature surface vs full Illustrator (weighted, see below) | **~68%** |
| Parity including interaction fidelity and hardening ("a power user can't tell the difference, but faster") | **~50%** |
| Time to **feature parity** (every menu item, tool, panel, effect and dialog functional) | **~340–540 h** one agent · **~85–155 h** with 4–6 agents |
| Time to **full parity** (feature parity + interaction-fidelity pass + hardening) | **~450–710 h** one agent · **~115–200 h** with 4–6 agents |
| Time to **feature parity** (every menu item, tool, panel, effect and dialog functional) | **~300–450 h** one agent · **~75–130 h** with 4–6 agents |
| Time to **full parity** (feature parity + interaction-fidelity pass + hardening) | **~425–650 h** one agent · **~105–185 h** with 4–6 agents |
### 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.
@@ -31,6 +31,7 @@ _Last updated: 2026-10-04._
- Native macOS menu bar, vector tool cursors, a ⌘K command palette, middle-button panning with any tool.
- Save / Don't Save / Cancel before closing or quitting with unsaved documents (tabs, Close, Close All, Quit, window close).
- Four brightness themes, persistent preferences.
- On Windows and Linux the app bar is the window's title bar (its own minimize, maximize and close buttons, drag to move, edges to resize), with the dragon app icon as the brand mark; dialogs and menus size to their content.
- **Tools:**
- **Selection:** Selection, Direct/Group Selection, Magic Wand, Lasso.
- **Drawing:** Pen, Curvature, anchor tools, Pencil, Paintbrush, Blob Brush, Smooth, Path Eraser, Join.
@@ -48,21 +49,21 @@ _Last updated: 2026-10-04._
- **Transparency:** opacity masks (clip/invert/disable/link), exported as SVG `<mask>` and PDF soft masks.
- **Advanced art:** live Blends (steps/distance/smooth colour, spine), Envelope Distort (warp/mesh/top object), Gradient Mesh, Shape Builder, Live Paint, Image Trace (12 presets), pattern swatches with pattern editing mode, live Repeat (radial/grid/mirror).
- **Paint and appearance (M3):**
- **Swatches:** names follow the colour model and are unique; Swatch Options (process/spot, Global, Gray/RGB/HSB/CMYK/Web, live preview); editing a global or spot swatch recolours every linked fill, stroke and text run in one undo step; multi-select and delete with confirmation; New Swatch and New Color Group dialogs (a group from the selected artwork's colours); swatches in colour groups convert, separate and count like any other. The Swatches panel selects ranges and whole groups, has a find field, and drags swatches to reorder, regroup or paint art; Add Used Colors, Select All Unused, Merge, Ungroup and Sort by Kind; a CMYK document keeps applied colours in CMYK.
- **Colour:** a Color Picker (colour field, H/S/B/R/G/B channel slider, HSB/RGB/Lab/CMYK fields, hex, web-only snapping, out-of-gamut correction); the Color panel follows each colour's own model and Alt-click paints the other proxy; proxies look through groups and show "?" for mixed paint; Invert, Complement, Apply Last Color (`,`) and Apply Last Gradient (`.`) keep the colour model; every paint command feeds the recent colours.
- **Gradients:** lossless, validated gradient params; gradients follow rotate, reflect, shear, non-uniform scale and distortions; the Gradient tool edits the fill or stroke of the active proxy, type included; an interactive on-canvas annotator (move, length/angle, rotate, add/move/delete/duplicate stops, midpoints, a stop popover, Delete and arrow keys). The Gradient panel has the Fill/Stroke proxy, a gradient-swatch dropdown with Save to Swatches, midpoint locations, Alt-drag to copy or swap stops, swatch drops on the ramp and a stop eyedropper; copied appearances and graphic styles place gradients on each target's own bounds; gradient handles snap and honour Constrain Angle.
- **Strokes:** one stroke-geometry module shared by the canvas, SVG, PDF and Outline Stroke; dotted lines (zero-length dashes draw dots or squares); arrowheads with hollow outlines, tip-on-end or extend-past-end alignment and one opacity for line and head. SVG and PDF export arrowheads, width profiles, brushes and aligned strokes exactly as the canvas draws them; Outline Stroke and the live Outline Stroke effect outline every stroke item as drawn (dashes, heads, profiles, alignment); dashes can be fitted to corners and path ends; width profiles carry through dashes, and their corners take the join.
- **Appearance:** the Appearance panel's selected row drives every paint, stroke, gradient and transparency edit (`item` on the commands); effects apply to one fill or stroke; per-item Opacity popups; Mixed Appearances, Layers target dots and basic-appearance rules. Effects can be reordered, moved between items and copied by dragging; Show All Hidden Attributes; clicking an effect edits it in place; the object thumbnail drags onto art; effects render on type, images, symbols, blends, envelopes, meshes and repeats, and per-item raster effects export.
- **Masks and clipping:** opacity-mask controls work while the mask is being edited; transparency commands take ids and work without a selection; clipping sets clip by compound paths, even-odd paths, text and groups on screen and in raster export, matching SVG/PDF.
- **Transparency:** three-state Knockout Group (on, neutral, off), Opacity & Mask Define Knockout Shape, Page Isolated Blending and Page Knockout Group, on screen and in SVG/PDF.
- **Graphic styles:** styles keep opacity and blend mode, capture groups and type, apply on top with Alt, and link to the objects using them; Redefine, Break Link, Graphic Style Options, Select All Unused, Sort by Name, and Select > Same Graphic Style / Appearance Attribute.
- **Swatches:** names follow the colour model and are unique; Swatch Options (process/spot, Global, Gray/RGB/HSB/CMYK/Web, live preview); editing a global or spot swatch recolours every linked fill, stroke and text run in one undo step; multi-select and delete with confirmation; New Swatch and New Color Group dialogs (a group from the selected artwork's colours); swatches in colour groups convert, separate and count like any other. The Swatches panel selects ranges and whole groups, has a find field, and drags swatches to reorder, regroup or paint art; Add Used Colors, Select All Unused, Merge, Ungroup and Sort by Kind; a CMYK document keeps applied colours in CMYK. Swatch libraries: nine generated colour libraries and five gradient libraries in a library panel, saved and loaded as `.vcswatches`, `.gpl` or CSS. Tints of global and spot colours ("Name 40%") stay linked and separate as a percentage of their plate. Spot colours can be defined in Lab (Spot Colors options). A built-in [Registration] swatch prints on every plate.
- **Colour:** a Color Picker (colour field, H/S/B/R/G/B channel slider, HSB/RGB/Lab/CMYK fields, hex, web-only snapping, out-of-gamut correction); the Color panel follows each colour's own model and Alt-click paints the other proxy; proxies look through groups and show "?" for mixed paint; Invert, Complement, Apply Last Color (`,`) and Apply Last Gradient (`.`) keep the colour model; every paint command feeds the recent colours. The Color Guide has 21 harmony rules, Steps and Variation options and Limit to Library. Adjust Color Balance (its Global mode shifts tints) and Saturate preview live; Edit Colors and Recolor also reach meshes, images and patterns. Recolor Artwork has colour reduction, five recolour methods, presets, Limit to Library, a colour-wheel Edit tab and Edit Color Group; a local Color Themes panel saves five-colour themes. Fill/Stroke chips open swatch and mixer popovers, panels have their shortcuts, and Eyedropper Options pick up and apply chosen attributes (Alt and Shift+Alt, image pixels). Fills and strokes can overprint (Attributes panel, Overprint Black options), and CMYK documents blend in inks on screen, in PDF and when flattening.
- **Gradients:** lossless, validated gradient params; gradients follow rotate, reflect, shear, non-uniform scale and distortions; the Gradient tool edits the fill or stroke of the active proxy, type included; an interactive on-canvas annotator (move, length/angle, rotate, add/move/delete/duplicate stops, midpoints, a stop popover, Delete and arrow keys). The Gradient panel has the Fill/Stroke proxy, a gradient-swatch dropdown with Save to Swatches, midpoint locations, Alt-drag to copy or swap stops, swatch drops on the ramp and a stop eyedropper; copied appearances and graphic styles place gradients on each target's own bounds; gradient handles snap and honour Constrain Angle. Gradient stops stay linked to global and spot swatches. Freeform gradients (points and lines) are edited on the canvas; radial gradients have an extent ellipse, an aspect handle and an off-centre focal point (SVG `fx`/`fy`, PDF two-point radials). A stroke's gradient runs within, along or across it. Object ▸ Expand turns gradients into N objects or a gradient mesh.
- **Strokes:** one stroke-geometry module shared by the canvas, SVG, PDF and Outline Stroke; dotted lines (zero-length dashes draw dots or squares); arrowheads with hollow outlines, tip-on-end or extend-past-end alignment and one opacity for line and head. SVG and PDF export arrowheads, width profiles, brushes and aligned strokes exactly as the canvas draws them; Outline Stroke and the live Outline Stroke effect outline every stroke item as drawn (dashes, heads, profiles, alignment); dashes can be fitted to corners and path ends; width profiles carry through dashes, and their corners take the join. The Stroke panel edits type's character strokes, follows the stroke units, shows mixed values blank and opens from the Control bar. A width profile library, thirty more arrowheads, and Width Point Edit with multi-select and discontinuous points. Visual bounds and clicks cover the whole painted stroke. Scale Strokes & Effects, Scale Corners and Use Preview Bounds work everywhere, and new art inherits stroke options, a graphic style or the whole last appearance.
- **Appearance:** the Appearance panel's selected row drives every paint, stroke, gradient and transparency edit (`item` on the commands); effects apply to one fill or stroke; per-item Opacity popups; Mixed Appearances, Layers target dots and basic-appearance rules. Effects can be reordered, moved between items and copied by dragging; Show All Hidden Attributes; clicking an effect edits it in place; the object thumbnail drags onto art; effects render on type, images, symbols, blends, envelopes, meshes and repeats, and per-item raster effects export. Groups, layers and type have their own fills, strokes and effects (Contents and Characters rows); the Layers panel's target circles target layers, groups and objects; Expand Appearance turns fills, strokes, effects and brushes into objects.
- **Masks and clipping:** opacity-mask controls work while the mask is being edited; transparency commands take ids and work without a selection; clipping sets clip by compound paths, even-odd paths, text and groups on screen and in raster export, matching SVG/PDF. Alt-click shows only the mask; SVG masks keep Clip and Invert; the transparency grid is per-document state; a clipping path's own fill and stroke paint behind and over the clipped art; layers can be clipping masks.
- **Transparency:** three-state Knockout Group (on, neutral, off), Opacity & Mask Define Knockout Shape, Page Isolated Blending and Page Knockout Group, on screen and in SVG/PDF. Blend modes match the standard formulas on screen, in SVG and in PDF, and non-isolated groups blend with the art below. Flatten Transparency with presets, a dialog and a Flattener Preview panel.
- **Graphic styles:** styles keep opacity and blend mode, capture groups and type, apply on top with Alt, and link to the objects using them; Redefine, Break Link, Graphic Style Options, Select All Unused, Sort by Name, and Select > Same Graphic Style / Appearance Attribute. The panel has list and thumbnail views with rendered previews, merge, reorder and drag and drop, plus a Control bar Style picker; six generated style libraries save and load as `.vcstyles`.
- **Neutral wording:** labels, MCP tool text, docs and packaging use neutral names, and `cargo xtask brands` (part of `cargo xtask ci`) fails on vendor names.
- **Colour, type and file workflows:** Recolor Artwork (dialog with harmonies), Edit Colors, Find & Replace, Change Case, Smart Punctuation, Guides, Lock/Hide Above, Transform Each, Rasterize.
- **Formats:**
- `.vectorcraft` (lossless JSON), SVG import/export, PDF export/import (including PDF-compatible `.ai`).
- PNG, JPEG and WebP export, Export for Screens, Place.
- **Performance:** 20k shapes + 1k texts render in 27 ms per full-retina frame (7.8 ms zoomed), 7× faster than the first version. The UI thread never blocks. The web build is 7.1 MB gzipped.
- **Tests:** ~1,430 automated tests: model-based property tests, a junk-parameter sweep over every command, golden renders, and MCP end-to-end tests over stdio.
- **Tests:** ~1,900 automated tests: model-based property tests, a junk-parameter sweep over every command, golden renders, and MCP end-to-end tests over stdio.
## Milestones and estimates
@@ -71,10 +72,10 @@ _Last updated: 2026-10-04._
| M0 | Skeleton + vertical slice | ✅ done | — |
| M1 | Selection, transform, layers, MCP | ✅ mostly done (transform reference point snaps to anchors/centres; rotated persistent bbox pending) | 4–6 |
| M2 | Drawing tools + smart guides | ✅ mostly done (Flare, Reshape, Live Corners widget dragging landed; Shaper, Pen modifier nuances) | 15–20 |
| M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | 🟡 M3.7–M3.39 and M3.42–M3.48 done: swatch options, global/spot edits, colour groups and Swatches panel depth (drag and drop, find, panel commands, document colour mode); Color Picker and Color panel behaviour; proxy commands; gradients that follow every transform, an interactive annotator, Gradient panel depth and rebased gradients; shared stroke geometry, dotted lines, arrowheads, SVG/PDF stroke parity, Outline Stroke fidelity, corner-fitted dashes, profiles through dashes; Appearance-panel targeting, per-item effects and opacity, effect drag/edit, effects on every object kind; three-state knockout and page groups; graphic style links and management; opacity-mask editing reach; clipping by any shape. Pending (M3.40–M3.41, M3.49–M3.98): stroke on type, overprint and the Attributes panel, swatch and style libraries, tints and linked gradient stops, freeform gradients and gradient on strokes, width profile library and Width tool depth, Scale Strokes and preview bounds, container appearance, target circles and Expand Appearance, blend accuracy and isolation, layer clipping masks, Colour Guide and Recolor depth, Expand, mask view, CMYK blending, Flatten Transparency | 45–85 |
| M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Color Picker, Color panel, Color Guide, Color Themes, Edit Colors and Recolor Artwork; gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool, Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries. Left: freeform and mixed spot/process gradients export as stops or process colours to SVG/PDF; flattener presets not yet used by PDF/print; confirm the Scale Strokes & Effects default | 4–8 |
| M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | 🟡 one engine loader/encoder for every frontend (desktop, web, CLI, control channel, headless MCP open native/SVG/SVGZ/PDF/.ai/.ait/PNG/JPEG/GIF/WebP/TIFF/BMP; `document.formats`; MCP `export` takes artboard/range/options; one PDF page per artboard in Export for Screens; template layers left out of raster exports); Export for Screens (PNG/JPG/WebP/SVG/PDF × scales) done; headless CLI/MCP export every format; system clipboard: copy puts SVG markup on it, paste takes SVG from other apps (Ctrl/Cmd+C/X/V now also work off macOS); live effects now survive SVG/PDF/clipboard export (geometry baked, SVG filters for shadows/glows/blur/feather); Save / Don't Save / Cancel before closing modified documents; PDF raster effects, PNG/PDF clipboard flavours, EPS/DXF pending | 52–73 |
| M5 | Performance | 🟡 background render + caches + MT done; `vectorcraft-cli bench` and `vectorcraft-cli perf` (budget suite); file format v2 opens 3× faster (50k paths: 722 → 244 ms); raster effects (glows, shadows, blur, feather) no longer force the whole frame single-threaded (filtered offscreen per effect, verified equal to the single-threaded reference); effect-heavy demos need a clean-machine benchmark; dirty-region rendering, GPU backend spike pending | 15–25 |
| M6 | Path operations (Pathfinder, Shape Builder, offset…) | ✅ mostly done (Shape Builder edge erase, large-offset bug open) | 3–6 |
| M6 | Path operations (Pathfinder, Shape Builder, offset…) | ✅ mostly done (Boolean precision on almost-horizontal edges fixed and the property tests made deterministic; Shape Builder edge erase, large-offset bug open) | 3–6 |
| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | 🟡 Character/Paragraph Styles, Area Type Options, threaded text, Fit Headline, Glyphs, OpenType panel, Find Font, Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects, tab stops + Tabs panel done; tab leaders, spell check, vertical type pending | 45–60 |
| M8 | Transform & distort (Puppet Warp, Liquify tools, Envelopes, Blends, Perspective Grid) | 🟡 live Blends, Envelopes (warp/mesh/top object), Width tool, Liquify tools, Puppet Warp and Perspective Grid landed; fidelity pass pending | 8–12 |
| M9 | Live effects (+ 3D & Materials) | 🟡 2D effects done incl. Effect → Pathfinder; SVG Filters, Document Raster Effects Settings, 3D pending | 86–135 |
@@ -82,10 +83,10 @@ _Last updated: 2026-10-04._
| M11 | Artboards & views (artboard panel/tool done, Trim View, middle-button pan; print tiling, multiple windows, presentation polish) | 🟡 | 20–33 |
| M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (12 presets, 18 ms/1k² image), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, regenerate in place) done; graph Design/Column/Marker designs pending | 6–10 |
| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 | 18–27 |
| M14 | 1.0 polish (preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) | 🟡 Preferences, shortcut editor, workspaces done; accessibility, Windows/Linux packaging pending | 20–30 |
| M14 | 1.0 polish (preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) | 🟡 Preferences, shortcut editor, workspaces, a custom title bar on Windows/Linux and content-sized dialogs and menus done; accessibility, Windows/Linux packaging pending | 18–28 |
| — | Interaction fidelity pass (every tool's modifiers, Properties panel per context, isolation, nuance) | ⬜ | 60–90 |
| — | Hardening at scale (big-file corpus, fuzzing, cross-platform + browser QA) | 🟡 | 50–80 |
| | **Total to full parity** (one agent; sum of the rows above — matches [Parity estimate](#parity-estimate)) | | **~450–710** |
| | **Total to full parity** (one agent; sum of the rows above — matches [Parity estimate](#parity-estimate)) | | **~425–650** |
## Parity estimate
@@ -96,17 +97,17 @@ time is counted per area from what is missing, calibrated on measured throughput
about 20 medium features (Text Wrap, Graphs, Effect → Pathfinder, export baking…) in ~16 h wall clock including builds
and CI on a heavily loaded machine — about 0.8 h per medium feature; large subsystems (3D, raster filters, vertical type)
are counted bottom-up. The M3 rows (colour, strokes, appearance) come from a detailed 92-task M3 plan whose review
found more missing depth than the first estimate; they are calibrated on its first two waves, where 13 packages planned at
~120 h took roughly 25–45 agent-hours.
found more missing depth than the first estimate; all 92 tasks landed on 2026-10-04 and 2026-10-05 with 6–8 agents in parallel; its packages, planned at 5–11 h each, took
about 1–1.5 agent-hours each, so the other rows (estimated on the older scale) are likely high.
| Area | Weight | Done | Missing (main items) | One agent (h) |
|---|---:|---:|---|---:|
| Selection, transform & align tools | 6 | 85% | rotated persistent bounding box, Start Global Edit, transform nuances | 4–6 |
| Drawing tools | 7 | 85% | Shaper Groups (merge/punch overlapping shapes), pen/pencil modifier nuances, Touch Type | 10–15 |
| Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 85% | Live Paint gap options, Shape Builder edge cases | 3–6 |
| Colour, swatches, gradients, patterns, mesh, recolor | 7 | 85% | swatch libraries (original), tints, linked gradient stops, freeform gradients, gradient on strokes, Expand, Colour Guide and Recolor depth, overprint, Tile Edge Color | 23–44 |
| Strokes, brushes, width profiles | 5 | 80% | stroke on type, width profile library, Width tool depth, Scale Strokes, brush options depth, brush libraries (generated in code) | 6–12 |
| Appearance, transparency, graphic styles, masks | 5 | 91% | container appearance, target circles, Expand Appearance, graphic style libraries, blend accuracy and isolation, Flatten Transparency, mask view (Alt-click) | 15–29 |
| Colour, swatches, gradients, patterns, mesh, recolor | 7 | 96% | freeform and mixed spot/process gradients in SVG/PDF (exported as stops or process colours), pattern fills in Expand | 2–4 |
| Strokes, brushes, width profiles | 5 | 88% | brush options depth, brush libraries (generated in code) | 6–10 |
| Appearance, transparency, graphic styles, masks | 5 | 97% | flattener presets in PDF/EPS/print, raster effect reach in preview bounds | 2–4 |
| Live vector effects | 5 | 85% | Outline Object, Pathfinder Hard/Soft Mix and Trap, SVG Filters | 6–10 |
| Raster effects (Effect Gallery, Document Raster Effects Settings) | 4 | 15% | ~55 filters (Artistic, Brush Strokes, Distort, Pixelate, Sketch, Texture…), resolution setting, raster effects in PDF | 30–45 |
| 3D and Materials | 4 | 0% | Extrude & Bevel, Revolve, Inflate, Rotate, lighting, materials (software renderer) | 50–80 |
@@ -123,18 +124,18 @@ found more missing depth than the first estimate; they are calibrated on its fir
| Automation | 3 | 60% | Variables (data merge), scripting surface, batch | 8–12 |
| UI chrome (panels, contextual Properties, workspaces, prefs) | 6 | 75% | ~14 panels (Tabs, Links, Attributes, Asset Export, SVG Interactivity, Variables, CSS Properties…), Properties per context | 20–30 |
| Libraries, Links, Package | 2 | 15% | Links panel, Package, local libraries | 10–15 |
| **Feature parity** | **103** | **~67%** | | **~340–540** |
| **Feature parity** | **103** | **~68%** | | **~300–450** |
| Interaction-fidelity pass (side by side with Illustrator: every tool modifier, cursor, dialog, Properties context) | | | | 60–90 |
| Hardening (big-file corpus, fuzzing, cross-platform and browser QA, accessibility, packaging) | | | | 50–80 |
| **Full parity** | | **~51%** | | **~450–710** |
| **Full parity** | | **~52%** | | **~425–650** |
With 4–6 agents working on disjoint crates (as the layering allows) the wall-clock time divides by roughly 3.5–4
(integration, review and shared files such as `menus.rs` serialize some work): **~85–155 h** to feature parity,
**~115–200 h** to full parity.
(integration, review and shared files such as `menus.rs` serialize some work): **~75–130 h** to feature parity,
**~105–185 h** to full parity.
_Inventories (2026-10-02):_ 426 engine commands + ~60 UI commands; 316 menu items wired, ~70 still disabled; 69 of 79
tools implemented (missing: Slice ×2, Touch Type, vertical type ×3, Print Tiling); 32 panels of ~45; 44 live
effects of ~110 (Illustrator effects 44/54, Photoshop-style raster effects 1/56); ~1,050 tests (~1,430 on 2026-10-04).
effects of ~110 (Illustrator effects 44/54, Photoshop-style raster effects 1/56); ~1,050 tests (~1,900 on 2026-10-05).
_Where we already beat Illustrator:_ exact curve booleans, off-thread multithreaded rendering, undo that never runs out,
lossless SVG/PDF export of live effects with SVG filters, a documented JSON format, the same app on the web, and every
+23 -10
View File
@@ -23,9 +23,9 @@ impl Rng {
}
/// `n` mixed paths (ellipses with strokes, translucent rectangles, stroked stars) on a 1600×1200 page.
pub fn synthetic(n: usize) -> Document {
pub fn synthetic(n: usize) -> Result<Document, String> {
let mut d = Document::new(1600.0, 1200.0);
let l = d.layers[0].id;
let l = d.layers.first().map(|l| l.id);
let mut r = Rng(42);
for i in 0..n {
let (x, y, s) = (r.next() * 1600.0, r.next() * 1200.0, 3.0 + r.next() * 22.0);
@@ -43,9 +43,9 @@ pub fn synthetic(n: usize) -> Document {
if i % 3 == 1 {
node.opacity = 0.8;
}
d.insert(Some(l), usize::MAX, node).expect("insert");
d.insert(l, usize::MAX, node).map_err(|e| format!("building the synthetic document: {e}"))?;
}
d
Ok(d)
}
fn median_ms(runs: usize, mut f: impl FnMut()) -> f64 {
@@ -57,7 +57,7 @@ fn median_ms(runs: usize, mut f: impl FnMut()) -> f64 {
})
.collect();
v.sort_by(f64::total_cmp);
v[v.len() / 2]
v.get(v.len() / 2).copied().unwrap_or(0.0)
}
/// 1-minute load average (macOS / Linux), if available.
@@ -87,7 +87,7 @@ pub fn run(args: &[String]) -> Result<(), String> {
println!("WARNING: the machine is busy; wall-clock timings below are not trustworthy.");
}
let t = Instant::now();
let doc = synthetic(n);
let doc = synthetic(n)?;
println!(" (built in {:.0} ms)", t.elapsed().as_secs_f64() * 1000.0);
let mut rows: Vec<(&str, f64, f64)> = vec![];
@@ -123,18 +123,31 @@ pub fn run(args: &[String]) -> Result<(), String> {
let mut bytes = vec![];
rows.push(("save .vectorcraft", median_ms(3, || bytes = vectorcraft_format::save_file(&doc)), 300.0));
rows.push(("open .vectorcraft", median_ms(3, || drop(vectorcraft_format::load(&bytes).expect("load"))), 300.0));
let mut failed = None;
let open = median_ms(3, || {
if let Err(e) = vectorcraft_format::load(&bytes) {
failed = Some(format!("open .vectorcraft: {e}"));
}
});
rows.push(("open .vectorcraft", open, 300.0));
let svg_opts = vectorcraft_svg::ExportOptions::default();
rows.push(("export SVG", median_ms(3, || drop(vectorcraft_svg::export(&doc, &svg_opts))), 500.0));
// Pathfinder Unite on 1,000 overlapping paths.
let unite = median_ms(3, || {
let mut s = vectorcraft_engine::Session::new();
s.add_document(synthetic(1000), None);
s.execute("select.all", &json!({})).expect("select");
s.execute("object.pathfinder.unite", &json!({})).expect("unite");
let r = synthetic(1000).and_then(|d| {
s.add_document(d, None);
s.execute("select.all", &json!({})).and_then(|_| s.execute("object.pathfinder.unite", &json!({}))).map_err(|e| e.to_string())
});
if let Err(e) = r {
failed = Some(format!("Pathfinder Unite: {e}"));
}
});
rows.push(("Pathfinder Unite, 1,000 paths", unite, 150.0));
if let Some(e) = failed {
return Err(e);
}
let mut over = 0;
println!(" {:<40} {:>10} {:>10}", "", "measured", "budget");
+2
View File
@@ -1,3 +1,5 @@
// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness).
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::io::Write;
use std::process::{Command, Stdio};
+2
View File
@@ -1,4 +1,6 @@
//! The CLI opens every readable format (PDF, .ai, images) through the engine's `document.open`.
// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness).
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::process::Command;
+2
View File
@@ -1,4 +1,6 @@
//! End-to-end MCP over stdio against the built `vectorcraft-cli mcp --headless` binary.
// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness).
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::io::{BufRead, BufReader, Write};
use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio};
+1 -1
View File
@@ -26,4 +26,4 @@ rfd = { workspace = true }
wasm-bindgen = "0.2"
wasm-bindgen-futures = "0.4"
js-sys = "0.3"
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "Location", "CssStyleDeclaration"] }
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "Location", "CssStyleDeclaration", "Event", "EventTarget", "MouseEvent", "DragEvent"] }
+74 -16
View File
@@ -1,14 +1,21 @@
//! The browser shell: web `Services`, drag-and-drop, and the eframe web runner.
use std::cell::Cell;
use std::rc::Rc;
use std::sync::{Arc, Mutex};
use vectorcraft_engine::Session;
use vectorcraft_engine::cmd::fileio;
use vectorcraft_ui_egui::place::{DropTarget, PlaceArrival, PlaceInbox};
use vectorcraft_ui_egui::{Services, VectorcraftApp};
use wasm_bindgen::JsCast as _;
type Inbox = Arc<Mutex<Vec<(String, Vec<u8>)>>>;
/// Where the pointer was over the canvas during the last file drag (CSS px from its top-left) and
/// whether Shift was held: where dropped files land.
type DragPos = Rc<Cell<Option<(f32, f32, bool)>>>;
const CANVAS_ID: &str = "vectorcraft_canvas";
const LOADING_ID: &str = "vectorcraft_loading";
@@ -23,6 +30,7 @@ pub fn start() {
log::error!("missing <canvas id=\"{CANVAS_ID}\">");
return;
};
let drag = track_drag(&canvas);
let mut options = eframe::WebOptions::default();
if query().contains("webgl")
&& let eframe::egui_wgpu::WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup
@@ -38,8 +46,9 @@ pub fn start() {
log::info!("vectorcraft-web: wgpu backend {:?}", rs.adapter.get_info().backend);
}
let inbox: Inbox = Arc::default();
let app = VectorcraftApp::new(Session::new(), services(inbox.clone(), cc.egui_ctx.clone()));
Ok(Box::new(WebShell { app, inbox }))
let place_inbox: PlaceInbox = Arc::default();
let app = VectorcraftApp::new(Session::new(), services(inbox.clone(), place_inbox.clone(), cc.egui_ctx.clone()));
Ok(Box::new(WebShell { app, inbox, place_inbox, drag }))
}),
)
.await;
@@ -56,29 +65,58 @@ fn query() -> String {
web_sys::window().and_then(|w| w.location().search().ok()).unwrap_or_default()
}
/// Follow file drags over the canvas: drag events carry the pointer position, which egui doesn't
/// get during a drag.
fn track_drag(canvas: &web_sys::HtmlCanvasElement) -> DragPos {
let pos = DragPos::default();
let p = pos.clone();
let on_drag = wasm_bindgen::closure::Closure::<dyn FnMut(web_sys::DragEvent)>::new(move |e: web_sys::DragEvent| {
p.set(Some((e.offset_x() as f32, e.offset_y() as f32, e.shift_key())));
});
for kind in ["dragover", "drop"] {
if let Err(e) = canvas.add_event_listener_with_callback(kind, on_drag.as_ref().unchecked_ref()) {
log::error!("couldn't follow {kind} events: {e:?}");
}
}
// The listener lives as long as the page.
on_drag.forget();
pos
}
/// Wraps the app to read dropped files asynchronously (browsers can't read them synchronously)
/// and feed them through the inbox.
/// and feed them through the inboxes: placed where they were dropped on the canvas, else opened.
struct WebShell {
app: VectorcraftApp,
inbox: Inbox,
place_inbox: PlaceInbox,
drag: DragPos,
}
impl eframe::App for WebShell {
fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
let dropped = ctx.input_mut(|i| std::mem::take(&mut i.raw.dropped_files));
for f in dropped {
let inbox = self.inbox.clone();
let ctx = ctx.clone();
wasm_bindgen_futures::spawn_local(async move {
let name = f.path().file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "dropped".into());
match f.bytes_async().await {
Ok(bytes) => {
inbox.lock().unwrap_or_else(|e| e.into_inner()).push((name, bytes));
ctx.request_repaint();
if !dropped.is_empty() {
let at = self.drag.take();
let z = ctx.zoom_factor();
let target = self.app.drop_target(at.map(|(x, y, _)| egui::pos2(x / z, y / z)), at.is_some_and(|a| a.2));
for f in dropped {
let (inbox, place_inbox, ctx) = (self.inbox.clone(), self.place_inbox.clone(), ctx.clone());
wasm_bindgen_futures::spawn_local(async move {
let name = f.path().file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "dropped".into());
match f.bytes_async().await {
Ok(bytes) => {
match target {
DropTarget::Place { at, embed } => {
place_inbox.lock().unwrap_or_else(|e| e.into_inner()).push(PlaceArrival { name, bytes, drop: Some((at, embed)) })
}
DropTarget::Open => inbox.lock().unwrap_or_else(|e| e.into_inner()).push((name, bytes)),
}
ctx.request_repaint();
}
Err(e) => log::error!("couldn't read dropped file {name}: {e}"),
}
Err(e) => log::error!("couldn't read dropped file {name}: {e}"),
}
});
});
}
}
self.app.logic(ctx);
}
@@ -92,9 +130,29 @@ impl eframe::App for WebShell {
}
}
fn services(inbox: Inbox, ctx: egui::Context) -> Services {
fn services(inbox: Inbox, place_inbox: PlaceInbox, ctx: egui::Context) -> Services {
let open_inbox = inbox.clone();
let picked = place_inbox.clone();
let place_ctx = ctx.clone();
Services {
// File → Place…: the picked files go to the Place dialog.
place_async: Some(Box::new(move || {
let inbox = picked.clone();
let ctx = place_ctx.clone();
wasm_bindgen_futures::spawn_local(async move {
let dialog = fileio::place_filters().fold(rfd::AsyncFileDialog::new().set_title("Place"), |d, (name, exts)| d.add_filter(name, exts));
let Some(files) = dialog.pick_files().await else {
return;
};
let mut arrived = vec![];
for f in files {
arrived.push(PlaceArrival { name: f.file_name(), bytes: f.read().await, drop: None });
}
inbox.lock().unwrap_or_else(|e| e.into_inner()).extend(arrived);
ctx.request_repaint();
});
})),
place_inbox: Some(place_inbox),
open_async: Some(Box::new(move || {
let inbox = open_inbox.clone();
let ctx = ctx.clone();
+5 -1
View File
@@ -19,9 +19,13 @@ log = { workspace = true }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
rfd = { workspace = true }
arboard = { workspace = true }
arboard = { workspace = true, features = ["image-data"] }
image = { workspace = true }
webbrowser = { workspace = true }
[target.'cfg(windows)'.dependencies]
clipboard-win = { workspace = true }
[target.'cfg(target_os = "macos")'.dependencies]
muda = { version = "0.21", default-features = false }
+4 -3
View File
@@ -4,12 +4,12 @@
//! cross-compile from macOS or Linux still links, unless `VECTORCRAFT_REQUIRE_WINRES=1` turns it into
//! an error (for release builds).
fn main() {
fn main() -> Result<(), String> {
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-changed=../../assets/app-icon/vectorcraft.ico");
println!("cargo:rerun-if-env-changed=VECTORCRAFT_REQUIRE_WINRES");
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") {
return;
return Ok(());
}
let mut res = winresource::WindowsResource::new();
res.set_icon("../../assets/app-icon/vectorcraft.ico")
@@ -21,8 +21,9 @@ fn main() {
.set("InternalName", "vectorcraft");
if let Err(e) = res.compile() {
if std::env::var_os("VECTORCRAFT_REQUIRE_WINRES").is_some() {
panic!("embedding Windows resources failed: {e}");
return Err(format!("embedding Windows resources failed: {e}"));
}
println!("cargo:warning=vectorcraft.exe built without icon/version resources: {e}");
}
Ok(())
}
+264
View File
@@ -0,0 +1,264 @@
//! The system clipboard with every format Copy offers and Paste reads
//! (`Services::system_clipboard`).
//!
//! - Windows: text, SVG, PDF, PNG and an opaque bitmap (for apps that don't read PNG) in one go;
//! Paste reads each of them.
//! - macOS and Linux: one format at a time, the text (a type-only copy's text or the SVG markup),
//! else the PNG as a bitmap; Paste reads text and bitmaps.
use std::io::Cursor;
use vectorcraft_engine::cmd::clipboard::{BITMAP, Flavour, PNG, TEXT};
use vectorcraft_ui_egui::SystemClipboard;
/// This platform's system clipboard.
pub fn system_clipboard() -> Box<dyn SystemClipboard> {
#[cfg(windows)]
let cb = Box::<win::Clipboard>::default();
#[cfg(not(windows))]
let cb = Box::<portable::Clipboard>::default();
cb
}
/// The text flavour among `flavours`.
fn text_of(flavours: &[Flavour]) -> Option<String> {
flavours.iter().find(|f| f.mime == TEXT).map(|f| String::from_utf8_lossy(&f.data).into_owned())
}
fn decode_png(png: &[u8]) -> Option<image::RgbaImage> {
Some(image::load_from_memory_with_format(png, image::ImageFormat::Png).ok()?.to_rgba8())
}
#[cfg(windows)]
mod win {
use std::num::NonZeroU32;
use clipboard_win::{formats, options::NoClear, raw};
use vectorcraft_engine::cmd::clipboard::{PDF, SVG};
use super::*;
/// The registered clipboard formats a flavour is written under (and read from, first held
/// first).
fn names(mime: &str) -> &'static [&'static str] {
match mime {
SVG => &["image/svg+xml"],
PDF => &["Portable Document Format", "application/pdf"],
PNG => &["PNG"],
_ => &[],
}
}
fn formats_of(mime: &str) -> impl Iterator<Item = u32> {
names(mime).iter().filter_map(|n| raw::register_format(n)).map(NonZeroU32::get)
}
fn err(e: impl std::fmt::Display) -> String {
format!("{e}")
}
/// `png` over white, as a BMP file (what the bitmap format takes).
fn opaque_bmp(png: &[u8]) -> Option<Vec<u8>> {
let img = decode_png(png)?;
let over = |c: u8, a: u8| ((u32::from(c) * u32::from(a) + 255 * (255 - u32::from(a)) + 127) / 255) as u8;
let mut rgb = Vec::with_capacity(img.as_raw().len() / 4 * 3);
for p in img.pixels() {
let [r, g, b, a] = p.0;
rgb.extend([over(r, a), over(g, a), over(b, a)]);
}
let rgb = image::RgbImage::from_raw(img.width(), img.height(), rgb)?;
let mut bmp = vec![];
rgb.write_to(&mut Cursor::new(&mut bmp), image::ImageFormat::Bmp).ok()?;
Some(bmp)
}
#[derive(Default)]
pub struct Clipboard {
/// The clipboard's sequence number right after our last write.
seq: Option<NonZeroU32>,
/// The text of our last write.
text: Option<String>,
}
impl SystemClipboard for Clipboard {
/// Writes every flavour it can; the first failure is reported.
fn write(&mut self, flavours: &[Flavour]) -> Result<(), String> {
let mut result = Ok(());
{
let _open = clipboard_win::Clipboard::new_attempts(10).map_err(err)?;
raw::empty().map_err(err)?;
let mut set = |r: clipboard_win::SysResult<()>| {
if result.is_ok() {
result = r.map_err(err);
}
};
for f in flavours {
if f.mime == TEXT {
set(raw::set_string_with(&String::from_utf8_lossy(&f.data), NoClear));
continue;
}
for id in formats_of(f.mime) {
set(raw::set_without_clear(id, &f.data));
}
if f.mime == PNG
&& let Some(bmp) = opaque_bmp(&f.data)
{
set(raw::set_bitmap_with(&bmp, NoClear));
}
}
}
self.seq = raw::seq_num();
self.text = text_of(flavours);
result
}
fn holds_ours(&mut self) -> bool {
if self.seq.is_some() && raw::seq_num() == self.seq {
return true;
}
// A clipboard manager may have copied our data again as its own.
let Some(ours) = self.text.as_deref() else { return false };
let Ok(_open) = clipboard_win::Clipboard::new_attempts(10) else { return false };
read_one(TEXT).is_some_and(|f| f.data == ours.as_bytes())
}
fn read(&mut self, mimes: &[&'static str]) -> Option<Flavour> {
let _open = clipboard_win::Clipboard::new_attempts(10).ok()?;
mimes.iter().find_map(|m| read_one(m))
}
fn has(&mut self, mimes: &[&'static str]) -> bool {
mimes.iter().any(|m| match *m {
TEXT => raw::is_format_avail(formats::CF_UNICODETEXT),
BITMAP => raw::is_format_avail(formats::CF_BITMAP) || formats_of(PNG).any(raw::is_format_avail),
m => formats_of(m).any(raw::is_format_avail),
})
}
}
/// Read the first registered format of `mime` the clipboard holds into `data`.
fn read_registered(mime: &str, data: &mut Vec<u8>) -> bool {
formats_of(mime).filter(|id| raw::is_format_avail(*id)).any(|id| {
data.clear();
raw::get_vec(id, data).is_ok() && !data.is_empty()
})
}
/// One flavour, while the clipboard is open.
fn read_one(mime: &'static str) -> Option<Flavour> {
let mut data = vec![];
let mime = match mime {
BITMAP if read_registered(PNG, &mut data) => PNG,
BITMAP => {
data.clear();
raw::get_bitmap(&mut data).ok()?;
"image/bmp"
}
TEXT => {
raw::get_string(&mut data).ok()?;
TEXT
}
m if read_registered(m, &mut data) => m,
_ => return None,
};
// Memory blocks can be longer than the data: SVG text ends at its first NUL.
if mime == SVG
&& let Some(end) = data.iter().position(|b| *b == 0)
{
data.truncate(end);
}
(!data.is_empty()).then_some(Flavour { mime, data })
}
}
/// arboard: one format at a time. Built everywhere so it is checked everywhere.
#[cfg_attr(windows, allow(dead_code))]
mod portable {
use std::borrow::Cow;
use super::*;
/// `img` as PNG bytes.
fn encode_png(img: &image::RgbaImage) -> Option<Vec<u8>> {
let mut out = vec![];
img.write_to(&mut Cursor::new(&mut out), image::ImageFormat::Png).ok()?;
Some(out)
}
/// What our last write put on the clipboard.
enum Ours {
Text(String),
Image(usize, usize),
}
#[derive(Default)]
pub struct Clipboard {
/// Kept open: on Linux the copied data lives as long as the handle does.
cb: Option<arboard::Clipboard>,
ours: Option<Ours>,
}
impl Clipboard {
fn cb(&mut self) -> Result<&mut arboard::Clipboard, String> {
if self.cb.is_none() {
self.cb = Some(arboard::Clipboard::new().map_err(|e| e.to_string())?);
}
self.cb.as_mut().ok_or_else(|| "no system clipboard".to_string())
}
}
impl SystemClipboard for Clipboard {
fn write(&mut self, flavours: &[Flavour]) -> Result<(), String> {
let text = text_of(flavours);
let image = match &text {
Some(_) => None,
None => flavours.iter().find(|f| f.mime == PNG).and_then(|f| decode_png(&f.data)),
};
let cb = self.cb()?;
let ours = match (text, image) {
(Some(t), _) => {
cb.set_text(t.as_str()).map_err(|e| e.to_string())?;
Some(Ours::Text(t))
}
(None, Some(img)) => {
let (width, height) = (img.width() as usize, img.height() as usize);
cb.set_image(arboard::ImageData { width, height, bytes: Cow::Owned(img.into_raw()) }).map_err(|e| e.to_string())?;
Some(Ours::Image(width, height))
}
(None, None) => {
cb.clear().map_err(|e| e.to_string())?;
None
}
};
self.ours = ours;
Ok(())
}
fn holds_ours(&mut self) -> bool {
let Some(cb) = self.cb.as_mut() else { return false };
match &self.ours {
Some(Ours::Text(t)) => cb.get_text().is_ok_and(|now| now == *t),
Some(Ours::Image(w, h)) => cb.get_image().is_ok_and(|now| (now.width, now.height) == (*w, *h)),
None => false,
}
}
fn read(&mut self, mimes: &[&'static str]) -> Option<Flavour> {
let cb = self.cb().ok()?;
mimes.iter().find_map(|m| match *m {
TEXT => cb.get_text().ok().filter(|t| !t.is_empty()).map(|t| Flavour { mime: TEXT, data: t.into_bytes() }),
BITMAP => {
let img = cb.get_image().ok()?;
let rgba = image::RgbaImage::from_raw(u32::try_from(img.width).ok()?, u32::try_from(img.height).ok()?, img.bytes.into_owned())?;
encode_png(&rgba).map(|data| Flavour { mime: PNG, data })
}
_ => None,
})
}
/// Text only: reading a bitmap costs as much as pasting it.
fn has(&mut self, mimes: &[&'static str]) -> bool {
mimes.contains(&TEXT) && self.cb().is_ok_and(|cb| cb.get_text().is_ok_and(|t| !t.is_empty()))
}
}
}
+100 -11
View File
@@ -6,13 +6,14 @@
//! `{"id":1,"method":"ui.inspect","params":{}}` → `{"id":1,"ok":true,"result":…}`.
//! See `vectorcraft_ui_egui::control` for the methods.
mod clipboard;
mod control_server;
#[cfg(target_os = "macos")]
mod native_menu;
use vectorcraft_engine::Session;
use vectorcraft_engine::cmd::fileio;
use vectorcraft_ui_egui::{Services, VectorcraftApp};
use vectorcraft_ui_egui::{FilePick, Services, VectorcraftApp};
struct App(VectorcraftApp, #[cfg(target_os = "macos")] Option<native_menu::NativeMenu>);
@@ -91,32 +92,112 @@ fn save_prefs(app: &VectorcraftApp) {
let mut ui = app.ui.clone();
ui.engine_prefs = app.session.prefs.to_json();
if let Ok(bytes) = serde_json::to_vec_pretty(&ui) {
let _ = std::fs::write(p, bytes);
// Preferences are best effort: a failed write keeps the previous file.
let _ = fileio::write_atomic(&p, &bytes);
}
}
}
/// A native file dialog showing `pick`'s file types, folder and suggested name.
fn file_dialog(pick: &FilePick) -> rfd::FileDialog {
let d = pick.filters.iter().fold(rfd::FileDialog::new(), |d, (name, exts)| d.add_filter(*name, exts));
let d = match &pick.folder {
Some(folder) => d.set_directory(folder),
None => d,
};
if pick.name.is_empty() { d } else { d.set_file_name(&pick.name) }
}
/// File → Show in Folder: select `path` in Finder / Explorer, or open its folder elsewhere.
fn reveal(path: &str) -> Result<(), String> {
reveal_command(path).spawn().map(|_| ()).map_err(|e| format!("can't show {path}: {e}"))
}
#[cfg(target_os = "macos")]
fn reveal_command(path: &str) -> std::process::Command {
let mut c = std::process::Command::new("open");
c.args(["-R", path]);
c
}
#[cfg(windows)]
fn reveal_command(path: &str) -> std::process::Command {
use std::os::windows::process::CommandExt as _;
// Explorer reads `/select,"path"` itself (the usual argument quoting breaks paths with spaces)
// and needs backslashes.
let mut c = std::process::Command::new("explorer");
c.raw_arg(format!("/select,\"{}\"", path.replace('/', "\\")));
c
}
#[cfg(not(any(target_os = "macos", windows)))]
fn reveal_command(path: &str) -> std::process::Command {
let folder = std::path::Path::new(path).parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or(std::path::Path::new("."));
let mut c = std::process::Command::new("xdg-open");
c.arg(folder);
c
}
/// Write a file the safe way: a failed write keeps the old file ([`fileio::write_atomic`]).
fn write_file(path: &str, bytes: &[u8]) -> Result<(), String> {
fileio::write_atomic(std::path::Path::new(path), bytes).map_err(|e| e.to_string())
}
fn services() -> Services {
Services {
pick_open: Some(Box::new(|| {
fileio::open_filters()
.fold(rfd::FileDialog::new(), |d, (name, exts)| d.add_filter(name, exts))
.pick_file()
pick_open: Some(Box::new(|pick: &FilePick| file_dialog(pick).pick_file().map(|p| p.to_string_lossy().to_string()))),
pick_open_multi: Some(Box::new(|| {
fileio::place_filters()
.fold(rfd::FileDialog::new().set_title("Place"), |d, (name, exts)| d.add_filter(name, exts))
.pick_files()
.unwrap_or_default()
.into_iter()
.map(|p| p.to_string_lossy().to_string())
.collect()
})),
pick_save: Some(Box::new(|pick: &FilePick| {
// The Templates folder may not exist yet.
if let Some(folder) = &pick.folder {
let _ = std::fs::create_dir_all(folder);
}
file_dialog(pick).save_file().map(|p| p.to_string_lossy().to_string())
})),
pick_save: Some(Box::new(|name: &str| rfd::FileDialog::new().set_file_name(name).save_file().map(|p| p.to_string_lossy().to_string()))),
read: Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))),
write: Some(Box::new(|p: &str, b: &[u8]| std::fs::write(p, b).map_err(|e| e.to_string()))),
// Menu-bar Paste never sees egui's Paste event, so read the clipboard directly.
clipboard_read: Some(Box::new(|| arboard::Clipboard::new().ok()?.get_text().ok())),
write: Some(Box::new(write_file)),
// Background Save and Export write from a worker thread.
write_shared: Some(std::sync::Arc::new(write_file)),
// Every format Copy offers and Paste reads (menu-bar Paste never sees egui's Paste event).
system_clipboard: Some(clipboard::system_clipboard()),
// Help → Discord / website / GitHub, the Discord button, About and Home links.
open_url: Some(Box::new(|url: &str| {
let _ = webbrowser::open(url);
})),
reveal: Some(Box::new(reveal)),
// Links panel: Edit Original; Package: Show Package. Relink to Folder and Package pick folders.
open_file: Some(Box::new(open_file)),
pick_folder: Some(Box::new(|| rfd::FileDialog::new().pick_folder().map(|p| p.to_string_lossy().to_string()))),
..Default::default()
}
}
/// Edit Original, Show Package: open `path` (a file or a folder) in the system's default app for it.
fn open_file(path: &str) -> Result<(), String> {
#[cfg(windows)]
let mut c = {
use std::os::windows::process::CommandExt as _;
let mut c = std::process::Command::new("explorer");
c.raw_arg(format!("\"{}\"", path.replace('/', "\\")));
c
};
#[cfg(target_os = "macos")]
let mut c = std::process::Command::new("open");
#[cfg(not(any(target_os = "macos", windows)))]
let mut c = std::process::Command::new("xdg-open");
#[cfg(not(windows))]
c.arg(path);
c.spawn().map(|_| ()).map_err(|e| format!("can't open {path}: {e}"))
}
/// The window, Dock, taskbar and app-switcher icon (`assets/app-icon/`, see its README). macOS gets
/// the version with Apple's transparent margin; elsewhere the full-bleed tile. The app ID matches
/// `packaging/linux/ai.storyteller.vectorcraft.desktop` so Wayland docks find the launcher icon.
@@ -128,6 +209,10 @@ fn app_icon() -> egui::IconData {
eframe::icon_data::from_png_bytes(png).unwrap_or_default()
}
/// Windows and Linux: no OS title bar; the app bar is the title bar (`vectorcraft_ui_egui::titlebar`).
/// macOS keeps its traffic lights over the integrated title strip.
const CUSTOM_TITLEBAR: bool = !cfg!(target_os = "macos");
fn main() -> eframe::Result {
let mut control_port: Option<u16> = std::env::var("VECTORCRAFT_CONTROL_PORT").ok().and_then(|p| p.parse().ok());
let mut files = Vec::new();
@@ -148,6 +233,7 @@ fn main() -> eframe::Result {
.with_inner_size([1440.0, 900.0])
.with_min_inner_size([800.0, 500.0])
.with_drag_and_drop(true)
.with_decorations(!CUSTOM_TITLEBAR)
.with_fullsize_content_view(true)
.with_titlebar_shown(false)
.with_title_shown(false)
@@ -161,10 +247,13 @@ fn main() -> eframe::Result {
Box::new(move |cc| {
let mut app = VectorcraftApp::new(Session::new(), services());
load_prefs(&mut app);
// User Defined swatch libraries live next to the preferences.
// User Defined swatch and graphic style libraries live next to the preferences.
let swatches = prefs_path().and_then(|p| Some(p.parent()?.join("Swatches").to_string_lossy().to_string()));
app.session.swatch_libraries.set_user_dir(swatches);
let styles = prefs_path().and_then(|p| Some(p.parent()?.join("Graphic Styles").to_string_lossy().to_string()));
app.session.style_libraries.set_user_dir(styles);
app.integrated_titlebar = cfg!(target_os = "macos");
app.custom_titlebar = CUSTOM_TITLEBAR;
if let Some(port) = control_port {
let rx = control_server::start(port, cc.egui_ctx.clone());
app = app.with_control(rx);
+12 -4
View File
@@ -1,6 +1,7 @@
//! macOS: VectorCraft's menu tree as the native system menu bar (like Illustrator on the Mac).
//! Items dispatch through the same command path as the in-window menus; enablement, check marks
//! and dynamic labels ("Undo Move") are refreshed a few times per second.
//! and dynamic labels ("Undo Move") are refreshed a few times per second, and the menu is rebuilt
//! when saved views or recent files come and go.
use std::collections::HashMap;
use std::str::FromStr;
@@ -22,6 +23,8 @@ pub struct NativeMenu {
last_refresh: f64,
/// Shortcut-override / workspace-list generation the menu was built for.
generation: u64,
/// Saved views and recent files listed (empty slots are left out, so a change rebuilds).
slots: usize,
}
/// Accelerator for a shortcut like "Cmd+Shift+]" (modifier-less shortcuts stay in the app so they
@@ -53,7 +56,7 @@ impl NativeMenu {
.filter(|(_, p, _, c)| (p.is_null() || p.as_object().is_some_and(|o| o.is_empty())) && menus::shortcut_of(c).and_then(accel).is_some())
.map(|(_, _, _, c)| c.clone())
.collect();
Self { _menu: menu, items, last_refresh: 0.0, generation }
Self { _menu: menu, items, last_refresh: 0.0, generation, slots: menus::listed_slots(app) }
}
/// Dispatch clicked items and refresh state.
@@ -69,8 +72,11 @@ impl NativeMenu {
return;
}
self.last_refresh = now;
// Shortcuts edited or workspaces added: rebuild so accelerators and lists are current.
if vectorcraft_ui_egui::shortcut_editor::GENERATION.load(std::sync::atomic::Ordering::Relaxed) != self.generation {
// Shortcuts edited, workspaces added, saved views or recent files changed: rebuild so
// accelerators and lists are current.
if vectorcraft_ui_egui::shortcut_editor::GENERATION.load(std::sync::atomic::Ordering::Relaxed) != self.generation
|| menus::listed_slots(app) != self.slots
{
*self = NativeMenu::install(app);
return;
}
@@ -137,6 +143,8 @@ fn build(
build(app, &sub, children, items, counter);
let _ = parent.append(&sub);
}
// Unused saved-view and recent-file slots are left out, as in the in-window menus.
Item::Cmd(_, cmd, _) if menus::hidden_slot(app, cmd) => {}
Item::Cmd(label, cmd, params) => {
*counter += 1;
let id = format!("dc{counter}");
+1 -1
View File
@@ -31,7 +31,7 @@ artwork. Licence: see `LICENSE.txt`.
| `vectorcraft-macos-512.png` | tile with Apple margin, 512 px | runtime Dock icon (`apps/vectorcraft/src/main.rs`) |
| `vectorcraft.icns` | macOS icon set, 16 to 1024 px | `cargo xtask bundle` (`CFBundleIconFile`) |
| `vectorcraft.ico` | Windows icon, 16 to 256 px | `apps/vectorcraft/build.rs` (embedded in the `.exe`) |
| `hicolor/<size>/apps/ai.storyteller.vectorcraft.png` | Linux theme icons, 16 to 512 px; the 256 one is also the runtime icon on Windows and Linux | `packaging/linux/ai.storyteller.vectorcraft.desktop` |
| `hicolor/<size>/apps/ai.storyteller.vectorcraft.png` | Linux theme icons, 16 to 512 px; the 256 one is also the runtime icon on Windows and Linux, the 128 one the brand mark in the app bar and About box (`crates/ui-egui/src/brand.rs`) | `packaging/linux/ai.storyteller.vectorcraft.desktop` |
| `hicolor/scalable/apps/ai.storyteller.vectorcraft.svg` | Linux scalable icon | as above |
## How it reaches each OS
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><rect x="4.75" y="4.75" width="14.5" height="14.5"/></svg>

After

Width:  |  Height:  |  Size: 241 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><rect x="4.75" y="4.75" width="14.5" height="14.5"/><rect x="10" y="10" width="4" height="4" fill="currentColor" stroke="none"/></svg>

After

Width:  |  Height:  |  Size: 317 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M12 5.5A6.5 6.5 0 1 1 5.5 12"/><path d="M3 14.5L5.5 11.5L8 14.5"/></svg>

After

Width:  |  Height:  |  Size: 264 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M12 5.5A6.5 6.5 0 1 0 18.5 12"/><path d="M16 14.5L18.5 11.5L21 14.5"/></svg>

After

Width:  |  Height:  |  Size: 268 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><g stroke-width="1.34"><path d="M3.66 20V9a5.34 5.34 0 0 1 5.34-5.34h11" stroke-opacity="0.2"/><path d="M5 20V9a4 4 0 0 1 4-4h11" stroke-opacity="0.6"/><path d="M6.34 20V9a2.66 2.66 0 0 1 2.66-2.66h11"/></g></svg>

After

Width:  |  Height:  |  Size: 396 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><g stroke-width="4"><path d="M5 20v-5" stroke-opacity="0.2"/><path d="M5 15v-6" stroke-opacity="0.45"/><path d="M5 9a4 4 0 0 1 4-4h2" stroke-opacity="0.7"/><path d="M11 5h9"/></g></svg>

After

Width:  |  Height:  |  Size: 368 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><defs><linearGradient id="g" gradientUnits="userSpaceOnUse" x1="3" y1="0" x2="21" y2="0"><stop offset="0" stop-color="white" stop-opacity="0.15"/><stop offset="1" stop-color="white"/></linearGradient></defs><path d="M5 20V9a4 4 0 0 1 4-4h11" stroke="url(#g)" stroke-width="4"/></svg>

After

Width:  |  Height:  |  Size: 466 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M4 4H20V20H4Z M8.5 8.5H15.5V15.5H8.5Z" fill="currentColor" fill-opacity="0.55" fill-rule="evenodd" stroke-width="1"/></svg>

After

Width:  |  Height:  |  Size: 315 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M4 4H20V20H4Z M8.5 8.5H15.5V15.5H8.5Z" fill="currentColor" fill-opacity="0.55" fill-rule="nonzero" stroke-width="1"/></svg>

After

Width:  |  Height:  |  Size: 315 B

+5
View File
@@ -0,0 +1,5 @@
# Tests may unwrap, expect and panic: a failing assertion is the point of a test. Shipped code may
# not (workspace lints in Cargo.toml; AGENTS.md › Robustness).
allow-unwrap-in-tests = true
allow-expect-in-tests = true
allow-panic-in-tests = true
+1 -2
View File
@@ -83,10 +83,9 @@ pub(crate) fn sweep(t: &Track, nib: &Nib) -> Vec<SubPath> {
};
let half = std::f64::consts::FRAC_PI_2;
let mut poly = left.clone();
let (pe, te) = *s.last().unwrap();
let (Some(&(pe, te)), Some(&(ps, ts))) = (s.last(), s.first()) else { return Vec::new() };
cap(pe, te, half, -half, &mut poly);
poly.extend(right.iter().rev());
let (ps, ts) = s[0];
cap(ps, ts, -half, -3.0 * half, &mut poly);
vec![SubPath::polyline(&poly, true)]
}
+20 -6
View File
@@ -37,9 +37,8 @@ fn map_color(c: &Color, mode: Colorization, key: &Color) -> Color {
}
fn map_paint(p: &mut Paint, mode: Colorization, key: &Color) {
if let Paint::Solid { color, swatch } = p {
*color = map_color(color, mode, key);
*swatch = None;
if let Paint::Solid { color, .. } = p {
*p = Paint::solid(map_color(color, mode, key));
}
}
@@ -83,9 +82,8 @@ pub fn tint_node(n: &mut Node, color: &Color, amount: f32) {
AppearanceItem::Fill(f) => &mut f.paint,
AppearanceItem::Stroke(s) => &mut s.paint,
};
if let Paint::Solid { color: c, swatch } = p {
*c = c.lerp(color, amount);
*swatch = None;
if let Paint::Solid { color: c, .. } = p {
*p = Paint::solid(c.lerp(color, amount));
}
}
if let vectorcraft_doc::NodeKind::Text(t) = &mut n.kind {
@@ -101,3 +99,19 @@ pub fn tint_node(n: &mut Node, color: &Color, amount: f32) {
}
}
}
/// The stain instance `inst` puts on its symbol's art: its visible fill colour and that fill's
/// opacity (how far the art mixes towards it). `None` for an unstained instance.
pub fn stain(inst: &Node) -> Option<(Color, f32)> {
let f = inst.appearance.fill().filter(|f| f.visible)?;
Some((f.paint.color()?, f.opacity))
}
/// A symbol's art for instance `inst`, stained by the instance's fill ([`stain`]).
pub fn instance_art(art: &Node, inst: &Node) -> Node {
let mut a = art.clone();
if let Some((c, amount)) = stain(inst) {
tint_node(&mut a, &c, amount);
}
a
}
+6 -2
View File
@@ -23,7 +23,7 @@ use vectorcraft_color::Paint;
use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, NodeId, NodeKind, StrokeLayer};
use vectorcraft_geom::{BezPath, Rect};
pub use colorize::{colorize, tint_node};
pub use colorize::{colorize, instance_art, stain, tint_node};
pub use defaults::defaults;
pub use serde_json;
@@ -325,7 +325,11 @@ pub fn unique_name(lib: &[Brush], base: &str) -> String {
if !lib.iter().any(|b| b.name == base) {
return base.to_string();
}
(2..).map(|i| format!("{base} {i}")).find(|n| !lib.iter().any(|b| &b.name == n)).unwrap()
// At most `lib.len()` names are taken, so one of the first `lib.len() + 1` candidates is free.
(2..=lib.len() + 2)
.map(|i| format!("{base} {i}"))
.find(|n| !lib.iter().any(|b| &b.name == n))
.unwrap_or_else(|| format!("{base} {}", lib.len() + 2))
}
// ---------- geometry ----------
+1 -1
View File
@@ -267,7 +267,7 @@ fn bristle_makes_translucent_strands() {
#[test]
fn tints_colorization_uses_stroke_colour() {
let b = art_brush(rect_art(10.0, 4.0), ArtScale::Stretch);
let BrushKind::Art(mut a) = b.kind else { unreachable!() };
let BrushKind::Art(mut a) = b.kind else { panic!("not an art brush") };
a.colorization = Colorization::Tints;
let b = Brush { name: "t".into(), kind: BrushKind::Art(a) };
let out = stroke_pieces(&b, &line(0.0, 0.0, 50.0, 0.0), &stroke(1.0));
+3 -3
View File
@@ -76,11 +76,11 @@ impl Track {
corner.push(a.dot(b) < cos_limit);
tangents.push(unit(a + b));
}
(Some(a), None) | (None, Some(a)) => {
(a, b) => {
// An end of an open track (both `None` only for a track without segments).
corner.push(false);
tangents.push(a);
tangents.push(a.or(b).unwrap_or(Vec2::new(1.0, 0.0)));
}
(None, None) => unreachable!(),
}
}
Some(Track { verts: pts, cum, closed, dirs, tangents, corner })
+23
View File
@@ -0,0 +1,23 @@
[package]
name = "vectorcraft-cad"
version.workspace = true
edition.workspace = true
license.workspace = true
description = "VectorCraft CAD interchange: a hand-written ASCII DXF writer (R12 to 2018)"
[lints]
workspace = true
[dependencies]
vectorcraft-geom = { workspace = true }
vectorcraft-color = { workspace = true }
vectorcraft-doc = { workspace = true }
vectorcraft-effects = { workspace = true }
vectorcraft-brush = { workspace = true }
vectorcraft-pathops = { workspace = true }
vectorcraft-text = { workspace = true }
kurbo = { workspace = true }
image = { workspace = true }
[dev-dependencies]
serde_json = { workspace = true }
+105
View File
@@ -0,0 +1,105 @@
//! The 256-colour index palette CAD apps share, generated rather than tabulated: indices 1–9 are
//! the standard colours, 10–249 run through 24 hues at five brightnesses each in a full and a
//! half-saturated tone, and 250–255 are greys.
use crate::ColorDepth;
/// The nine standard colours (index 7 shows white on a dark background and black on paper).
const STANDARD: [[u8; 3]; 9] =
[[255, 0, 0], [255, 255, 0], [0, 255, 0], [0, 255, 255], [0, 0, 255], [255, 0, 255], [255, 255, 255], [128, 128, 128], [192, 192, 192]];
/// The brightness of the five shades of each hue.
const SHADES: [f64; 5] = [1.0, 0.65, 0.5, 0.3, 0.15];
/// The RGB of colour index `i` (1–255; anything else is index 7's white).
pub fn aci_rgb(i: u8) -> [u8; 3] {
match i {
1..=9 => STANDARD[usize::from(i - 1)],
10..=249 => {
let hue = f64::from(i / 10 - 1) * 15.0;
let k = i % 10;
let v = SHADES[usize::from(k / 2)];
let pastel = k % 2 == 1;
hue_rgb(hue).map(|f| {
let f = if pastel { f + (1.0 - f) / 2.0 } else { f };
(255.0 * v * f).floor() as u8
})
}
250..=255 => {
let g = (51.0 + 204.0 * f64::from(i - 250) / 5.0).floor() as u8;
[g; 3]
}
_ => STANDARD[6],
}
}
/// The fully saturated, full-brightness colour of `hue` degrees as 0–1 channels.
fn hue_rgb(hue: f64) -> [f64; 3] {
let h = hue.rem_euclid(360.0) / 60.0;
let x = 1.0 - (h % 2.0 - 1.0).abs();
match h as u8 {
0 => [1.0, x, 0.0],
1 => [x, 1.0, 0.0],
2 => [0.0, 1.0, x],
3 => [0.0, x, 1.0],
4 => [x, 0.0, 1.0],
_ => [1.0, 0.0, x],
}
}
/// The indices a colour depth may use (true colour: all of them, for the fallback index).
fn candidates(depth: ColorDepth) -> Box<dyn Iterator<Item = u8>> {
match depth {
ColorDepth::Aci8 => Box::new(1..=8),
ColorDepth::Aci16 => Box::new((1..=9).chain([30]).chain(250..=255)),
ColorDepth::Aci256 | ColorDepth::True => Box::new(1..=255),
}
}
/// The index of `depth` nearest to `rgb` (squared RGB distance; ties go to the lower index).
/// Index 7 stands for both white and black, as CAD apps draw it in the background's contrast.
pub fn nearest_aci(rgb: [u8; 3], depth: ColorDepth) -> u8 {
let dist = |c: [u8; 3]| rgb.iter().zip(c).map(|(a, b)| (i32::from(*a) - i32::from(b)).pow(2)).sum::<i32>();
candidates(depth).min_by_key(|i| if *i == 7 { dist([255; 3]).min(dist([0; 3])) } else { dist(aci_rgb(*i)) }).unwrap_or(7)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_palette_matches_its_known_entries() {
let known: [(u8, [u8; 3]); 14] = [
(1, [255, 0, 0]),
(10, [255, 0, 0]),
(11, [255, 127, 127]),
(12, [165, 0, 0]),
(13, [165, 82, 82]),
(17, [76, 38, 38]),
(19, [38, 19, 19]),
(20, [255, 63, 0]),
(21, [255, 159, 127]),
(30, [255, 127, 0]),
(140, [0, 191, 255]),
(250, [51, 51, 51]),
(252, [132, 132, 132]),
(255, [255, 255, 255]),
];
for (i, rgb) in known {
assert_eq!(aci_rgb(i), rgb, "index {i}");
}
}
#[test]
fn nearest_index_by_depth() {
assert_eq!(nearest_aci([255, 0, 0], ColorDepth::Aci8), 1);
assert_eq!(nearest_aci([0, 0, 0], ColorDepth::Aci256), 7, "black is index 7");
assert_eq!(nearest_aci([255, 255, 255], ColorDepth::Aci16), 7);
assert_eq!(nearest_aci([255, 127, 0], ColorDepth::Aci256), 30);
assert_eq!(nearest_aci([255, 127, 0], ColorDepth::Aci16), 30);
assert_eq!(nearest_aci([255, 127, 0], ColorDepth::Aci8), 1, "8 colours: red is nearest");
assert_eq!(nearest_aci([60, 60, 60], ColorDepth::Aci16), 250);
assert_eq!(nearest_aci([100, 100, 100], ColorDepth::Aci8), 8);
assert_eq!(nearest_aci([60, 60, 60], ColorDepth::Aci8), 7, "dark greys go to black");
}
}
+325
View File
@@ -0,0 +1,325 @@
//! CAD interchange: a hand-written ASCII DXF writer, versions R12 to 2018.
//!
//! [`export`] writes the visible art of a document into one DXF drawing: each layer becomes a DXF
//! layer (hidden ones switched off, locked ones locked, non-printing ones not plotted), paths
//! become polylines (straight segments) or cubic splines (curves), fills solid hatches, type text
//! entities or glyph outlines, and placed images image entities linked to PNG or JPEG files the
//! caller writes next to the drawing. Coordinates are y-up, in drawing units: `scale` units per
//! `unit` of the art, with the origin at the bottom-left corner of [`DxfOptions::region`].
//!
//! What DXF can't hold (blending modes, opacity masks, raster effects, gradients, patterns,
//! clipping) is approximated or left out, and each such loss comes back as a warning.
//!
//! - `aci`: the 256-colour index palette and the nearest index of a colour.
//! - `writer`: group codes, handles and the file's sections, tables and objects.
//! - `scene`: the document walk that turns objects into entities.
mod aci;
mod scene;
mod writer;
use vectorcraft_doc::{Document, Unit};
use vectorcraft_geom::Rect;
pub use aci::{aci_rgb, nearest_aci};
/// The DXF version a file is written for (the `$ACADVER` it declares).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
pub enum DxfVersion {
R12,
R13,
R14,
R2000,
R2004,
R2007,
R2010,
R2013,
#[default]
R2018,
}
impl DxfVersion {
/// Newest first, as version menus list them.
pub const ALL: [Self; 9] = [Self::R2018, Self::R2013, Self::R2010, Self::R2007, Self::R2004, Self::R2000, Self::R14, Self::R13, Self::R12];
/// The `version` param value.
pub fn id(self) -> &'static str {
match self {
Self::R12 => "R12",
Self::R13 => "R13",
Self::R14 => "R14",
Self::R2000 => "2000",
Self::R2004 => "2004",
Self::R2007 => "2007",
Self::R2010 => "2010",
Self::R2013 => "2013",
Self::R2018 => "2018",
}
}
/// The releases that write this version (menus).
pub fn label(self) -> &'static str {
match self {
Self::R12 => "R12",
Self::R13 => "R13",
Self::R14 => "R14",
Self::R2000 => "2000–2002",
Self::R2004 => "2004–2006",
Self::R2007 => "2007–2009",
Self::R2010 => "2010–2012",
Self::R2013 => "2013–2017",
Self::R2018 => "2018",
}
}
/// The `$ACADVER` header value.
pub fn acadver(self) -> &'static str {
match self {
Self::R12 => "AC1009",
Self::R13 => "AC1012",
Self::R14 => "AC1014",
Self::R2000 => "AC1015",
Self::R2004 => "AC1018",
Self::R2007 => "AC1021",
Self::R2010 => "AC1024",
Self::R2013 => "AC1027",
Self::R2018 => "AC1032",
}
}
/// A version by id (`2018`, `R2018`, `r12`) or `$ACADVER` (`AC1032`), any case.
pub fn from_id(s: &str) -> Option<Self> {
let s = s.trim();
Self::ALL.into_iter().find(|v| {
let id = v.id();
s.eq_ignore_ascii_case(id) || s.eq_ignore_ascii_case(v.acadver()) || s.strip_prefix(['R', 'r']).is_some_and(|y| y == id)
})
}
/// Objects carry handles and subclass markers; splines, hatches and images exist.
fn handles(self) -> bool {
self >= Self::R13
}
/// Lightweight polylines.
fn lwpolyline(self) -> bool {
self >= Self::R14
}
/// Lineweights, layouts, plot styles and long symbol names.
fn r2000(self) -> bool {
self >= Self::R2000
}
/// True colour and transparency.
fn true_color(self) -> bool {
self >= Self::R2004
}
/// Text is UTF-8 (earlier versions escape what isn't ASCII as `\U+XXXX`).
fn utf8(self) -> bool {
self >= Self::R2007
}
}
/// How many colours entities may use: indexed colours of the 256-colour palette, or true colour
/// (with the nearest index for apps that read only the index).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ColorDepth {
/// Indices 1–8: the seven standard colours and dark grey.
Aci8,
/// Indices 1–9, orange (30) and the six greys (250–255).
Aci16,
/// Every index 1–255.
Aci256,
/// 24-bit colour (DXF 2004 and later).
#[default]
True,
}
impl ColorDepth {
pub const ALL: [Self; 4] = [Self::Aci8, Self::Aci16, Self::Aci256, Self::True];
/// The `colors` param value.
pub fn id(self) -> &'static str {
match self {
Self::Aci8 => "8",
Self::Aci16 => "16",
Self::Aci256 => "256",
Self::True => "true",
}
}
pub fn label(self) -> &'static str {
match self {
Self::Aci8 => "8 Colors",
Self::Aci16 => "16 Colors",
Self::Aci256 => "256 Colors",
Self::True => "True Colors",
}
}
/// A depth by id (`8`, `16`, `256`, `true`; `truecolor` and `24` also read).
pub fn from_id(s: &str) -> Option<Self> {
let s = s.trim().to_ascii_lowercase();
match s.as_str() {
"truecolor" | "truecolors" | "true colors" | "24" => Some(Self::True),
_ => Self::ALL.into_iter().find(|d| d.id() == s),
}
}
}
/// The file format placed images are written in.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum RasterFormat {
#[default]
Png,
/// No transparency: transparent pixels show white.
Jpeg,
}
impl RasterFormat {
pub const ALL: [Self; 2] = [Self::Png, Self::Jpeg];
/// The `rasterFormat` param value.
pub fn id(self) -> &'static str {
match self {
Self::Png => "png",
Self::Jpeg => "jpeg",
}
}
pub fn label(self) -> &'static str {
match self {
Self::Png => "PNG",
Self::Jpeg => "JPEG",
}
}
/// The extension the image files get.
pub fn extension(self) -> &'static str {
match self {
Self::Png => "png",
Self::Jpeg => "jpg",
}
}
/// A format by id (`png`, `jpeg`, `jpg`), any case.
pub fn from_id(s: &str) -> Option<Self> {
let s = s.trim();
if s.eq_ignore_ascii_case("jpg") {
return Some(Self::Jpeg);
}
Self::ALL.into_iter().find(|f| s.eq_ignore_ascii_case(f.id()))
}
}
/// What the export favours when DXF can't hold an object's look as it is.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Preserve {
/// Type becomes glyph outlines; strokes a plain CAD line can't draw (aligned inside or
/// outside, width profiles, arrowheads, fitted dashes) become their filled outlines; brush
/// strokes become their brush art.
#[default]
Appearance,
/// Type stays text; every stroke is a line with its weight and dashes.
Editability,
}
impl Preserve {
pub const ALL: [Self; 2] = [Self::Appearance, Self::Editability];
/// The `preserve` param value.
pub fn id(self) -> &'static str {
match self {
Self::Appearance => "appearance",
Self::Editability => "editability",
}
}
pub fn label(self) -> &'static str {
match self {
Self::Appearance => "Preserve Appearance",
Self::Editability => "Maximize Editability",
}
}
pub fn from_id(s: &str) -> Option<Self> {
Self::ALL.into_iter().find(|p| s.trim().eq_ignore_ascii_case(p.id()))
}
}
/// The DXF export settings.
#[derive(Clone, Debug)]
pub struct DxfOptions {
pub version: DxfVersion,
/// The unit of the art that `scale` drawing units stand for.
pub unit: Unit,
/// Drawing units per `unit` (1 mm = `scale` units).
pub scale: f64,
/// Lineweights grow with `scale` (else they keep their printed width).
pub scale_lineweights: bool,
pub colors: ColorDepth,
pub raster: RasterFormat,
pub preserve: Preserve,
/// Alter Paths for Appearance: every stroke is written as the filled area it paints.
pub alter_paths: bool,
/// Type is written as glyph outlines (always with [`Preserve::Appearance`]).
pub outline_text: bool,
/// The drawing's origin is this region's bottom-left corner (document space).
pub region: Rect,
/// Leave out objects entirely outside `region` (one drawing per artboard).
pub crop: bool,
}
impl Default for DxfOptions {
fn default() -> Self {
Self {
version: DxfVersion::default(),
unit: Unit::Millimeters,
scale: 1.0,
scale_lineweights: false,
colors: ColorDepth::default(),
raster: RasterFormat::default(),
preserve: Preserve::default(),
alter_paths: false,
outline_text: false,
region: Rect::ZERO,
crop: false,
}
}
}
/// An image file a drawing links to, to be written next to it under `name`.
#[derive(Clone, Debug)]
pub struct DxfImage {
pub name: String,
pub bytes: Vec<u8>,
}
/// A written drawing.
#[derive(Clone, Debug, Default)]
pub struct DxfOutput {
pub bytes: Vec<u8>,
/// The image files the drawing links to (by name, next to it).
pub images: Vec<DxfImage>,
/// What was approximated or left out.
pub warnings: Vec<String>,
}
/// The smallest and largest `scale` (drawing units per unit).
pub const SCALE_RANGE: std::ops::RangeInclusive<f64> = 1e-6..=1e6;
/// Write `doc` as a DXF drawing with `opts`. Live geometry effects are applied first; template
/// layers, guides and hidden objects are left out.
pub fn export(doc: &Document, opts: &DxfOptions) -> Result<DxfOutput, String> {
if !(opts.scale.is_finite() && SCALE_RANGE.contains(&opts.scale)) {
return Err(format!("scale must be a number from {} to {}, not {}", SCALE_RANGE.start(), SCALE_RANGE.end(), opts.scale));
}
let r = opts.region;
if ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) {
return Err("the export region is not finite".into());
}
let baked = vectorcraft_effects::bake_document(doc);
let doc = baked.as_ref().unwrap_or(doc);
Ok(scene::Scene::new(doc, opts).run())
}
#[cfg(test)]
mod tests;
+854
View File
@@ -0,0 +1,854 @@
//! The document walk: each visible object becomes DXF entities on its layer's DXF layer, in paint
//! order. Fills are solid hatches (outlines in R12), strokes polylines and cubic splines with a
//! lineweight and dashes, or filled outlines where the look needs them.
use std::collections::HashMap;
use std::io::Cursor;
use kurbo::PathEl;
use vectorcraft_color::Paint;
use vectorcraft_doc::{AppearanceItem, Dash, Document, ImageObject, Node, NodeKind, StrokeLayer, TextKind, TextObject, Unit};
use vectorcraft_effects::stroke;
use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect};
use crate::aci::nearest_aci;
use crate::writer::{Codes, Drawing, EntityStyle, Handle, ImageDef, Layer, LineType, fixed};
use crate::{ColorDepth, DxfImage, DxfOptions, DxfOutput, Preserve, RasterFormat};
/// Curves are flattened to within this distance (points) where DXF needs straight segments
/// (hatch boundaries, R12 polylines).
const FLATNESS: f64 = 0.05;
/// How deep symbols and brush art may nest in one another (deeper art is left out).
const MAX_NEST: u32 = 8;
/// Cap height as a fraction of the type size: the height of CAD text is that of its capitals.
const CAP_HEIGHT: f64 = 0.7;
/// Longest text value older DXF versions read.
const MAX_TEXT: usize = 250;
/// The lineweights DXF knows (hundredths of a millimetre).
const LINEWEIGHTS: [i32; 24] = [0, 5, 9, 13, 15, 18, 20, 25, 30, 35, 40, 50, 53, 60, 70, 80, 90, 100, 106, 120, 140, 158, 200, 211];
const NO_TRUE_COLOR: &str = "true colour needs DXF 2004 or later: colours are written as the nearest of the 256 indexed colours";
const NO_TRANSPARENCY: &str = "transparency needs DXF 2004 or later: transparent objects are written opaque";
const NO_FILLS: &str = "DXF R12 has no fills: filled areas are written as their outlines";
const NO_IMAGES: &str = "DXF R12 has no images: placed images are left out";
const WIDE_LINES: &str =
"lines wider than 2.11 mm (the widest lineweight) are written at 2.11 mm: Alter Paths for Appearance writes their true width";
const STROKE_EXTRAS: &str = "stroke alignment, width profiles, arrowheads and brushes are left out (Maximize Editability writes strokes as lines)";
const CLIPPING: &str = "clipping masks are not applied: the art they clip is written whole";
const TYPE_ITEMS: &str = "fills and strokes added to whole type objects are left out of text entities (outline the text to keep them)";
/// One segment of a subpath, cubics for every curve.
#[derive(Clone, Copy)]
enum Seg {
Line(Point),
Cubic(Point, Point, Point),
}
impl Seg {
fn end(self) -> Point {
match self {
Seg::Line(p) | Seg::Cubic(_, _, p) => p,
}
}
}
/// A subpath: its start, its segments and whether it closes.
struct Sub {
start: Point,
segs: Vec<Seg>,
closed: bool,
}
/// The subpaths of `bp` (quadratics raised to cubics).
fn subpaths(bp: &BezPath) -> Vec<Sub> {
let mut out = vec![];
let mut cur: Option<Sub> = None;
let mut last = Point::ZERO;
for el in bp.elements() {
let seg = match *el {
PathEl::MoveTo(p) => {
out.extend(cur.replace(Sub { start: p, segs: vec![], closed: false }));
last = p;
continue;
}
PathEl::ClosePath => {
if let Some(mut s) = cur.take() {
s.closed = true;
last = s.start;
out.push(s);
}
continue;
}
PathEl::LineTo(p) => Seg::Line(p),
PathEl::QuadTo(q, p) => Seg::Cubic(last + (q - last) * (2.0 / 3.0), p + (q - p) * (2.0 / 3.0), p),
PathEl::CurveTo(a, b, p) => Seg::Cubic(a, b, p),
};
last = seg.end();
cur.get_or_insert_with(|| Sub { start: last, segs: vec![], closed: false }).segs.push(seg);
}
out.extend(cur);
out
}
/// `bp` flattened into polygons (each closing implicitly), consecutive repeats dropped.
fn polygons(bp: &BezPath) -> Vec<Vec<Point>> {
let mut out: Vec<Vec<Point>> = vec![];
let mut cur: Vec<Point> = vec![];
let push = |p: Point, cur: &mut Vec<Point>| {
if cur.last().is_none_or(|q| q.distance(p) > 1e-9) {
cur.push(p);
}
};
kurbo::flatten(bp.iter(), FLATNESS, |el| match el {
PathEl::MoveTo(p) => {
out.push(std::mem::take(&mut cur));
push(p, &mut cur);
}
PathEl::LineTo(p) => push(p, &mut cur),
PathEl::ClosePath => out.push(std::mem::take(&mut cur)),
_ => {}
});
out.push(cur);
for poly in &mut out {
if poly.len() > 1 && poly.first().zip(poly.last()).is_some_and(|(a, b)| a.distance(*b) <= 1e-9) {
poly.pop();
}
}
out.retain(|p| p.len() >= 2);
out
}
/// A DXF symbol name (layer, text style) from `name`: from DXF 2000 up to 255 characters
/// without `<>/\":;?*|=`` ` ``; before, up to 31 letters, digits, `$`, `-` and `_`, in capitals.
fn symbol_name(name: &str, long: bool) -> String {
let s: String = if long {
let bad = |c: char| c.is_control() || "<>/\\\":;?*|=`".contains(c);
name.trim().chars().map(|c| if bad(c) { '_' } else { c }).take(255).collect()
} else {
name.trim().chars().map(|c| if c.is_ascii_alphanumeric() || "$-_".contains(c) { c.to_ascii_uppercase() } else { '_' }).take(31).collect()
};
s.trim().to_string()
}
/// `base` made unique among `taken` (any case) by `_2`, `_3`…, within `max` characters.
fn unique(base: &str, taken: &[&str], max: usize) -> String {
let base = if base.is_empty() { "Layer".to_string() } else { base.to_string() };
let free = |n: &str| !taken.iter().any(|t| t.eq_ignore_ascii_case(n));
if free(&base) {
return base;
}
(2..)
.map(|i| {
let suffix = format!("_{i}");
let keep: String = base.chars().take(max.saturating_sub(suffix.len())).collect();
format!("{keep}{suffix}")
})
.find(|n| free(n))
.unwrap_or(base)
}
fn overlaps(a: Rect, b: Rect) -> bool {
a.x0 <= b.x1 && b.x0 <= a.x1 && a.y0 <= b.y1 && b.y0 <= a.y1
}
/// The layer flags art inherits from the layers around it.
#[derive(Clone, Copy)]
struct LayerFlags {
off: bool,
locked: bool,
plot: bool,
}
pub(crate) struct Scene<'a> {
doc: &'a Document,
o: &'a DxfOptions,
/// Document space → drawing units (y up, origin at the region's bottom-left).
to_dxf: Affine,
/// Drawing units per point.
k: f64,
/// The entities written so far.
e: Codes,
next: u32,
layers: Vec<Layer>,
/// The DXF layer art goes on, and its flags.
layer: String,
flags: LayerFlags,
linetypes: Vec<LineType>,
/// (style name, font family).
styles: Vec<(String, String)>,
images: Vec<ImageDef>,
files: Vec<DxfImage>,
/// Image keys → index into `images` (`None`: left out).
by_key: HashMap<String, Option<usize>>,
warnings: Vec<String>,
brushes: Option<Vec<vectorcraft_brush::Brush>>,
extents: Option<[f64; 4]>,
/// The opacity of the containers around the current object.
opacity: f32,
/// Symbols and brush art being written inside one another.
nest: u32,
}
impl<'a> Scene<'a> {
pub fn new(doc: &'a Document, o: &'a DxfOptions) -> Self {
let k = o.scale / o.unit.points();
let r = o.region;
Self {
doc,
o,
to_dxf: Affine::new([k, 0.0, 0.0, -k, -r.x0 * k, r.y1 * k]),
k,
e: Codes::new(o.version),
next: fixed::FIRST_FREE,
layers: vec![],
layer: "0".into(),
flags: LayerFlags { off: false, locked: false, plot: true },
linetypes: vec![],
styles: vec![],
images: vec![],
files: vec![],
by_key: HashMap::new(),
warnings: vec![],
brushes: None,
extents: None,
opacity: 1.0,
nest: 0,
}
}
pub fn run(mut self) -> DxfOutput {
if self.o.colors == ColorDepth::True && !self.o.version.true_color() {
self.warn(NO_TRUE_COLOR);
}
let doc = self.doc;
for l in &doc.layers {
self.node(l, false);
}
let r = self.o.region;
let limits = [0.0, 0.0, r.width() * self.k, r.height() * self.k];
let one = (self.o.scale - 1.0).abs() < 1e-12;
let insunits = match self.o.unit {
Unit::Inches if one => 1,
Unit::Feet | Unit::FeetInches if one => 2,
Unit::Millimeters if one => 4,
Unit::Centimeters if one => 5,
Unit::Meters if one => 6,
Unit::Yards if one => 10,
_ => 0,
};
let drawing = Drawing {
version: self.o.version,
layers: self.layers,
linetypes: self.linetypes,
styles: self.styles,
images: self.images,
entities: self.e.into_string(),
extents: self.extents.unwrap_or(limits),
limits,
insunits,
metric: matches!(self.o.unit, Unit::Millimeters | Unit::Centimeters | Unit::Meters),
next: self.next,
};
DxfOutput { bytes: drawing.write().into_bytes(), images: self.files, warnings: self.warnings }
}
fn warn(&mut self, w: &str) {
if !self.warnings.iter().any(|x| x == w) {
self.warnings.push(w.to_string());
}
}
fn handle(&mut self) -> Handle {
let h = Handle(self.next);
self.next = self.next.saturating_add(1);
h
}
/// A document point in drawing units, counted in the extents.
fn pt(&mut self, p: Point) -> Point {
let q = self.to_dxf * p;
let e = self.extents.get_or_insert([q.x, q.y, q.x, q.y]);
*e = [e[0].min(q.x), e[1].min(q.y), e[2].max(q.x), e[3].max(q.y)];
q
}
fn node(&mut self, n: &Node, force: bool) {
if let NodeKind::Layer { template: true, .. } = n.kind {
return;
}
// Hidden layers are written, switched off.
let layer = n.is_layer();
if !force && !n.visible && !layer {
return;
}
if self.o.crop && !layer {
match n.visual_bounds() {
Some(b) if !overlaps(b, self.o.region) => return,
None if !n.is_container() => return,
_ => {}
}
}
self.note_losses(n);
let opacity = self.opacity;
self.opacity *= n.opacity.clamp(0.0, 1.0);
match &n.kind {
NodeKind::Layer { children, printable, clip, .. } => {
let outer = (self.layer.clone(), self.flags);
self.flags =
LayerFlags { off: self.flags.off || !n.visible, locked: self.flags.locked || n.locked, plot: self.flags.plot && *printable };
self.layer = self.add_layer(n);
self.children(children, *clip);
(self.layer, self.flags) = outer;
}
NodeKind::Group { children, clip } => self.children(children, *clip),
NodeKind::Path { path, rule, guide, .. } => {
if !*guide {
self.shape(n, &path.to_bezpath(), *rule);
}
}
NodeKind::Compound { children, rule } => {
let mut bp = BezPath::new();
for p in children.iter().filter_map(|c| c.path_data()) {
bp.extend(p.to_bezpath());
}
self.shape(n, &bp, *rule);
}
NodeKind::Text(t) => self.text(n, t),
NodeKind::Image(im) => self.image(im),
NodeKind::SymbolInstance { symbol, xf } => {
if let Some(sym) = self.doc.symbols.iter().find(|s| &s.name == symbol)
&& self.nest < MAX_NEST
{
let mut art = (*sym.art).clone();
art.transform(*xf, false);
self.nest += 1;
self.node(&art, true);
self.nest -= 1;
}
}
// Live blends, envelopes, meshes and repeats are written as their evaluated art.
NodeKind::Blend { .. } | NodeKind::Envelope { .. } | NodeKind::Mesh(_) | NodeKind::Repeat(_) => {
let g = vectorcraft_doc::live::expand_deep(n, None);
for c in g.children().into_iter().flatten() {
self.node(c, false);
}
}
}
self.opacity = opacity;
}
/// A container's children; a clipping container's first child is its clipping path, which
/// paints its fills below the others and its strokes over them.
fn children(&mut self, children: &[std::sync::Arc<Node>], clip: bool) {
let Some((first, rest)) = children.split_first().filter(|_| clip) else {
children.iter().for_each(|c| self.node(c, false));
return;
};
self.warn(CLIPPING);
let paint = first.clip_paint();
if let Some(f) = &paint.fill {
self.node(f, false);
}
rest.iter().for_each(|c| self.node(c, false));
if let Some(s) = &paint.stroke {
self.node(s, false);
}
}
/// Warn about what DXF can't hold in `n`'s look.
fn note_losses(&mut self, n: &Node) {
if n.blend != vectorcraft_color::BlendMode::Normal {
self.warn("blending modes are left out");
}
if n.mask.as_ref().is_some_and(|m| !m.disabled) {
self.warn("opacity masks are left out");
}
let raster = |fx: &[vectorcraft_doc::Effect]| fx.iter().any(|e| e.visible && vectorcraft_effects::is_raster(&e.id));
if raster(&n.appearance.effects) || n.appearance.items.iter().any(|i| raster(i.effects())) {
self.warn("raster effects (shadows, glows, blurs, feathering) are left out");
}
}
/// A DXF layer for document layer `n`, with a name no other layer has.
fn add_layer(&mut self, n: &Node) -> String {
let long = self.o.version.r2000();
let base = symbol_name(n.name.as_deref().unwrap_or("Layer"), long);
let mut taken: Vec<&str> = self.layers.iter().map(|l| l.name.as_str()).collect();
taken.extend(["0", "Defpoints"]);
let name = unique(&base, &taken, if long { 255 } else { 31 });
let aci = match n.kind {
NodeKind::Layer { color, .. } => nearest_aci(color.rgb(), ColorDepth::Aci256),
_ => 7,
};
let f = self.flags;
self.layers.push(Layer { name: name.clone(), aci, off: f.off, locked: f.locked, plot: f.plot });
name
}
/// One colour for a paint: a solid colour, the average of a gradient's stops, or a pattern's
/// first solid fill.
fn paint_rgb(&mut self, p: &Paint) -> Option<[u8; 3]> {
let rgb = |c: &vectorcraft_color::Color| {
let [r, g, b, _] = c.to_rgba8(1.0);
[r, g, b]
};
match p {
Paint::None => None,
Paint::Solid { color, .. } => Some(rgb(color)),
Paint::Gradient(g) => {
self.warn("gradients are written as one colour, the average of their stops");
let stops = &g.gradient.stops;
let n = stops.len().max(1) as f64;
let sum = stops.iter().map(|s| rgb(&s.color)).fold([0.0; 3], |a, c| [0, 1, 2].map(|i| a[i] + f64::from(c[i])));
Some(sum.map(|v| (v / n).round().clamp(0.0, 255.0) as u8))
}
Paint::Pattern { pattern, .. } => {
self.warn("pattern fills are written as one colour");
let first = self.doc.pattern(pattern).and_then(|def| def.art.iter().find_map(|a| first_solid(a)));
Some(first.map_or([128; 3], |c| rgb(&c)))
}
}
}
/// The entity style of colour `rgb` at `opacity` (times the containers'), with an optional
/// stroke weight (points) and linetype.
fn style(&mut self, rgb: [u8; 3], opacity: f32, weight: Option<f64>, linetype: Option<String>) -> EntityStyle {
let v = self.o.version;
let opacity = (self.opacity * opacity).clamp(0.0, 1.0);
let alpha = if opacity >= 0.998 {
None
} else if v.true_color() {
Some((opacity * 255.0).round() as u8)
} else {
self.warn(NO_TRANSPARENCY);
None
};
EntityStyle {
aci: nearest_aci(rgb, self.o.colors),
rgb: (self.o.colors == ColorDepth::True).then(|| u32::from_be_bytes([0, rgb[0], rgb[1], rgb[2]])),
lineweight: weight.filter(|_| v.r2000()).map(|w| self.lineweight(w)),
linetype,
alpha,
}
}
/// The DXF lineweight nearest to `width` points (scaled with the drawing when asked).
fn lineweight(&mut self, width: f64) -> i32 {
let scale = if self.o.scale_lineweights { self.o.scale } else { 1.0 };
let hundredths = width * 2540.0 / 72.0 * scale;
let max = LINEWEIGHTS[LINEWEIGHTS.len() - 1];
if hundredths > f64::from(max) + 5.0 {
self.warn(WIDE_LINES);
}
LINEWEIGHTS.into_iter().min_by(|a, b| (f64::from(*a) - hundredths).abs().total_cmp(&(f64::from(*b) - hundredths).abs())).unwrap_or(max)
}
/// A linetype for dash pattern `d` (one per distinct pattern).
fn linetype(&mut self, d: &Dash) -> String {
let mut lengths: Vec<f64> = d.pattern.iter().map(|v| v * self.k).collect();
if lengths.len() % 2 == 1 {
lengths.extend(lengths.clone());
}
let pattern: Vec<f64> = lengths.iter().enumerate().map(|(i, v)| if i % 2 == 0 { *v } else { -v }).collect();
let same = |l: &LineType| l.pattern.len() == pattern.len() && l.pattern.iter().zip(&pattern).all(|(a, b)| (a - b).abs() < 1e-9);
if let Some(l) = self.linetypes.iter().find(|l| same(l)) {
return l.name.clone();
}
let name = format!("DASHED{}", self.linetypes.len() + 1);
self.linetypes.push(LineType { name: name.clone(), pattern });
name
}
/// A path's fills and strokes, in paint order.
fn shape(&mut self, n: &Node, bp: &BezPath, rule: FillRule) {
if bp.elements().is_empty() {
return;
}
for item in &n.appearance.items {
match item {
AppearanceItem::Fill(f) if f.visible => {
if let Some(rgb) = self.paint_rgb(&f.paint) {
let style = self.style(rgb, f.opacity, None, None);
self.area(bp, rule, &style, false);
}
}
AppearanceItem::Stroke(st) if st.visible && st.width > 0.0 && st.width.is_finite() => self.stroke(bp, rule, st),
_ => {}
}
}
}
fn stroke(&mut self, bp: &BezPath, rule: FillRule, st: &StrokeLayer) {
let appearance = self.o.preserve == Preserve::Appearance;
if appearance
&& st.brush.is_some()
&& self.nest < MAX_NEST
&& let Some(art) = self.brush_art(bp, st)
{
let opacity = self.opacity;
self.opacity *= st.opacity.clamp(0.0, 1.0);
self.nest += 1;
art.iter().for_each(|piece| self.node(piece, true));
self.nest -= 1;
self.opacity = opacity;
return;
}
let Some(rgb) = self.paint_rgb(&st.paint) else { return };
let plain = stroke::is_plain(st);
if self.o.alter_paths || (appearance && !plain) {
let region = stroke::outline_region(&PathData::from_bezpath(bp), rule, st);
let style = self.style(rgb, st.opacity, None, None);
self.area(&region.to_bezpath(), FillRule::NonZero, &style, true);
return;
}
if !plain {
self.warn(STROKE_EXTRAS);
}
let linetype = st.dash.as_ref().filter(|d| d.is_dashed()).map(|d| self.linetype(d));
let style = self.style(rgb, st.opacity, Some(st.width), linetype);
self.lines(bp, &style, st.width);
}
fn brush_art(&mut self, bp: &BezPath, st: &StrokeLayer) -> Option<Vec<Node>> {
let doc = self.doc;
let brushes = self.brushes.get_or_insert_with(|| vectorcraft_brush::library(doc));
let b = st.brush.as_deref().and_then(|name| brushes.iter().find(|b| b.name == name))?;
Some(vectorcraft_brush::stroke_pieces(b, bp, st))
}
/// A filled area as a solid hatch (R12: its outlines). `clean`: the path has no overlaps, so
/// the hatch's even-odd rule reads it as it is.
fn area(&mut self, bp: &BezPath, rule: FillRule, style: &EntityStyle, clean: bool) {
if !self.o.version.handles() {
self.warn(NO_FILLS);
self.lines(bp, style, 0.0);
return;
}
let several = bp.elements().iter().filter(|e| matches!(e, PathEl::MoveTo(_))).count() > 1;
let normalized = (rule == FillRule::NonZero && several && !clean)
.then(|| vectorcraft_pathops::try_normalize(&PathData::from_bezpath(bp), rule).ok())
.flatten()
.map(|p| p.to_bezpath());
let loops: Vec<Vec<Point>> = polygons(normalized.as_ref().unwrap_or(bp)).into_iter().filter(|p| p.len() >= 3).collect();
if loops.is_empty() {
return;
}
let h = self.handle();
let layer = self.layer.clone();
self.e.entity("HATCH", h, fixed::MODEL_RECORD, &layer, style, "AcDbHatch");
self.e.xyz(10, 0.0, 0.0);
self.e.normal();
self.e.raw(2, "SOLID");
self.e.int(70, 1);
self.e.int(71, 0);
self.e.int(91, loops.len() as i64);
for l in &loops {
// An external polyline boundary, closed, without bulges.
self.e.int(92, 3);
self.e.int(72, 0);
self.e.int(73, 1);
self.e.int(93, l.len() as i64);
for p in l {
let q = self.pt(*p);
self.e.xy(10, q.x, q.y);
}
self.e.int(97, 0);
}
self.e.int(75, 0);
self.e.int(76, 1);
self.e.int(98, 0);
}
/// Path `bp` as lines: polylines for straight subpaths (and for curves in R12, flattened),
/// cubic splines for curved ones. `width`: the stroke weight, which DXF before 2000 gives
/// polylines as a width.
fn lines(&mut self, bp: &BezPath, style: &EntityStyle, width: f64) {
let v = self.o.version;
let width = (!v.r2000() && width > 0.0).then_some(width * self.k);
for sub in subpaths(bp) {
if sub.segs.is_empty() {
continue;
}
if sub.segs.iter().all(|s| matches!(s, Seg::Line(_))) {
let mut pts: Vec<Point> = std::iter::once(sub.start).chain(sub.segs.iter().map(|s| s.end())).collect();
if sub.closed && pts.len() > 2 && pts.last().is_some_and(|p| p.distance(sub.start) <= 1e-9) {
pts.pop();
}
self.polyline(&pts, sub.closed, style, width);
} else if v.handles() {
self.spline(&sub, style);
} else {
let mut path = BezPath::new();
path.move_to(sub.start);
for s in &sub.segs {
match *s {
Seg::Line(p) => path.line_to(p),
Seg::Cubic(a, b, p) => path.curve_to(a, b, p),
}
}
for pts in polygons(&path) {
self.polyline(&pts, sub.closed, style, width);
}
}
}
}
/// A polyline through `pts` (document space): lightweight from R14, else a polyline with a
/// vertex entity per point.
fn polyline(&mut self, pts: &[Point], closed: bool, style: &EntityStyle, width: Option<f64>) {
if pts.len() < 2 {
return;
}
let pts: Vec<Point> = pts.iter().map(|p| self.pt(*p)).collect();
let layer = self.layer.clone();
let h = self.handle();
let flags = i64::from(closed);
if self.o.version.lwpolyline() {
self.e.entity("LWPOLYLINE", h, fixed::MODEL_RECORD, &layer, style, "AcDbPolyline");
self.e.int(90, pts.len() as i64);
self.e.int(70, flags);
if let Some(w) = width {
self.e.num(43, w);
}
for p in &pts {
self.e.xy(10, p.x, p.y);
}
return;
}
self.e.entity("POLYLINE", h, fixed::MODEL_RECORD, &layer, style, "AcDb2dPolyline");
self.e.int(66, 1);
self.e.xyz(10, 0.0, 0.0);
self.e.int(70, flags);
if let Some(w) = width {
self.e.num(40, w);
self.e.num(41, w);
}
for p in &pts {
let vh = self.handle();
self.e.entity("VERTEX", vh, h, &layer, style, "AcDbVertex");
if self.o.version.handles() {
self.e.raw(100, "AcDb2dVertex");
}
self.e.xyz(10, p.x, p.y);
}
let end = self.handle();
self.e.entity("SEQEND", end, h, &layer, style, "");
}
/// A curved subpath as one cubic B-spline whose clamped knots repeat at every joint, so it
/// passes through every anchor (straight segments become straight cubics).
fn spline(&mut self, sub: &Sub, style: &EntityStyle) {
let end = sub.segs.last().map_or(sub.start, |s| s.end());
let closing = (sub.closed && end.distance(sub.start) > 1e-9).then_some(Seg::Line(sub.start));
let mut ctrl = vec![sub.start];
let mut last = sub.start;
for seg in sub.segs.iter().copied().chain(closing) {
match seg {
Seg::Line(p) => ctrl.extend([last.lerp(p, 1.0 / 3.0), last.lerp(p, 2.0 / 3.0), p]),
Seg::Cubic(a, b, p) => ctrl.extend([a, b, p]),
}
last = seg.end();
}
let n = (ctrl.len() - 1) / 3;
let mut knots = vec![0.0; 4];
for i in 1..n {
knots.extend([i as f64; 3]);
}
knots.extend([n as f64; 4]);
let ctrl: Vec<Point> = ctrl.iter().map(|p| self.pt(*p)).collect();
let layer = self.layer.clone();
let h = self.handle();
self.e.entity("SPLINE", h, fixed::MODEL_RECORD, &layer, style, "AcDbSpline");
self.e.normal();
// Planar.
self.e.int(70, 8);
self.e.int(71, 3);
self.e.int(72, knots.len() as i64);
self.e.int(73, ctrl.len() as i64);
self.e.int(74, 0);
for k in knots {
self.e.num(40, k);
}
for p in ctrl {
self.e.xyz(10, p.x, p.y);
}
}
/// Type: glyph outlines (Preserve Appearance, Outline Text, type on a path), else one text
/// entity per run of each line.
fn text(&mut self, n: &Node, t: &TextObject) {
let outline = self.o.preserve == Preserve::Appearance || self.o.outline_text || matches!(t.kind, TextKind::OnPath { .. });
if outline {
if let Some(o) = vectorcraft_effects::outline_text(n) {
self.node(&o, true);
}
return;
}
if !n.appearance.items.is_empty() {
self.warn(TYPE_ITEMS);
}
let layout = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
let plain = t.plain_text();
let xf = self.to_dxf * t.xf;
let [a, b, c, d, _, _] = xf.as_coeffs();
// Along and across the baseline, in drawing units per text-space unit.
let along = a.hypot(b);
if along <= 1e-12 {
return;
}
let across = (a * d - b * c).abs() / along;
let angle = b.atan2(a).to_degrees();
for line in &layout.lines {
let Some(glyphs) = layout.glyphs.get(line.glyph_start..line.glyph_end) else { continue };
for run in glyphs.chunk_by(|x, y| x.run == y.run) {
let Some(first) = run.first() else { continue };
let lo = run.iter().map(|g| g.byte).min().unwrap_or(first.byte);
let hi = run.iter().map(|g| g.byte + g.len).max().unwrap_or(lo);
let Some(s) = plain.get(lo..hi).map(str::trim_end).filter(|s| !s.trim().is_empty()) else { continue };
let Some(cs) = t.runs.get(first.run).map(|r| &r.style) else { continue };
let paint = if cs.fill.is_none() { &cs.stroke } else { &cs.fill };
let Some(rgb) = self.paint_rgb(paint) else { continue };
let style = self.style(rgb, 1.0, None, None);
let text_style = self.text_style(&cs.font_family);
let height = cs.size * cs.v_scale / 100.0 * CAP_HEIGHT * across;
let width = if cs.v_scale > 0.0 { cs.h_scale / cs.v_scale } else { 1.0 };
let origin = run.iter().map(|g| g.origin).min_by(|p, q| p.x.total_cmp(&q.x)).unwrap_or(first.origin);
let p = self.pt(t.xf * origin);
let layer = self.layer.clone();
let h = self.handle();
self.e.entity("TEXT", h, fixed::MODEL_RECORD, &layer, &style, "AcDbText");
self.e.xyz(10, p.x, p.y);
self.e.num(40, height);
let s: String = s.chars().take(MAX_TEXT).collect();
self.e.str(1, &s);
if angle.abs() > 1e-9 {
self.e.num(50, angle);
}
if (width - 1.0).abs() > 1e-9 {
self.e.num(41, width);
}
self.e.str(7, &text_style);
if self.o.version.handles() {
self.e.raw(100, "AcDbText");
}
}
}
}
/// The text style for font `family` (one per family).
fn text_style(&mut self, family: &str) -> String {
if let Some((name, _)) = self.styles.iter().find(|(_, f)| f == family) {
return name.clone();
}
let long = self.o.version.r2000();
let mut taken: Vec<&str> = self.styles.iter().map(|(n, _)| n.as_str()).collect();
taken.push(crate::writer::STANDARD_STYLE);
let name = unique(&symbol_name(family, long), &taken, if long { 255 } else { 31 });
self.styles.push((name.clone(), family.to_string()));
name
}
/// A placed image, linked to its file (written once per image).
fn image(&mut self, im: &ImageObject) {
if !self.o.version.handles() {
self.warn(NO_IMAGES);
return;
}
let Some(i) = self.image_def(&im.key) else { return };
let Some((dw, dh)) = self.images.get(i).map(|d| (f64::from(d.size.0), f64::from(d.size.1))) else { return };
let (w, h) = (f64::from(im.width.max(1)), f64::from(im.height.max(1)));
let map = self.to_dxf * im.xf;
let lin = |v: kurbo::Vec2| (map * v.to_point()) - (map * Point::ZERO);
// Insertion at the bottom-left corner; u along one file pixel, v one pixel up.
let u = lin(kurbo::Vec2::new(w / dw, 0.0));
let v = lin(kurbo::Vec2::new(0.0, -h / dh));
for corner in [Point::new(0.0, 0.0), Point::new(w, 0.0), Point::new(0.0, h), Point::new(w, h)] {
self.pt(im.xf * corner);
}
let at = map * Point::new(0.0, h);
let handle = self.handle();
let reactor = self.handle();
let Some(def) = self.images.get_mut(i) else { return };
def.reactors.push((reactor, handle));
let def = def.handle;
let layer = self.layer.clone();
let style = EntityStyle { aci: 7, ..EntityStyle::default() };
self.e.entity("IMAGE", handle, fixed::MODEL_RECORD, &layer, &style, "AcDbRasterImage");
self.e.int(90, 0);
self.e.xyz(10, at.x, at.y);
self.e.xyz(11, u.x, u.y);
self.e.xyz(12, v.x, v.y);
self.e.xy(13, dw, dh);
self.e.handle(340, def);
// Shown, also when not aligned with the screen; PNG with its transparency.
self.e.int(70, if self.o.raster == RasterFormat::Png { 11 } else { 3 });
self.e.int(280, 0);
self.e.int(281, 50);
self.e.int(282, 50);
self.e.int(283, 0);
self.e.handle(360, reactor);
self.e.int(71, 1);
self.e.int(91, 2);
self.e.xy(14, -0.5, -0.5);
self.e.xy(14, dw - 0.5, dh - 0.5);
if self.o.version >= crate::DxfVersion::R2010 {
self.e.int(290, 0);
}
}
/// The image file for image `key`, encoded once in the chosen format (`None`: left out).
fn image_def(&mut self, key: &str) -> Option<usize> {
if let Some(i) = self.by_key.get(key) {
return *i;
}
let made = self.encode_image(key);
let i = match made {
Ok((file, size)) => {
let handle = self.handle();
self.images.push(ImageDef { name: file.name.clone(), size, handle, reactors: vec![] });
self.files.push(file);
Some(self.images.len() - 1)
}
Err(e) => {
self.warn(&e);
None
}
};
self.by_key.insert(key.to_string(), i);
i
}
/// Image `key` as a file in the chosen format, and its size in pixels.
fn encode_image(&self, key: &str) -> Result<(DxfImage, (u32, u32)), String> {
let blob = self.doc.images.get(key).filter(|b| !b.bytes.is_empty()).ok_or_else(|| format!("image '{key}' has no pixels and was left out"))?;
let img = image::load_from_memory(&blob.bytes).map_err(|_| format!("image '{key}' could not be decoded and was left out"))?;
let size = (img.width(), img.height());
let mut bytes = vec![];
let written = match self.o.raster {
RasterFormat::Png => img.to_rgba8().write_to(&mut Cursor::new(&mut bytes), image::ImageFormat::Png),
RasterFormat::Jpeg => {
// No alpha in JPEG: transparent pixels over white.
let mut rgba = img.to_rgba8();
for p in rgba.pixels_mut() {
let a = u32::from(p[3]);
for c in 0..3 {
p[c] = ((u32::from(p[c]) * a + 255 * (255 - a)) / 255) as u8;
}
}
let rgb = image::DynamicImage::ImageRgba8(rgba).to_rgb8();
rgb.write_with_encoder(image::codecs::jpeg::JpegEncoder::new_with_quality(&mut bytes, 90))
}
};
written.map_err(|e| format!("image '{key}' could not be written: {e}"))?;
Ok((DxfImage { name: format!("{}.{}", blob.content_key(), self.o.raster.extension()), bytes }, size))
}
}
/// The first visible solid fill colour in `n` (pattern art).
fn first_solid(n: &Node) -> Option<vectorcraft_color::Color> {
let own = n.appearance.items.iter().find_map(|i| match i {
AppearanceItem::Fill(f) if f.visible => f.paint.color(),
_ => None,
});
own.or_else(|| n.children().into_iter().flatten().find_map(|c| first_solid(c)))
}
+371
View File
@@ -0,0 +1,371 @@
//! DXF output read back as group codes: versions, entities, colours, units, layers, type, images.
use std::sync::Arc;
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{Appearance, CharStyle, Dash, Document, ImageBlob, ImageObject, Node, NodeKind, TextObject, Unit};
use vectorcraft_geom::{Affine, PathData, Point, Rect, shapes};
use crate::*;
type Pairs = Vec<(i32, String)>;
/// The `(code, value)` pairs of a DXF file.
fn pairs(dxf: &[u8]) -> Pairs {
let text = std::str::from_utf8(dxf).expect("UTF-8");
let lines: Vec<&str> = text.lines().collect();
assert_eq!(lines.len() % 2, 0, "group codes and values come in pairs");
lines.chunks(2).map(|p| (p[0].trim().parse().expect("a group code"), p[1].to_string())).collect()
}
/// The objects of section `name`: each the pairs from its `0` code on.
fn section(p: &[(i32, String)], name: &str) -> Vec<Pairs> {
let start = p.windows(2).position(|w| w[0] == (0, "SECTION".into()) && w[1] == (2, name.into()));
let Some(start) = start else { return vec![] };
let mut out: Vec<Pairs> = vec![];
for pair in &p[start + 2..] {
if *pair == (0, "ENDSEC".into()) {
break;
}
if pair.0 == 0 {
out.push(vec![]);
}
if let Some(o) = out.last_mut() {
o.push(pair.clone());
}
}
out
}
fn kind(o: &[(i32, String)]) -> &str {
o.first().map_or("", |p| p.1.as_str())
}
fn get(o: &[(i32, String)], code: i32) -> Option<&str> {
o.iter().find(|p| p.0 == code).map(|p| p.1.as_str())
}
fn all(o: &[(i32, String)], code: i32) -> Vec<f64> {
o.iter().filter(|p| p.0 == code).map(|p| p.1.trim().parse().expect("a number")).collect()
}
fn header(p: &[(i32, String)], var: &str) -> Option<String> {
let i = p.iter().position(|x| *x == (9, var.into()))?;
p.get(i + 1).map(|x| x.1.clone())
}
fn entities(out: &DxfOutput) -> Vec<Pairs> {
section(&pairs(&out.bytes), "ENTITIES")
}
fn kinds(out: &DxfOutput) -> Vec<String> {
entities(out).iter().map(|e| kind(e).to_string()).collect()
}
fn table(out: &DxfOutput, kind_: &str) -> Vec<Pairs> {
section(&pairs(&out.bytes), "TABLES").into_iter().filter(|o| kind(o) == kind_).collect()
}
/// A 200 × 100 pt document whose first layer holds what `nodes` makes.
fn doc_with(nodes: impl FnOnce(&mut Document) -> Vec<Node>) -> Document {
let mut d = Document::new(200.0, 100.0);
let nodes = nodes(&mut d);
let layer = d.layers[0].id;
for n in nodes {
d.insert(Some(layer), usize::MAX, n).unwrap();
}
d
}
fn path(d: &mut Document, p: PathData, fill: Paint, stroke: Paint, width: f64) -> Node {
Node::path(d.alloc_id(), p, Appearance::basic(fill, stroke, width))
}
/// The options with the first artboard as the region, in points.
fn opts(d: &Document) -> DxfOptions {
DxfOptions { region: d.artboards[0].rect, unit: Unit::Points, ..DxfOptions::default() }
}
/// A red-filled rectangle with a black 1 pt stroke, and an unfilled blue 2 pt ellipse.
fn shapes_doc() -> Document {
doc_with(|d| {
vec![
path(d, shapes::rectangle(Rect::new(10.0, 10.0, 110.0, 60.0)), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::BLACK), 1.0),
path(d, shapes::ellipse(Rect::new(120.0, 20.0, 180.0, 80.0)), Paint::None, Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 2.0),
]
})
}
#[test]
fn every_version_declares_its_acadver_and_is_well_formed() {
let d = shapes_doc();
for v in DxfVersion::ALL {
let out = export(&d, &DxfOptions { version: v, ..opts(&d) }).unwrap();
let p = pairs(&out.bytes);
assert_eq!(header(&p, "$ACADVER").as_deref(), Some(v.acadver()), "{v:?}");
assert_eq!(p.last(), Some(&(0, "EOF".to_string())), "{v:?}");
let opened = p.iter().filter(|x| **x == (0, "SECTION".into())).count();
assert_eq!(opened, p.iter().filter(|x| **x == (0, "ENDSEC".into())).count(), "{v:?}: balanced sections");
assert!(!entities(&out).is_empty(), "{v:?}");
if v >= DxfVersion::R13 {
// Every handle is unique and below $HANDSEED.
let body = &p[p.iter().position(|x| *x == (0, "ENDSEC".into())).unwrap()..];
let handles: Vec<u32> = body.iter().filter(|x| x.0 == 5 || x.0 == 105).map(|x| u32::from_str_radix(&x.1, 16).unwrap()).collect();
let unique: std::collections::HashSet<_> = handles.iter().collect();
assert_eq!(unique.len(), handles.len(), "{v:?}: unique handles");
let seed = u32::from_str_radix(&header(&p, "$HANDSEED").unwrap(), 16).unwrap();
assert!(handles.iter().all(|h| *h < seed), "{v:?}: handles below the seed");
assert!(section(&p, "OBJECTS").iter().any(|o| kind(o) == "DICTIONARY"), "{v:?}: root dictionary");
} else {
assert!(header(&p, "$HANDSEED").is_none());
}
}
assert_eq!(DxfVersion::from_id("r2013"), Some(DxfVersion::R2013));
assert_eq!(DxfVersion::from_id("AC1009"), Some(DxfVersion::R12));
assert_eq!(DxfVersion::from_id("2019"), None);
}
#[test]
fn lines_are_lwpolylines_curves_splines_and_fills_hatches() {
let d = shapes_doc();
let out = export(&d, &opts(&d)).unwrap();
assert_eq!(kinds(&out), ["HATCH", "LWPOLYLINE", "SPLINE"], "fill, then stroke, then the ellipse's stroke");
let e = entities(&out);
// The rectangle, y up from the artboard's bottom-left corner: 10..110 × 40..90.
let poly = &e[1];
assert_eq!(get(poly, 70), Some("1"), "closed");
let mut xs = all(poly, 10);
xs.sort_by(f64::total_cmp);
assert_eq!(xs, [10.0, 10.0, 110.0, 110.0]);
let mut ys = all(poly, 20);
ys.sort_by(f64::total_cmp);
assert_eq!(ys, [40.0, 40.0, 90.0, 90.0]);
let hatch = &e[0];
assert_eq!((get(hatch, 2), get(hatch, 70), get(hatch, 91), get(hatch, 93)), (Some("SOLID"), Some("1"), Some("1"), Some("4")));
// The ellipse: four cubics through clamped knots.
let spline = &e[2];
assert_eq!((get(spline, 71), get(spline, 73)), (Some("3"), Some("13")));
assert_eq!(all(spline, 40), [0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0, 4.0, 4.0, 4.0, 4.0]);
// R14 has lightweight polylines but no lineweights: the stroke is a polyline width.
let r14 = export(&d, &DxfOptions { version: DxfVersion::R14, ..opts(&d) }).unwrap();
assert_eq!(get(&entities(&r14)[1], 43), Some("1"));
assert_eq!(get(&entities(&r14)[1], 370), None);
// R13 has splines and hatches, and polylines of vertices.
let r13 = export(&d, &DxfOptions { version: DxfVersion::R13, ..opts(&d) }).unwrap();
assert_eq!(kinds(&r13), ["HATCH", "POLYLINE", "VERTEX", "VERTEX", "VERTEX", "VERTEX", "SEQEND", "SPLINE"]);
// R12: polylines only; the fill is its outline, the ellipse flattened.
let r12 = export(&d, &DxfOptions { version: DxfVersion::R12, ..opts(&d) }).unwrap();
let k = kinds(&r12);
assert!(k.iter().all(|k| matches!(k.as_str(), "POLYLINE" | "VERTEX" | "SEQEND")), "{k:?}");
assert_eq!(k.iter().filter(|k| *k == "POLYLINE").count(), 3);
assert!(k.iter().filter(|k| *k == "VERTEX").count() > 20, "the ellipse is flattened");
assert!(r12.warnings.iter().any(|w| w.contains("R12 has no fills")), "{:?}", r12.warnings);
}
#[test]
fn colours_map_to_the_index_palette_or_true_colour() {
let d = shapes_doc();
let style = |o: &DxfOutput, i: usize| {
let e = &entities(o)[i];
(get(e, 62).map(str::to_string), get(e, 420).map(str::to_string))
};
let out = export(&d, &opts(&d)).unwrap();
assert_eq!(style(&out, 0), (Some("1".into()), Some("16711680".into())), "red: index 1, true colour 0xFF0000");
assert_eq!(style(&out, 1), (Some("7".into()), Some("0".into())), "black is index 7");
assert_eq!(style(&out, 2), (Some("5".into()), Some("255".into())));
for depth in [ColorDepth::Aci8, ColorDepth::Aci16, ColorDepth::Aci256] {
let o = export(&d, &DxfOptions { colors: depth, ..opts(&d) }).unwrap();
assert_eq!(style(&o, 0), (Some("1".into()), None), "{depth:?}");
}
let orange = doc_with(|d| {
vec![path(d, shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Paint::solid(Color::from_hex("#ff8000").unwrap()), Paint::None, 0.0)]
});
let aci = |depth| get(&entities(&export(&orange, &DxfOptions { colors: depth, ..opts(&orange) }).unwrap())[0], 62).unwrap().to_string();
assert_eq!(
(aci(ColorDepth::Aci256), aci(ColorDepth::Aci16), aci(ColorDepth::Aci8)),
("30".into(), "30".into(), "2".into()),
"8 colours: yellow is nearest"
);
// True colour needs 2004: earlier versions fall back to indices, and say so.
let old = export(&d, &DxfOptions { version: DxfVersion::R2000, ..opts(&d) }).unwrap();
assert_eq!(style(&old, 0), (Some("1".into()), None));
assert!(old.warnings.iter().any(|w| w.contains("true colour")));
}
#[test]
fn units_scale_coordinates_and_set_insunits() {
let d = shapes_doc();
let insunits = |o: &DxfOutput| header(&pairs(&o.bytes), "$INSUNITS");
let max_x = |o: &DxfOutput| all(&entities(o)[1], 10).into_iter().fold(f64::MIN, f64::max);
let mm = export(&d, &DxfOptions { unit: Unit::Millimeters, ..opts(&d) }).unwrap();
assert_eq!(insunits(&mm).as_deref(), Some("4"));
assert!((max_x(&mm) - 110.0 * 25.4 / 72.0).abs() < 1e-5);
assert_eq!(header(&pairs(&mm.bytes), "$MEASUREMENT").as_deref(), Some("1"));
let inches = export(&d, &DxfOptions { unit: Unit::Inches, ..opts(&d) }).unwrap();
assert_eq!(insunits(&inches).as_deref(), Some("1"));
// 1 in = 10 units: unitless, coordinates ten times larger.
let scaled = export(&d, &DxfOptions { unit: Unit::Inches, scale: 10.0, ..opts(&d) }).unwrap();
assert_eq!(insunits(&scaled).as_deref(), Some("0"));
assert!((max_x(&scaled) - 110.0 / 72.0 * 10.0).abs() < 1e-5);
// Lineweights: 1 pt is 0.35 mm, scaled with the drawing only when asked.
assert_eq!(get(&entities(&scaled)[1], 370), Some("35"));
let heavy = export(&d, &DxfOptions { unit: Unit::Inches, scale: 2.0, scale_lineweights: true, ..opts(&d) }).unwrap();
assert_eq!(get(&entities(&heavy)[1], 370), Some("70"));
assert!(export(&d, &DxfOptions { scale: 0.0, ..opts(&d) }).is_err());
assert!(export(&d, &DxfOptions { scale: f64::NAN, ..opts(&d) }).is_err());
}
#[test]
fn layers_become_dxf_layers() {
let mut d = shapes_doc();
let second = d.add_layer(Some("Dims: <top>"));
let hidden = d.add_layer(Some("Notes"));
let template = d.add_layer(Some("Tracing"));
for l in [second, hidden, template] {
let n = path(&mut d, shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Paint::solid(Color::BLACK), Paint::None, 0.0);
d.insert(Some(l), 0, n).unwrap();
}
if let Some(n) = d.node_mut(hidden) {
n.visible = false;
}
if let Some(NodeKind::Layer { template, .. }) = d.node_mut(template).map(|n| &mut n.kind) {
*template = true;
}
let out = export(&d, &opts(&d)).unwrap();
let layers: Vec<(String, String)> =
table(&out, "LAYER").iter().map(|o| (get(o, 2).unwrap().to_string(), get(o, 62).unwrap().to_string())).collect();
let names: Vec<&str> = layers.iter().map(|l| l.0.as_str()).collect();
assert_eq!(names, ["0", "Layer 1", "Dims_ _top_", "Notes"], "the template layer is left out");
assert!(layers[3].1.starts_with('-'), "a hidden layer is switched off");
let on: Vec<String> = entities(&out).iter().map(|e| get(e, 8).unwrap().to_string()).collect();
assert_eq!(on, ["Layer 1", "Layer 1", "Layer 1", "Dims_ _top_", "Notes"]);
// Before 2000: capitals, letters, digits and $-_ only.
let r12 = export(&d, &DxfOptions { version: DxfVersion::R12, ..opts(&d) }).unwrap();
let names: Vec<String> = table(&r12, "LAYER").iter().map(|o| get(o, 2).unwrap().to_string()).collect();
assert_eq!(names, ["0", "LAYER_1", "DIMS___TOP_", "NOTES"]);
}
#[test]
fn dashes_become_linetypes_and_opacity_transparency() {
let d = doc_with(|d| {
let mut n = path(d, shapes::line(Point::new(0.0, 50.0), Point::new(100.0, 50.0)), Paint::None, Paint::solid(Color::BLACK), 1.0);
if let Some(st) = n.appearance.stroke_mut() {
st.dash = Some(Dash { pattern: vec![6.0, 3.0], offset: 0.0, align_corners: false });
}
n.opacity = 0.5;
vec![n]
});
let out = export(&d, &opts(&d)).unwrap();
let e = &entities(&out)[0];
let alpha = (0x0200_0000 | 128).to_string();
assert_eq!((get(e, 6), get(e, 440)), (Some("DASHED1"), Some(alpha.as_str())));
let lt = table(&out, "LTYPE").into_iter().find(|o| get(o, 2) == Some("DASHED1")).unwrap();
assert_eq!(all(&lt, 49), [6.0, -3.0]);
let old = export(&d, &DxfOptions { version: DxfVersion::R2000, ..opts(&d) }).unwrap();
assert!(get(&entities(&old)[0], 440).is_none());
assert!(old.warnings.iter().any(|w| w.contains("transparency")));
}
#[test]
fn alter_paths_writes_strokes_as_filled_outlines() {
let d = shapes_doc();
let out = export(&d, &DxfOptions { alter_paths: true, ..opts(&d) }).unwrap();
assert_eq!(kinds(&out), ["HATCH", "HATCH", "HATCH"]);
// The rectangle's stroke: an outer and an inner boundary.
assert_eq!(get(&entities(&out)[1], 91), Some("2"));
// Preserve Appearance outlines only the strokes a line can't draw.
let mut d = shapes_doc();
let rect = d.layers[0].children().and_then(|c| c.first()).map(|n| n.id).unwrap();
if let Some(st) = d.node_mut(rect).and_then(|n| n.appearance.stroke_mut()) {
st.align = vectorcraft_doc::StrokeAlign::Outside;
}
assert_eq!(kinds(&export(&d, &opts(&d)).unwrap()), ["HATCH", "HATCH", "SPLINE"]);
let editable = export(&d, &DxfOptions { preserve: Preserve::Editability, ..opts(&d) }).unwrap();
assert_eq!(kinds(&editable), ["HATCH", "LWPOLYLINE", "SPLINE"]);
assert!(editable.warnings.iter().any(|w| w.contains("stroke alignment")));
}
fn text_doc(text: &str, size: f64) -> Document {
doc_with(|d| {
let style = CharStyle { size, fill: Paint::solid(Color::rgb(0.0, 0.5, 0.0)), ..CharStyle::default() };
let t = TextObject::point(Point::new(10.0, 50.0), text, style);
vec![Node::new(d.alloc_id(), NodeKind::Text(Box::new(t)))]
})
}
#[test]
fn type_is_text_or_outlines() {
let d = text_doc("Plan A", 20.0);
let editable = export(&d, &DxfOptions { preserve: Preserve::Editability, ..opts(&d) }).unwrap();
let e = entities(&editable);
assert_eq!(e.len(), 1);
assert_eq!((kind(&e[0]), get(&e[0], 1)), ("TEXT", Some("Plan A")));
assert!((all(&e[0], 40)[0] - 14.0).abs() < 1e-6, "the cap height of 20 pt type");
assert_eq!((all(&e[0], 10)[0], all(&e[0], 20)[0]), (10.0, 50.0), "the baseline start, y up");
let family = CharStyle::default().font_family;
let style = table(&editable, "STYLE").into_iter().find(|o| get(o, 3) == Some(&*format!("{family}.ttf"))).unwrap();
assert_eq!(get(&e[0], 7), get(&style, 2));
// Outline Text, and Preserve Appearance: the glyphs as filled outlines.
for o in [DxfOptions { preserve: Preserve::Editability, outline_text: true, ..opts(&d) }, opts(&d)] {
let k = kinds(&export(&d, &o).unwrap());
assert!(!k.is_empty() && k.iter().all(|k| k == "HATCH"), "{k:?}");
}
}
#[test]
fn text_outside_ascii_is_escaped_before_2007() {
let d = text_doc("Größe", 12.0);
let text = |v| {
let out = export(&d, &DxfOptions { version: v, preserve: Preserve::Editability, ..opts(&d) }).unwrap();
get(&entities(&out)[0], 1).unwrap().to_string()
};
assert_eq!(text(DxfVersion::R2004), "Gr\\U+00F6\\U+00DFe");
assert_eq!(text(DxfVersion::R2018), "Größe");
}
#[test]
fn images_link_png_or_jpeg_files() {
let mut png = vec![];
image::RgbaImage::from_pixel(4, 2, image::Rgba([255, 0, 0, 128])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
let mut d = doc_with(|d| {
let im = ImageObject {
key: "raster-1".into(),
width: 4,
height: 2,
xf: Affine::translate((10.0, 20.0)) * Affine::scale(5.0),
link: None,
placement: Default::default(),
};
vec![Node::new(d.alloc_id(), NodeKind::Image(im))]
});
d.images.insert("raster-1".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(png), proxy: None });
let out = export(&d, &opts(&d)).unwrap();
let e = entities(&out);
assert_eq!(kind(&e[0]), "IMAGE");
// The bottom-left corner (10, 30) is (10, 70) y up; a pixel is 5 units.
assert_eq!((all(&e[0], 10)[0], all(&e[0], 20)[0]), (10.0, 70.0));
assert_eq!((all(&e[0], 11)[0], all(&e[0], 22)[0], all(&e[0], 13)[0], all(&e[0], 23)[0]), (5.0, 5.0, 4.0, 2.0));
assert_eq!(out.images.len(), 1);
assert!(out.images[0].name.ends_with(".png") && out.images[0].bytes.starts_with(b"\x89PNG"));
let p = pairs(&out.bytes);
let objects = section(&p, "OBJECTS");
let def = objects.iter().find(|o| kind(o) == "IMAGEDEF").unwrap();
assert_eq!(get(def, 1), Some(out.images[0].name.as_str()));
assert_eq!(get(&e[0], 340), get(def, 5), "the image points at its definition");
assert!(objects.iter().any(|o| kind(o) == "IMAGEDEF_REACTOR"));
assert!(section(&p, "CLASSES").iter().any(|o| get(o, 1) == Some("IMAGE")));
let jpeg = export(&d, &DxfOptions { raster: RasterFormat::Jpeg, ..opts(&d) }).unwrap();
assert!(jpeg.images[0].name.ends_with(".jpg") && jpeg.images[0].bytes.starts_with(&[0xFF, 0xD8]));
let r12 = export(&d, &DxfOptions { version: DxfVersion::R12, ..opts(&d) }).unwrap();
assert!(entities(&r12).is_empty() && r12.images.is_empty());
assert!(r12.warnings.iter().any(|w| w.contains("no images")));
}
#[test]
fn crop_leaves_out_art_outside_the_region() {
let d = shapes_doc();
// Only the ellipse (120..180) reaches into 115..200.
let o = DxfOptions { region: Rect::new(115.0, 0.0, 200.0, 100.0), crop: true, ..opts(&d) };
assert_eq!(kinds(&export(&d, &o).unwrap()), ["SPLINE"]);
assert_eq!(kinds(&export(&d, &DxfOptions { crop: false, ..o }).unwrap()).len(), 3);
}
+661
View File
@@ -0,0 +1,661 @@
//! The ASCII DXF file: group codes, handles, and the sections, tables and objects around the
//! entities. DXF R13 and later give every object a handle and subclass markers; R2000 and later
//! add layouts and plot styles, which CAD apps expect to find.
use std::fmt::Write as _;
use crate::DxfVersion;
/// An object handle (written in hex).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Handle(pub u32);
/// The handles of the fixed objects every drawing has. Entities and table entries count up from
/// [`FIRST_FREE`].
pub(crate) mod fixed {
use super::Handle;
pub const LAYER_TABLE: Handle = Handle(0x1);
pub const LTYPE_TABLE: Handle = Handle(0x2);
pub const APPID_TABLE: Handle = Handle(0x3);
pub const DIMSTYLE_TABLE: Handle = Handle(0x4);
pub const STYLE_TABLE: Handle = Handle(0x5);
pub const UCS_TABLE: Handle = Handle(0x6);
pub const VIEW_TABLE: Handle = Handle(0x7);
pub const VPORT_TABLE: Handle = Handle(0x8);
pub const BLOCK_RECORD_TABLE: Handle = Handle(0x9);
pub const ROOT: Handle = Handle(0xA);
pub const GROUPS: Handle = Handle(0xB);
pub const LAYOUTS: Handle = Handle(0xC);
pub const MODEL_RECORD: Handle = Handle(0xD);
pub const PAPER_RECORD: Handle = Handle(0xE);
pub const MODEL_BLOCK: Handle = Handle(0xF);
pub const MODEL_END: Handle = Handle(0x10);
pub const PAPER_BLOCK: Handle = Handle(0x11);
pub const PAPER_END: Handle = Handle(0x12);
pub const MODEL_LAYOUT: Handle = Handle(0x13);
pub const PAPER_LAYOUT: Handle = Handle(0x14);
pub const ACTIVE_VPORT: Handle = Handle(0x15);
pub const ACAD_APPID: Handle = Handle(0x16);
pub const STANDARD_DIMSTYLE: Handle = Handle(0x17);
pub const IMAGE_DICT: Handle = Handle(0x18);
pub const IMAGE_VARS: Handle = Handle(0x19);
pub const PLOT_STYLES: Handle = Handle(0x1A);
pub const PLOT_NORMAL: Handle = Handle(0x1B);
pub const FIRST_FREE: u32 = 0x30;
}
/// A number as DXF writes it: up to 6 decimals, no trailing zeros, 0 for anything not finite.
pub(crate) fn num(v: f64) -> String {
if !v.is_finite() {
return "0".into();
}
let s = format!("{v:.6}");
let s = s.trim_end_matches('0').trim_end_matches('.');
if s == "-0" || s.is_empty() { "0".into() } else { s.into() }
}
/// Text as a DXF string value: one line, `^` escaped, and before DXF 2007 (which reads UTF-8)
/// every character outside ASCII as `\U+XXXX`.
pub(crate) fn text(s: &str, utf8: bool) -> String {
let mut out = String::with_capacity(s.len());
for c in s.chars() {
match c {
'\r' | '\n' | '\t' => out.push(' '),
c if c.is_control() => {}
'^' => out.push_str("^ "),
c if !utf8 && !c.is_ascii() => match u16::try_from(u32::from(c)) {
Ok(u) => _ = write!(out, "\\U+{u:04X}"),
Err(_) => out.push('?'),
},
c => out.push(c),
}
}
out
}
/// Group-code/value pairs in the order they are written.
pub(crate) struct Codes {
pub v: DxfVersion,
out: String,
}
impl Codes {
pub fn new(v: DxfVersion) -> Self {
Self { v, out: String::new() }
}
pub fn into_string(self) -> String {
self.out
}
pub fn append(&mut self, other: &str) {
self.out.push_str(other);
}
/// A value written as it is (names and keywords the writer itself chose).
pub fn raw(&mut self, code: u16, value: &str) {
_ = writeln!(self.out, "{code:>3}\n{value}");
}
/// Text from the document, encoded for the version (see [`text`]).
pub fn str(&mut self, code: u16, value: &str) {
let t = text(value, self.v.utf8());
self.raw(code, &t);
}
pub fn int(&mut self, code: u16, value: i64) {
_ = writeln!(self.out, "{code:>3}\n{value}");
}
pub fn num(&mut self, code: u16, value: f64) {
_ = writeln!(self.out, "{code:>3}\n{}", num(value));
}
pub fn handle(&mut self, code: u16, h: Handle) {
_ = writeln!(self.out, "{code:>3}\n{:X}", h.0);
}
/// A 2D point at `code` (x), `code + 10` (y).
pub fn xy(&mut self, code: u16, x: f64, y: f64) {
self.num(code, x);
self.num(code + 10, y);
}
/// A 3D point at `code`, `code + 10`, `code + 20` (z = 0).
pub fn xyz(&mut self, code: u16, x: f64, y: f64) {
self.xy(code, x, y);
self.num(code + 20, 0.0);
}
/// The extrusion direction of planar entities: the z axis.
pub fn normal(&mut self) {
self.num(210, 0.0);
self.num(220, 0.0);
self.num(230, 1.0);
}
/// The start of an object: its type, and from R13 its handle, owner and first subclass.
fn object(&mut self, kind: &str, h: Handle, owner: Handle, subclass: &str) {
self.raw(0, kind);
if self.v.handles() {
self.handle(if kind == "DIMSTYLE" { 105 } else { 5 }, h);
self.handle(330, owner);
self.raw(100, subclass);
}
}
/// A table entry: the shared record subclass, then the table's own (from R13).
fn record(&mut self, kind: &str, h: Handle, table: Handle, subclass: &str) {
self.object(kind, h, table, "AcDbSymbolTableRecord");
if self.v.handles() {
self.raw(100, subclass);
}
}
fn section(&mut self, name: &str) {
self.raw(0, "SECTION");
self.raw(2, name);
}
fn end_section(&mut self) {
self.raw(0, "ENDSEC");
}
fn table(&mut self, name: &str, h: Handle, count: usize) {
self.raw(0, "TABLE");
self.raw(2, name);
if self.v.handles() {
self.handle(5, h);
self.raw(330, "0");
self.raw(100, "AcDbSymbolTable");
}
self.int(70, count as i64);
if name == "DIMSTYLE" && self.v.r2000() {
self.raw(100, "AcDbDimStyleTable");
}
}
fn end_table(&mut self) {
self.raw(0, "ENDTAB");
}
}
/// How an entity is drawn: its colour index, true colour, lineweight, linetype and transparency.
#[derive(Clone, Debug, Default)]
pub(crate) struct EntityStyle {
pub aci: u8,
/// `0xRRGGBB` (DXF 2004 and later).
pub rgb: Option<u32>,
/// Hundredths of a millimetre (DXF 2000 and later).
pub lineweight: Option<i32>,
pub linetype: Option<String>,
/// Opacity 0–255 (DXF 2004 and later; opaque is left out).
pub alpha: Option<u8>,
}
impl Codes {
/// The start of an entity of `kind` owned by `owner` (model space, or a polyline for its
/// vertices) on `layer` with its style, ending with `subclass` (none when empty).
pub fn entity(&mut self, kind: &str, h: Handle, owner: Handle, layer: &str, style: &EntityStyle, subclass: &str) {
self.object(kind, h, owner, "AcDbEntity");
self.str(8, layer);
if let Some(lt) = &style.linetype {
self.str(6, lt);
}
self.int(62, i64::from(style.aci.max(1)));
if self.v.r2000()
&& let Some(lw) = style.lineweight
{
self.int(370, i64::from(lw));
}
if self.v.true_color() {
if let Some(rgb) = style.rgb {
self.int(420, i64::from(rgb));
}
if let Some(a) = style.alpha {
self.int(440, 0x0200_0000 | i64::from(a));
}
}
if self.v.handles() && !subclass.is_empty() {
self.raw(100, subclass);
}
}
}
/// A DXF layer.
#[derive(Clone, Debug)]
pub(crate) struct Layer {
pub name: String,
pub aci: u8,
/// Switched off (a hidden layer).
pub off: bool,
pub locked: bool,
/// Plotted (printable).
pub plot: bool,
}
/// A dash pattern: dash, gap, dash… lengths in drawing units.
#[derive(Clone, Debug)]
pub(crate) struct LineType {
pub name: String,
pub pattern: Vec<f64>,
}
/// A placed image file and the image entities that show it.
#[derive(Clone, Debug)]
pub(crate) struct ImageDef {
pub name: String,
pub size: (u32, u32),
pub handle: Handle,
/// `(reactor, image entity)` per image entity.
pub reactors: Vec<(Handle, Handle)>,
}
/// Everything around the entities, collected while they were written.
pub(crate) struct Drawing {
pub version: DxfVersion,
pub layers: Vec<Layer>,
pub linetypes: Vec<LineType>,
/// Text styles: (style name, font family).
pub styles: Vec<(String, String)>,
pub images: Vec<ImageDef>,
/// The entities' group codes.
pub entities: String,
/// `[x0, y0, x1, y1]` of everything written (drawing units).
pub extents: [f64; 4],
/// The export region (drawing units).
pub limits: [f64; 4],
/// `$INSUNITS`.
pub insunits: u8,
pub metric: bool,
/// The next free handle.
pub next: u32,
}
/// The text style every drawing has.
pub(crate) const STANDARD_STYLE: &str = "Standard";
impl Drawing {
/// The whole file.
pub fn write(self) -> String {
let v = self.version;
let mut c = Codes::new(v);
// Table entries get the handles after the entities'.
let mut next = self.next;
let mut take = |n: usize| {
let start = next;
next = next.saturating_add(u32::try_from(n).unwrap_or(u32::MAX));
start
};
let ltype_base = take(3 + self.linetypes.len());
let layer_base = take(1 + self.layers.len());
let style_base = take(1 + self.styles.len());
self.header(&mut c, next);
if v.handles() {
self.classes(&mut c);
}
c.section("TABLES");
self.vport(&mut c);
self.ltypes(&mut c, ltype_base);
self.layer_table(&mut c, layer_base);
self.style_table(&mut c, style_base);
if v.handles() {
for (name, h) in [("VIEW", fixed::VIEW_TABLE), ("UCS", fixed::UCS_TABLE)] {
c.table(name, h, 0);
c.end_table();
}
c.table("APPID", fixed::APPID_TABLE, 1);
c.record("APPID", fixed::ACAD_APPID, fixed::APPID_TABLE, "AcDbRegAppTableRecord");
c.raw(2, "ACAD");
c.int(70, 0);
c.end_table();
c.table("DIMSTYLE", fixed::DIMSTYLE_TABLE, 1);
c.record("DIMSTYLE", fixed::STANDARD_DIMSTYLE, fixed::DIMSTYLE_TABLE, "AcDbDimStyleTableRecord");
c.raw(2, "Standard");
c.int(70, 0);
c.end_table();
c.table("BLOCK_RECORD", fixed::BLOCK_RECORD_TABLE, 2);
for (name, h, layout) in
[("*Model_Space", fixed::MODEL_RECORD, fixed::MODEL_LAYOUT), ("*Paper_Space", fixed::PAPER_RECORD, fixed::PAPER_LAYOUT)]
{
c.record("BLOCK_RECORD", h, fixed::BLOCK_RECORD_TABLE, "AcDbBlockTableRecord");
c.raw(2, name);
if v.r2000() {
c.handle(340, layout);
c.int(70, 0);
c.int(280, 1);
c.int(281, 0);
}
}
c.end_table();
}
c.end_section();
if v.handles() {
c.section("BLOCKS");
for (name, record, begin, end) in [
("*Model_Space", fixed::MODEL_RECORD, fixed::MODEL_BLOCK, fixed::MODEL_END),
("*Paper_Space", fixed::PAPER_RECORD, fixed::PAPER_BLOCK, fixed::PAPER_END),
] {
c.object("BLOCK", begin, record, "AcDbEntity");
c.raw(8, "0");
c.raw(100, "AcDbBlockBegin");
c.raw(2, name);
c.int(70, 0);
c.xyz(10, 0.0, 0.0);
c.raw(3, name);
c.raw(1, "");
c.object("ENDBLK", end, record, "AcDbEntity");
c.raw(8, "0");
c.raw(100, "AcDbBlockEnd");
}
c.end_section();
}
c.section("ENTITIES");
c.append(&self.entities);
c.end_section();
if v.handles() {
self.objects(&mut c);
}
c.raw(0, "EOF");
c.into_string()
}
fn header(&self, c: &mut Codes, handseed: u32) {
let v = self.version;
let var = |c: &mut Codes, name: &str| c.raw(9, name);
c.section("HEADER");
var(c, "$ACADVER");
c.raw(1, v.acadver());
var(c, "$DWGCODEPAGE");
c.raw(3, "ANSI_1252");
var(c, "$INSBASE");
c.xyz(10, 0.0, 0.0);
let [x0, y0, x1, y1] = self.extents;
var(c, "$EXTMIN");
c.xyz(10, x0, y0);
var(c, "$EXTMAX");
c.xyz(10, x1, y1);
let [lx0, ly0, lx1, ly1] = self.limits;
var(c, "$LIMMIN");
c.xy(10, lx0, ly0);
var(c, "$LIMMAX");
c.xy(10, lx1, ly1);
if v.r2000() {
var(c, "$LWDISPLAY");
c.int(290, 1);
var(c, "$INSUNITS");
c.int(70, i64::from(self.insunits));
var(c, "$MEASUREMENT");
c.int(70, i64::from(self.metric));
}
if v.handles() {
var(c, "$HANDSEED");
c.handle(5, Handle(handseed));
}
c.end_section();
}
fn classes(&self, c: &mut Codes) {
let mut classes: Vec<(&str, &str, &str, i64, bool)> = vec![];
if self.version.r2000() {
classes.extend([
("ACDBDICTIONARYWDFLT", "AcDbDictionaryWithDefault", "ObjectDBX Classes", 0, false),
("ACDBPLACEHOLDER", "AcDbPlaceHolder", "ObjectDBX Classes", 0, false),
("LAYOUT", "AcDbLayout", "ObjectDBX Classes", 0, false),
]);
}
if !self.images.is_empty() {
classes.extend([
("RASTERVARIABLES", "AcDbRasterVariables", "ISM", 0, false),
("IMAGE", "AcDbRasterImage", "ISM", 2175, true),
("IMAGEDEF", "AcDbRasterImageDef", "ISM", 0, false),
("IMAGEDEF_REACTOR", "AcDbRasterImageDefReactor", "ISM", 1, false),
]);
}
c.section("CLASSES");
for (name, cpp, app, flags, entity) in classes {
c.raw(0, "CLASS");
c.raw(1, name);
c.raw(2, cpp);
c.raw(3, app);
c.int(90, flags);
if self.version.true_color() {
c.int(91, 0);
}
c.int(280, 0);
c.int(281, i64::from(entity));
}
c.end_section();
}
/// The active viewport, zoomed to the drawing's extents.
fn vport(&self, c: &mut Codes) {
let [x0, y0, x1, y1] = self.extents;
c.table("VPORT", fixed::VPORT_TABLE, 1);
c.record("VPORT", fixed::ACTIVE_VPORT, fixed::VPORT_TABLE, "AcDbViewportTableRecord");
c.raw(2, if self.version.handles() { "*Active" } else { "*ACTIVE" });
c.int(70, 0);
c.xy(10, 0.0, 0.0);
c.xy(11, 1.0, 1.0);
c.xy(12, (x0 + x1) / 2.0, (y0 + y1) / 2.0);
c.xy(13, 0.0, 0.0);
c.xy(14, 1.0, 1.0);
c.xy(15, 10.0, 10.0);
c.xyz(16, 0.0, 0.0);
c.num(36, 1.0);
c.xyz(17, 0.0, 0.0);
let (w, h) = ((x1 - x0).abs(), (y1 - y0).abs());
// The view's height, with a margin; its width follows from the aspect ratio.
c.num(40, (h.max(w / 1.5) * 1.1).max(1.0));
c.num(41, 1.5);
c.num(42, 50.0);
c.num(43, 0.0);
c.num(44, 0.0);
c.num(50, 0.0);
c.num(51, 0.0);
for (code, value) in [(71, 0), (72, 1000), (73, 1), (74, 3), (75, 0), (76, 0), (77, 0), (78, 0)] {
c.int(code, value);
}
if self.version.r2000() {
c.int(281, 0);
c.int(65, 0);
c.num(146, 0.0);
}
c.end_table();
}
fn ltypes(&self, c: &mut Codes, base: u32) {
c.table("LTYPE", fixed::LTYPE_TABLE, 3 + self.linetypes.len());
let solid = [("ByBlock", ""), ("ByLayer", ""), ("Continuous", "Solid line")];
let rows = solid.iter().map(|(n, d)| (*n, *d, &[][..])).chain(self.linetypes.iter().map(|l| (l.name.as_str(), "", l.pattern.as_slice())));
for (i, (name, desc, pattern)) in rows.enumerate() {
c.record("LTYPE", Handle(base.saturating_add(i as u32)), fixed::LTYPE_TABLE, "AcDbLinetypeTableRecord");
c.str(2, name);
c.int(70, 0);
c.str(3, if pattern.is_empty() { desc } else { "Dashed" });
c.int(72, 65);
c.int(73, pattern.len() as i64);
c.num(40, pattern.iter().map(|v| v.abs()).sum());
for v in pattern {
c.num(49, *v);
if self.version.handles() {
c.int(74, 0);
}
}
}
c.end_table();
}
fn layer_table(&self, c: &mut Codes, base: u32) {
let zero = Layer { name: "0".into(), aci: 7, off: false, locked: false, plot: true };
c.table("LAYER", fixed::LAYER_TABLE, 1 + self.layers.len());
for (i, l) in std::iter::once(&zero).chain(&self.layers).enumerate() {
c.record("LAYER", Handle(base.saturating_add(i as u32)), fixed::LAYER_TABLE, "AcDbLayerTableRecord");
c.str(2, &l.name);
c.int(70, if l.locked { 4 } else { 0 });
// A negative colour switches the layer off.
let aci = i64::from(l.aci.max(1));
c.int(62, if l.off { -aci } else { aci });
c.raw(6, "Continuous");
if self.version.r2000() {
c.int(290, i64::from(l.plot));
c.int(370, -3);
c.handle(390, fixed::PLOT_NORMAL);
}
}
c.end_table();
}
fn style_table(&self, c: &mut Codes, base: u32) {
c.table("STYLE", fixed::STYLE_TABLE, 1 + self.styles.len());
let standard = (STANDARD_STYLE.to_string(), String::new());
for (i, (name, family)) in std::iter::once(&standard).chain(&self.styles).enumerate() {
c.record("STYLE", Handle(base.saturating_add(i as u32)), fixed::STYLE_TABLE, "AcDbTextStyleTableRecord");
c.str(2, name);
c.int(70, 0);
c.num(40, 0.0);
c.num(41, 1.0);
c.num(50, 0.0);
c.int(71, 0);
c.num(42, 2.5);
// The font file; from 2000 the family name too, which is how CAD apps find a TrueType font.
if family.is_empty() {
c.raw(3, "txt");
} else {
c.str(3, &format!("{family}.ttf"));
}
c.raw(4, "");
if self.version.r2000() && !family.is_empty() {
c.raw(1001, "ACAD");
c.str(1000, family);
c.int(1071, 0);
}
}
c.end_table();
}
fn objects(&self, c: &mut Codes) {
let v = self.version;
let images = !self.images.is_empty();
c.section("OBJECTS");
let dict = |c: &mut Codes, h: Handle, owner: Handle, entries: &[(&str, Handle)]| {
c.object("DICTIONARY", h, owner, "AcDbDictionary");
c.int(281, 1);
for (name, e) in entries {
c.str(3, name);
c.handle(350, *e);
}
};
let mut root = vec![("ACAD_GROUP", fixed::GROUPS)];
if images {
root.extend([("ACAD_IMAGE_DICT", fixed::IMAGE_DICT), ("ACAD_IMAGE_VARS", fixed::IMAGE_VARS)]);
}
if v.r2000() {
root.extend([("ACAD_LAYOUT", fixed::LAYOUTS), ("ACAD_PLOTSTYLENAME", fixed::PLOT_STYLES)]);
}
dict(c, fixed::ROOT, Handle(0), &root);
dict(c, fixed::GROUPS, fixed::ROOT, &[]);
if v.r2000() {
dict(c, fixed::LAYOUTS, fixed::ROOT, &[("Layout1", fixed::PAPER_LAYOUT), ("Model", fixed::MODEL_LAYOUT)]);
c.object("ACDBDICTIONARYWDFLT", fixed::PLOT_STYLES, fixed::ROOT, "AcDbDictionary");
c.int(281, 1);
c.raw(3, "Normal");
c.handle(350, fixed::PLOT_NORMAL);
c.raw(100, "AcDbDictionaryWithDefault");
c.handle(340, fixed::PLOT_NORMAL);
c.object("ACDBPLACEHOLDER", fixed::PLOT_NORMAL, fixed::PLOT_STYLES, "AcDbPlaceHolder");
self.layout(c, fixed::MODEL_LAYOUT, "Model", 0, fixed::MODEL_RECORD);
self.layout(c, fixed::PAPER_LAYOUT, "Layout1", 1, fixed::PAPER_RECORD);
}
if images {
c.object("RASTERVARIABLES", fixed::IMAGE_VARS, fixed::ROOT, "AcDbRasterVariables");
c.int(90, 0);
c.int(70, 0);
c.int(71, 1);
c.int(72, 0);
let entries: Vec<(&str, Handle)> = self.images.iter().map(|i| (i.name.as_str(), i.handle)).collect();
dict(c, fixed::IMAGE_DICT, fixed::ROOT, &entries);
for img in &self.images {
c.raw(0, "IMAGEDEF");
c.handle(5, img.handle);
c.raw(102, "{ACAD_REACTORS");
c.handle(330, fixed::IMAGE_DICT);
for (reactor, _) in &img.reactors {
c.handle(330, *reactor);
}
c.raw(102, "}");
c.handle(330, fixed::IMAGE_DICT);
c.raw(100, "AcDbRasterImageDef");
c.int(90, 0);
c.str(1, &img.name);
c.xy(10, f64::from(img.size.0), f64::from(img.size.1));
c.xy(11, 1.0, 1.0);
c.int(280, 1);
c.int(281, 0);
for (reactor, image) in &img.reactors {
c.object("IMAGEDEF_REACTOR", *reactor, *image, "AcDbRasterImageDefReactor");
c.int(90, 2);
c.handle(330, *image);
}
}
}
c.end_section();
}
/// A layout (DXF 2000 and later): its plot settings, then the layout itself.
fn layout(&self, c: &mut Codes, h: Handle, name: &str, tab: i64, record: Handle) {
let [x0, y0, x1, y1] = self.extents;
c.object("LAYOUT", h, fixed::LAYOUTS, "AcDbPlotSettings");
c.raw(1, "");
c.raw(2, "none_device");
c.raw(4, "");
c.raw(6, "");
for code in 40..=49 {
c.num(code, 0.0);
}
c.num(140, 0.0);
c.num(141, 0.0);
c.num(142, 1.0);
c.num(143, 1.0);
c.int(70, 688);
c.int(72, 1);
c.int(73, 0);
c.int(74, 5);
c.raw(7, "");
c.int(75, 16);
c.num(147, 1.0);
c.xy(148, 0.0, 0.0);
c.raw(100, "AcDbLayout");
c.raw(1, name);
c.int(70, 1);
c.int(71, tab);
let [lx0, ly0, lx1, ly1] = self.limits;
c.xy(10, lx0, ly0);
c.xy(11, lx1, ly1);
c.xyz(12, 0.0, 0.0);
c.xyz(14, x0, y0);
c.xyz(15, x1, y1);
c.num(146, 0.0);
c.xyz(13, 0.0, 0.0);
c.xyz(16, 1.0, 0.0);
c.xyz(17, 0.0, 1.0);
c.int(76, 1);
c.handle(330, record);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn numbers_and_text_are_written_plainly() {
assert_eq!(num(1.5), "1.5");
assert_eq!(num(-0.0000001), "0");
assert_eq!(num(2.0), "2");
assert_eq!(num(f64::NAN), "0");
assert_eq!(text("a^b\nc", true), "a^ b c");
assert_eq!(text("Größe 😀", false), "Gr\\U+00F6\\U+00DFe ?");
assert_eq!(text("Größe", true), "Größe");
}
}
+46 -3
View File
@@ -159,6 +159,21 @@ pub fn composite(mode: BlendMode, backdrop: [f32; 4], source: [f32; 4]) -> [f32;
[c(0) / ao, c(1) / ao, c(2) / ao, ao]
}
/// CMYK blending (CMYK documents). The formulas above work on additive values, so inks blend as
/// their complements, as subtractive colour spaces blend in PDF: a CMYK colour splits into two
/// additive planes, each blended with the formulas above, the complemented C, M and Y as one
/// colour and the complemented K as a grey. Multiply then adds inks (cyan over magenta prints
/// both: blue), and on the grey plane Hue, Saturation and Color keep the backdrop's black while
/// Luminosity takes the source's, as PDF has it for K.
pub fn cmyk_planes([c, m, y, k]: [f32; 4]) -> [[f32; 3]; 2] {
[[1.0 - c, 1.0 - m, 1.0 - y], [1.0 - k; 3]]
}
/// The inks of blended [`cmyk_planes`]: the C, M, Y plane and the K plane's grey.
pub fn planes_cmyk(cmy: [f32; 3], k: f32) -> [f32; 4] {
[1.0 - cmy[0], 1.0 - cmy[1], 1.0 - cmy[2], 1.0 - k].map(|v| v.clamp(0.0, 1.0))
}
fn screen(b: f32, s: f32) -> f32 {
b + s - b * s
}
@@ -175,16 +190,17 @@ fn sat(c: [f32; 3]) -> f32 {
c[0].max(c[1]).max(c[2]) - c[0].min(c[1]).min(c[2])
}
/// Bring a colour moved off the gamut by [`set_lum`] back in, keeping its luminance.
/// Bring a colour moved off the gamut by [`set_lum`] back in, keeping its luminance. A grey (all
/// components at its luminance, give or take rounding) is clamped instead of scaled by 0/0.
fn clip_color(c: [f32; 3]) -> [f32; 3] {
let l = lum(c);
let (n, x) = (c[0].min(c[1]).min(c[2]), c[0].max(c[1]).max(c[2]));
let mut c = c;
if n < 0.0 {
c = c.map(|v| l + (v - l) * l / (l - n));
c = if l - n > f32::EPSILON { c.map(|v| l + (v - l) * l / (l - n)) } else { c.map(|v| v.max(0.0)) };
}
if x > 1.0 {
c = c.map(|v| l + (v - l) * (1.0 - l) / (x - l));
c = if x - l > f32::EPSILON { c.map(|v| l + (v - l) * (1.0 - l) / (x - l)) } else { c.map(|v| v.min(1.0)) };
}
c
}
@@ -244,6 +260,12 @@ mod tests {
assert!((lum(blend_rgb(m, b, s)) - lum(b)).abs() < 1e-5, "{m:?}");
}
assert!((lum(blend_rgb(BlendMode::Luminosity, b, s)) - lum(s)).abs() < 1e-5);
// Greys stay finite where rounding puts their luminance just off their components.
for m in [BlendMode::Hue, BlendMode::Saturation, BlendMode::Color, BlendMode::Luminosity] {
for (b, s) in [([0.7; 3], [0.0; 3]), ([0.0; 3], [0.3; 3]), ([1.0; 3], [0.9; 3]), ([0.9; 3], [1.0; 3])] {
assert!(blend_rgb(m, b, s).iter().all(|v| v.is_finite() && (-1e-6..=1.0 + 1e-6).contains(v)), "{m:?} {b:?} {s:?}");
}
}
// Saturation of grey is 0: a grey source desaturates the backdrop to its luminance.
let l = lum(b);
assert!(near(blend_rgb(BlendMode::Saturation, b, [0.5; 3]), [l; 3]));
@@ -264,6 +286,27 @@ mod tests {
assert!(near([o[0], o[1], o[2]], [0.5; 3]) && (o[3] - 0.5).abs() < 1e-6, "{o:?}");
}
#[test]
fn cmyk_planes_blend_inks() {
let blend = |m: BlendMode, b: [f32; 4], s: [f32; 4]| {
let (pb, ps) = (cmyk_planes(b), cmyk_planes(s));
planes_cmyk(blend_rgb(m, pb[0], ps[0]), blend_rgb(m, pb[1], ps[1])[0])
};
let (cyan, magenta) = ([1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0]);
// Multiply adds the inks: cyan over magenta prints both.
assert_eq!(blend(BlendMode::Multiply, magenta, cyan), [1.0, 1.0, 0.0, 0.0]);
// Screen keeps the lighter (less ink) per plate.
assert_eq!(blend(BlendMode::Screen, magenta, cyan), [0.0; 4]);
let (b, s) = ([0.2, 0.6, 0.1, 0.3], [0.7, 0.1, 0.5, 0.8]);
// K: backdrop's for Hue, Saturation and Color, the source's for Luminosity.
for m in [BlendMode::Hue, BlendMode::Saturation, BlendMode::Color] {
assert!((blend(m, b, s)[3] - b[3]).abs() < 1e-6, "{m:?}");
}
assert!((blend(BlendMode::Luminosity, b, s)[3] - s[3]).abs() < 1e-6);
let back = planes_cmyk(cmyk_planes(b)[0], cmyk_planes(b)[1][0]);
assert!(back.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-6), "{back:?}");
}
#[test]
fn parse_labels() {
assert_eq!(BlendMode::parse("color burn"), Some(BlendMode::ColorBurn));
+118 -9
View File
@@ -1,10 +1,14 @@
//! ICC profiles through `moxcms` (pure Rust): built-in RGB spaces and user-supplied `.icc` files.
//! ICC profiles through `moxcms` (pure Rust): built-in RGB spaces and user-supplied `.icc` files,
//! and the profiles exports embed ([`encode_builtin`]), written in code from the CMS.
use std::sync::{Arc, OnceLock};
use moxcms::{ColorProfile, DataColorSpace, Layout, ProfileText, RenderingIntent, TransformF32Executor, TransformOptions};
use moxcms::{
ColorProfile, DataColorSpace, Layout, LocalizableString, LutMultidimensionalType, LutStore, LutWarehouse, Matrix3d, ProfileClass, ProfileText,
RenderingIntent, ToneReprCurve, TransformF32Executor, TransformOptions, Vector3d,
};
use super::{CmsError, Intent, ProfileKind};
use super::{CmsError, Intent, ProfileKind, lab};
fn moxcms_intent(i: Intent) -> RenderingIntent {
match i {
@@ -27,6 +31,8 @@ type Xf = Option<Arc<TransformF32Executor>>;
pub struct IccProfile {
pub name: String,
pub kind: ProfileKind,
/// The file it was loaded from (empty for profiles made in code).
source: Vec<u8>,
profile: ColorProfile,
srgb: ColorProfile,
to_srgb: [OnceLock<Xf>; 4],
@@ -58,12 +64,25 @@ impl IccProfile {
other => return Err(CmsError::Unsupported(format!("profile colour space {other:?} is not RGB, CMYK or Gray"))),
};
let name = name.or_else(|| text(&profile.description)).unwrap_or_else(|| format!("Untitled {kind:?} profile"));
Ok(Self { name, kind, profile, srgb: ColorProfile::new_srgb(), to_srgb: Default::default(), from_srgb: Default::default() })
Ok(Self {
name,
kind,
source: Vec::new(),
profile,
srgb: ColorProfile::new_srgb(),
to_srgb: Default::default(),
from_srgb: Default::default(),
})
}
pub fn from_bytes(name: Option<String>, bytes: &[u8]) -> Result<Self, CmsError> {
let p = ColorProfile::new_from_slice(bytes).map_err(|e| CmsError::BadProfile(format!("{e:?}")))?;
Self::from_profile(name, p)
Ok(Self { source: bytes.to_vec(), ..Self::from_profile(name, p)? })
}
/// The profile as an ICC file: the bytes it was loaded from, else encoded.
pub fn bytes(&self) -> Result<Vec<u8>, CmsError> {
if self.source.is_empty() { encode(&self.profile) } else { Ok(self.source.clone()) }
}
fn layout(&self) -> Layout {
@@ -122,14 +141,104 @@ impl IccProfile {
}
}
/// Built-in RGB working spaces from `moxcms`'s standard primaries.
pub fn builtin_rgb(name: &str) -> Option<IccProfile> {
let p = match name {
/// The primaries and tone curves of built-in RGB space `name`.
fn rgb_space(name: &str) -> Option<ColorProfile> {
Some(match name {
super::WIDE_GAMUT_RGB => ColorProfile::new_adobe_rgb(),
super::DISPLAY_P3 => ColorProfile::new_display_p3(),
super::PROPHOTO_RGB => ColorProfile::new_pro_photo_rgb(),
super::SRGB => ColorProfile::new_srgb(),
_ => return None,
})
}
/// Built-in RGB working spaces from `moxcms`'s standard primaries.
pub fn builtin_rgb(name: &str) -> Option<IccProfile> {
IccProfile::from_profile(Some(name.to_string()), rgb_space(name)?).ok()
}
/// Built-in RGB space `name` as an ICC file, under its name here.
pub(super) fn builtin_rgb_bytes(name: &str) -> Result<Vec<u8>, CmsError> {
encode(&labelled(rgb_space(name).ok_or_else(|| CmsError::UnknownProfile(name.into()))?, name))
}
/// Encode `p` as an ICC file. The creation date is fixed so exports are reproducible.
pub(super) fn encode(p: &ColorProfile) -> Result<Vec<u8>, CmsError> {
let mut bytes = p.encode().map_err(|e| CmsError::BadProfile(format!("{e:?}")))?;
// Header bytes 24..36: year, month, day, hours, minutes, seconds (u16 each).
if let Some(date) = bytes.get_mut(24..36) {
date.copy_from_slice(&[2026u16, 1, 1, 0, 0, 0].map(u16::to_be_bytes).concat());
}
Ok(bytes)
}
fn text_tag(s: &str) -> Option<ProfileText> {
Some(ProfileText::Localizable(vec![LocalizableString::new("en".into(), "US".into(), s.into())]))
}
/// Profiles made here carry their name and no copyright claim.
fn labelled(mut p: ColorProfile, name: &str) -> ColorProfile {
p.description = text_tag(name);
p.copyright = text_tag("No copyright, use freely");
p
}
/// Grid points per input channel of the CMYK → Lab table and of the Lab → CMYK table.
const A2B_GRID: usize = 9;
const B2A_GRID: usize = 17;
/// A CMYK output profile sampled from a conversion: `to_lab` (CMYK → media-relative Lab) in a
/// 9⁴ table, `from_lab` (Lab → CMYK, gamut-mapped) in a 17³ table, Lab PCS (ICC v4 encoding).
pub(super) fn cmyk_profile(name: &str, to_lab: impl Fn([f32; 4]) -> lab::Lab, from_lab: impl Fn(lab::Lab) -> [f32; 4]) -> ColorProfile {
let unit = |i: usize, n: usize| i as f32 / (n - 1) as f32;
let q = |v: f32| (v.clamp(0.0, 1.0) * 65535.0).round() as u16;
let mut a2b = Vec::with_capacity(A2B_GRID.pow(4) * 3);
for i in 0..A2B_GRID.pow(4) {
let cmyk = [3, 2, 1, 0].map(|d| unit(i / A2B_GRID.pow(d) % A2B_GRID, A2B_GRID));
let l = to_lab(cmyk);
a2b.extend([l.l / 100.0, (l.a + 128.0) / 255.0, (l.b + 128.0) / 255.0].map(q));
}
let mut b2a = Vec::with_capacity(B2A_GRID.pow(3) * 4);
for i in 0..B2A_GRID.pow(3) {
let [l, a, b] = [2, 1, 0].map(|d| unit(i / B2A_GRID.pow(d) % B2A_GRID, B2A_GRID));
b2a.extend(from_lab(lab::Lab::new(l * 100.0, a * 255.0 - 128.0, b * 255.0 - 128.0)).map(q));
}
let identity = |n: usize| vec![ToneReprCurve::Parametric(vec![1.0]); n];
let table = |inputs: usize, outputs: usize, grid: usize, clut: Vec<u16>| {
let mut grid_points = [0u8; 16];
grid_points[..inputs].fill(grid as u8);
LutWarehouse::Multidimensional(LutMultidimensionalType {
num_input_channels: inputs as u8,
num_output_channels: outputs as u8,
grid_points,
clut: Some(LutStore::Store16(clut)),
// A curves sit on the device side, B curves on the PCS side.
a_curves: identity(4),
b_curves: identity(3),
m_curves: vec![],
matrix: Matrix3d::IDENTITY,
bias: Vector3d::default(),
})
};
IccProfile::from_profile(Some(name.to_string()), p).ok()
let a2b = table(4, 3, A2B_GRID, a2b);
let b2a = table(3, 4, B2A_GRID, b2a);
let mut p = ColorProfile::default();
p.profile_class = ProfileClass::OutputDevice;
p.color_space = DataColorSpace::Cmyk;
p.pcs = DataColorSpace::Lab;
p.rendering_intent = RenderingIntent::RelativeColorimetric;
p.white_point = moxcms::WHITE_POINT_D50.to_xyzd();
p.media_white_point = Some(p.white_point);
p.lut_a_to_b_perceptual = Some(a2b.clone());
p.lut_a_to_b_colorimetric = Some(a2b);
p.lut_b_to_a_perceptual = Some(b2a.clone());
p.lut_b_to_a_colorimetric = Some(b2a);
labelled(p, name)
}
/// The grey space of greyscale exports: sRGB's tone curve, D50 white.
pub(super) fn gray_profile(name: &str) -> ColorProfile {
let mut p = ColorProfile::new_gray_with_gamma(2.2);
p.gray_trc = ColorProfile::new_srgb().red_trc;
labelled(p, name)
}
+50 -7
View File
@@ -33,6 +33,8 @@ pub const PROPHOTO_RGB: &str = "ProPhoto RGB";
pub const GENERIC_CMYK: &str = "VectorCraft Generic CMYK (SWOP-like)";
/// Profile-free CMYK (`rgb = (1−c)(1−k)` …): uncalibrated, kept for legacy numbers.
pub const DEVICE_CMYK: &str = "Device CMYK (uncalibrated)";
/// The grey space greyscale exports are written in: sRGB's tone curve (a grey shows as on screen).
pub const GRAY: &str = "Gray (sRGB tone curve)";
/// Built-in RGB and CMYK working spaces, in menu order.
const BUILTIN_RGB: [&str; 4] = [SRGB, WIDE_GAMUT_RGB, DISPLAY_P3, PROPHOTO_RGB];
@@ -140,6 +142,8 @@ pub enum Model {
Rgb,
Cmyk,
Gray,
/// CIE L*a*b* (D50).
Lab,
}
#[derive(Clone)]
@@ -250,6 +254,33 @@ pub fn register_icc(bytes: &[u8], name: Option<String>) -> Result<ProfileInfo, C
Ok(info)
}
/// Profile `name` as an ICC file to embed in an export: any RGB or CMYK profile of [`profiles`]
/// (by its current or legacy name), or [`GRAY`]. Built-in profiles are written in code from the
/// CMS: the RGB spaces from their primaries, the CMYK spaces as lookup tables sampled from their
/// model (both directions, perceptual and relative colorimetric, Lab PCS); a profile the user
/// loaded is the file it came from. Cached.
pub fn icc_bytes(name: &str) -> Result<Arc<[u8]>, CmsError> {
static CACHE: Mutex<Vec<(String, Arc<[u8]>)>> = Mutex::new(Vec::new());
let name = canonical_name(name);
if let Some(p) = user_profile(name) {
return p.bytes().map(Arc::from);
}
if let Some((_, b)) = CACHE.lock().unwrap_or_else(|e| e.into_inner()).iter().find(|(n, _)| n == name) {
return Ok(b.clone());
}
let bytes: Arc<[u8]> = if name == GRAY {
icc::encode(&icc::gray_profile(name))?
} else if BUILTIN_CMYK.contains(&name) {
let cms = Cms::new(&ColorSettings { cmyk: name.into(), ..ColorSettings::default() })?;
icc::encode(&icc::cmyk_profile(name, |c| cms.cmyk_to_lab(c), |l| cms.lab_to_cmyk(l, Intent::RelativeColorimetric)))?
} else {
icc::builtin_rgb_bytes(name)?
}
.into();
CACHE.lock().unwrap_or_else(|e| e.into_inner()).push((name.to_string(), bytes.clone()));
Ok(bytes)
}
/// Load a `.icc`/`.icm` file from disk (native only).
#[cfg(not(target_arch = "wasm32"))]
pub fn load_icc_file(path: &std::path::Path) -> Result<ProfileInfo, CmsError> {
@@ -354,6 +385,7 @@ impl Cms {
Color::Rgb { r, g, b } => self.rgb_to_srgb([r, g, b]),
Color::Cmyk { c, m, y, k } => self.cmyk_to_srgb([c, m, y, k], false),
Color::Gray { k } => [1.0 - k.clamp(0.0, 1.0); 3],
Color::Lab { l, a, b } => lab::lab_to_srgb(Lab::new(l, a, b)),
}
}
@@ -361,23 +393,33 @@ impl Cms {
pub fn lab(&self, c: &Color) -> Lab {
match *c {
Color::Cmyk { c, m, y, k } => self.cmyk_to_lab([c, m, y, k]),
Color::Lab { l, a, b } => Lab::new(l, a, b),
_ => lab::srgb_to_lab(self.display_rgb(c)),
}
}
/// Ink values of any colour in the working CMYK space (CMYK passes through; grey is K only).
/// Ink values of any colour in the working CMYK space (CMYK passes through; grey is K only;
/// Lab separates from its own values).
pub fn to_cmyk(&self, c: &Color, intent: Intent) -> [f32; 4] {
match *c {
Color::Cmyk { c, m, y, k } => [c, m, y, k],
Color::Gray { k } => [0.0, 0.0, 0.0, k],
Color::Rgb { .. } => self.srgb_to_cmyk(self.display_rgb(c), intent),
Color::Lab { l, a, b } => self.lab_to_cmyk(Lab::new(l, a, b), intent),
}
}
/// Convert `c` into `model` (a colour already in `model` is returned unchanged).
pub fn convert(&self, c: &Color, model: Model, intent: Intent) -> Color {
match (c, model) {
(Color::Rgb { .. }, Model::Rgb) | (Color::Cmyk { .. }, Model::Cmyk) | (Color::Gray { .. }, Model::Gray) => *c,
(Color::Rgb { .. }, Model::Rgb)
| (Color::Cmyk { .. }, Model::Cmyk)
| (Color::Gray { .. }, Model::Gray)
| (Color::Lab { .. }, Model::Lab) => *c,
(_, Model::Lab) => {
let Lab { l, a, b } = self.lab(c);
Color::Lab { l, a, b }
}
(_, Model::Cmyk) => {
let [c, m, y, k] = self.to_cmyk(c, intent);
Color::Cmyk { c, m, y, k }
@@ -404,19 +446,18 @@ impl Cms {
/// How far (ΔE2000) the best CMYK reproduction of `c` is from `c` (0 for CMYK/grey colours).
pub fn gamut_error(&self, c: &Color) -> f32 {
match c {
Color::Rgb { .. } => {
let srgb = self.display_rgb(c);
let src = lab::srgb_to_lab(srgb);
Color::Rgb { .. } | Color::Lab { .. } => {
let src = self.lab(c);
match &self.cmyk {
CmykSpace::Generic(g) => g.gamut_error(src),
CmykSpace::Device => 0.0,
CmykSpace::Icc(_) => {
let back = self.cmyk_to_srgb(self.srgb_to_cmyk(srgb, Intent::RelativeColorimetric), false);
let back = self.cmyk_to_srgb(self.to_cmyk(c, Intent::RelativeColorimetric), false);
delta_e2000(src, lab::srgb_to_lab(back))
}
}
}
_ => 0.0,
Color::Cmyk { .. } | Color::Gray { .. } => 0.0,
}
}
@@ -659,3 +700,5 @@ pub(crate) fn cmyk_is_device() -> bool {
#[cfg(test)]
mod tests;
#[cfg(test)]
mod tests_icc;
+26
View File
@@ -215,3 +215,29 @@ fn loads_system_cmyk_icc() {
assert!(de(rgb, back) < 5.0, "{back:?}");
assert_eq!(c.cmyk_to_srgb([0.0; 4], false).map(|v| (v * 255.0).round() as u8), [255, 255, 255]);
}
#[test]
fn lab_colours_round_trip_through_the_cms() {
let c = cms_no_bpc();
let ri = Intent::RelativeColorimetric;
// In-gamut Lab colours separate into working CMYK and come back within a small ΔE.
for (l, a, b) in [(60.0, 20.0, 30.0), (50.0, -20.0, -10.0), (75.0, 5.0, 40.0), (40.0, 30.0, -25.0)] {
let lab = Color::lab(l, a, b);
assert_eq!(c.lab(&lab), Lab::new(l, a, b), "Lab passes through");
assert_eq!(c.convert(&lab, Model::Lab, ri), lab, "already Lab: unchanged");
let ink = c.convert(&lab, Model::Cmyk, ri);
let Color::Cmyk { c: cc, m, y, k } = ink else { panic!("CMYK") };
assert_eq!([cc, m, y, k], c.to_cmyk(&lab, ri), "separation = conversion");
let back = c.lab(&ink);
assert!(delta_e2000(back, Lab::new(l, a, b)) < 1.5, "{l} {a} {b} → {ink:?} → {back:?}");
assert!(!c.out_of_gamut(&lab), "{l} {a} {b} is printable");
// Through RGB and back to Lab.
let rgb = c.convert(&lab, Model::Rgb, ri);
let Color::Lab { l: l2, a: a2, b: b2 } = c.convert(&rgb, Model::Lab, ri) else { panic!("Lab") };
assert!(delta_e76(Lab::new(l2, a2, b2), Lab::new(l, a, b)) < 0.05, "{l} {a} {b} → {rgb:?} → {l2} {a2} {b2}");
}
// A saturated Lab blue no press reaches is out of gamut; Lab grey converts to a neutral.
assert!(c.out_of_gamut(&Color::lab(30.0, 60.0, -100.0)));
let Color::Gray { k } = c.convert(&Color::lab(50.0, 0.0, 0.0), Model::Gray, ri) else { panic!("Gray") };
assert!((k - 0.53).abs() < 0.01, "{k}");
}
+62
View File
@@ -0,0 +1,62 @@
use super::*;
fn parse(bytes: &[u8]) -> moxcms::ColorProfile {
moxcms::ColorProfile::new_from_slice(bytes).unwrap()
}
#[test]
fn builtin_rgb_spaces_encode_under_their_names() {
for name in BUILTIN_RGB {
let p = IccProfile::from_bytes(None, &icc_bytes(name).unwrap()).unwrap();
assert_eq!((p.name.as_str(), p.kind), (name, ProfileKind::Rgb));
}
// Legacy names find today's profile.
assert_eq!(icc_bytes(LEGACY_NAMES[0].0).unwrap(), icc_bytes(WIDE_GAMUT_RGB).unwrap());
assert!(matches!(icc_bytes("No Such Profile"), Err(CmsError::UnknownProfile(_))));
}
#[test]
fn cmyk_profiles_convert_like_the_cms() {
for name in BUILTIN_CMYK {
let bytes = icc_bytes(name).unwrap();
assert_eq!(parse(&bytes).color_space, moxcms::DataColorSpace::Cmyk);
let p = IccProfile::from_bytes(None, &bytes).unwrap();
assert_eq!((p.name.as_str(), p.kind), (name, ProfileKind::Cmyk));
let cms = Cms::new(&ColorSettings { cmyk: name.into(), ..Default::default() }).unwrap();
for cmyk in [[0.0; 4], [1.0, 0.0, 0.0, 0.0], [0.2, 0.7, 0.1, 0.3], [0.0, 0.0, 0.0, 1.0], [0.5, 0.5, 0.5, 0.0]] {
let want = cms.cmyk_to_srgb(cmyk, false);
let got = p.to_srgb(&cmyk, Intent::RelativeColorimetric).unwrap();
let de = delta_e2000(lab::srgb_to_lab(want), lab::srgb_to_lab(got));
assert!(de < 2.5, "{name} {cmyk:?}: {want:?} vs {got:?} (ΔE {de})");
}
// And back: an in-gamut colour separates to about the same inks.
let srgb = cms.cmyk_to_srgb([0.1, 0.6, 0.8, 0.0], false);
let back = p.from_srgb(srgb, Intent::RelativeColorimetric).unwrap();
let again = cms.cmyk_to_srgb([back[0], back[1], back[2], back[3]], false);
assert!(delta_e2000(lab::srgb_to_lab(srgb), lab::srgb_to_lab(again)) < 3.0, "{back:?}");
}
}
#[test]
fn gray_is_srgb_toned() {
let p = IccProfile::from_bytes(None, &icc_bytes(GRAY).unwrap()).unwrap();
assert_eq!((p.name.as_str(), p.kind), (GRAY, ProfileKind::Gray));
for v in [0.0f32, 0.25, 0.5, 1.0] {
let got = p.to_srgb(&[v], Intent::RelativeColorimetric).unwrap();
assert!(got.iter().all(|c| (c - v).abs() < 0.01), "{v} → {got:?}");
}
}
#[test]
fn encoded_profiles_are_reproducible() {
assert_eq!(icc::builtin_rgb_bytes(DISPLAY_P3).unwrap(), icc::builtin_rgb_bytes(DISPLAY_P3).unwrap());
}
#[test]
fn a_loaded_profile_is_embedded_as_loaded() {
let mut bytes = icc::builtin_rgb_bytes(PROPHOTO_RGB).unwrap();
// A byte the parser ignores (in the reserved header area) marks the file as this one.
bytes[100] = 7;
register_icc(&bytes, Some("Embedded As Loaded RGB".into())).unwrap();
assert_eq!(&*icc_bytes("Embedded As Loaded RGB").unwrap(), &bytes[..]);
}
+43 -2
View File
@@ -87,6 +87,31 @@ pub fn spread_scale(b: Rect) -> f64 {
b.width().abs().max(b.height().abs()) / 2.0
}
/// The box a freeform gradient painted over `bounds` is placed on: `bounds` with positive sides, a
/// side without length getting a sliver (so a grid over it maps back invertibly). `None` for an
/// empty or non-finite box.
pub fn painted_box(bounds: Rect) -> Option<Rect> {
let b = bounds.abs();
let side = b.width().max(b.height());
(side > 1e-9 && side.is_finite()).then(|| Rect::from_center_size(b.center(), (b.width().max(side * 1e-3), b.height().max(side * 1e-3))))
}
/// Device pixels per cell of the grid a freeform gradient is sampled on.
const CELL_PX: f64 = 4.0;
/// Fewest and most cells along the painted box's longer side.
const MIN_CELLS: f64 = 8.0;
const MAX_CELLS: f64 = 256.0;
/// The grid (columns, rows) a freeform gradient on box `b` (see [`painted_box`]) is sampled on
/// when the box's longer side spans `device` pixels: a cell per few pixels, in power-of-two steps
/// (so zooming reuses grids), 8 to 256 cells along the longer side.
pub fn grid_size(b: Rect, device: f64) -> (u16, u16) {
let side = b.width().max(b.height());
let cells = 2f64.powf((device / CELL_PX).max(1.0).log2().ceil()).clamp(MIN_CELLS, MAX_CELLS);
let along = |len: f64| (cells * len / side).ceil().clamp(2.0, MAX_CELLS) as u16;
(along(b.width()), along(b.height()))
}
/// Where a point lies nearest on a line (see [`Freeform::nearest_on_lines`]).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct LineHit {
@@ -144,7 +169,7 @@ impl Freeform {
/// swatch chips, exports without freeform shading and re-seeding on other art use.
pub fn stops(&self) -> Vec<GradientStop> {
let n = self.points.len();
let stop = |offset: f32, p: &FreeformPoint| GradientStop { offset, color: p.color, opacity: p.opacity, midpoint: 0.5 };
let stop = |offset: f32, p: &FreeformPoint| GradientStop { opacity: p.opacity, ..GradientStop::new(offset, p.color) };
match n {
0 => Gradient::default().stops,
1 => vec![stop(0.0, &self.points[0]), stop(1.0, &self.points[0])],
@@ -214,7 +239,13 @@ impl Freeform {
/// The colour field, with colours converted and lines tessellated once (for sampling many
/// spots).
pub fn field(&self, scale: f64) -> Field {
let src = |p: &FreeformPoint| Source { at: p.at, rgb: p.color.to_rgb(), opacity: p.opacity, radius: p.spread.clamp(0.0, 1.0) as f64 * scale };
self.field_with(scale, &Color::to_rgb)
}
/// [`Self::field`] with colours turned into the three blended values by `rgb` (CMYK
/// documents blend ink planes, see [`crate::blend::cmyk_planes`]).
pub fn field_with(&self, scale: f64, rgb: &dyn Fn(&Color) -> [f32; 3]) -> Field {
let src = |p: &FreeformPoint| Source { at: p.at, rgb: rgb(&p.color), opacity: p.opacity, radius: p.spread.clamp(0.0, 1.0) as f64 * scale };
let points: Vec<Source> = self.points.iter().map(src).collect();
let mut pieces = vec![];
for (l, ix) in self.lines.iter().enumerate() {
@@ -365,6 +396,16 @@ impl Piece {
}
impl Field {
/// Samples at the centres of a `cols` × `rows` grid of cells over `b`, row by row: RGB and
/// opacity (as [`Self::sample`]).
pub fn grid(&self, b: Rect, cols: u16, rows: u16) -> impl Iterator<Item = ([f32; 3], f32)> + '_ {
let (cw, ch) = (b.width() / cols as f64, b.height() / rows as f64);
(0..rows as usize * cols as usize).map(move |k| {
let (i, j) = (k % cols as usize, k / cols as usize);
self.sample(Point::new(b.x0 + (i as f64 + 0.5) * cw, b.y0 + (j as f64 + 0.5) * ch))
})
}
/// Display RGB and opacity at `p`.
pub fn sample(&self, p: Point) -> ([f32; 3], f32) {
// (weight sum, weighted rgba) inside discs, and blending by distance outside them.
+227 -47
View File
@@ -31,7 +31,7 @@ impl GradientKind {
}
}
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct GradientStop {
/// 0..=1 along the gradient.
pub offset: f32,
@@ -41,6 +41,27 @@ pub struct GradientStop {
/// Midpoint to the next stop, 0.13..=0.87 (Illustrator's diamond), default 0.5.
#[serde(default = "half")]
pub midpoint: f32,
/// The global or spot swatch this stop's colour is linked to (edits to the swatch recolour it).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub swatch: Option<String>,
/// Tint of the linked swatch (0..1; 1 without a link), as on a solid paint.
#[serde(default = "crate::full_tint", skip_serializing_if = "crate::is_full_tint")]
pub tint: f32,
}
impl GradientStop {
/// An opaque, unlinked stop of `color` at `offset` with a centred midpoint.
pub fn new(offset: f32, color: Color) -> Self {
Self { offset, color, opacity: 1.0, midpoint: 0.5, swatch: None, tint: 1.0 }
}
/// Give the stop `color`, linked to `link` (a global swatch and tint) or unlinked.
pub fn set_color(&mut self, color: Color, link: Option<(String, f32)>) {
self.color = color;
(self.swatch, self.tint) = match link {
Some((n, t)) => (Some(n), t),
None => (None, 1.0),
};
}
}
fn one() -> f32 {
@@ -59,19 +80,18 @@ pub struct Gradient {
impl Default for Gradient {
/// Illustrator's default "White, Black" gradient.
fn default() -> Self {
Self {
kind: GradientKind::Linear,
stops: vec![
GradientStop { offset: 0.0, color: Color::WHITE, opacity: 1.0, midpoint: 0.5 },
GradientStop { offset: 1.0, color: Color::BLACK, opacity: 1.0, midpoint: 0.5 },
],
}
Self { kind: GradientKind::Linear, stops: vec![GradientStop::new(0.0, Color::WHITE), GradientStop::new(1.0, Color::BLACK)] }
}
}
impl Gradient {
/// Colour and opacity at `t` (honours midpoints).
pub fn sample(&self, t: f32) -> (Color, f32) {
self.sample_with(t, Color::lerp)
}
/// [`Gradient::sample`] with neighbouring stop colours mixed by `mix` (e.g. in their own colour
/// model rather than display RGB).
pub fn sample_with(&self, t: f32, mix: impl Fn(&Color, &Color, f32) -> Color) -> (Color, f32) {
let stops = &self.stops;
if stops.is_empty() {
return (Color::BLACK, 1.0);
@@ -87,26 +107,29 @@ impl Gradient {
// Map through the midpoint: u=mid → 0.5.
let m = a.midpoint.clamp(0.01, 0.99);
let v = if u < m { 0.5 * u / m } else { 0.5 + 0.5 * (u - m) / (1.0 - m) };
return (a.color.lerp(&b.color, v), a.opacity + (b.opacity - a.opacity) * v);
return (mix(&a.color, &b.color, v), a.opacity + (b.opacity - a.opacity) * v);
}
}
let l = stops.last().unwrap();
(l.color, l.opacity)
match stops.last() {
Some(l) => (l.color, l.opacity),
None => (Color::BLACK, 1.0),
}
}
/// Stops expanded so that midpoints are represented as explicit stops (for renderers without midpoints).
pub fn expanded_stops(&self) -> Vec<(f32, Color, f32)> {
let mut out = Vec::new();
for (i, s) in self.stops.iter().enumerate() {
out.push((s.offset, s.color, s.opacity));
if let Some(n) = self.stops.get(i + 1)
&& (s.midpoint - 0.5).abs() > 1e-3
{
self.expanded().map(|(t, c, o, _)| (t, c, o)).collect()
}
/// [`Self::expanded_stops`], each stop that stands for a midpoint with that midpoint (`None`
/// on the gradient's own stops).
pub fn expanded(&self) -> impl Iterator<Item = (f32, Color, f32, Option<f32>)> + '_ {
self.stops.iter().enumerate().flat_map(move |(i, s)| {
let mid = self.stops.get(i + 1).filter(|_| (s.midpoint - 0.5).abs() > 1e-3).map(|n| {
let t = s.offset + (n.offset - s.offset) * s.midpoint;
let (c, o) = self.sample(t);
out.push((t, c, o));
}
}
out
(t, c, o, Some(s.midpoint))
});
std::iter::once((s.offset, s.color, s.opacity, None)).chain(mid)
})
}
pub fn reverse(&mut self) {
self.stops.reverse();
@@ -117,6 +140,32 @@ impl Gradient {
pub fn sort(&mut self) {
self.stops.sort_by(|a, b| a.offset.total_cmp(&b.offset));
}
/// The part of the gradient from `from` to `to` (0..1, either way round) as a linear gradient
/// of its own running 0 → 1: the same colours (midpoints become stops, as in
/// [`Self::expanded_stops`]). One colour throughout when `from == to`.
pub fn span(&self, from: f32, to: f32) -> Gradient {
if to < from {
let mut g = self.span(to, from);
g.reverse();
return g;
}
let stop = |offset: f32, t: f32| {
let (color, opacity) = self.sample(t);
GradientStop { opacity, ..GradientStop::new(offset, color) }
};
let d = to - from;
let mut stops = vec![stop(0.0, from)];
if d > 1e-6 {
stops.extend(
self.expanded_stops()
.into_iter()
.filter(|(t, ..)| *t > from && *t < to)
.map(|(t, color, opacity)| GradientStop { opacity, ..GradientStop::new((t - from) / d, color) }),
);
}
stops.push(stop(1.0, to));
Gradient { kind: GradientKind::Linear, stops }
}
}
// ---------- stop editing (the Gradient panel, the annotator and agents share these) ----------
@@ -137,7 +186,7 @@ pub fn insert_stop(g: &Gradient, offset: f32) -> (Vec<GradientStop>, usize) {
let offset = offset.clamp(0.0, 1.0);
let (color, opacity) = g.sample(offset);
let mut stops = g.stops.clone();
let i = place_stop(&mut stops, GradientStop { offset, color, opacity, midpoint: 0.5 });
let i = place_stop(&mut stops, GradientStop { opacity, ..GradientStop::new(offset, color) });
(stops, i)
}
@@ -166,19 +215,22 @@ pub fn move_stop(stops: &[GradientStop], i: usize, offset: f32) -> (Vec<Gradient
/// Add a copy of stop `i` at `offset` (Alt-drag). Returns the stops and the copy's index.
pub fn duplicate_stop(stops: &[GradientStop], i: usize, offset: f32) -> (Vec<GradientStop>, usize) {
let mut v = stops.to_vec();
let Some(&s) = v.get(i) else { return (v, i) };
let Some(s) = v.get(i).cloned() else { return (v, i) };
let ni = place_stop(&mut v, GradientStop { offset: offset.clamp(0.0, 1.0), ..s });
(v, ni)
}
/// Swap the colours of stops `a` and `b` (Alt-dropping one stop on another); offsets, opacities
/// and midpoints stay. Out-of-range indices leave the stops unchanged.
/// Swap the colours of stops `a` and `b` (Alt-dropping one stop on another), with their swatch
/// links and tints; offsets, opacities and midpoints stay. Out-of-range indices leave the stops
/// unchanged.
pub fn swap_stop_colors(stops: &[GradientStop], a: usize, b: usize) -> Vec<GradientStop> {
let mut v = stops.to_vec();
if a < v.len() && b < v.len() {
let c = v[a].color;
v[a].color = v[b].color;
v[b].color = c;
if a < v.len() && b < v.len() && a != b {
let (lo, hi) = v.split_at_mut(a.max(b));
let (x, y) = (&mut lo[a.min(b)], &mut hi[0]);
std::mem::swap(&mut x.color, &mut y.color);
std::mem::swap(&mut x.swatch, &mut y.swatch);
std::mem::swap(&mut x.tint, &mut y.tint);
}
v
}
@@ -213,8 +265,15 @@ pub struct GradientGeom {
/// Radial aspect ratio (height / width), 1 = circle.
#[serde(default = "one64")]
pub aspect: f64,
/// A radial gradient's focal point, where its first stop sits (an off-centre radial), in the
/// same space; inside the extent ellipse. None: the centre (`start`).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub focal: Option<Point>,
}
/// How far out a focal point may sit, as a fraction of the extent ellipse.
const FOCAL_MAX: f64 = 0.99;
fn one64() -> f64 {
1.0
}
@@ -227,11 +286,11 @@ impl GradientGeom {
let a = angle_deg.to_radians();
let d = Vec2::new(a.cos(), -a.sin());
match kind {
GradientKind::Radial => Self { start: c, end: c + d * (b.width().max(b.height()) / 2.0), aspect: 1.0 },
GradientKind::Radial => Self { start: c, end: c + d * (b.width().max(b.height()) / 2.0), aspect: 1.0, focal: None },
_ => {
// Project the box corners onto the direction to cover the whole box.
let half = (b.width() * d.x.abs() + b.height() * d.y.abs()) / 2.0;
Self { start: c - d * half, end: c + d * half, aspect: 1.0 }
Self { start: c - d * half, end: c + d * half, aspect: 1.0, focal: None }
}
}
}
@@ -243,6 +302,8 @@ impl GradientGeom {
/// (the radius along the vector, `aspect` × the radius across it); its principal axes give the
/// new end (on the axis nearest the mapped vector) and aspect.
pub fn transform(&mut self, a: Affine, kind: GradientKind) {
// The focal point is a point like any other.
self.focal = self.focal.map(|f| a * f);
let [m0, m1, m2, m3, _, _] = a.as_coeffs();
let lin = |v: Vec2| Vec2::new(m0 * v.x + m2 * v.y, m1 * v.x + m3 * v.y);
let perp = |v: Vec2| Vec2::new(-v.y, v.x);
@@ -289,21 +350,76 @@ impl GradientGeom {
pub fn rebase(&mut self, from: Rect, to: Rect) {
self.start = rebase_point(self.start, from, to);
self.end = rebase_point(self.end, from, to);
self.focal = self.focal.map(|f| rebase_point(f, from, to));
}
/// The gradient parameter (0 at the start, 1 at the end) at document point `p`: the projection
/// onto the vector for linear gradients, the elliptical radius (honouring `aspect`) for radial.
/// onto the vector for linear gradients, the elliptical radius (honouring `aspect`) for radial,
/// measured from the focal point (each level is the ellipse scaled about the line from the
/// focal point to the centre).
pub fn param_at(&self, kind: GradientKind, p: Point) -> f64 {
let u = self.end - self.start;
let l2 = u.hypot2();
if l2 < 1e-18 {
if u.hypot2() < 1e-18 {
return 0.0;
}
let d = p - self.start;
let along = d.dot(u) / l2;
match kind {
GradientKind::Radial => along.hypot(d.cross(u) / (l2 * self.aspect.max(1e-9))),
_ => along,
if kind != GradientKind::Radial {
return (p - self.start).dot(u) / u.hypot2();
}
let Some(to_unit) = self.unit_frame().map(|m| m.inverse()) else { return 0.0 };
let q = (to_unit * p).to_vec2();
let Some(f) = self.focal.map(|f| (to_unit * f).to_vec2()) else { return q.hypot() };
// The level t through q: |q - f(1 - t)| = t, the root at t >= 0 (|f| < 1).
let d = q - f;
let a = f.hypot2() - 1.0;
if a.abs() < 1e-12 {
return q.hypot();
}
let b = d.dot(f);
(-b - (b * b - a * d.hypot2()).max(0.0).sqrt()) / a
}
/// The map from the unit circle onto a radial's extent ellipse: (1, 0) to the end, (0, 1) to
/// `aspect` × the radius across the vector. None when the ellipse is flat (no inverse).
pub fn unit_frame(&self) -> Option<Affine> {
let u = self.end - self.start;
(u.hypot2() * self.aspect.abs() > 1e-18).then(|| Affine::new([u.x, u.y, -u.y * self.aspect, u.x * self.aspect, self.start.x, self.start.y]))
}
/// The map that squashes a radial gradient's circle (centre `start`, radius the vector's
/// length) into its extent ellipse: by `aspect` across the vector, about the centre.
pub fn radial_squash(&self) -> Affine {
let angle = (self.end - self.start).atan2();
let c = self.start.to_vec2();
Affine::translate(c)
* Affine::rotate(angle)
* Affine::scale_non_uniform(1.0, self.aspect.max(1e-3))
* Affine::rotate(-angle)
* Affine::translate(-c)
}
/// Where a radial gradient's first stop sits: its focal point, else its centre.
pub fn focal_point(&self) -> Point {
self.focal.unwrap_or(self.start)
}
/// Set the focal point, pulled inside the extent ellipse; one on the centre (or a gradient
/// with no extent) has none.
pub fn set_focal(&mut self, f: Option<Point>) {
self.focal = f.and_then(|f| {
let m = self.unit_frame()?;
let q = (m.inverse() * f).to_vec2();
let r = q.hypot();
(r > 1e-6).then(|| if r > FOCAL_MAX { m * (q * (FOCAL_MAX / r)).to_point() } else { f })
});
}
/// After a change of the vector or aspect from `before`, put the focal point back where it
/// was relative to the extent ellipse.
pub fn keep_focal_from(&mut self, before: &GradientGeom) {
let rel = before.focal.zip(before.unit_frame()).map(|(f, m)| m.inverse() * f);
self.focal = None;
if let (Some(q), Some(m)) = (rel, self.unit_frame()) {
self.set_focal(Some(m * q));
}
}
pub fn angle_deg(&self) -> f64 {
@@ -458,7 +574,7 @@ mod tests {
}
fn linear(start: (f64, f64), end: (f64, f64)) -> GradientGeom {
GradientGeom { start: start.into(), end: end.into(), aspect: 1.0 }
GradientGeom { start: start.into(), end: end.into(), aspect: 1.0, focal: None }
}
#[test]
@@ -480,12 +596,12 @@ mod tests {
#[test]
fn non_uniform_scale_turns_a_circle_into_an_ellipse() {
let mut g = GradientGeom { start: Point::new(10.0, 10.0), end: Point::new(20.0, 10.0), aspect: 1.0 };
let mut g = GradientGeom { start: Point::new(10.0, 10.0), end: Point::new(20.0, 10.0), aspect: 1.0, focal: None };
g.transform(Affine::scale_non_uniform(2.0, 1.0), GradientKind::Radial);
assert!(close(g.start, Point::new(20.0, 10.0)) && close(g.end, Point::new(40.0, 10.0)), "{g:?}");
assert!((g.aspect - 0.5).abs() < 1e-9);
// A vertical vector keeps its axis: the ellipse is twice as wide as the vector is long.
let mut v = GradientGeom { start: Point::ZERO, end: Point::new(0.0, -10.0), aspect: 1.0 };
let mut v = GradientGeom { start: Point::ZERO, end: Point::new(0.0, -10.0), aspect: 1.0, focal: None };
v.transform(Affine::scale_non_uniform(2.0, 1.0), GradientKind::Radial);
assert!(close(v.end, Point::new(0.0, -10.0)) && (v.aspect - 2.0).abs() < 1e-9, "{v:?}");
}
@@ -494,7 +610,7 @@ mod tests {
fn samples_follow_shear_and_rotation() {
let shear = Affine::new([1.0, 0.3, 0.7, 1.2, 15.0, -4.0]) * Affine::rotate(0.4);
for kind in [GradientKind::Linear, GradientKind::Radial] {
let g = GradientGeom { start: Point::new(30.0, 40.0), end: Point::new(80.0, 55.0), aspect: 0.6 };
let g = GradientGeom { start: Point::new(30.0, 40.0), end: Point::new(80.0, 55.0), aspect: 0.6, focal: None };
let mut m = g;
m.transform(shear, kind);
for p in [Point::new(30.0, 40.0), Point::new(55.0, 70.0), Point::new(90.0, 10.0), Point::new(-20.0, 48.0)] {
@@ -509,7 +625,7 @@ mod tests {
let b = Rect::new(0.0, 0.0, 100.0, 60.0);
let g = GradientGeom::fit(GradientKind::Radial, b, 90.0);
assert!(close(g.start, Point::new(50.0, 30.0)) && close(g.end, Point::new(50.0, -20.0)), "end above the centre: {g:?}");
let e = GradientGeom { start: Point::ZERO, end: Point::new(10.0, 0.0), aspect: 0.5 };
let e = GradientGeom { start: Point::ZERO, end: Point::new(10.0, 0.0), aspect: 0.5, focal: None };
assert!((e.param_at(GradientKind::Radial, Point::new(0.0, 5.0)) - 1.0).abs() < 1e-12);
assert!((e.param_at(GradientKind::Radial, Point::new(5.0, 0.0)) - 0.5).abs() < 1e-12);
assert!((e.param_at(GradientKind::Linear, Point::new(5.0, 7.0)) - 0.5).abs() < 1e-12);
@@ -517,7 +633,7 @@ mod tests {
fn g3() -> Gradient {
let mut g = Gradient::default();
g.stops.insert(1, GradientStop { offset: 0.5, color: Color::rgb(1.0, 0.0, 0.0), opacity: 1.0, midpoint: 0.5 });
g.stops.insert(1, GradientStop::new(0.5, Color::rgb(1.0, 0.0, 0.0)));
g
}
@@ -588,11 +704,11 @@ mod tests {
#[test]
fn rebase_keeps_relative_positions() {
let mut g = GradientGeom { start: Point::new(110.0, 150.0), end: Point::new(190.0, 120.0), aspect: 0.5 };
let mut g = GradientGeom { start: Point::new(110.0, 150.0), end: Point::new(190.0, 120.0), aspect: 0.5, focal: None };
g.rebase(Rect::new(100.0, 100.0, 200.0, 200.0), Rect::new(500.0, 0.0, 700.0, 50.0));
assert!(close(g.start, Point::new(520.0, 25.0)) && close(g.end, Point::new(680.0, 10.0)) && g.aspect == 0.5, "{g:?}");
// A box without height (a horizontal line) keeps the offset from its centre line.
let mut h = GradientGeom { start: Point::new(0.0, 12.0), end: Point::new(10.0, 10.0), aspect: 1.0 };
let mut h = GradientGeom { start: Point::new(0.0, 12.0), end: Point::new(10.0, 10.0), aspect: 1.0, focal: None };
h.rebase(Rect::new(0.0, 10.0, 10.0, 10.0), Rect::new(0.0, 0.0, 20.0, 40.0));
assert!(close(h.start, Point::new(0.0, 22.0)) && close(h.end, Point::new(20.0, 20.0)), "{h:?}");
// Unplaced paints have nothing to move.
@@ -611,4 +727,68 @@ mod tests {
p.pin(Rect::new(0.0, 0.0, 1.0, 1.0));
assert_eq!(p.geom, Some(GradientGeom::fit(GradientKind::Linear, b, 90.0)));
}
/// A 100 pt circle at (200, 200) with its focal point 40 pt left of the centre.
fn off_centre() -> GradientGeom {
let mut g = GradientGeom { start: Point::new(200.0, 200.0), end: Point::new(300.0, 200.0), aspect: 1.0, focal: None };
g.set_focal(Some(Point::new(160.0, 200.0)));
g
}
#[test]
fn focal_round_trips_through_serde_and_defaults_to_none() {
let g = off_centre();
let s = serde_json::to_string(&g).unwrap();
assert!(s.contains("\"focal\""), "{s}");
assert_eq!(serde_json::from_str::<GradientGeom>(&s).unwrap(), g);
// Placements saved before focal points existed load centred, and centred ones write none.
let old: GradientGeom = serde_json::from_str(r#"{"start":{"x":0.0,"y":0.0},"end":{"x":1.0,"y":0.0}}"#).unwrap();
assert_eq!((old.focal, old.aspect), (None, 1.0));
assert!(!serde_json::to_string(&old).unwrap().contains("focal"));
}
#[test]
fn focal_follows_transforms_and_rebases() {
let mut g = off_centre();
let a = Affine::translate((10.0, -5.0)) * Affine::rotate(0.7) * Affine::scale_non_uniform(2.0, 0.5);
let f = a * g.focal.unwrap();
g.transform(a, GradientKind::Radial);
assert!(close(g.focal.unwrap(), f), "{g:?}");
// Still at the same parameter: the first stop.
assert!(g.param_at(GradientKind::Radial, f).abs() < 1e-9);
let mut h = off_centre();
h.rebase(Rect::new(100.0, 100.0, 300.0, 300.0), Rect::new(0.0, 0.0, 100.0, 100.0));
assert!(close(h.focal.unwrap(), Point::new(30.0, 50.0)) && close(h.start, Point::new(50.0, 50.0)), "{h:?}");
}
#[test]
fn param_runs_from_the_focal_point_to_the_ellipse() {
let g = off_centre();
let t = |x: f64, y: f64| g.param_at(GradientKind::Radial, Point::new(x, y));
assert!(t(160.0, 200.0).abs() < 1e-9);
// The extent circle is the last stop all round.
for a in [0.0f64, 1.0, 2.5, 4.0] {
let p = Point::new(200.0 + 100.0 * a.cos(), 200.0 + 100.0 * a.sin());
assert!((g.param_at(GradientKind::Radial, p) - 1.0).abs() < 1e-9, "{a}");
}
// The centre lies on the level-2/7 circle: centred 2/7 of the way back to the focal point
// (0.4 of the radius off), with a radius of 2/7.
assert!((t(200.0, 200.0) - 2.0 / 7.0).abs() < 1e-9, "{}", t(200.0, 200.0));
assert!(t(180.0, 200.0) < t(220.0, 200.0), "nearer the focal side is earlier");
assert_eq!(GradientGeom { focal: None, ..g }.param_at(GradientKind::Radial, Point::new(250.0, 200.0)), 0.5);
}
#[test]
fn focal_is_kept_inside_the_ellipse_and_follows_its_reshaping() {
let mut g = off_centre();
g.set_focal(Some(Point::new(500.0, 200.0)));
assert!(close(g.focal.unwrap(), Point::new(299.0, 200.0)), "pulled inside: {g:?}");
g.set_focal(Some(Point::new(200.0, 200.0)));
assert_eq!(g.focal, None, "on the centre: centred");
// A new vector and aspect keep it in its place in the ellipse.
let before = off_centre();
let mut h = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(0.0, 50.0), aspect: 0.5, focal: None };
h.keep_focal_from(&before);
assert!(close(h.focal.unwrap(), Point::new(0.0, -20.0)), "{h:?}");
}
}
+124 -2
View File
@@ -1,7 +1,9 @@
//! Colour harmony rules and the variation grid of the Color Guide panel (our own colour math).
//! Colour harmony rules, the variation grid of the Color Guide panel and the five-colour themes of
//! the Color Themes panel (our own colour math).
use serde::{Deserialize, Serialize};
use crate::recolor::Palette;
use crate::{Color, keep_model};
/// A harmony rule: a group of colours built from a base colour, base first.
@@ -185,6 +187,47 @@ impl Harmony {
}))
.collect()
}
/// A [`THEME_SIZE`]-colour theme from `base`: the rule's colours, each followed by the lighter or
/// darker variations of it that fill the remaining places (the rule's first colours get them
/// first). The base colour comes first, every colour in its model.
pub fn theme(self, base: Color) -> Vec<Color> {
let colors = self.apply(base);
let n = colors.len();
let mut rows: Vec<Vec<Color>> = colors.iter().map(|c| vec![*c]).collect();
let opts = GuideOptions::default();
for k in 0..THEME_SIZE.saturating_sub(n) {
let (i, pass) = (k % n, k / n);
// Alternate lighter and darker along the rule and from one pass to the next.
let step = if (i + pass) % 2 == 0 { 3 } else { -3 };
rows[i].push(variation(colors[i], &opts, step));
}
rows.into_iter().flatten().take(THEME_SIZE).collect()
}
}
/// The number of colours in a colour theme.
pub const THEME_SIZE: usize = 5;
/// Move colour `i` of a harmony on the hue and saturation wheel to `hsb` (hue in degrees,
/// saturation and brightness 0..1), keeping its model. With `linked` the other colours keep their
/// relation to it: they turn by the same hue, scale their saturation alike and shift their
/// brightness by as much.
pub fn move_on_wheel(colors: &mut [Color], i: usize, hsb: [f32; 3], linked: bool) {
let Some(&old) = colors.get(i) else { return };
let [h0, s0, v0] = old.to_hsb();
let (dh, ratio, dv) = (hsb[0] - h0, if s0 > 0.01 { hsb[1] / s0 } else { 1.0 }, hsb[2] - v0);
for (j, c) in colors.iter_mut().enumerate() {
let new = if j == i {
hsb
} else if linked {
let [h, s, v] = c.to_hsb();
[h + dh, (s * ratio).clamp(0.0, 1.0), (v + dv).clamp(0.0, 1.0)]
} else {
continue;
};
*c = keep_model(*c, Color::from_hsb(new[0], new[1], new[2]));
}
}
/// What the variation grid varies: towards black and white, towards cool and warm, or towards
@@ -293,6 +336,23 @@ impl Guide {
pub fn centre(&self) -> usize {
self.grid.first().map_or(0, |r| r.len() / 2)
}
/// The guide limited to `palette` (Limit to Library): every harmony colour and variation snaps
/// to the palette's nearest colour (CIEDE2000), in that colour's own model.
pub fn limited(mut self, palette: &Palette) -> Self {
if palette.is_empty() {
return self;
}
let centre = self.centre();
for (row, c) in self.grid.iter_mut().zip(&mut self.colors) {
for v in row.iter_mut() {
*v = palette.nearest(*v);
}
// The centre column is the harmony colour itself.
*c = row[centre];
}
self
}
}
#[cfg(test)]
@@ -326,7 +386,7 @@ mod tests {
for h in Harmony::ALL {
assert!(h.apply(base).iter().all(|c| matches!(c, Color::Cmyk { .. })), "{}", h.label());
}
let Color::Cmyk { c, m, y, .. } = Harmony::Complementary.apply(base)[1] else { unreachable!() };
let Color::Cmyk { c, m, y, .. } = Harmony::Complementary.apply(base)[1] else { panic!("a CMYK complement") };
assert!(c > m && c > y, "the complement of red is a cyan: {c} {m} {y}");
let g = Guide::new(Color::gray(0.4), Harmony::Triad, &GuideOptions::default());
assert!(g.grid.iter().flatten().all(|c| matches!(c, Color::Gray { .. })));
@@ -382,4 +442,66 @@ mod tests {
let g = Guide::new(base, Harmony::Triad, &GuideOptions { steps: 99, ..Default::default() });
assert_eq!(g.grid[0].len(), 41);
}
#[test]
fn a_limited_guide_only_holds_palette_colours() {
let lib =
[Color::rgb(1.0, 0.0, 0.0), Color::cmyk(1.0, 0.0, 0.0, 0.0), Color::gray(0.5), Color::rgb8(250, 240, 200), Color::lab(30.0, 10.0, -40.0)];
let palette = Palette::new(lib);
for rule in Harmony::ALL {
let g = Guide::new(Color::rgb8(200, 60, 40), rule, &GuideOptions::default()).limited(&palette);
assert!(g.grid.iter().flatten().chain(&g.colors).all(|c| lib.contains(c)), "{}", rule.label());
for (row, c) in g.grid.iter().zip(&g.colors) {
assert_eq!(row[g.centre()], *c, "{}: the harmony colour stays in the centre", rule.label());
}
}
// The nearest colour wins: a pale yellow snaps to the cream and its darkest shade to the grey.
let g = Guide::new(Color::rgb(0.95, 0.9, 0.75), Harmony::Complementary, &GuideOptions::default()).limited(&palette);
assert_eq!(g.colors[0], lib[3]);
assert_eq!(g.grid[0][0], lib[2]);
// An empty palette limits nothing.
let free = Guide::new(Color::rgb(0.8, 0.1, 0.1), Harmony::Triad, &GuideOptions::default());
assert_eq!(free.clone().limited(&Palette::default()), free);
}
#[test]
fn themes_have_five_colours_base_first() {
for base in [Color::rgb8(230, 120, 40), Color::cmyk(0.1, 0.8, 0.3, 0.05)] {
for rule in Harmony::ALL {
let t = rule.theme(base);
assert_eq!(t.len(), THEME_SIZE, "{}", rule.label());
assert_eq!(t[0], base, "{}", rule.label());
assert!(t.iter().all(|c| c.model() == base.model()), "{}: colours keep the base model", rule.label());
}
}
// A two-colour rule fills in variations next to the colour they vary.
let red = Color::rgb(1.0, 0.0, 0.0);
let t = Harmony::Complementary.theme(red);
assert_eq!(t[3].to_hex(), "#00ffff", "the complement follows the base's variations");
let l = |c: &Color| c.to_lab().l;
assert!(l(&t[1]) > l(&t[0]) && l(&t[2]) < l(&t[0]), "the base, a lighter and a darker red");
assert!(l(&t[4]) < l(&t[3]));
for (i, a) in t.iter().enumerate() {
assert!(t[i + 1..].iter().all(|b| b.to_hex() != a.to_hex()), "{} repeats", a.to_hex());
}
// Five-colour rules are themes as they are.
assert_eq!(Harmony::Pentagram.theme(red), Harmony::Pentagram.apply(red));
}
#[test]
fn moving_a_linked_colour_moves_the_others_alike() {
let mut c = [Color::rgb(1.0, 0.0, 0.0), Color::rgb(1.0, 1.0, 0.0), Color::cmyk(0.0, 1.0, 0.0, 0.0)];
move_on_wheel(&mut c, 0, [120.0, 1.0, 1.0], false);
assert_eq!(c[0].to_hex(), "#00ff00");
assert_eq!(c[1].to_hex(), "#ffff00", "unlinked: only that colour moves");
move_on_wheel(&mut c, 0, [240.0, 0.5, 1.0], true);
assert_eq!(c[0].to_hex(), "#8080ff");
let [h, s, v] = c[1].to_hsb();
assert!((h - 180.0).abs() < 0.5 && (s - 0.5).abs() < 0.01 && v > 0.99, "it turned and paled as much: {h} {s} {v}");
assert!(matches!(c[2], Color::Cmyk { .. }), "colours keep their model");
// An index past the end moves nothing.
let before = c;
move_on_wheel(&mut c, 5, [0.0, 0.0, 0.0], true);
assert_eq!(c, before);
}
}
+174 -12
View File
@@ -1,7 +1,7 @@
//! Colour, paint and blend-mode types for VectorCraft.
//!
//! Colours keep the model the user picked them in (RGB, CMYK, Gray, HSB is a UI view of RGB), so
//! documents don't drift when converting back and forth. Rendering asks for [`Color::to_rgba`].
//! Colours keep the model the user picked them in (RGB, CMYK, Gray, Lab; HSB is a UI view of RGB),
//! so documents don't drift when converting back and forth. Rendering asks for [`Color::to_rgba`].
#![forbid(unsafe_code)]
pub mod blend;
@@ -11,6 +11,7 @@ pub mod gradient;
pub mod harmony;
pub mod libraries;
pub mod palette_io;
pub mod recolor;
pub mod swatch;
pub use blend::BlendMode;
@@ -21,13 +22,31 @@ pub use swatch::{Swatch, SwatchGroup, default_swatches};
use serde::{Deserialize, Serialize};
/// A colour in its authoring model. Components are 0..=1.
/// A colour in its authoring model. Components are 0..=1, except Lab's.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "model", rename_all = "lowercase")]
pub enum Color {
Rgb { r: f32, g: f32, b: f32 },
Cmyk { c: f32, m: f32, y: f32, k: f32 },
Gray { k: f32 },
Rgb {
r: f32,
g: f32,
b: f32,
},
Cmyk {
c: f32,
m: f32,
y: f32,
k: f32,
},
Gray {
k: f32,
},
/// CIE L*a*b* (D50): L 0..100, a and b about −128..127. Device independent, the way spot
/// colours are defined; it shows and separates through the active colour settings.
Lab {
l: f32,
a: f32,
b: f32,
},
}
impl Default for Color {
@@ -52,6 +71,9 @@ impl Color {
pub fn gray(k: f32) -> Self {
Color::Gray { k }
}
pub fn lab(l: f32, a: f32, b: f32) -> Self {
Color::Lab { l, a, b }
}
/// Display (sRGB) colour through the active colour settings ([`cms::active`]): RGB is
/// converted from the working RGB space, CMYK through the working CMYK profile (relative
@@ -62,15 +84,18 @@ impl Color {
Color::Cmyk { c, m, y, k } if cms::cmyk_is_device() => cms::naive_cmyk_to_rgb([c, m, y, k]),
// Illustrator's Gray is ink percentage: 0 = white, 1 = black.
Color::Gray { k } => [1.0 - k; 3],
Color::Lab { l, a, b } => cms::lab::lab_to_srgb(cms::Lab::new(l, a, b)),
_ => cms::active().display_rgb(self),
}
}
/// Profile-free display RGB (`(1−c)(1−k)` …), the pre-colour-management formula.
/// Profile-free display RGB (`(1−c)(1−k)` …), the pre-colour-management formula (Lab, being
/// device independent, is its sRGB colour).
pub fn to_rgb_uncalibrated(&self) -> [f32; 3] {
match *self {
Color::Rgb { r, g, b } => [r, g, b],
Color::Cmyk { c, m, y, k } => cms::naive_cmyk_to_rgb([c, m, y, k]),
Color::Gray { k } => [1.0 - k; 3],
Color::Lab { l, a, b } => cms::lab::lab_to_srgb(cms::Lab::new(l, a, b)),
}
}
/// CIE Lab (D50) through the active colour settings.
@@ -182,11 +207,12 @@ impl Color {
Color::Cmyk { c, m, y, k }
}
Color::Gray { k } => Color::Gray { k: 1.0 - k },
Color::Lab { .. } => self.invert().in_model(cms::Model::Lab),
}
}
/// Complement in the colour's own model: each component becomes (highest + lowest) − itself,
/// over R, G, B or over C, M, Y (K kept). For RGB this is the hue turned by 180°; a grey is its
/// own complement.
/// own complement; Lab turns its hue by 180° (a and b negated).
pub fn complement_keep_model(&self) -> Self {
let flip = |v: [f32; 3]| {
let s = v[0].max(v[1]).max(v[2]) + v[0].min(v[1]).min(v[2]);
@@ -202,6 +228,7 @@ impl Color {
Color::Cmyk { c, m, y, k }
}
Color::Gray { .. } => *self,
Color::Lab { l, a, b } => Color::Lab { l, a: -a, b: -b },
}
}
/// Linear interpolation in display RGB.
@@ -216,11 +243,12 @@ impl Color {
Color::Rgb { .. } => cms::Model::Rgb,
Color::Cmyk { .. } => cms::Model::Cmyk,
Color::Gray { .. } => cms::Model::Gray,
Color::Lab { .. } => cms::Model::Lab,
}
}
/// This colour expressed in `model` with the profile-free formulas Edit Colors uses (RGB from
/// the display colour, CMYK by [`Color::to_cmyk`], Gray as ink from luminance); unchanged when it
/// is in `model` already.
/// the display colour, CMYK by [`Color::to_cmyk`], Gray as ink from luminance, Lab by
/// [`Color::to_lab`]); unchanged when it is in `model` already.
pub fn in_model(self, model: cms::Model) -> Color {
if self.model() == model {
return self;
@@ -238,6 +266,28 @@ impl Color {
let [r, g, b] = self.to_rgb();
Color::gray((1.0 - (0.299 * r + 0.587 * g + 0.114 * b)).clamp(0.0, 1.0))
}
cms::Model::Lab => {
let cms::Lab { l, a, b } = self.to_lab();
Color::Lab { l, a, b }
}
}
}
/// Tint `t` (0..1) of this colour, the colour a tint of a global or spot swatch shows: CMYK and
/// Gray inks scale by `t`, RGB and Lab mix toward white (`t` = 0 is paper white, 1 the colour
/// itself; Lab toward L 100, a = b = 0, as a PDF Lab alternate interpolates).
pub fn tinted(self, t: f32) -> Color {
let t = t.clamp(0.0, 1.0);
if t == 1.0 {
return self;
}
match self {
Color::Cmyk { c, m, y, k } => Color::Cmyk { c: c * t, m: m * t, y: y * t, k: k * t },
Color::Gray { k } => Color::Gray { k: k * t },
Color::Rgb { r, g, b } => {
let w = |v: f32| v + (1.0 - v) * (1.0 - t);
Color::Rgb { r: w(r), g: w(g), b: w(b) }
}
Color::Lab { l, a, b } => Color::Lab { l: 100.0 - (100.0 - l) * t, a: a * t, b: b * t },
}
}
pub fn model_name(&self) -> &'static str {
@@ -245,6 +295,7 @@ impl Color {
Color::Rgb { .. } => "RGB",
Color::Cmyk { .. } => "CMYK",
Color::Gray { .. } => "Grayscale",
Color::Lab { .. } => "Lab",
}
}
}
@@ -262,10 +313,15 @@ pub enum Paint {
#[default]
None,
Solid {
/// The colour shown: with a link, the swatch's colour at `tint` ([`Color::tinted`]).
color: Color,
/// Name of the global swatch this colour is linked to (edits to the swatch update it).
#[serde(default, skip_serializing_if = "Option::is_none")]
swatch: Option<String>,
/// Tint of the linked swatch (0..1; 1 without a link): a spot tint prints this much of its
/// plate, and swatch edits keep it.
#[serde(default = "full_tint", skip_serializing_if = "is_full_tint")]
tint: f32,
},
Gradient(Box<GradientPaint>),
Pattern {
@@ -281,9 +337,22 @@ fn is_identity(a: &kurbo::Affine) -> bool {
*a == kurbo::Affine::IDENTITY
}
pub(crate) fn full_tint() -> f32 {
1.0
}
pub(crate) fn is_full_tint(t: &f32) -> bool {
*t == 1.0
}
/// A tint as a whole percentage ("40" for 0.4).
pub fn tint_percent(t: f32) -> f32 {
(t.clamp(0.0, 1.0) * 100.0).round()
}
impl Paint {
pub fn solid(c: Color) -> Self {
Paint::Solid { color: c, swatch: None }
Paint::Solid { color: c, swatch: None, tint: 1.0 }
}
pub fn is_none(&self) -> bool {
matches!(self, Paint::None)
@@ -294,15 +363,41 @@ impl Paint {
_ => None,
}
}
/// The Registration colour: 100% of every ink, linked to [`swatch::REGISTRATION`].
pub fn registration() -> Self {
Paint::Solid { color: Color::cmyk(1.0, 1.0, 1.0, 1.0), swatch: Some(swatch::REGISTRATION.into()), tint: 1.0 }
}
/// Is this a colour linked to the Registration swatch (it prints on every plate)?
pub fn is_registration(&self) -> bool {
matches!(self, Paint::Solid { swatch: Some(s), .. } if s == swatch::REGISTRATION)
}
pub fn label(&self) -> String {
match self {
Paint::None => "None".into(),
Paint::Solid { color, swatch: Some(n) } => format!("{n} ({})", color.to_hex()),
Paint::Solid { color, swatch: Some(n), tint } if *tint < 1.0 => format!("{n} {}% ({})", tint_percent(*tint), color.to_hex()),
Paint::Solid { color, swatch: Some(n), .. } => format!("{n} ({})", color.to_hex()),
Paint::Solid { color, .. } => color.to_hex(),
Paint::Gradient(g) => format!("{} gradient", g.gradient.kind.label()),
Paint::Pattern { pattern, .. } => format!("pattern {pattern}"),
}
}
/// Apply `f` to the colours of this paint that can link to a swatch (a solid colour, each
/// gradient stop) with their link and tint; `f` returns true when it changed them. A colour
/// left without a link gets tint 1. Returns whether anything changed.
pub fn map_links(&mut self, f: &mut dyn FnMut(&mut Color, &mut Option<String>, &mut f32) -> bool) -> bool {
let mut one = |c: &mut Color, link: &mut Option<String>, tint: &mut f32| {
let changed = f(c, link, tint);
if link.is_none() {
*tint = 1.0;
}
changed
};
match self {
Paint::Solid { color, swatch, tint } => one(color, swatch, tint),
Paint::Gradient(g) => g.gradient.stops.iter_mut().fold(false, |ch, s| one(&mut s.color, &mut s.swatch, &mut s.tint) | ch),
_ => false,
}
}
}
#[cfg(test)]
@@ -376,6 +471,73 @@ mod tests {
assert_eq!(keep_model(red, Color::rgb(0.0, 0.5, 1.0)), Color::rgb(0.0, 0.5, 1.0));
}
#[test]
fn tints_scale_inks_and_mix_rgb_toward_white() {
let close = |a: Color, b: Color| {
let v = |c: Color| match c {
Color::Cmyk { c, m, y, k } => vec![c, m, y, k],
Color::Rgb { r, g, b } => vec![r, g, b],
Color::Gray { k } => vec![k],
Color::Lab { l, a, b } => vec![l, a, b],
};
a.model() == b.model() && v(a).iter().zip(v(b)).all(|(x, y)| (x - y).abs() < 1e-6)
};
assert!(close(Color::cmyk(0.5, 1.0, 0.0, 0.2).tinted(0.4), Color::cmyk(0.2, 0.4, 0.0, 0.08)));
assert!(close(Color::gray(0.5).tinted(0.5), Color::gray(0.25)));
assert!(close(Color::rgb(1.0, 0.0, 0.5).tinted(0.4), Color::rgb(1.0, 0.6, 0.8)), "RGB mixes toward white");
assert!(close(Color::lab(40.0, 60.0, -20.0).tinted(0.25), Color::lab(85.0, 15.0, -5.0)), "Lab mixes toward paper white");
assert_eq!(Color::rgb(0.2, 0.4, 0.6).tinted(1.0), Color::rgb(0.2, 0.4, 0.6));
assert_eq!(Color::cmyk(0.3, 0.3, 0.3, 0.3).tinted(0.0), Color::cmyk(0.0, 0.0, 0.0, 0.0));
assert_eq!(Color::rgb(0.0, 0.0, 0.0).tinted(-1.0).to_hex(), "#ffffff", "clamped");
assert_eq!(tint_percent(0.404), 40.0);
}
#[test]
fn tints_serialize_only_below_full_and_read_old_files() {
let full = serde_json::to_string(&Paint::Solid { color: Color::gray(1.0), swatch: Some("Ink".into()), tint: 1.0 }).unwrap();
assert!(!full.contains("tint"), "{full}");
let old: Paint = serde_json::from_str(r#"{"type":"solid","color":{"model":"gray","k":1.0},"swatch":"Ink"}"#).unwrap();
assert_eq!(old, Paint::Solid { color: Color::gray(1.0), swatch: Some("Ink".into()), tint: 1.0 });
let t = Paint::Solid { color: Color::gray(0.4), swatch: Some("Ink".into()), tint: 0.4 };
let s = serde_json::to_string(&t).unwrap();
assert!(s.contains("\"tint\":0.4"), "{s}");
assert_eq!(serde_json::from_str::<Paint>(&s).unwrap(), t);
assert_eq!(t.label(), "Ink 40% (#999999)");
}
#[test]
fn mapping_links_resets_the_tint_of_unlinked_colours() {
let mut p = Paint::Solid { color: Color::gray(0.4), swatch: Some("Ink".into()), tint: 0.4 };
assert!(p.map_links(&mut |_, l, _| l.take().is_some()));
assert_eq!(p, Paint::solid(Color::gray(0.4)));
let mut g = Paint::Gradient(Box::new(GradientPaint::new(Gradient::default())));
g.map_links(&mut |_, l, t| {
*l = Some("Ink".into());
*t = 0.5;
true
});
let Paint::Gradient(g) = g else { panic!("a gradient") };
assert!(g.gradient.stops.iter().all(|s| s.swatch.as_deref() == Some("Ink") && s.tint == 0.5));
}
#[test]
fn lab_colours_serialize_with_their_tag_and_keep_their_model() {
let c = Color::lab(52.5, 70.0, -30.0);
let s = serde_json::to_string(&c).unwrap();
assert_eq!(s, r#"{"model":"lab","l":52.5,"a":70.0,"b":-30.0}"#);
assert_eq!(serde_json::from_str::<Color>(&s).unwrap(), c);
assert_eq!((c.model(), c.model_name()), (cms::Model::Lab, "Lab"));
assert_eq!(c.complement_keep_model(), Color::lab(52.5, -70.0, 30.0));
assert_eq!(c.invert_keep_model().model(), cms::Model::Lab);
// Results of colour operations on a Lab colour stay Lab, and the conversion is exact.
let red = Color::rgb(1.0, 0.0, 0.0);
let Color::Lab { l, a, b } = keep_model(c, red) else { panic!("Lab") };
assert!((l - 54.29).abs() < 0.1 && (a - 80.8).abs() < 0.3 && (b - 69.9).abs() < 0.3, "{l} {a} {b}");
assert_eq!(keep_model(c, red).to_hex(), "#ff0000");
assert_eq!(Color::lab(100.0, 0.0, 0.0).to_hex(), "#ffffff");
assert_eq!(Color::lab(0.0, 0.0, 0.0).to_rgb_uncalibrated(), [0.0; 3]);
}
#[test]
fn paint_serde() {
let p = Paint::solid(Color::rgb8(10, 20, 30));
+3 -1
View File
@@ -170,7 +170,7 @@ fn group(name: &str, swatches: Vec<Swatch>) -> SwatchGroup {
/// A gradient swatch through `stops` of (offset, colour, opacity).
pub(crate) fn gradient(name: &str, kind: GradientKind, stops: &[(f32, Color, f32)]) -> Swatch {
let stops = stops.iter().map(|&(offset, color, opacity)| GradientStop { offset, color, opacity, midpoint: 0.5 }).collect();
let stops = stops.iter().map(|&(offset, color, opacity)| GradientStop { opacity, ..GradientStop::new(offset, color) }).collect();
Swatch { name: name.into(), paint: Paint::Gradient(Box::new(GradientPaint::new(Gradient { kind, stops }))), global: false, spot: false }
}
@@ -452,6 +452,8 @@ mod tests {
Color::Rgb { r, g, b } => vec![r, g, b],
Color::Cmyk { c, m, y, k } => vec![c, m, y, k],
Color::Gray { k } => vec![k],
// Normalized to 0..1 like the others.
Color::Lab { l, a, b } => vec![l / 100.0, (a + 128.0) / 255.0, (b + 128.0) / 255.0],
};
lib.iter()
.flat_map(|s| match &s.paint {
+2 -2
View File
@@ -241,8 +241,8 @@ mod tests {
let grad = Paint::Gradient(Box::new(GradientPaint::new(Gradient {
kind: GradientKind::Linear,
stops: vec![
GradientStop { offset: 0.0, color: Color::cmyk(0.1, 0.2, 0.3, 0.0), opacity: 1.0, midpoint: 0.4 },
GradientStop { offset: 1.0, color: Color::rgb8(255, 0, 0), opacity: 0.5, midpoint: 0.5 },
GradientStop { midpoint: 0.4, ..GradientStop::new(0.0, Color::cmyk(0.1, 0.2, 0.3, 0.0)) },
GradientStop { opacity: 0.5, ..GradientStop::new(1.0, Color::rgb8(255, 0, 0)) },
],
})));
SwatchLibrary {
+586
View File
@@ -0,0 +1,586 @@
//! Recolor Artwork's colour math (our own): colour identity keys, the White/Black/Grays preserve
//! rules, the methods that map a row of current colours to its new colour, colour reduction by
//! clustering in Lab, the nearest colour of a library and the randomizers.
use std::fmt;
use crate::cms::{Lab, delta_e2000};
use crate::{Color, keep_model};
/// A colour's identity: its model and exact components (to a hundredth of an RGB level, a percent
/// or a Lab unit), so colours that only look alike (a CMYK red and an RGB red) stay apart and keep
/// their model. Written as `rgb 255 128 0` (0–255), `cmyk 0 100 100 0`, `gray 40` (percent) or
/// `lab 55 60 -40` (L 0–100, a and b).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ColorKey {
model: u8,
v: [i32; 4],
}
/// Key resolution: RGB components are kept to 1/RGB_Q, CMYK and Gray ones to 1/INK_Q and Lab ones
/// to 1/LAB_Q (hundredths of the written units).
const RGB_Q: f32 = 25_500.0;
const INK_Q: f32 = 10_000.0;
const LAB_Q: f32 = 100.0;
impl ColorKey {
pub fn of(c: &Color) -> Self {
let rgb = |x: f32| (x.clamp(0.0, 1.0) * RGB_Q).round() as i32;
let ink = |x: f32| (x.clamp(0.0, 1.0) * INK_Q).round() as i32;
match *c {
Color::Rgb { r, g, b } => Self { model: 0, v: [rgb(r), rgb(g), rgb(b), 0] },
Color::Cmyk { c, m, y, k } => Self { model: 1, v: [ink(c), ink(m), ink(y), ink(k)] },
Color::Gray { k } => Self { model: 2, v: [ink(k), 0, 0, 0] },
Color::Lab { l, a, b } => {
let lab = |x: f32| (x * LAB_Q).round() as i32;
Self { model: 3, v: [lab(l.clamp(0.0, 100.0)), lab(a), lab(b), 0] }
}
}
}
/// The colour this key names.
pub fn color(&self) -> Color {
let f = |i: usize| self.v[i] as f32 / INK_Q;
match self.model {
0 => Color::rgb(self.v[0] as f32 / RGB_Q, self.v[1] as f32 / RGB_Q, self.v[2] as f32 / RGB_Q),
1 => Color::cmyk(f(0), f(1), f(2), f(3)),
2 => Color::gray(f(0)),
_ => Color::lab(self.v[0] as f32 / LAB_Q, self.v[1] as f32 / LAB_Q, self.v[2] as f32 / LAB_Q),
}
}
/// Parse the written form (see [`ColorKey`]); extra spaces and case are ignored.
pub fn parse(s: &str) -> Option<Self> {
let mut it = s.split_whitespace();
let model = it.next()?.to_ascii_lowercase();
let nums: Vec<f32> = it.map(|t| t.parse::<f32>().ok().filter(|v| v.is_finite())).collect::<Option<_>>()?;
let c = match (model.as_str(), nums.as_slice()) {
("rgb", [r, g, b]) => Color::rgb(r / 255.0, g / 255.0, b / 255.0),
("cmyk", [c, m, y, k]) => Color::cmyk(c / 100.0, m / 100.0, y / 100.0, k / 100.0),
("gray", [k]) => Color::gray(k / 100.0),
("lab", [l, a, b]) => Color::lab(*l, *a, *b),
_ => return None,
};
Some(Self::of(&c))
}
}
impl fmt::Display for ColorKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// Components are hundredths of the written units: exact with two decimals.
let num = |q: i32| {
let s = format!("{}{}.{:02}", if q < 0 { "-" } else { "" }, q.abs() / 100, q.abs() % 100);
s.trim_end_matches('0').trim_end_matches('.').to_string()
};
let [a, b, c, k] = self.v.map(num);
match self.model {
0 => write!(f, "rgb {a} {b} {c}"),
1 => write!(f, "cmyk {a} {b} {c} {k}"),
2 => write!(f, "gray {a}"),
_ => write!(f, "lab {a} {b} {c}"),
}
}
}
/// The neutral a colour is, if any: paper white, black (rich blacks included) or a grey.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Neutral {
White,
Black,
Gray,
}
impl Neutral {
pub fn of(c: &Color) -> Option<Self> {
const E: f32 = 0.005;
match *c {
Color::Gray { k } if k <= E => Some(Neutral::White),
Color::Gray { k } if k >= 1.0 - E => Some(Neutral::Black),
Color::Gray { .. } => Some(Neutral::Gray),
Color::Cmyk { c, m, y, k } if c.max(m).max(y).max(k) <= E => Some(Neutral::White),
Color::Cmyk { k, .. } if k >= 1.0 - E => Some(Neutral::Black),
Color::Cmyk { c, m, y, .. } => (c.max(m).max(y) <= E).then_some(Neutral::Gray),
// Lab: lightness at the ends, no chroma between them (to half a unit).
Color::Lab { l, a, b } if l >= 99.5 && a.abs().max(b.abs()) <= 0.5 => Some(Neutral::White),
Color::Lab { l, .. } if l <= 0.5 => Some(Neutral::Black),
Color::Lab { a, b, .. } => (a.abs().max(b.abs()) <= 0.5).then_some(Neutral::Gray),
Color::Rgb { r, g, b } => {
let (lo, hi) = (r.min(g).min(b), r.max(g).max(b));
if lo >= 1.0 - E {
Some(Neutral::White)
} else if hi <= E {
Some(Neutral::Black)
} else {
(hi - lo <= E).then_some(Neutral::Gray)
}
}
}
}
}
/// Which neutrals Recolor Artwork leaves alone (White and Black by default).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Preserve {
pub white: bool,
pub black: bool,
pub grays: bool,
}
impl Default for Preserve {
fn default() -> Self {
Self { white: true, black: true, grays: false }
}
}
impl Preserve {
pub const NONE: Self = Self { white: false, black: false, grays: false };
/// Whether `c` stays as it is.
pub fn keeps(&self, c: &Color) -> bool {
match Neutral::of(c) {
Some(Neutral::White) => self.white,
Some(Neutral::Black) => self.black,
Some(Neutral::Gray) => self.grays,
None => false,
}
}
}
/// How the colours of a row take its new colour.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Method {
/// Every colour becomes the new colour.
#[default]
Exact,
/// Tints of the row's darkest colour become the same tints of the new colour; other colours
/// become the new colour.
PreserveTints,
/// Every colour becomes a tint of the new colour as light, relative to the row's darkest colour,
/// as it is.
ScaleTints,
/// The colour of average lightness becomes the new colour; lighter and darker ones become tints
/// and shades of it.
TintsShades,
/// The row's most saturated colour becomes the new colour; the others turn by the same hue and
/// keep their saturation and brightness.
HueShift,
}
impl Method {
pub const ALL: [Method; 5] = [Method::Exact, Method::PreserveTints, Method::ScaleTints, Method::TintsShades, Method::HueShift];
pub fn id(self) -> &'static str {
match self {
Method::Exact => "exact",
Method::PreserveTints => "preserveTints",
Method::ScaleTints => "scaleTints",
Method::TintsShades => "tintsShades",
Method::HueShift => "hueShift",
}
}
pub fn label(self) -> &'static str {
match self {
Method::Exact => "Exact",
Method::PreserveTints => "Preserve Tints",
Method::ScaleTints => "Scale Tints",
Method::TintsShades => "Tints and Shades",
Method::HueShift => "Hue Shift",
}
}
/// A method from its id or label (case and spaces ignored).
pub fn parse(s: &str) -> Option<Self> {
let key = |x: &str| x.chars().filter(|c| c.is_alphanumeric()).collect::<String>().to_ascii_lowercase();
let want = key(s);
Self::ALL.into_iter().find(|m| key(m.id()) == want || key(m.label()) == want)
}
/// The colour of `row` the new colour stands for: the most saturated for Hue Shift, the one
/// of average lightness for Tints and Shades, else the darkest. `None` for an empty row.
pub fn key_color(self, row: &[Color]) -> Option<Color> {
let labs: Vec<(Color, Lab)> = row.iter().map(|c| (*c, c.to_lab())).collect();
let pick = |score: &dyn Fn(&Lab) -> f32| labs.iter().min_by(|a, b| score(&a.1).total_cmp(&score(&b.1))).map(|x| x.0);
match self {
Method::HueShift => pick(&|l| -l.chroma() * 1000.0 + l.l),
Method::TintsShades => {
let mean = mean_l(&labs);
pick(&|l| (l.l - mean).abs())
}
_ => pick(&|l| l.l * 1000.0 - l.chroma()),
}
}
}
fn mean_l(labs: &[(Color, Lab)]) -> f32 {
labs.iter().map(|x| x.1.l).sum::<f32>() / labs.len().max(1) as f32
}
/// Ink of `c` in `model`'s terms: CMYK and Gray components, 1 − RGB, or Lab's distance from paper
/// white (as [`Color::tinted`] scales it).
fn ink(c: Color, model: crate::cms::Model) -> [f32; 4] {
match c.in_model(model) {
Color::Cmyk { c, m, y, k } => [c, m, y, k],
Color::Gray { k } => [k, 0.0, 0.0, 0.0],
Color::Rgb { r, g, b } => [1.0 - r, 1.0 - g, 1.0 - b, 0.0],
Color::Lab { l, a, b } => [(100.0 - l) / 100.0, a / 100.0, b / 100.0, 0.0],
}
}
fn dot(a: [f32; 4], b: [f32; 4]) -> f32 {
a.iter().zip(b).map(|(x, y)| x * y).sum()
}
/// How much of `base`'s ink `c` carries (0 = paper, 1 = `base` or darker), measured in `c`'s model:
/// the tint of `base` closest to `c`.
pub fn tint_of(c: Color, base: Color) -> f32 {
let (a, b) = (ink(c, c.model()), ink(base, c.model()));
let bb = dot(b, b);
if bb <= 1e-9 { 1.0 } else { (dot(a, b) / bb).clamp(0.0, 1.0) }
}
/// Whether `c` is a tint of `base` (its ink a fraction of `base`'s).
pub fn is_tint(c: Color, base: Color) -> bool {
let t = tint_of(c, base);
let (a, b) = (ink(c, c.model()), ink(base, c.model()));
a.iter().zip(b).all(|(x, y)| (x - y * t).abs() <= 0.01)
}
/// `c` darkened by `f` (0..1) toward black: more K for CMYK and Gray, scaled RGB and Lab.
pub fn shaded(c: Color, f: f32) -> Color {
let f = f.clamp(0.0, 1.0);
match c {
Color::Cmyk { c, m, y, k } => Color::cmyk(c, m, y, k + (1.0 - k) * f),
Color::Gray { k } => Color::gray(k + (1.0 - k) * f),
Color::Lab { l, a, b } => Color::lab(l * (1.0 - f), a * (1.0 - f), b * (1.0 - f)),
Color::Rgb { r, g, b } => Color::rgb(r * (1.0 - f), g * (1.0 - f), b * (1.0 - f)),
}
}
/// One row of Recolor Artwork prepared for mapping: its current colours take `to` by `method`.
#[derive(Clone, Copy, Debug)]
pub struct RowMap {
method: Method,
to: Color,
key: Color,
mean_l: f32,
/// Hue turn from the key colour to the new colour (Hue Shift).
turn: f32,
}
impl RowMap {
/// The map of a row of current colours `row` (non-empty) to the new colour `to`.
pub fn new(method: Method, row: &[Color], to: Color) -> Self {
let key = method.key_color(row).unwrap_or(to);
let mean_l = match method {
Method::TintsShades => mean_l(&row.iter().map(|c| (*c, c.to_lab())).collect::<Vec<_>>()),
_ => 0.0,
};
Self { method, to, key, mean_l, turn: to.to_hsb()[0] - key.to_hsb()[0] }
}
/// The colour of the row the new colour stands for.
pub fn key(&self) -> Color {
self.key
}
/// The new colour of current colour `c`, in `c`'s model.
pub fn map(&self, c: Color) -> Color {
let to = keep_model(c, self.to);
match self.method {
Method::Exact => to,
Method::PreserveTints if is_tint(c, self.key) => to.tinted(tint_of(c, self.key)),
Method::PreserveTints => to,
Method::ScaleTints => to.tinted(tint_of(c, self.key)),
Method::TintsShades => {
let d = c.to_lab().l - self.mean_l;
if d >= 0.0 { to.tinted(1.0 - d / (100.0 - self.mean_l).max(1e-3)) } else { shaded(to, -d / self.mean_l.max(1e-3)) }
}
Method::HueShift if c == self.key => to,
Method::HueShift => {
let [h, s, v] = c.to_hsb();
if s <= 0.0 { c } else { keep_model(c, Color::from_hsb(h + self.turn, s, v)) }
}
}
}
}
/// Group `colors` into at most `n` rows of similar colours, for colour reduction: k-means in Lab
/// (lightness counting half, so tints and shades of a hue stay together) weighted by `weights`,
/// seeded with the heaviest colour and then farthest-first, so the result is the same on every
/// run. Returns the rows as indices into `colors`, ordered by their first index (each in input
/// order).
pub fn cluster(colors: &[Color], weights: &[f32], n: usize) -> Vec<Vec<usize>> {
let pts: Vec<[f32; 3]> = colors
.iter()
.map(|c| {
let l = c.to_lab();
[l.l * 0.5, l.a, l.b]
})
.collect();
let w = |i: usize| weights.get(i).copied().unwrap_or(1.0).max(1e-6);
let d2 = |a: &[f32; 3], b: &[f32; 3]| (a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2) + (a[2] - b[2]).powi(2);
let n = n.max(1);
if pts.is_empty() {
return vec![];
}
// Seeds: the heaviest colour, then each time the one farthest from every seed so far.
let first = (0..pts.len()).fold(0, |best, i| if w(i) > w(best) { i } else { best });
let mut centres = vec![pts[first]];
let mut near: Vec<f32> = pts.iter().map(|p| d2(p, &pts[first])).collect();
while centres.len() < n {
let (i, far) = near.iter().enumerate().fold((0, 0.0f32), |b, (i, d)| if *d > b.1 { (i, *d) } else { b });
if far <= 1e-6 {
break;
}
centres.push(pts[i]);
for (j, p) in pts.iter().enumerate() {
near[j] = near[j].min(d2(p, &pts[i]));
}
}
let nearest = |p: &[f32; 3], cs: &[[f32; 3]]| (0..cs.len()).min_by(|a, b| d2(p, &cs[*a]).total_cmp(&d2(p, &cs[*b]))).unwrap_or(0);
let mut of: Vec<usize> = pts.iter().map(|p| nearest(p, &centres)).collect();
for _ in 0..50 {
let mut sum = vec![([0.0f32; 3], 0.0f32); centres.len()];
for (i, p) in pts.iter().enumerate() {
let s = &mut sum[of[i]];
for (acc, v) in s.0.iter_mut().zip(p) {
*acc += v * w(i);
}
s.1 += w(i);
}
for (c, (s, wt)) in centres.iter_mut().zip(&sum) {
if *wt > 0.0 {
*c = s.map(|v| v / wt);
}
}
let next: Vec<usize> = pts.iter().map(|p| nearest(p, &centres)).collect();
if next == of {
break;
}
of = next;
}
let mut rows: Vec<Vec<usize>> = vec![vec![]; centres.len()];
for (i, c) in of.into_iter().enumerate() {
rows[c].push(i);
}
rows.retain(|r| !r.is_empty());
rows.sort_by_key(|r| r[0]);
rows
}
/// A set of colours to snap to (Limit to Library), with their Lab values cached.
#[derive(Clone, Debug, Default)]
pub struct Palette(Vec<(Color, Lab)>);
impl Palette {
pub fn new(colors: impl IntoIterator<Item = Color>) -> Self {
Self(colors.into_iter().map(|c| (c, c.to_lab())).collect())
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
/// The palette colour closest to `c` (CIEDE2000), in its own model; `c` for an empty palette.
pub fn nearest(&self, c: Color) -> Color {
let l = c.to_lab();
self.0.iter().min_by(|a, b| delta_e2000(a.1, l).total_cmp(&delta_e2000(b.1, l))).map_or(c, |x| x.0)
}
}
/// A small deterministic generator (xorshift64*) for the randomizers.
pub struct Rng(u64);
impl Rng {
pub fn new(seed: u64) -> Self {
Self(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1)
}
pub fn next_u64(&mut self) -> u64 {
let mut x = self.0;
x ^= x >> 12;
x ^= x << 25;
x ^= x >> 27;
self.0 = x;
x.wrapping_mul(0x2545_F491_4F6C_DD1D)
}
/// Uniform in `lo..hi`.
pub fn range(&mut self, lo: f32, hi: f32) -> f32 {
lo + (hi - lo) * ((self.next_u64() >> 40) as f32 / (1u64 << 24) as f32)
}
/// Shuffle `v` in place (Fisher–Yates).
pub fn shuffle<T>(&mut self, v: &mut [T]) {
for i in (1..v.len()).rev() {
let j = (self.next_u64() % (i as u64 + 1)) as usize;
v.swap(i, j);
}
}
/// `c` with a random saturation and brightness, its hue kept (greys stay grey), in its model.
pub fn saturation_brightness(&mut self, c: Color) -> Color {
let [h, s, _] = c.to_hsb();
let (s2, v2) = (self.range(0.25, 1.0), self.range(0.3, 1.0));
keep_model(c, Color::from_hsb(h, if s <= 0.0 { 0.0 } else { s2 }, v2))
}
}
#[cfg(test)]
mod tests {
use super::*;
fn close(a: Color, b: Color) -> bool {
let v = |c: Color| match c {
Color::Cmyk { c, m, y, k } => vec![c, m, y, k],
Color::Rgb { r, g, b } => vec![r, g, b],
Color::Gray { k } => vec![k],
Color::Lab { l, a, b } => vec![l / 100.0, a / 100.0, b / 100.0],
};
a.model() == b.model() && v(a).iter().zip(v(b)).all(|(x, y)| (x - y).abs() < 1e-3)
}
#[test]
fn keys_keep_the_model_and_round_trip() {
let colors = [
Color::rgb(1.0, 0.5, 0.0),
Color::rgb(1.0 / 3.0, 0.2, 0.9),
Color::cmyk(0.0, 1.0, 1.0, 0.0),
Color::cmyk(0.1234, 0.5, 0.0, 0.07),
Color::gray(0.4),
];
for c in colors {
let k = ColorKey::of(&c);
assert_eq!(ColorKey::parse(&k.to_string()), Some(k), "{k}");
assert!(close(k.color(), c));
}
assert_eq!(ColorKey::of(&Color::rgb(1.0, 0.5, 0.0)).to_string(), "rgb 255 127.5 0");
assert_eq!(ColorKey::of(&Color::cmyk(0.0, 1.0, 1.0, 0.0)).to_string(), "cmyk 0 100 100 0");
assert_eq!(ColorKey::of(&Color::gray(0.4)).to_string(), "gray 40");
assert_eq!(ColorKey::of(&Color::rgb8(18, 52, 86)).to_string(), "rgb 18 52 86", "8-bit colours read as whole levels");
// A CMYK red and an RGB red are different colours.
assert_ne!(ColorKey::of(&Color::cmyk(0.0, 1.0, 1.0, 0.0)), ColorKey::of(&Color::rgb(1.0, 0.0, 0.0)));
assert_eq!(ColorKey::parse(" CMYK 0 100 100 0 "), ColorKey::parse("cmyk 0 100 100 0"));
let lab = Color::lab(55.0, 60.5, -40.25);
assert_eq!(ColorKey::of(&lab).to_string(), "lab 55 60.5 -40.25");
assert_eq!(ColorKey::parse("lab 55 60.5 -40.25").map(|k| k.color()), Some(lab));
assert_ne!(ColorKey::of(&lab), ColorKey::of(&keep_model(Color::WHITE, lab)), "a Lab colour isn't its RGB lookalike");
assert_eq!(ColorKey::parse("#ff0000"), None);
assert_eq!(ColorKey::parse("rgb 1 2"), None);
}
#[test]
fn neutrals_and_preserve() {
assert_eq!(Neutral::of(&Color::WHITE), Some(Neutral::White));
assert_eq!(Neutral::of(&Color::cmyk(0.0, 0.0, 0.0, 0.0)), Some(Neutral::White));
assert_eq!(Neutral::of(&Color::cmyk(0.6, 0.4, 0.4, 1.0)), Some(Neutral::Black), "rich black");
assert_eq!(Neutral::of(&Color::gray(0.5)), Some(Neutral::Gray));
assert_eq!(Neutral::of(&Color::rgb(0.5, 0.5, 0.5)), Some(Neutral::Gray));
assert_eq!(Neutral::of(&Color::cmyk(0.0, 0.0, 0.0, 0.3)), Some(Neutral::Gray));
assert_eq!(Neutral::of(&Color::rgb(0.5, 0.4, 0.5)), None);
assert_eq!(Neutral::of(&Color::lab(100.0, 0.0, 0.0)), Some(Neutral::White));
assert_eq!(Neutral::of(&Color::lab(0.0, 0.0, 0.0)), Some(Neutral::Black));
assert_eq!(Neutral::of(&Color::lab(50.0, 0.2, -0.3)), Some(Neutral::Gray));
assert_eq!(Neutral::of(&Color::lab(50.0, 20.0, 0.0)), None);
let p = Preserve::default();
assert!(p.keeps(&Color::BLACK) && p.keeps(&Color::WHITE) && !p.keeps(&Color::gray(0.5)));
assert!(!Preserve::NONE.keeps(&Color::BLACK));
}
#[test]
fn methods_parse_by_id_and_label() {
for m in Method::ALL {
assert_eq!(Method::parse(m.id()), Some(m));
assert_eq!(Method::parse(m.label()), Some(m));
}
assert_eq!(Method::parse("tints & shades"), Some(Method::TintsShades));
assert_eq!(Method::parse("nope"), None);
}
#[test]
fn scale_tints_keep_tint_ratios() {
let red = Color::cmyk(0.0, 1.0, 1.0, 0.0);
let pink = red.tinted(0.4);
let row = [pink, red];
let m = RowMap::new(Method::ScaleTints, &row, Color::cmyk(1.0, 0.5, 0.0, 0.0));
assert!(close(m.key(), red), "the darkest colour is the key");
assert!(close(m.map(red), Color::cmyk(1.0, 0.5, 0.0, 0.0)));
assert!(close(m.map(pink), Color::cmyk(0.4, 0.2, 0.0, 0.0)), "{:?}", m.map(pink));
// RGB tints mix toward white.
let blue = Color::rgb(0.0, 0.0, 1.0);
let m = RowMap::new(Method::ScaleTints, &[blue, blue.tinted(0.5)], Color::rgb(1.0, 0.0, 0.0));
assert!(close(m.map(blue.tinted(0.5)), Color::rgb(1.0, 0.5, 0.5)));
// Lab tints too (toward paper white).
let base = Color::lab(40.0, 60.0, -20.0);
let to = Color::lab(50.0, -40.0, 30.0);
let m = RowMap::new(Method::ScaleTints, &[base, base.tinted(0.25)], to);
assert!(close(m.map(base.tinted(0.25)), to.tinted(0.25)), "{:?}", m.map(base.tinted(0.25)));
}
#[test]
fn preserve_tints_only_scales_real_tints() {
let red = Color::cmyk(0.0, 1.0, 1.0, 0.0);
let other = Color::cmyk(0.0, 0.3, 0.8, 0.0);
let to = Color::cmyk(1.0, 0.0, 0.0, 0.0);
let m = RowMap::new(Method::PreserveTints, &[red, red.tinted(0.5), other], to);
assert!(close(m.map(red.tinted(0.5)), Color::cmyk(0.5, 0.0, 0.0, 0.0)));
assert!(close(m.map(other), to), "not a tint: exact");
let s = RowMap::new(Method::ScaleTints, &[red, other], to);
assert!(!close(s.map(other), to), "Scale Tints scales every colour");
}
#[test]
fn exact_tints_shades_and_hue_shift() {
let to = Color::rgb(0.0, 0.4, 1.0);
let row = [Color::rgb(0.9, 0.2, 0.2), Color::rgb(0.5, 0.1, 0.1), Color::rgb(1.0, 0.7, 0.7)];
let e = RowMap::new(Method::Exact, &row, to);
assert!(row.iter().all(|c| e.map(*c) == to));
let ts = RowMap::new(Method::TintsShades, &row, to);
let l = |c: Color| c.to_lab().l;
assert!(l(ts.map(row[2])) > l(ts.map(row[0])) && l(ts.map(row[0])) > l(ts.map(row[1])), "lighter stays lighter");
let hs = RowMap::new(Method::HueShift, &row, to);
assert_eq!(hs.map(hs.key()), to);
let [h, s, v] = hs.map(row[1]).to_hsb();
let [_, s0, v0] = row[1].to_hsb();
assert!((h - to.to_hsb()[0]).abs() < 1.0 && (s - s0).abs() < 1e-3 && (v - v0).abs() < 1e-3, "{h} {s} {v}");
// Results keep the model of the colour they replace.
let m = RowMap::new(Method::Exact, &[Color::gray(0.3)], to);
assert!(matches!(m.map(Color::gray(0.3)), Color::Gray { .. }));
let lab = [Color::lab(40.0, 50.0, 30.0), Color::lab(70.0, 20.0, 10.0)];
for method in Method::ALL {
let m = RowMap::new(method, &lab, to);
assert!(lab.iter().all(|c| matches!(m.map(*c), Color::Lab { .. })), "{}", method.label());
}
assert!(matches!(shaded(lab[0], 0.5), Color::Lab { .. }));
}
#[test]
fn clustering_reduces_to_n_rows_of_similar_colours() {
let colors =
[Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0), Color::rgb(0.9, 0.1, 0.05), Color::rgb(0.1, 0.1, 0.9), Color::rgb(1.0, 0.2, 0.2)];
let rows = cluster(&colors, &[5.0, 4.0, 1.0, 1.0, 1.0], 2);
assert_eq!(rows, vec![vec![0, 2, 4], vec![1, 3]]);
assert_eq!(cluster(&colors, &[1.0; 5], 9).len(), 5, "never more rows than colours");
assert_eq!(cluster(&colors, &[1.0; 5], 1), vec![vec![0, 1, 2, 3, 4]]);
assert_eq!(cluster(&[Color::WHITE, Color::WHITE], &[1.0, 1.0], 2).len(), 1, "identical colours share a row");
assert!(cluster(&[], &[], 3).is_empty());
}
#[test]
fn palette_snaps_to_the_nearest_colour() {
let p = Palette::new([Color::rgb(1.0, 0.0, 0.0), Color::cmyk(1.0, 0.0, 0.0, 0.0), Color::gray(0.5)]);
assert_eq!(p.nearest(Color::rgb(0.9, 0.1, 0.1)), Color::rgb(1.0, 0.0, 0.0));
assert_eq!(p.nearest(Color::rgb(0.45, 0.45, 0.45)), Color::gray(0.5));
let lab = Palette::new([Color::lab(50.0, 70.0, 50.0), Color::lab(50.0, -60.0, 50.0)]);
assert_eq!(lab.nearest(Color::rgb(0.9, 0.1, 0.1)), Color::lab(50.0, 70.0, 50.0), "library colours keep their model");
assert_eq!(Palette::default().nearest(Color::WHITE), Color::WHITE);
}
#[test]
fn randomizers_are_deterministic_and_keep_hue() {
let mut a: Vec<u32> = (0..10).collect();
let mut b = a.clone();
Rng::new(7).shuffle(&mut a);
Rng::new(7).shuffle(&mut b);
assert_eq!(a, b);
assert_ne!(a, (0..10).collect::<Vec<_>>());
let c = Color::cmyk(0.0, 0.8, 0.9, 0.1);
let r = Rng::new(3).saturation_brightness(c);
assert!(matches!(r, Color::Cmyk { .. }));
assert!(matches!(Rng::new(3).saturation_brightness(Color::lab(50.0, 40.0, 20.0)), Color::Lab { .. }));
assert_eq!(Rng::new(3).saturation_brightness(Color::gray(0.4)).to_hsb()[1], 0.0, "greys stay grey");
}
}
+39 -3
View File
@@ -17,6 +17,30 @@ pub struct Swatch {
pub spot: bool,
}
/// The name of the built-in Registration swatch ([`registration`]).
pub const REGISTRATION: &str = "[Registration]";
/// The built-in Registration swatch: a global colour of 100% of every ink that prints on every
/// plate, process and spot (printer's marks). Every document has it; it can't be edited or deleted.
pub fn registration() -> &'static Swatch {
static S: std::sync::OnceLock<Swatch> = std::sync::OnceLock::new();
S.get_or_init(|| Swatch { name: REGISTRATION.into(), paint: Paint::solid(Color::cmyk(1.0, 1.0, 1.0, 1.0)), global: true, spot: false })
}
impl Swatch {
/// A tint swatch's base swatch and tint: its colour links to another (global) swatch.
pub fn tint_of(&self) -> Option<(&str, f32)> {
match &self.paint {
Paint::Solid { swatch: Some(base), tint, .. } => Some((base, *tint)),
_ => None,
}
}
/// None and Registration: built in, they can't be edited, moved or deleted.
pub fn is_reserved(&self) -> bool {
self.paint.is_none() || self.name == REGISTRATION
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SwatchGroup {
pub name: String,
@@ -24,7 +48,7 @@ pub struct SwatchGroup {
}
fn solid(name: &str, hex: &str) -> Swatch {
Swatch { name: name.into(), paint: Paint::solid(Color::from_hex(hex).unwrap()), global: false, spot: false }
Swatch { name: name.into(), paint: Paint::solid(Color::from_hex(hex).unwrap_or(Color::BLACK)), global: false, spot: false }
}
/// The default swatches of a document in colour `model`: [`base_swatches`] with their RGB colours
@@ -102,8 +126,8 @@ fn base_swatches() -> (Vec<Swatch>, Vec<SwatchGroup>) {
paint: Paint::Gradient(Box::new(crate::GradientPaint::new(Gradient {
kind,
stops: vec![
GradientStop { offset: 0.0, color: Color::from_hex(a).unwrap(), opacity: 1.0, midpoint: 0.5 },
GradientStop { offset: 1.0, color: Color::from_hex(b).unwrap(), opacity: 1.0, midpoint: 0.5 },
GradientStop::new(0.0, Color::from_hex(a).unwrap_or(Color::WHITE)),
GradientStop::new(1.0, Color::from_hex(b).unwrap_or(Color::BLACK)),
],
}))),
global: false,
@@ -159,4 +183,16 @@ mod tests {
let black = s.iter().find(|w| w.name == "Black").and_then(|w| w.paint.color());
assert_eq!(black, Some(Color::cmyk(0.0, 0.0, 0.0, 1.0)));
}
#[test]
fn default_swatches_parse() {
// `solid`/`grad` fall back to black or white on a bad literal instead of panicking; make sure
// none falls back.
let src = include_str!("swatch.rs");
let hexes: Vec<&str> = src.split('"').filter(|t| t.starts_with('#') && t.len() == 7).collect();
assert!(hexes.len() > 30);
for h in hexes {
assert!(Color::from_hex(h).is_some(), "{h}");
}
}
}
+351 -39
View File
@@ -46,8 +46,14 @@ impl Dash {
pub fn is_dashed(&self) -> bool {
self.pattern.iter().all(|v| v.is_finite() && *v >= 0.0) && self.pattern.iter().any(|v| *v > 0.0)
}
/// Scale the dash and gap lengths and the offset by `s`.
pub fn scale(&mut self, s: f64) {
self.pattern.iter_mut().for_each(|v| *v *= s);
self.offset *= s;
}
}
/// An arrowhead shape. Saved by variant name: new shapes are appended, never renamed or reordered.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Arrowhead {
Triangle,
@@ -60,21 +66,130 @@ pub enum Arrowhead {
Diamond,
Arrow,
ArrowOpen,
Barbed,
/// One barb, on the left of the direction the head points.
HalfArrowLeft,
/// One barb, on the right of the direction the head points.
HalfArrowRight,
Concave,
DoubleBar,
Feather,
DotOnBar,
Chevron,
DoubleArrow,
Target,
Star,
Cross,
Plus,
Hexagon,
HexagonOpen,
Tag,
TagOpen,
HalfCircle,
Drop,
Slash,
DoubleSlash,
DiamondOpen,
TriangleReverse,
Swallowtail,
Bracket,
Fork,
Leaf,
Kite,
TriangleBar,
Oval,
}
impl Arrowhead {
pub const ALL: [Arrowhead; 10] = [
/// Every arrowhead, in menu order (arrows, then outlined shapes, then bars and marks).
pub const ALL: [Arrowhead; 40] = [
Arrowhead::Arrow,
Arrowhead::ArrowOpen,
Arrowhead::Barbed,
Arrowhead::Concave,
Arrowhead::DoubleArrow,
Arrowhead::HalfArrowLeft,
Arrowhead::HalfArrowRight,
Arrowhead::Chevron,
Arrowhead::Feather,
Arrowhead::Swallowtail,
Arrowhead::Triangle,
Arrowhead::TriangleOpen,
Arrowhead::TriangleReverse,
Arrowhead::TriangleBar,
Arrowhead::Kite,
Arrowhead::Leaf,
Arrowhead::Drop,
Arrowhead::Circle,
Arrowhead::CircleOpen,
Arrowhead::HalfCircle,
Arrowhead::Oval,
Arrowhead::Target,
Arrowhead::Square,
Arrowhead::SquareOpen,
Arrowhead::Tag,
Arrowhead::TagOpen,
Arrowhead::Diamond,
Arrowhead::DiamondOpen,
Arrowhead::Hexagon,
Arrowhead::HexagonOpen,
Arrowhead::Star,
Arrowhead::Cross,
Arrowhead::Plus,
Arrowhead::Bar,
Arrowhead::DoubleBar,
Arrowhead::DotOnBar,
Arrowhead::Slash,
Arrowhead::DoubleSlash,
Arrowhead::Bracket,
Arrowhead::Fork,
];
/// The name the arrowhead menus show.
pub fn label(self) -> &'static str {
match self {
Arrowhead::Triangle => "Triangle",
Arrowhead::TriangleOpen => "Triangle (open)",
Arrowhead::Circle => "Circle",
Arrowhead::CircleOpen => "Circle (open)",
Arrowhead::Square => "Square",
Arrowhead::SquareOpen => "Square (open)",
Arrowhead::Bar => "Bar",
Arrowhead::Diamond => "Diamond",
Arrowhead::Arrow => "Arrow",
Arrowhead::ArrowOpen => "Arrow (open)",
Arrowhead::Barbed => "Barbed",
Arrowhead::HalfArrowLeft => "Half Arrow (left)",
Arrowhead::HalfArrowRight => "Half Arrow (right)",
Arrowhead::Concave => "Concave",
Arrowhead::DoubleBar => "Double Bar",
Arrowhead::Feather => "Feather",
Arrowhead::DotOnBar => "Dot on Bar",
Arrowhead::Chevron => "Chevron",
Arrowhead::DoubleArrow => "Double Arrow",
Arrowhead::Target => "Target",
Arrowhead::Star => "Star",
Arrowhead::Cross => "Cross",
Arrowhead::Plus => "Plus",
Arrowhead::Hexagon => "Hexagon",
Arrowhead::HexagonOpen => "Hexagon (open)",
Arrowhead::Tag => "Tag",
Arrowhead::TagOpen => "Tag (open)",
Arrowhead::HalfCircle => "Half Circle",
Arrowhead::Drop => "Drop",
Arrowhead::Slash => "Slash",
Arrowhead::DoubleSlash => "Double Slash",
Arrowhead::DiamondOpen => "Diamond (open)",
Arrowhead::TriangleReverse => "Reverse Triangle",
Arrowhead::Swallowtail => "Swallowtail",
Arrowhead::Bracket => "Bracket",
Arrowhead::Fork => "Fork",
Arrowhead::Leaf => "Leaf",
Arrowhead::Kite => "Kite",
Arrowhead::TriangleBar => "Triangle to Bar",
Arrowhead::Oval => "Oval",
}
}
}
/// Where an arrowhead sits relative to the end of its path. In both modes the stroke stops under
@@ -88,7 +203,9 @@ pub enum ArrowAlign {
Tip,
}
/// Variable-width profile: (position 0..1 along the path, left width factor, right width factor).
/// Variable-width profile: (position 0..1 along the path, left width factor, right width factor),
/// in order along the path. Two points at the same position make a discontinuous point: the
/// first is the width just before it, the second the width just after it (a step).
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct WidthProfile {
pub points: Vec<(f64, f64, f64)>,
@@ -106,9 +223,12 @@ pub struct ProfilePreset {
}
impl WidthProfile {
/// Width factor at `t` (average of both sides), linear between points.
/// (left, right) width factors at `t`, linear between points.
pub fn at(&self, t: f64) -> (f64, f64) {
let p = &self.points;
Self::at_points(&self.points, t)
}
/// [`Self::at`] of a profile's points (a preset's or a saved profile's).
pub fn at_points(p: &[(f64, f64, f64)], t: f64) -> (f64, f64) {
if p.is_empty() {
return (1.0, 1.0);
}
@@ -121,15 +241,20 @@ impl WidthProfile {
return (w[0].1 + (w[1].1 - w[0].1) * u, w[0].2 + (w[1].2 - w[0].2) * u);
}
}
let l = p.last().unwrap();
(l.1, l.2)
p.last().map_or((1.0, 1.0), |l| (l.1, l.2))
}
/// The built-in profiles, in menu order. "uniform" is the plain stroke (no profile).
pub const PRESETS: [ProfilePreset; 4] = [
pub const PRESETS: [ProfilePreset; 7] = [
ProfilePreset { id: "uniform", label: "Uniform", points: &[(0.0, 1.0, 1.0), (1.0, 1.0, 1.0)] },
ProfilePreset { id: "lens", label: "Lens", points: &[(0.0, 0.0, 0.0), (0.5, 1.0, 1.0), (1.0, 0.0, 0.0)] },
ProfilePreset { id: "taperStart", label: "Taper Start", points: &[(0.0, 0.0, 0.0), (1.0, 1.0, 1.0)] },
ProfilePreset { id: "taperEnd", label: "Taper End", points: &[(0.0, 1.0, 1.0), (1.0, 0.0, 0.0)] },
// Full width at both ends, pinched to a quarter in the middle.
ProfilePreset { id: "pinch", label: "Pinch", points: &[(0.0, 1.0, 1.0), (0.5, 0.25, 0.25), (1.0, 1.0, 1.0)] },
// A round head a fifth of the way along, then a long taper to the end.
ProfilePreset { id: "teardrop", label: "Teardrop", points: &[(0.0, 0.0, 0.0), (0.2, 1.0, 1.0), (1.0, 0.0, 0.0)] },
// Two swells between narrow necks.
ProfilePreset { id: "wave", label: "Wave", points: &[(0.0, 0.3, 0.3), (0.25, 1.0, 1.0), (0.5, 0.3, 0.3), (0.75, 1.0, 1.0), (1.0, 0.3, 0.3)] },
];
/// The built-in profile with this id.
pub fn preset(id: &str) -> Option<Self> {
@@ -145,14 +270,35 @@ impl WidthProfile {
}
/// The lens profile (thin ends, full width in the middle).
pub fn lens() -> Self {
Self::preset("lens").expect("built-in")
Self::preset("lens").unwrap_or_default()
}
pub fn taper_end() -> Self {
Self::preset("taperEnd").expect("built-in")
Self::preset("taperEnd").unwrap_or_default()
}
pub fn taper_start() -> Self {
Self::preset("taperStart").expect("built-in")
Self::preset("taperStart").unwrap_or_default()
}
/// The (left, right) factors just before and just after `t`: they differ only at a
/// discontinuous point (two points at `t`, within `1e-7`).
pub fn around(&self, t: f64) -> ((f64, f64), (f64, f64)) {
let p = &self.points;
if let Some(i) = p.iter().position(|q| (q.0 - t).abs() <= 1e-7) {
let j = i + p[i..].iter().take_while(|q| (q.0 - p[i].0).abs() <= 1e-9).count() - 1;
if j > i {
return ((p[i].1, p[i].2), (p[j].1, p[j].2));
}
}
let v = self.at(t);
(v, v)
}
}
/// A width profile saved to the Profile list under a name (Add to Profiles), kept with the
/// preferences.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SavedProfile {
pub name: String,
pub profile: WidthProfile,
}
/// A live effect in an appearance stack. Parameters are interpreted by `vectorcraft-effects`.
@@ -237,8 +383,44 @@ pub struct StrokeLayer {
/// Overprint Stroke (see [`FillLayer::overprint`]).
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
pub overprint: bool,
/// How a gradient paint maps onto the stroke (within, along or across it).
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
pub gradient_mode: StrokeGradientMode,
}
/// How a gradient on a stroke is laid out (the Gradient panel's Stroke buttons). Saved by variant
/// name: new modes are appended, never renamed.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum StrokeGradientMode {
/// Placed on the page like a fill's gradient and seen through the stroke.
#[default]
Within,
/// From the start of each subpath to its end, following the path.
Along,
/// From the stroke's left edge to its right edge (left of the path's direction), all along it.
Across,
}
impl StrokeGradientMode {
pub const ALL: [StrokeGradientMode; 3] = [StrokeGradientMode::Within, StrokeGradientMode::Along, StrokeGradientMode::Across];
/// The name commands use (`within`, `along`, `across`).
pub fn name(self) -> &'static str {
match self {
StrokeGradientMode::Within => "within",
StrokeGradientMode::Along => "along",
StrokeGradientMode::Across => "across",
}
}
/// Parse a mode name (any case).
pub fn parse(s: &str) -> Option<Self> {
Self::ALL.into_iter().find(|m| m.name().eq_ignore_ascii_case(s))
}
}
/// How far any arrowhead reaches from its tip, in units of its weight (the open arrow's arms are
/// cut square a little behind its 4 × 4 box).
pub(crate) const HEAD_REACH: f64 = 4.6;
fn ten() -> f64 {
10.0
}
@@ -273,24 +455,71 @@ impl StrokeLayer {
effects: vec![],
arrow_align: ArrowAlign::Extend,
overprint: false,
gradient_mode: StrokeGradientMode::Within,
}
}
/// Weight of the start (`end == false`) or end arrowhead: stroke weight × its scale, at least
/// a quarter point. A head of weight `hw` is `4·hw` long and wide.
/// a quarter point. A head of weight `hw` fits a box about `4·hw` long and wide.
pub fn arrow_weight(&self, end: bool) -> f64 {
let pct = if end { self.arrow_scale.1 } else { self.arrow_scale.0 };
(self.width * pct / 100.0).max(0.25)
}
/// How far the arrowheads can reach from the path's end points (0 without heads): the
/// head's diagonal, or with [`ArrowAlign::Extend`] its length plus the cap past the end.
/// How far the start (`end == false`) or end arrowhead can reach from its end point (0
/// without one): the head's diagonal, or with [`ArrowAlign::Extend`] its length, plus the cap.
pub fn head_reach(&self, end: bool) -> f64 {
let head = if end { self.end_arrow } else { self.start_arrow };
head.map_or(0.0, |_| HEAD_REACH * self.arrow_weight(end) + self.width / 2.0)
}
/// How far the arrowheads can reach from the path's end points (0 without heads).
pub fn arrow_reach(&self) -> f64 {
let reach = |head: Option<Arrowhead>, end: bool| head.map_or(0.0, |_| 4.5 * self.arrow_weight(end) + self.width / 2.0);
reach(self.start_arrow, false).max(reach(self.end_arrow, true))
self.head_reach(false).max(self.head_reach(true))
}
/// The widest the width profile makes the stroke, as a factor of its weight (1 without one).
pub fn profile_max(&self) -> f64 {
self.profile.as_ref().and_then(|p| p.points.iter().map(|&(_, l, r)| l.max(r)).reduce(f64::max)).unwrap_or(1.0).max(0.0)
}
/// The stroke's body across a path that is `closed` or open: how far it reaches from the path
/// at full width (half the weight centred; the whole weight on one side when aligned inside or
/// outside a closed path, which open paths ignore), and for aligned strokes which side it
/// paints (`Some(true)`: inside).
pub fn body(&self, closed: bool) -> (f64, Option<bool>) {
match self.align {
StrokeAlign::Outside if closed => (self.width, Some(false)),
StrokeAlign::Inside if closed => (self.width, Some(true)),
_ => (self.width / 2.0, None),
}
}
/// How far the body paints outside a path that is `closed` or open, at the profile's widest.
pub fn side_reach(&self, closed: bool) -> f64 {
match self.body(closed) {
(_, Some(true)) => 0.0,
(half, _) => half * self.profile_max(),
}
}
/// The farthest this stroke can paint from any path: its body, miter spikes up to the miter
/// limit, projecting caps' corners and the arrowheads ([`Appearance::outset`]).
pub fn reach(&self) -> f64 {
let side = self.side_reach(true).max(self.side_reach(false));
let miter = if self.join == LineJoin::Miter { self.miter_limit.max(1.0) } else { 1.0 };
let cap = if self.cap == LineCap::Square { std::f64::consts::SQRT_2 } else { 1.0 };
(side * miter.max(cap)).max(self.arrow_reach())
}
/// The box an unplaced gradient on this stroke fits to (see [`stroke_paint_bounds`]).
pub fn paint_bounds(&self, geometric: vectorcraft_geom::Rect) -> vectorcraft_geom::Rect {
stroke_paint_bounds(geometric, self.width)
}
/// The gradient this stroke lays along or across its path: its linear or radial gradient
/// paint when [`Self::gradient_mode`] isn't Within (freeform gradients always paint within).
pub fn path_gradient(&self) -> Option<&vectorcraft_color::GradientPaint> {
match &self.paint {
Paint::Gradient(g)
if self.gradient_mode != StrokeGradientMode::Within && g.gradient.kind != vectorcraft_color::GradientKind::Freeform =>
{
Some(g)
}
_ => None,
}
}
}
/// The box an unplaced gradient on a stroke of `width` fits to: the geometric bounds grown by half
@@ -321,6 +550,12 @@ impl AppearanceItem {
AppearanceItem::Stroke(s) => &s.paint,
}
}
pub fn paint_mut(&mut self) -> &mut Paint {
match self {
AppearanceItem::Fill(f) => &mut f.paint,
AppearanceItem::Stroke(s) => &mut s.paint,
}
}
pub fn visible(&self) -> bool {
match self {
AppearanceItem::Fill(f) => f.visible,
@@ -529,36 +764,37 @@ impl Appearance {
Some(i) => self.items.get_mut(i).map(AppearanceItem::effects_mut),
}
}
/// Largest distance the painted area extends beyond the geometry (for visual bounds).
pub fn outset(&self) -> f64 {
self.items
.iter()
.filter_map(|i| match i {
AppearanceItem::Stroke(s) if s.visible && !s.paint.is_none() => Some(
match s.align {
StrokeAlign::Center => s.width / 2.0 * if s.join == LineJoin::Miter { s.miter_limit.min(4.0) } else { 1.0 },
StrokeAlign::Outside => s.width,
StrokeAlign::Inside => 0.0,
}
.max(s.arrow_reach()),
),
_ => None,
})
.fold(0.0, f64::max)
/// The visible strokes that paint something.
pub fn painted_strokes(&self) -> impl Iterator<Item = &StrokeLayer> {
self.items.iter().filter_map(|i| match i {
AppearanceItem::Stroke(s) if s.visible && !s.paint.is_none() => Some(s),
_ => None,
})
}
/// Scale stroke weights (Scale Strokes & Effects).
/// Largest distance the painted area can extend beyond any geometry (see
/// [`StrokeLayer::reach`]); paths measure their own with [`Self::stroked_bounds`].
pub fn outset(&self) -> f64 {
self.painted_strokes().map(StrokeLayer::reach).fold(0.0, f64::max)
}
/// Scale stroke weights, dash lengths and dash offsets (Scale Strokes & Effects).
pub fn scale_strokes(&mut self, s: f64) {
for i in &mut self.items {
if let AppearanceItem::Stroke(st) = i {
st.width *= s;
if let Some(d) = &mut st.dash {
for v in &mut d.pattern {
*v *= s;
}
d.scale(s);
}
}
}
}
/// Scale the distance parameters of every effect (the object's and each fill's and stroke's)
/// by `s` with `scale` (the effects catalogue knows which parameters are distances).
pub fn scale_effects(&mut self, s: f64, scale: fn(&mut Effect, f64)) {
let items = self.items.iter_mut().flat_map(|i| i.effects_mut().iter_mut());
for e in self.effects.iter_mut().chain(items) {
scale(e, s);
}
}
/// Gradient paints of the fills and strokes.
fn gradients_mut(&mut self) -> impl Iterator<Item = &mut vectorcraft_color::GradientPaint> {
self.items.iter_mut().filter_map(|i| match i {
@@ -587,6 +823,7 @@ impl Appearance {
&& ga.start.distance(go.start) <= 1e-6
&& ga.end.distance(go.end) <= 1e-6
&& (ga.aspect - go.aspect).abs() <= 1e-6
&& ga.focal_point().distance(go.focal_point()) <= 1e-6
{
*ga = *go;
}
@@ -779,14 +1016,14 @@ mod tests {
use vectorcraft_geom::{Point, Rect};
let placed = |x: f64| {
let mut g = GradientPaint::new(Gradient::default());
g.geom = Some(GradientGeom { start: Point::new(x, 0.0), end: Point::new(x + 10.0, 0.0), aspect: 1.0 });
g.geom = Some(GradientGeom { start: Point::new(x, 0.0), end: Point::new(x + 10.0, 0.0), aspect: 1.0, focal: None });
Paint::Gradient(Box::new(g))
};
let mut a = Appearance::basic(placed(0.0), placed(-5.0), 10.0);
a.rebase_gradients(Rect::new(0.0, 0.0, 100.0, 100.0), Rect::new(100.0, 0.0, 300.0, 100.0));
let start = |p: Paint| match p {
Paint::Gradient(g) => g.geom.unwrap().start,
_ => unreachable!(),
_ => panic!("a gradient"),
};
// The fill's start stays on the left edge; the stroke's on its inflated box's (−5 → 95).
assert_eq!((start(a.fill_paint()), start(a.stroke_paint())), (Point::new(100.0, 0.0), Point::new(95.0, 0.0)));
@@ -863,6 +1100,60 @@ mod tests {
assert_eq!(WidthProfile::lens().points, vec![(0.0, 0.0, 0.0), (0.5, 1.0, 1.0), (1.0, 0.0, 0.0)]);
}
#[test]
fn arrowhead_names_are_stable_and_every_one_is_listed_once() {
// Saved files store these names: they may only ever be appended to.
const SAVED: [&str; 40] = [
"Triangle",
"TriangleOpen",
"Circle",
"CircleOpen",
"Square",
"SquareOpen",
"Bar",
"Diamond",
"Arrow",
"ArrowOpen",
"Barbed",
"HalfArrowLeft",
"HalfArrowRight",
"Concave",
"DoubleBar",
"Feather",
"DotOnBar",
"Chevron",
"DoubleArrow",
"Target",
"Star",
"Cross",
"Plus",
"Hexagon",
"HexagonOpen",
"Tag",
"TagOpen",
"HalfCircle",
"Drop",
"Slash",
"DoubleSlash",
"DiamondOpen",
"TriangleReverse",
"Swallowtail",
"Bracket",
"Fork",
"Leaf",
"Kite",
"TriangleBar",
"Oval",
];
for name in SAVED {
let a: Arrowhead = serde_json::from_value(serde_json::json!(name)).unwrap();
assert_eq!(serde_json::to_value(a).unwrap(), name);
assert_eq!(Arrowhead::ALL.iter().filter(|x| **x == a).count(), 1, "{name} in the menu once");
}
let labels: std::collections::HashSet<&str> = Arrowhead::ALL.iter().map(|a| a.label()).collect();
assert_eq!(labels.len(), Arrowhead::ALL.len(), "labels are distinct");
}
#[test]
fn arrow_align_defaults_to_extend_and_round_trips() {
let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), 2.0);
@@ -886,8 +1177,9 @@ mod tests {
st.arrow_scale = (100.0, 200.0);
assert_eq!(st.arrow_weight(false), 4.0);
assert_eq!(st.arrow_weight(true), 8.0);
assert_eq!((st.head_reach(false), st.head_reach(true)), (0.0, HEAD_REACH * 8.0 + 2.0));
// A 32 pt head whose tip sits up to its length (plus the cap) past the end point.
assert_eq!(a.outset(), 4.5 * 8.0 + 2.0);
assert_eq!(a.outset(), HEAD_REACH * 8.0 + 2.0);
a.stroke_mut().unwrap().width = 0.01;
assert_eq!(a.stroke().unwrap().arrow_weight(true), 0.25, "heads keep a minimum size");
}
@@ -899,8 +1191,28 @@ mod tests {
assert_eq!(a.outset(), 5.0);
a.stroke_mut().unwrap().align = StrokeAlign::Outside;
assert_eq!(a.outset(), 10.0);
// Open paths stroke inside-aligned strokes centred.
a.stroke_mut().unwrap().align = StrokeAlign::Inside;
assert_eq!(a.outset(), 0.0);
assert_eq!(a.outset(), 5.0);
assert_eq!((a.stroke().unwrap().side_reach(true), a.stroke().unwrap().body(true)), (0.0, (10.0, Some(true))));
}
#[test]
fn outset_covers_miter_spikes_projecting_caps_and_profile_maxima() {
let mut a = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 2.0);
// Miter joins can spike out to the limit × half the weight.
assert_eq!(a.outset(), 10.0);
let st = a.stroke_mut().unwrap();
st.join = LineJoin::Bevel;
st.cap = LineCap::Square;
assert!((a.outset() - std::f64::consts::SQRT_2).abs() < 1e-12, "a projecting cap's corner");
let st = a.stroke_mut().unwrap();
st.cap = LineCap::Round;
st.profile = Some(WidthProfile { points: vec![(0.0, 0.5, 2.5), (1.0, 1.0, 1.0)] });
assert_eq!(st.profile_max(), 2.5);
assert_eq!(a.outset(), 2.5);
a.stroke_mut().unwrap().paint = Paint::None;
assert_eq!(a.outset(), 0.0, "an unpainted stroke");
}
#[test]
+17 -13
View File
@@ -99,7 +99,7 @@ fn hit_children(parent: &Node, p: Point, opt: HitOptions, chain: &mut Vec<NodeId
if !c.visible || c.locked {
continue;
}
if let Some(b) = c.visual_bounds()
if let Some(b) = c.reach_bounds()
&& !b.inflate(opt.tol, opt.tol).contains(p)
{
continue;
@@ -117,13 +117,22 @@ fn hit_children(parent: &Node, p: Point, opt: HitOptions, chain: &mut Vec<NodeId
None
}
/// A click on the strokes of a path or compound path `n` along `bp`: what any visible stroke
/// paints there (arrowheads, alignment, width profile, projecting caps, miter spikes), else its
/// outline within the tolerance. Outline mode hits the outline only.
fn hit_stroke(n: &Node, bp: &vectorcraft_geom::BezPath, rule: vectorcraft_geom::FillRule, p: Point, opt: HitOptions) -> Option<HitKind> {
if !opt.outline && n.appearance.stroke_hit(bp, rule, p, opt.tol) {
return Some(HitKind::Stroke);
}
stroke_contains(bp, 0.0, opt.tol, p).then_some(HitKind::Outline)
}
fn hit_leaf(n: &Node, p: Point, opt: HitOptions) -> Option<HitKind> {
match &n.kind {
NodeKind::Path { path, rule, .. } => {
let bp = path.to_bezpath();
let sw = n.appearance.stroke_width();
if stroke_contains(&bp, if opt.outline { 0.0 } else { sw }, opt.tol, p) {
return Some(if opt.outline || sw == 0.0 { HitKind::Outline } else { HitKind::Stroke });
if let Some(k) = hit_stroke(n, &bp, *rule, p, opt) {
return Some(k);
}
let filled = !n.appearance.fill_paint().is_none();
if !opt.outline && !opt.path_only && filled && fill_contains(&bp, *rule, p) {
@@ -131,15 +140,10 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions) -> Option<HitKind> {
}
None
}
NodeKind::Compound { children, rule } => {
let mut bp = vectorcraft_geom::BezPath::new();
for c in children {
if let Some(pd) = c.path_data() {
bp.extend(pd.to_bezpath());
}
}
if stroke_contains(&bp, n.appearance.stroke_width(), opt.tol, p) {
return Some(HitKind::Stroke);
NodeKind::Compound { rule, .. } => {
let bp = n.stroke_path()?;
if let Some(k) = hit_stroke(n, &bp, *rule, p, opt) {
return Some(k);
}
(!opt.outline && fill_contains(&bp, *rule, p)).then_some(HitKind::Fill)
}
+178 -13
View File
@@ -8,12 +8,21 @@
pub mod appearance;
pub mod graph;
pub mod hit;
pub mod links;
pub mod live;
pub mod marks;
pub mod metadata;
pub mod node;
pub mod overprint;
pub mod pattern;
mod pixels;
pub mod profiles;
pub mod rastersettings;
mod reach;
pub mod selection;
pub mod setup;
pub mod slices;
pub mod style_libs;
pub mod swatches;
pub mod text;
@@ -33,20 +42,30 @@ pub(crate) mod skip {
}
}
pub use appearance::StrokeGradientMode;
pub use appearance::{
Appearance, AppearanceItem, ArrowAlign, Arrowhead, Dash, Effect, FillLayer, LineCap, LineJoin, ProfilePreset, StrokeAlign, StrokeLayer,
WidthProfile,
Appearance, AppearanceItem, ArrowAlign, Arrowhead, Dash, Effect, FillLayer, LineCap, LineJoin, ProfilePreset, SavedProfile, StrokeAlign,
StrokeLayer, WidthProfile,
};
pub use graph::{GraphKind, GraphSpec};
pub use hit::{Hit, HitKind};
pub use links::{LinkInfo, PlacementOptions};
pub use live::{BlendOrientation, BlendSpacing, BlendSpec, EnvelopeKind, GradientMesh, MeshPoint};
pub use metadata::{CopyrightStatus, DocMetadata};
pub use node::Knockout;
pub use node::Scaling;
pub use node::{ImageMap, ObjectAttributes};
pub use node::{ImageObject, LAYER_COLORS, LayerColor, LiveShape, Node, NodeId, NodeKind, OpacityMask};
pub use pattern::{Overlap, PatternDef, PatternEdit, RepeatKind, RepeatSpec, TileType};
pub use profiles::ColorProfiles;
pub use rastersettings::{RasterColorModel, RasterEffectsSettings};
pub use selection::{AnchorRef, Selection};
pub use setup::{Background, DocSetup, ExportText, GridSize, Quotes};
pub use slices::{CellAlign, CellVAlign, Slice, SliceArea, SliceKind, SliceOptions, SliceSource};
pub use style_libs::StyleLibrary;
pub use text::{
AreaOptions, CharStyle, FirstBaseline, Justify, ParaStyle, PathEffect, TabAlign, TabStop, TextKind, TextObject, TextRun, TextStyleDef, TextWrap,
WrapShape,
AreaOptions, CharPosition, CharStyle, FirstBaseline, Justify, ParaStyle, PathEffect, ScriptMetrics, TabAlign, TabStop, TextKind, TextObject,
TextRun, TextStyleDef, TextWrap, WrapShape,
};
pub use vectorcraft_color as color;
pub use vectorcraft_geom as geom;
@@ -142,23 +161,55 @@ impl Unit {
}
/// Format a point value in this unit the way fields show it (e.g. `12.5 pt`, `3 in`).
pub fn format(self, pt: f64) -> String {
let v = self.from_pt(pt);
let s = format!("{:.3}", v);
format!("{} {}", self.number(pt), self.suffix())
}
/// [`Unit::format`] without the suffix (`12.5`), for narrow fields.
pub fn number(self, pt: f64) -> String {
let s = format!("{:.3}", self.from_pt(pt));
let s = s.trim_end_matches('0').trim_end_matches('.');
let s = if s == "-0" { "0" } else { s };
format!("{s} {}", self.suffix())
if s == "-0" { "0".into() } else { s.into() }
}
/// Parse `12`, `12pt`, `1in`, `3 mm`, `2p6` (picas+points), simple `+ - * /` arithmetic.
pub fn parse(self, s: &str) -> Option<f64> {
parse_measure(s, self)
}
/// The value naming this unit in the Units preferences (`points`, `millimeters`,
/// `feetInches`).
pub fn key(self) -> &'static str {
match self {
Unit::Points => "points",
Unit::Picas => "picas",
Unit::Inches => "inches",
Unit::Millimeters => "millimeters",
Unit::Centimeters => "centimeters",
Unit::Pixels => "pixels",
Unit::FeetInches => "feetInches",
Unit::Meters => "meters",
Unit::Yards => "yards",
Unit::Feet => "feet",
}
}
/// The unit `name` names: its label, suffix or [`Unit::key`] in any case, ignoring spaces and
/// punctuation (`Millimeters`, `mm`, `Feet & Inches`, `feetInches`).
pub fn named(name: &str) -> Option<Unit> {
let letters = |s: &'static str| s.chars().filter(char::is_ascii_alphanumeric).map(|c| c.to_ascii_lowercase());
let given = || name.chars().filter(char::is_ascii_alphanumeric).map(|c| c.to_ascii_lowercase());
Unit::ALL.into_iter().find(|u| letters(u.label()).eq(given()) || u.suffix().chars().eq(given()))
}
/// A point value as the canvas measurement labels show it: two decimals and the suffix
/// (`12.50 mm`).
pub fn readout(self, pt: f64) -> String {
format!("{:.2} {}", self.from_pt(pt), self.suffix())
}
}
fn parse_measure(s: &str, default: Unit) -> Option<f64> {
let s = s.trim();
// Simple arithmetic on the right (Illustrator fields accept "10+5", "100/2", "3in*2").
for op in ['+', '-', '*', '/'] {
if let Some(i) = s[1.min(s.len())..].rfind(op).map(|i| i + 1.min(s.len())) {
// Past the first character, so a leading sign isn't an operator.
let skip = s.chars().next().map_or(0, char::len_utf8);
if let Some(i) = s[skip..].rfind(op).map(|i| i + skip) {
let (l, r) = (&s[..i], &s[i + 1..]);
if l.trim().is_empty() {
continue;
@@ -356,6 +407,10 @@ pub struct ImageBlob {
pub mime: String,
#[serde(skip)]
pub bytes: Arc<Vec<u8>>,
/// A linked image's low-resolution preview (PNG, see [`links`]): what a save writes when only
/// linked images show this blob, and what `bytes` hold while the linked file can't be read.
#[serde(skip)]
pub proxy: Option<Arc<Vec<u8>>>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
@@ -423,12 +478,58 @@ pub struct Document {
/// pass their contents through) knock each other out.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub page_knockout: bool,
/// Swatches panel → Spot Colors: spot colours defined in Lab show and separate from their Lab
/// values (on, the default) or from their working-CMYK equivalents (off)
/// ([`Document::linked_color`]).
#[serde(default = "yes", skip_serializing_if = "skip::is_true")]
pub spot_use_lab: bool,
/// File → Document Setup (bleed, transparency grid, paper, type options).
#[serde(default, skip_serializing_if = "skip::is_default")]
pub setup: DocSetup,
/// Layers panel → Paste Remembers Layers: pasted objects go back into the layers (by name)
/// they were copied from instead of the current layer.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub paste_remembers_layers: bool,
/// File → File Info (the title is [`Document::title`]).
#[serde(default, skip_serializing_if = "skip::is_default")]
pub metadata: DocMetadata,
/// Effect → Document Raster Effects Settings besides the resolution
/// ([`Document::raster_effects_ppi`]).
#[serde(default, skip_serializing_if = "skip::is_default")]
pub raster_effects: RasterEffectsSettings,
/// The view (zoom, centre, rotation) the document was saved with; it reopens there. Written at
/// save time only, so changing the view never marks the document modified.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub last_view: Option<SavedView>,
/// Edit → Assign Profile: the profiles the document is tagged with (files before format v3
/// kept them in `unknown`, see [`Document::migrate_color_profiles`]).
#[serde(default, skip_serializing_if = "ColorProfiles::is_empty")]
pub color_profiles: ColorProfiles,
/// File → Export for Screens: the settings it last exported with (`document.exportForScreens`
/// params), so the dialog reopens on them.
#[serde(default, skip_serializing_if = "serde_json::Map::is_empty")]
pub export_settings: serde_json::Map<String, serde_json::Value>,
/// Top-level keys this version doesn't know (written by a newer one), kept so saving doesn't
/// lose them. Separate from [`Document::unknown`], which holds foreign data by design.
#[serde(flatten)]
pub extra: serde_json::Map<String, serde_json::Value>,
/// User slices (Slice tool, Object → Slice); object slices are [`Node::slice`].
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub slices: Vec<Slice>,
/// Object → Slice → Clip to Artboard: slices are clipped to the artboards and auto slices fill
/// them (on, the default); off, auto slices cover the art and the slices.
#[serde(default = "yes", skip_serializing_if = "skip::is_true")]
pub slices_clip_to_artboard: bool,
}
fn ppi72() -> f64 {
72.0
}
fn yes() -> bool {
true
}
pub const FORMAT_VERSION: u32 = 1;
impl Document {
@@ -473,6 +574,17 @@ impl Document {
unknown: Default::default(),
page_isolate: false,
page_knockout: false,
spot_use_lab: true,
setup: DocSetup::default(),
paste_remembers_layers: false,
metadata: DocMetadata::default(),
raster_effects: RasterEffectsSettings::default(),
last_view: None,
color_profiles: ColorProfiles::default(),
export_settings: Default::default(),
extra: Default::default(),
slices: vec![],
slices_clip_to_artboard: true,
};
let id = d.alloc_id();
d.layers.push(Arc::new(Node::layer(id, "Layer 1", LayerColor::Preset(0))));
@@ -494,6 +606,7 @@ impl Document {
for l in &self.layers {
l.walk(&mut |n| max = max.max(n.id.0));
}
max = self.slices.iter().fold(max, |m, s| m.max(s.id.0));
self.next_id = self.next_id.max(max + 1);
}
@@ -598,8 +711,11 @@ impl Document {
pub fn remove(&mut self, id: NodeId) -> Result<Arc<Node>, DocError> {
let parent = self.parent_of(id);
let path = self.index_path(id).ok_or(DocError::NoNode(id))?;
let idx = *path.last().unwrap();
let idx = *path.last().ok_or(DocError::NoNode(id))?;
let ch = self.children_mut(parent)?;
if idx >= ch.len() {
return Err(DocError::NoNode(id));
}
Ok(ch.remove(idx))
}
@@ -702,8 +818,7 @@ impl Document {
n.id = self.alloc_id();
if let Some(ch) = n.children_mut() {
let old: Vec<Arc<Node>> = std::mem::take(ch);
let fresh: Vec<Arc<Node>> = old.iter().map(|c| Arc::new(self.reid(c))).collect();
*n.children_mut().unwrap() = fresh;
*ch = old.iter().map(|c| Arc::new(self.reid(c))).collect();
}
n
}
@@ -764,7 +879,7 @@ impl Document {
fn default_graphic_styles() -> Vec<GraphicStyle> {
use vectorcraft_color::{Color, Paint};
let solid = |hex| Paint::solid(Color::from_hex(hex).unwrap());
let solid = |hex| Paint::solid(Color::from_hex(hex).unwrap_or(Color::BLACK));
[
GraphicStyle::new(DEFAULT_GRAPHIC_STYLE, Appearance::default_art()),
GraphicStyle::new("Black Outline", Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0)),
@@ -777,6 +892,14 @@ fn default_graphic_styles() -> Vec<GraphicStyle> {
.collect()
}
impl Document {
/// Make the next id allocated at least `next`: ids handed out outside the layer tree (such
/// as an importer's opacity mask and pattern art), which [`Document::fix_next_id`] doesn't see.
pub fn reserve_ids(&mut self, next: u64) {
self.next_id = self.next_id.max(next);
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -868,6 +991,43 @@ mod tests {
assert!(!ids.contains(&a) && !ids.contains(&b));
}
#[test]
fn setup_round_trips_and_old_files_load() {
let (mut d, _, _) = doc_with_rects();
// A document without a setup writes no `setup` key (old readers and files stay unchanged).
assert!(!serde_json::to_string(&d).unwrap().contains("\"setup\""));
d.setup.bleed = [9.0, 9.0, 0.0, 18.0];
d.setup.grid_size = GridSize::Large;
d.setup.typographers_quotes = false;
d.setup.quotes = setup::language_quotes("German").unwrap();
d.setup.flattener_preset = Some("High Resolution".into());
d.setup.background = Background::White;
d.setup.export_text = ExportText::Appearance;
let back: Document = serde_json::from_str(&serde_json::to_string(&d).unwrap()).unwrap();
assert_eq!(back.setup, d.setup);
// Files written before Document Setup existed load with the defaults.
let mut v = serde_json::to_value(&d).unwrap();
v.as_object_mut().unwrap().remove("setup");
let old: Document = serde_json::from_value(v).unwrap();
assert_eq!(old.setup, DocSetup::default());
}
#[test]
fn char_position_round_trips() {
let st = CharStyle {
position: CharPosition::Subscript(ScriptMetrics { size: 50.0, position: 20.0 }),
small_caps: Some(75.0),
..CharStyle::default()
};
let v = serde_json::to_value(&st).unwrap();
assert_eq!(v["position"], serde_json::json!({"kind": "subscript", "size": 50.0, "position": 20.0}));
assert_eq!(serde_json::from_value::<CharStyle>(v).unwrap(), st);
let plain = serde_json::to_value(CharStyle::default()).unwrap();
assert!(plain.get("position").is_none() && plain.get("small_caps").is_none());
let (scale, shift) = CharPosition::Subscript(ScriptMetrics::DEFAULT).scale_shift(10.0);
assert!((scale - 0.583).abs() < 1e-9 && (shift + 3.33).abs() < 1e-9);
}
#[test]
fn units() {
assert_eq!(Unit::Inches.parse("1"), Some(72.0));
@@ -882,3 +1042,8 @@ mod tests {
assert_eq!(Unit::Inches.format(144.0), "2 in");
}
}
#[cfg(test)]
mod tests_slices;
#[cfg(test)]
mod tests_units;
+352
View File
@@ -0,0 +1,352 @@
//! Linked files: where a placed file lives and what it was when last read ([`LinkInfo`]), the
//! low-resolution preview a linked image keeps for when its file can't be read
//! ([`ImageBlob::proxy`]), and every image object of a document ([`Document::visit_images`]).
use std::collections::{BTreeMap, BTreeSet};
use std::io::Cursor;
use std::sync::Arc;
use serde::{Deserialize, Deserializer, Serialize};
use crate::{Document, ImageBlob, ImageObject, Node, NodeKind};
/// The longest side of a linked image's preview (pixels). Smaller images keep no preview: their
/// full pixels are saved instead.
pub const PROXY_SIZE: u32 = 256;
/// The MIME type of previews.
pub const PROXY_MIME: &str = "image/png";
/// A linked file: an image object shows the file at `path` (File → Place with Link) and the
/// document saves only a preview of it.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct LinkInfo {
/// The file's absolute path.
pub path: String,
/// The path relative to the document's folder (`/` separators), written on save: how the file
/// is found after the document and its links move together.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub relative: Option<String>,
/// The file's modification time when last read (milliseconds since the Unix epoch).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub modified: Option<u64>,
/// The file's size when last read (bytes).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub size: Option<u64>,
/// The hash of the file's bytes when last read ([`hash_bytes`]).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub hash: Option<String>,
/// The page shown, for a linked document page (1-based).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub page: Option<u32>,
}
impl LinkInfo {
/// A link to `path` with nothing known about the file.
pub fn new(path: impl Into<String>) -> Self {
Self { path: path.into(), ..Self::default() }
}
/// The file name: the path's last component, whichever system's separators it uses.
pub fn name(&self) -> &str {
self.path.rsplit(['/', '\\']).next().unwrap_or(&self.path)
}
}
impl From<&str> for LinkInfo {
fn from(path: &str) -> Self {
Self::new(path)
}
}
/// [`ImageObject::link`] from a link object or, as files saved before links had details, a path.
pub(crate) fn de_link<'de, D: Deserializer<'de>>(d: D) -> Result<Option<LinkInfo>, D::Error> {
#[derive(Deserialize)]
#[serde(untagged)]
enum Repr {
Path(String),
Info(LinkInfo),
}
Ok(Option::<Repr>::deserialize(d)?.map(|r| match r {
Repr::Path(path) => LinkInfo::new(path),
Repr::Info(info) => info,
}))
}
/// A hash of `bytes` (FNV-1a), the same for identical files: `img` and 16 hex digits.
pub fn hash_bytes(bytes: &[u8]) -> String {
let h = bytes.iter().fold(0xcbf29ce484222325u64, |h, x| (h ^ *x as u64).wrapping_mul(0x100000001b3));
format!("img{h:016x}")
}
impl ImageBlob {
/// A blob of encoded image `bytes` of type `mime`, without a preview.
pub fn new(mime: impl Into<String>, bytes: Vec<u8>) -> Self {
Self { mime: mime.into(), bytes: Arc::new(bytes), proxy: None }
}
/// This blob with a preview of at most [`PROXY_SIZE`] pixels a side (PNG), when the image is
/// larger than that and decodes; otherwise unchanged.
pub fn with_proxy(mut self) -> Self {
if self.proxy.is_none() {
self.proxy = proxy_png(&self.bytes).map(Arc::new);
}
self
}
/// Are the bytes the preview (the linked file hasn't been read)?
pub fn is_proxy(&self) -> bool {
self.proxy.as_ref().is_some_and(|p| Arc::ptr_eq(p, &self.bytes))
}
}
/// `bytes` decoded and shrunk to fit [`PROXY_SIZE`] as a PNG; `None` when small enough already or
/// undecodable.
fn proxy_png(bytes: &[u8]) -> Option<Vec<u8>> {
let (w, h) = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?.into_dimensions().ok()?;
if w.max(h) <= PROXY_SIZE {
return None;
}
let small = image::load_from_memory(bytes).ok()?.thumbnail(PROXY_SIZE, PROXY_SIZE);
let mut png = Vec::new();
small.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).ok()?;
Some(png)
}
/// `n` and every descendant, opacity-mask art included.
fn walk_all<'a>(n: &'a Node, f: &mut impl FnMut(&'a Node)) {
f(n);
if let Some(m) = &n.mask {
walk_all(&m.art, f);
}
for c in n.children().into_iter().flatten() {
walk_all(c, f);
}
}
impl Document {
/// Visit every image object: in the layers, then in symbol definitions and pattern swatches,
/// opacity-mask art included.
pub fn visit_images<'a>(&'a self, mut f: impl FnMut(&'a Node, &'a ImageObject)) {
let roots = self.layers.iter().chain(self.symbols.iter().map(|s| &s.art)).chain(self.patterns.iter().flat_map(|p| &p.art));
for root in roots {
walk_all(root, &mut |n| {
if let NodeKind::Image(im) = &n.kind {
f(n, im);
}
});
}
}
/// The keys of image blobs only linked images show: what a save writes as their preview.
pub fn linked_only_images(&self) -> BTreeSet<String> {
if self.images.values().all(|b| b.proxy.is_none()) {
return BTreeSet::new();
}
// Per key: (shown linked, shown embedded).
let mut uses: BTreeMap<&str, (bool, bool)> = BTreeMap::new();
self.visit_images(|_, im| {
let u = uses.entry(im.key.as_str()).or_default();
if im.link.is_some() {
u.0 = true;
} else {
u.1 = true;
}
});
uses.into_iter().filter(|(_, (linked, embedded))| *linked && !embedded).map(|(k, _)| k.to_string()).collect()
}
}
/// Links panel → Placement Options: how a file read again (Relink, Update Link) takes the place of
/// the art it replaces.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct PlacementOptions {
#[serde(default)]
pub preserve: Preserve,
/// Where the new art sits in the old bounds (all but [`Preserve::Bounds`]).
#[serde(default)]
pub align: Align,
/// Clip the new art to the old bounds where it is larger.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub clip: bool,
}
/// What a relinked image keeps of the art it replaces.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum Preserve {
/// Its scale (relative to each file's 100% size), rotation and position.
Transforms,
/// Its bounds: the new art is stretched into them.
#[default]
Bounds,
/// Nothing but its position: the new art at 100%, unrotated.
FileDimensions,
/// Its bounds: the new art scaled proportionally to fit inside them.
Fit,
/// Its bounds: the new art scaled proportionally to fill them.
Fill,
}
impl Preserve {
pub const ALL: [Preserve; 5] = [Preserve::Transforms, Preserve::Bounds, Preserve::FileDimensions, Preserve::Fit, Preserve::Fill];
/// The id commands use (`transforms`, `bounds`, `fileDimensions`, `fit`, `fill`).
pub fn id(self) -> &'static str {
match self {
Preserve::Transforms => "transforms",
Preserve::Bounds => "bounds",
Preserve::FileDimensions => "fileDimensions",
Preserve::Fit => "fit",
Preserve::Fill => "fill",
}
}
pub fn from_id(id: &str) -> Option<Self> {
Self::ALL.into_iter().find(|p| p.id() == id)
}
}
/// A point of the 3×3 alignment grid, row by row from the top left.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum Align {
TopLeft,
Top,
TopRight,
Left,
#[default]
Center,
Right,
BottomLeft,
Bottom,
BottomRight,
}
impl Align {
pub const ALL: [Align; 9] =
[Align::TopLeft, Align::Top, Align::TopRight, Align::Left, Align::Center, Align::Right, Align::BottomLeft, Align::Bottom, Align::BottomRight];
/// The id commands use (`topLeft` … `bottomRight`).
pub fn id(self) -> &'static str {
match self {
Align::TopLeft => "topLeft",
Align::Top => "top",
Align::TopRight => "topRight",
Align::Left => "left",
Align::Center => "center",
Align::Right => "right",
Align::BottomLeft => "bottomLeft",
Align::Bottom => "bottom",
Align::BottomRight => "bottomRight",
}
}
pub fn from_id(id: &str) -> Option<Self> {
Self::ALL.into_iter().find(|a| a.id() == id)
}
/// The fractions (0, ½ or 1) of the free room left of and above the new art.
pub fn fractions(self) -> (f64, f64) {
let i = Self::ALL.iter().position(|a| *a == self).unwrap_or(4);
((i % 3) as f64 / 2.0, (i / 3) as f64 / 2.0)
}
}
impl Document {
/// Change every image object (in the layers, symbol definitions and pattern swatches, opacity-mask
/// art included) for which `pick` holds; only the subtrees holding one are copied.
pub fn update_images(&mut self, pick: impl Fn(&ImageObject) -> bool, mut f: impl FnMut(&mut ImageObject)) {
fn holds(n: &Node, pick: &dyn Fn(&ImageObject) -> bool) -> bool {
let mut hit = false;
walk_all(n, &mut |c| hit |= matches!(&c.kind, NodeKind::Image(im) if pick(im)));
hit
}
fn update(n: &mut Arc<Node>, pick: &dyn Fn(&ImageObject) -> bool, f: &mut dyn FnMut(&mut ImageObject)) {
if !holds(n, pick) {
return;
}
let n = Arc::make_mut(n);
if let NodeKind::Image(im) = &mut n.kind
&& pick(im)
{
f(im);
}
if let Some(m) = &mut n.mask {
update(&mut m.art, pick, f);
}
for c in n.children_mut().into_iter().flatten() {
update(c, pick, f);
}
}
let roots =
self.layers.iter_mut().chain(self.symbols.iter_mut().map(|s| &mut s.art)).chain(self.patterns.iter_mut().flat_map(|p| &mut p.art));
for root in roots {
update(root, &pick, &mut f);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::NodeId;
use vectorcraft_geom::Affine;
fn png(w: u32, h: u32) -> Vec<u8> {
let mut out = vec![];
image::RgbaImage::from_pixel(w, h, image::Rgba([10, 200, 30, 255])).write_to(&mut Cursor::new(&mut out), image::ImageFormat::Png).unwrap();
out
}
fn image(d: &mut Document, key: &str, link: Option<LinkInfo>) -> NodeId {
let id = d.alloc_id();
let layer = d.layers[0].id;
d.insert(
Some(layer),
0,
Node::new(
id,
NodeKind::Image(ImageObject { key: key.into(), width: 4, height: 4, xf: Affine::IDENTITY, link, placement: Default::default() }),
),
)
.unwrap()
}
#[test]
fn a_path_string_from_older_files_reads_as_a_link() {
let old: ImageObject = serde_json::from_str(r#"{"key":"k","width":2,"height":1,"xf":[1,0,0,1,0,0],"link":"C:\\art\\photo.png"}"#).unwrap();
let link = old.link.unwrap();
assert_eq!((link.path.as_str(), link.name(), link.hash.as_deref()), ("C:\\art\\photo.png", "photo.png", None));
let new: ImageObject =
serde_json::from_str(r#"{"key":"k","width":2,"height":1,"xf":[1,0,0,1,0,0],"link":{"path":"/a/b.png","size":9,"page":2}}"#).unwrap();
assert_eq!(new.link, Some(LinkInfo { size: Some(9), page: Some(2), ..LinkInfo::new("/a/b.png") }));
let none: ImageObject = serde_json::from_str(r#"{"key":"k","width":2,"height":1,"xf":[1,0,0,1,0,0]}"#).unwrap();
assert_eq!(none.link, None);
// Written as an object, with only what is known.
let v = serde_json::to_value(&new).unwrap();
assert_eq!(v["link"], serde_json::json!({"path": "/a/b.png", "size": 9, "page": 2}));
}
#[test]
fn large_images_get_a_small_png_preview() {
let big = ImageBlob::new("image/png", png(600, 300)).with_proxy();
let p = image::load_from_memory(big.proxy.as_ref().unwrap()).unwrap();
assert_eq!((p.width(), p.height()), (256, 128));
assert!(!big.is_proxy(), "the bytes are the full image");
assert!(ImageBlob::new("image/png", png(40, 20)).with_proxy().proxy.is_none(), "small images keep their pixels");
assert!(ImageBlob::new("image/png", vec![1, 2, 3]).with_proxy().proxy.is_none(), "undecodable");
}
#[test]
fn only_blobs_no_embedded_image_shows_are_linked_only() {
let mut d = Document::new(100.0, 100.0);
for k in ["a", "b", "c"] {
d.images.insert(k.into(), ImageBlob::new("image/png", png(300, 10)).with_proxy());
}
image(&mut d, "a", Some(LinkInfo::new("/a.png")));
image(&mut d, "b", Some(LinkInfo::new("/b.png")));
image(&mut d, "b", None);
image(&mut d, "c", None);
assert_eq!(d.linked_only_images().into_iter().collect::<Vec<_>>(), ["a"]);
}
}
+87 -38
View File
@@ -162,6 +162,7 @@ pub fn lerp_color(a: &Color, b: &Color, t: f32) -> Color {
match (*a, *b) {
(Color::Cmyk { c, m, y, k }, Color::Cmyk { c: c2, m: m2, y: y2, k: k2 }) => Color::cmyk(l(c, c2), l(m, m2), l(y, y2), l(k, k2)),
(Color::Gray { k }, Color::Gray { k: k2 }) => Color::gray(l(k, k2)),
(Color::Lab { l: l1, a, b }, Color::Lab { l: l2, a: a2, b: b2 }) => Color::lab(l(l1, l2), l(a, a2), l(b, b2)),
_ => a.lerp(b, t),
}
}
@@ -195,6 +196,7 @@ fn lerp_gradient(a: &GradientPaint, b: &GradientPaint, t: f32) -> Option<Gradien
g.start = ga.start.lerp(gb.start, t as f64);
g.end = ga.end.lerp(gb.end, t as f64);
g.aspect = ga.aspect + (gb.aspect - ga.aspect) * t as f64;
g.focal = (ga.focal.is_some() || gb.focal.is_some()).then(|| ga.focal_point().lerp(gb.focal_point(), t as f64));
out.geom = Some(g);
} else {
out.geom = None;
@@ -464,11 +466,7 @@ impl Spine {
if pts.len() < 2 {
return None;
}
let mut cum = vec![0.0];
for w in pts.windows(2) {
cum.push(cum.last().unwrap() + w[0].distance(w[1]));
}
Some(Self { pts, cum })
Some(Self { cum: cumulative_lengths(&pts), pts })
}
pub fn length(&self) -> f64 {
*self.cum.last().unwrap_or(&0.0)
@@ -637,6 +635,18 @@ fn poly_len(c: &CubicBez) -> f64 {
c.p0.distance(c.p1) + c.p1.distance(c.p2) + c.p2.distance(c.p3)
}
/// Running length along a polyline: `0, |p0p1|, |p0p1| + |p1p2|, …` (one entry per point).
fn cumulative_lengths(pts: &[Point]) -> Vec<f64> {
let mut total = 0.0;
let mut cum = Vec::with_capacity(pts.len());
cum.push(0.0);
for w in pts.windows(2) {
total += w[0].distance(w[1]);
cum.push(total);
}
cum
}
/// Map every point of `path` through the non-linear function `f`. Segments are split into pieces
/// no longer than about `max_piece` (up to 64 per segment) and their control points mapped, which
/// approximates the image curve to O(h²). Closedness and subpath structure are preserved.
@@ -660,7 +670,9 @@ pub fn map_nonlinear(path: &PathData, max_piece: f64, f: impl Fn(Point) -> Point
let k = ((poly_len(&c) / max_piece).ceil() as usize).clamp(1, 64);
for j in 0..k {
let sub = c.subsegment((j as f64 / k as f64)..((j + 1) as f64 / k as f64));
res.last_mut().unwrap().h_out = f(sub.p1);
if let Some(last) = res.last_mut() {
last.h_out = f(sub.p1);
}
if j + 1 < k {
res.push(Anchor { p: f(sub.p3), h_in: f(sub.p2), h_out: f(sub.p3), kind: Default::default() });
} else {
@@ -671,8 +683,9 @@ pub fn map_nonlinear(path: &PathData, max_piece: f64, f: impl Fn(Point) -> Point
}
if let Some(h) = pending_in
&& sp.closed
&& let Some(first) = res.first_mut()
{
res[0].h_in = h;
first.h_in = h;
}
let anchors = res.into_iter().map(|a| Anchor::with_handles(a.p, a.h_in, a.h_out)).collect();
subs.push(SubPath::new(anchors, sp.closed));
@@ -702,11 +715,8 @@ fn resample(poly: &[Point], m: usize) -> Vec<Point> {
if poly.len() == 1 {
return vec![poly[0]; m];
}
let mut cum = vec![0.0];
for w in poly.windows(2) {
cum.push(cum.last().unwrap() + w[0].distance(w[1]));
}
let total = *cum.last().unwrap();
let cum = cumulative_lengths(poly);
let total = cum.last().copied().unwrap_or(0.0);
let mut out = Vec::with_capacity(m);
let mut i = 0;
for k in 0..m {
@@ -747,7 +757,10 @@ impl Coons {
let r = path.bounds()?;
let tol = (r.width() + r.height()).max(1e-6) / 2000.0;
let mut poly = flatten_subpath(sp, tol);
if poly.len() > 1 && poly[0].distance(*poly.last().unwrap()) < 1e-9 {
if poly.len() > 1
&& let (Some(a), Some(b)) = (poly.first(), poly.last())
&& a.distance(*b) < 1e-9
{
poly.pop();
}
if poly.len() < 3 {
@@ -812,6 +825,12 @@ impl Coons {
// Gradient meshes
// =====================================================================================
/// `0, 1/n, …, 1` for `n` (clamped to 1..=200) even steps.
fn even_steps(n: u32) -> Vec<f64> {
let n = n.clamp(1, 200);
(0..=n).map(|i| i as f64 / n as f64).collect()
}
impl GradientMesh {
pub fn idx(&self, r: usize, c: usize) -> usize {
r * (self.cols as usize + 1) + c
@@ -822,43 +841,73 @@ impl GradientMesh {
/// A mesh over surface `s` (u, v ∈ [0,1]) with handles from its partial derivatives.
pub fn from_surface(rows: u32, cols: u32, s: &dyn Fn(f64, f64) -> Point, color: &dyn Fn(f64, f64) -> Color) -> Self {
let (rows, cols) = (rows.clamp(1, 200), cols.clamp(1, 200));
let (du, dv) = (1.0 / cols as f64, 1.0 / rows as f64);
let (us, vs) = (even_steps(cols), even_steps(rows));
Self::from_grid(&us, &vs, s, &|r, c, _| (color(us[c], vs[r]), 1.0))
}
/// A mesh over surface `s` (u, v ∈ [0,1]) whose column lines sit at `us` and row lines at `vs`
/// (ascending, at least two each; equal neighbours make a patch of no width, a sharp colour
/// change), with handles from its partial derivatives. `color(row, col, point)` gives each
/// point its colour and opacity.
pub fn from_grid(us: &[f64], vs: &[f64], s: &dyn Fn(f64, f64) -> Point, color: &dyn Fn(usize, usize, Point) -> (Color, f32)) -> Self {
let (rows, cols) = (vs.len().saturating_sub(1), us.len().saturating_sub(1));
let eps = 1e-3;
let mut points = Vec::with_capacity(((rows + 1) * (cols + 1)) as usize);
for r in 0..=rows {
for c in 0..=cols {
let (u, v) = (c as f64 * du, r as f64 * dv);
let mut points = Vec::with_capacity(us.len() * vs.len());
for (r, &v) in vs.iter().enumerate() {
for (c, &u) in us.iter().enumerate() {
let p = s(u, v);
let d_u = (s((u + eps).min(1.0), v) - s((u - eps).max(0.0), v)) / ((u + eps).min(1.0) - (u - eps).max(0.0));
let d_v = (s(u, (v + eps).min(1.0)) - s(u, (v - eps).max(0.0))) / ((v + eps).min(1.0) - (v - eps).max(0.0));
let hu = d_u * (du / 3.0);
let hv = d_v * (dv / 3.0);
// Outward handles on the border are unused: keep them at the point.
let z = Vec2::ZERO;
let handles =
[if c < cols { hu } else { z }, if c > 0 { -hu } else { z }, if r < rows { hv } else { z }, if r > 0 { -hv } else { z }];
points.push(MeshPoint { p, color: color(u, v), opacity: 1.0, handles });
// A third of the way to the neighbouring line along the tangent; outward handles on
// the border are unused, so they stay at the point.
let h = |d: Vec2, from: f64, to: Option<&f64>| to.map_or(Vec2::ZERO, |to| d * ((to - from) / 3.0));
let handles = [
h(d_u, u, us.get(c + 1)),
h(d_u, u, c.checked_sub(1).map(|i| &us[i])),
h(d_v, v, vs.get(r + 1)),
h(d_v, v, r.checked_sub(1).map(|i| &vs[i])),
];
let (color, opacity) = color(r, c, p);
points.push(MeshPoint { p, color, opacity, handles });
}
}
Self { rows, cols, points }
Self { rows: rows as u32, cols: cols as u32, points }
}
/// Create Gradient Mesh for a path: the outline split at its corners, coloured per `appearance`.
pub fn for_path(path: &PathData, rows: u32, cols: u32, base: Color, appearance: MeshAppearance, highlight: f64) -> Option<Self> {
let mut m = Self::for_path_with(path, rows, cols, &|_| (base, 1.0))?;
m.highlight(appearance, highlight);
Some(m)
}
/// Create Gradient Mesh for a path: the outline split at its corners, each point taking the
/// colour and opacity `color_at` gives at its position (a gradient fill's, say).
pub fn for_path_with(path: &PathData, rows: u32, cols: u32, color_at: &dyn Fn(Point) -> (Color, f32)) -> Option<Self> {
let coons = Coons::from_path(path)?;
Some(Self::from_grid(&even_steps(cols), &even_steps(rows), &|u, v| coons.eval(u, v), &|_, _, p| color_at(p)))
}
/// Create Gradient Mesh → Appearance: lighten the points towards white, to the centre or to
/// the edges, by at most `highlight` %.
pub fn highlight(&mut self, appearance: MeshAppearance, highlight: f64) {
let h = (highlight / 100.0).clamp(0.0, 1.0) as f32;
let color = |u: f64, v: f64| -> Color {
let d = ((u - 0.5).abs().max((v - 0.5).abs()) * 2.0) as f32; // 0 centre … 1 edge
let w = match appearance {
MeshAppearance::Flat => 0.0,
MeshAppearance::ToCenter => (1.0 - d) * h,
MeshAppearance::ToEdge => d * h,
};
if w > 0.0 { lerp_color(&base, &Color::WHITE, w) } else { base }
};
let s = |u: f64, v: f64| coons.eval(u, v);
Some(Self::from_surface(rows, cols, &s, &color))
let (rows, cols) = (self.rows as usize, self.cols as usize);
for r in 0..=rows {
for c in 0..=cols {
let (u, v) = (c as f64 / cols as f64, r as f64 / rows as f64);
let d = ((u - 0.5).abs().max((v - 0.5).abs()) * 2.0) as f32; // 0 centre … 1 edge
let w = match appearance {
MeshAppearance::Flat => 0.0,
MeshAppearance::ToCenter => (1.0 - d) * h,
MeshAppearance::ToEdge => d * h,
};
if w > 0.0 {
let i = self.idx(r, c);
self.points[i].color = lerp_color(&self.points[i].color, &Color::WHITE, w);
}
}
}
}
/// Horizontal edge from (r, c) to (r, c+1).
+367
View File
@@ -0,0 +1,367 @@
//! Printer's marks drawn as art: the trim marks of Object → Create Trim Marks and Effect → Crop
//! Marks, stroked in the Registration colour so that they print on every plate, and the printer's
//! marks around a printed page ([`PrinterMarks`]: PDF export's Marks and Bleeds, and print).
use std::sync::Arc;
use serde::{Deserialize, Serialize};
use vectorcraft_color::{Color, Paint};
use vectorcraft_geom::{Point, Rect, shapes};
use crate::{Appearance, CharStyle, Node, NodeId, NodeKind, TextObject};
/// Trim mark style (the preference `japaneseCropMarks` picks Japanese).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum MarkStyle {
/// One line per edge at each corner, set off from the trim box.
#[default]
Roman,
/// Double lines at each corner (the trim and the bleed edges) and centre marks on each side.
Japanese,
}
impl MarkStyle {
pub fn id(self) -> &'static str {
match self {
MarkStyle::Roman => "roman",
MarkStyle::Japanese => "japanese",
}
}
/// Parse an id, ignoring case.
pub fn parse(s: &str) -> Option<Self> {
[MarkStyle::Roman, MarkStyle::Japanese].into_iter().find(|m| m.id().eq_ignore_ascii_case(s))
}
}
/// Trim marks around a rectangle (the trim box).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct TrimMarks {
pub style: MarkStyle,
/// Roman: the gap between the trim box and the marks.
pub offset: f64,
/// How long each mark is.
pub length: f64,
/// Japanese: the bleed, between the trim lines and the outer lines (3 mm).
pub bleed: f64,
/// Stroke weight.
pub weight: f64,
}
impl Default for TrimMarks {
fn default() -> Self {
Self { style: MarkStyle::Roman, offset: 9.0, length: 18.0, bleed: 3.0 * 72.0 / 25.4, weight: 0.3 }
}
}
impl TrimMarks {
/// The default marks of `style`.
pub fn of(style: MarkStyle) -> Self {
Self { style, ..Default::default() }
}
/// How far the marks reach outside the trim box.
pub fn reach(&self) -> f64 {
let gap = match self.style {
MarkStyle::Roman => self.offset,
MarkStyle::Japanese => self.bleed,
};
gap + self.length + self.weight
}
/// The marks' lines around `r`.
pub fn lines(&self, r: Rect) -> Vec<(Point, Point)> {
let (l, mut out) = (self.length, vec![]);
// Each corner with its outward directions.
let corners = [(r.x0, r.y0, -1.0, -1.0), (r.x1, r.y0, 1.0, -1.0), (r.x1, r.y1, 1.0, 1.0), (r.x0, r.y1, -1.0, 1.0)];
match self.style {
MarkStyle::Roman => {
let o = self.offset;
for (x, y, sx, sy) in corners {
out.push((Point::new(x + sx * o, y), Point::new(x + sx * (o + l), y)));
out.push((Point::new(x, y + sy * o), Point::new(x, y + sy * (o + l))));
}
}
MarkStyle::Japanese => {
let b = self.bleed;
for (x, y, sx, sy) in corners {
// The trim lines, outside the bleed, and the bleed lines meeting at its corner.
out.push((Point::new(x + sx * b, y), Point::new(x + sx * (b + l), y)));
out.push((Point::new(x, y + sy * b), Point::new(x, y + sy * (b + l))));
out.push((Point::new(x, y + sy * b), Point::new(x + sx * (b + l), y + sy * b)));
out.push((Point::new(x + sx * b, y), Point::new(x + sx * b, y + sy * (b + l))));
}
// A cross outside the bleed at the middle of each side.
let c = r.center();
for (p, dx, dy) in [
(Point::new(c.x, r.y0), 0.0, -1.0),
(Point::new(r.x1, c.y), 1.0, 0.0),
(Point::new(c.x, r.y1), 0.0, 1.0),
(Point::new(r.x0, c.y), -1.0, 0.0),
] {
let at = |d: f64| Point::new(p.x + dx * d, p.y + dy * d);
out.push((at(b), at(b + l)));
let m = at(b + l / 2.0);
out.push((Point::new(m.x - dy * l / 2.0, m.y - dx * l / 2.0), Point::new(m.x + dy * l / 2.0, m.y + dx * l / 2.0)));
}
}
}
out
}
/// The marks around `r` as a group named "Trim Marks" of lines stroked in Registration, with
/// ids from `alloc` (the group's last).
pub fn group(&self, r: Rect, alloc: &mut dyn FnMut() -> NodeId) -> Node {
let ap = Appearance::basic(Paint::None, Paint::registration(), self.weight);
let children = self.lines(r).into_iter().map(|(a, b)| Arc::new(Node::path(alloc(), shapes::line(a, b), ap.clone()))).collect();
let mut g = Node::group(alloc(), children);
g.name = Some("Trim Marks".into());
g
}
}
/// `r` grown by `[top, bottom, left, right]` (a bleed, or how far marks reach).
pub fn outset(r: Rect, [top, bottom, left, right]: [f64; 4]) -> Rect {
Rect::new(r.x0 - left, r.y0 - top, r.x1 + right, r.y1 + bottom)
}
/// The printer's marks around a printed page's trim box (its artboard): trim marks, a
/// registration target at the middle of each side, colour bars along the top and the page
/// information line below the bottom marks. They sit in a band [`PrinterMarks::LENGTH`] deep that
/// starts at the offset from the trim box (outside the bleed), and are drawn in Registration, the
/// colour bars aside.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PrinterMarks {
pub trim: bool,
pub registration: bool,
pub color_bars: bool,
pub page_info: bool,
pub style: MarkStyle,
/// Stroke weight of the trim marks and registration targets.
pub weight: f64,
/// Roman: the gap between the trim box and the marks (at least the bleed).
pub offset: f64,
}
/// Where the printer's marks of one page go ([`PrinterMarks::layout`]).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct MarksLayout {
/// Lines stroked in Registration: the trim marks and the targets' cross hairs.
pub lines: Vec<(Point, Point)>,
/// Registration target rings (centre, radius), stroked in Registration.
pub rings: Vec<(Point, f64)>,
/// The colour bars: each patch and its paint.
pub patches: Vec<(Rect, Paint)>,
/// The page information line's baseline start.
pub info: Option<Point>,
}
impl PrinterMarks {
/// How deep the band of marks is (the trim marks' length).
pub const LENGTH: f64 = 18.0;
/// The side of a colour bar patch.
pub const PATCH: f64 = 10.0;
/// The page information's type size.
pub const INFO_SIZE: f64 = 7.0;
/// Any mark is on.
pub fn any(&self) -> bool {
self.trim || self.registration || self.color_bars || self.page_info
}
/// The trim marks for a page with `bleed` (`[top, bottom, left, right]`): Roman ones outside
/// the bleed, Japanese ones with their outer lines on the bleed (3 mm without one).
pub fn trim_marks(&self, bleed: [f64; 4]) -> TrimMarks {
let most = bleed.iter().copied().fold(0.0, f64::max);
let d = TrimMarks::of(self.style);
TrimMarks { offset: self.offset.max(most), length: Self::LENGTH, bleed: if most > 0.0 { most } else { d.bleed }, weight: self.weight, ..d }
}
/// The distance from the trim box to the band of marks.
fn gap(&self, bleed: [f64; 4]) -> f64 {
let t = self.trim_marks(bleed);
match self.style {
MarkStyle::Roman => t.offset,
MarkStyle::Japanese => t.bleed,
}
}
/// How far the marks reach outside the trim box, `[top, bottom, left, right]` (0 without
/// marks): the band on every side, and the page information below it.
pub fn reach(&self, bleed: [f64; 4]) -> [f64; 4] {
if !self.any() {
return [0.0; 4];
}
let band = self.gap(bleed) + Self::LENGTH + self.weight;
let bottom = if self.page_info { band + Self::INFO_SIZE * 1.6 } else { band };
[band, bottom, band, band]
}
/// Where the marks around trim box `trim` go, for a page with `bleed` and the spot inks
/// `spots` (their colour bar patches follow the process ones).
pub fn layout(&self, trim: Rect, bleed: [f64; 4], spots: &[Paint]) -> MarksLayout {
let mut out = MarksLayout::default();
if !self.any() {
return out;
}
let (gap, l) = (self.gap(bleed), Self::LENGTH);
if self.trim {
out.lines = self.trim_marks(bleed).lines(trim);
}
let c = trim.center();
// The middle of the band.
let mid = gap + l / 2.0;
if self.registration {
let sides = [
(Point::new(c.x, trim.y0), 0.0, -1.0),
(Point::new(trim.x1, c.y), 1.0, 0.0),
(Point::new(c.x, trim.y1), 0.0, 1.0),
(Point::new(trim.x0, c.y), -1.0, 0.0),
];
for (p, dx, dy) in sides {
let at = Point::new(p.x + dx * mid, p.y + dy * mid);
out.rings.push((at, l / 3.0));
out.rings.push((at, l / 6.0));
// Japanese trim marks draw this cross already.
if !(self.trim && self.style == MarkStyle::Japanese) {
out.lines.push((Point::new(at.x - l / 2.0, at.y), Point::new(at.x + l / 2.0, at.y)));
out.lines.push((Point::new(at.x, at.y - l / 2.0), Point::new(at.x, at.y + l / 2.0)));
}
}
}
if self.color_bars {
let s = Self::PATCH;
let y = trim.y0 - mid - s / 2.0;
let cmyk = |c, m, y, k| Paint::solid(Color::cmyk(c, m, y, k));
// Solid inks, their overprints and the spot inks left of the top target; black tints
// right of it. Patches that don't fit are left out.
let solids = [
cmyk(1.0, 0.0, 0.0, 0.0),
cmyk(0.0, 1.0, 0.0, 0.0),
cmyk(0.0, 0.0, 1.0, 0.0),
cmyk(0.0, 0.0, 0.0, 1.0),
cmyk(1.0, 1.0, 0.0, 0.0),
cmyk(1.0, 0.0, 1.0, 0.0),
cmyk(0.0, 1.0, 1.0, 0.0),
cmyk(1.0, 1.0, 1.0, 0.0),
];
let tints: Vec<Paint> = (1..=10).map(|i| cmyk(0.0, 0.0, 0.0, i as f32 / 10.0)).collect();
let clear = l / 2.0 + 2.0;
let rows = [(solids.iter().chain(spots).cloned().collect(), trim.x0 + s / 2.0, c.x - clear), (tints, c.x + clear, trim.x1 - s / 2.0)];
for (paints, from, to) in rows {
let fits = ((to - from) / s).floor().max(0.0) as usize;
for (i, paint) in paints.into_iter().take(fits).enumerate() {
let x = from + i as f64 * s;
out.patches.push((Rect::new(x, y, x + s, y + s), paint));
}
}
}
if self.page_info {
out.info = Some(Point::new(trim.x0, trim.y1 + gap + l + self.weight + Self::INFO_SIZE * 1.1));
}
out
}
/// The marks around `trim` as a group named "Printer's Marks", with ids from `alloc` (the
/// group's last): the colour bar patches, then Registration lines and rings, then `info` as
/// point type in Registration.
pub fn art(&self, trim: Rect, bleed: [f64; 4], spots: &[Paint], info: &str, alloc: &mut dyn FnMut() -> NodeId) -> Node {
let m = self.layout(trim, bleed, spots);
let reg = Appearance::basic(Paint::None, Paint::registration(), self.weight);
let shape = |id, path, ap: &Appearance| Arc::new(Node::path(id, path, ap.clone()));
let mut children: Vec<Arc<Node>> =
m.patches.into_iter().map(|(r, p)| shape(alloc(), shapes::rectangle(r), &Appearance::basic(p, Paint::None, 0.0))).collect();
children.extend(m.lines.into_iter().map(|(a, b)| shape(alloc(), shapes::line(a, b), &reg)));
children.extend(m.rings.into_iter().map(|(c, r)| shape(alloc(), shapes::ellipse(Rect::from_center_size(c, (2.0 * r, 2.0 * r))), &reg)));
if let Some(at) = m.info.filter(|_| !info.is_empty()) {
let style = CharStyle { size: Self::INFO_SIZE, fill: Paint::registration(), ..Default::default() };
children.push(Arc::new(Node::new(alloc(), NodeKind::Text(Box::new(TextObject::point(at, info, style))))));
}
let mut g = Node::group(alloc(), children);
g.name = Some("Printer's Marks".into());
g
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn roman_marks_sit_off_the_corners_and_japanese_ones_are_doubled() {
let r = Rect::new(0.0, 0.0, 100.0, 50.0);
let roman = TrimMarks::default().lines(r);
assert_eq!(roman.len(), 8);
assert!(roman.iter().all(|(a, b)| !r.contains(*a) && !r.contains(*b)));
assert_eq!(roman[0], (Point::new(-9.0, 0.0), Point::new(-27.0, 0.0)));
let jp = TrimMarks::of(MarkStyle::Japanese);
let lines = jp.lines(r);
assert_eq!(lines.len(), 24, "four lines per corner and a cross per side");
// Two horizontal lines at the top-left corner: the trim line and the bleed line.
let tl: Vec<f64> = lines[..4].iter().filter(|(a, b)| a.y == b.y).map(|(a, _)| a.y).collect();
assert_eq!(tl.len(), 2);
assert!((tl[0] - 0.0).abs() < 1e-9 && (tl[1] + jp.bleed).abs() < 1e-9, "{tl:?}");
let mut n = 0;
let g = jp.group(r, &mut || {
n += 1;
NodeId(n)
});
assert_eq!((g.children().unwrap().len(), g.id), (24, NodeId(25)));
assert!(g.children().unwrap()[0].appearance.stroke().unwrap().paint.is_registration());
assert_eq!(MarkStyle::parse("Japanese"), Some(MarkStyle::Japanese));
}
fn all(style: MarkStyle) -> PrinterMarks {
PrinterMarks { trim: true, registration: true, color_bars: true, page_info: true, style, weight: 0.25, offset: 6.0 }
}
#[test]
fn printer_marks_sit_in_a_band_outside_the_trim_box() {
let trim = Rect::new(0.0, 0.0, 200.0, 100.0);
let m = all(MarkStyle::Roman);
let lay = m.layout(trim, [0.0; 4], &[]);
// Golden positions: the band starts at the 6 pt offset and is 18 pt deep.
assert_eq!(lay.lines[0], (Point::new(-6.0, 0.0), Point::new(-24.0, 0.0)), "top-left trim mark");
assert_eq!(lay.rings[..2], [(Point::new(100.0, -15.0), 6.0), (Point::new(100.0, -15.0), 3.0)], "top target");
assert_eq!(lay.lines[8..10], [(Point::new(91.0, -15.0), Point::new(109.0, -15.0)), (Point::new(100.0, -24.0), Point::new(100.0, -6.0))]);
assert_eq!(lay.patches[0], (Rect::new(5.0, -20.0, 15.0, -10.0), Paint::solid(Color::cmyk(1.0, 0.0, 0.0, 0.0))), "cyan first");
assert_eq!(lay.patches[8].0, Rect::new(111.0, -20.0, 121.0, -10.0), "black tints right of the target");
assert_eq!(lay.patches.len(), 8 + 8, "as many patches as fit each half");
assert_eq!(lay.info, Some(Point::new(0.0, 100.0 + 24.25 + 7.7)));
let reach = m.reach([0.0; 4]);
assert_eq!(reach, [24.25, 24.25 + 11.2, 24.25, 24.25]);
// Everything lies outside the trim box and inside the sheet the reach makes.
let sheet = outset(trim, reach);
let points = lay.lines.iter().flat_map(|(a, b)| [*a, *b]).chain(lay.rings.iter().map(|(c, _)| *c));
for p in points.chain(lay.patches.iter().flat_map(|(r, _)| [r.origin(), Point::new(r.x1, r.y1)])) {
assert!(sheet.contains(p) && !trim.inflate(-1e-9, -1e-9).contains(p), "{p:?}");
}
// A bleed pushes the marks out; no marks reach nothing.
assert_eq!(m.layout(trim, [9.0, 0.0, 0.0, 0.0], &[]).lines[0], (Point::new(-9.0, 0.0), Point::new(-27.0, 0.0)));
assert_eq!(PrinterMarks { trim: false, registration: false, color_bars: false, page_info: false, ..m }.reach([9.0; 4]), [0.0; 4]);
}
#[test]
fn japanese_printer_marks_share_the_centre_crosses_and_draw_as_art() {
let trim = Rect::new(0.0, 0.0, 200.0, 100.0);
let m = all(MarkStyle::Japanese);
let lay = m.layout(trim, [0.0; 4], &[]);
assert_eq!(lay.lines.len(), 24, "the targets add rings to the trim marks' centre crosses");
let b = TrimMarks::default().bleed;
assert_eq!(lay.rings[0].0, Point::new(100.0, -(b + 9.0)));
let spot = Paint::Solid { color: Color::cmyk(0.0, 0.5, 1.0, 0.0), swatch: Some("Ink".into()), tint: 1.0 };
let wide = Rect::new(0.0, 0.0, 400.0, 100.0);
assert_eq!(m.layout(wide, [0.0; 4], std::slice::from_ref(&spot)).patches[8].1, spot, "spot inks follow the process patches");
let mut n = 0;
let g = m.art(trim, [0.0; 4], &[], "Page 1", &mut || {
n += 1;
NodeId(n)
});
let kids = g.children().unwrap();
let NodeKind::Text(t) = &kids.last().unwrap().kind else { panic!("the page information is type") };
assert_eq!((t.plain_text().as_str(), t.first_style().fill.is_registration()), ("Page 1", true));
let strokes: Vec<_> = kids.iter().filter_map(|k| k.appearance.stroke()).filter(|s| !s.paint.is_none()).collect();
assert!(strokes.len() == 24 + 8 && strokes.iter().all(|s| s.paint.is_registration()), "lines and rings in Registration");
}
}
+151
View File
@@ -0,0 +1,151 @@
//! File → File Info: the document's descriptive metadata (author, description, keywords, rating,
//! copyright) and its created and modified dates, which the SVG, PDF and PNG writers carry. The
//! document title is [`crate::Document::title`]. Every field is defaulted, so documents saved
//! before File Info existed load unchanged.
use serde::{Deserialize, Serialize};
/// File Info → Copyright Status.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum CopyrightStatus {
#[default]
Unknown,
Copyrighted,
PublicDomain,
}
impl CopyrightStatus {
pub const ALL: [CopyrightStatus; 3] = [CopyrightStatus::Unknown, CopyrightStatus::Copyrighted, CopyrightStatus::PublicDomain];
pub fn id(self) -> &'static str {
match self {
CopyrightStatus::Unknown => "unknown",
CopyrightStatus::Copyrighted => "copyrighted",
CopyrightStatus::PublicDomain => "publicDomain",
}
}
pub fn label(self) -> &'static str {
match self {
CopyrightStatus::Unknown => "Unknown",
CopyrightStatus::Copyrighted => "Copyrighted",
CopyrightStatus::PublicDomain => "Public Domain",
}
}
pub fn parse(s: &str) -> Option<Self> {
Self::ALL.into_iter().find(|c| c.id().eq_ignore_ascii_case(s) || c.label().eq_ignore_ascii_case(s))
}
}
/// Highest File Info rating (stars).
pub const MAX_RATING: u8 = 5;
/// File → File Info.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct DocMetadata {
pub author: String,
/// The author's position or job title.
pub author_title: String,
pub description: String,
/// Keywords, each once, in the order they were added.
pub keywords: Vec<String>,
/// 0 (unrated) to [`MAX_RATING`] stars.
pub rating: u8,
pub copyright_status: CopyrightStatus,
pub copyright_notice: String,
/// Where to read more about the copyright.
pub copyright_url: String,
/// When the document was created, as Unix seconds (UTC).
pub created: Option<i64>,
/// When the document was last saved, as Unix seconds (UTC).
pub modified: Option<i64>,
}
impl DocMetadata {
/// The PNG text entries (registered keywords where one fits) for a document titled `title`:
/// only the non-empty ones.
pub fn png_text<'a>(&'a self, title: &'a str) -> Vec<(&'static str, std::borrow::Cow<'a, str>)> {
let mut out: Vec<(&'static str, std::borrow::Cow<'a, str>)> = vec![];
let mut push = |k: &'static str, v: std::borrow::Cow<'a, str>| {
if !v.trim().is_empty() {
out.push((k, v));
}
};
push("Title", title.into());
push("Author", self.author.as_str().into());
push("Description", self.description.as_str().into());
push("Keywords", self.keywords.join(", ").into());
push("Copyright", self.copyright_notice.as_str().into());
push("Copyright URL", self.copyright_url.as_str().into());
push("Creation Time", self.created.map(iso8601).unwrap_or_default().into());
out
}
}
/// The current time as Unix seconds (UTC); `None` where the platform has no clock (the web build).
#[cfg(not(target_arch = "wasm32"))]
pub fn now_unix() -> Option<i64> {
use std::time::{SystemTime, UNIX_EPOCH};
SystemTime::now().duration_since(UNIX_EPOCH).ok().and_then(|d| i64::try_from(d.as_secs()).ok())
}
#[cfg(target_arch = "wasm32")]
pub fn now_unix() -> Option<i64> {
None
}
/// Unix seconds (UTC) → `[year, month, day, hour, minute, second]` (civil-from-days, proleptic
/// Gregorian; years clamped to 0–9999).
pub fn civil(t: i64) -> [i64; 6] {
// Clamp first so every step stays in range for any input.
let t = t.clamp(-62_167_219_200, 253_402_300_799);
let days = t.div_euclid(86_400);
let secs = t.rem_euclid(86_400);
let z = days + 719_468;
let era = z.div_euclid(146_097);
let doe = z - era * 146_097;
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let day = doy - (153 * mp + 2) / 5 + 1;
let month = if mp < 10 { mp + 3 } else { mp - 9 };
let year = yoe + era * 400 + i64::from(month <= 2);
[year.clamp(0, 9999), month, day, secs / 3600, secs / 60 % 60, secs % 60]
}
/// Unix seconds → `2026-10-05T14:03:00Z`.
pub fn iso8601(t: i64) -> String {
let [y, mo, d, h, mi, s] = civil(t);
format!("{y:04}-{mo:02}-{d:02}T{h:02}:{mi:02}:{s:02}Z")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn dates_and_statuses() {
assert_eq!(iso8601(0), "1970-01-01T00:00:00Z");
assert_eq!(iso8601(1_791_208_980), "2026-10-05T14:03:00Z");
assert_eq!(civil(i64::MIN)[0], 0);
assert_eq!(civil(i64::MAX)[0], 9999);
assert_eq!(CopyrightStatus::parse("Public Domain"), Some(CopyrightStatus::PublicDomain));
assert_eq!(CopyrightStatus::parse("publicdomain"), Some(CopyrightStatus::PublicDomain));
assert_eq!(CopyrightStatus::parse("maybe"), None);
}
#[test]
fn png_text_skips_empty_entries() {
let m = DocMetadata { author: "Ada".into(), keywords: vec!["a".into(), "b".into()], created: Some(0), ..Default::default() };
let t: Vec<(&str, String)> = m.png_text("Poster").into_iter().map(|(k, v)| (k, v.into_owned())).collect();
assert_eq!(
t,
[
("Title", "Poster".to_string()),
("Author", "Ada".into()),
("Keywords", "a, b".into()),
("Creation Time", "1970-01-01T00:00:00Z".into())
]
);
assert!(DocMetadata::default().png_text("").is_empty());
}
}
+280 -18
View File
@@ -138,6 +138,17 @@ impl LiveShape {
}
}
}
/// Divide live corner radii by `k`, the mean scale of a transform just applied, so the corners
/// keep their size (Scale Corners off). False when nothing changed.
pub fn keep_corners(&mut self, k: f64) -> bool {
match self {
LiveShape::Rectangle { radii, .. } if radii.iter().any(|r| *r > 0.0) && k > 1e-12 => {
radii.iter_mut().for_each(|r| *r /= k);
true
}
_ => false,
}
}
/// Rotation angle of the live shape in degrees (shown in the Properties panel).
pub fn angle_deg(&self) -> f64 {
match self {
@@ -150,6 +161,36 @@ impl LiveShape {
}
}
/// What a transform scales besides geometry, by its mean scale (the square root of its
/// determinant). `Scaling::default()` (and `false`) scales nothing else; `true` scales stroke
/// weights and dashes only. Transforms the user asks for take theirs from Scale Strokes & Effects
/// and Scale Corners.
#[derive(Clone, Copy, Debug, Default)]
pub struct Scaling {
/// Stroke weights, dash lengths and dash offsets scale.
pub strokes: bool,
/// With `strokes`: scales an effect's distance parameters (the effects catalogue's).
pub effects: Option<fn(&mut crate::Effect, f64)>,
/// Type keeps its character strokes' weight (they otherwise scale with the type).
pub keep_type_strokes: bool,
/// Live corner radii keep their size.
pub keep_corners: bool,
}
impl Scaling {
/// The mean scale of `a` when it scales (isn't 1): what strokes, effects and corners scale by.
pub fn factor(a: Affine) -> Option<f64> {
let k = a.determinant().abs().sqrt();
((k - 1.0).abs() > 1e-9).then_some(k)
}
}
impl From<bool> for Scaling {
fn from(strokes: bool) -> Self {
Self { strokes, ..Self::default() }
}
}
/// Embedded or linked raster image.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ImageObject {
@@ -159,8 +200,13 @@ pub struct ImageObject {
pub height: u32,
/// Maps pixel space (0..w, 0..h) into the document.
pub xf: Affine,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub link: Option<String>,
/// The file a linked image shows (File → Place with Link); `None`: embedded. Files saved
/// before links had details hold just the path.
#[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "crate::links::de_link")]
pub link: Option<crate::LinkInfo>,
/// Links panel → Placement Options: how a file read again takes this image's place.
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
pub placement: crate::links::PlacementOptions,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
@@ -282,6 +328,13 @@ pub struct Node {
/// that style's look: editing its appearance or transparency breaks the link.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub graphic_style: Option<u32>,
/// Attributes panel: centre point display, image map, URL and note (`None`: all defaults).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub attrs: Option<Box<ObjectAttributes>>,
/// Object → Slice → Make: the object is an object slice (its slice follows its bounds) with
/// these options.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub slice: Option<Box<crate::SliceOptions>>,
}
/// Opacity mask: the luminance of the mask art sets the object's opacity (white = opaque).
@@ -328,6 +381,8 @@ impl Node {
graph: None,
kind,
graphic_style: None,
attrs: None,
slice: None,
}
}
pub fn path(id: NodeId, path: PathData, appearance: Appearance) -> Self {
@@ -426,6 +481,30 @@ impl Node {
_ => None,
}
}
/// The path a path's or compound path's own strokes follow (a compound's members' together).
pub fn stroke_path(&self) -> Option<vectorcraft_geom::BezPath> {
match &self.kind {
NodeKind::Path { path, .. } => Some(path.to_bezpath()),
NodeKind::Compound { children, .. } => {
let mut bp = vectorcraft_geom::BezPath::new();
children.iter().filter_map(|c| c.path_data()).for_each(|pd| bp.extend(pd.to_bezpath()));
Some(bp)
}
_ => None,
}
}
/// A quick box round everything the object can paint, for culling clicks: paths and compound
/// paths grow their geometric bounds by the farthest their strokes can reach from any path
/// ([`Appearance::outset`]) instead of measuring along their shape.
pub fn reach_bounds(&self) -> Option<Rect> {
match &self.kind {
NodeKind::Path { .. } | NodeKind::Compound { .. } => {
let o = self.appearance.outset();
self.geometric_bounds().map(|b| b.inflate(o, o))
}
_ => self.visual_bounds(),
}
}
/// Geometric bounds (no stroke), recursively. Clip groups are bounded by their clip path.
pub fn geometric_bounds(&self) -> Option<Rect> {
match &self.kind {
@@ -449,11 +528,18 @@ impl Node {
NodeKind::Repeat(r) => r.bounds(),
}
}
/// Visual bounds (includes stroke outset).
/// Visual bounds: what the object paints, its strokes included (paths and compound paths
/// measure theirs along their own shape, see [`Appearance::stroked_bounds`]).
pub fn visual_bounds(&self) -> Option<Rect> {
match &self.kind {
NodeKind::Group { children, clip: true } | NodeKind::Layer { children, clip: true, .. } => {
children.first().and_then(|c| c.geometric_bounds())
// A clipping path that paints (see `clip_paint`) strokes over the clip edge.
let clip = children.first()?;
if matches!(clip.kind, NodeKind::Path { .. } | NodeKind::Compound { .. } | NodeKind::Text(_)) {
clip.visual_bounds()
} else {
clip.geometric_bounds()
}
}
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => {
// The container's own strokes paint around its members.
@@ -469,6 +555,10 @@ impl Node {
let o = crate::live::max_outset(content);
self.geometric_bounds().map(|b| b.inflate(o, o))
}
NodeKind::Path { .. } | NodeKind::Compound { .. } => {
let b = self.geometric_bounds()?;
Some(self.appearance.stroked_bounds(b, || self.stroke_path().unwrap_or_default()))
}
_ => {
let o = self.appearance.outset();
self.geometric_bounds().map(|b| b.inflate(o, o))
@@ -476,16 +566,23 @@ impl Node {
}
}
/// Apply an affine transform to the geometry (and gradients) of this node and its descendants.
/// `scale_strokes` also scales stroke weights by the transform's mean scale.
pub fn transform(&mut self, a: Affine, scale_strokes: bool) {
/// `scaling` says what else scales by the transform's mean scale (a bool: stroke weights
/// only, see [`Scaling`]).
pub fn transform(&mut self, a: Affine, scaling: impl Into<Scaling>) {
self.transform_scaled(a, &scaling.into());
}
fn transform_scaled(&mut self, a: Affine, sc: &Scaling) {
// Refitting an unplaced gradient only reproduces moves and uniform scales.
if !keeps_gradient_fit(a) {
self.pin_gradients();
}
if scale_strokes {
let det = a.determinant().abs().sqrt();
if (det - 1.0).abs() > 1e-9 {
self.appearance.scale_strokes(det);
let k = Scaling::factor(a);
if let Some(k) = k
&& sc.strokes
{
self.appearance.scale_strokes(k);
if let Some(f) = sc.effects {
self.appearance.scale_effects(k, f);
}
}
self.appearance.transform_gradients(a);
@@ -494,19 +591,33 @@ impl Node {
path.transform(a);
if let Some(l) = live {
l.transform(a);
if sc.keep_corners
&& let Some(k) = k
&& l.keep_corners(k)
{
*path = l.to_path();
}
}
}
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } | NodeKind::Compound { children, .. } => {
for c in children.iter_mut() {
Arc::make_mut(c).transform(a, scale_strokes);
Arc::make_mut(c).transform_scaled(a, sc);
}
}
NodeKind::Text(t) => {
t.transform(a);
// Character strokes scale with the type: undo that when strokes keep their weight.
if sc.keep_type_strokes
&& let Some(k) = k.filter(|k| *k > 1e-12)
{
t.scale_char_strokes(1.0 / k);
}
}
NodeKind::Text(t) => t.transform(a),
NodeKind::Image(im) => im.xf = a * im.xf,
NodeKind::SymbolInstance { xf, .. } => *xf = a * *xf,
NodeKind::Blend { children, spec } => {
for c in children.iter_mut() {
Arc::make_mut(c).transform(a, scale_strokes);
Arc::make_mut(c).transform_scaled(a, sc);
}
if let Some(s) = &mut spec.spine {
s.transform(a);
@@ -514,7 +625,7 @@ impl Node {
}
NodeKind::Envelope { content, kind, .. } => {
for c in content.iter_mut() {
Arc::make_mut(c).transform(a, scale_strokes);
Arc::make_mut(c).transform_scaled(a, sc);
}
match kind {
EnvelopeKind::Mesh { points, .. } => {
@@ -527,12 +638,12 @@ impl Node {
}
}
NodeKind::Mesh(m) => m.transform(a),
NodeKind::Repeat(r) => r.transform(a, scale_strokes),
NodeKind::Repeat(r) => r.transform(a, *sc),
}
if let Some(m) = &mut self.mask
&& m.linked
{
Arc::make_mut(&mut m.art).transform(a, scale_strokes);
Arc::make_mut(&mut m.art).transform_scaled(a, sc);
}
}
/// Visit this node and all descendants depth first (paint order).
@@ -574,7 +685,8 @@ impl Node {
let b = t.local_bounds();
return Some(if stroke { (&st.stroke, t.xf, crate::appearance::stroke_paint_bounds(b, st.stroke_width)) } else { (&st.fill, t.xf, b) });
}
let b = self.geometric_bounds()?;
// An object without bounds (an empty path) still shows its paints, fitted to an empty box.
let b = self.geometric_bounds().unwrap_or(Rect::ZERO);
if stroke {
self.appearance.stroke_at(item).map(|s| (&s.paint, Affine::IDENTITY, s.paint_bounds(b)))
} else {
@@ -675,6 +787,54 @@ impl Node {
_ => Some((unite(&shapes), FillRule::NonZero)),
}
}
/// What this object paints as the clipping path of a clip group, shared by the renderer and
/// the SVG and PDF writers: its fills, painted behind the clipped art, and its strokes, painted
/// over it (unclipped). Each part is this object keeping only those appearance items (type:
/// also only its characters' fills or strokes); `None` where it paints nothing, as right after
/// Make Clipping Mask. Only paths, compound paths and type paint as clipping paths.
pub fn clip_paint(&self) -> ClipPaint {
use crate::appearance::AppearanceItem;
let runs = match &self.kind {
NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } => None,
NodeKind::Text(t) => Some(&t.runs),
_ => return ClipPaint::default(),
};
let paints = |fill: bool| {
let item = |i: &AppearanceItem| match i {
AppearanceItem::Fill(f) => fill && f.visible && !f.paint.is_none(),
AppearanceItem::Stroke(s) => !fill && s.visible && !s.paint.is_none() && s.width > 0.0,
};
let run = |r: &crate::text::TextRun| if fill { !r.style.fill.is_none() } else { !r.style.stroke.is_none() && r.style.stroke_width > 0.0 };
self.appearance.items.iter().any(item) || runs.is_some_and(|rs| rs.iter().any(run))
};
let part = |fill: bool| {
paints(fill).then(|| {
let mut n = self.clone();
for i in (0..n.appearance.items.len()).rev() {
if matches!(n.appearance.items[i], AppearanceItem::Fill(_)) != fill {
n.appearance.remove_item(i);
}
}
if let NodeKind::Text(t) = &mut n.kind {
for r in &mut t.runs {
*(if fill { &mut r.style.stroke } else { &mut r.style.fill }) = vectorcraft_color::Paint::None;
}
}
n
})
};
ClipPaint { fill: part(true), stroke: part(false) }
}
}
/// What a clipping path paints ([`Node::clip_paint`]).
#[derive(Clone, Debug, Default)]
pub struct ClipPaint {
/// The clipping path with only its fills: painted behind the clipped art (inside the clip).
pub fill: Option<Node>,
/// The clipping path with only its strokes: painted over the clipped art, not clipped.
pub stroke: Option<Node>,
}
/// Knockout Group state of a container (the Transparency panel's three-state checkbox). In a
@@ -825,6 +985,99 @@ impl Node {
}
}
/// Window → Attributes: an object's settings that don't change how it prints.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ObjectAttributes {
/// Show Center / Don't Show Center (`None`: the object kind's default, [`Node::shows_center`]).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub show_center: Option<bool>,
/// Image Map: the clickable area the URL covers in web output.
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
pub image_map: ImageMap,
/// URL the object links to (SVG `<a href>`; empty: none).
#[serde(default, skip_serializing_if = "String::is_empty")]
pub url: String,
/// The note shown in the Attributes panel.
#[serde(default, skip_serializing_if = "String::is_empty")]
pub note: String,
}
/// The Attributes panel's Image Map shapes.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ImageMap {
#[default]
None,
Rectangle,
Polygon,
}
impl ImageMap {
pub const ALL: [ImageMap; 3] = [ImageMap::None, ImageMap::Rectangle, ImageMap::Polygon];
pub fn label(self) -> &'static str {
match self {
ImageMap::None => "None",
ImageMap::Rectangle => "Rectangle",
ImageMap::Polygon => "Polygon",
}
}
/// Parse a label or serialized name, ignoring case.
pub fn parse(s: &str) -> Option<Self> {
Self::ALL.into_iter().find(|m| m.label().eq_ignore_ascii_case(s))
}
}
impl Node {
/// The URL this object links to, if any.
pub fn url(&self) -> Option<&str> {
self.attrs.as_deref().map(|a| a.url.as_str()).filter(|u| !u.is_empty())
}
/// Whether the canvas shows this object's centre point when it is selected: as set in the
/// Attributes panel, else [`Self::shows_center_by_default`].
pub fn shows_center(&self) -> bool {
self.attrs.as_deref().and_then(|a| a.show_center).unwrap_or_else(|| self.shows_center_by_default())
}
/// Shapes drawn with the shape tools (live rectangles, ellipses and polygons) show their centre.
pub fn shows_center_by_default(&self) -> bool {
matches!(&self.kind, NodeKind::Path { live: Some(l), .. } if !matches!(l, LiveShape::Line { .. }))
}
/// Change this object's attributes with `f`; all-default attributes are dropped.
pub fn edit_attrs<R>(&mut self, f: impl FnOnce(&mut ObjectAttributes) -> R) -> R {
let mut a = self.attrs.take().unwrap_or_default();
let r = f(&mut a);
self.attrs = (*a != ObjectAttributes::default()).then_some(a);
r
}
}
impl Node {
/// Whether this object shows any transparency, itself or anything inside it: object, fill or
/// stroke opacity below 100%, a blend mode, an opacity mask, effects or transparent gradient
/// stops. Hidden objects show none.
pub fn shows_transparency(&self) -> bool {
use vectorcraft_color::Paint;
let see_through = |p: &Paint| matches!(p, Paint::Gradient(g) if g.gradient.stops.iter().any(|s| s.opacity < 1.0));
let effects = |fx: &[crate::Effect]| fx.iter().any(|e| e.visible);
self.visible
&& (self.opacity < 1.0
|| self.blend != BlendMode::Normal
|| self.mask.as_ref().is_some_and(|m| !m.disabled)
|| effects(&self.appearance.effects)
|| self
.appearance
.items
.iter()
.any(|i| i.visible() && (i.opacity() < 1.0 || i.blend() != BlendMode::Normal || see_through(i.paint()) || effects(i.effects())))
|| self.children().is_some_and(|ch| ch.iter().any(|c| c.shows_transparency())))
}
}
/// Is `a` a move plus a positive uniform scale (after which a refit gradient still matches)?
fn keeps_gradient_fit(a: Affine) -> bool {
let [m0, m1, m2, m3, _, _] = a.as_coeffs();
@@ -832,6 +1085,15 @@ fn keeps_gradient_fit(a: Affine) -> bool {
m0 > 0.0 && m1.abs() <= eps && m2.abs() <= eps && (m0 - m3).abs() <= eps
}
impl Node {
/// Whether a document point lies in this object's filled regions ([`Node::clip_shapes`]; true
/// everywhere for objects without them, such as type, whose boxes stand in).
pub fn contains_fn(&self) -> impl Fn(Point) -> bool + use<> {
let shapes = self.clip_shapes(None);
move |p| shapes.is_empty() || shapes.iter().any(|(bp, rule)| vectorcraft_geom::hit::fill_contains(bp, *rule, p))
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -880,7 +1142,7 @@ mod tests {
let fresh = || Node::path(NodeId(2), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 50.0)), Appearance::basic(grad(), grad(), 2.0));
let geoms = |n: &Node| match (n.appearance.fill_paint(), n.appearance.stroke_paint()) {
(Paint::Gradient(f), Paint::Gradient(s)) => (f.geom, s.geom),
_ => unreachable!(),
_ => panic!("gradient fill and stroke"),
};
let mut n = fresh();
n.transform(Affine::translate((10.0, 5.0)) * Affine::scale(2.0), true);
+6 -6
View File
@@ -11,13 +11,13 @@ use crate::{Document, Node, NodeId, NodeKind};
pub const LEGACY_OVERPRINT_KEY: &str = "overprintBlack";
/// Black ink of at least `min_k` (0..1): CMYK with that much K and, unless `rich`, no cyan,
/// magenta or yellow; or a grey that dark. RGB colours are never black ink.
/// magenta or yellow; or a grey that dark. RGB and Lab colours are never black ink.
pub fn is_black_ink(c: &Color, min_k: f32, rich: bool) -> bool {
const E: f32 = 0.005;
match *c {
Color::Cmyk { c, m, y, k } => k >= min_k - E && (rich || (c <= E && m <= E && y <= E)),
Color::Gray { k } => k >= min_k - E,
Color::Rgb { .. } => false,
Color::Rgb { .. } | Color::Lab { .. } => false,
}
}
@@ -48,7 +48,7 @@ impl OverprintBlack {
/// [`Self::spot`]), or a gradient whose every stop is.
fn black(&self, p: &Paint, spots: &[String]) -> bool {
match p {
Paint::Solid { color, swatch } => {
Paint::Solid { color, swatch, .. } => {
(self.spot || !swatch.as_ref().is_some_and(|s| spots.contains(s))) && is_black_ink(color, self.min_k, self.rich)
}
Paint::Gradient(g) => !g.gradient.stops.is_empty() && g.gradient.stops.iter().all(|s| is_black_ink(&s.color, self.min_k, self.rich)),
@@ -159,14 +159,14 @@ mod tests {
assert!(!n.appearance.fill().unwrap().overprint, "a gradient with a white stop is not black");
// Spot-linked blacks only with `spot`; type runs too.
let spot = Paint::Solid { color: Color::cmyk(0.0, 0.0, 0.0, 1.0), swatch: Some("Ink".into()) };
let spot = Paint::Solid { color: Color::cmyk(0.0, 0.0, 0.0, 1.0), swatch: Some("Ink".into()), tint: 1.0 };
let style = CharStyle { fill: spot, stroke: k, stroke_width: 1.0, ..CharStyle::default() };
let mut t = Node::new(NodeId(2), NodeKind::Text(Box::new(TextObject::point(Point::ZERO, "Hi", style))));
OverprintBlack::default().apply(&mut t, &["Ink".to_string()]);
let NodeKind::Text(tx) = &t.kind else { unreachable!() };
let NodeKind::Text(tx) = &t.kind else { panic!("type") };
assert!(!tx.runs[0].style.overprint_fill && tx.runs[0].style.overprint_stroke);
OverprintBlack { spot: true, ..Default::default() }.apply(&mut t, &["Ink".to_string()]);
let NodeKind::Text(tx) = &t.kind else { unreachable!() };
let NodeKind::Text(tx) = &t.kind else { panic!("type") };
assert!(tx.runs[0].style.overprint_fill);
}
+13 -2
View File
@@ -182,6 +182,10 @@ pub struct PatternDef {
pub dim_copies: f32,
#[serde(default = "yes")]
pub show_tile_edge: bool,
/// Show Swatch Bounds: pattern editing mode outlines the part of the tiling the swatch repeats
/// (the tile, or the period of a brick or hex tiling), dashed.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub show_swatch_bounds: bool,
}
impl PatternDef {
@@ -200,6 +204,7 @@ impl PatternDef {
copies: 5,
dim_copies: 70.0,
show_tile_edge: true,
show_swatch_bounds: false,
}
}
pub fn width(&self) -> f64 {
@@ -226,6 +231,11 @@ impl PatternDef {
pub fn period(&self) -> (f64, f64) {
tile_period(self.tile_type, self.width(), self.height())
}
/// The swatch bounds (Show Swatch Bounds): the period of the tiling from the tile's origin.
pub fn swatch_bounds(&self) -> Rect {
let (w, h) = self.period();
Rect::from_origin_size(self.tile.origin(), (w, h))
}
/// Maps the art's coordinates into pattern space for instance offset `o`.
pub fn instance_xf(&self, o: Vec2) -> Affine {
Affine::translate(o - self.tile.origin().to_vec2())
@@ -493,9 +503,10 @@ impl RepeatSpec {
self.transforms().into_iter().fold(None, |acc, m| vectorcraft_geom::union_opt(acc, Some(m.transform_rect_bbox(b))))
}
/// Apply a document transform (source + arrangement parameters).
pub fn transform(&mut self, a: Affine, scale_strokes: bool) {
pub fn transform(&mut self, a: Affine, scaling: impl Into<crate::node::Scaling>) {
let scaling = scaling.into();
for c in self.source.iter_mut() {
Arc::make_mut(c).transform(a, scale_strokes);
Arc::make_mut(c).transform(a, scaling);
}
let s = a.determinant().abs().sqrt();
match &mut self.kind {
+80 -3
View File
@@ -9,13 +9,12 @@ use crate::ImageBlob;
impl ImageBlob {
/// A PNG blob of `png` bytes.
pub fn png(png: Vec<u8>) -> Self {
Self { mime: "image/png".into(), bytes: Arc::new(png) }
Self::new("image/png", png)
}
/// A key derived from the bytes (FNV-1a), the same for identical images.
pub fn content_key(&self) -> String {
let h = self.bytes.iter().fold(0xcbf29ce484222325u64, |h, x| (h ^ *x as u64).wrapping_mul(0x100000001b3));
format!("img{h:016x}")
crate::links::hash_bytes(&self.bytes)
}
/// The image with `f` applied to each pixel's (straight) RGB, alpha kept and fully transparent
@@ -42,6 +41,65 @@ impl ImageBlob {
}
}
impl ImageBlob {
/// The colour around pixel (`x`, `y`) (pixel space): the alpha-weighted average of the `size` ×
/// `size` pixels centred on it, clipped to the image, as straight RGBA. `None` outside the
/// image, where every pixel is transparent, or when the image can't be decoded. The last image
/// decoded is kept for the next sample (the Eyedropper samples one image click after click).
pub fn sample(&self, x: f64, y: f64, size: u32) -> Option<[u8; 4]> {
sample_pixels(&*self.decoded()?, x, y, size)
}
/// [`Self::sample`] at (`x`, `y`) in the pixel space of an image object of `object` (width,
/// height) pixels, which the decoded pixels may not match (a linked image showing its preview).
pub fn sample_object(&self, x: f64, y: f64, object: (u32, u32), size: u32) -> Option<[u8; 4]> {
let img = self.decoded()?;
let k = |n: u32, of: u32| n as f64 / of.max(1) as f64;
sample_pixels(&img, x * k(img.width(), object.0), y * k(img.height(), object.1), size)
}
/// The decoded pixels (the last image decoded is kept for the next sample).
fn decoded(&self) -> Option<Arc<image::RgbaImage>> {
thread_local! {
static LAST: std::cell::RefCell<Option<(String, Arc<image::RgbaImage>)>> = const { std::cell::RefCell::new(None) };
}
let key = self.content_key();
LAST.with_borrow_mut(|last| match last {
Some((k, img)) if *k == key => Some(img.clone()),
_ => {
let img = Arc::new(image::load_from_memory(&self.bytes).ok()?.to_rgba8());
*last = Some((key, img.clone()));
Some(img)
}
})
}
}
/// [`ImageBlob::sample`] of decoded pixels `img`.
fn sample_pixels(img: &image::RgbaImage, x: f64, y: f64, size: u32) -> Option<[u8; 4]> {
let (w, h) = (img.width() as i64, img.height() as i64);
let (cx, cy) = (x.floor() as i64, y.floor() as i64);
if !(0..w).contains(&cx) || !(0..h).contains(&cy) {
return None;
}
let r = size.max(1) as i64 / 2;
let (mut sum, mut alpha, mut n) = ([0u64; 3], 0u64, 0u64);
for py in (cy - r).max(0)..=(cy + r).min(h - 1) {
for px in (cx - r).max(0)..=(cx + r).min(w - 1) {
let [pr, pg, pb, pa] = img.get_pixel(px as u32, py as u32).0;
let a = pa as u64;
sum = [sum[0] + pr as u64 * a, sum[1] + pg as u64 * a, sum[2] + pb as u64 * a];
alpha += a;
n += 1;
}
}
if alpha == 0 {
return None;
}
let c = |v: u64| ((v + alpha / 2) / alpha) as u8;
Some([c(sum[0]), c(sum[1]), c(sum[2]), ((alpha + n / 2) / n) as u8])
}
#[cfg(test)]
mod tests {
use super::*;
@@ -57,6 +115,25 @@ mod tests {
image::load_from_memory(&b.bytes).unwrap().to_rgba8().pixels().map(|p| p.0).collect()
}
#[test]
fn samples_a_pixel_or_the_average_around_it() {
let b = blob(&[[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255], [9, 9, 9, 0]], 4, 1);
assert_eq!(b.sample(1.5, 0.5, 1), Some([0, 255, 0, 255]));
assert_eq!(b.sample(1.5, 0.5, 3), Some([85, 85, 85, 255]), "red, green and blue averaged");
assert_eq!(b.sample(3.2, 0.5, 3), Some([0, 0, 255, 128]), "transparent pixels don't count towards the colour");
assert_eq!(b.sample(3.2, 0.5, 1), None, "all transparent");
assert_eq!(b.sample(-0.5, 0.5, 5), None, "outside");
assert_eq!(b.sample(0.0, 0.0, 5), Some([85, 85, 85, 255]), "clipped to the image");
}
#[test]
fn samples_in_the_pixel_space_of_an_object_with_more_pixels() {
// An object of 8 × 2 pixels showing these 4 × 1 (a linked image's preview).
let b = blob(&[[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255], [9, 9, 9, 255]], 4, 1);
assert_eq!(b.sample_object(5.0, 1.5, (8, 2), 1), Some([0, 0, 255, 255]));
assert_eq!(b.sample_object(1.0, 0.0, (4, 1), 1), b.sample(1.0, 0.0, 1), "the same size: the same pixels");
}
#[test]
fn maps_each_colour_once_and_keeps_alpha() {
let b = blob(&[[255, 0, 0, 255], [255, 0, 0, 128], [0, 0, 255, 255], [10, 20, 30, 0]], 2, 2);
+75
View File
@@ -0,0 +1,75 @@
//! The colour profiles a document is tagged with (Edit → Assign Profile).
use serde::{Deserialize, Serialize};
use crate::Document;
/// `Document::unknown` key under which files before format v3 kept the assigned profiles
/// (`{rgb?, cmyk?}`); still written when saving for those versions.
pub const LEGACY_PROFILES_KEY: &str = "colorProfiles";
/// The profiles a document is tagged with, by name (`None`: the working space).
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ColorProfiles {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub rgb: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cmyk: Option<String>,
}
impl ColorProfiles {
pub fn is_empty(&self) -> bool {
self.rgb.is_none() && self.cmyk.is_none()
}
/// The legacy JSON form (`{"rgb": name|null, "cmyk": name|null}`).
pub fn to_legacy(&self) -> serde_json::Value {
serde_json::json!({ "rgb": self.rgb, "cmyk": self.cmyk })
}
/// Read the legacy JSON form (anything that isn't a name counts as none).
pub fn from_legacy(v: &serde_json::Value) -> Self {
let name = |k: &str| v.get(k).and_then(serde_json::Value::as_str).map(str::to_string);
Self { rgb: name("rgb"), cmyk: name("cmyk") }
}
}
impl Document {
/// Files before format v3 kept the assigned profiles under [`LEGACY_PROFILES_KEY`] in
/// `unknown`: move them to [`Document::color_profiles`].
pub fn migrate_color_profiles(&mut self) {
let Some(v) = self.unknown.remove(LEGACY_PROFILES_KEY) else { return };
if self.color_profiles.is_empty() {
self.color_profiles = ColorProfiles::from_legacy(&v);
}
}
/// The reverse of [`Document::migrate_color_profiles`], for saving in a version before v3.
pub fn store_legacy_color_profiles(&mut self) {
let profiles = std::mem::take(&mut self.color_profiles);
if !profiles.is_empty() {
self.unknown.insert(LEGACY_PROFILES_KEY.into(), profiles.to_legacy());
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn legacy_profiles_migrate_both_ways() {
let mut d = Document::new(10.0, 10.0);
d.unknown.insert(LEGACY_PROFILES_KEY.into(), serde_json::json!({"rgb": "Wide RGB", "cmyk": null}));
d.migrate_color_profiles();
assert_eq!(d.color_profiles, ColorProfiles { rgb: Some("Wide RGB".into()), cmyk: None });
assert!(!d.unknown.contains_key(LEGACY_PROFILES_KEY));
d.store_legacy_color_profiles();
assert!(d.color_profiles.is_empty());
assert_eq!(d.unknown[LEGACY_PROFILES_KEY], serde_json::json!({"rgb": "Wide RGB", "cmyk": null}));
// Nothing assigned: nothing stored.
let mut e = Document::new(10.0, 10.0);
e.store_legacy_color_profiles();
assert!(e.unknown.is_empty());
}
}
+135
View File
@@ -0,0 +1,135 @@
//! Effect → Document Raster Effects Settings, besides the resolution
//! ([`crate::Document::raster_effects_ppi`]): how raster effects (shadows, glows, blurs, feathers)
//! become pixels when they are flattened for output or expanded, and the defaults of Rasterize.
//! Every field is defaulted, so documents saved before these settings existed load unchanged.
use serde::{Deserialize, Serialize};
use crate::setup::Background;
/// The colour model raster effect images are made in.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum RasterColorModel {
/// The document's colour mode (RGB or CMYK).
#[default]
Document,
Grayscale,
/// Black and white pixels only.
Bitmap,
}
impl RasterColorModel {
pub const ALL: [RasterColorModel; 3] = [RasterColorModel::Document, RasterColorModel::Grayscale, RasterColorModel::Bitmap];
pub fn id(self) -> &'static str {
match self {
RasterColorModel::Document => "document",
RasterColorModel::Grayscale => "grayscale",
RasterColorModel::Bitmap => "bitmap",
}
}
}
/// Largest Add … Around Object, in points.
pub const MAX_ADD_AROUND: f64 = 1000.0;
/// Document Raster Effects Settings (resolution aside).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct RasterEffectsSettings {
pub color_model: RasterColorModel,
/// White: images are opaque, on white. Transparent: they keep their transparency.
pub background: Background,
/// Off: the art's edges are hard (raster effects stay smooth).
pub anti_alias: bool,
/// With a white background, the white stays only under the art (outside it the image is
/// transparent); Rasterize clips its image to the art's outline.
pub clipping_mask: bool,
/// Extra room around the art, in points (0–[`MAX_ADD_AROUND`]).
pub add_around: f64,
/// Keep spot colours in raster effects (stored; effect images are made in process colour).
pub preserve_spot_colors: bool,
}
impl Default for RasterEffectsSettings {
fn default() -> Self {
Self {
color_model: RasterColorModel::Document,
background: Background::Transparent,
anti_alias: true,
clipping_mask: false,
add_around: 0.0,
preserve_spot_colors: true,
}
}
}
impl RasterEffectsSettings {
/// Turn premultiplied RGBA8 pixels into what these settings make of them: the colour model,
/// then the background. (Anti-aliasing is the renderer's.)
pub fn finish_pixels(&self, pixels: &mut [u8]) {
let white = self.background == Background::White;
if self.color_model == RasterColorModel::Document && !white {
return;
}
for px in pixels.as_chunks_mut::<4>().0 {
let a = px[3];
if self.color_model != RasterColorModel::Document && a != 0 {
// Rec. 709 luma of the premultiplied colour (still premultiplied).
let y = 0.2126 * px[0] as f32 + 0.7152 * px[1] as f32 + 0.0722 * px[2] as f32;
let y = match self.color_model {
RasterColorModel::Bitmap => {
if y >= a as f32 / 2.0 {
a
} else {
0
}
}
_ => y.round().min(a as f32) as u8,
};
px[..3].fill(y);
}
// Over white; a clipping mask leaves what the art doesn't cover transparent.
if white && !(self.clipping_mask && a == 0) {
let under = 255 - a;
for c in &mut px[..3] {
*c = c.saturating_add(under);
}
px[3] = 255;
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn finish(s: RasterEffectsSettings, px: [u8; 4]) -> [u8; 4] {
let mut p = px;
s.finish_pixels(&mut p);
p
}
#[test]
fn pixels_follow_the_settings() {
let d = RasterEffectsSettings::default();
assert_eq!(finish(d.clone(), [100, 0, 0, 100]), [100, 0, 0, 100], "the defaults change nothing");
let white = RasterEffectsSettings { background: Background::White, ..d.clone() };
assert_eq!(finish(white.clone(), [0, 0, 0, 0]), [255, 255, 255, 255]);
assert_eq!(finish(white.clone(), [100, 0, 0, 100]), [255, 155, 155, 255]);
let masked = RasterEffectsSettings { clipping_mask: true, ..white };
assert_eq!(finish(masked, [0, 0, 0, 0]), [0, 0, 0, 0]);
let gray = RasterEffectsSettings { color_model: RasterColorModel::Grayscale, ..d.clone() };
assert_eq!(finish(gray, [255, 0, 0, 255]), [54, 54, 54, 255]);
let bitmap = RasterEffectsSettings { color_model: RasterColorModel::Bitmap, ..d };
assert_eq!(finish(bitmap.clone(), [255, 0, 0, 255]), [0, 0, 0, 255]);
assert_eq!(finish(bitmap, [0, 255, 0, 255]), [255, 255, 255, 255]);
}
#[test]
fn partial_settings_fill_in_the_rest() {
let s: RasterEffectsSettings = serde_json::from_str(r#"{"background":"white"}"#).unwrap();
assert_eq!(s, RasterEffectsSettings { background: Background::White, ..Default::default() });
}
}
+431
View File
@@ -0,0 +1,431 @@
//! Where a path's strokes paint, from the path's geometry without building their outlines: the
//! visual bounds and the clicks of a stroke take in its alignment, its width profile, miter spikes
//! up to the miter limit, projecting caps and arrowheads.
use vectorcraft_geom::bez::{CORNER_COS, kink, segments, subpaths, tangent, unit};
use vectorcraft_geom::hit::fill_contains;
use vectorcraft_geom::kurbo::{ParamCurveArclen, ParamCurveNearest};
use vectorcraft_geom::{BezPath, FillRule, ParamCurve, PathSeg, Point, Rect, Shape, Vec2};
use crate::appearance::HEAD_REACH;
use crate::{Appearance, ArrowAlign, Dash, LineCap, LineJoin, StrokeAlign, StrokeLayer, WidthProfile};
/// Arc-length accuracy for placing a point along a profile (document points).
const ARCLEN_ACCURACY: f64 = 1e-3;
/// The segments of a subpath that have length (zero-length ones, all of whose points coincide,
/// have no direction).
fn drawn(els: &[vectorcraft_geom::PathEl]) -> Vec<PathSeg> {
let moves = |s: &PathSeg| match s {
PathSeg::Line(l) => l.p1 != l.p0,
PathSeg::Quad(q) => q.p1 != q.p0 || q.p2 != q.p0,
PathSeg::Cubic(c) => c.p1 != c.p0 || c.p2 != c.p0 || c.p3 != c.p0,
};
segments(els).into_iter().filter(moves).collect()
}
/// The open subpath ends of `segs`: (point, unit direction out of the path) at its start and end.
fn ends(segs: &[PathSeg]) -> Option<[(Point, Vec2); 2]> {
let (first, last) = (segs.first()?, segs.last()?);
Some([(first.start(), -tangent(first, 0.0)), (last.end(), tangent(last, 1.0))])
}
/// The joints between consecutive segments (and, `closed`, where the subpath closes): the point
/// and the unit tangents in and out.
fn joints(segs: &[PathSeg], closed: bool) -> impl Iterator<Item = (Point, Vec2, Vec2)> + '_ {
let n = segs.len();
let pairs = if closed && n > 1 { n } else { n.saturating_sub(1) };
(0..pairs).map(move |i| {
let (a, b) = (&segs[i], &segs[(i + 1) % n]);
(a.end(), tangent(a, 1.0), tangent(b, 0.0))
})
}
/// The miter spike at a corner with tangents `t_in`, `t_out` of a stroke reaching `side` from its
/// path: its tip and the corner's outer offset points, or `None` when the path doesn't turn there
/// or the miter limit bevels it.
fn miter(at: Point, t_in: Vec2, t_out: Vec2, side: f64, limit: f64) -> Option<[Point; 3]> {
let cos = t_in.dot(t_out);
// cos(half the turn) is sin(half the angle between the segments): the miter is side / it.
let half = ((1.0 + cos) / 2.0).max(0.0).sqrt();
if cos >= CORNER_COS || half * limit < 1.0 {
return None;
}
let out = unit(t_in - t_out);
// The offset of each segment on the outer side of the turn.
let outer = |t: Vec2| {
let n = Vec2::new(-t.y, t.x);
if n.dot(out) >= 0.0 { n } else { -n }
};
Some([at + outer(t_in) * side, at + out * (side / half), at + outer(t_out) * side])
}
/// The heads' ends of `bp`: the start of its first subpath and the end of its last, when open (as
/// the stroke geometry places them), each with `true` for the end head.
fn head_ends(st: &StrokeLayer, bp: &BezPath) -> Vec<(Point, Vec2, bool)> {
if st.start_arrow.is_none() && st.end_arrow.is_none() {
return vec![];
}
let subs = subpaths(bp);
let open_ends = |sub: Option<&(std::ops::Range<usize>, bool)>| sub.filter(|s| !s.1).and_then(|s| ends(&drawn(&bp.elements()[s.0.clone()])));
let mut out = vec![];
if st.start_arrow.is_some()
&& let Some([(at, dir), _]) = open_ends(subs.first())
{
out.push((at, dir, false));
}
if st.end_arrow.is_some()
&& let Some([_, (at, dir)]) = open_ends(subs.last())
{
out.push((at, dir, true));
}
out
}
/// (left, right) width factors where `p`'s nearest point on the subpath `segs` sits (segment `i`
/// at `t`): the profile at that fraction of the subpath's length, or wider where an end of the
/// segment is a corner. The stroke draws the sides there straight to the corner's join and inner
/// meeting point, which can lie outside the exact width all along the segment.
fn profile_at(profile: &WidthProfile, segs: &[PathSeg], closed: bool, i: usize, t: f64) -> (f64, f64) {
let n = segs.len();
let lens: Vec<f64> = segs.iter().map(|s| s.arclen(ARCLEN_ACCURACY)).collect();
let total: f64 = lens.iter().sum::<f64>().max(1e-12);
let before = lens[..i].iter().sum::<f64>();
let mut w = profile.at((before + segs[i].subsegment(0.0..t).arclen(ARCLEN_ACCURACY)) / total);
let corner = |a: usize, b: usize| (closed || a < b) && kink(&segs[a], &segs[b]);
let starts = n > 1 && corner((i + n - 1) % n, i);
let ends = n > 1 && corner(i, (i + 1) % n);
// A closed subpath's last segment ends where it starts.
let end = if i + 1 == n { 0.0 } else { before + lens[i] };
for (is, at) in [(starts, before), (ends, end)] {
if is {
let (l, r) = profile.at(at / total);
w = (w.0.max(l), w.1.max(r));
}
}
w
}
/// Is `p` inside the convex polygon `pts` (either winding), or within `tol` of it?
fn in_convex(pts: &[Point], p: Point, tol: f64) -> bool {
let n = pts.len();
// Signed distances from each edge's line.
let (lo, hi) = (0..n).fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), i| {
let e = pts[(i + 1) % n] - pts[i];
let d = e.cross(p - pts[i]) / e.hypot().max(1e-12);
(lo.min(d), hi.max(d))
});
lo >= -tol || hi <= tol
}
impl StrokeLayer {
/// Does bounding this stroke need its path's shape: miter spikes, projecting caps, arrowheads,
/// or an alignment that depends on whether the path is closed? Else it reaches evenly round it.
fn needs_shape(&self) -> bool {
self.join == LineJoin::Miter
|| self.cap == LineCap::Square
|| self.start_arrow.is_some()
|| self.end_arrow.is_some()
|| self.align != StrokeAlign::Center
}
/// The box this stroke paints along `bp`, whose geometric bounds are `bounds`: the bounds grown
/// by the body's reach, with the tips of the miter spikes the limit keeps, the corners of
/// projecting caps and the reach of the arrowheads round their end points.
pub fn bounds_on(&self, bp: &BezPath, bounds: Rect) -> Rect {
let els = bp.elements();
let mut out = bounds;
let mut side_max: f64 = 0.0;
// Dashes put a cap on every dash: projecting ones reach a corner's diagonal anywhere.
let capped_dashes = self.cap == LineCap::Square && self.dash.as_ref().is_some_and(Dash::is_dashed);
for (r, closed) in subpaths(bp) {
let side = self.side_reach(closed);
side_max = side_max.max(if capped_dashes { side * std::f64::consts::SQRT_2 } else { side });
if side <= 0.0 {
continue;
}
let segs = drawn(&els[r]);
if self.join == LineJoin::Miter {
for (at, t_in, t_out) in joints(&segs, closed) {
if let Some([_, tip, _]) = miter(at, t_in, t_out, side, self.miter_limit) {
out = out.union_pt(tip);
}
}
}
if self.cap == LineCap::Square && !closed {
for (at, dir) in ends(&segs).into_iter().flatten() {
let n = Vec2::new(-dir.y, dir.x) * side;
out = out.union_pt(at + dir * side + n).union_pt(at + dir * side - n);
}
}
}
for (at, _, end) in head_ends(self, bp) {
let r = self.head_reach(end);
out = out.union(Rect::from_center_size(at, (2.0 * r, 2.0 * r)));
}
out.union(bounds.inflate(side_max, side_max))
}
/// Does this stroke along `bp` (filled with `rule`) paint within `tol` of `p`? Inside and
/// outside strokes of closed paths count on their own side only (and within `tol` of the
/// path); a width profile counts at its width where `p` is nearest.
pub fn hits(&self, bp: &BezPath, rule: FillRule, p: Point, tol: f64) -> bool {
let reach = self.reach() + tol;
if self.width.is_nan() || self.width <= 0.0 || !bp.bounding_box().inflate(reach, reach).contains(p) {
return false;
}
if head_ends(self, bp).into_iter().any(|(at, out, end)| self.head_contains(at, out, end, p, tol)) {
return true;
}
let els = bp.elements();
// Aligned strokes paint on one side of the path only.
let on_side = |region: Option<bool>, d: f64| region.is_none_or(|inside| d <= tol || fill_contains(bp, rule, p) == inside);
// Every dash gets the caps, as wide as the stroke where the dash ends: round ones reach as
// far as the widest point, projecting ones a corner's diagonal.
let dash_caps = match self.cap {
LineCap::Butt => None,
_ if !self.dash.as_ref().is_some_and(Dash::is_dashed) => None,
LineCap::Round => Some(1.0),
LineCap::Square => Some(std::f64::consts::SQRT_2),
};
for (r, closed) in subpaths(bp) {
let segs = drawn(&els[r]);
let (half, region) = self.body(closed);
let full = half * self.profile_max() * dash_caps.unwrap_or(1.0);
// The nearest point on this subpath.
let near = segs.iter().enumerate().map(|(i, s)| (i, s.nearest(p, 1e-9))).min_by(|a, b| a.1.distance_sq.total_cmp(&b.1.distance_sq));
if let Some((i, nr)) = near
&& nr.distance_sq.sqrt() <= full + tol
{
let d = nr.distance_sq.sqrt();
let factor = if dash_caps.is_some() {
full / half.max(1e-12)
} else {
self.profile.as_ref().map_or(1.0, |pr| {
let (l, rt) = profile_at(pr, &segs, closed, i, nr.t);
// Nearest to a segment's end, `p` is beside a join or past a cap, which
// spans the widths of both sides.
let at_end = nr.t <= 1e-9 || nr.t >= 1.0 - 1e-9;
// Left of the direction of travel (y down) reads the left width.
let tn = tangent(&segs[i], nr.t);
let left = (p - segs[i].eval(nr.t)).dot(Vec2::new(tn.y, -tn.x)) >= 0.0;
if at_end {
l.max(rt)
} else if left {
l
} else {
rt
}
})
};
if d <= half * factor.max(0.0) + tol && on_side(region, d) {
return true;
}
}
if full <= 0.0 {
continue;
}
if self.join == LineJoin::Miter
&& joints(&segs, closed).any(|(at, t_in, t_out)| {
miter(at, t_in, t_out, full, self.miter_limit).is_some_and(|[a, tip, b]| in_convex(&[at, a, tip, b], p, tol))
})
&& on_side(region, f64::INFINITY)
{
return true;
}
if self.cap == LineCap::Square
&& !closed
&& ends(&segs).into_iter().flatten().any(|(at, dir)| {
let n = Vec2::new(-dir.y, dir.x) * full;
in_convex(&[at + n, at + n + dir * full, at - n + dir * full, at - n], p, tol)
})
{
return true;
}
}
false
}
/// Is `p` within `tol` of where the start (`end == false`) or end arrowhead at `at` (the path
/// leaving along `out`) can paint? Heads are at most about 4.6 weights long and 4 wide. With
/// [`ArrowAlign::Extend`] a head points along `out` with its tip up to its length (or the cap)
/// past the end; with [`ArrowAlign::Tip`] its tip is on the end and it lies back along the
/// chord the path bends through under it, so anywhere within its length of the end.
fn head_contains(&self, at: Point, out: Vec2, end: bool, p: Point, tol: f64) -> bool {
let hw = self.arrow_weight(end);
let v = p - at;
match self.arrow_align {
ArrowAlign::Tip => v.hypot() <= HEAD_REACH * hw + tol,
ArrowAlign::Extend => {
let along = v.dot(out);
v.cross(out).abs() <= 2.0 * hw + tol && along <= 4.0 * hw + self.width / 2.0 + tol && along >= -HEAD_REACH * hw - tol
}
}
}
}
impl Appearance {
/// The visual bounds of a path with geometric bounds `bounds` painted with this appearance:
/// the bounds with what each visible stroke paints round it ([`StrokeLayer::bounds_on`]).
/// `bp` (the path) is only built when a stroke needs its shape.
pub fn stroked_bounds(&self, bounds: Rect, bp: impl FnOnce() -> BezPath) -> Rect {
let mut path = Some(bp);
let mut shape = None;
self.painted_strokes().fold(bounds, |acc, s| {
if !s.needs_shape() {
let o = s.side_reach(false);
return acc.union(bounds.inflate(o, o));
}
let bp: &BezPath = shape.get_or_insert_with(|| path.take().map(|f| f()).unwrap_or_default());
acc.union(s.bounds_on(bp, bounds))
})
}
/// Does a visible stroke of this appearance along `bp` (filled with `rule`) paint within
/// `tol` of `p` ([`StrokeLayer::hits`])?
pub fn stroke_hit(&self, bp: &BezPath, rule: FillRule, p: Point, tol: f64) -> bool {
self.painted_strokes().any(|s| s.hits(bp, rule, p, tol))
}
}
#[cfg(test)]
mod tests {
use vectorcraft_color::{Color, Paint};
use vectorcraft_geom::{PathData, shapes};
use super::*;
use crate::{Arrowhead, Document, Node, StrokeAlign, hit};
fn stroke(width: f64, f: impl FnOnce(&mut StrokeLayer)) -> StrokeLayer {
let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), width);
f(&mut st);
st
}
fn line() -> BezPath {
shapes::line(Point::new(0.0, 0.0), Point::new(100.0, 0.0)).to_bezpath()
}
/// A thin triangle whose 22.6° apex at (100, 20) miters about 5 times half the weight out.
fn triangle() -> BezPath {
let mut bp = BezPath::new();
bp.move_to((0.0, 0.0));
bp.line_to((100.0, 20.0));
bp.line_to((0.0, 40.0));
bp.close_path();
bp
}
fn square() -> BezPath {
shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)).to_bezpath()
}
#[test]
fn a_bigger_arrowhead_grows_the_bounds() {
let l = line();
let b = l.bounding_box();
let at = |scale: f64| {
stroke(2.0, |s| {
s.join = LineJoin::Round;
s.end_arrow = Some(Arrowhead::Triangle);
s.arrow_scale = (100.0, scale);
})
};
let (small, big) = (at(100.0).bounds_on(&l, b), at(300.0).bounds_on(&l, b));
assert!(big.x1 > small.x1 + 15.0 && big.y1 > small.y1 + 7.0, "{small:?} → {big:?}");
// A 300% head on a 2 pt stroke is 24 pt long and wide: its tip, past the end, is inside.
assert!(big.x1 >= 100.0 + 24.0 && big.y1 >= 12.0 && big.x0 == -1.0, "{big:?}");
// The start has no head.
assert_eq!(at(300.0).head_reach(false), 0.0);
}
#[test]
fn rectangles_keep_exact_bounds_and_sharp_corners_spike_up_to_the_limit() {
let sq = square();
let b = sq.bounding_box();
let st = stroke(4.0, |_| {});
assert_eq!(st.bounds_on(&sq, b), b.inflate(2.0, 2.0), "right-angle miters stay in the box");
// A sharp spike: a thin triangle's apex miters far out unless the limit bevels it.
let tri = triangle();
let tb = tri.bounding_box();
let spiked = st.bounds_on(&tri, tb);
assert!(spiked.x1 > 100.0 + 10.0, "{spiked:?}");
let mut low = st.clone();
low.miter_limit = 2.0;
assert!(low.bounds_on(&tri, tb).x1 <= 100.0 + 2.0 + 1e-9, "beveled");
// Projecting caps reach past the ends; inside strokes stay in.
let l = line();
let cap = stroke(4.0, |s| s.cap = LineCap::Square).bounds_on(&l, l.bounding_box());
assert_eq!((cap.x0, cap.x1, cap.y1), (-2.0, 102.0, 2.0));
assert_eq!(stroke(4.0, |s| s.align = StrokeAlign::Inside).bounds_on(&sq, b), b);
assert_eq!(stroke(4.0, |s| s.align = StrokeAlign::Outside).bounds_on(&sq, b), b.inflate(4.0, 4.0));
}
#[test]
fn clicks_hit_outside_strokes_on_their_side_only() {
let sq = square();
let w = 10.0;
let st = stroke(w, |s| s.align = StrokeAlign::Outside);
assert!(st.hits(&sq, FillRule::NonZero, Point::new(-0.8 * w, 50.0), 0.5), "0.8·w outside");
assert!(!st.hits(&sq, FillRule::NonZero, Point::new(0.8 * w, 50.0), 0.5), "nothing painted inside");
assert!(st.hits(&sq, FillRule::NonZero, Point::new(0.3, 50.0), 0.5), "on the path");
let inside = stroke(w, |s| s.align = StrokeAlign::Inside);
assert!(inside.hits(&sq, FillRule::NonZero, Point::new(0.8 * w, 50.0), 0.5));
assert!(!inside.hits(&sq, FillRule::NonZero, Point::new(-0.8 * w, 50.0), 0.5));
// A centred stroke reaches half its weight each side.
let centre = stroke(w, |_| {});
assert!(centre.hits(&sq, FillRule::NonZero, Point::new(-4.0, 50.0), 0.5));
assert!(!centre.hits(&sq, FillRule::NonZero, Point::new(-8.0, 50.0), 0.5));
}
#[test]
fn clicks_follow_the_width_profile() {
let l = line();
let lens = stroke(10.0, |s| s.profile = Some(WidthProfile::lens()));
assert!(lens.hits(&l, FillRule::NonZero, Point::new(50.0, 4.8), 0.1), "the lens's widest point");
assert!(!lens.hits(&l, FillRule::NonZero, Point::new(5.0, 4.8), 0.1), "its thin end");
// A profile wider than the weight on one side.
let wide = stroke(10.0, |s| s.profile = Some(WidthProfile { points: vec![(0.0, 3.0, 1.0), (1.0, 3.0, 1.0)] }));
// Left of travel (+x, y down) is −y.
assert!(wide.hits(&l, FillRule::NonZero, Point::new(50.0, -14.0), 0.1));
assert!(!wide.hits(&l, FillRule::NonZero, Point::new(50.0, 14.0), 0.1));
assert!(wide.bounds_on(&l, l.bounding_box()).y0 <= -15.0);
}
#[test]
fn clicks_hit_heads_caps_and_spikes() {
let l = line();
let head = stroke(2.0, |s| {
s.end_arrow = Some(Arrowhead::Triangle);
s.arrow_scale = (100.0, 300.0);
});
// The 24 pt head sits past the end in extend mode, 12 pt either side of the line.
assert!(head.hits(&l, FillRule::NonZero, Point::new(110.0, 6.0), 0.1));
assert!(!head.hits(&l, FillRule::NonZero, Point::new(50.0, 6.0), 0.1));
let mut tip = head.clone();
tip.arrow_align = ArrowAlign::Tip;
assert!(tip.hits(&l, FillRule::NonZero, Point::new(90.0, 6.0), 0.1) && !tip.hits(&l, FillRule::NonZero, Point::new(130.0, 0.0), 0.1));
let cap = stroke(10.0, |s| s.cap = LineCap::Square);
assert!(cap.hits(&l, FillRule::NonZero, Point::new(104.0, 4.5), 0.1), "the cap's corner");
assert!(!stroke(10.0, |_| {}).hits(&l, FillRule::NonZero, Point::new(104.0, 4.5), 0.1), "a butt end");
let tri = triangle();
let spike = stroke(4.0, |_| {});
assert!(spike.hits(&tri, FillRule::NonZero, Point::new(106.0, 20.0), 0.1), "in the miter spike");
assert!(!spike.hits(&tri, FillRule::NonZero, Point::new(106.0, 23.0), 0.1));
}
#[test]
fn document_hit_testing_and_visual_bounds_use_the_whole_stroke() {
let mut d = Document::new(300.0, 300.0);
let (l, id) = (d.layers[0].id, d.alloc_id());
let mut ap = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 10.0);
ap.stroke_mut().unwrap().align = StrokeAlign::Outside;
let sq = PathData::from_bezpath(&shapes::rectangle(Rect::new(100.0, 100.0, 200.0, 200.0)).to_bezpath());
d.insert(Some(l), 0, Node::path(id, sq, ap)).unwrap();
let opt = hit::HitOptions { tol: 1.0, ..Default::default() };
let h = hit::hit_test(&d, Point::new(92.0, 150.0), opt).expect("0.8·w outside the path");
assert_eq!((h.leaf, h.kind), (id, hit::HitKind::Stroke));
assert!(hit::hit_test(&d, Point::new(108.0, 150.0), opt).is_none(), "an unfilled interior");
assert_eq!(d.node(id).unwrap().visual_bounds(), Some(Rect::new(90.0, 90.0, 210.0, 210.0)));
}
}
+63
View File
@@ -19,6 +19,16 @@ pub struct Selection {
/// Key object for Align.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub key: Option<NodeId>,
/// The object, group or layer targeted through its target circle in the Layers panel, which
/// appearance, transparency and opacity-mask commands then act on (a targeted layer has its
/// art selected). Any other selection change clears it.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub target: Option<NodeId>,
/// Slices selected with the Slice Selection tool: user slice ids and the ids of objects whose
/// object slice is selected (see [`crate::slices`]). Any change to the object selection
/// clears them.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub slices: Vec<NodeId>,
}
impl Selection {
@@ -35,6 +45,8 @@ impl Selection {
self.objects.clear();
self.anchors.clear();
self.key = None;
self.target = None;
self.slices.clear();
}
pub fn set(&mut self, ids: impl IntoIterator<Item = NodeId>) {
self.clear();
@@ -43,17 +55,30 @@ impl Selection {
}
}
pub fn add(&mut self, id: NodeId) {
self.target = None;
self.slices.clear();
if !self.objects.contains(&id) {
self.objects.push(id);
}
}
pub fn remove(&mut self, id: NodeId) {
self.target = None;
self.slices.clear();
self.objects.retain(|x| *x != id);
self.anchors.remove(&id);
if self.key == Some(id) {
self.key = None;
}
}
/// Select slices `ids` (see [`Selection::slices`]) and nothing else.
pub fn set_slices(&mut self, ids: impl IntoIterator<Item = NodeId>) {
self.clear();
for id in ids {
if !self.slices.contains(&id) {
self.slices.push(id);
}
}
}
pub fn toggle(&mut self, id: NodeId) {
if self.contains(id) { self.remove(id) } else { self.add(id) }
}
@@ -68,6 +93,27 @@ impl Selection {
if self.key.is_some_and(|k| doc.node(k).is_none()) {
self.key = None;
}
if self.target.is_some_and(|t| doc.node(t).is_none()) {
self.target = None;
}
self.slices.retain(|id| doc.is_slice(*id));
}
/// Target `id` (see [`Selection::target`]): a layer gets its visible, unlocked art selected,
/// anything else is selected itself.
pub fn set_target(&mut self, doc: &Document, id: NodeId) {
match doc.node(id) {
Some(n) if n.is_layer() => self.set(n.children().into_iter().flatten().filter(|c| c.visible && !c.locked).map(|c| c.id)),
_ => self.set([id]),
}
self.target = Some(id);
}
/// What appearance and transparency edits act on: the targeted object, group or layer, else
/// the selected objects.
pub fn subjects(&self) -> &[NodeId] {
match &self.target {
Some(t) => std::slice::from_ref(t),
None => &self.objects,
}
}
/// Top-level ordering: selected ids sorted by paint order (bottom first).
pub fn in_paint_order(&self, doc: &Document) -> Vec<NodeId> {
@@ -93,4 +139,21 @@ mod tests {
s.clear();
assert!(s.is_empty());
}
#[test]
fn selection_changes_clear_the_target() {
let mut s = Selection::default();
s.set([NodeId(2), NodeId(3)]);
s.target = Some(NodeId(1));
assert_eq!(s.subjects(), &[NodeId(1)]);
s.add(NodeId(4));
assert_eq!(s.target, None);
assert_eq!(s.subjects(), &[NodeId(2), NodeId(3), NodeId(4)]);
s.target = Some(NodeId(1));
s.remove(NodeId(2));
assert_eq!(s.target, None);
s.target = Some(NodeId(1));
s.set([NodeId(3)]);
assert_eq!(s.target, None);
}
}
+317
View File
@@ -0,0 +1,317 @@
//! Document Setup (File → Document Setup): the bleed around the artboards, view options
//! (transparency grid, simulated paper, images in outline mode, substitution highlights), output
//! options and the document's typographic defaults. Every field is defaulted, so documents saved
//! before Document Setup existed load unchanged.
use serde::{Deserialize, Serialize};
use vectorcraft_color::Color;
use vectorcraft_geom::Rect;
use crate::text::ScriptMetrics;
/// Transparency grid cell size.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum GridSize {
Small,
#[default]
Medium,
Large,
}
impl GridSize {
pub const ALL: [GridSize; 3] = [GridSize::Small, GridSize::Medium, GridSize::Large];
pub fn id(self) -> &'static str {
match self {
GridSize::Small => "small",
GridSize::Medium => "medium",
GridSize::Large => "large",
}
}
pub fn label(self) -> &'static str {
match self {
GridSize::Small => "Small",
GridSize::Medium => "Medium",
GridSize::Large => "Large",
}
}
pub fn parse(s: &str) -> Option<Self> {
Self::ALL.into_iter().find(|g| g.id().eq_ignore_ascii_case(s))
}
/// Edge of one grid cell in screen points (the grid does not scale with the zoom).
pub fn cell(self) -> f32 {
match self {
GridSize::Small => 4.0,
GridSize::Medium => 8.0,
GridSize::Large => 16.0,
}
}
}
const fn hex(v: u32) -> Color {
Color::Rgb { r: ((v >> 16) & 0xff) as f32 / 255.0, g: ((v >> 8) & 0xff) as f32 / 255.0, b: (v & 0xff) as f32 / 255.0 }
}
/// Transparency grid colour presets (VectorCraft's own pairs). Any other pair is "Custom".
pub const GRID_COLOR_PRESETS: &[(&str, [Color; 2])] = &[
("Light", [hex(0xffffff), hex(0xcccccc)]),
("Medium", [hex(0xb3b3b3), hex(0x8c8c8c)]),
("Dark", [hex(0x666666), hex(0x4d4d4d)]),
("Red", [hex(0xffffff), hex(0xffc7c7)]),
("Orange", [hex(0xffffff), hex(0xffdcb8)]),
("Green", [hex(0xffffff), hex(0xc6efc6)]),
("Blue", [hex(0xffffff), hex(0xc4dcff)]),
("Purple", [hex(0xffffff), hex(0xe2c9ff)]),
];
/// How text is written to formats without live type (Document Setup → Type → Export).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum ExportText {
/// Keep text as text (editable).
#[default]
Editable,
/// Write glyph outlines (exact appearance without the fonts).
Appearance,
}
impl ExportText {
pub fn id(self) -> &'static str {
match self {
ExportText::Editable => "editable",
ExportText::Appearance => "appearance",
}
}
pub fn parse(s: &str) -> Option<Self> {
[ExportText::Editable, ExportText::Appearance].into_iter().find(|e| e.id().eq_ignore_ascii_case(s))
}
}
/// Quote characters (Document Setup → Type): opening and closing double and single quotes.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Quotes {
pub double: [char; 2],
pub single: [char; 2],
}
impl Default for Quotes {
fn default() -> Self {
Self::ENGLISH
}
}
impl Quotes {
pub const ENGLISH: Self = Self { double: ['“', '”'], single: ['‘', '’'] };
/// Double-quote pairs offered by Document Setup.
pub const DOUBLE_CHOICES: &[[char; 2]] = &[['“', '”'], ['„', '“'], ['„', '”'], ['”', '”'], ['«', '»'], ['»', '«'], ['「', '」'], ['"', '"']];
/// Single-quote pairs offered by Document Setup.
pub const SINGLE_CHOICES: &[[char; 2]] = &[['‘', '’'], ['‚', '‘'], ['‚', '’'], ['’', '’'], ['‹', '›'], ['›', '‹'], ['『', '』'], ['\'', '\'']];
/// Is `c` one of these opening quotes?
fn is_open(&self, c: char) -> bool {
c == self.double[0] || c == self.single[0]
}
/// A quote opens after nothing, whitespace, an opening bracket, a dash or another opening quote.
fn opens(&self, prev: Option<char>) -> bool {
prev.is_none_or(|p| p.is_whitespace() || matches!(p, '(' | '[' | '{' | '—' | '–') || self.is_open(p))
}
/// `text` with straight quotes (`"` and `'`) replaced by these quotes: opening or closing by
/// context (an apostrophe is a closing single quote). `prev` is the character before `text`,
/// and is updated to its last character, so text can be converted in pieces.
pub fn apply(&self, text: &str, prev: &mut Option<char>) -> String {
let mut out = String::with_capacity(text.len());
for c in text.chars() {
let r = match c {
'"' => self.double[usize::from(!self.opens(*prev))],
'\'' => self.single[usize::from(!self.opens(*prev))],
c => c,
};
out.push(r);
*prev = Some(r);
}
out
}
}
/// Document languages and the quote characters each uses (choosing a language in Document Setup
/// also picks its quotes).
pub const LANGUAGES: &[(&str, Quotes)] = &[
("English: USA", Quotes::ENGLISH),
("English: UK", Quotes { double: ['“', '”'], single: ['‘', '’'] }),
("German", Quotes { double: ['„', '“'], single: ['‚', '‘'] }),
("German: Swiss", Quotes { double: ['«', '»'], single: ['‹', '›'] }),
("French", Quotes { double: ['«', '»'], single: ['‹', '›'] }),
("Italian", Quotes { double: ['«', '»'], single: ['‘', '’'] }),
("Spanish", Quotes { double: ['«', '»'], single: ['‘', '’'] }),
("Portuguese", Quotes { double: ['«', '»'], single: ['‘', '’'] }),
("Dutch", Quotes { double: ['“', '”'], single: ['‘', '’'] }),
("Danish", Quotes { double: ['»', '«'], single: ['›', '‹'] }),
("Swedish", Quotes { double: ['”', '”'], single: ['’', '’'] }),
("Finnish", Quotes { double: ['”', '”'], single: ['’', '’'] }),
("Norwegian", Quotes { double: ['«', '»'], single: ['‘', '’'] }),
("Polish", Quotes { double: ['„', '”'], single: ['‚', '’'] }),
("Czech", Quotes { double: ['„', '“'], single: ['‚', '‘'] }),
("Russian", Quotes { double: ['«', '»'], single: ['„', '“'] }),
("Japanese", Quotes { double: ['「', '」'], single: ['『', '』'] }),
("Chinese", Quotes { double: ['“', '”'], single: ['‘', '’'] }),
];
/// The quotes of a [`LANGUAGES`] entry (case-insensitive).
pub fn language_quotes(language: &str) -> Option<Quotes> {
LANGUAGES.iter().find(|(l, _)| l.eq_ignore_ascii_case(language)).map(|(_, q)| *q)
}
/// The transparency flattener preset Document Setup uses unless another is chosen.
pub const DEFAULT_FLATTENER: &str = "Medium Resolution";
/// Background Contents (New Document): what shows behind the art on the artboards, and what
/// raster exports put there.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum Background {
#[default]
Transparent,
/// A white artboard background (not an object): raster exports are opaque white there.
White,
}
impl Background {
pub const ALL: [Background; 2] = [Background::Transparent, Background::White];
pub fn id(self) -> &'static str {
match self {
Background::Transparent => "transparent",
Background::White => "white",
}
}
pub fn parse(s: &str) -> Option<Self> {
Self::ALL.into_iter().find(|b| b.id().eq_ignore_ascii_case(s))
}
}
/// Largest bleed on any side, in points (1 inch).
pub const MAX_BLEED: f64 = 72.0;
/// File → Document Setup.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct DocSetup {
/// Bleed beyond every artboard edge in points: top, bottom, left, right.
pub bleed: [f64; 4],
/// Show Images in Outline Mode.
pub outline_images: bool,
/// Highlight text whose font is missing (drawn in a substitute font).
pub highlight_substituted_fonts: bool,
/// Highlight glyphs the font lacks (drawn from a fallback font).
pub highlight_substituted_glyphs: bool,
/// Transparency grid cell size.
pub grid_size: GridSize,
/// Transparency grid colours; the first is also the simulated paper colour.
pub grid_colors: [Color; 2],
/// Simulate Colored Paper: artboards show the paper colour and art is multiplied onto it.
pub simulate_paper: bool,
/// Transparency flattener preset for output that can't keep transparency (None =
/// [`DEFAULT_FLATTENER`]).
pub flattener_preset: Option<String>,
/// Discard White Overprint in Output.
pub discard_white_overprint: bool,
/// Document language (one of [`LANGUAGES`]).
pub language: String,
pub quotes: Quotes,
/// Use Typographer's Quotes: typed straight quotes become [`DocSetup::quotes`].
pub typographers_quotes: bool,
pub superscript: ScriptMetrics,
pub subscript: ScriptMetrics,
/// Synthesized small capitals, percent of the font size.
pub small_caps_size: f64,
pub export_text: ExportText,
/// Background Contents chosen in New Document.
pub background: Background,
}
impl Default for DocSetup {
fn default() -> Self {
Self {
bleed: [0.0; 4],
outline_images: false,
highlight_substituted_fonts: true,
highlight_substituted_glyphs: false,
grid_size: GridSize::Medium,
grid_colors: GRID_COLOR_PRESETS[0].1,
simulate_paper: false,
flattener_preset: None,
discard_white_overprint: true,
language: LANGUAGES[0].0.to_string(),
quotes: Quotes::ENGLISH,
typographers_quotes: true,
superscript: ScriptMetrics::DEFAULT,
subscript: ScriptMetrics::DEFAULT,
small_caps_size: 70.0,
export_text: ExportText::Editable,
background: Background::Transparent,
}
}
}
impl DocSetup {
/// `artboard` grown by the bleed.
pub fn bleed_rect(&self, artboard: Rect) -> Rect {
crate::marks::outset(artboard, self.bleed)
}
pub fn has_bleed(&self) -> bool {
self.bleed.iter().any(|b| *b > 0.0)
}
/// The simulated paper colour.
pub fn paper(&self) -> Color {
self.grid_colors[0]
}
/// The name of the grid colour preset in use, or "Custom".
pub fn grid_colors_name(&self) -> &'static str {
GRID_COLOR_PRESETS.iter().find(|(_, c)| *c == self.grid_colors).map_or("Custom", |(n, _)| n)
}
/// The flattener preset in use.
pub fn flattener(&self) -> &str {
self.flattener_preset.as_deref().unwrap_or(DEFAULT_FLATTENER)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn quotes_open_and_close_by_context() {
let mut prev = None;
assert_eq!(Quotes::ENGLISH.apply("\"Hi,\" it's 'x'", &mut prev), "“Hi,” it’s ‘x’");
let german = language_quotes("german").unwrap();
let mut prev = Some('(');
assert_eq!(german.apply("\"a\"", &mut prev), "„a“");
assert_eq!(prev, Some('“'));
// Converting in pieces keeps the context.
let mut prev = None;
let a = Quotes::ENGLISH.apply("\"", &mut prev);
let b = Quotes::ENGLISH.apply("\"", &mut prev);
assert_eq!((a.as_str(), b.as_str()), ("“", "“"));
}
#[test]
fn bleed_grows_the_artboard() {
let s = DocSetup { bleed: [9.0, 9.0, 4.0, 2.0], ..Default::default() };
assert_eq!(s.bleed_rect(Rect::new(0.0, 0.0, 100.0, 50.0)), Rect::new(-4.0, -9.0, 102.0, 59.0));
assert!(s.has_bleed() && !DocSetup::default().has_bleed());
}
#[test]
fn presets_and_defaults() {
let d = DocSetup::default();
assert_eq!(d.grid_colors_name(), "Light");
assert_eq!(d.flattener(), "Medium Resolution");
assert_eq!(Background::parse("WHITE"), Some(Background::White));
assert_eq!(GridSize::parse("LARGE"), Some(GridSize::Large));
assert_eq!(ExportText::parse("appearance"), Some(ExportText::Appearance));
// A partial setup fills in the rest.
let s: DocSetup = serde_json::from_str(r#"{"bleed":[1,2,3,4]}"#).unwrap();
assert_eq!(s, DocSetup { bleed: [1.0, 2.0, 3.0, 4.0], ..DocSetup::default() });
}
}
+315
View File
@@ -0,0 +1,315 @@
//! Slices (Object → Slice): rectangles that cut the artwork into the pieces web output saves.
//!
//! User slices are rectangles of their own ([`Document::slices`]); object slices follow the
//! bounds of an object with [`Node::slice`] options; auto slices fill the rest of the slice region
//! (the artboards with Clip to Artboard on, else the art and the slices) and are never stored.
//! User slice ids come from the document's id counter, so a slice id never names an object and
//! one id list can hold both kinds (an object slice goes by its object's id).
//!
//! Slices are numbered left to right, top to bottom, auto slices included.
use std::sync::Arc;
use serde::{Deserialize, Serialize};
use vectorcraft_geom::Rect;
use crate::{Document, Node, NodeId};
/// Below this a slice edge or size is no edge or size (points).
const EPS: f64 = 1e-6;
/// Enums whose values have a stable key (params, JSON) and a label (dialogs).
macro_rules! keyed {
($(#[$m:meta])* $name:ident { $($(#[$vm:meta])* $v:ident = ($key:literal, $label:literal)),+ $(,)? }) => {
$(#[$m])*
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum $name {
$($(#[$vm])* $v,)+
}
impl $name {
pub const ALL: &'static [$name] = &[$($name::$v),+];
/// The value params and JSON use (`noImage`).
pub fn key(self) -> &'static str {
match self {
$($name::$v => $key,)+
}
}
/// The dialog label (`No Image`).
pub fn label(self) -> &'static str {
match self {
$($name::$v => $label,)+
}
}
/// The value `s` names: its key or label in any case.
pub fn parse(s: &str) -> Option<Self> {
let s = s.trim();
Self::ALL.iter().copied().find(|v| v.key().eq_ignore_ascii_case(s) || v.label().eq_ignore_ascii_case(s))
}
}
};
}
keyed!(
/// Slice Options → Slice Type: what web output puts in the slice's cell.
SliceKind {
/// The artwork as an image (with a link, alt text and a status message).
#[default]
Image = ("image", "Image"),
/// An empty cell showing `text` (HTML allowed) on the background.
NoImage = ("noImage", "No Image"),
/// The text of the sliced type object as HTML (object slices of type only).
HtmlText = ("htmlText", "HTML Text"),
}
);
keyed!(
/// Horizontal alignment of a No Image / HTML Text cell's text.
CellAlign {
#[default]
Default = ("default", "Default"),
Left = ("left", "Left"),
Center = ("center", "Center"),
Right = ("right", "Right"),
}
);
keyed!(
/// Vertical alignment of a No Image / HTML Text cell's text.
CellVAlign {
#[default]
Default = ("default", "Default"),
Top = ("top", "Top"),
Middle = ("middle", "Middle"),
Baseline = ("baseline", "Baseline"),
Bottom = ("bottom", "Bottom"),
}
);
/// Slice Options: how web output writes a slice.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct SliceOptions {
#[serde(skip_serializing_if = "crate::skip::is_default")]
pub kind: SliceKind,
/// The slice's file name in web output; empty: `<document>_<number>` ([`Document::slice_name`]).
#[serde(skip_serializing_if = "String::is_empty")]
pub name: String,
/// Image: the link the slice's image opens.
#[serde(skip_serializing_if = "String::is_empty")]
pub url: String,
/// Image: the frame the link opens in (`_blank`, `_self`, `_parent`, `_top` or a name).
#[serde(skip_serializing_if = "String::is_empty")]
pub target: String,
/// Image: the browser's status message over the slice.
#[serde(skip_serializing_if = "String::is_empty")]
pub message: String,
/// Image: the alternative text.
#[serde(skip_serializing_if = "String::is_empty")]
pub alt: String,
/// No Image: the text the cell shows (HTML allowed).
#[serde(skip_serializing_if = "String::is_empty")]
pub text: String,
/// The cell's background: empty (none), `matte` or `#rrggbb`.
#[serde(skip_serializing_if = "String::is_empty")]
pub background: String,
#[serde(skip_serializing_if = "crate::skip::is_default")]
pub h_align: CellAlign,
#[serde(skip_serializing_if = "crate::skip::is_default")]
pub v_align: CellVAlign,
}
/// A user slice: a rectangle drawn with the Slice tool or made by an Object → Slice command.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Slice {
/// From the document's id counter (never an object's id).
pub id: NodeId,
pub rect: Rect,
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
pub options: SliceOptions,
}
/// Where a slice comes from.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum SliceSource {
/// A [`Slice`] of the document.
User,
/// The bounds of an object with slice options.
Object,
/// Generated over what no other slice covers.
Auto,
}
impl SliceSource {
pub fn key(self) -> &'static str {
match self {
SliceSource::User => "user",
SliceSource::Object => "object",
SliceSource::Auto => "auto",
}
}
}
/// One slice as laid out: its id (none for auto slices), source, rectangle (clipped to the
/// artboards with Clip to Artboard on) and number (1-based).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct SliceArea {
pub id: Option<NodeId>,
pub source: SliceSource,
pub rect: Rect,
pub number: usize,
}
/// A rectangle with a size and finite coordinates.
pub fn valid_rect(r: Rect) -> bool {
[r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) && r.width() > EPS && r.height() > EPS
}
impl Document {
/// The user slice `id`.
pub fn slice(&self, id: NodeId) -> Option<&Slice> {
self.slices.iter().find(|s| s.id == id)
}
pub fn slice_mut(&mut self, id: NodeId) -> Option<&mut Slice> {
self.slices.iter_mut().find(|s| s.id == id)
}
/// Is `id` a user slice or an object with slice options?
pub fn is_slice(&self, id: NodeId) -> bool {
self.slice(id).is_some() || self.node(id).is_some_and(|n| n.slice.is_some())
}
/// The options of slice `id` (user or object).
pub fn slice_options(&self, id: NodeId) -> Option<&SliceOptions> {
match self.slice(id) {
Some(s) => Some(&s.options),
None => self.node(id)?.slice.as_deref(),
}
}
/// The rectangle of slice `id` before clipping: a user slice's own, an object slice's object's
/// visual bounds.
pub fn slice_bounds(&self, id: NodeId) -> Option<Rect> {
match self.slice(id) {
Some(s) => Some(s.rect),
None => self.node(id).filter(|n| n.slice.is_some())?.visual_bounds(),
}
}
/// The visible objects with slice options and their visual bounds, in paint order.
pub fn object_slices(&self) -> Vec<(NodeId, Rect)> {
fn walk(nodes: &[Arc<Node>], out: &mut Vec<(NodeId, Rect)>) {
for n in nodes.iter().filter(|n| n.visible) {
if n.slice.is_some()
&& let Some(b) = n.visual_bounds()
{
out.push((n.id, b));
}
if let Some(ch) = n.children() {
walk(ch, out);
}
}
}
let mut out = vec![];
walk(&self.layers, &mut out);
out
}
/// Every slice id: the user slices, then the object slices.
pub fn slice_ids(&self) -> Vec<NodeId> {
self.slices.iter().map(|s| s.id).chain(self.object_slices().into_iter().map(|(id, _)| id)).collect()
}
/// The box Clip to Artboard clips slices to: the artboards' bounds.
pub fn slice_clip(&self) -> Option<Rect> {
self.artboards.iter().map(|a| a.rect).reduce(|a, b| a.union(b))
}
/// The user and object slices with their rectangles as laid out (clipped to [`Self::slice_clip`]
/// when Clip to Artboard is on; one wholly outside stays as it is).
fn cut_slices(&self) -> Vec<(NodeId, SliceSource, Rect)> {
let clip = self.slices_clip_to_artboard.then(|| self.slice_clip()).flatten();
let clipped = |r: Rect| clip.map(|c| c.intersect(r)).filter(|c| valid_rect(*c)).unwrap_or(r);
let users = self.slices.iter().map(|s| (s.id, SliceSource::User, s.rect));
let objects = self.object_slices().into_iter().map(|(id, r)| (id, SliceSource::Object, r));
users.chain(objects).map(|(id, src, r)| (id, src, clipped(r))).collect()
}
/// The slices as laid out, numbered left to right, top to bottom: the user and object slices
/// and the auto slices filling the rest of the region (the artboards with Clip to Artboard on,
/// else the visible art and the slices). Empty while the document has no user or object slice.
pub fn slice_layout(&self) -> Vec<SliceArea> {
let cut = self.cut_slices();
if cut.is_empty() {
return vec![];
}
let region = if self.slices_clip_to_artboard { self.slice_clip() } else { None }
.or_else(|| cut.iter().fold(self.art_bounds(), |acc, (_, _, r)| vectorcraft_geom::union_opt(acc, Some(*r))));
let rects: Vec<Rect> = cut.iter().map(|(_, _, r)| *r).collect();
let autos = region.map(|g| auto_slices(g, &rects)).unwrap_or_default();
let mut out: Vec<SliceArea> = cut
.into_iter()
.map(|(id, source, rect)| SliceArea { id: Some(id), source, rect, number: 0 })
.chain(autos.into_iter().map(|rect| SliceArea { id: None, source: SliceSource::Auto, rect, number: 0 }))
.collect();
out.sort_by(|a, b| a.rect.y0.total_cmp(&b.rect.y0).then(a.rect.x0.total_cmp(&b.rect.x0)));
for (i, a) in out.iter_mut().enumerate() {
a.number = i + 1;
}
out
}
/// The name web output gives slice `area`: its options' name, else `<document>_<number>`
/// (two digits at least, `Untitled-1_03`).
pub fn slice_name(&self, area: &SliceArea) -> String {
match area.id.and_then(|id| self.slice_options(id)).filter(|o| !o.name.is_empty()) {
Some(o) => o.name.clone(),
None => {
let stem = self.title.rsplit_once('.').map_or(self.title.as_str(), |(s, _)| s);
format!("{stem}_{:02}", area.number)
}
}
}
}
/// The auto slices of `region`: rectangles covering what none of `cut` covers, without
/// overlapping each other or `cut`. The region is cut into rows at every slice's top and bottom;
/// each row's uncovered spans become slices, and a span continuing the one above it (same left and
/// right) extends it.
pub fn auto_slices(region: Rect, cut: &[Rect]) -> Vec<Rect> {
if !valid_rect(region) {
return vec![];
}
let inside: Vec<Rect> = cut.iter().map(|r| region.intersect(*r)).filter(|r| valid_rect(*r)).collect();
let mut ys: Vec<f64> = inside.iter().flat_map(|r| [r.y0, r.y1]).chain([region.y0, region.y1]).collect();
ys.sort_by(f64::total_cmp);
ys.dedup_by(|a, b| (*a - *b).abs() <= EPS);
let (mut open, mut done): (Vec<Rect>, Vec<Rect>) = (vec![], vec![]);
for band in ys.windows(2) {
let [y0, y1] = [band[0], band[1]];
let mid = (y0 + y1) / 2.0;
let mut spans: Vec<(f64, f64)> = inside.iter().filter(|r| r.y0 < mid && mid < r.y1).map(|r| (r.x0, r.x1)).collect();
spans.sort_by(|a, b| a.0.total_cmp(&b.0));
// The uncovered spans of this row.
let mut free = vec![];
let mut x = region.x0;
for (a, b) in spans {
if a - x > EPS {
free.push((x, a));
}
x = x.max(b);
}
if region.x1 - x > EPS {
free.push((x, region.x1));
}
// Spans continuing an open slice extend it; the others close.
let mut next = Vec::with_capacity(free.len());
for (a, b) in free {
match open.iter().position(|r: &Rect| (r.x0 - a).abs() <= EPS && (r.x1 - b).abs() <= EPS) {
Some(i) => {
let mut r = open.swap_remove(i);
r.y1 = y1;
next.push(r);
}
None => next.push(Rect::new(a, y0, b, y1)),
}
}
done.append(&mut open);
open = next;
}
done.append(&mut open);
done
}
+511
View File
@@ -0,0 +1,511 @@
//! Graphic style libraries: named, read-only sets of graphic styles (Window → Graphic Style
//! Libraries). The built-in ones are generated here in code ([`STYLE_LIBRARIES`]); user libraries
//! are `.vcstyles` files ([`write`], [`read`]): JSON holding the styles and the pattern
//! definitions they paint with.
//!
//! Library styles stand alone: no id, and no links to the swatches of the document they came from
//! ([`StyleLibrary::from_document`]).
use std::sync::{Arc, OnceLock};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use vectorcraft_color::{BlendMode, Color, Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop, Paint};
use vectorcraft_geom::Point;
use crate::{
Appearance, AppearanceItem, Arrowhead, Dash, Document, Effect, FillLayer, GraphicStyle, Knockout, LineCap, LineJoin, PatternDef, StrokeAlign,
StrokeLayer, WidthProfile,
};
/// A graphic style library: its name, its styles and the patterns they paint with.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct StyleLibrary {
pub name: String,
#[serde(default)]
pub styles: Vec<GraphicStyle>,
/// The pattern swatches the styles' fills and strokes paint with.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub patterns: Vec<PatternDef>,
}
impl StyleLibrary {
pub fn len(&self) -> usize {
self.styles.len()
}
pub fn is_empty(&self) -> bool {
self.styles.is_empty()
}
pub fn style(&self, name: &str) -> Option<&GraphicStyle> {
self.styles.iter().find(|g| g.name == name)
}
/// The document's styles `names` (empty: all of them, in panel order) as a library named
/// `name`, standing alone ([`GraphicStyle::standalone`]) with the patterns they paint with.
pub fn from_document(d: &Document, names: &[String], name: String) -> Result<Self, String> {
if let Some(n) = names.iter().find(|n| d.graphic_style(n).is_none()) {
return Err(format!("no graphic style `{n}`"));
}
let styles: Vec<GraphicStyle> =
d.graphic_styles.iter().filter(|g| names.is_empty() || names.contains(&g.name)).map(GraphicStyle::standalone).collect();
let mut patterns: Vec<PatternDef> = vec![];
for p in styles.iter().flat_map(GraphicStyle::patterns) {
if !patterns.iter().any(|x| x.name == p)
&& let Some(def) = d.pattern(p)
{
patterns.push(def.clone());
}
}
Ok(Self { name, styles, patterns })
}
}
impl GraphicStyle {
/// Do both styles look the same (appearance and transparency; names and ids aside)?
pub fn same_look(&self, other: &GraphicStyle) -> bool {
(&self.appearance, self.opacity, self.blend, self.isolate, self.knockout, self.unit_box)
== (&other.appearance, other.opacity, other.blend, other.isolate, other.knockout, other.unit_box)
}
/// The style as a library holds it: no id, and its paints unlinked from swatches.
pub fn standalone(&self) -> GraphicStyle {
let mut g = GraphicStyle { id: 0, ..self.clone() };
for it in &mut g.appearance.items {
match it.paint_mut() {
// The colour shown stays, unlinked.
Paint::Solid { swatch, tint, .. } => (*swatch, *tint) = (None, 1.0),
Paint::Gradient(gp) => {
gp.swatch = None;
gp.gradient.stops.iter_mut().for_each(|st| st.set_color(st.color, None));
}
Paint::None | Paint::Pattern { .. } => {}
}
}
g
}
/// The names of the patterns the style's fills and strokes paint with.
pub fn patterns(&self) -> impl Iterator<Item = &str> {
self.appearance.items.iter().filter_map(|it| match it.paint() {
Paint::Pattern { pattern, .. } => Some(pattern.as_str()),
_ => None,
})
}
}
// ---------- .vcstyles files ----------
/// The extension (and `format` header) of graphic style library files.
pub const STYLES_EXT: &str = "vcstyles";
/// The file: a header around the library.
#[derive(Serialize, Deserialize)]
struct NativeFile {
format: String,
version: u32,
#[serde(flatten)]
library: StyleLibrary,
}
/// `lib` as a `.vcstyles` file.
pub fn write(lib: &StyleLibrary) -> String {
let file = NativeFile { format: STYLES_EXT.into(), version: 1, library: lib.clone() };
serde_json::to_string_pretty(&file).unwrap_or_default()
}
/// Read a `.vcstyles` file; an unnamed library is called `name`.
pub fn read(text: &str, name: &str) -> Result<StyleLibrary, String> {
let f: NativeFile = serde_json::from_str(text.trim_start_matches('\u{feff}')).map_err(|e| format!("not a graphic style library: {e}"))?;
if f.format != STYLES_EXT {
return Err(format!("not a graphic style library (format `{}`)", f.format));
}
let mut lib = f.library;
if lib.name.trim().is_empty() {
lib.name = name.into();
}
Ok(lib)
}
/// Does `text` look like a `.vcstyles` file (its header names the format)?
pub fn sniff(text: &str) -> bool {
let t = text.trim_start_matches('\u{feff}').trim_start();
let head = t.char_indices().nth(256).map_or(t, |(i, _)| &t[..i]);
t.starts_with('{') && head.contains(&format!("\"{STYLES_EXT}\""))
}
// ---------- built-in libraries ----------
/// A built-in library: a stable id, its menu name and the function that makes its styles.
pub struct BuiltinStyleLibrary {
pub id: &'static str,
pub name: &'static str,
make: fn() -> Vec<GraphicStyle>,
}
/// The built-in graphic style libraries, in menu order.
pub const STYLE_LIBRARIES: &[BuiltinStyleLibrary] = &[
BuiltinStyleLibrary { id: "shadows-glows", name: "Shadows and Glows", make: shadows_glows },
BuiltinStyleLibrary { id: "outlines-rules", name: "Outlines and Rules", make: outlines_rules },
BuiltinStyleLibrary { id: "hand-drawn", name: "Hand-Drawn", make: hand_drawn },
BuiltinStyleLibrary { id: "gradient-finishes", name: "Gradient Finishes", make: gradient_finishes },
BuiltinStyleLibrary { id: "shape-effects", name: "Shape Effects", make: shape_effects },
BuiltinStyleLibrary { id: "blends-transparency", name: "Blends and Transparency", make: blends_transparency },
];
/// Built-in library `id`, made once.
pub fn builtin_style_library(id: &str) -> Option<Arc<StyleLibrary>> {
static LIBS: OnceLock<Vec<Arc<StyleLibrary>>> = OnceLock::new();
let libs = LIBS.get_or_init(|| {
STYLE_LIBRARIES.iter().map(|b| Arc::new(StyleLibrary { name: b.name.into(), styles: (b.make)(), patterns: vec![] })).collect()
});
STYLE_LIBRARIES.iter().position(|b| b.id == id).map(|i| libs[i].clone())
}
fn hex(h: &str) -> Color {
Color::from_hex(h).unwrap_or(Color::BLACK)
}
fn solid(h: &str) -> Paint {
Paint::solid(hex(h))
}
fn fill(h: &str) -> FillLayer {
FillLayer::new(solid(h))
}
fn stroke(h: &str, width: f64) -> StrokeLayer {
StrokeLayer::new(solid(h), width)
}
/// A stroke with round caps and joins.
fn round(h: &str, width: f64) -> StrokeLayer {
StrokeLayer { cap: LineCap::Round, join: LineJoin::Round, ..stroke(h, width) }
}
/// Live effect `id` with `params` (the others keep the effect's defaults).
fn fx(id: &str, params: Value) -> Effect {
Effect { id: id.into(), params, visible: true }
}
/// A gradient of `(offset, colour, opacity)` stops.
fn gradient(kind: GradientKind, stops: &[(f32, &str, f32)]) -> Gradient {
Gradient { kind, stops: stops.iter().map(|&(offset, c, opacity)| GradientStop { opacity, ..GradientStop::new(offset, hex(c)) }).collect() }
}
/// A linear gradient fitted to each object's box at `angle` degrees (90: upwards).
fn linear(angle: f64, stops: &[(f32, &str, f32)]) -> Paint {
Paint::Gradient(Box::new(GradientPaint { angle, ..GradientPaint::new(gradient(GradientKind::Linear, stops)) }))
}
/// A radial gradient placed in the unit box (each object gets it at the same place relative to its
/// bounds): centred at `(x, y)` with `radius`.
fn radial_at(x: f64, y: f64, radius: f64, stops: &[(f32, &str, f32)]) -> Paint {
let geom = GradientGeom { start: Point::new(x, y), end: Point::new(x + radius, y), aspect: 1.0, focal: None };
Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..GradientPaint::new(gradient(GradientKind::Radial, stops)) }))
}
/// A style of fills and strokes `items` (painted first to last) and object `effects`.
fn style(name: &str, items: Vec<AppearanceItem>, effects: Vec<Effect>) -> GraphicStyle {
GraphicStyle::new(name, Appearance { items, effects, contents_index: None })
}
use AppearanceItem::{Fill as F, Stroke as S};
fn shadows_glows() -> Vec<GraphicStyle> {
let shadow = |opacity: f64, x: f64, y: f64, blur: f64, color: &str| {
fx("stylize.dropShadow", json!({"mode": "multiply", "opacity": opacity, "x": x, "y": y, "blur": blur, "color": color}))
};
vec![
style("Soft Shadow", vec![F(fill("#f4f1ea"))], vec![shadow(45.0, 4.0, 4.0, 6.0, "#1d1b2a")]),
style(
"Hard Shadow",
vec![F(fill("#ffd166")), S(stroke("#1d1b2a", 2.0))],
vec![fx("stylize.dropShadow", json!({"mode": "normal", "opacity": 100.0, "x": 5.0, "y": 5.0, "blur": 0.0, "color": "#1d1b2a"}))],
),
style("Lifted Card", vec![F(fill("#ffffff")), S(stroke("#d9d9e3", 0.5))], vec![shadow(30.0, 0.0, 8.0, 12.0, "#2b2d42")]),
style(
"Halo",
vec![F(fill("#2b2d42"))],
vec![fx("stylize.outerGlow", json!({"mode": "normal", "opacity": 90.0, "blur": 8.0, "color": "#8ecae6"}))],
),
style(
"Neon Tube",
vec![S(round("#ff4fd8", 4.0)), S(round("#ffe8fb", 1.5))],
vec![fx("stylize.outerGlow", json!({"mode": "normal", "opacity": 85.0, "blur": 7.0, "color": "#ff4fd8"}))],
),
style(
"Inner Light",
vec![F(fill("#3a86ff"))],
vec![fx("stylize.innerGlow", json!({"mode": "screen", "opacity": 70.0, "blur": 9.0, "color": "#ffffff", "source": "center"}))],
),
style(
"Ember",
vec![F(fill("#e85d04"))],
vec![
fx("stylize.innerGlow", json!({"mode": "screen", "opacity": 80.0, "blur": 6.0, "color": "#ffba08", "source": "edge"})),
fx("stylize.outerGlow", json!({"mode": "normal", "opacity": 70.0, "blur": 5.0, "color": "#dc2f02"})),
],
),
style("Feathered", vec![F(fill("#8338ec"))], vec![fx("stylize.feather", json!({"radius": 6.0}))]),
style("Haze", vec![F(FillLayer { opacity: 0.8, ..fill("#06d6a0") })], vec![fx("blur.gaussian", json!({"radius": 3.0}))]),
]
}
fn outlines_rules() -> Vec<GraphicStyle> {
let dashed =
|h: &str, width: f64, pattern: Vec<f64>| StrokeLayer { dash: Some(Dash { pattern, offset: 0.0, align_corners: true }), ..round(h, width) };
let keyline = |h: &str, width: f64, offset: f64| StrokeLayer {
effects: vec![fx("path.offsetPath", json!({"offset": offset, "joins": "round"}))],
..stroke(h, width)
};
vec![
style("Double Rule", vec![F(fill("#ffffff")), S(stroke("#14213d", 6.0)), S(stroke("#ffffff", 3.0))], vec![]),
style("Triple Rule", vec![F(fill("#fefae0")), S(stroke("#283618", 10.0)), S(stroke("#fefae0", 6.0)), S(stroke("#283618", 2.0))], vec![]),
style("Dashed Border", vec![F(fill("#e9f5f2")), S(dashed("#264653", 2.0, vec![6.0, 4.0]))], vec![]),
style("Dotted Border", vec![F(fill("#fff4e6")), S(dashed("#e76f51", 3.0, vec![0.0, 6.0]))], vec![]),
style("Offset Keyline", vec![F(fill("#e9c46a")), S(keyline("#264653", 1.5, 4.0))], vec![]),
style("Inset Keyline", vec![F(fill("#2a9d8f")), S(keyline("#ffffff", 1.5, -4.0))], vec![]),
style("Outside Stroke", vec![F(fill("#f4a261")), S(StrokeLayer { align: StrokeAlign::Outside, ..stroke("#264653", 4.0) })], vec![]),
style("Tapered Ink", vec![S(StrokeLayer { profile: Some(WidthProfile::lens()), ..round("#1b1b1b", 5.0) })], vec![]),
style("Pointer", vec![S(StrokeLayer { end_arrow: Some(Arrowhead::Triangle), ..round("#e76f51", 2.0) })], vec![]),
style("Highlighter", vec![S(StrokeLayer { opacity: 0.6, blend: BlendMode::Multiply, ..round("#ffd60a", 10.0) })], vec![]),
]
}
fn hand_drawn() -> Vec<GraphicStyle> {
let rough = |h: &str, width: f64, seed: u32| StrokeLayer {
effects: vec![fx("distort.roughen", json!({"size": 1.5, "relative": true, "detail": 8.0, "points": "smooth", "seed": seed}))],
..round(h, width)
};
let scribble = |h: &str, angle: f64, opacity: f32| FillLayer {
opacity,
effects: vec![fx("stylize.scribble", json!({"angle": angle, "strokeWidth": 1.5, "spacing": 4.0, "curviness": 5.0, "variation": 0.5}))],
..fill(h)
};
vec![
style("Sketchy Line", vec![F(fill("#fefae0")), S(rough("#1d3557", 1.25, 1)), S(rough("#1d3557", 0.75, 7))], vec![]),
style("Scribble Fill", vec![F(scribble("#e63946", 30.0, 1.0)), S(rough("#1d3557", 1.25, 3))], vec![]),
style("Crosshatch", vec![F(scribble("#457b9d", 45.0, 0.8)), F(scribble("#457b9d", -45.0, 0.8)), S(rough("#1d3557", 1.0, 5))], vec![]),
style(
"Wobble",
vec![F(fill("#a8dadc")), S(round("#1d3557", 2.0))],
vec![fx("distort.tweak", json!({"h": 3.0, "v": 3.0, "relative": true, "seed": 5}))],
),
style(
"Zig Zag Edge",
vec![
F(fill("#f1faee")),
S(StrokeLayer {
effects: vec![fx("distort.zigZag", json!({"size": 3.0, "relative": false, "ridges": 6, "points": "corner"}))],
..stroke("#e63946", 1.5)
}),
],
vec![],
),
style(
"Wavy Edge",
vec![F(fill("#bde0fe")), S(round("#3a5a9b", 1.5))],
vec![fx("distort.zigZag", json!({"size": 3.0, "relative": false, "ridges": 5, "points": "smooth"}))],
),
style("Puffy", vec![F(fill("#ffc8dd")), S(round("#c9184a", 1.5))], vec![fx("distort.puckerBloat", json!({"amount": 25.0}))]),
style("Starburst", vec![F(fill("#ffbe0b")), S(stroke("#fb5607", 1.0))], vec![fx("distort.puckerBloat", json!({"amount": -40.0}))]),
]
}
fn gradient_finishes() -> Vec<GraphicStyle> {
let rim = |h: &str| S(stroke(h, 1.0));
vec![
style(
"Glossy",
vec![
F(FillLayer::new(linear(-90.0, &[(0.0, "#7ab8ff", 1.0), (1.0, "#1d4ed8", 1.0)]))),
F(FillLayer::new(linear(-90.0, &[(0.0, "#ffffff", 0.7), (0.5, "#ffffff", 0.0)]))),
rim("#1e3a8a"),
],
vec![],
),
style(
"Brushed Metal",
vec![
F(FillLayer::new(linear(
0.0,
&[(0.0, "#bfbfbf", 1.0), (0.3, "#f5f5f5", 1.0), (0.55, "#a6a6a6", 1.0), (0.8, "#e6e6e6", 1.0), (1.0, "#8c8c8c", 1.0)],
))),
rim("#595959"),
],
vec![],
),
style(
"Spotlight",
vec![F(FillLayer::new(radial_at(0.35, 0.3, 0.9, &[(0.0, "#ffffff", 1.0), (0.35, "#ffbe0b", 1.0), (1.0, "#fb5607", 1.0)])))],
vec![],
),
style(
"Sunset Band",
vec![F(FillLayer::new(linear(-90.0, &[(0.0, "#ffbe0b", 1.0), (0.35, "#fb5607", 1.0), (0.7, "#ff006e", 1.0), (1.0, "#8338ec", 1.0)])))],
vec![],
),
style(
"Sea Glass",
vec![
F(FillLayer {
opacity: 0.85,
..FillLayer::new(linear(-45.0, &[(0.0, "#caf0f8", 1.0), (0.5, "#48cae4", 1.0), (1.0, "#0077b6", 1.0)]))
}),
rim("#03045e"),
],
vec![],
),
style(
"Pearl",
vec![
F(FillLayer::new(radial_at(0.4, 0.35, 0.8, &[(0.0, "#ffffff", 1.0), (0.5, "#e8e1f0", 1.0), (1.0, "#b8b0c8", 1.0)]))),
S(stroke("#8a7fa0", 0.75)),
],
vec![],
),
style(
"Chrome Rim",
vec![F(fill("#22223b")), S(StrokeLayer::new(linear(-90.0, &[(0.0, "#f8f9fa", 1.0), (0.5, "#6c757d", 1.0), (1.0, "#dee2e6", 1.0)]), 4.0))],
vec![],
),
style(
"Glow Orb",
vec![F(FillLayer::new(radial_at(0.5, 0.5, 0.5, &[(0.0, "#ffffff", 1.0), (0.4, "#80ffdb", 1.0), (1.0, "#5390d9", 1.0)])))],
vec![fx("stylize.outerGlow", json!({"mode": "normal", "opacity": 60.0, "blur": 6.0, "color": "#80ffdb"}))],
),
]
}
fn shape_effects() -> Vec<GraphicStyle> {
let basic = |f: &str, s: &str, w: f64| vec![F(fill(f)), S(round(s, w))];
vec![
style("Rounded", basic("#90be6d", "#43aa8b", 2.0), vec![fx("stylize.roundCorners", json!({"radius": 10.0}))]),
style(
"Pill Badge",
vec![F(fill("#f94144"))],
vec![fx("convertToShape.roundedRectangle", json!({"relative": true, "extraW": 12.0, "extraH": 6.0, "radius": 40.0}))],
),
style(
"Round Badge",
vec![F(fill("#577590")), S(stroke("#ffffff", 2.0))],
vec![fx("convertToShape.ellipse", json!({"relative": true, "extraW": 10.0, "extraH": 10.0}))],
),
style("Arc", basic("#f8961e", "#f3722c", 1.5), vec![fx("warp.arc", json!({"bend": 30.0}))]),
style("Flag Wave", basic("#277da1", "#1d4e89", 1.5), vec![fx("warp.flag", json!({"bend": 25.0}))]),
style("Bulge", basic("#f9c74f", "#f8961e", 1.5), vec![fx("warp.bulge", json!({"bend": 30.0}))]),
style("Twisted", basic("#4d908e", "#264653", 1.5), vec![fx("distort.twist", json!({"angle": 30.0}))]),
style(
"Echo",
vec![F(FillLayer { opacity: 0.55, ..fill("#43aa8b") }), S(stroke("#264653", 1.0))],
vec![fx("distort.transform", json!({"copies": 3, "moveH": 4.0, "moveV": 4.0}))],
),
style(
"Spiral Copies",
vec![F(FillLayer { opacity: 0.35, ..fill("#f94144") }), S(stroke("#9d0208", 0.75))],
vec![fx("distort.transform", json!({"copies": 5, "rotate": 12.0, "scaleH": 90.0, "scaleV": 90.0}))],
),
]
}
fn blends_transparency() -> Vec<GraphicStyle> {
let with =
|g: GraphicStyle, opacity: f32, blend: BlendMode, isolate: bool, knockout: Knockout| GraphicStyle { opacity, blend, isolate, knockout, ..g };
let one = |name: &str, h: &str| style(name, vec![F(fill(h))], vec![]);
// A fill blending with the fills under it, so the style shows on any backdrop.
let over = |paint: Paint, blend: BlendMode| F(FillLayer { blend, ..FillLayer::new(paint) });
vec![
with(one("Multiply Tint", "#ffbe0b"), 1.0, BlendMode::Multiply, false, Knockout::Neutral),
with(one("Darken Veil", "#4cc9f0"), 0.85, BlendMode::Darken, false, Knockout::Neutral),
with(style("Ghosted", vec![F(fill("#7209b7")), S(stroke("#3a0ca3", 1.0))], vec![]), 0.4, BlendMode::Normal, false, Knockout::Neutral),
with(one("Invert", "#ffffff"), 1.0, BlendMode::Difference, false, Knockout::Neutral),
style("Two Tone", vec![F(fill("#4361ee")), F(FillLayer { opacity: 0.6, blend: BlendMode::Multiply, ..fill("#f72585") })], vec![]),
style(
"Overlay Glaze",
vec![F(fill("#f72585")), over(linear(-90.0, &[(0.0, "#ffffff", 1.0), (1.0, "#000000", 1.0)]), BlendMode::Overlay)],
vec![],
),
style(
"Screen Light",
vec![F(fill("#3a0ca3")), over(radial_at(0.5, 0.4, 0.6, &[(0.0, "#4cc9f0", 1.0), (1.0, "#000000", 1.0)]), BlendMode::Screen)],
vec![],
),
with(
style(
"Soft Light Wash",
vec![F(fill("#0096c7")), over(linear(0.0, &[(0.0, "#ffffff", 1.0), (1.0, "#03045e", 1.0)]), BlendMode::SoftLight)],
vec![],
),
1.0,
BlendMode::Normal,
true,
Knockout::Neutral,
),
with(style("Knockout Group", vec![F(fill("#4895ef")), S(stroke("#3f37c9", 1.0))], vec![]), 0.7, BlendMode::Normal, true, Knockout::On),
]
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn builtin_libraries_are_non_empty_with_unique_names() {
let mut ids: Vec<&str> = STYLE_LIBRARIES.iter().map(|b| b.id).collect();
ids.sort_unstable();
ids.dedup();
assert_eq!(ids.len(), STYLE_LIBRARIES.len(), "library ids are unique");
for b in STYLE_LIBRARIES {
let lib = builtin_style_library(b.id).unwrap();
assert_eq!(lib.name, b.name);
assert!(lib.len() >= 6, "{}", b.id);
let mut names: Vec<&str> = lib.styles.iter().map(|g| g.name.as_str()).collect();
names.sort_unstable();
names.dedup();
assert_eq!(names.len(), lib.len(), "style names in {} are unique", b.id);
assert!(lib.styles.iter().all(|g| g.id == 0 && g.unit_box && !g.appearance.items.is_empty()));
}
assert!(Arc::ptr_eq(&builtin_style_library("hand-drawn").unwrap(), &builtin_style_library("hand-drawn").unwrap()), "made once");
assert!(builtin_style_library("nope").is_none());
}
#[test]
fn vcstyles_round_trip() {
let mut lib = (*builtin_style_library("gradient-finishes").unwrap()).clone();
lib.styles.extend(builtin_style_library("blends-transparency").unwrap().styles.iter().cloned());
let text = write(&lib);
assert!(sniff(&text) && !sniff("{\"format\": \"vectorcraft\"}") && !sniff("GIMP Palette"));
assert_eq!(read(&text, "Fallback").unwrap(), lib);
// An unnamed library takes the file's name; other JSON isn't a library.
let unnamed = write(&StyleLibrary { name: " ".into(), ..lib.clone() });
assert_eq!(read(&unnamed, "Mine").unwrap().name, "Mine");
assert!(read("{\"format\": \"vcswatches\", \"version\": 1, \"name\": \"x\"}", "x").is_err());
}
#[test]
fn a_library_from_a_document_stands_alone_and_keeps_its_patterns() {
let mut d = Document::new(100.0, 100.0);
let red = Paint::Solid { color: Color::rgb(1.0, 0.0, 0.0), swatch: Some("Red".into()), tint: 0.5 };
let dots = Paint::Pattern { pattern: "Dots".into(), xf: Default::default() };
d.patterns.push(PatternDef::new("Dots", vec![]));
let mut g = GraphicStyle::new("Linked", Appearance::basic(red, dots, 2.0));
g.id = 9;
d.graphic_styles.push(g);
let lib = StyleLibrary::from_document(&d, &["Linked".into()], "Mine".into()).unwrap();
assert_eq!(lib.len(), 1);
let s = &lib.styles[0];
assert_eq!((s.id, s.appearance.fill_paint()), (0, Paint::solid(Color::rgb(1.0, 0.0, 0.0))), "unlinked, no id");
assert_eq!(lib.patterns.iter().map(|p| p.name.as_str()).collect::<Vec<_>>(), ["Dots"]);
assert!(s.same_look(&GraphicStyle { name: "Other".into(), id: 3, ..s.clone() }));
assert!(!s.same_look(&GraphicStyle { opacity: 0.5, ..s.clone() }));
assert_eq!(StyleLibrary::from_document(&d, &[], "All".into()).unwrap().len(), d.graphic_styles.len());
assert!(StyleLibrary::from_document(&d, &["nope".into()], "x".into()).is_err());
// Gradients lose their swatch and their stops' links too.
let mut gp = GradientPaint::new(gradient(GradientKind::Linear, &[(0.0, "#ff0000", 1.0), (1.0, "#0000ff", 1.0)]));
gp.swatch = Some("Sunset".into());
gp.gradient.stops[0].set_color(hex("#ff0000"), Some(("Red".into(), 0.5)));
let g = GraphicStyle::new("G", Appearance::basic(Paint::Gradient(Box::new(gp)), Paint::None, 1.0)).standalone();
let Paint::Gradient(gp) = g.appearance.fill_paint() else { panic!("a gradient") };
assert!(gp.swatch.is_none() && gp.gradient.stops.iter().all(|s| s.swatch.is_none() && s.tint == 1.0));
}
}
+89 -45
View File
@@ -1,13 +1,16 @@
//! Swatch lookups across colour groups and the walks over the paints that link to swatches.
//!
//! A swatch lives either in `Document::swatches` or in one of `Document::swatch_groups`; every
//! lookup here covers both. Solid paints link to a global swatch by name (`Paint::Solid.swatch`);
//! [`Document::map_solid_paints`] rewrites those links (and colours) wherever art can hold them,
//! copying only the nodes that change.
//! lookup here covers both. Solid paints and gradient stops link to a global swatch by name, at a
//! tint (`Paint::Solid.swatch` / `.tint`, `GradientStop.swatch` / `.tint`); a tint swatch is a
//! swatch whose own paint links to its base that way. [`Document::map_solid_paints`] rewrites
//! those links (and colours) wherever art and swatches hold them, copying only the nodes that
//! change.
use std::sync::Arc;
use vectorcraft_color::{Color, Paint, Swatch};
use vectorcraft_color::swatch::REGISTRATION;
use vectorcraft_color::{Color, Paint, Swatch, tint_percent};
use crate::{AppearanceItem, Document, Node, NodeId, NodeKind};
@@ -19,12 +22,50 @@ impl Document {
pub fn swatches_iter_mut(&mut self) -> impl Iterator<Item = &mut Swatch> {
self.swatches.iter_mut().chain(self.swatch_groups.iter_mut().flat_map(|g| g.swatches.iter_mut()))
}
/// Swatch `name`, the built-in Registration swatch ([`vectorcraft_color::swatch::registration`])
/// included.
pub fn swatch(&self, name: &str) -> Option<&Swatch> {
self.swatches_iter().find(|s| s.name == name)
self.swatches_iter().find(|s| s.name == name).or_else(|| (name == REGISTRATION).then(vectorcraft_color::swatch::registration))
}
pub fn swatch_mut(&mut self, name: &str) -> Option<&mut Swatch> {
self.swatches_iter_mut().find(|s| s.name == name)
}
/// The colour of global (or spot) swatch `name`, which its tints scale ([`Document::linked_color`]
/// of its own); `None` when `name` isn't a global solid colour of its own (a tint swatch isn't).
pub fn global_color(&self, name: &str) -> Option<Color> {
let w = self.swatch(name).filter(|w| w.global)?;
match &w.paint {
Paint::Solid { color, swatch: None, .. } => Some(self.linked_color(*color, w.spot)),
_ => None,
}
}
/// The colour art linked to a swatch of `color` shows and prints from: a Lab spot colour is
/// its working-CMYK equivalent when the Spot Colors options use CMYK values
/// ([`Document::spot_use_lab`] off); any other colour is itself.
pub fn linked_color(&self, color: Color, spot: bool) -> Color {
match color {
Color::Lab { .. } if spot && !self.spot_use_lab => {
let cms = vectorcraft_color::cms::active();
cms.convert(&color, vectorcraft_color::cms::Model::Cmyk, cms.settings().intent)
}
_ => color,
}
}
/// The link a colour taken from swatch `name` gets: a global solid colour links to itself at
/// 100 %, a tint swatch to its base at its tint; `None` for other swatches.
pub fn swatch_link(&self, name: &str) -> Option<(String, f32)> {
let w = self.swatch(name)?;
match (w.tint_of(), &w.paint) {
(Some((base, tint)), _) => Some((base.to_string(), tint)),
(None, Paint::Solid { .. }) if w.global => Some((name.to_string(), 1.0)),
_ => None,
}
}
/// Tint `tint` (0..1) of global swatch `name` as a solid paint linked to it.
pub fn tint_paint(&self, name: &str, tint: f32) -> Option<Paint> {
let tint = tint.clamp(0.0, 1.0);
Some(Paint::Solid { color: self.global_color(name)?.tinted(tint), swatch: Some(name.to_string()), tint })
}
/// Index of the colour group holding swatch `name` (`None` when ungrouped or missing).
pub fn swatch_group_of(&self, name: &str) -> Option<usize> {
self.swatch_groups.iter().position(|g| g.swatches.iter().any(|s| s.name == name))
@@ -49,6 +90,7 @@ impl Document {
/// "New Pattern Swatch 1"…
pub fn new_swatch_name(&self, paint: &Paint) -> String {
let base = match paint {
Paint::Solid { swatch: Some(n), tint, .. } if *tint < 1.0 => return self.free_swatch_name(&format!("{n} {}%", tint_percent(*tint))),
Paint::Solid { color, .. } => return self.free_swatch_name(&color_name(*color)),
Paint::Gradient(_) => "New Gradient Swatch",
_ => "New Pattern Swatch",
@@ -66,11 +108,12 @@ impl Document {
Some(list.remove(i))
}
/// Visit every solid paint (fills, strokes and text runs) in the art, symbol definitions,
/// pattern tiles and graphic styles. `f(colour, link)` may change both and returns true when it
/// did. Only nodes holding a changed paint (and the paths to them) are copied. Returns the
/// number of changed paints.
pub fn map_solid_paints(&mut self, f: &mut dyn FnMut(&mut Color, &mut Option<String>) -> bool) -> usize {
/// Visit every colour that can link to a swatch — solid paints and gradient stops of fills,
/// strokes and text runs — in the art, symbol definitions, pattern tiles, graphic styles and the
/// swatches themselves (tint swatches, gradient swatches' stops). `f(colour, link, tint)` may
/// change them and returns true when it did ([`Paint::map_links`]). Only nodes holding a changed
/// paint (and the paths to them) are copied. Returns the number of changed paints.
pub fn map_solid_paints(&mut self, f: &mut LinkFn) -> usize {
let mut n = map_trees(&mut self.layers, f);
for s in &mut self.symbols {
n += map_tree(&mut s.art, f);
@@ -80,15 +123,18 @@ impl Document {
}
for gs in &mut self.graphic_styles {
for it in &mut gs.appearance.items {
n += usize::from(map_solid(item_paint_mut(it), f));
n += usize::from(item_paint_mut(it).map_links(f));
}
}
for w in self.swatches_iter_mut() {
n += usize::from(w.paint.map_links(f));
}
n
}
/// [`Document::map_solid_paints`] limited to the subtrees of `ids` (each paint visited once even
/// when an id is inside another).
pub fn map_solid_paints_in(&mut self, ids: &[NodeId], f: &mut dyn FnMut(&mut Color, &mut Option<String>) -> bool) -> usize {
/// [`Document::map_solid_paints`] limited to the art in the subtrees of `ids` (each paint
/// visited once even when an id is inside another).
pub fn map_solid_paints_in(&mut self, ids: &[NodeId], f: &mut LinkFn) -> usize {
let roots: Vec<NodeId> =
ids.iter().copied().filter(|id| !self.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| ids.contains(p)))).collect();
let mut n = 0;
@@ -123,7 +169,7 @@ impl Document {
}
/// The default name of a solid swatch: its values in its own colour model ("C=10 M=20 Y=30 K=0",
/// "R=255 G=128 B=0", "Gray K=40").
/// "R=255 G=128 B=0", "Gray K=40", "L=52 a=70 b=-30").
pub fn color_name(c: Color) -> String {
// Clamped first, so a conversion's tiny negative never reads "-0".
let pct = |v: f32| (v.clamp(0.0, 1.0) * 100.0).round();
@@ -132,17 +178,23 @@ pub fn color_name(c: Color) -> String {
Color::Cmyk { c, m, y, k } => format!("C={} M={} Y={} K={}", pct(c), pct(m), pct(y), pct(k)),
Color::Rgb { r, g, b } => format!("R={} G={} B={}", byte(r), byte(g), byte(b)),
Color::Gray { k } => format!("Gray K={}", pct(k)),
// `+ 0.0` turns a rounded -0 into 0.
Color::Lab { l, a, b } => format!("L={} a={} b={}", l.round() + 0.0, a.round() + 0.0, b.round() + 0.0),
}
}
/// Every colour in the subtree of `n` with the swatch it links to: solid fills, strokes and text
/// runs (with their link), then gradient stops and mesh points (unlinked), in paint order.
/// What [`Document::map_solid_paints`] applies to each linkable colour: `(colour, link, tint)`,
/// true when it changed them.
pub type LinkFn<'a> = dyn FnMut(&mut Color, &mut Option<String>, &mut f32) -> bool + 'a;
/// Every colour in the subtree of `n` with the swatch it links to: solid fills, strokes, text runs
/// and gradient stops (with their link), then mesh points (unlinked), in paint order.
pub fn node_colors(n: &Node, f: &mut dyn FnMut(&Color, Option<&str>)) {
n.walk(&mut |m| {
for p in node_paints(m) {
match p {
Paint::Solid { color, swatch } => f(color, swatch.as_deref()),
Paint::Gradient(g) => g.gradient.stops.iter().for_each(|s| f(&s.color, None)),
Paint::Solid { color, swatch, .. } => f(color, swatch.as_deref()),
Paint::Gradient(g) => g.gradient.stops.iter().for_each(|s| f(&s.color, s.swatch.as_deref())),
_ => {}
}
}
@@ -184,24 +236,17 @@ fn node_paints_mut(n: &mut Node) -> impl Iterator<Item = &mut Paint> {
n.appearance.items.iter_mut().map(item_paint_mut).chain(runs.iter_mut().flat_map(|r| [&mut r.style.fill, &mut r.style.stroke]))
}
/// Apply `f` to a solid paint; true when it changed.
fn map_solid(p: &mut Paint, f: &mut dyn FnMut(&mut Color, &mut Option<String>) -> bool) -> bool {
match p {
Paint::Solid { color, swatch } => f(color, swatch),
_ => false,
}
}
/// `n` with `f` applied to its subtree's solid paints, or `None` when nothing changed (then nothing
/// was copied). Also returns the number of changed paints.
fn map_node(n: &Node, f: &mut dyn FnMut(&mut Color, &mut Option<String>) -> bool) -> Option<(Node, usize)> {
// Try each own paint on a scratch copy first, so unchanged nodes are never cloned.
let mut changes: Vec<(usize, Color, Option<String>)> = vec![];
/// `n` with `f` applied to its subtree's linkable colours, or `None` when nothing changed (then
/// nothing was copied). Also returns the number of changed paints.
fn map_node(n: &Node, f: &mut LinkFn) -> Option<(Node, usize)> {
// Try each own solid or gradient paint on a scratch copy first, so unchanged nodes are never
// cloned.
let mut changes: Vec<(usize, Paint)> = vec![];
for (i, p) in node_paints(n).enumerate() {
if let Paint::Solid { color, swatch } = p {
let (mut c, mut s) = (*color, swatch.clone());
if f(&mut c, &mut s) {
changes.push((i, c, s));
if matches!(p, Paint::Solid { .. } | Paint::Gradient(_)) {
let mut q = p.clone();
if q.map_links(f) {
changes.push((i, q));
}
}
}
@@ -212,10 +257,9 @@ fn map_node(n: &Node, f: &mut dyn FnMut(&mut Color, &mut Option<String>) -> bool
let mut changes = changes.into_iter().peekable();
for (i, p) in node_paints_mut(&mut m).enumerate() {
if changes.peek().is_some_and(|c| c.0 == i)
&& let (Some((_, c, s)), Paint::Solid { color, swatch }) = (changes.next(), p)
&& let Some((_, q)) = changes.next()
{
*color = c;
*swatch = s;
*p = q;
}
}
out = Some(m);
@@ -234,7 +278,7 @@ fn map_node(n: &Node, f: &mut dyn FnMut(&mut Color, &mut Option<String>) -> bool
out.map(|m| (m, count))
}
fn map_tree(n: &mut Arc<Node>, f: &mut dyn FnMut(&mut Color, &mut Option<String>) -> bool) -> usize {
fn map_tree(n: &mut Arc<Node>, f: &mut LinkFn) -> usize {
match map_node(n, f) {
Some((new, count)) => {
*n = Arc::new(new);
@@ -244,7 +288,7 @@ fn map_tree(n: &mut Arc<Node>, f: &mut dyn FnMut(&mut Color, &mut Option<String>
}
}
fn map_trees(v: &mut [Arc<Node>], f: &mut dyn FnMut(&mut Color, &mut Option<String>) -> bool) -> usize {
fn map_trees(v: &mut [Arc<Node>], f: &mut LinkFn) -> usize {
v.iter_mut().map(|n| map_tree(n, f)).sum()
}
@@ -257,7 +301,7 @@ mod tests {
use crate::Appearance;
fn linked(color: Color, name: &str) -> Paint {
Paint::Solid { color, swatch: Some(name.into()) }
Paint::Solid { color, swatch: Some(name.into()), tint: 1.0 }
}
/// A document with a grouped global swatch "Brand", a rectangle filled with it and an unlinked one.
@@ -309,7 +353,7 @@ mod tests {
let (mut d, a, b) = doc();
let before = d.clone();
let blue = Color::rgb(0.0, 0.0, 1.0);
let n = d.map_solid_paints(&mut |c, s| {
let n = d.map_solid_paints(&mut |c, s, _| {
if s.as_deref() != Some("Brand") {
return false;
}
@@ -323,7 +367,7 @@ mod tests {
assert!(Arc::ptr_eq(&unchanged(&d), &unchanged(&before)), "the unlinked rectangle is shared, not copied");
// Nothing to change: the tree is untouched.
let again = d.clone();
assert_eq!(d.map_solid_paints(&mut |_, _| false), 0);
assert_eq!(d.map_solid_paints(&mut |_, _, _| false), 0);
assert!(Arc::ptr_eq(&d.layers[0], &again.layers[0]));
}
@@ -332,7 +376,7 @@ mod tests {
let (mut d, a, b) = doc();
let layer = d.layers[0].id;
let mut seen = 0;
let n = d.map_solid_paints_in(&[layer, a], &mut |_, s| {
let n = d.map_solid_paints_in(&[layer, a], &mut |_, s, _| {
seen += 1;
s.take().is_some()
});
+125
View File
@@ -0,0 +1,125 @@
//! Slice layout: object slices follow their objects, clipping, numbering and auto slices.
use proptest::prelude::*;
use vectorcraft_geom::{Point, Rect, shapes};
use crate::slices::auto_slices;
use crate::{Appearance, Document, Node, Slice, SliceOptions, SliceSource};
fn rect(d: &mut Document, r: Rect) -> crate::NodeId {
let l = d.layers[0].id;
let id = d.alloc_id();
d.insert(Some(l), usize::MAX, Node::path(id, shapes::rectangle(r), Appearance::basic(crate::color::Paint::None, crate::color::Paint::None, 0.0)))
.unwrap();
id
}
fn user(d: &mut Document, r: Rect) -> crate::NodeId {
let id = d.alloc_id();
d.slices.push(Slice { id, rect: r, options: SliceOptions::default() });
id
}
/// How many of `rects` hold point `p` (strictly inside).
fn holders(rects: &[Rect], p: Point) -> usize {
rects.iter().filter(|r| r.x0 < p.x && p.x < r.x1 && r.y0 < p.y && p.y < r.y1).count()
}
#[test]
fn an_object_slice_follows_its_object_and_numbers_run_by_rows() {
let mut d = Document::new(300.0, 200.0);
let a = rect(&mut d, Rect::new(100.0, 50.0, 200.0, 150.0));
assert!(d.slice_layout().is_empty(), "no slices, no auto slices");
d.node_mut(a).unwrap().slice = Some(Box::default());
let lay = d.slice_layout();
let own = lay.iter().find(|s| s.id == Some(a)).unwrap();
assert_eq!((own.source, own.rect), (SliceSource::Object, Rect::new(100.0, 50.0, 200.0, 150.0)));
// Three rows: the band above, the object's row (left, object, right) and the band below.
assert_eq!(lay.len(), 5);
assert_eq!(lay.iter().map(|s| s.number).collect::<Vec<_>>(), [1, 2, 3, 4, 5]);
assert_eq!(own.number, 3);
assert_eq!(d.slice_name(own), "Untitled-1_03");
// Moving the object moves its slice.
d.node_mut(a).unwrap().transform(vectorcraft_geom::Affine::translate((-50.0, 0.0)), crate::Scaling::default());
assert_eq!(d.slice_layout().iter().find(|s| s.id == Some(a)).unwrap().rect, Rect::new(50.0, 50.0, 150.0, 150.0));
// Hidden objects have no slice.
d.node_mut(a).unwrap().visible = false;
assert!(d.slice_layout().is_empty());
}
#[test]
fn clip_to_artboard_clips_slices_and_off_covers_the_art() {
let mut d = Document::new(100.0, 100.0);
let s = user(&mut d, Rect::new(50.0, 50.0, 150.0, 150.0));
let own = |d: &Document| d.slice_layout().into_iter().find(|a| a.id == Some(s)).unwrap().rect;
assert_eq!(own(&d), Rect::new(50.0, 50.0, 100.0, 100.0));
let lay = d.slice_layout();
let autos: Vec<Rect> = lay.iter().filter(|a| a.source == SliceSource::Auto).map(|a| a.rect).collect();
assert_eq!(autos.iter().map(|r| r.area()).sum::<f64>(), 100.0 * 100.0 - 50.0 * 50.0);
d.slices_clip_to_artboard = false;
assert_eq!(own(&d), Rect::new(50.0, 50.0, 150.0, 150.0));
// The region is now the slice itself (no art): nothing left for auto slices.
assert_eq!(d.slice_layout().len(), 1);
rect(&mut d, Rect::new(0.0, 0.0, 20.0, 20.0));
let total: f64 = d.slice_layout().iter().map(|a| a.rect.area()).sum();
assert_eq!(total, 150.0 * 150.0);
}
#[test]
fn slices_survive_a_native_round_trip_and_old_files_load() {
let mut d = Document::new(100.0, 100.0);
let a = rect(&mut d, Rect::new(10.0, 10.0, 20.0, 20.0));
d.node_mut(a).unwrap().slice = Some(Box::new(SliceOptions { kind: crate::SliceKind::NoImage, text: "<b>hi</b>".into(), ..Default::default() }));
let s = user(&mut d, Rect::new(30.0, 30.0, 60.0, 60.0));
d.slice_mut(s).unwrap().options.url = "https://example.com".into();
d.slices_clip_to_artboard = false;
let json = serde_json::to_string(&d).unwrap();
let back: Document = serde_json::from_str(&json).unwrap();
assert_eq!(back.slices, d.slices);
assert_eq!(back.node(a).unwrap().slice, d.node(a).unwrap().slice);
assert!(!back.slices_clip_to_artboard);
// A document without slices writes none of the new keys (older readers see what they knew).
let plain = serde_json::to_string(&Document::new(10.0, 10.0)).unwrap();
assert!(!plain.contains("slice"), "{plain}");
let old: Document = serde_json::from_str(&plain).unwrap();
assert!(old.slices.is_empty() && old.slices_clip_to_artboard);
}
#[test]
fn auto_slices_fill_around_a_slice_in_rows() {
let autos = auto_slices(Rect::new(0.0, 0.0, 90.0, 90.0), &[Rect::new(30.0, 30.0, 60.0, 60.0)]);
let mut got: Vec<(f64, f64, f64, f64)> = autos.iter().map(|r| (r.x0, r.y0, r.x1, r.y1)).collect();
got.sort_by(|a, b| a.1.total_cmp(&b.1).then(a.0.total_cmp(&b.0)));
assert_eq!(got, [(0.0, 0.0, 90.0, 30.0), (0.0, 30.0, 30.0, 60.0), (60.0, 30.0, 90.0, 60.0), (0.0, 60.0, 90.0, 90.0)]);
// Spans that continue down one column merge.
let autos = auto_slices(Rect::new(0.0, 0.0, 90.0, 90.0), &[Rect::new(30.0, 0.0, 60.0, 40.0), Rect::new(30.0, 40.0, 60.0, 90.0)]);
assert_eq!(autos.len(), 2, "{autos:?}");
}
fn arb_rect() -> impl Strategy<Value = Rect> {
(-20.0..120.0f64, -20.0..120.0f64, 1.0..80.0f64, 1.0..80.0f64).prop_map(|(x, y, w, h)| Rect::new(x, y, x + w, y + h))
}
proptest! {
/// Auto slices never overlap each other or the slices, and with the slices they cover the
/// whole region.
#[test]
fn auto_slices_cover_without_overlap(cut in prop::collection::vec(arb_rect(), 0..8)) {
let region = Rect::new(0.0, 0.0, 100.0, 100.0);
let autos = auto_slices(region, &cut);
for r in &autos {
prop_assert!(r.x0 >= region.x0 && r.y0 >= region.y0 && r.x1 <= region.x1 && r.y1 <= region.y1, "{r:?} leaves the region");
}
// Sample off every edge (edges are at integers plus random fractions; the samples sit at
// odd 1/8ths, which a random float edge practically never hits).
for i in 0..50 {
for j in 0..50 {
let p = Point::new(i as f64 * 2.0 + 0.125 * 7.0, j as f64 * 2.0 + 0.125 * 3.0);
let in_cut = holders(&cut, p) > 0;
let in_auto = holders(&autos, p);
prop_assert!(in_auto <= 1, "{p:?} in {in_auto} auto slices");
prop_assert!(in_cut != (in_auto == 1), "{p:?}: in a slice {in_cut}, in an auto slice {in_auto}");
}
}
}
}
+65
View File
@@ -0,0 +1,65 @@
//! Units: format/parse round-trips in every unit, typed units winning over the field's unit, names
//! and canvas readouts.
use super::Unit;
#[test]
fn every_unit_round_trips_through_its_field_text() {
for u in Unit::ALL {
// Field text keeps three decimals of the unit: half a step is the most a round trip loses.
let tol = 0.0005 * u.points() + 1e-9;
for pt in [0.0, 1.0, 12.5, 72.0, 100.0, 595.28, 1234.5678, -36.0] {
let shown = u.format(pt);
let back = u.parse(&shown).unwrap_or_else(|| panic!("{u:?} can't read back `{shown}`"));
assert!((back - pt).abs() <= tol, "{u:?}: {pt} → `{shown}` → {back}");
// The bare number reads in the field's unit, and in any unit with its suffix.
let bare = u.parse(&u.number(pt)).unwrap();
assert!((bare - pt).abs() <= tol, "{u:?}: bare `{}` → {bare}", u.number(pt));
let pts = Unit::Points.parse(&shown).unwrap();
assert!((pts - pt).abs() <= tol, "{u:?}: `{shown}` in a points field → {pts}");
}
}
}
#[test]
fn typed_units_win_over_the_fields_unit() {
let mm = 72.0 / 25.4;
assert_eq!(Unit::Millimeters.parse("10"), Some(10.0 * mm));
assert_eq!(Unit::Millimeters.parse("12 pt"), Some(12.0));
assert_eq!(Unit::Millimeters.parse("1in"), Some(72.0));
assert_eq!(Unit::Points.parse("5 mm"), Some(5.0 * mm));
assert_eq!(Unit::Centimeters.parse("2p6"), Some(30.0));
assert_eq!(Unit::Millimeters.parse("10+5"), Some(15.0 * mm));
assert_eq!(Unit::Inches.parse("1 + 36 pt"), Some(108.0));
assert_eq!(Unit::Pixels.parse("-4"), Some(-4.0));
}
#[test]
fn odd_text_reads_as_nothing_without_panicking() {
for s in ["", "é", "é5", "°+1", "×2", "5 ×", "—3", "mm", "1/0", "--", "+"] {
assert_eq!(Unit::Millimeters.parse(s), None, "{s}");
}
}
#[test]
fn units_are_named_by_label_key_or_suffix() {
for u in Unit::ALL {
assert_eq!(Unit::named(u.label()), Some(u));
assert_eq!(Unit::named(u.key()), Some(u));
assert_eq!(Unit::named(&u.label().to_uppercase()), Some(u));
}
assert_eq!(Unit::named("mm"), Some(Unit::Millimeters));
assert_eq!(Unit::named("Feet & Inches"), Some(Unit::FeetInches));
assert_eq!(Unit::named("feetInches"), Some(Unit::FeetInches));
assert_eq!(Unit::named("furlongs"), None);
assert_eq!(Unit::named(""), None);
}
#[test]
fn readouts_show_two_decimals() {
assert_eq!(Unit::Points.readout(15.0), "15.00 pt");
assert_eq!(Unit::Millimeters.readout(72.0), "25.40 mm");
assert_eq!(Unit::Inches.readout(-36.0), "-0.50 in");
assert_eq!(Unit::Millimeters.number(1.0), "0.353");
assert_eq!(Unit::Points.number(-0.0001), "0");
}
+68
View File
@@ -76,6 +76,62 @@ pub struct CharStyle {
pub stroke_miter_limit: f64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub stroke_dash: Option<Dash>,
/// Superscript or subscript (Character panel).
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
pub position: CharPosition,
/// Small Caps (Character panel): lowercase letters drawn as capitals at this percentage of the
/// size (Document Setup → Type → Small Caps); None = off.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub small_caps: Option<f64>,
}
/// Superscript or subscript proportions in percent of the font size (Document Setup → Type).
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct ScriptMetrics {
/// Glyph size.
pub size: f64,
/// Baseline offset: up for superscript, down for subscript.
pub position: f64,
}
impl ScriptMetrics {
pub const DEFAULT: Self = Self { size: 58.3, position: 33.3 };
}
impl Default for ScriptMetrics {
fn default() -> Self {
Self::DEFAULT
}
}
/// Character position (Character panel Superscript / Subscript). The proportions are the
/// document's when the position is applied, and follow later Document Setup changes.
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "camelCase")]
pub enum CharPosition {
#[default]
Normal,
Superscript(ScriptMetrics),
Subscript(ScriptMetrics),
}
impl CharPosition {
/// Glyph scale and baseline shift (points, positive = up) for text of `size` points.
pub fn scale_shift(self, size: f64) -> (f64, f64) {
match self {
CharPosition::Normal => (1.0, 0.0),
CharPosition::Superscript(m) => (m.size / 100.0, m.position / 100.0 * size),
CharPosition::Subscript(m) => (m.size / 100.0, -m.position / 100.0 * size),
}
}
/// `normal`, `superscript` or `subscript`.
pub fn id(self) -> &'static str {
match self {
CharPosition::Normal => "normal",
CharPosition::Superscript(_) => "superscript",
CharPosition::Subscript(_) => "subscript",
}
}
}
fn ten() -> f64 {
@@ -118,6 +174,8 @@ impl Default for CharStyle {
stroke_join: LineJoin::Miter,
stroke_miter_limit: 10.0,
stroke_dash: None,
position: CharPosition::Normal,
small_caps: None,
}
}
}
@@ -414,6 +472,16 @@ impl TextObject {
pub fn transform(&mut self, a: Affine) {
self.xf = a * self.xf;
}
/// Scale the character strokes' weights and dashes by `s` (they are drawn in text space, so
/// `1 / scale` keeps their weight through a transform that scales the type).
pub fn scale_char_strokes(&mut self, s: f64) {
for r in &mut self.runs {
r.style.stroke_width *= s;
if let Some(d) = &mut r.style.stroke_dash {
d.scale(s);
}
}
}
/// Layout bounds in text space (the layout cache, else the estimate): the box an unplaced run
/// gradient fits, as the renderers lay it out.
pub fn local_bounds(&self) -> Rect {
+140 -39
View File
@@ -6,14 +6,20 @@
//! outlines, [`reshape`]) — is evaluated exactly like the renderer does, and so are the own fills,
//! strokes and geometry effects of groups and layers ([`evaluate_container`]). Raster effects
//! (shadows, glows, blur) stay on the objects for the exporter to translate (e.g. SVG filters).
//!
//! Object → Expand Appearance goes further ([`expand_leaf`]): every fill and stroke becomes an
//! object of its own, strokes turned into filled art by the caller (their outlines or brush art).
use std::sync::Arc;
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Node, NodeKind};
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Node, NodeKind, StrokeLayer};
use vectorcraft_geom::{FillRule, PathData};
use crate::group::has_own_paint;
use crate::{GeomContext, apply_geometry_with, evaluate_container, has_geometry, has_pathfinder, is_geometry, needs_outline, reshape};
use crate::group::{has_own_paint, paints};
use crate::{
GeomContext, apply_geometry_with, crop_marks_art, evaluate_container, has_crop_marks, has_geometry, has_pathfinder, is_geometry, needs_outline,
reshape,
};
fn item_effects(item: &AppearanceItem) -> &[vectorcraft_doc::Effect] {
match item {
@@ -31,7 +37,8 @@ fn clear_item_effects(item: &mut AppearanceItem) {
/// Does anything in `n`'s subtree need baking?
pub fn needs_bake(n: &Node) -> bool {
has_pathfinder(n)
has_crop_marks(n)
|| has_pathfinder(n)
|| has_own_paint(n)
|| has_geometry(&n.appearance.effects)
|| n.appearance.items.iter().any(|i| has_geometry(item_effects(i)))
@@ -71,6 +78,10 @@ fn bake_node(d: &mut Document, n: &Node) -> Option<Node> {
if !needs_bake(n) {
return None;
}
// Crop marks: the object and its marks.
if let Some(m) = crop_marks_art(n) {
return Some(bake_pieces(d, m));
}
// Type, images, symbol instances and live objects: reshaped through their outlines.
if needs_outline(n) && has_geometry(&n.appearance.effects) {
let symbol = match &n.kind {
@@ -82,21 +93,8 @@ fn bake_node(d: &mut Document, n: &Node) -> Option<Node> {
}
// Groups and layers: Pathfinder, geometry effects and their own fills and strokes. The new
// pieces (results, outlines, the fills' and strokes' art) get ids of their own.
if let Some(mut m) = evaluate_container(n) {
let mut seen = std::collections::HashSet::from([m.id]);
let children = m.children().cloned().unwrap_or_default();
let children = children
.into_iter()
.map(|c| {
let mut c = Arc::unwrap_or_clone(c);
fresh_ids(d, &mut c, &mut seen);
Arc::new(bake_node(d, &c).unwrap_or(c))
})
.collect();
if let Some(ch) = m.children_mut() {
*ch = children;
}
return Some(m);
if let Some(m) = evaluate_container(n) {
return Some(bake_pieces(d, m));
}
if let Some(ch) = n.children() {
if matches!(n.kind, NodeKind::Compound { .. })
@@ -114,6 +112,25 @@ fn bake_node(d: &mut Document, n: &Node) -> Option<Node> {
bake_leaf(d, n)
}
/// `m`, art evaluated from an object, with its children baked and given ids of their own (the
/// pieces copied from the source keep the source's ids until then).
fn bake_pieces(d: &mut Document, mut m: Node) -> Node {
let mut seen = std::collections::HashSet::from([m.id]);
let children = m.children().cloned().unwrap_or_default();
let children = children
.into_iter()
.map(|c| {
let mut c = Arc::unwrap_or_clone(c);
fresh_ids(d, &mut c, &mut seen);
Arc::new(bake_node(d, &c).unwrap_or(c))
})
.collect();
if let Some(ch) = m.children_mut() {
*ch = children;
}
m
}
/// Give `n` and its descendants a new id wherever one was already `seen` (the pieces evaluated art
/// copies from its source keep ids of their own).
pub fn fresh_ids(d: &mut Document, n: &mut Node, seen: &mut std::collections::HashSet<vectorcraft_doc::NodeId>) {
@@ -126,18 +143,50 @@ pub fn fresh_ids(d: &mut Document, n: &mut Node, seen: &mut std::collections::Ha
}
}
fn bake_leaf(d: &mut Document, n: &Node) -> Option<Node> {
/// A new path of `n`'s (its geometry `path`, filled under `rule`) painted by `item` alone, with
/// none of `n`'s transparency.
fn piece(d: &mut Document, n: &Node, path: PathData, rule: FillRule, item: AppearanceItem) -> Node {
let id = d.alloc_id();
let kind = path_kind(d, path, rule);
Node {
id,
name: None,
appearance: Appearance { items: vec![item], ..Default::default() },
opacity: 1.0,
blend: Default::default(),
isolate: false,
knockout: Default::default(),
knockout_shape: false,
mask: None,
trace: None,
wrap: None,
graph: None,
// The group keeps the URL (one link around the pieces).
attrs: None,
kind,
..n.clone()
}
}
/// `n`'s geometry with its object-level geometry effects applied, its fill rule, the context of
/// its effects, and `n` without those effects.
fn leaf_base(n: &Node) -> Option<(PathData, FillRule, GeomContext<'_>, Node)> {
let (base, rule) = geometry(n)?;
let ctx = GeomContext::of(n);
let g = apply(&n.appearance.effects, &base, &ctx);
let mut m = n.clone();
m.appearance.effects.retain(|e| !is_geometry(&e.id));
Some((g, rule, ctx, m))
}
fn bake_leaf(d: &mut Document, n: &Node) -> Option<Node> {
let (g, rule, ctx, mut m) = leaf_base(n)?;
if !n.appearance.items.iter().any(|i| has_geometry(item_effects(i))) {
m.kind = path_kind(d, g, rule);
return Some(m);
}
// Per-item geometry: one path per fill/stroke, grouped under the object's transparency and
// raster effects (what Expand Appearance produces).
// raster effects.
let children = n
.appearance
.items
@@ -146,24 +195,7 @@ fn bake_leaf(d: &mut Document, n: &Node) -> Option<Node> {
let ig = apply(item_effects(item), &g, &ctx.item(item));
let mut it = item.clone();
clear_item_effects(&mut it);
let id = d.alloc_id();
let kind = path_kind(d, ig, rule);
Arc::new(Node {
id,
name: None,
appearance: Appearance { items: vec![it], ..Default::default() },
opacity: 1.0,
blend: Default::default(),
isolate: false,
knockout: Default::default(),
knockout_shape: false,
mask: None,
trace: None,
wrap: None,
graph: None,
kind,
..n.clone()
})
Arc::new(piece(d, n, ig, rule, it))
})
.collect();
m.appearance.items.clear();
@@ -171,6 +203,75 @@ fn bake_leaf(d: &mut Document, n: &Node) -> Option<Node> {
Some(m)
}
/// Turns one stroke of a path (the path after its geometry effects, its fill rule, the stroke
/// without geometry effects) into filled art for [`expand_leaf`]: its outline filled with its
/// paint, or its brush art. `None` when it paints nothing.
pub type StrokeArt<'a> = &'a mut dyn FnMut(&mut Document, &PathData, FillRule, &StrokeLayer) -> Option<Node>;
/// Object → Expand Appearance of a path or compound path `n`: its geometry effects applied, every
/// visible fill becomes a copy of the path painted by that fill alone and every visible stroke the
/// filled art `stroke_art` makes of it (each with its fill's or stroke's opacity and blend mode as
/// its own), in paint order, as the members of a group that keeps
/// `n`'s id, name, transparency, opacity mask and remaining (raster) effects. A single piece
/// without transparency or effects of its own takes `n`'s place itself. Hidden fills, strokes and
/// effects are dropped. `None` for other kinds of objects.
pub fn expand_leaf(d: &mut Document, n: &Node, stroke_art: StrokeArt) -> Option<Node> {
let (g, rule, ctx, mut m) = leaf_base(n)?;
m.appearance.effects.retain(|e| e.visible);
let mut pieces = vec![];
for item in n.appearance.items.iter().filter(|i| paints(i)) {
let ig = apply(item.effects(), &g, &ctx.item(item));
let mut it = item.clone();
clear_item_effects(&mut it);
it.effects_mut().retain(|e| e.visible);
let p = match &it {
AppearanceItem::Stroke(st) => stroke_art(d, &ig, rule, st),
AppearanceItem::Fill(_) => Some(piece(d, n, ig, rule, it)),
};
pieces.extend(p.map(hoist_transparency));
}
m.appearance.items.clear();
m.appearance.contents_index = None;
match pieces.as_slice() {
[one] if m.appearance.effects.is_empty() && one.has_default_transparency() && one.appearance.effects.is_empty() => {
m.kind = one.kind.clone();
m.appearance = one.appearance.clone();
}
_ => m.kind = NodeKind::Group { children: pieces.into_iter().map(Arc::new).collect(), clip: false },
}
Some(m)
}
/// `p` with the opacity and blend mode of its only fill or stroke as its own (the same look, and a
/// basic appearance).
fn hoist_transparency(mut p: Node) -> Node {
if p.has_default_transparency()
&& let [item] = p.appearance.items.as_mut_slice()
{
let (opacity, blend) = match item {
AppearanceItem::Fill(f) => (&mut f.opacity, &mut f.blend),
AppearanceItem::Stroke(s) => (&mut s.opacity, &mut s.blend),
};
p.opacity = std::mem::replace(opacity, 1.0);
p.blend = std::mem::take(blend);
}
p
}
/// [`expand_leaf`] every path and compound path in `n` (art made for Expand Appearance, such as a
/// group's own fills and strokes or outlined type), in place.
pub fn expand_art(d: &mut Document, n: &mut Node, stroke_art: StrokeArt) {
if matches!(n.kind, NodeKind::Path { clipping: false, guide: false, .. } | NodeKind::Compound { .. }) {
if let Some(m) = expand_leaf(d, n, stroke_art) {
*n = m;
}
return;
}
for c in n.children_mut().into_iter().flatten() {
expand_art(d, Arc::make_mut(c), stroke_art);
}
}
/// A copy of `doc` with every live geometry effect baked into plain paths, or `None` when the
/// document has none (export it as is).
pub fn bake_document(doc: &Document) -> Option<Document> {
+6 -3
View File
@@ -112,8 +112,11 @@ pub fn pathfinder_children(group: &Node, hook: Option<OutlineHook>) -> Option<Ve
if shape_mode && lv.len() > 1 {
let parts: Vec<(PathData, FillRule)> = lv.iter().filter_map(geometry).collect();
let refs: Vec<(&PathData, FillRule)> = parts.iter().map(|(p, r)| (p, *r)).collect();
shapes.push(po::Shape::new(po::unite_all(&refs), FillRule::NonZero, sources.len() as u64));
sources.push(lv.pop().expect("non-empty"));
let key = sources.len() as u64;
if let Some(top) = lv.pop() {
shapes.push(po::Shape::new(po::unite_all(&refs), FillRule::NonZero, key));
sources.push(top);
}
} else {
for l in lv {
if let Some((p, r)) = geometry(&l) {
@@ -141,7 +144,7 @@ fn is_container(n: &Node) -> bool {
}
/// Does `item` paint anything?
fn paints(item: &AppearanceItem) -> bool {
pub fn paints(item: &AppearanceItem) -> bool {
item.visible()
&& !item.paint().is_none()
&& match item {
+81 -7
View File
@@ -27,6 +27,7 @@ mod bake;
mod clip;
mod distort;
mod group;
mod marks;
mod raster;
mod reshape;
pub mod stroke;
@@ -36,18 +37,22 @@ mod warp;
#[cfg(test)]
mod tests;
#[cfg(test)]
mod tests_scale;
use serde_json::{Map, Value, json};
use vectorcraft_doc::{AppearanceItem, Effect, Node, NodeKind, StrokeLayer};
use vectorcraft_geom::{BezPath, FillRule, PathData, Rect};
pub use bake::{bake_document, fresh_ids, needs_bake};
pub use bake::{StrokeArt, bake_document, expand_art, expand_leaf, fresh_ids, needs_bake};
pub use clip::clip_outline;
pub use group::{
OutlineHook, PATHFINDER_EFFECTS, evaluate_container, has_container_appearance, has_pathfinder, is_pathfinder, member_shapes, pathfinder_children,
OutlineHook, PATHFINDER_EFFECTS, evaluate_container, has_container_appearance, has_pathfinder, is_pathfinder, member_shapes, paints,
pathfinder_children,
};
pub use marks::{CROP_MARKS, crop_marks_art, has_crop_marks};
pub use raster::{RasterFx, outset, raster_effects};
pub use reshape::{needs_outline, outline_art, outline_text, reshape};
pub use reshape::{expand_outlined, needs_outline, outline_art, outline_text, reshape};
pub use warp::{WarpStyle, warp_point};
/// Catalogue entry for one effect.
@@ -65,6 +70,50 @@ pub struct EffectInfo {
pub defaults: Value,
/// Raster (painted) rather than geometry effect.
pub raster: bool,
/// The parameters that are distances in points (Scale Strokes & Effects scales them).
pub lengths: Lengths,
}
/// Which of an effect's parameters are distances in points.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Lengths {
/// Always distances.
pub always: &'static [&'static str],
/// Distances while the effect's `relative` parameter is false (percentages of the object's
/// size otherwise).
pub absolute: &'static [&'static str],
}
impl Lengths {
/// The distance parameters while the effect's `relative` parameter is `relative`.
pub fn keys(&self, relative: bool) -> impl Iterator<Item = &'static str> + '_ {
self.always.iter().chain(if relative { &[][..] } else { self.absolute }).copied()
}
}
/// Is parameter `key` of effect `id` a distance in points while its `relative` parameter is
/// `relative`?
pub fn is_length(id: &str, key: &str, relative: bool) -> bool {
catalog_index().get(id).is_some_and(|info| info.lengths.keys(relative).any(|k| k == key))
}
/// The distance parameters of effect `id` (none for unknown effects).
fn lengths_of(id: &str) -> Lengths {
let always = |always| Lengths { always, absolute: &[] };
match id {
"convertToShape.rectangle" | "convertToShape.ellipse" => always(&["extraW", "extraH", "width", "height"]),
"convertToShape.roundedRectangle" => always(&["extraW", "extraH", "width", "height", "radius"]),
"distort.roughen" | "distort.zigZag" => Lengths { always: &[], absolute: &["size"] },
"distort.tweak" => Lengths { always: &[], absolute: &["h", "v"] },
"distort.transform" => always(&["moveH", "moveV"]),
"path.offsetPath" => always(&["offset"]),
"path.outlineStroke" => always(&["width"]),
"stylize.roundCorners" | "stylize.feather" | "blur.gaussian" => always(&["radius"]),
"stylize.scribble" => always(&["overlap", "strokeWidth", "spacing", "variation"]),
"stylize.dropShadow" => always(&["x", "y", "blur"]),
"stylize.innerGlow" | "stylize.outerGlow" => always(&["blur"]),
_ => Lengths::default(),
}
}
const WARP_DOC: &str =
@@ -98,8 +147,8 @@ pub const WARP_STYLES: [(&str, &str); 15] = [
/// Every supported effect with its dialog defaults.
pub fn effect_catalog() -> Vec<EffectInfo> {
let g = |id, label, menu, params, defaults| EffectInfo { id, label, menu, params, defaults, raster: false };
let r = |id, label, menu, params, defaults| EffectInfo { id, label, menu, params, defaults, raster: true };
let g = |id, label, menu, params, defaults| EffectInfo { id, label, menu, params, defaults, raster: false, lengths: lengths_of(id) };
let r = |id, label, menu, params, defaults| EffectInfo { id, label, menu, params, defaults, raster: true, lengths: lengths_of(id) };
let mut v = vec![
g(
"convertToShape.rectangle",
@@ -228,6 +277,13 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
for (id, label, _) in PATHFINDER_EFFECTS {
v.push(g(id, label, PATHFINDER, "{} (groups and layers: live Pathfinder over the members)", json!({})));
}
v.push(g(
CROP_MARKS,
"Crop Marks",
&["Effect"],
"{style?: \"roman\"|\"japanese\" (default: the japaneseCropMarks preference when applied)} trim marks in [Registration] around the object's bounds, following it",
json!({}),
));
v
}
@@ -267,14 +323,32 @@ pub fn new_effect(id: &str, params: &Value) -> Option<Effect> {
Some(Effect { id: id.to_string(), params: merged_params(id, params), visible: true })
}
/// Scale the distance parameters of `e` by `s` (Scale Strokes & Effects; see
/// [`EffectInfo::lengths`]). A distance left at its default is written out scaled; one the
/// effect doesn't have (Outline Stroke's weight following its stroke) stays absent.
pub fn scale_effect(e: &mut Effect, s: f64) {
let Some(info) = catalog_index().get(e.id.as_str()) else { return };
let merged = merged_params(&e.id, &e.params);
let relative = util::flag(&merged, "relative", false);
for k in info.lengths.keys(relative) {
let v = util::num(&merged, k, f64::NAN);
if v.is_finite() {
if !e.params.is_object() {
e.params = Value::Object(Map::new());
}
e.params[k] = json!(v * s);
}
}
}
/// Is `id` a raster (painted) effect?
pub fn is_raster(id: &str) -> bool {
matches!(id, "stylize.dropShadow" | "stylize.innerGlow" | "stylize.outerGlow" | "stylize.feather" | "blur.gaussian")
}
/// Does `id` change geometry?
/// Does `id` change geometry? (Crop Marks adds art of its own instead, [`crop_marks_art`].)
pub fn is_geometry(id: &str) -> bool {
!is_raster(id) && !is_pathfinder(id) && catalog_index().contains_key(id)
!is_raster(id) && !is_pathfinder(id) && id != CROP_MARKS && catalog_index().contains_key(id)
}
/// Any visible geometry effect in the list?
+70
View File
@@ -0,0 +1,70 @@
//! Effect → Crop Marks: live trim marks in the Registration colour around the object, which follow
//! it as it moves or changes size. The renderer, the exporters ([`crate::bake_document`]) and
//! Expand Appearance draw the object as [`crop_marks_art`].
use std::sync::Arc;
use vectorcraft_doc::Node;
use vectorcraft_doc::marks::{MarkStyle, TrimMarks};
/// The effect id.
pub const CROP_MARKS: &str = "cropMarks";
/// Does `n` carry a visible Crop Marks effect?
pub fn has_crop_marks(n: &Node) -> bool {
n.appearance.effects.iter().any(|e| e.visible && e.id == CROP_MARKS)
}
/// The art of an object with Crop Marks: a group (with the object's id, name and transparency) of
/// the object itself, without the effect, and the marks around its visual bounds (the last Crop
/// Marks effect's style). `None` without a visible Crop Marks effect.
pub fn crop_marks_art(n: &Node) -> Option<Node> {
let fx = n.appearance.effects.iter().rev().find(|e| e.visible && e.id == CROP_MARKS)?;
let style = fx.params.get("style").and_then(|v| v.as_str()).and_then(MarkStyle::parse).unwrap_or_default();
let bounds = n.visual_bounds()?;
let marks = TrimMarks::of(style).group(bounds, &mut || n.id);
let mut object = n.clone();
object.appearance.effects.retain(|e| e.id != CROP_MARKS);
// The group takes over the object's identity, transparency, mask and link.
let mut g = Node::group(n.id, vec![]);
(g.visible, g.locked) = (n.visible, n.locked);
g.name = object.name.take();
g.opacity = std::mem::replace(&mut object.opacity, 1.0);
g.blend = std::mem::take(&mut object.blend);
g.isolate = std::mem::take(&mut object.isolate);
g.mask = object.mask.take();
g.attrs = object.attrs.take();
if let Some(ch) = g.children_mut() {
*ch = vec![Arc::new(object), Arc::new(marks)];
}
Some(g)
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
use vectorcraft_doc::{Appearance, Effect, NodeId};
use vectorcraft_geom::{Rect, shapes};
#[test]
fn the_marks_surround_the_object_and_follow_it() {
let mut n = Node::path(NodeId(7), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 50.0)), Appearance::default_art());
assert!(crop_marks_art(&n).is_none());
n.opacity = 0.5;
n.appearance.effects.push(Effect { id: CROP_MARKS.into(), params: json!({"style": "japanese"}), visible: true });
let art = crop_marks_art(&n).unwrap();
assert_eq!((art.id, art.opacity), (NodeId(7), 0.5));
let [object, marks] = art.children().unwrap().as_slice() else { panic!() };
assert!(object.appearance.effects.is_empty() && object.opacity == 1.0);
assert_eq!(marks.children().unwrap().len(), 24, "Japanese marks");
// Around the stroked bounds (0.5 outside the path), by the marks' reach.
let reach = TrimMarks::of(MarkStyle::Japanese).reach() + 0.5;
let b = art.visual_bounds().unwrap();
assert!((b.x0 + reach).abs() < 2.0 && (b.x1 - 100.0 - reach).abs() < 2.0, "{b:?}");
// Moved, the marks move along.
n.transform(vectorcraft_geom::Affine::translate((40.0, 0.0)), false);
let b2 = crop_marks_art(&n).unwrap().visual_bounds().unwrap();
assert!((b2.x0 - b.x0 - 40.0).abs() < 1e-6);
}
}
+18 -2
View File
@@ -113,10 +113,26 @@ fn outline_nested_text(n: &mut Node) {
/// a group with `n`'s id, name, transparency, opacity mask and remaining (raster) effects; `None`
/// when `n` has no visible geometry effect or no art (a symbol instance without `symbol_art`).
pub fn reshape(n: &Node, symbol_art: Option<&Node>) -> Option<Node> {
let fx = geometry_effects(n);
if fx.is_empty() || !needs_outline(n) {
if geometry_effects(n).is_empty() || !needs_outline(n) {
return None;
}
as_art(n, symbol_art)
}
/// `n` (see [`needs_outline`]) as plain art for Expand Appearance: [`reshape`]d when it has
/// geometry effects, else type with fills or strokes of its own outlined, in the same form. `None`
/// when it has neither.
pub fn expand_outlined(n: &Node, symbol_art: Option<&Node>) -> Option<Node> {
let own_paint = matches!(n.kind, NodeKind::Text(_)) && !n.appearance.items.is_empty();
if !needs_outline(n) || (geometry_effects(n).is_empty() && !own_paint) {
return None;
}
as_art(n, symbol_art)
}
/// [`reshape`] without its checks (no geometry effects: just the art).
fn as_art(n: &Node, symbol_art: Option<&Node>) -> Option<Node> {
let fx = geometry_effects(n);
let mut art = match &n.kind {
NodeKind::Image(im) => {
let frame = shapes::rectangle(Rect::new(0.0, 0.0, im.width as f64, im.height as f64)).transformed(im.xf);
+12 -70
View File
@@ -8,28 +8,29 @@
//! - [`width_outline`]: variable-width (profile) strokes, with the stroke's joins at corners;
//! - [`line_outline`]: the line part of a stroke as one filled outline (profile, dashes, dots,
//! caps and joins);
//! - [`for_writer`] and [`outline_region`]: strokes for the SVG/PDF writers and Outline Stroke.
//! - [`for_writer`] and [`outline_region`]: strokes for the SVG/PDF writers and Outline Stroke;
//! - [`gradient_slices`] and [`gradient_meshes`]: gradients laid along or across a stroke.
mod arrow;
mod dash;
mod gradient;
mod outline;
mod width;
use std::borrow::Cow;
use kurbo::{BezPath, ParamCurve, ParamCurveDeriv, PathEl, PathSeg, Vec2};
use kurbo::{BezPath, PathEl, PathSeg};
use vectorcraft_doc::{LineCap, LineJoin, StrokeAlign, StrokeLayer};
pub(crate) use vectorcraft_geom::bez::{kink, segments, subpaths, tangent, unit};
pub use arrow::Arrow;
pub use dash::{Dashed, Dot, dash, dot_outline};
pub use gradient::{Slice, WrittenSlices, gradient_meshes, gradient_slices, written_slices};
pub use outline::{OUTLINE_TOL, Written, WrittenShape, for_writer, is_plain, outline_region};
pub use width::width_outline;
/// Arc-length accuracy for dashing and trimming (document points).
const ARCLEN_ACCURACY: f64 = 1e-6;
/// Tangents meeting at more than about 1° (this cosine) make a corner: fitted dashes centre on it
/// and variable-width strokes give it the stroke's join.
const CORNER_COS: f64 = 0.9998;
/// The geometry one stroke paints, in the coordinate space of its path.
#[derive(Clone, Debug)]
@@ -119,40 +120,6 @@ pub fn line_outline(line: &BezPath, st: &StrokeLayer, width: f64, tol: f64) -> B
}
}
/// Do segments `a` and `b` (`b` following `a`) meet at a corner?
pub(crate) fn kink(a: &PathSeg, b: &PathSeg) -> bool {
tangent(a, 1.0).dot(tangent(b, 0.0)) < CORNER_COS
}
/// Unit tangent of `s` at `t`, robust at ends where control points coincide with the end point.
pub(crate) fn tangent(s: &PathSeg, t: f64) -> Vec2 {
let d = match s {
PathSeg::Line(l) => l.p1 - l.p0,
PathSeg::Quad(q) => {
let v = q.deriv().eval(t).to_vec2();
if v.hypot() > 1e-9 { v } else { q.p2 - q.p0 }
}
PathSeg::Cubic(c) => {
let v = c.deriv().eval(t).to_vec2();
if v.hypot() > 1e-9 {
v
} else if t < 0.5 {
// The first control point that differs from the start gives the direction.
[c.p2, c.p3].into_iter().map(|p| p - c.p0).find(|v| v.hypot() > 1e-9).unwrap_or_default()
} else {
[c.p1, c.p0].into_iter().map(|p| c.p3 - p).find(|v| v.hypot() > 1e-9).unwrap_or_default()
}
}
};
unit(d)
}
/// `v` normalised, or +x when it has no length.
pub(crate) fn unit(v: Vec2) -> Vec2 {
let h = v.hypot();
if h > 1e-12 { v / h } else { Vec2::new(1.0, 0.0) }
}
/// Append `seg` to `out` (which must already have a current point at its start).
pub(crate) fn push_seg(out: &mut BezPath, seg: &PathSeg) {
match seg {
@@ -162,38 +129,13 @@ pub(crate) fn push_seg(out: &mut BezPath, seg: &PathSeg) {
}
}
/// Element ranges of the subpaths of `bp` (each with whether it is closed).
pub(crate) fn subpaths(bp: &BezPath) -> Vec<(std::ops::Range<usize>, bool)> {
let els = bp.elements();
let mut out = vec![];
let mut start = 0;
for (i, el) in els.iter().enumerate() {
match el {
PathEl::MoveTo(_) if i > start => {
out.push((start..i, false));
start = i;
}
PathEl::ClosePath => {
out.push((start..i + 1, true));
start = i + 1;
}
_ => {}
}
}
if start < els.len() {
out.push((start..els.len(), false));
}
// A lone MoveTo (or a MoveTo straight after a ClosePath) draws nothing.
out.retain(|(r, _)| r.len() > 1);
out
}
/// The segments of one subpath (`els` starts with its MoveTo; a ClosePath adds the closing line).
pub(crate) fn segments(els: &[PathEl]) -> Vec<PathSeg> {
kurbo::segments(els.iter().copied()).collect()
}
#[cfg(test)]
mod tests;
#[cfg(test)]
mod tests_arrows;
#[cfg(test)]
mod tests_fit;
#[cfg(test)]
mod tests_gradient;
#[cfg(test)]
mod tests_reach;
+156 -6
View File
@@ -1,14 +1,16 @@
//! Arrowheads. A head of weight `hw` (stroke weight × scale) is `4·hw` long and `4·hw` wide.
//! Hollow kinds are rings (`hw/2` walls) or, for the open arrow, a chevron with `hw` arms. The
//! stroke ends under the head at the head's *inset* from the tip: halfway into solid heads, in
//! the back wall of hollow ones (with the cap kept out of the hole) and at the chevron's inner
//! Arrowheads. A head of weight `hw` (stroke weight × scale) fits a box `4·hw` long and `4·hw`
//! wide. Hollow kinds are rings (`hw/2` walls) or, for the open arrow, a chevron with `hw` arms.
//! The stroke ends under the head at the head's *inset* from the tip: halfway into solid heads,
//! in the back wall of hollow ones (with the cap kept out of the hole) and at the chevron's inner
//! corner. With [`ArrowAlign::Tip`] the tip sits on the end point and the stroke is shortened by
//! the inset; with [`ArrowAlign::Extend`] the path keeps its length and the tip sits the inset
//! past the end point.
//! past the end point. Heads added after the first ten are drawn in local units ([`local`]).
use std::borrow::Cow;
use kurbo::{BezPath, ParamCurve, ParamCurveArclen, PathSeg, Point, Shape, Vec2};
use std::f64::consts::{FRAC_PI_2, PI};
use kurbo::{Affine, BezPath, ParamCurve, ParamCurveArclen, PathSeg, Point, Shape, Vec2};
use vectorcraft_doc::{ArrowAlign, Arrowhead, StrokeLayer};
use super::{ARCLEN_ACCURACY, StrokePieces, cap_extent, push_seg, segments, subpaths, tangent, unit};
@@ -185,6 +187,10 @@ fn inset(kind: Arrowhead, hw: f64, cap: f64) -> f64 {
Arrowhead::TriangleOpen | Arrowhead::CircleOpen | Arrowhead::SquareOpen => hollow(l),
// The inner corner of the chevron: arm / sin(half angle).
Arrowhead::ArrowOpen => (arm(hw) * (l * l + l * l / 4.0).sqrt() / (l / 2.0)).max(cap),
_ => match local_stop(kind) {
Stop::At(u) => (u * hw).max(cap),
Stop::Wall(back) => hollow(back * hw),
},
}
}
@@ -224,6 +230,150 @@ fn shape(kind: Arrowhead, tip: Point, dir: Vec2, hw: f64) -> BezPath {
let t = bar(hw);
polygon(&mut p, &[tip + n * half, tip + n * half - dir * t, tip - n * half - dir * t, tip - n * half]);
}
_ => {
// Local x runs back from the tip, y across to the right of `dir`; a unit is `hw`.
p = local(kind);
p.apply_affine(Affine::new([-dir.x * hw, -dir.y * hw, n.x * hw, n.y * hw, tip.x, tip.y]));
}
}
p
}
/// Where the stroke ends under a head drawn in local units.
enum Stop {
/// This many units back from the tip (or as far as the cap needs).
At(f64),
/// In the back wall of a ring whose back is this many units from the tip.
Wall(f64),
}
/// Flat-to-flat length of the hexagons (their corners touch the sides of the 4-unit box).
const HEX: f64 = 2.0 * 1.732_050_807_568_877_2;
/// Flattening tolerance of the curved local heads, in units.
const LOCAL_TOL: f64 = 1e-3;
fn local_stop(kind: Arrowhead) -> Stop {
match kind {
Arrowhead::Target | Arrowhead::TagOpen | Arrowhead::DiamondOpen => Stop::Wall(4.0),
Arrowhead::HexagonOpen => Stop::Wall(HEX),
Arrowhead::DoubleBar | Arrowhead::DotOnBar => Stop::At(0.375),
Arrowhead::Bracket => Stop::At(0.3),
Arrowhead::Fork => Stop::At(2.7),
Arrowhead::HalfArrowLeft | Arrowhead::HalfArrowRight | Arrowhead::Feather => Stop::At(1.3),
Arrowhead::Swallowtail => Stop::At(1.4),
Arrowhead::Chevron => Stop::At(1.0),
Arrowhead::Slash => Stop::At(1.2),
Arrowhead::DoubleSlash => Stop::At(1.05),
Arrowhead::DoubleArrow => Stop::At(1.7),
Arrowhead::HalfCircle => Stop::At(1.0),
Arrowhead::Concave => Stop::At(2.6),
Arrowhead::Hexagon => Stop::At(HEX / 2.0),
_ => Stop::At(2.0),
}
}
/// The outline of a head added after the first ten, in local units: x from the tip (0) back
/// along the line (to at most 4), y across it (−2 to 2, positive to the right of the direction
/// the head points). Every shape is generated here.
fn local(kind: Arrowhead) -> BezPath {
let mut p = BezPath::new();
let poly = |p: &mut BezPath, pts: &[(f64, f64)]| polygon(p, &pts.iter().map(|&q| Point::from(q)).collect::<Vec<_>>());
let ring_poly = |p: &mut BezPath, pts: &[(f64, f64)]| ring_polygon(p, &pts.iter().map(|&q| Point::from(q)).collect::<Vec<_>>(), ring(1.0));
let circle = |p: &mut BezPath, c: (f64, f64), r: f64| p.extend(kurbo::Circle::new(c, r).path_elements(LOCAL_TOL));
// A regular polygon of `n` corners around `c`, the first at angle `a0`, alternating radii.
let star = |c: (f64, f64), radii: &[f64], n: usize, a0: f64| -> Vec<(f64, f64)> {
(0..n).map(|i| (a0 + i as f64 * 2.0 * PI / n as f64, radii[i % radii.len()])).map(|(a, r)| (c.0 + r * a.cos(), c.1 + r * a.sin())).collect()
};
// A plus of arms `h` long and `k` thick round (2, 0), turned by `turn`.
let plus = |h: f64, k: f64, turn: f64| -> Vec<(f64, f64)> {
let arm = [(k, h), (k, k), (h, k)];
let (sin, cos) = turn.sin_cos();
(0..4)
.flat_map(|q| arm.iter().map(move |&(x, y)| [(x, y), (y, -x), (-x, -y), (-y, x)][q]))
.map(|(x, y)| (2.0 + x * cos - y * sin, x * sin + y * cos))
.collect()
};
let hexagon = star((HEX / 2.0, 0.0), &[2.0], 6, PI / 6.0);
match kind {
Arrowhead::Barbed => poly(&mut p, &[(0.0, 0.0), (3.6, 2.0), (2.6, 0.55), (4.0, 0.55), (4.0, -0.55), (2.6, -0.55), (3.6, -2.0)]),
Arrowhead::HalfArrowLeft => poly(&mut p, &[(0.0, 0.0), (4.0, -2.0), (3.0, -0.5), (3.0, 0.5), (1.0, 0.5)]),
Arrowhead::HalfArrowRight => poly(&mut p, &[(0.0, 0.0), (4.0, 2.0), (3.0, 0.5), (3.0, -0.5), (1.0, -0.5)]),
Arrowhead::Concave => {
p.move_to((0.0, 0.0));
p.quad_to((2.4, 0.4), (4.0, 2.0));
p.line_to((4.0, -2.0));
p.quad_to((2.4, -0.4), (0.0, 0.0));
p.close_path();
}
Arrowhead::DoubleBar => {
poly(&mut p, &[(0.0, -2.0), (0.75, -2.0), (0.75, 2.0), (0.0, 2.0)]);
poly(&mut p, &[(1.5, -2.0), (2.25, -2.0), (2.25, 2.0), (1.5, 2.0)]);
}
Arrowhead::Feather => poly(&mut p, &[(0.0, 0.5), (1.4, 2.0), (4.0, 2.0), (2.6, 0.5), (2.6, -0.5), (4.0, -2.0), (1.4, -2.0), (0.0, -0.5)]),
Arrowhead::DotOnBar => {
poly(&mut p, &[(0.0, -2.0), (0.75, -2.0), (0.75, 2.0), (0.0, 2.0)]);
circle(&mut p, (2.5, 0.0), 1.25);
}
Arrowhead::Chevron => poly(&mut p, &[(0.0, 0.0), (2.0, 2.0), (4.0, 2.0), (2.0, 0.0), (4.0, -2.0), (2.0, -2.0)]),
Arrowhead::DoubleArrow => poly(&mut p, &[(0.0, 0.0), (2.2, 1.8), (1.9, 0.5), (4.0, 2.0), (3.4, 0.0), (4.0, -2.0), (1.9, -0.5), (2.2, -1.8)]),
Arrowhead::Target => {
circle(&mut p, (2.0, 0.0), 2.0);
p.extend(kurbo::Circle::new((2.0, 0.0), 2.0 - ring(1.0)).to_path(LOCAL_TOL).reverse_subpaths());
circle(&mut p, (2.0, 0.0), 0.75);
}
Arrowhead::Star => poly(&mut p, &star((2.0, 0.0), &[2.0, 0.85], 10, PI)),
Arrowhead::Cross => poly(&mut p, &plus(2.2, 0.4, PI / 4.0)),
Arrowhead::Plus => poly(&mut p, &plus(1.9, 0.4, 0.0)),
Arrowhead::Hexagon => poly(&mut p, &hexagon),
Arrowhead::HexagonOpen => ring_poly(&mut p, &hexagon),
Arrowhead::Tag => poly(&mut p, &[(0.0, 0.0), (1.6, 2.0), (4.0, 2.0), (4.0, -2.0), (1.6, -2.0)]),
Arrowhead::TagOpen => ring_poly(&mut p, &[(0.0, 0.0), (1.6, 2.0), (4.0, 2.0), (4.0, -2.0), (1.6, -2.0)]),
Arrowhead::HalfCircle => {
p.move_to((2.0, 2.0));
p.extend(kurbo::Arc::new((2.0, 0.0), (2.0, 2.0), FRAC_PI_2, PI, 0.0).append_iter(LOCAL_TOL));
p.close_path();
}
Arrowhead::Drop => {
// Straight sides from the tip, tangent to a round back.
let (c, r) = (Point::new(2.6, 0.0), 1.4);
let a = PI - (r / c.x).acos();
p.move_to((0.0, 0.0));
p.line_to(c + Vec2::from_angle(a) * r);
p.extend(kurbo::Arc::new(c, (r, r), a, -2.0 * a, 0.0).append_iter(LOCAL_TOL));
p.close_path();
}
Arrowhead::Slash => poly(&mut p, &[(0.0, 2.0), (0.8, 2.0), (2.4, -2.0), (1.6, -2.0)]),
Arrowhead::DoubleSlash => {
poly(&mut p, &[(0.0, 2.0), (0.7, 2.0), (2.1, -2.0), (1.4, -2.0)]);
poly(&mut p, &[(1.6, 2.0), (2.3, 2.0), (3.7, -2.0), (3.0, -2.0)]);
}
Arrowhead::DiamondOpen => ring_poly(&mut p, &[(0.0, 0.0), (2.0, 2.0), (4.0, 0.0), (2.0, -2.0)]),
Arrowhead::TriangleReverse => poly(&mut p, &[(0.0, 2.0), (4.0, 0.0), (0.0, -2.0)]),
Arrowhead::Swallowtail => poly(&mut p, &[(0.0, 2.0), (4.0, 2.0), (2.8, 0.0), (4.0, -2.0), (0.0, -2.0)]),
Arrowhead::Bracket => poly(&mut p, &[(0.0, 2.0), (2.0, 2.0), (2.0, 1.4), (0.6, 1.4), (0.6, -1.4), (2.0, -1.4), (2.0, -2.0), (0.0, -2.0)]),
Arrowhead::Fork => poly(&mut p, &[(0.0, 2.0), (3.0, 2.0), (3.0, -2.0), (0.0, -2.0), (0.0, -1.4), (2.4, -1.4), (2.4, 1.4), (0.0, 1.4)]),
Arrowhead::Leaf => {
p.move_to((0.0, 0.0));
p.quad_to((2.0, 3.2), (4.0, 0.0));
p.quad_to((2.0, -3.2), (0.0, 0.0));
p.close_path();
}
Arrowhead::Kite => poly(&mut p, &[(0.0, 0.0), (1.3, 1.7), (4.0, 0.0), (1.3, -1.7)]),
Arrowhead::TriangleBar => {
poly(&mut p, &[(0.0, 2.0), (0.6, 2.0), (0.6, 0.25), (4.0, 1.8), (4.0, -1.8), (0.6, -0.25), (0.6, -2.0), (0.0, -2.0)])
}
Arrowhead::Oval => p.extend(kurbo::Ellipse::new((2.0, 0.0), (2.0, 1.2), 0.0).path_elements(LOCAL_TOL)),
// The first ten are drawn by `shape`.
Arrowhead::Triangle
| Arrowhead::TriangleOpen
| Arrowhead::Circle
| Arrowhead::CircleOpen
| Arrowhead::Square
| Arrowhead::SquareOpen
| Arrowhead::Bar
| Arrowhead::Diamond
| Arrowhead::Arrow
| Arrowhead::ArrowOpen => {}
}
p
}
+432
View File
@@ -0,0 +1,432 @@
//! Gradients laid along or across a stroke ([`StrokeGradientMode::Along`] and
//! [`StrokeGradientMode::Across`]).
//!
//! Each subpath becomes a strip of *ribs*: cross-sections through the flattened path that reach
//! past everything the stroke paints there (its width profile, joins, caps and arrowheads). Between
//! two ribs lies a slice painted with a linear piece of the gradient: along, from the first rib's
//! centre to the next one's (padded beyond, so the outside of a turn keeps the colour of the point
//! it turns at); across, from the stroke's left edge to its right edge. Ribs sit on the bisectors
//! of gentle turns, so neighbouring slices meet where both give the same colour; a sharp corner
//! gets a fan of ribs round its outside, painted in the corner's colour.
//!
//! Clipped to the stroke's outline, the slices paint it: the canvas and the SVG and PDF writers
//! fill them ([`gradient_slices`]); Outline Stroke turns the strip into a gradient mesh
//! ([`gradient_meshes`]).
use kurbo::{BezPath, Point, Shape, Vec2};
use vectorcraft_doc::color::{Gradient, GradientGeom, GradientPaint, Paint};
use vectorcraft_doc::live::{H_DOWN, H_LEFT, H_RIGHT, H_UP, lerp_color};
use vectorcraft_doc::{GradientMesh, LineJoin, MeshPoint, StrokeAlign, StrokeGradientMode, StrokeLayer};
use vectorcraft_geom::FillRule;
use super::width::{flatten, left, length, split_at};
use super::{aligned_width, cap_extent, is_closed, segments, subpaths, unit};
/// Largest stretch of a rib on a turn's bisector (1 / cos of half the turn, about 74°) before the
/// corner gets a fan of ribs round its outside.
const SHARP: f64 = 1.25;
/// Past this stretch (a turn of about 150°) the inside of a corner is not cut on its bisector,
/// which would reach far back along both sides: the slices either side overlap there instead.
const HAIRPIN: f64 = 4.0;
/// Rows of a mesh across the stroke (more where the gradient has stops).
const MESH_ROWS: usize = 16;
/// The most of a subpath one column of a mesh along the stroke spans.
const MESH_STEP: f64 = 1.0 / 32.0;
/// The most of a subpath one slice spans while a width profile shapes the across gradient.
const PROFILE_STEP: f64 = 1.0 / 64.0;
/// Flattening tolerance, cover margin and growth (see [`gradient_slices`]) of meshes and written
/// slices (document points).
const SLICE_TOL: f64 = 0.05;
const SLICE_MARGIN: f64 = 0.5;
const SLICE_GROW: f64 = 0.25;
/// A cross-section of the strip a stroke's gradient is laid on.
#[derive(Clone, Copy, Debug)]
struct Rib {
/// Where it crosses the path.
c: Point,
/// Its left and right ends: the strip runs from `l` through `c` to `r`.
l: Point,
r: Point,
/// How far across the stroke `l` and `r` stand: a point `x` left of the path (negative:
/// right) lies `x / reach` of the way from `c` to the end on its side.
reach: (f64, f64),
/// Fraction of the subpath's length at `c`.
t: f64,
/// Where the across gradient starts and ends: this far left and right of the path.
band: (f64, f64),
}
impl Rib {
/// A rib square to direction `d`, reaching `r` either side of `c`.
fn square(c: Point, d: Vec2, r: f64, t: f64, band: (f64, f64)) -> Self {
let n = left(d);
Rib { c, l: c + n * r, r: c - n * r, reach: (r, r), t, band }
}
/// The point `x` left of the path along the rib (negative: right).
fn at(&self, x: f64) -> Point {
if x >= 0.0 {
self.c + (self.l - self.c) * (x / self.reach.0.max(1e-12))
} else {
self.c + (self.r - self.c) * (-x / self.reach.1.max(1e-12))
}
}
}
/// What lays out the ribs of one stroke.
struct Lay<'a> {
st: &'a StrokeLayer,
/// Half the stroked width ([`aligned_width`]).
hw: f64,
/// How far ribs reach either side of the path where nothing wider is near.
cover: f64,
margin: f64,
/// How far a strip runs on past the start and end of an open subpath (caps and heads).
ext: (f64, f64),
}
impl Lay<'_> {
/// The across band at fraction `t` of a subpath whose visible side is `side` (`Some(true)`:
/// left; `None`: both, a centred stroke).
fn band(&self, t: f64, side: Option<bool>) -> (f64, f64) {
let (l, r) = self.st.profile.as_ref().map_or((1.0, 1.0), |p| p.at(t));
let (l, r) = (self.hw * l.max(0.0), self.hw * r.max(0.0));
match side {
None => (l, r),
Some(true) => (l, 0.0),
Some(false) => (0.0, r),
}
}
/// The ribs at a turn at `p` from direction `din` to `dout` (unit vectors), reaching `r`
/// across: one on the bisector, or a fan round the outside of a sharp corner (its miter, or the
/// box round its round or bevel join).
fn turn(&self, p: Point, din: Vec2, dout: Vec2, r: f64, t: f64, band: (f64, f64)) -> Vec<Rib> {
let (nin, nout) = (left(din), left(dout));
let den = 1.0 + nin.dot(nout);
let stretch = if den > 1e-12 { (2.0 / den).sqrt() } else { f64::INFINITY };
if stretch <= SHARP {
let m = (nin + nout) / den;
return vec![Rib { c: p, l: p + m * r, r: p - m * r, reach: (r, r), t, band }];
}
// `s` is 1 when the outside of the turn is on the left; `out_dir` the outward bisector.
let s = if dout.dot(nin) > 0.0 { -1.0 } else { 1.0 };
let sum = nin + nout;
let out_dir = if sum.hypot() > 1e-9 { unit(sum) * s } else { din };
let (o1, o2) = (p + nin * (s * r), p + nout * (s * r));
let mitered = stretch <= std::f64::consts::SQRT_2 || (self.st.join == LineJoin::Miter && stretch <= self.st.miter_limit);
let outer = if mitered { vec![o1, p + out_dir * (stretch * r), o2] } else { vec![o1, o1 + din * r, o2 - dout * r, o2] };
let last = outer.len() - 1;
outer
.into_iter()
.enumerate()
.map(|(k, o)| {
let (inner, inner_reach) = match k {
_ if stretch <= HAIRPIN => (p - out_dir * (stretch * r), r),
0 => (p - nin * (s * r), r),
_ if k == last => (p - nout * (s * r), r),
_ => (p, 0.0),
};
let o_reach = o.distance(p);
if s > 0.0 {
Rib { c: p, l: o, r: inner, reach: (o_reach, inner_reach), t, band }
} else {
Rib { c: p, l: inner, r: o, reach: (inner_reach, o_reach), t, band }
}
})
.collect()
}
}
/// The ribs of each subpath of `bp` (filled with `rule`) under stroke `st`, flattened to `tol`,
/// reaching `margin` past what the stroke paints. Fractions `marks` of each subpath get ribs of
/// their own, and no two are more than `max_dt` of it apart.
fn strips(bp: &BezPath, rule: FillRule, st: &StrokeLayer, tol: f64, margin: f64, marks: &[f64], max_dt: f64) -> Vec<Vec<Rib>> {
let closed_path = is_closed(bp);
let hw = aligned_width(st, closed_path) / 2.0;
if !(hw > 0.0 && hw.is_finite()) {
return vec![];
}
let full = hw * st.profile_max();
let heads = (st.head_reach(false), st.head_reach(true));
let cap = cap_extent(st.cap, 2.0 * full);
let lay = Lay { st, hw, cover: full + margin, margin, ext: (cap.max(heads.0) + margin, cap.max(heads.1) + margin) };
let subs = subpaths(bp);
let count = subs.len();
let mut out = vec![];
for (k, (range, closed)) in subs.into_iter().enumerate() {
let (pts, corner) = flatten(&segments(&bp.elements()[range]), closed, tol.max(1e-4));
let side =
(st.align != StrokeAlign::Center && closed_path && closed).then(|| band_on_left(bp, rule, &pts, st.align, (4.0 * tol).min(hw / 2.0)));
// Arrowheads sit on the start of the first subpath and the end of the last one.
let heads = (if k == 0 { heads.0 } else { 0.0 }, if k + 1 == count { heads.1 } else { 0.0 });
let ribs = match pts.len() {
0 => continue,
// A subpath of no length: a dot (round and projecting caps paint it).
1 => {
let (d, b, e) = (Vec2::new(1.0, 0.0), lay.band(0.0, side), lay.ext.0.max(lay.ext.1));
vec![Rib::square(pts[0] - d * e, d, lay.cover, 0.0, b), Rib::square(pts[0] + d * e, d, lay.cover, 0.0, b)]
}
_ => {
let total = length(&pts, closed);
if total <= 1e-12 {
continue;
}
let steps = if max_dt < 1.0 { (1.0 / max_dt).ceil() as usize } else { 1 };
let profile = st.profile.iter().flat_map(|p| p.points.iter().map(|q| q.0));
let at: Vec<f64> =
marks.iter().copied().chain(profile).chain((1..steps).map(|i| i as f64 / steps as f64)).map(|t| t * total).collect();
let (pts, _) = split_at(&pts, &corner, closed, &at);
strip(&lay, &pts, closed, total, side, if closed { (0.0, 0.0) } else { heads })
}
};
out.push(ribs);
}
out
}
/// Is the visible band of an inside or outside stroke (`align`) on the left of the closed
/// subpath `pts` of `bp`? Probes `off` left of the middle of its longest segment (past where
/// flattening moved it).
fn band_on_left(bp: &BezPath, rule: FillRule, pts: &[Point], align: StrokeAlign, off: f64) -> bool {
let n = pts.len();
let Some(i) = (0..n).max_by(|&a, &b| pts[a].distance(pts[(a + 1) % n]).total_cmp(&pts[b].distance(pts[(b + 1) % n]))) else { return true };
let (a, b) = (pts[i], pts[(i + 1) % n]);
let probe = a.midpoint(b) + left(unit(b - a)) * off.max(1e-6);
let w = bp.winding(probe);
let inside = if rule == FillRule::EvenOdd { w % 2 != 0 } else { w != 0 };
inside == (align == StrokeAlign::Inside)
}
/// The ribs along one flattened subpath `pts` of length `total` (`heads`: how far arrowheads
/// reach from its start and end).
fn strip(lay: &Lay, pts: &[Point], closed: bool, total: f64, side: Option<bool>, heads: (f64, f64)) -> Vec<Rib> {
let n = pts.len();
let seg_count = if closed { n } else { n - 1 };
let dir: Vec<Vec2> = (0..seg_count).map(|i| unit(pts[(i + 1) % n] - pts[i])).collect();
// Ribs near an arrowhead reach across it.
let reach = |s: f64| {
let mut r = lay.cover;
if heads.0 > 0.0 && s <= heads.0 {
r = r.max(heads.0 + lay.margin);
}
if heads.1 > 0.0 && total - s <= heads.1 {
r = r.max(heads.1 + lay.margin);
}
r
};
let mut out = Vec::with_capacity(n + 4);
let mut s = 0.0;
if !closed {
let (d, b) = (dir[0], lay.band(0.0, side));
out.push(Rib::square(pts[0] - d * lay.ext.0, d, reach(0.0), 0.0, b));
out.push(Rib::square(pts[0], d, reach(0.0), 0.0, b));
s = pts[0].distance(pts[1]);
}
let (first, last) = if closed { (0, n) } else { (1, n - 1) };
for i in first..last {
let v = i % n;
let t = s / total;
let ribs = lay.turn(pts[v], dir[(v + seg_count - 1) % seg_count], dir[v % seg_count], reach(s), t, lay.band(t, side));
// A closed subpath starts after the fan of its first corner and ends with it.
let skip = if closed && i == 0 { ribs.len() - 1 } else { 0 };
out.extend(ribs.into_iter().skip(skip));
s += pts[v].distance(pts[(v + 1) % n]);
}
if closed {
out.extend(lay.turn(pts[0], dir[seg_count - 1], dir[0], reach(total), 1.0, lay.band(1.0, side)));
} else {
let (d, b) = (dir[seg_count - 1], lay.band(1.0, side));
out.push(Rib::square(pts[n - 1], d, reach(total), 1.0, b));
out.push(Rib::square(pts[n - 1] + d * lay.ext.1, d, reach(total), 1.0, b));
}
out
}
/// A piece of a stroke whose gradient runs along or across it ([`gradient_slices`]).
#[derive(Clone, Debug)]
pub struct Slice {
/// The area it paints (clipped to the stroke's outline).
pub shape: BezPath,
/// Its piece of the gradient runs from position `span.0` at `from` to `span.1` at `to`, and
/// on unchanged past them; one colour when the span is empty.
pub from: Point,
pub to: Point,
pub span: (f64, f64),
}
impl Slice {
/// The slice's paint: its piece of `g` as a linear gradient placed from `from` to `to`.
pub fn paint(&self, g: &Gradient) -> Paint {
let gradient = g.span(self.span.0 as f32, self.span.1 as f32);
let end = if self.from.distance(self.to) > 1e-9 { self.to } else { self.from + Vec2::new(1.0, 0.0) };
let geom = GradientGeom { start: self.from, end, aspect: 1.0, focal: None };
Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), angle: geom.angle_deg(), ..GradientPaint::new(gradient) }))
}
}
/// The slices that paint stroke `st` of `bp` (filled with `rule`) when its gradient runs along or
/// across the path (see the module docs): flattened to `tol`, reaching `margin` past the
/// stroke's edge. Clip them to the stroke's outline and fill them in order. With `grow` > 0 each
/// slice reaches that much past its edges into its neighbours, so antialiased edges show no
/// seams: filled so that each replaces what it covers (copy), they paint each point once; filled
/// over each other, only opaque gradients may grow (translucent ones would darken there).
pub fn gradient_slices(bp: &BezPath, rule: FillRule, st: &StrokeLayer, tol: f64, margin: f64, grow: f64) -> Vec<Slice> {
let across = st.gradient_mode == StrokeGradientMode::Across;
// A width profile changes the across band along the path: ribs close enough to follow it.
let max_dt = if across && st.profile.is_some() { PROFILE_STEP } else { 1.0 };
let mut out = vec![];
for ribs in strips(bp, rule, st, tol, margin, &[], max_dt) {
for w in ribs.windows(2) {
let (a, b) = (&w[0], &w[1]);
let shape = polygon(&[a.l, b.l, b.c, b.r, a.r, a.c], grow);
if shape.elements().is_empty() {
continue;
}
let (from, to, span) = if across {
let axis = b.c - a.c;
let n = if axis.hypot() > 1e-9 { left(unit(axis)) } else { unit((a.l - a.r) + (b.l - b.r)) };
let mid = a.c.midpoint(b.c);
let (l, r) = ((a.band.0 + b.band.0) / 2.0, (a.band.1 + b.band.1) / 2.0);
(mid + n * l, mid - n * r, (0.0, 1.0))
} else {
(a.c, b.c, (a.t, b.t))
};
out.push(Slice { shape, from, to, span });
}
}
out
}
/// The closed polygon through `pts`, each edge moved out by `grow` (mitred, at most 4 × `grow`
/// out at a corner). Repeated points and spikes are dropped; empty when no area is left.
fn polygon(pts: &[Point], grow: f64) -> BezPath {
let mut v: Vec<Point> = pts.to_vec();
// Drop repeated points and spikes (there and straight back), which have no outward side.
loop {
let n = v.len();
let same = |a: Point, b: Point| a.distance(b) <= 1e-9;
let Some(i) = (0..n).find(|&i| n > 2 && (same(v[i], v[(i + 1) % n]) || same(v[(i + n - 1) % n], v[(i + 1) % n]))) else { break };
v.remove(i);
}
let mut out = BezPath::new();
if v.len() < 3 {
return out;
}
let n = v.len();
if grow > 0.0 {
let area: f64 = (0..n).map(|i| v[i].to_vec2().cross(v[(i + 1) % n].to_vec2())).sum();
let side = if area >= 0.0 { 1.0 } else { -1.0 };
let normal = |i: usize| {
let d = unit(v[(i + 1) % n] - v[i]);
Vec2::new(d.y, -d.x) * side
};
v = (0..n)
.map(|i| {
let (n1, n2) = (normal((i + n - 1) % n), normal(i));
let den = 1.0 + n1.dot(n2);
let m = if den > 1e-9 { (n1 + n2) / den } else { n1 };
let m = if m.hypot() > 4.0 { m * (4.0 / m.hypot()) } else { m };
v[i] + m * grow
})
.collect();
}
out.move_to(v[0]);
for p in &v[1..] {
out.line_to(*p);
}
out.close_path();
out
}
/// What a writer paints for a stroke whose gradient runs along or across it.
#[derive(Clone, Debug)]
pub struct WrittenSlices {
/// The outlines the stroke is written as, as one path (non-zero rule) to clip the slices.
pub clip: BezPath,
/// The slices in paint order, each with its piece of the gradient.
pub slices: Vec<(BezPath, Paint)>,
}
/// How a file writer paints stroke `st` of `bp` (filled with `rule`) when its gradient runs along
/// or across it ([`StrokeLayer::path_gradient`]), given the filled outlines it writes for the
/// stroke ([`for_writer`](super::for_writer)): [`gradient_slices`] clipped to them. Where the
/// gradient is opaque the slices overlap a little, so viewers that antialias every shape show no
/// seams. `None` without such a gradient.
pub fn written_slices(bp: &BezPath, rule: FillRule, st: &StrokeLayer, outlines: &[BezPath]) -> Option<WrittenSlices> {
let g = &st.path_gradient()?.gradient;
let clip = match outlines {
[one] => one.clone(),
_ => vectorcraft_pathops::stroke_region(outlines).to_bezpath(),
};
let grow = if g.stops.iter().all(|s| s.opacity >= 1.0) { SLICE_GROW } else { 0.0 };
let slices = gradient_slices(bp, rule, st, SLICE_TOL, SLICE_MARGIN, grow)
.into_iter()
.map(|s| {
let paint = s.paint(g);
(s.shape, paint)
})
.collect();
Some(WrittenSlices { clip, slices })
}
/// Outline Stroke of stroke `st` of `bp` (filled with `rule`) whose gradient `g` runs along or
/// across it: a gradient mesh per subpath over all the stroke can paint there (clip it to the
/// stroke's outline), coloured as [`gradient_slices`] paint it.
pub fn gradient_meshes(bp: &BezPath, rule: FillRule, st: &StrokeLayer, g: &Gradient) -> Vec<GradientMesh> {
let across = st.gradient_mode == StrokeGradientMode::Across;
let color = |t: f64| g.sample_with(t.clamp(0.0, 1.0) as f32, lerp_color);
// Along: a column at each stop (colours are linear between columns), close enough to look smooth.
let marks: Vec<f64> = if across { vec![] } else { g.expanded_stops().iter().map(|s| s.0 as f64).collect() };
let max_dt = match (across, st.profile.is_some()) {
(false, _) => MESH_STEP,
(true, true) => PROFILE_STEP,
(true, false) => 1.0,
};
// Rows across: the strip's edges, then (across) the band's left edge to its right edge with a row at each stop.
let mut us: Vec<f64> = if across {
(0..=MESH_ROWS).map(|i| i as f64 / MESH_ROWS as f64).chain(g.expanded_stops().iter().map(|s| s.0 as f64)).collect()
} else {
vec![0.5]
};
us.sort_by(f64::total_cmp);
us.dedup_by(|a, b| (*a - *b).abs() < 1e-6);
strips(bp, rule, st, SLICE_TOL, SLICE_MARGIN, &marks, max_dt)
.into_iter()
.filter(|ribs| ribs.len() > 1)
.map(|ribs| {
let (rows, cols) = (us.len() + 1, ribs.len() - 1);
// Each level across: a point on each rib and the gradient position there.
let level = |row: usize, rib: &Rib| -> (Point, f64) {
let t = |u: f64| if across { u } else { rib.t };
match row {
0 => (rib.l, t(0.0)),
_ if row == rows => (rib.r, t(1.0)),
_ if across => {
let (l, r) = rib.band;
(rib.at(l - us[row - 1] * (l + r)), us[row - 1])
}
_ => (rib.c, rib.t),
}
};
let level = &level;
let pos: Vec<Point> = (0..=rows).flat_map(|row| ribs.iter().map(move |rib| level(row, rib).0)).collect();
let at = |row: usize, col: usize| pos[row * (cols + 1) + col];
let mut points = Vec::with_capacity(pos.len());
for row in 0..=rows {
for (col, rib) in ribs.iter().enumerate() {
let p = at(row, col);
let toward = |o: Option<Point>| o.map_or(Vec2::ZERO, |o| (o - p) / 3.0);
let mut handles = [Vec2::ZERO; 4];
handles[H_RIGHT] = toward((col < cols).then(|| at(row, col + 1)));
handles[H_LEFT] = toward(col.checked_sub(1).map(|c| at(row, c)));
handles[H_DOWN] = toward((row < rows).then(|| at(row + 1, col)));
handles[H_UP] = toward(row.checked_sub(1).map(|r| at(r, col)));
let (color, opacity) = color(level(row, rib).1);
points.push(MeshPoint { p, color, opacity, handles });
}
}
GradientMesh { rows: rows as u32, cols: cols as u32, points }
})
.collect()
}
+9 -4
View File
@@ -33,12 +33,15 @@ pub enum WrittenShape {
/// and dash pattern.
Stroke { width: f64 },
/// Filled outlines (non-zero rule): the line, then each arrowhead. They overlap, so they take
/// the stroke's opacity once, as a group.
/// the stroke's opacity once, as a group. A gradient along or across the stroke
/// ([`StrokeLayer::path_gradient`]) paints its [`gradient_slices`](super::gradient_slices)
/// clipped to them instead.
Fill(Vec<BezPath>),
}
/// Does `st` draw as a plain centred stroke on every path (no alignment, arrowheads, width
/// profile, brush, fitted dashes or dots)? Writers then need no geometry for it.
/// profile, brush, fitted dashes, dots or gradient along or across it)? Writers then need no
/// geometry for it.
pub fn is_plain(st: &StrokeLayer) -> bool {
st.align == StrokeAlign::Center
&& st.start_arrow.is_none()
@@ -46,6 +49,7 @@ pub fn is_plain(st: &StrokeLayer) -> bool {
&& st.profile.is_none()
&& st.brush.is_none()
&& !needs_outline_dashes(st)
&& st.path_gradient().is_none()
}
/// Dashes a plain stroke can't draw like the canvas: fitted to corners, or zero-length dashes
@@ -54,9 +58,10 @@ fn needs_outline_dashes(st: &StrokeLayer) -> bool {
st.dash.as_ref().is_some_and(|d| d.is_dashed() && (d.align_corners || (st.cap != LineCap::Butt && d.pattern.contains(&0.0))))
}
/// Do these pieces of `st` need filled outlines (see [`is_plain`])? Alignment alone doesn't.
/// Do these pieces of `st` need filled outlines (see [`is_plain`])? Alignment alone doesn't; a
/// gradient along or across the stroke paints slices clipped to them.
fn needs_outline(pieces: &StrokePieces, st: &StrokeLayer) -> bool {
!pieces.heads.is_empty() || st.profile.is_some() || needs_outline_dashes(st)
!pieces.heads.is_empty() || st.profile.is_some() || needs_outline_dashes(st) || st.path_gradient().is_some()
}
/// How a writer draws stroke `st` along `bp` (brushes aside) to match the canvas.
+83
View File
@@ -0,0 +1,83 @@
//! Every arrowhead's outline: drawn, inside its box (4 × 4 weights; the open arrow's square-cut
//! arms reach a little further back), without self-intersections, and covering the end of the
//! stroke under it.
use kurbo::{BezPath, PathEl, Point, Shape};
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{ArrowAlign, Arrowhead, StrokeLayer};
use super::stroke_pieces;
/// A 2 pt line along +x ending at (100, 0) with `kind` at its end, tip on the end point: heads
/// of weight 2, so 8 long and 8 wide.
fn head(kind: Arrowhead) -> super::Arrow {
let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), 2.0);
st.end_arrow = Some(kind);
st.arrow_align = ArrowAlign::Tip;
let mut l = BezPath::new();
l.move_to((0.0, 0.0));
l.line_to((100.0, 0.0));
stroke_pieces(&l, &st).heads.remove(0)
}
/// The outline's closed contours as polygons (curves flattened).
fn contours(bp: &BezPath) -> Vec<Vec<Point>> {
let mut out: Vec<Vec<Point>> = vec![];
kurbo::flatten(bp.iter(), 1e-3, |el| match el {
PathEl::MoveTo(p) => out.push(vec![p]),
PathEl::LineTo(p) => out.last_mut().unwrap().push(p),
PathEl::ClosePath => {
let c = out.last_mut().unwrap();
if c.len() > 1 && c[0].distance(*c.last().unwrap()) < 1e-9 {
c.pop();
}
}
_ => panic!("flattened"),
});
out
}
/// Do segments `a` and `b` cross at a point inside both (touching ends don't count)?
fn cross(a: (Point, Point), b: (Point, Point)) -> bool {
let orient = |p: Point, q: Point, r: Point| (q - p).cross(r - p);
let (d1, d2) = (orient(b.0, b.1, a.0), orient(b.0, b.1, a.1));
let (d3, d4) = (orient(a.0, a.1, b.0), orient(a.0, a.1, b.1));
d1 * d2 < -1e-12 && d3 * d4 < -1e-12
}
#[test]
fn every_outline_is_drawn_inside_its_box_without_self_intersections() {
let (o, d) = (Point::ORIGIN, Point::new(2.0, 2.0));
assert!(cross((o, d), (Point::new(0.0, 2.0), Point::new(2.0, 0.0))) && !cross((o, d), (d, Point::new(4.0, 0.0))), "the check itself");
for kind in Arrowhead::ALL {
let h = head(kind);
assert!(h.outline.area().abs() > 4.0, "{kind:?} is drawn");
let b = h.outline.bounding_box();
assert!(b.x0 >= 91.0 - 1e-6 && b.x1 <= 100.0 + 1e-6 && b.y0 >= -4.0 - 1e-6 && b.y1 <= 4.0 + 1e-6, "{kind:?} leaves its box: {b:?}");
let edges: Vec<(Point, Point)> = contours(&h.outline).iter().flat_map(|c| (0..c.len()).map(|i| (c[i], c[(i + 1) % c.len()]))).collect();
assert!(edges.len() >= 3, "{kind:?}");
for (i, a) in edges.iter().enumerate() {
for b in &edges[i + 1..] {
assert!(!cross(*a, *b), "{kind:?}: {a:?} crosses {b:?}");
}
}
}
}
#[test]
fn the_stroke_ends_inside_every_head() {
for kind in Arrowhead::ALL {
let h = head(kind);
// Just in front of where the line stops, on its centre line.
let end = h.tip - h.dir * (h.inset - 0.1);
assert_ne!(h.outline.winding(end), 0, "{kind:?}: the line ends outside the head (inset {})", h.inset);
}
}
#[test]
fn half_arrows_barb_on_their_own_side() {
// Pointing along +x on a y-down page, left is −y.
assert!(head(Arrowhead::HalfArrowLeft).outline.bounding_box().y0 < -3.0);
assert!(head(Arrowhead::HalfArrowLeft).outline.bounding_box().y1 < 1.5);
assert!(head(Arrowhead::HalfArrowRight).outline.bounding_box().y1 > 3.0);
}
+213
View File
@@ -0,0 +1,213 @@
use kurbo::{BezPath, Point, Shape, Vec2};
use vectorcraft_color::{Color, Gradient, GradientPaint, GradientStop, Paint};
use vectorcraft_doc::{ArrowAlign, Arrowhead, Dash, LineCap, LineJoin, StrokeAlign, StrokeGradientMode, StrokeLayer, WidthProfile};
use vectorcraft_geom::FillRule;
use super::*;
fn stroke(width: f64, mode: StrokeGradientMode) -> StrokeLayer {
let mut st = StrokeLayer::new(Paint::Gradient(Box::new(GradientPaint::new(Gradient::default()))), width);
st.gradient_mode = mode;
st
}
fn poly(pts: &[(f64, f64)], closed: bool) -> BezPath {
let mut b = BezPath::new();
b.move_to(pts[0]);
for p in &pts[1..] {
b.line_to(*p);
}
if closed {
b.close_path();
}
b
}
/// The gradient position the slices give `p` (the last slice holding it wins, as when filled).
fn param(slices: &[Slice], p: Point) -> Option<f64> {
slices.iter().rev().find(|s| s.shape.contains(p)).map(|s| {
let d = s.to - s.from;
let u = if d.hypot2() > 1e-18 { ((p - s.from).dot(d) / d.hypot2()).clamp(0.0, 1.0) } else { 0.0 };
s.span.0 + (s.span.1 - s.span.0) * u
})
}
fn slices(bp: &BezPath, st: &StrokeLayer) -> Vec<Slice> {
gradient_slices(bp, FillRule::NonZero, st, 0.01, 0.5, 0.0)
}
/// Every point the stroke paints (on a grid over each of its outlines) lies in a slice.
fn assert_covered(bp: &BezPath, st: &StrokeLayer) {
let sl = slices(bp, st);
let pieces = stroke_pieces(bp, st);
let mut parts = vec![line_outline(&pieces.line, st, aligned_width(st, is_closed(bp)), 0.01)];
parts.extend(pieces.heads.into_iter().map(|h| h.outline));
for part in &parts {
let b = part.bounding_box();
let n = 60;
for i in 0..=n {
for j in 0..=n {
let p = Point::new(b.x0 + b.width() * i as f64 / n as f64, b.y0 + b.height() * j as f64 / n as f64);
if part.contains(p) {
assert!(param(&sl, p).is_some(), "{p:?} of the stroke is in no slice ({:?})", st.join);
}
}
}
}
}
#[test]
fn span_is_the_part_of_the_gradient_between_two_positions() {
let g = Gradient::default();
let grey = |g: &Gradient, t: f32| g.sample(t).0.to_rgb()[0];
let s = g.span(0.25, 0.75);
assert_eq!(s.stops.len(), 2);
assert!((grey(&s, 0.0) - 0.75).abs() < 1e-5 && (grey(&s, 1.0) - 0.25).abs() < 1e-5);
assert!((grey(&s, 0.5) - 0.5).abs() < 1e-5);
// Backwards, and one colour when empty.
let r = g.span(0.75, 0.25);
assert!((grey(&r, 0.0) - 0.25).abs() < 1e-5 && (grey(&r, 1.0) - 0.75).abs() < 1e-5);
let c = g.span(0.4, 0.4);
assert!((grey(&c, 0.0) - grey(&c, 1.0)).abs() < 1e-6);
// Stops and off-centre midpoints inside the span keep their colours.
let mut g3 = Gradient::default();
g3.stops.insert(1, GradientStop::new(0.5, Color::rgb(1.0, 0.0, 0.0)));
g3.stops[0].midpoint = 0.25;
let s3 = g3.span(0.0, 1.0);
for t in [0.05, 0.125, 0.3, 0.5, 0.7, 0.95] {
let (a, b) = (g3.sample(t).0.to_rgb(), s3.sample(t).0.to_rgb());
assert!(a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-4), "{t}: {a:?} vs {b:?}");
}
}
#[test]
fn along_maps_the_length_of_the_path_in_any_direction() {
let st = stroke(10.0, StrokeGradientMode::Along);
for angle in [0.0f64, 37.0, 90.0, 200.0, 315.0] {
let d = Vec2::new(angle.to_radians().cos(), angle.to_radians().sin());
let start = Point::new(50.0, 50.0);
let sl = slices(&poly(&[(start.x, start.y), (start.x + 100.0 * d.x, start.y + 100.0 * d.y)], false), &st);
let n = Vec2::new(-d.y, d.x);
for (at, across) in [(25.0, 0.0), (25.0, 4.0), (25.0, -4.0), (60.0, 2.0)] {
let t = param(&sl, start + d * at + n * across).unwrap();
assert!((t - at / 100.0).abs() < 1e-6, "{angle}°: {t} at {at}");
}
// Past the ends (under caps and arrowheads) the end colours carry on.
assert_eq!(param(&sl, start - d * 0.3), Some(0.0));
// The slices hug the stroke.
assert_eq!(param(&sl, start + d * 50.0 + n * 7.0), None);
}
// Round a closed square: positions are fractions of its perimeter.
let sl = slices(&poly(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], true), &st);
assert!((param(&sl, Point::new(50.0, 2.0)).unwrap() - 0.125).abs() < 1e-6);
assert!((param(&sl, Point::new(102.0, 50.0)).unwrap() - 0.375).abs() < 1e-6);
assert!((param(&sl, Point::new(101.0, -1.0)).unwrap() - 0.25).abs() < 1e-6);
}
#[test]
fn along_keeps_a_corners_colour_round_its_outside() {
let st = stroke(20.0, StrokeGradientMode::Along);
// Right then down: the outside of the corner is up and to the right.
let sl = slices(&poly(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0)], false), &st);
for p in [(105.0, -5.0), (109.0, -9.0), (101.0, -8.0), (108.0, -1.0)] {
assert!((param(&sl, p.into()).unwrap() - 0.5).abs() < 1e-6, "{p:?}");
}
// Inside the corner each side takes the nearest point of its own segment.
assert!((param(&sl, Point::new(92.0, 5.0)).unwrap() - 0.46).abs() < 1e-6);
assert!((param(&sl, Point::new(95.0, 8.0)).unwrap() - 0.54).abs() < 1e-6);
}
#[test]
fn across_runs_from_the_left_edge_to_the_right() {
let st = stroke(10.0, StrokeGradientMode::Across);
// Travelling +x (y down), the left edge is up.
let line = poly(&[(0.0, 0.0), (100.0, 0.0)], false);
let sl = slices(&line, &st);
for (y, want) in [(-5.0, 0.0), (-2.5, 0.25), (0.0, 0.5), (4.0, 0.9), (5.0, 1.0)] {
assert!((param(&sl, Point::new(37.0, y)).unwrap() - want).abs() < 1e-6, "{y}");
}
// The same all round a curve: half way across is half way, wherever.
let sl = slices(&kurbo::Circle::new((0.0, 0.0), 60.0).to_path(1e-3), &st);
for k in 0..12 {
let dir = Vec2::from_angle(k as f64 * 0.5);
let (inner, mid) = (param(&sl, (dir * 56.0).to_point()).unwrap(), param(&sl, (dir * 60.0).to_point()).unwrap());
assert!((mid - 0.5).abs() < 0.02 && (inner - 0.5).abs() > 0.3, "{mid} {inner}");
}
// With a width profile, across runs between the stroke's edges where they are.
let mut lens = st.clone();
lens.profile = Some(WidthProfile::lens());
let sl = slices(&line, &lens);
// A quarter of the way along, the lens is half as wide: its top edge is 2.5 up.
assert!(param(&sl, Point::new(25.0, -2.4)).unwrap() < 0.05);
assert!((param(&sl, Point::new(50.0, -2.5)).unwrap() - 0.25).abs() < 0.02);
}
#[test]
fn an_aligned_stroke_spans_the_gradient_across_the_side_it_shows_on() {
for align in [StrokeAlign::Inside, StrokeAlign::Outside] {
for reverse in [false, true] {
let mut st = stroke(10.0, StrokeGradientMode::Across);
st.align = align;
let mut pts = vec![(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)];
if reverse {
pts.reverse();
}
let sl = slices(&poly(&pts, true), &st);
// Across the top edge: from the path to 10 pt into the side the stroke shows on.
let dy = if align == StrokeAlign::Inside { 1.0 } else { -1.0 };
let (at_path, far) = (param(&sl, Point::new(50.0, 0.0)).unwrap(), param(&sl, Point::new(50.0, 10.0 * dy)).unwrap());
assert!((at_path - far).abs() > 0.99, "{align:?} {reverse}: {at_path} → {far}");
assert!((param(&sl, Point::new(50.0, 5.0 * dy)).unwrap() - 0.5).abs() < 1e-6);
}
}
}
#[test]
fn slices_cover_everything_the_stroke_paints() {
let zig = poly(&[(0.0, 0.0), (60.0, 40.0), (0.0, 80.0), (70.0, 90.0), (75.0, 20.0)], false);
let mut curve = BezPath::new();
curve.move_to((0.0, 0.0));
curve.curve_to((80.0, -60.0), (120.0, 120.0), (10.0, 60.0));
let triangle = poly(&[(0.0, 0.0), (100.0, 0.0), (50.0, 30.0)], true);
for mode in [StrokeGradientMode::Along, StrokeGradientMode::Across] {
for join in [LineJoin::Miter, LineJoin::Round, LineJoin::Bevel] {
let mut st = stroke(12.0, mode);
st.join = join;
st.cap = LineCap::Square;
assert_covered(&zig, &st);
assert_covered(&curve, &st);
assert_covered(&triangle, &st);
st.start_arrow = Some(Arrowhead::Triangle);
st.end_arrow = Some(Arrowhead::CircleOpen);
assert_covered(&zig, &st);
st.arrow_align = ArrowAlign::Tip;
assert_covered(&curve, &st);
st.profile = WidthProfile::preset("wave");
st.dash = Some(Dash { pattern: vec![12.0, 6.0], ..Default::default() });
assert_covered(&zig, &st);
st.align = StrokeAlign::Outside;
assert_covered(&triangle, &st);
}
}
}
#[test]
fn meshes_colour_the_stroke_as_the_slices_do() {
let g = Gradient::default();
let shape = poly(&[(0.0, 0.0), (100.0, 0.0), (100.0, 60.0)], false);
for mode in [StrokeGradientMode::Along, StrokeGradientMode::Across] {
let st = stroke(10.0, mode);
let sl = slices(&shape, &st);
let meshes = gradient_meshes(&shape, FillRule::NonZero, &st, &g);
assert_eq!(meshes.len(), 1);
assert!(meshes[0].is_valid());
let quads = meshes[0].quads(4);
for p in [(25.0, 0.0), (40.0, -3.0), (70.0, 4.0), (100.0, 30.0), (98.0, 50.0), (103.0, 20.0)] {
let p = Point::new(p.0, p.1);
let want = 1.0 - param(&sl, p).unwrap();
let q = quads.iter().find(|q| poly(&q.pts.map(|v| (v.x, v.y)), true).contains(p)).expect("in the mesh");
let got = q.color.to_rgb()[0] as f64;
assert!((got - want).abs() < 0.05, "{mode:?} {p:?}: mesh {got} vs {want}");
}
}
}
+92
View File
@@ -0,0 +1,92 @@
//! The document's stroke bounds and clicks (`vectorcraft_doc` reach) against the geometry the
//! stroke really paints: every painted point is inside the visual bounds and hits.
use kurbo::{BezPath, Point, Rect, Shape};
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{ArrowAlign, Arrowhead, Dash, LineCap, LineJoin, StrokeAlign, StrokeLayer, WidthProfile};
use vectorcraft_geom::hit::fill_contains;
use vectorcraft_geom::{FillRule, PathData};
use super::outline_region;
fn paths() -> Vec<BezPath> {
let mut curve = BezPath::new();
curve.move_to((10.0, 60.0));
curve.curve_to((30.0, 0.0), (70.0, 120.0), (90.0, 40.0));
let mut zigzag = BezPath::new();
zigzag.move_to((10.0, 20.0));
zigzag.line_to((40.0, 70.0));
zigzag.line_to((55.0, 15.0));
zigzag.line_to((90.0, 60.0));
let mut tri = BezPath::new();
tri.move_to((10.0, 10.0));
tri.line_to((90.0, 30.0));
tri.line_to((10.0, 50.0));
tri.close_path();
vec![curve, zigzag, tri, Rect::new(20.0, 20.0, 80.0, 70.0).to_path(0.1)]
}
/// Check `st` along `bp`: the painted region's box is inside the bounds, and points of the
/// region (on a 1.5 pt grid) hit within a quarter point, as the painted outlines are flattened.
/// Variable widths are drawn straight between their offsets at the path's samples and inner
/// corners, which beside sharp corners can paint up to about a point past the exact width there.
fn check(bp: &BezPath, st: &StrokeLayer, what: &str) {
let region = outline_region(&PathData::from_bezpath(bp), FillRule::NonZero, st).to_bezpath();
if region.elements().is_empty() {
return;
}
let painted = region.bounding_box();
let bounds = st.bounds_on(bp, bp.bounding_box());
assert!(bounds.inflate(0.05, 0.05).contains_rect(painted), "{what}: paints {painted:?} outside {bounds:?}");
let tol = if st.profile.is_some() { 1.0 } else { 0.25 };
// Off the outline's own coordinates, so no sample sits level with a vertex.
let (mut x, mut checked) = (painted.x0 + 0.371, 0);
while x <= painted.x1 {
let mut y = painted.y0 + 0.293;
while y <= painted.y1 {
let p = Point::new(x, y);
if fill_contains(&region, FillRule::EvenOdd, p) {
assert!(st.hits(bp, FillRule::NonZero, p, tol), "{what}: painted {p:?} doesn't hit");
checked += 1;
}
y += 1.5;
}
x += 1.5;
}
assert!(checked > 0, "{what}: no samples");
}
#[test]
fn bounds_and_clicks_cover_what_every_stroke_paints() {
let profiles = [None, Some(WidthProfile::lens()), Some(WidthProfile { points: vec![(0.0, 2.0, 0.5), (0.6, 0.8, 1.6), (1.0, 1.2, 0.3)] })];
for (pi, bp) in paths().iter().enumerate() {
for align in [StrokeAlign::Center, StrokeAlign::Inside, StrokeAlign::Outside] {
for cap in [LineCap::Butt, LineCap::Round, LineCap::Square] {
for (join, limit) in [(LineJoin::Miter, 10.0), (LineJoin::Miter, 2.0), (LineJoin::Round, 10.0), (LineJoin::Bevel, 10.0)] {
for (fi, profile) in profiles.iter().enumerate() {
for dash in [None, Some(Dash { pattern: vec![7.0, 4.0], offset: 0.0, align_corners: false })] {
let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), 6.0);
(st.align, st.cap, st.join, st.miter_limit, st.profile, st.dash) =
(align, cap, join, limit, profile.clone(), dash.clone());
check(bp, &st, &format!("path {pi} {align:?} {cap:?} {join:?} {limit} profile {fi} dashed {}", dash.is_some()));
}
}
}
}
}
}
}
#[test]
fn bounds_and_clicks_cover_every_arrowhead() {
let bp = &paths()[0];
for kind in Arrowhead::ALL {
for align in [ArrowAlign::Extend, ArrowAlign::Tip] {
for (scale, cap) in [(50.0, LineCap::Round), (100.0, LineCap::Butt), (300.0, LineCap::Square)] {
let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), 3.0);
(st.start_arrow, st.end_arrow, st.arrow_align, st.arrow_scale, st.cap) = (Some(kind), Some(kind), align, (scale, scale), cap);
check(bp, &st, &format!("{kind:?} {align:?} {scale}%"));
}
}
}
}
+51 -13
View File
@@ -43,7 +43,7 @@ pub(super) fn left(t: Vec2) -> Vec2 {
/// The flattened points of one subpath (consecutive duplicates removed; a closed one doesn't
/// repeat its start), each marked when it is a corner of the path.
fn flatten(segs: &[PathSeg], closed: bool, tol: f64) -> (Vec<Point>, Vec<bool>) {
pub(super) fn flatten(segs: &[PathSeg], closed: bool, tol: f64) -> (Vec<Point>, Vec<bool>) {
let Some(s0) = segs.first() else { return (vec![], vec![]) };
let (mut pts, mut corner) = (vec![s0.start()], vec![false]);
// The first and the last segment that drew something.
@@ -85,17 +85,31 @@ fn flatten(segs: &[PathSeg], closed: bool, tol: f64) -> (Vec<Point>, Vec<bool>)
}
/// Insert samples where the profile has width points (so the piecewise-linear profile is exact
/// along straight runs). `span` maps the subpath onto the profile (see [`outline_spans`]).
/// along straight runs; the two points of a discontinuous point share one sample). `span` maps the
/// subpath onto the profile (see [`outline_spans`]).
fn densify(pts: &[Point], corner: &[bool], closed: bool, profile: &WidthProfile, span: (f64, f64)) -> (Vec<Point>, Vec<bool>) {
let n = pts.len();
let seg_count = if closed { n } else { n - 1 };
let total: f64 = (0..seg_count).map(|i| pts[i].distance(pts[(i + 1) % n])).sum();
let total = length(pts, closed);
let range = span.1 - span.0;
if total <= 1e-12 || range <= 1e-12 {
return (pts.to_vec(), corner.to_vec());
}
// Where the profile's points fall along this piece (a span past 1 wraps round a closed path).
let marks: Vec<f64> = profile.points.iter().flat_map(|p| [p.0, p.0 + 1.0]).map(|t| (t - span.0) / range * total).collect();
split_at(pts, corner, closed, &marks)
}
/// Length of a flattened subpath (see [`flatten`]).
pub(super) fn length(pts: &[Point], closed: bool) -> f64 {
let n = pts.len();
let seg_count = if closed { n } else { n.saturating_sub(1) };
(0..seg_count).map(|i| pts[i].distance(pts[(i + 1) % n])).sum()
}
/// A flattened subpath (see [`flatten`]) with points added `marks` along it (distances from its
/// start; those on a point or off the subpath are ignored).
pub(super) fn split_at(pts: &[Point], corner: &[bool], closed: bool, marks: &[f64]) -> (Vec<Point>, Vec<bool>) {
let n = pts.len();
let seg_count = if closed { n } else { n.saturating_sub(1) };
let mut out = (Vec::with_capacity(n + marks.len()), Vec::with_capacity(n + marks.len()));
let mut acc = 0.0;
for i in 0..seg_count {
@@ -105,13 +119,14 @@ fn densify(pts: &[Point], corner: &[bool], closed: bool, profile: &WidthProfile,
out.1.push(corner[i]);
let mut inner: Vec<f64> = marks.iter().copied().filter(|d| *d > acc + 1e-9 && *d < acc + len - 1e-9).collect();
inner.sort_by(f64::total_cmp);
inner.dedup_by(|a, b| (*a - *b).abs() <= 1e-9);
for d in inner {
out.0.push(a.lerp(b, (d - acc) / len));
out.1.push(false);
}
acc += len;
}
if !closed {
if !closed && n > 0 {
out.0.push(pts[n - 1]);
out.1.push(corner[n - 1]);
}
@@ -153,26 +168,34 @@ impl Ctx<'_> {
if total <= 1e-12 {
return;
}
// Left and right offsets at `d` along this piece.
// Left and right offsets just before and just after `d` along this piece (they differ
// at a discontinuous point).
let width_at = |d: f64| {
let t = span.0 + (span.1 - span.0) * d / total;
let (l, r) = self.profile.at(if t > 1.0 { t - 1.0 } else { t });
(self.half * l.max(0.0), self.half * r.max(0.0))
let (b, a) = self.profile.around(if t > 1.0 { t - 1.0 } else { t });
let side = |(l, r): (f64, f64)| (self.half * l.max(0.0), self.half * r.max(0.0));
(side(b), side(a))
};
let mut lpts = Vec::with_capacity(n);
let mut rpts = Vec::with_capacity(n);
for (i, &p) in pts.iter().enumerate() {
let (wl, wr) = width_at(cum[i]);
let (before, after) = width_at(cum[i]);
if !closed && (i == 0 || i == n - 1) {
let nm = left(seg_dir[i.min(seg_count - 1)]);
let (wl, wr) = if i == 0 { after } else { before };
lpts.push(p + nm * wl);
rpts.push(p - nm * wr);
continue;
}
let ip = if i == 0 { seg_count - 1 } else { i - 1 };
let v = Vertex { p, a: seg_dir[ip], b: seg_dir[i], la: cum[ip + 1] - cum[ip], lb: cum[i + 1] - cum[i], corner: corner[i] };
self.join(&mut lpts, &v, wl, 1.0);
self.join(&mut rpts, &v, wr, -1.0);
// A step: the side goes straight out (or in) from the width before to the one after.
for (k, (wl, wr)) in [before, after].into_iter().enumerate() {
if k == 0 || (wl, wr) != before {
self.join(&mut lpts, &v, wl, 1.0);
self.join(&mut rpts, &v, wr, -1.0);
}
}
}
if closed {
polygon(out, lpts.into_iter());
@@ -180,7 +203,7 @@ impl Ctx<'_> {
return;
}
let (t0, t1) = (seg_dir[0], seg_dir[seg_count - 1]);
let ((wl0, wr0), (wl1, wr1)) = (width_at(0.0), width_at(total));
let ((wl0, wr0), (wl1, wr1)) = (width_at(0.0).1, width_at(total).0);
let mut ring = lpts;
// End cap: from the left side around the end to the right side.
cap_points(&mut ring, pts[n - 1], left(t1), t1, wl1, wr1, self.cap);
@@ -304,6 +327,21 @@ mod tests {
assert!(bb.y0 < -4.99 && bb.y1 <= 1e-9, "{bb:?}");
}
#[test]
fn a_discontinuous_point_steps_the_width() {
// 5 pt either side for the first half, 10 pt for the second: a step at the middle.
let p = WidthProfile { points: vec![(0.0, 1.0, 1.0), (0.5, 1.0, 1.0), (0.5, 2.0, 2.0), (1.0, 2.0, 2.0)] };
let o = width_outline(&line(), 10.0, &p, &capped(LineCap::Butt), 0.01);
assert!((area(&o) - 1500.0).abs() < 1e-6, "{}", area(&o));
// No ramp: just before the middle the outline is still 5 pt from the line.
assert!(!o.contains(kurbo::Point::new(49.0, -6.0)) && o.contains(kurbo::Point::new(51.0, -6.0)));
// A step at a corner of a polyline renders too.
let mut l = line();
l.line_to((100.0, 100.0));
let a = area(&width_outline(&l, 10.0, &p, &capped(LineCap::Butt), 0.01));
assert!(a.is_finite() && (a - 3000.0).abs() < 150.0, "{a}");
}
#[test]
fn closed_paths_make_a_ring() {
let mut sq = BezPath::new();
+1 -1
View File
@@ -131,7 +131,7 @@ pub fn scribble(path: &PathData, b: Rect, p: &Value) -> PathData {
}
}
xs.sort_by(f64::total_cmp);
let mut spans: Vec<(f64, f64)> = xs.chunks_exact(2).map(|s| (s[0] - overlap, s[1] + overlap)).collect();
let mut spans: Vec<(f64, f64)> = xs.as_chunks::<2>().0.iter().map(|s| (s[0] - overlap, s[1] + overlap)).collect();
if row % 2 == 1 {
spans.reverse();
}
+34
View File
@@ -0,0 +1,34 @@
//! Scale Strokes & Effects on effects: the catalogue's distance parameters and `scale_effect`.
use serde_json::json;
use vectorcraft_doc::Effect;
use super::*;
#[test]
fn every_distance_parameter_is_a_parameter() {
for e in effect_catalog() {
for k in e.lengths.always.iter().chain(e.lengths.absolute) {
assert!(e.defaults.get(*k).is_some() || e.params.contains(&format!("{k}?:")), "{}: `{k}` is not a parameter", e.id);
}
if !e.lengths.absolute.is_empty() {
assert!(e.defaults.get("relative").is_some(), "{}: absolute lengths need a `relative` param", e.id);
}
}
}
#[test]
fn scale_effect_scales_distances_only() {
let mut e = new_effect("stylize.dropShadow", &json!({"x": 3, "y": "4 pt"})).unwrap();
scale_effect(&mut e, 2.0);
assert_eq!((&e.params["x"], &e.params["y"], &e.params["blur"]), (&json!(6.0), &json!(8.0), &json!(10.0)));
assert_eq!(e.params["opacity"], json!(75.0));
// Outline Stroke without a weight follows its stroke's: nothing to scale.
let mut o = Effect { id: "path.outlineStroke".into(), params: json!(null), visible: true };
scale_effect(&mut o, 2.0);
assert_eq!(o.params, json!(null));
// Relative tweaks are percentages of the object's size.
let mut t = new_effect("distort.tweak", &json!({"h": 10, "relative": true})).unwrap();
scale_effect(&mut t, 2.0);
assert_eq!(t.params["h"], json!(10));
}
+1
View File
@@ -21,6 +21,7 @@ vectorcraft-trace = { workspace = true }
vectorcraft-svg = { workspace = true }
vectorcraft-format = { workspace = true }
vectorcraft-pdf = { workspace = true }
vectorcraft-cad = { workspace = true }
image = { workspace = true }
flate2 = { workspace = true }
kurbo = { workspace = true }
+246 -65
View File
@@ -19,12 +19,14 @@
use serde_json::{Value, json};
use vectorcraft_color::{BlendMode, Paint};
use vectorcraft_doc::{Appearance, AppearanceItem, FillLayer, Node, NodeKind, StrokeLayer};
use vectorcraft_doc::{Appearance, AppearanceItem, CharStyle, FillLayer, Node, NodeKind, ParaStyle, StrokeLayer};
use vectorcraft_geom::Rect;
use super::edit::selected_roots;
use super::opacitymask::percent;
use super::paint::paint_from;
use super::*;
use super::{AppearanceAttrs, EyedropperAttrs, FillAttrs, StrokeAttrs};
use crate::EngineError;
pub fn specs() -> Vec<CommandSpec> {
@@ -115,7 +117,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Eyedropper",
[],
None,
"{source: id, ids?, appearance?: bool, transparency?: bool (default: eyedropper.setOptions)} copy fill, stroke, weight and effects (appearance) and opacity and blend (transparency) from `source` to ids (default: selection), the appearance also to the paint defaults; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art)",
"{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes) from `source` to ids (default: the selection), the fill, stroke and weight also to the paint defaults; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead; `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art) → {ids}",
has_doc,
copy_from
),
@@ -146,6 +148,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
target_contents
),
cmd!(
"appearance.transfer",
"Move Appearance",
[],
None,
"{source: id, target: id, copy?: bool} give `target` (a layer, group or object) the appearance (fills, strokes, effects) and transparency (opacity, blend mode, isolation, knockout) of `source`, as dragging a target circle onto another in the Layers panel does; the source is left with a cleared appearance (as appearance.clear) unless `copy` (Alt-drag). Opacity masks stay; placed gradients keep their place relative to each object's bounds → {source, target}",
has_doc,
transfer
),
]
}
@@ -163,7 +174,7 @@ impl Session {
pub fn appearance_item(&self) -> Option<usize> {
let a = self.active_appearance_item.as_ref()?;
let st = self.active()?;
if st.uid != a.doc || st.selection.objects != a.objects {
if st.uid != a.doc || st.selection.subjects() != a.objects.as_slice() {
return None;
}
let n = st.doc.node(*a.objects.first()?)?;
@@ -228,7 +239,8 @@ impl ItemTarget {
/// leaves (as without an active item) and vice versa. Explicit items are kept (and checked).
pub(crate) fn of_kind(self, s: &Session, fill: bool) -> Self {
let ItemTarget::Item { index, explicit: false } = self else { return self };
let fits = s.active().and_then(|st| st.doc.node(*st.selection.objects.first()?)?.appearance.items.get(index).map(|it| it.is_fill() == fill));
let fits =
s.active().and_then(|st| st.doc.node(*st.selection.subjects().first()?)?.appearance.items.get(index).map(|it| it.is_fill() == fill));
if fits == Some(true) { self } else { ItemTarget::Top }
}
@@ -272,12 +284,22 @@ fn targets_contents(p: &Value) -> Result<bool> {
}
}
/// Objects whose own appearance stack a command edits: `ids`/`id` (layers too), else the selected
/// objects (a selected compound-path member stands for its compound); with `target: "contents"`
/// the painted objects inside the groups and layers among them ([`leaf_targets`]).
/// The objects appearance edits act on without `ids`: the targeted object, group or layer
/// (`layer.target`), else the selected objects (a selected compound-path member stands for its
/// compound).
pub(crate) fn subject_roots(s: &Session) -> Result<Vec<NodeId>> {
match s.doc()?.selection.target {
Some(t) => Ok(vec![t]),
None => selected_roots(s),
}
}
/// Objects whose own appearance stack a command edits: `ids`/`id` (layers too), else the
/// [`subject_roots`]; with `target: "contents"` the painted objects inside the groups and layers
/// among them ([`leaf_targets`]).
pub(crate) fn appearance_targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
let roots = if p.get("ids").is_none() && p.get("id").is_none() {
selected_roots(s)?
subject_roots(s)?
} else {
let d = &s.doc()?.doc;
targets(s, p)?.into_iter().filter(|id| d.node(*id).is_some()).collect()
@@ -345,7 +367,7 @@ fn set_active_item(s: &mut Session, p: &Value) -> Result<Value> {
None => return Err(bad(C, "missing `index` (an item index or null)")),
};
let st = s.doc()?;
let objects = st.selection.objects.clone();
let objects = st.selection.subjects().to_vec();
let first = objects.first().and_then(|id| st.doc.node(*id)).ok_or_else(|| EngineError::Other("nothing selected".into()))?;
let fill = first.appearance.items.get(index).ok_or_else(|| bad(C, format!("no appearance item {index}")))?.is_fill();
let doc = st.uid;
@@ -391,11 +413,7 @@ fn clear_appearance(s: &mut Session, p: &Value) -> Result<Value> {
s.edit("Clear Appearance", |d, _| {
for id in &ids {
if let Some(n) = d.node_mut(*id) {
// No fill, no stroke, and the object's Opacity row back to Default. A group keeps no
// fill or stroke rows of its own.
n.appearance = if is_group(n) { Appearance::default() } else { Appearance::basic(Paint::None, Paint::None, 1.0) };
n.opacity = 1.0;
n.blend = BlendMode::Normal;
clear(n);
}
}
Ok(())
@@ -404,6 +422,45 @@ fn clear_appearance(s: &mut Session, p: &Value) -> Result<Value> {
ok()
}
/// Clear Appearance on `n`: no fill, no stroke, and the object's Opacity row back to Default. A
/// group keeps no fill or stroke rows of its own.
fn clear(n: &mut Node) {
n.appearance = if is_group(n) { Appearance::default() } else { Appearance::basic(Paint::None, Paint::None, 1.0) };
n.opacity = 1.0;
n.blend = BlendMode::Normal;
}
fn transfer(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "appearance.transfer";
let source = id_param(p, "source").ok_or_else(|| bad(C, "missing `source` id"))?;
let target = id_param(p, "target").ok_or_else(|| bad(C, "missing `target` id"))?;
if source == target {
return Err(bad(C, "`source` and `target` are the same object"));
}
let copy = bool_or(p, "copy", false);
s.edit(if copy { "Copy Appearance" } else { "Move Appearance" }, |d, _| {
let src = d.node(source).cloned().ok_or(EngineError::NoNode(source))?;
let to = d.node_mut(target).ok_or(EngineError::NoNode(target))?;
let mut ap = src.appearance.clone();
if let (Some(f), Some(t)) = (src.geometric_bounds(), to.geometric_bounds()) {
ap.rebase_gradients(f, t);
}
// Only groups, layers and type have a Contents (Characters) row to keep a slot for.
if to.contents_label().is_none() {
ap.contents_index = None;
}
to.appearance = ap;
(to.opacity, to.blend, to.isolate, to.knockout, to.knockout_shape) = (src.opacity, src.blend, src.isolate, src.knockout, src.knockout_shape);
if !copy && let Some(n) = d.node_mut(source) {
clear(n);
(n.isolate, n.knockout, n.knockout_shape) = (false, Default::default(), false);
}
Ok(())
})?;
s.active_appearance_item = None;
Ok(json!({ "source": source.0, "target": target.0 }))
}
/// A group or layer (no fill or stroke rows of its own unless added).
fn is_group(n: &Node) -> bool {
matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. })
@@ -630,68 +687,192 @@ fn target_contents(s: &mut Session, p: &Value) -> Result<Value> {
}
fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
let src_id = id_param(p, "source").ok_or_else(|| bad("appearance.copyFrom", "missing `source` id"))?;
let src = s.doc()?.doc.node(src_id).cloned().ok_or(EngineError::NoNode(src_id))?;
// The appearance and the box its placed gradients are relative to (type: its first run's
// paints, in text space).
let (appearance, src_box) = match &src.kind {
NodeKind::Text(t) if !t.runs.is_empty() => {
let r = &t.runs[0];
(r.style.basic_appearance(), Some(t.local_bounds()))
}
_ => (src.appearance.clone(), src.geometric_bounds()),
};
// `appearance` placed on an object whose box (in its paint space) is `to`.
let placed = |to: Option<vectorcraft_geom::Rect>| {
let mut ap = appearance.clone();
if let (Some(f), Some(t)) = (src_box, to) {
ap.rebase_gradients(f, t);
}
ap
};
let opts = s.eyedropper.with(p);
if opts.appearance {
s.paint.fill = super::gradient::unplaced(&appearance.fill_paint());
s.paint.stroke = super::gradient::unplaced(&appearance.stroke_paint());
s.remember_paint(&s.paint.fill.clone());
if appearance.stroke().is_some() {
s.paint.stroke_width = appearance.stroke_width();
}
}
let ids = match ids_param(p, "ids") {
const C: &str = "appearance.copyFrom";
let clicked = id_param(p, "source").ok_or_else(|| bad(C, "missing `source` id"))?;
let (reverse, append) = (bool_or(p, "reverse", false), bool_or(p, "append", false));
let attrs = s.prefs.eyedropper.attrs(p).map_err(|e| bad(C, e))?;
let selected = match ids_param(p, "ids") {
Some(v) => v,
None => selected_roots(s)?,
};
let mut targets = leaf_targets(s, &ids)?;
// Reversed, the first selected object's attributes go onto the clicked object.
let (src_id, mut targets) = if reverse {
let first = leaf_targets(s, &selected)?.into_iter().next().ok_or_else(|| bad(C, "select the object to copy from"))?;
(first, leaf_targets(s, &[clicked])?)
} else {
(clicked, leaf_targets(s, &selected)?)
};
targets.retain(|id| *id != src_id);
if targets.is_empty() || !(opts.appearance || opts.transparency) {
let picked = Picked::of(s.doc()?.doc.node(src_id).ok_or(EngineError::NoNode(src_id))?);
if !reverse {
picked.to_defaults(s, &attrs.appearance);
}
if targets.is_empty() || attrs.is_empty() {
return Ok(json!({ "ids": [] }));
}
let (opacity, blend) = (src.opacity, src.blend);
s.edit("Eyedropper", |d, _| {
for id in &targets {
let Some(n) = d.node_mut(*id) else { continue };
if opts.transparency {
n.opacity = opacity;
n.blend = blend;
if let Some(n) = d.node_mut(*id) {
picked.apply(n, &attrs, append);
}
if !opts.appearance {
continue;
}
if let NodeKind::Text(t) = &mut n.kind {
let ap = placed(Some(t.local_bounds()));
// Characters without a painted stroke get no weight.
let stroke =
ap.stroke().map_or_else(|| StrokeLayer::new(Paint::None, 0.0), |s| StrokeLayer { width: ap.stroke_width(), ..s.clone() });
for r in &mut t.runs {
r.style.fill = ap.fill_paint();
r.style.set_stroke_layer(&stroke);
}
continue;
}
n.appearance = placed(n.geometric_bounds());
}
Ok(())
})?;
Ok(json!({ "ids": targets.iter().map(|i| i.0).collect::<Vec<_>>() }))
}
/// What the Eyedropper picks up from an object.
struct Picked {
/// The appearance stack (type: its first run's fill and stroke as a basic appearance).
appearance: Appearance,
/// The box (in the source's paint space) its placed gradients are relative to.
bounds: Option<Rect>,
opacity: f32,
blend: BlendMode,
/// Type's first character style and its paragraph attributes.
text: Option<(CharStyle, ParaStyle)>,
}
impl Picked {
fn of(n: &Node) -> Self {
let (appearance, bounds, text) = match &n.kind {
NodeKind::Text(t) if !t.runs.is_empty() => {
let st = &t.runs[0].style;
(st.basic_appearance(), Some(t.local_bounds()), Some((st.clone(), t.para.clone())))
}
_ => (n.appearance.clone(), n.geometric_bounds(), None),
};
Self { appearance, bounds, opacity: n.opacity, blend: n.blend, text }
}
/// The appearance placed on an object whose box (in its paint space) is `to`: placed gradients
/// land at the same place relative to it.
fn placed(&self, to: Option<Rect>) -> Appearance {
let mut ap = self.appearance.clone();
if let (Some(f), Some(t)) = (self.bounds, to) {
ap.rebase_gradients(f, t);
}
ap
}
/// The paint defaults for new art take the picked-up fill, stroke and weight.
fn to_defaults(&self, s: &mut Session, a: &AppearanceAttrs) {
if a.fill.color {
s.paint.fill = super::gradient::unplaced(&self.appearance.fill_paint());
s.remember_paint(&s.paint.fill.clone());
}
if a.stroke.color {
s.paint.stroke = super::gradient::unplaced(&self.appearance.stroke_paint());
}
if a.stroke.weight && self.appearance.stroke().is_some() {
s.paint.stroke_width = self.appearance.stroke_width();
}
}
/// Apply attributes `a` to `n`. `append` adds the fills and strokes (and effects) on top of its
/// stack instead. Type takes the paints on its characters, and character and paragraph
/// attributes from type.
fn apply(&self, n: &mut Node, a: &EyedropperAttrs, append: bool) {
let ap = &a.appearance;
if ap.transparency {
n.opacity = self.opacity;
n.blend = self.blend;
}
if append {
let placed = self.placed(n.geometric_bounds());
n.appearance.items.extend(placed.items.into_iter().filter(|it| if it.is_fill() { ap.fill.color } else { ap.stroke.color }));
n.appearance.effects.extend(placed.effects);
return;
}
if let NodeKind::Text(t) = &mut n.kind {
let placed = self.placed(Some(t.local_bounds()));
let text = self.text.as_ref();
for r in &mut t.runs {
if let Some((cs, _)) = text.filter(|_| a.character) {
// The character attributes; the paints follow the appearance attributes.
let st = &mut r.style;
*st = CharStyle {
fill: std::mem::take(&mut st.fill),
stroke: std::mem::take(&mut st.stroke),
stroke_width: st.stroke_width,
overprint_fill: st.overprint_fill,
overprint_stroke: st.overprint_stroke,
..cs.clone()
};
}
run_attrs(&mut r.style, &placed, ap);
}
if let Some((_, para)) = text.filter(|_| a.paragraph) {
t.para = para.clone();
}
if text.is_some() && a.character {
super::typecmd::refresh_bounds(t);
}
return;
}
let placed = self.placed(n.geometric_bounds());
if ap.fill == FillAttrs::ALL && ap.stroke == StrokeAttrs::ALL {
n.appearance = placed;
} else {
focal_attrs(&mut n.appearance, &placed, ap);
}
}
}
/// The focal (topmost) fill and stroke attributes `a` of `from` onto `to`. Taking a colour creates
/// a missing fill or stroke.
fn focal_attrs(to: &mut Appearance, from: &Appearance, a: &AppearanceAttrs) {
if a.fill.color {
to.set_fill(from.fill_paint());
}
if let (Some(t), Some(f)) = (to.fill_mut(), from.fill()) {
if a.fill.transparency {
(t.opacity, t.blend) = (f.opacity, f.blend);
}
if a.fill.overprint {
t.overprint = f.overprint;
}
}
if a.stroke.color {
to.set_stroke(from.stroke_paint());
}
if let (Some(t), Some(k)) = (to.stroke_mut(), from.stroke()) {
let s = &a.stroke;
if s.transparency {
(t.opacity, t.blend) = (k.opacity, k.blend);
}
if s.overprint {
t.overprint = k.overprint;
}
if s.weight {
t.width = k.width;
}
if s.cap {
t.cap = k.cap;
}
if s.join {
t.join = k.join;
}
if s.miter {
t.miter_limit = k.miter_limit;
}
if s.dash {
t.dash = k.dash.clone();
}
}
}
/// The fill and stroke attributes `a` of `from` onto a type run's characters (their stroke takes
/// what characters have: paint, weight, cap, join, miter limit, dashes and overprint). Characters
/// without a painted stroke get no weight, a painted one at least 1 pt.
fn run_attrs(st: &mut CharStyle, from: &Appearance, a: &AppearanceAttrs) {
let mut ap = st.basic_appearance();
focal_attrs(&mut ap, from, a);
let (Some(f), Some(k)) = (ap.fill(), ap.stroke()) else { return };
(st.fill, st.overprint_fill, st.overprint_stroke) = (f.paint.clone(), f.overprint, k.overprint);
let width = if a.stroke.color { ap.stroke_width() } else { k.width };
st.set_stroke_layer(&StrokeLayer { width, ..k.clone() });
if !st.stroke.is_none() {
super::gradient::run_stroke_weight(st);
}
}
+185
View File
@@ -0,0 +1,185 @@
//! Window → Attributes: overprint, centre point display, image map, URL and note
//! (`attributes.set`), the fill rule (`path.setFillRule`) and, through `path.reverse`, the path
//! direction. The panel reads everything back with `attributes.info` ([`super::overprint`]).
use std::collections::BTreeSet;
use serde_json::{Value, json};
use vectorcraft_doc::{Document, ImageMap, Node, NodeKind, ObjectAttributes};
use vectorcraft_geom::FillRule;
use super::overprint::{AttributesInfo, apply_overprint, edit_counted, overprint_jobs};
use super::path::paths_in;
use super::*;
/// How many URLs the Attributes panel's recent list keeps.
const RECENT_URLS: usize = 10;
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
"attributes.set",
"Attributes",
[],
None,
"{overprintFill?: bool, overprintStroke?: bool (aimed as object.setOverprint's fill and stroke, item? too), showCenter?: bool (the canvas shows the selected object's centre point), imageMap?: \"none\"|\"rectangle\"|\"polygon\", url?: string (\"\" removes it; SVG export links the object), note?: string, ids?} set the Attributes panel's values on ids or the selection, as one undo step; a URL given joins the recent URLs (attributes.info) → {changed: objects}",
has_doc,
set
),
cmd!(
"path.setFillRule",
"Fill Rule",
[],
None,
"{rule: \"nonZero\"|\"evenOdd\", ids?} the fill rule of the paths and compound paths in ids or the selection (groups: those inside), as one undo step → {changed}",
has_doc,
set_fill_rule
),
]
}
/// A fill rule as the commands name it.
pub(super) fn rule_name(r: FillRule) -> &'static str {
match r {
FillRule::NonZero => "nonZero",
FillRule::EvenOdd => "evenOdd",
}
}
fn parse_rule(s: &str) -> Option<FillRule> {
match s.to_ascii_lowercase().replace(['-', ' ', '_'], "").as_str() {
"nonzero" | "nonzerowinding" => Some(FillRule::NonZero),
"evenodd" => Some(FillRule::EvenOdd),
_ => None,
}
}
/// The one value every item of `it` shares, if any.
fn same<T: PartialEq>(mut it: impl Iterator<Item = T>) -> Option<T> {
let first = it.next()?;
it.all(|v| v == first).then_some(first)
}
/// The paths and compound paths in `n`'s subtree that have a fill rule of their own with it (not a
/// compound path's members, which fill with its rule).
fn ruled<'a>(n: &'a Node, out: &mut Vec<(&'a Node, FillRule)>) {
match &n.kind {
NodeKind::Path { rule, guide: false, .. } | NodeKind::Compound { rule, .. } => out.push((n, *rule)),
_ => n.children().into_iter().flatten().for_each(|c| ruled(c, out)),
}
}
/// The Attributes panel's values of `info.ids` beyond overprinting.
pub(super) fn fill_info(d: &Document, info: &mut AttributesInfo) {
let nodes: Vec<&Node> = info.ids.iter().filter_map(|id| d.node(*id)).collect();
let attrs = || nodes.iter().map(|n| n.attrs.as_deref().cloned().unwrap_or_default());
info.show_center = same(nodes.iter().map(|n| n.shows_center()));
info.image_map = same(attrs().map(|a| a.image_map));
info.url = same(attrs().map(|a| a.url));
info.note = same(attrs().map(|a| a.note));
let mut all = vec![];
nodes.iter().for_each(|n| ruled(n, &mut all));
info.fill_rule = same(all.into_iter().map(|(_, r)| r));
let paths = paths_in(d, &info.ids);
let subpaths = paths.iter().filter_map(|id| d.node(*id)?.path_data()).flat_map(|p| &p.subpaths);
info.reversed = same(subpaths.map(|sp| sp.signed_area() < 0.0));
}
/// The attribute edits `p` asks for, applied to `a`.
#[derive(Default)]
struct Edits {
show_center: Option<bool>,
image_map: Option<ImageMap>,
url: Option<String>,
note: Option<String>,
}
impl Edits {
fn parse(p: &Value) -> Result<Self> {
const C: &str = "attributes.set";
let text = |k: &str| -> Result<Option<String>> {
p.get(k).map(|v| v.as_str().map(|s| s.trim().to_string()).ok_or_else(|| bad(C, format!("`{k}` must be a string")))).transpose()
};
Ok(Self {
show_center: p.get("showCenter").map(|v| v.as_bool().ok_or_else(|| bad(C, "`showCenter` must be true or false"))).transpose()?,
image_map: text("imageMap")?
.map(|s| ImageMap::parse(&s).ok_or_else(|| bad(C, "`imageMap` must be none, rectangle or polygon")))
.transpose()?,
url: text("url")?,
note: text("note")?,
})
}
fn is_empty(&self) -> bool {
self.show_center.is_none() && self.image_map.is_none() && self.url.is_none() && self.note.is_none()
}
/// `n`'s attributes with the edits applied (Show Center kept only where it isn't the default).
fn apply(&self, n: &Node) -> ObjectAttributes {
let mut a = n.attrs.as_deref().cloned().unwrap_or_default();
if let Some(v) = self.show_center {
a.show_center = (v != n.shows_center_by_default()).then_some(v);
}
if let Some(v) = self.image_map {
a.image_map = v;
}
if let Some(v) = &self.url {
a.url.clone_from(v);
}
if let Some(v) = &self.note {
a.note.clone_from(v);
}
a
}
}
fn set(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "attributes.set";
let jobs = overprint_jobs(s, p, C, ["overprintFill", "overprintStroke"])?;
let edits = Edits::parse(p)?;
if jobs.is_empty() && edits.is_empty() {
return Err(bad(C, "give overprintFill, overprintStroke, showCenter, imageMap, url or note"));
}
let ids = targets(s, p)?;
let changed = edit_counted(s, "Attributes", |d| {
let mut changed = BTreeSet::new();
apply_overprint(d, &jobs, C, &mut changed)?;
if !edits.is_empty() {
for id in &ids {
let Some(n) = d.node(*id) else { continue };
let new = edits.apply(n);
if new != n.attrs.as_deref().cloned().unwrap_or_default()
&& let Some(n) = d.node_mut(*id)
{
n.edit_attrs(|a| *a = new);
changed.insert(*id);
}
}
}
Ok(changed.len())
})?;
if let Some(url) = edits.url.filter(|u| !u.is_empty() && !ids.is_empty()) {
s.recent_urls.retain(|u| *u != url);
s.recent_urls.insert(0, url);
s.recent_urls.truncate(RECENT_URLS);
}
Ok(json!({ "changed": changed }))
}
fn set_fill_rule(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "path.setFillRule";
let rule = str_param(p, "rule").and_then(parse_rule).ok_or_else(|| bad(C, "`rule` must be nonZero or evenOdd"))?;
let ids = targets(s, p)?;
let changed = edit_counted(s, "Fill Rule", |d| {
let mut all = vec![];
ids.iter().filter_map(|id| d.node(*id)).for_each(|n| ruled(n, &mut all));
let todo: BTreeSet<_> = all.into_iter().filter(|(_, r)| *r != rule).map(|(n, _)| n.id).collect();
for id in &todo {
if let Some(NodeKind::Path { rule: r, .. } | NodeKind::Compound { rule: r, .. }) = d.node_mut(*id).map(|n| &mut n.kind) {
*r = rule;
}
}
Ok(todo.len())
})?;
Ok(json!({ "changed": changed }))
}
+7 -6
View File
@@ -248,11 +248,12 @@ fn brush_apply(s: &mut Session, p: &Value) -> Result<Value> {
if n.appearance.stroke().is_none_or(|st| st.paint.is_none()) {
n.appearance.set_stroke(stroke.clone());
}
let st = n.appearance.stroke_mut().expect("stroke");
if st.width <= 0.0 {
st.width = 1.0;
if let Some(st) = n.appearance.stroke_mut() {
if st.width <= 0.0 {
st.width = 1.0;
}
st.brush = Some(name.clone());
}
st.brush = Some(name.clone());
}
Ok(())
})?;
@@ -515,7 +516,7 @@ fn unique_symbol_name(d: &Document, base: &str) -> String {
if !taken(base) {
return base.to_string();
}
(2..).map(|i| format!("{base} {i}")).find(|n| !taken(n)).unwrap()
(2..).map(|i| format!("{base} {i}")).find(|n| !taken(n)).unwrap_or_else(|| base.to_string())
}
fn instances_of(d: &Document, name: Option<&str>) -> Vec<NodeId> {
@@ -676,7 +677,7 @@ fn symbol_edit(s: &mut Session, p: &Value) -> Result<Value> {
let first = *ids.first().ok_or_else(|| EngineError::Other("select a symbol instance".into()))?;
let name = match &s.doc()?.doc.node(first).map(|n| n.kind.clone()) {
Some(NodeKind::SymbolInstance { symbol, .. }) => symbol.clone(),
_ => unreachable!(),
_ => return Err(EngineError::Other("select a symbol instance".into())),
};
let out = s.edit("Edit Symbol", |d, sel| {
let out = break_links(d, &[first])?;
+10 -3
View File
@@ -308,7 +308,7 @@ fn sb_merge(s: &mut Session, p: &Value) -> Result<Value> {
new_nodes.push(shape_node(d, rest, Some(leaf)));
}
}
if !erase && i == style_src {
if !erase && Some(i) == style_src {
let mut m = shape_node(d, union.clone(), Some(leaf));
if let Some(f) = &fill {
m.appearance.set_fill(f.clone());
@@ -399,7 +399,7 @@ fn build_children(d: &mut Document, sources: Vec<Arc<Node>>) -> Result<(Vec<Arc<
let nfaces = regs.len();
for r in regs {
let id = d.alloc_id();
let fill = styles[r.top()].0.clone();
let fill = r.top().and_then(|t| styles.get(t)).map_or(Paint::None, |s| s.0.clone());
let mut n = Node::path(id, r.path, fill_only(fill));
n.name = Some(FACE_NAME.into());
children.push(Arc::new(n));
@@ -680,7 +680,14 @@ fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Value> {
let label = if expand { "Image Trace (Make and Expand)" } else { "Image Trace" };
let id = s.edit(label, |d, sel| {
let src = d.node(target).cloned().ok_or(EngineError::NoNode(target))?;
let mut image = if is_trace_group(&src) { (**src.children().unwrap().first().unwrap()).clone() } else { src.clone() };
let mut image = if is_trace_group(&src) {
src.children()
.and_then(|c| c.first())
.map(|c| (**c).clone())
.ok_or_else(|| EngineError::Other("Image Trace: the traced image is missing".into()))?
} else {
src.clone()
};
image.visible = true;
let mut children: Vec<Arc<Node>> = vec![];
if !expand {
+165 -43
View File
@@ -1,30 +1,56 @@
//! System clipboard interchange: the copied objects as SVG markup (what other apps paste), and
//! SVG markup from other apps turned into clipboard objects (pasted with the Paste commands).
//! The internal clipboard and system clipboard interchange.
//!
//! The UI owns the platform clipboard; these commands only convert. Within VectorCraft the
//! internal clipboard stays lossless (live effects, masks, symbols); SVG is the outside format.
//! Copy keeps the objects together with the document resources they use ([`Clipboard`]), so
//! pasting into any document brings those along (see `resources`).
//!
//! System clipboard: the copied objects as SVG markup (what other apps paste), and SVG markup from
//! other apps turned into clipboard objects (pasted with the Paste commands). The UI owns the
//! platform clipboard; these commands only convert. Within VectorCraft the internal clipboard stays
//! lossless (live effects, masks, symbols); SVG is the outside format, with PNG, PDF and plain
//! text besides it (see `flavours`).
mod flavours;
mod resources;
use std::collections::BTreeMap;
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_doc::{Document, Node, NodeId};
use vectorcraft_geom::{Affine, Point};
use vectorcraft_brush::Brush;
use vectorcraft_color::Swatch;
use vectorcraft_doc::{Document, GraphicStyle, ImageBlob, Node, NodeId, PatternDef, Symbol, TextStyleDef};
use vectorcraft_geom::Rect;
pub use flavours::{BITMAP, Flavour, PASTE_ORDER, PDF, PNG, SVG, TEXT};
pub(crate) use resources::SwatchChoices;
use super::*;
use crate::DocState;
pub fn specs() -> Vec<CommandSpec> {
vec![
let mut v = vec![
cmd!(query "clipboard.exportSvg", "Clipboard as SVG", [], None, "{} → {svg} the copied objects as standalone SVG (null when the clipboard is empty)", always, export_svg),
cmd!(
query "clipboard.importSvg",
"Load SVG into Clipboard",
[],
None,
"{svg, center?: [x, y]} replace the clipboard with the SVG's objects, centred on `center` (default: the first artboard) → {count}; then run edit.pasteInPlace",
"{svg | dataBase64 (SVG or SVGZ bytes), center?: [x, y]} replace the clipboard with the SVG's objects (and the images, patterns and symbols they use), centred on `center` (default: the first artboard) → {count}; then run edit.pasteInPlace",
has_doc,
import_svg
),
]
cmd!(
query "clipboard.conflicts",
"Swatch Conflicts",
[],
None,
"{} → {swatches: [{name, document, clipboard, spot}]} the global or spot swatches the copied objects use whose name the active document gives another colour (`document`/`clipboard`: #rrggbb): Paste asks Merge or Add for each (pass the answer as edit.paste* {swatchConflict}). Pasting back into the document the objects came from raises none",
has_doc,
conflicts
),
];
v.extend(flavours::specs());
v
}
/// Is `text` SVG markup (as other apps put on the clipboard)?
@@ -33,20 +59,118 @@ pub fn looks_like_svg(text: &str) -> bool {
(t.starts_with("<svg") || t.starts_with("<?xml") || t.starts_with("<!--") || t.starts_with("<!DOCTYPE svg")) && t.contains("<svg")
}
/// What Copy puts on the internal clipboard: the objects and every document resource they use.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Clipboard {
/// The copied objects in paint order (document coordinates).
pub nodes: Vec<Node>,
/// Blobs of the images the objects show, by key.
pub images: BTreeMap<String, ImageBlob>,
/// Symbols the objects place (also inside other symbols and patterns).
pub symbols: Vec<Symbol>,
/// Patterns the objects paint with (pasting makes their swatches again).
pub patterns: Vec<PatternDef>,
/// Global and spot swatches the objects' colours link to, the tint swatches of the tints they
/// use and the gradient swatches their gradients came from. Never the built-in [Registration]
/// swatch, which every document has.
pub swatches: Vec<Swatch>,
/// Graphic styles the objects are linked to.
pub graphic_styles: Vec<GraphicStyle>,
pub char_styles: Vec<TextStyleDef>,
pub para_styles: Vec<TextStyleDef>,
/// Brushes the objects' strokes use.
pub brushes: Vec<Brush>,
/// The artboard the objects were copied from: Paste on All Artboards keeps their offset to it.
pub source_artboard: Option<Rect>,
/// Per object: the name of the layer it was copied from (Paste Remembers Layers).
pub source_layers: Vec<Option<String>>,
/// The open document the objects came from ([`DocState::uid`]): pasting back into it uses its
/// own resources as they are now.
pub source_doc: Option<u64>,
}
impl Clipboard {
pub fn is_empty(&self) -> bool {
self.nodes.is_empty()
}
/// Objects `roots` of `st`'s document with their resources, source artboard and layers.
pub(crate) fn copy(st: &DocState, roots: &[NodeId]) -> Self {
let d = &*st.doc;
let mut nodes = vec![];
let mut source_layers = vec![];
for id in roots {
let (Some(n), Some(anc)) = (d.node(*id), d.ancestry(*id)) else { continue };
nodes.push(n.clone());
// The nearest enclosing layer (or sublayer).
source_layers.push(anc.iter().rev().skip(1).find_map(|a| d.node(*a).filter(|l| l.is_layer())).and_then(|l| l.name.clone()));
}
let bounds = nodes.iter().filter_map(Node::visual_bounds).reduce(|a, b| a.union(b));
let board = bounds.and_then(|b| d.artboard_at(b.center())).unwrap_or(0);
Self { source_artboard: d.artboards.get(board).map(|a| a.rect), source_layers, source_doc: Some(st.uid), ..Self::gather(d, nodes) }
}
/// Every object of `src` (each top-level layer's contents) with its resources, for Place and
/// pasting outside SVG. Their layers don't count for Paste Remembers Layers.
pub fn from_document(src: &Document) -> Self {
let nodes = src.layers.iter().flat_map(|l| l.children().into_iter().flatten()).map(|n| (**n).clone()).collect();
Self::gather(src, nodes)
}
/// Union of the objects' visual bounds.
pub fn bounds(&self) -> Option<Rect> {
self.nodes.iter().filter_map(Node::visual_bounds).reduce(|a, b| a.union(b))
}
/// The swatch name conflicts pasting into `st` raises, as (pasted, document) swatches: none
/// back in the document the objects came from.
pub fn swatch_conflicts<'a>(&'a self, st: &'a DocState) -> Vec<(&'a Swatch, &'a Swatch)> {
if self.source_doc == Some(st.uid) {
return vec![];
}
self.conflicts(&st.doc, &self.used())
}
/// A standalone document holding the objects and their resources (SVG export).
pub fn to_document(&self) -> Document {
let mut d = Document::new(100.0, 100.0);
d.images = self.images.clone();
d.symbols = self.symbols.clone();
d.patterns = self.patterns.clone();
d.swatches.extend(self.swatches.iter().cloned());
d.graphic_styles.extend(self.graphic_styles.iter().cloned());
d.char_styles = self.char_styles.clone();
d.para_styles = self.para_styles.clone();
if !self.brushes.is_empty() {
let mut lib = vectorcraft_brush::library(&d);
for b in &self.brushes {
match lib.iter_mut().find(|x| x.name == b.name) {
Some(x) => *x = b.clone(),
None => lib.push(b.clone()),
}
}
vectorcraft_brush::store(&mut d, &lib);
}
let mut layer = Node::layer(NodeId(u64::MAX), "Clipboard", vectorcraft_doc::LayerColor::Preset(0));
if let Some(ch) = layer.children_mut() {
*ch = self.nodes.iter().cloned().map(Arc::new).collect();
}
d.layers = vec![Arc::new(layer)];
d
}
}
impl Session {
/// The internal clipboard as standalone SVG (`None` when it is empty).
pub fn clipboard_svg(&self) -> Option<String> {
if self.clipboard.is_empty() {
return None;
}
// The active document supplies swatches, symbols, patterns and image blobs.
let mut d = self.active().map(|st| (*st.doc).clone()).unwrap_or_else(|| Document::new(100.0, 100.0));
let mut layer = Node::layer(NodeId(u64::MAX), "Clipboard", vectorcraft_doc::LayerColor::Preset(0));
if let Some(ch) = layer.children_mut() {
*ch = self.clipboard.iter().cloned().map(Arc::new).collect();
}
d.layers = vec![Arc::new(layer)];
Some(vectorcraft_svg::export(&d, &vectorcraft_svg::ExportOptions { artboard: None, object_ids: false, ..Default::default() }))
let d = self.clipboard.to_document();
Some(vectorcraft_svg::export(
&d,
&vectorcraft_svg::ExportOptions { artboard: None, object_ids: vectorcraft_svg::ObjectIds::Minimal, ..Default::default() },
))
}
}
@@ -55,34 +179,32 @@ fn export_svg(s: &mut Session, _: &Value) -> Result<Value> {
}
fn import_svg(s: &mut Session, p: &Value) -> Result<Value> {
let svg = str_param(p, "svg").ok_or_else(|| bad("clipboard.importSvg", "missing svg"))?;
let src = vectorcraft_svg::import(svg).map_err(|e| bad("clipboard.importSvg", e.to_string()))?;
let mut nodes: Vec<Node> = src.layers.iter().flat_map(|l| l.children().cloned().unwrap_or_default()).map(|n| (*n).clone()).collect();
if nodes.is_empty() {
return Err(bad("clipboard.importSvg", "the SVG has no drawable objects"));
}
let center = match p.get("center").and_then(Value::as_array) {
Some(c) if c.len() == 2 => Point::new(c[0].as_f64().unwrap_or(0.0), c[1].as_f64().unwrap_or(0.0)),
_ => s.doc()?.doc.artboards.first().map(|a| a.rect.center()).unwrap_or_default(),
const C: &str = "clipboard.importSvg";
let svg = match (str_param(p, "svg"), str_param(p, "dataBase64")) {
(Some(svg), _) => std::borrow::Cow::Borrowed(svg),
(None, Some(b64)) => {
let bytes = vectorcraft_format::base64_decode(b64).ok_or_else(|| bad(C, "bad base64"))?;
vectorcraft_svg::text_of(&bytes).map_err(|e| bad(C, e.to_string()))?.into_owned().into()
}
(None, None) => return Err(bad(C, "give svg, or dataBase64 of an SVG or SVGZ file")),
};
let bounds = nodes.iter().filter_map(|n| n.visual_bounds()).reduce(|a, b| a.union(b));
if let Some(b) = bounds {
let xf = Affine::translate(center - b.center());
for n in &mut nodes {
n.transform(xf, false);
}
let (src, _) = super::fileio::import_svg(&svg, None).map_err(|e| bad(C, e.to_string()))?;
let clip = Clipboard::from_document(&src);
if clip.is_empty() {
return Err(bad(C, "the SVG has no drawable objects"));
}
// Embedded images: their blobs join the document (keys are content hashes).
if !src.images.is_empty() {
let st = s.doc_mut()?;
let d = Arc::make_mut(&mut st.doc);
for (k, b) in &src.images {
d.images.entry(k.clone()).or_insert_with(|| b.clone());
}
}
let count = nodes.len();
s.clipboard = nodes;
Ok(json!({ "count": count }))
Ok(json!({ "count": s.load_clipboard(clip, p)? }))
}
fn conflicts(s: &mut Session, _: &Value) -> Result<Value> {
let hex = |w: &Swatch| w.paint.color().map(|c| c.to_hex());
let list: Vec<Value> = s
.clipboard
.swatch_conflicts(s.doc()?)
.into_iter()
.map(|(c, t)| json!({"name": c.name, "document": hex(t), "clipboard": hex(c), "spot": c.spot}))
.collect();
Ok(json!({ "swatches": list }))
}
#[cfg(test)]
+296
View File
@@ -0,0 +1,296 @@
//! Clipboard flavours: what Copy offers other apps besides SVG (PNG, PDF and plain text) and what
//! Paste takes from them (bitmaps, plain text and PDF).
//!
//! The UI owns the platform clipboard (`Services::system_clipboard` in the egui frontend): on Copy
//! it publishes [`Session::clipboard_flavours`]; before a Paste it turns what another app put on
//! the system clipboard into the internal clipboard with the `clipboard.import*` commands. These
//! commands only convert, so agents can drive them headless.
use serde_json::{Value, json};
use vectorcraft_doc::{Document, ImageObject, Node, NodeId, NodeKind, TextObject};
use vectorcraft_geom::{Affine, Point};
use super::super::fileio;
use super::super::place::pt_per_px;
use super::*;
/// Plain text: a type-only copy's text, else the SVG markup (Include SVG Code).
pub const TEXT: &str = "text/plain";
/// SVG markup (Include SVG Code).
pub const SVG: &str = "image/svg+xml";
/// A PDF of the copied objects (On Copy: PDF).
pub const PDF: &str = "application/pdf";
/// A PNG of the copied objects (always offered).
pub const PNG: &str = "image/png";
/// Any bitmap (PNG, BMP…), in what Paste asks the system clipboard for.
pub const BITMAP: &str = "image/*";
/// What Paste reads from other apps, best first: vector art before text, text before bitmaps
/// (word processors offer a picture of copied text too).
pub const PASTE_ORDER: [&str; 4] = [SVG, PDF, TEXT, BITMAP];
/// One representation of the clipboard's contents.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Flavour {
pub mime: &'static str,
pub data: Vec<u8>,
}
/// Longest side (px) of the PNG Copy offers: larger art is scaled down to fit.
const COPY_PNG_SIDE: f64 = 4096.0;
/// Most bytes of text `clipboard.importText` takes.
const MAX_TEXT: usize = 1 << 20;
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
query "clipboard.exportPng",
"Clipboard as PNG",
[],
None,
"{scale?: 1 (pixels per point, up to 64)} → {dataBase64, width, height (px)} the copied objects cropped to their visual bounds, transparent around them (dataBase64 null when the clipboard is empty)",
always,
export_png
),
cmd!(
query "clipboard.exportPdf",
"Clipboard as PDF",
[],
None,
"{} → {dataBase64} a one-page PDF of the copied objects, the page their visual bounds (null when the clipboard is empty)",
always,
export_pdf
),
cmd!(
query "clipboard.exportText",
"Clipboard as Text",
[],
None,
"{} → {text} the copied type objects' text, one object per line (null unless every copied object is type, or a group of type)",
always,
export_text
),
cmd!(
query "clipboard.flavours",
"Clipboard Formats",
[],
None,
"{} → {flavours: [mime…]} what Copy offers other apps for the current clipboard, best first, by the Clipboard Handling preferences: text/plain (a type-only copy's text, else the SVG markup with copyAsSvg), image/svg+xml (copyAsSvg), application/pdf (copyAsPdf), image/png (always; PDF and PNG only for objects with an area); the app publishes them on Copy and Cut",
always,
flavours
),
cmd!(
query "clipboard.importImage",
"Load Image into Clipboard",
[],
None,
"{dataBase64 (PNG, JPEG, GIF, WebP, TIFF or BMP bytes), mime?: the type the system clipboard gave (an image/… type; the format is read from the bytes), center?: [x, y]} replace the clipboard with the image, embedded at 100% of its physical size (its resolution, else 72 ppi), centred on `center` (default: the first artboard) → {count, width, height (pt), pixelWidth, pixelHeight}; then run edit.paste",
has_doc,
import_image
),
cmd!(
query "clipboard.importText",
"Load Text into Clipboard",
[],
None,
"{text, center?: [x, y]} replace the clipboard with point text of `text` (one paragraph per line; trailing line breaks dropped) in the default type style, centred on `center` (default: the first artboard) → {count}; then run edit.paste",
has_doc,
import_text
),
cmd!(
query "clipboard.importPdf",
"Load PDF into Clipboard",
[],
None,
"{dataBase64, page?: 1, password? (an encrypted PDF), center?: [x, y]} replace the clipboard with the objects of one PDF page (with the images, patterns and swatches they use), centred on `center` (default: the first artboard) → {count, warnings}; then run edit.paste",
has_doc,
import_pdf
),
]
}
/// Is every object type (or a group of type only)?
fn type_only(n: &Node) -> bool {
match &n.kind {
NodeKind::Text(_) => true,
NodeKind::Group { children, .. } => !children.is_empty() && children.iter().all(|c| type_only(c)),
_ => false,
}
}
impl Session {
/// The copied type objects' text, one object per line (`None` unless the clipboard holds type
/// only).
pub fn clipboard_text(&self) -> Option<String> {
let nodes = &self.clipboard.nodes;
if nodes.is_empty() || !nodes.iter().all(type_only) {
return None;
}
let mut lines = vec![];
for n in nodes {
n.walk(&mut |c| {
if let NodeKind::Text(t) = &c.kind {
lines.push(t.plain_text());
}
});
}
Some(lines.join("\n"))
}
/// The clipboard as a document whose one artboard is the objects' visual bounds (`None` when
/// it is empty or has no extent).
fn clipboard_cropped(&self) -> Option<(Document, vectorcraft_geom::Rect)> {
let b = self.clipboard.bounds().filter(|b| b.width() > 0.0 && b.height() > 0.0)?;
Some((fileio::with_single_artboard(self.clipboard.to_document(), b, "Clipboard"), b))
}
/// A PNG of the copied objects at `scale` pixels per point → (bytes, width, height); `None`
/// when the clipboard is empty.
pub fn clipboard_png(&self, scale: f64) -> Result<Option<(Vec<u8>, u32, u32)>> {
const C: &str = "clipboard.exportPng";
let Some((doc, b)) = self.clipboard_cropped() else { return Ok(None) };
let (w, h) = vectorcraft_render::raster_size(b, scale).map_err(|e| bad(C, e))?;
let png = fileio::encode(&doc, "png", &json!({ "scale": scale, "background": "transparent" }))?;
Ok(Some((png, w, h)))
}
/// A one-page PDF of the copied objects (without the native document inside); `None` when the
/// clipboard is empty.
pub fn clipboard_pdf(&self) -> Result<Option<Vec<u8>>> {
let Some((doc, _)) = self.clipboard_cropped() else { return Ok(None) };
fileio::encode(&doc, "pdf", &json!({ "preserveEditing": false })).map(Some)
}
/// The MIME types of [`Self::clipboard_flavours`], without making them.
pub fn clipboard_flavour_types(&self) -> Vec<&'static str> {
if self.clipboard.is_empty() {
return vec![];
}
let (svg, pdf) = (self.prefs.copy_as_svg, self.prefs.copy_as_pdf);
let text = svg || self.clipboard.nodes.iter().all(type_only);
// Art without an area (a lone guide-like line) has no page or picture.
let area = self.clipboard.bounds().is_some_and(|b| b.width() > 0.0 && b.height() > 0.0);
[(TEXT, text), (SVG, svg), (PDF, pdf && area), (PNG, area)].into_iter().filter_map(|(m, on)| on.then_some(m)).collect()
}
/// What Copy offers other apps, best first (see `clipboard.flavours`). A flavour that can't be
/// made (art too large to render) is left out; the PNG is scaled down to at most
/// [`COPY_PNG_SIDE`] pixels a side.
pub fn clipboard_flavours(&self) -> Vec<Flavour> {
let types = self.clipboard_flavour_types();
let svg = types.contains(&SVG).then(|| self.clipboard_svg()).flatten();
let mut out = vec![];
for mime in types {
let data = match mime {
TEXT => self.clipboard_text().or_else(|| svg.clone()).map(String::into_bytes),
SVG => svg.clone().map(String::into_bytes),
PDF => self.clipboard_pdf().inspect_err(|e| log::warn!("clipboard PDF: {e}")).ok().flatten(),
_ => {
let side = self.clipboard.bounds().map_or(1.0, |b| b.width().max(b.height()));
let scale = (COPY_PNG_SIDE / side).clamp(0.01, 1.0);
self.clipboard_png(scale).inspect_err(|e| log::warn!("clipboard PNG: {e}")).ok().flatten().map(|(png, ..)| png)
}
};
out.extend(data.map(|data| Flavour { mime, data }));
}
out
}
/// Replace the clipboard with `clip`, centred on `p`'s `center` (default: the first
/// artboard's centre) → the number of objects.
pub(super) fn load_clipboard(&mut self, mut clip: Clipboard, p: &Value) -> Result<usize> {
let center = match point_param(p, "center") {
Some(c) => c,
None => self.doc()?.doc.artboards.first().map(|a| a.rect.center()).unwrap_or_default(),
};
if let Some(b) = clip.bounds() {
let xf = Affine::translate(center - b.center());
for n in &mut clip.nodes {
n.transform(xf, false);
}
}
let count = clip.nodes.len();
self.clipboard = clip;
Ok(count)
}
}
/// The bytes of `p`'s `dataBase64`.
fn data_param(p: &Value, cmd: &str) -> Result<Vec<u8>> {
let b64 = str_param(p, "dataBase64").ok_or_else(|| bad(cmd, "give dataBase64"))?;
vectorcraft_format::base64_decode(b64).ok_or_else(|| bad(cmd, "bad base64"))
}
fn export_png(s: &mut Session, p: &Value) -> Result<Value> {
let scale = f64_or(p, "scale", 1.0);
if !(scale > 0.0 && scale <= 64.0) {
return Err(bad("clipboard.exportPng", "scale must be a number above 0, at most 64"));
}
Ok(match s.clipboard_png(scale)? {
Some((png, w, h)) => json!({ "dataBase64": vectorcraft_format::base64_encode(&png), "width": w, "height": h }),
None => json!({ "dataBase64": null }),
})
}
fn export_pdf(s: &mut Session, _: &Value) -> Result<Value> {
Ok(json!({ "dataBase64": s.clipboard_pdf()?.map(|b| vectorcraft_format::base64_encode(&b)) }))
}
fn export_text(s: &mut Session, _: &Value) -> Result<Value> {
Ok(json!({ "text": s.clipboard_text() }))
}
fn flavours(s: &mut Session, _: &Value) -> Result<Value> {
Ok(json!({ "flavours": s.clipboard_flavour_types() }))
}
fn import_image(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "clipboard.importImage";
if let Some(m) = str_param(p, "mime").filter(|m| !m.starts_with("image/") || *m == SVG) {
return Err(bad(C, format!("`{m}` isn't a bitmap: use clipboard.importSvg, importPdf or importText")));
}
let img = fileio::raster_image(&data_param(p, C)?).map_err(|e| bad(C, e.to_string()))?;
let (sx, sy) = pt_per_px(img.ppi);
let (w, h) = (img.width, img.height);
let image =
ImageObject { key: img.key.clone(), width: w, height: h, xf: Affine::scale_non_uniform(sx, sy), link: None, placement: Default::default() };
let mut clip = Clipboard { nodes: vec![Node::new(NodeId(1), NodeKind::Image(image))], ..Default::default() };
clip.images.insert(img.key, img.blob);
let count = s.load_clipboard(clip, p)?;
Ok(json!({ "count": count, "width": w as f64 * sx, "height": h as f64 * sy, "pixelWidth": w, "pixelHeight": h }))
}
fn import_text(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "clipboard.importText";
let raw = str_param(p, "text").ok_or_else(|| bad(C, "give text"))?;
if raw.len() > MAX_TEXT {
return Err(bad(C, format!("the text is over {} MB", MAX_TEXT >> 20)));
}
let text = raw.replace("\r\n", "\n").replace('\r', "\n");
let text = text.trim_end_matches('\n');
if text.trim().is_empty() {
return Err(bad(C, "the text is empty"));
}
let mut t = TextObject::point(Point::ZERO, text, super::super::create::new_type_style(s, &Value::Null));
t.cached_bounds = Some(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).bounds);
let n = Node::new(NodeId(1), NodeKind::Text(Box::new(t)));
let count = s.load_clipboard(Clipboard { nodes: vec![n], ..Default::default() }, p)?;
Ok(json!({ "count": count }))
}
fn import_pdf(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "clipboard.importPdf";
let bytes = data_param(p, C)?;
let page = match p.get("page") {
None | Some(Value::Null) => 1,
Some(v) => v.as_u64().filter(|n| (1..=100_000).contains(n)).ok_or_else(|| bad(C, "page must be a whole number from 1"))? as usize,
};
let opts = fileio::LoadOptions { password: str_param(p, "password").map(str::to_string), ..Default::default() };
let (mut doc, warnings) = fileio::page_document(&bytes, page - 1, &opts).map_err(|e| bad(C, e.to_string()))?;
doc.drop_edit_modes();
let clip = Clipboard::from_document(&doc);
if clip.is_empty() {
return Err(bad(C, format!("page {page} of the PDF has no objects")));
}
let count = s.load_clipboard(clip, p)?;
Ok(json!({ "count": count, "warnings": warnings }))
}
@@ -0,0 +1,691 @@
//! The document resources copied objects use, and adding them to the document they're pasted into.
//!
//! Objects refer to resources by name (image blobs, symbols, patterns, swatches, character and
//! paragraph styles, brushes) and to graphic styles by id. Copy follows those references, also
//! through the symbols, patterns and styles it finds, and keeps what they lead to.
//!
//! Pasting matches each resource by name: an identical one in the document is used, a missing one
//! is added, and a different one of the same name is added under a free name, which the pasted
//! objects follow. Global and spot swatches are the exception: for a name the document gives
//! another colour the caller picks Merge (the objects take the document's swatch) or Add (the
//! pasted swatch comes in renamed), the Swatch Conflict dialog's question. Colours linked to a
//! swatch then show it as the document does: its colour at their tint, and a Lab spot colour as
//! the document's Spot Colors option says. Pasting back into the document the objects came from
//! uses its resources as they are now.
use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
use serde_json::{Map, Value, json};
use vectorcraft_brush::Brush;
use vectorcraft_color::{Color, Paint, Swatch};
use vectorcraft_doc::{Appearance, AppearanceItem, Document, GraphicStyle, Node, NodeKind, PatternDef, Symbol, TextStyleDef};
use super::super::patterncmds::add_pattern;
use super::super::{Result, bad, unique_name};
use super::Clipboard;
/// A resource kind objects refer to (graphic styles by id, the others by name).
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
enum Res {
Image,
Symbol,
Pattern,
Swatch,
CharStyle,
ParaStyle,
Brush,
GraphicStyle,
}
impl Res {
fn id(self) -> &'static str {
match self {
Res::Image => "image",
Res::Symbol => "symbol",
Res::Pattern => "pattern",
Res::Swatch => "swatch",
Res::CharStyle => "charStyle",
Res::ParaStyle => "paraStyle",
Res::Brush => "brush",
Res::GraphicStyle => "graphicStyle",
}
}
}
/// A reference from art to a resource.
enum Ref<'a> {
Name(Res, &'a str),
/// A colour linked to a swatch, at a tint.
Swatch(&'a str, f32),
/// A link to the graphic style with this id.
Style(u32),
}
type Visit<'v> = &'v mut dyn FnMut(Ref<'_>);
fn paint_refs(p: &Paint, f: Visit) {
match p {
Paint::Solid { swatch: Some(s), tint, .. } => f(Ref::Swatch(s, *tint)),
Paint::Gradient(g) => {
// The gradient swatch it was applied from, and its stops' links.
if let Some(s) = &g.swatch {
f(Ref::Name(Res::Swatch, s));
}
g.gradient.stops.iter().filter_map(|st| Some((st.swatch.as_deref()?, st.tint))).for_each(|(s, t)| f(Ref::Swatch(s, t)));
}
Paint::Pattern { pattern, .. } => f(Ref::Name(Res::Pattern, pattern)),
_ => {}
}
}
fn appearance_refs(a: &Appearance, f: Visit) {
for it in &a.items {
paint_refs(it.paint(), f);
if let AppearanceItem::Stroke(l) = it
&& let Some(b) = &l.brush
{
f(Ref::Name(Res::Brush, b));
}
}
}
/// The paints a character or paragraph style can set (by their serialized names).
const STYLE_PAINTS: [&str; 2] = ["fill", "stroke"];
fn style_paint(attrs: &Map<String, Value>, key: &str) -> Option<Paint> {
serde_json::from_value(attrs.get(key)?.clone()).ok()
}
fn attrs_refs(attrs: &Map<String, Value>, f: Visit) {
for p in STYLE_PAINTS.iter().filter_map(|k| style_paint(attrs, k)) {
paint_refs(&p, f);
}
}
/// Every reference in the subtree of `n` (opacity-mask art included).
fn node_refs(n: &Node, f: Visit) {
n.walk(&mut |m| {
appearance_refs(&m.appearance, f);
if let Some(id) = m.graphic_style {
f(Ref::Style(id));
}
if let Some(mask) = &m.mask {
node_refs(&mask.art, f);
}
match &m.kind {
NodeKind::Text(t) => {
for r in &t.runs {
paint_refs(&r.style.fill, f);
paint_refs(&r.style.stroke, f);
if let Some(s) = &r.style.style_name {
f(Ref::Name(Res::CharStyle, s));
}
}
if let Some(s) = &t.para.style_name {
f(Ref::Name(Res::ParaStyle, s));
}
}
NodeKind::Image(im) => f(Ref::Name(Res::Image, &im.key)),
NodeKind::SymbolInstance { symbol, .. } => f(Ref::Name(Res::Symbol, symbol)),
_ => {}
}
});
}
/// A global or spot colour of its own (not a tint of another swatch): what colours link to.
fn is_base(w: &Swatch) -> bool {
(w.global || w.spot) && matches!(w.paint, Paint::Solid { swatch: None, .. })
}
/// The definitions references lead to: a document's, or the clipboard's own.
struct Defs<'a> {
swatches: Vec<&'a Swatch>,
symbols: &'a [Symbol],
patterns: &'a [PatternDef],
styles: &'a [GraphicStyle],
char_styles: &'a [TextStyleDef],
para_styles: &'a [TextStyleDef],
}
impl<'a> Defs<'a> {
fn of(d: &'a Document) -> Self {
Self {
swatches: d.swatches_iter().collect(),
symbols: &d.symbols,
patterns: &d.patterns,
styles: &d.graphic_styles,
char_styles: &d.char_styles,
para_styles: &d.para_styles,
}
}
}
/// What references lead out of.
enum Source<'a> {
Node(&'a Node),
Appearance(&'a Appearance),
Attrs(&'a Map<String, Value>),
Paint(&'a Paint),
}
/// The resources a set of objects uses, through the definitions they lead to.
#[derive(Default)]
pub(super) struct Used {
names: BTreeMap<Res, BTreeSet<String>>,
/// The tints (below 100 %) of the swatches used: (swatch, tint).
tints: Vec<(String, f32)>,
styles: BTreeSet<u32>,
}
impl Used {
fn of<'a>(defs: &Defs<'a>, nodes: &'a [Node]) -> Self {
let mut used = Used::default();
let mut todo: Vec<Source<'a>> = nodes.iter().map(Source::Node).collect();
while let Some(src) = todo.pop() {
let mut found = |r: Ref<'_>| used.note(defs, r, &mut todo);
match src {
Source::Node(n) => node_refs(n, &mut found),
Source::Appearance(a) => appearance_refs(a, &mut found),
Source::Attrs(a) => attrs_refs(a, &mut found),
Source::Paint(p) => paint_refs(p, &mut found),
}
}
used
}
/// Note `r`; a definition seen for the first time joins `todo`.
fn note<'a>(&mut self, defs: &Defs<'a>, r: Ref<'_>, todo: &mut Vec<Source<'a>>) {
let (res, name) = match r {
Ref::Style(id) => {
if self.styles.insert(id) {
todo.extend(defs.styles.iter().filter(|g| g.id != 0 && g.id == id).map(|g| Source::Appearance(&g.appearance)));
}
return;
}
Ref::Swatch(name, tint) => {
if tint < 1.0 && !self.has_tint(name, tint) {
self.tints.push((name.to_string(), tint));
}
(Res::Swatch, name)
}
Ref::Name(res, name) => (res, name),
};
let set = self.names.entry(res).or_default();
if set.contains(name) {
return;
}
set.insert(name.to_string());
match res {
// A tint swatch's base, a gradient swatch's linked stops.
Res::Swatch => todo.extend(defs.swatches.iter().filter(|w| w.name == name).map(|w| Source::Paint(&w.paint))),
Res::Symbol => todo.extend(defs.symbols.iter().filter(|s| s.name == name).map(|s| Source::Node(&s.art))),
Res::Pattern => todo.extend(defs.patterns.iter().filter(|p| p.name == name).flat_map(|p| p.art.iter().map(|a| Source::Node(a)))),
Res::CharStyle => todo.extend(defs.char_styles.iter().filter(|s| s.name == name).map(|s| Source::Attrs(&s.attrs))),
Res::ParaStyle => todo.extend(defs.para_styles.iter().filter(|s| s.name == name).map(|s| Source::Attrs(&s.attrs))),
_ => {}
}
}
fn has(&self, r: Res, name: &str) -> bool {
self.names.get(&r).is_some_and(|s| s.contains(name))
}
fn has_tint(&self, name: &str, tint: f32) -> bool {
self.tints.iter().any(|(n, t)| n == name && *t == tint)
}
/// Does the clipboard carry swatch `w`: a used global or spot colour or gradient swatch, or a
/// tint swatch of a tint used? (Never the built-in Registration swatch.)
fn carries(&self, w: &Swatch) -> bool {
let named = is_base(w) || matches!(w.paint, Paint::Gradient(_));
!w.is_reserved() && (named && self.has(Res::Swatch, &w.name) || w.tint_of().is_some_and(|(b, t)| self.has_tint(b, t)))
}
}
/// A resource list entry known by its name.
trait Named: Clone {
fn name(&self) -> &str;
fn set_name(&mut self, name: String);
}
macro_rules! named {
($($t:ty),+) => {$(
impl Named for $t {
fn name(&self) -> &str {
&self.name
}
fn set_name(&mut self, name: String) {
self.name = name;
}
}
)+};
}
named!(Symbol, TextStyleDef, Brush);
/// Where a pasted resource ended up in the document.
enum Placed {
/// The document's own of that name is used.
Existing,
/// The document's own numbered copy ("Name 2", from an earlier paste) is used.
Reused(String),
Added,
/// Added under a free name.
Renamed(String),
}
impl Placed {
/// Added as `name`, which `from` was free or not.
fn added(from: &str, name: String) -> Self {
if name == from { Placed::Added } else { Placed::Renamed(name) }
}
/// The name of the definition the paste added (`None` when the document's own is used).
fn new_name(&self, from: &str) -> Option<String> {
match self {
Placed::Existing | Placed::Reused(_) => None,
Placed::Added => Some(from.to_string()),
Placed::Renamed(n) => Some(n.clone()),
}
}
}
/// Is `name` `base` or a numbered copy of it ("base 2")?
fn copy_of(base: &str, name: &str) -> bool {
name == base || name.strip_prefix(base).and_then(|r| r.strip_prefix(' ')).is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))
}
/// The document's own resource for pasted resource `name`, among the document's `names`: the
/// one of that name when `same` holds for it (or, pasting back into the source document, at all),
/// else a numbered copy of it (added by an earlier paste) that is the same. `None`: add it.
fn existing<'a>(name: &str, names: impl IntoIterator<Item = &'a str>, same_doc: bool, same: impl Fn(&str) -> bool) -> Option<Placed> {
let mut found: Vec<&str> = names.into_iter().filter(|n| copy_of(name, n)).collect();
// The name itself first.
found.sort_by_key(|n| *n != name);
if same_doc && found.first() == Some(&name) {
return Some(Placed::Existing);
}
found.into_iter().find(|n| same(n)).map(|n| if n == name { Placed::Existing } else { Placed::Reused(n.to_string()) })
}
/// Find `item` in `list` ([`existing`], `same` comparing it under the entry's name) or add it
/// under a free name.
fn place<T: Named>(list: &mut Vec<T>, item: &T, same_doc: bool, same: impl Fn(&T, &T) -> bool) -> Placed {
let same_as = |n: &str| {
let mut c = item.clone();
c.set_name(n.to_string());
list.iter().find(|x| x.name() == n).is_some_and(|x| same(x, &c))
};
if let Some(p) = existing(item.name(), list.iter().map(Named::name), same_doc, same_as) {
return p;
}
let name = unique_name(item.name(), |n| list.iter().any(|x| x.name() == n));
let mut c = item.clone();
c.set_name(name.clone());
list.push(c);
Placed::added(item.name(), name)
}
/// Merge or Add, for a swatch whose name the document gives another colour.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum SwatchChoice {
#[default]
Merge,
Add,
}
/// The `swatchConflict` parameter: one choice for every conflict, or one per swatch name (the
/// others merge).
#[derive(Clone, Debug, Default)]
pub(crate) struct SwatchChoices {
all: SwatchChoice,
by_name: BTreeMap<String, SwatchChoice>,
}
impl SwatchChoices {
pub(crate) fn parse(cmd: &str, p: &Value) -> Result<Self> {
let one = |v: &Value| match v.as_str() {
Some("merge") => Ok(SwatchChoice::Merge),
Some("add") => Ok(SwatchChoice::Add),
_ => Err(bad(cmd, format!("swatchConflict must be \"merge\" or \"add\", not {v}"))),
};
match p.get("swatchConflict") {
None | Some(Value::Null) => Ok(Self::default()),
Some(Value::Object(m)) => {
Ok(Self { all: SwatchChoice::Merge, by_name: m.iter().map(|(k, v)| Ok((k.clone(), one(v)?))).collect::<Result<_>>()? })
}
Some(v) => Ok(Self { all: one(v)?, by_name: BTreeMap::new() }),
}
}
fn of(&self, name: &str) -> SwatchChoice {
self.by_name.get(name).copied().unwrap_or(self.all)
}
}
/// How pasted art is relinked to the document's resources.
#[derive(Debug, Default)]
struct Relink {
renames: BTreeMap<Res, BTreeMap<String, String>>,
/// Graphic style id on the clipboard → its id in the document. Links to other ids are dropped.
styles: BTreeMap<u32, u32>,
/// Swatch (its name in the document) → the colour linked colours show at 100 %.
colors: BTreeMap<String, Color>,
}
impl Relink {
fn name(&self, r: Res, s: &mut String) {
if let Some(n) = self.renames.get(&r).and_then(|m| m.get(s.as_str())) {
*s = n.clone();
}
}
/// `name` as the document knows it.
fn renamed(&self, r: Res, name: &str) -> String {
let mut n = name.to_string();
self.name(r, &mut n);
n
}
fn paint(&self, p: &mut Paint) {
match p {
Paint::Pattern { pattern, .. } => self.name(Res::Pattern, pattern),
Paint::Gradient(g) => {
if let Some(s) = &mut g.swatch {
self.name(Res::Swatch, s);
}
}
_ => {}
}
p.map_links(&mut |c, link, tint| {
if let Some(l) = link {
self.name(Res::Swatch, l);
if let Some(base) = self.colors.get(l.as_str()) {
*c = base.tinted(*tint);
}
}
false
});
}
fn appearance(&self, a: &mut Appearance) {
for it in &mut a.items {
self.paint(it.paint_mut());
if let AppearanceItem::Stroke(l) = it
&& let Some(b) = &mut l.brush
{
self.name(Res::Brush, b);
}
}
}
fn attrs(&self, a: &mut Map<String, Value>) {
for k in STYLE_PAINTS {
let Some(before) = style_paint(a, k) else { continue };
let mut p = before.clone();
self.paint(&mut p);
if p != before
&& let Ok(v) = serde_json::to_value(&p)
{
a.insert(k.to_string(), v);
}
}
}
/// Relink a node tree (the mirror of [`node_refs`]).
fn node(&self, n: &mut Node) {
self.appearance(&mut n.appearance);
n.graphic_style = n.graphic_style.and_then(|id| self.styles.get(&id).copied());
if let Some(m) = &mut n.mask {
self.node(Arc::make_mut(&mut m.art));
}
match &mut n.kind {
NodeKind::Text(t) => {
for r in &mut t.runs {
self.paint(&mut r.style.fill);
self.paint(&mut r.style.stroke);
if let Some(s) = &mut r.style.style_name {
self.name(Res::CharStyle, s);
}
}
if let Some(s) = &mut t.para.style_name {
self.name(Res::ParaStyle, s);
}
}
NodeKind::Image(im) => self.name(Res::Image, &mut im.key),
NodeKind::SymbolInstance { symbol, .. } => self.name(Res::Symbol, symbol),
_ => {}
}
for c in n.children_mut().into_iter().flatten() {
self.node(Arc::make_mut(c));
}
}
}
/// Is `ours` (a document definition's art) the art of `theirs` (a pasted one's) once that is
/// relinked by `r`? Graphic style links don't count: they are relinked last.
fn same_art(r: &Relink, ours: &[Arc<Node>], theirs: &[Arc<Node>]) -> bool {
let unlinked = Relink::default();
let relinked = |r: &Relink, n: &Node| {
let mut n = n.clone();
r.node(&mut n);
n
};
ours.len() == theirs.len() && ours.iter().zip(theirs).all(|(a, b)| relinked(&unlinked, a) == relinked(r, b))
}
/// What pasting did to the document's resources (part of the paste result).
#[derive(Debug, Default)]
pub(crate) struct Imported {
relink: Relink,
/// Resources added to the document (renamed ones included).
pub added: usize,
/// Swatch conflicts resolved by merging.
pub merged: usize,
/// `{kind, from, to}` for every resource the pasted objects now know under another name: added
/// renamed, or a copy added renamed by an earlier paste.
pub renamed: Vec<Value>,
}
impl Imported {
fn placed(&mut self, r: Res, from: &str, p: &Placed) {
if matches!(p, Placed::Added | Placed::Renamed(_)) {
self.added += 1;
}
if let Placed::Reused(to) | Placed::Renamed(to) = p {
self.renamed.push(json!({"kind": r.id(), "from": from, "to": to}));
self.relink.renames.entry(r).or_default().insert(from.to_string(), to.clone());
}
}
/// Point a pasted copy at the document's resources.
pub(crate) fn apply(&self, n: &mut Node) {
self.relink.node(n);
}
}
impl Clipboard {
/// `nodes` (from `src`) and the resources of `src` they use.
pub(super) fn gather(src: &Document, nodes: Vec<Node>) -> Self {
let used = Used::of(&Defs::of(src), &nodes);
let pick = |r: Res, list: &[TextStyleDef]| list.iter().filter(|s| used.has(r, &s.name)).cloned().collect::<Vec<_>>();
let brushes = match used.names.get(&Res::Brush) {
Some(names) => vectorcraft_brush::library(src).into_iter().filter(|b| names.contains(&b.name)).collect(),
None => vec![],
};
Self {
images: src.images.iter().filter(|(k, _)| used.has(Res::Image, k)).map(|(k, b)| (k.clone(), b.clone())).collect(),
symbols: src.symbols.iter().filter(|s| used.has(Res::Symbol, &s.name)).cloned().collect(),
patterns: src.patterns.iter().filter(|p| used.has(Res::Pattern, &p.name)).cloned().collect(),
swatches: src.swatches_iter().filter(|w| used.carries(w)).cloned().collect(),
graphic_styles: src.graphic_styles.iter().filter(|g| g.id != 0 && used.styles.contains(&g.id)).cloned().collect(),
char_styles: pick(Res::CharStyle, &src.char_styles),
para_styles: pick(Res::ParaStyle, &src.para_styles),
brushes,
nodes,
..Default::default()
}
}
/// The resources the objects use now (Paste without Formatting leaves text styles behind).
pub(super) fn used(&self) -> Used {
let defs = Defs {
swatches: self.swatches.iter().collect(),
symbols: &self.symbols,
patterns: &self.patterns,
styles: &self.graphic_styles,
char_styles: &self.char_styles,
para_styles: &self.para_styles,
};
Used::of(&defs, &self.nodes)
}
/// The used global and spot colours whose name `d` gives another one: (pasted, document).
pub(super) fn conflicts<'a, 'd>(&'a self, d: &'d Document, used: &Used) -> Vec<(&'a Swatch, &'d Swatch)> {
self.swatches
.iter()
.filter(|w| is_base(w) && used.has(Res::Swatch, &w.name))
.filter_map(|w| d.swatch(&w.name).filter(|t| is_base(t) && (t.paint != w.paint || t.spot != w.spot)).map(|t| (w, t)))
.collect()
}
/// Add the resources the objects use to `d` (inside the paste's undo step) and work out how
/// pasted copies relink to them.
pub(crate) fn import_into(&self, d: &mut Document, choices: &SwatchChoices, same_doc: bool) -> Imported {
let used = self.used();
let mut out = Imported::default();
self.import_images(d, &used, same_doc, &mut out);
self.import_brushes(d, &used, same_doc, &mut out);
self.import_swatches(d, &used, choices, same_doc, &mut out);
// Character and paragraph styles (their colours relinked first).
for (r, mine, theirs) in [(Res::CharStyle, &self.char_styles, &mut d.char_styles), (Res::ParaStyle, &self.para_styles, &mut d.para_styles)] {
for def in mine.iter().filter(|s| used.has(r, &s.name)) {
let mut s = def.clone();
out.relink.attrs(&mut s.attrs);
let p = place(theirs, &s, same_doc, PartialEq::eq);
out.placed(r, &def.name, &p);
}
}
// Symbols and patterns, compared once relinked. Those added are relinked at the end, when
// every new name and graphic style id is known.
let mut added_symbols = vec![];
for def in self.symbols.iter().filter(|s| used.has(Res::Symbol, &s.name)) {
let r = &out.relink;
let p = place(&mut d.symbols, def, same_doc, |a, b| same_art(r, std::slice::from_ref(&a.art), std::slice::from_ref(&b.art)));
added_symbols.extend(p.new_name(&def.name));
out.placed(Res::Symbol, &def.name, &p);
}
let mut added_patterns = vec![];
for def in self.patterns.iter().filter(|p| used.has(Res::Pattern, &p.name)) {
// Tile options alike, and the art once relinked.
let bare = |p: &PatternDef| PatternDef { name: String::new(), art: vec![], ..p.clone() };
let same = |n: &str| d.pattern(n).is_some_and(|x| bare(x) == bare(def) && same_art(&out.relink, &x.art, &def.art));
let p = existing(&def.name, d.patterns.iter().map(|p| p.name.as_str()), same_doc, same).unwrap_or_else(|| {
// Its swatch comes along under the same name.
let name = unique_name(&def.name, |n| d.pattern(n).is_some() || d.swatch_name_taken(n));
add_pattern(d, PatternDef { name: name.clone(), ..def.clone() });
Placed::added(&def.name, name)
});
added_patterns.extend(p.new_name(&def.name));
out.placed(Res::Pattern, &def.name, &p);
}
self.import_graphic_styles(d, &used, same_doc, &mut out);
for s in d.symbols.iter_mut().filter(|s| added_symbols.contains(&s.name)) {
out.relink.node(Arc::make_mut(&mut s.art));
}
for p in d.patterns.iter_mut().filter(|p| added_patterns.contains(&p.name)) {
for a in &mut p.art {
out.relink.node(Arc::make_mut(a));
}
}
out
}
/// Image blobs: a different blob under a key the document uses gets a new key.
fn import_images(&self, d: &mut Document, used: &Used, same_doc: bool, out: &mut Imported) {
for (key, blob) in self.images.iter().filter(|(k, _)| used.has(Res::Image, k)) {
let p = existing(key, d.images.keys().map(String::as_str), same_doc, |k| d.images.get(k) == Some(blob)).unwrap_or_else(|| {
let k = unique_name(key, |n| d.images.contains_key(n));
d.images.insert(k.clone(), blob.clone());
Placed::added(key, k)
});
out.placed(Res::Image, key, &p);
}
}
fn import_brushes(&self, d: &mut Document, used: &Used, same_doc: bool, out: &mut Imported) {
let brushes: Vec<&Brush> = self.brushes.iter().filter(|b| used.has(Res::Brush, &b.name)).collect();
if brushes.is_empty() {
return;
}
let mut lib = vectorcraft_brush::library(d);
let before = lib.len();
for b in brushes {
let p = place(&mut lib, b, same_doc, PartialEq::eq);
out.placed(Res::Brush, &b.name, &p);
}
if lib.len() != before {
vectorcraft_brush::store(d, &lib);
}
}
/// Global and spot colours (a name conflict merges or adds as `choices` say), then the tint
/// swatches of the tints used and the gradient swatches.
fn import_swatches(&self, d: &mut Document, used: &Used, choices: &SwatchChoices, same_doc: bool, out: &mut Imported) {
let conflicts: BTreeSet<String> =
if same_doc { BTreeSet::new() } else { self.conflicts(d, used).into_iter().map(|(w, _)| w.name.clone()).collect() };
let bases: Vec<&Swatch> = self.swatches.iter().filter(|w| is_base(w) && used.has(Res::Swatch, &w.name)).collect();
for w in &bases {
let p = if conflicts.contains(&w.name) && choices.of(&w.name) == SwatchChoice::Merge {
out.merged += 1;
Placed::Existing
} else {
add_swatch(d, w, same_doc)
};
out.placed(Res::Swatch, &w.name, &p);
}
// Linked colours show the document's swatch of their link.
for w in &bases {
let name = out.relink.renamed(Res::Swatch, &w.name);
if let Some(c) = d.global_color(&name) {
out.relink.colors.insert(name, c);
}
}
// Then the tint and gradient swatches, linked like the objects.
for def in self.swatches.iter().filter(|w| !is_base(w) && used.carries(w)) {
let mut w = def.clone();
out.relink.paint(&mut w.paint);
let p = add_swatch(d, &w, same_doc);
out.placed(Res::Swatch, &def.name, &p);
}
}
/// Graphic styles: in the source document by id, elsewhere by name and look.
fn import_graphic_styles(&self, d: &mut Document, used: &Used, same_doc: bool, out: &mut Imported) {
for g in self.graphic_styles.iter().filter(|g| used.styles.contains(&g.id)) {
let mut new = g.clone();
out.relink.appearance(&mut new.appearance);
let found = match d.graphic_styles.iter().position(|x| same_doc && x.id == g.id) {
Some(i) => Some(i),
None => {
let same = |n: &str| d.graphic_style(n).is_some_and(|x| x.same_look(&new));
let p = existing(&g.name, d.graphic_styles.iter().map(|x| x.name.as_str()), same_doc, same);
// Objects follow the style's id, not its name.
p.and_then(|p| d.graphic_style_index(if let Placed::Reused(n) = &p { n } else { &g.name }))
}
};
let i = match found {
Some(i) => i,
None => {
let name = unique_name(&g.name, |n| d.graphic_style(n).is_some());
out.placed(Res::GraphicStyle, &g.name, &Placed::added(&g.name, name.clone()));
let id = d.next_graphic_style_id();
d.graphic_styles.push(GraphicStyle { name, id, ..new });
d.graphic_styles.len() - 1
}
};
out.relink.styles.insert(g.id, d.graphic_style_id(i));
}
}
}
/// Swatch `w` in `d` ([`existing`]), else added under a free name (swatches and colour groups
/// share one namespace).
fn add_swatch(d: &mut Document, w: &Swatch, same_doc: bool) -> Placed {
let same = |n: &str| d.swatch(n).is_some_and(|t| *t == Swatch { name: n.to_string(), ..w.clone() });
existing(&w.name, d.swatches_iter().map(|t| t.name.as_str()), same_doc, same).unwrap_or_else(|| {
let name = d.free_swatch_name(&w.name);
d.swatches.push(Swatch { name: name.clone(), ..w.clone() });
Placed::added(&w.name, name)
})
}
Loaded 100 of 563 files, more files were not shown because too many files have changed in this diff. Show more