VectorCraft: An open-source, vector art tool written by scratch in pure Rust
Merge storytold/main into AF.3 native Affinity import
callmeBallochb5ae419734a2
diff --cc README.mdindex 145b9b41c,2e4a43c34..bbc0787c6--- a/README.md+++ b/README.md@@@ -193,14 -193,8 +193,14 @@@ milestones, and honest time-to-parity e**Where we are (2026-10-07):** roughly 69–75% of Illustrator's features exist and work, and about 40–55% of"a power user can't tell the difference". Everyday vector illustration is close to usable: drawing and path tools,Pathfinder and Shape Builder, paint, gradients, appearance and transparency, type with styles, threading and Hebrew/Arabic bidirectional layout, and-files (SVG, PDF and PDF-compatible `.ai` with PDF/X, EPS, DXF, EMF/WMF, raster formats and PSD, Print, Package). The interface+files (SVG, PDF and PDF-compatible `.ai` with PDF/X, EPS, DXF, EMF/WMF, raster formats and PSD, Print, Package).+Affinity documents (`.af` from Affinity 3, `.afdesign`, `.afpub` and, by their content, `.afphoto` from Affinity 1 and 2) open+and place natively: layers, groups, artboards and pages, curves and shapes, fills, gradients and strokes, clipping+and masks, text and images, with what didn't come in (effects, adjustments, brushes, master pages…) listed in the+import warning; a file whose native data can't be read opens as its embedded preview, saying why. VectorCraft+doesn't write Affinity files. [Scope and limits](crates/affinity/README.md).+The interface- speaks English, Japanese, Traditional and Simplified Chinese, Spanish and Italian (and Czech and Brazilian Portuguese in the menus).+ speaks English, Japanese, Traditional and Simplified Chinese, Spanish, French, Italian and Russian (and Czech and Brazilian Portuguese in the menus).The scores areself-assessed, so the [honest assessment](ROADMAP.md#honest-assessment-2026-10-05) explains how far to trust them.diff --cc ROADMAP.mdindex 2d0c01bd7,8496cebfa..2ace207ed--- a/ROADMAP.md+++ b/ROADMAP.md@@@ -158,9 -158,9 +160,10 @@@ grade by behaviour against `plan/illust- **Fonts:** a font is found by any of its names (family and style in every language of its name table, legacy family/style pairs, PostScript name), so documents from other apps open with the font they name; Find Font and `text.fonts` say for each font whether it was found exactly, by another name, substituted or missing, and how many glyphs are missing. PDF and `.ai` import brings Japanese text back as live type: CID fonts without a ToUnicode map read through the standard CMaps, vertical columns (WMode 1) as vertical type, letter spacing as tracking; a glyph is live type only when the installed font (in the closest style of its family) draws the same glyph, and text in a font that isn't installed comes in as live type shown in the fallback font until the font is installed (exports that draw it — PDF, EPS, EMF/WMF, raster, SVG outlines or embedded fonts — warn that they wrote the fallback font; `textAs: outlines` keeps the PDF's embedded glyphs).- **Files (M4):**- `.vectorcraft` (lossless JSON, compressed, atomic saves, save down to v1), Save As with a format chooser, Save a Copy, Revert, templates, Data Recovery after a crash (browser tabs hold their copies with Web Locks too, so a background tab's copies are never taken for a crash's, and a tab repairs copies another removed when it resumes: #367), background save and export. The desktop app writes its warnings and errors (graphics adapter, a lost graphics device, panics the guard recovered from) to standard error and to `logs/vectorcraft.log` next to the preferences, the two previous runs kept and each file capped at 16 MiB, so a launch without a terminal still leaves something to attach to a bug report (#465).- - SVG/SVGZ in and out with SVG Options, Preserve Editing, symbols, filters, rich text and physical units (SVG type under a transform or `viewBox` scale opens at the size it draws at, the scale moved into its size, leading, baseline shift and strokes, a stretch, skew or rotation kept as its transform: #396; a top-level group with a clip path, such as a clipped Inkscape layer, opens as a layer with a clipping mask, its name kept: #420); PDF and PDF-compatible `.ai` in and out (layers, with hidden ones kept hidden with their art and nested ones as sublayers, on pages of up to 64 million operators, art whose layer can't be told going to a hidden, non-printing layer rather than showing or printing: #419; strokes kept live, a fill and a stroke of one outline as one object; a type object's stroke written as each glyph's outline stroked back on the type, so it stays one editable object; lines wrapped in a frame (each wrapped line ending in a space, one left edge, leading and font) back as one area type object, left aligned or justified with its paragraph spacing, where laying it out breaks the lines where the file does; glyphs set apart by gaps wider than a space (a barcode's digit groups) keeping their places; layers stacked as the pages mark them even when one first paints on a later page, art ending a layer's marked content or a clip closing in a later layer kept in its own layer, and layers with no art kept empty: #508; masks, editable text with type set along a curve coming back as type on a path, each artboard's art on its own page only, an `.ai`'s white page under its layers left out rather than coming in as art, spot colours, presets, security, marks and bleed, ICC output intents, raster effects, subset fonts, PDF/X, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3). CMYK images keep their ink amounts from PDF import (and from placed CMYK TIFFs) to PDF export: a CMYK JPEG passes through unchanged, others stay CMYK (DeviceCMYK, or ICC-based CMYK in PDF/X-3/X-4) unless the Output settings convert them; the canvas shows them through the working CMYK profile (#320).+ - SVG/SVGZ in and out with SVG Options, Preserve Editing, symbols, filters, rich text and physical units (SVG type under a transform or `viewBox` scale opens at the size it draws at, the scale moved into its size, leading, baseline shift and strokes, a stretch, skew or rotation kept as its transform: #396; a top-level group with a clip path, such as a clipped Inkscape layer, opens as a layer with a clipping mask, its name kept: #420; hidden objects written hidden on Save and `convert`, and `data-*` attributes kept as the objects' own data: #522; top-level groups open as layers named from `data-name`, else the id, also when one more group (a transform on all the art, a `<switch>`) wraps them, hidden ones hidden, and a file whose art sits loose under a root `<svg>` with an id (or `data-name`), as one-layer exports write it, opens with its one layer named from it; nested groups stay groups, except the sublayers VectorCraft writes, marked `data-vc-layer`, and Inkscape sublayers, which open as sublayers in their layer's colour: #372); PDF and PDF-compatible `.ai` in and out (layers, with hidden ones kept hidden with their art and nested ones as sublayers, on pages of up to 64 million operators, art whose layer can't be told going to a hidden, non-printing layer rather than showing or printing: #419; strokes kept live, a fill and a stroke of one outline as one object; a type object's stroke written as each glyph's outline stroked back on the type, so it stays one editable object; lines wrapped in a frame (each wrapped line ending in a space, one left edge, leading and font) back as one area type object, left aligned or justified with its paragraph spacing, where laying it out breaks the lines where the file does; glyphs set apart by gaps wider than a space (a barcode's digit groups) keeping their places; layers stacked as the pages mark them even when one first paints on a later page, art ending a layer's marked content or a clip closing in a later layer kept in its own layer, and layers with no art kept empty: #508; masks, editable text with type set along a curve coming back as type on a path, each artboard's art on its own page only, an `.ai`'s white page under its layers left out rather than coming in as art, spot colours, presets, security, marks and bleed, ICC output intents, raster effects, subset fonts, PDF/X, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3). CMYK images keep their ink amounts from PDF import (and from placed CMYK TIFFs) to PDF export: a CMYK JPEG passes through unchanged, others stay CMYK (DeviceCMYK, or ICC-based CMYK in PDF/X-3/X-4) unless the Output settings convert them; the canvas shows them through the working CMYK profile (#320).- EPS and DXF in and out, EMF/WMF in and out; PNG (with PNG-8), JPEG, WebP, GIF, TIFF, BMP, Targa and layered PSD export. EPS import runs a PostScript Level 3 interpreter written from the PostScript Language Reference: resource categories and `resourceforall`, local and global VM (`currentglobal`/`setglobal`/`gcheck`), `clipsave`/`cliprestore`, subarrays and substrings that share storage, the standard dictionaries in `systemdict`, `dictstack`, `internaldict`, executable filters and strings, `load` by any key, `//name` immediate names, `token`, `execform`, user paths, `cshow`, `rootfont`, `cachestatus`, colour rendering and halftone queries, file `status` and data read with `flushfile`, and `pdfmark` marks dropped (Discord feedback, #466, #469, #474). Masked images (`ImageType 3` in its three interleavings) and reusable streams are read, and an image's several data sources are read in turn, as the reference defines (procedures that read one file get their own rows: such images came in banded, #498). `restore` puts dictionaries back as they were at the `save`, so programs that count their saves in a dictionary read to their end (part of #505). Tiling patterns come in as pattern swatches, uncoloured ones too; Type 3 fonts' glyphs as their outlines, spaced by `ashow`/`widthshow`/`xshow`/`kshow`; mesh and function-based shadings (types 1, 4–7) as gradient meshes; sampled functions (type 0) and Flate/LZW predictors are read. It is tested with programs written from the specification in the ways common generators use these features; Inkscape/cairo EPS files open as vectors. When a file's PostScript still can't be read, it opens as its TIFF preview, its Windows metafile preview (as vectors) or its EPSI preview, and the warning (in the status bar, `document.open`/`app.open`/MCP `open_file` replies and `vectorcraft-cli info`) names the error, the operator that raised it and the procedures it ran in. Legacy PostScript `.ai` files (Illustrator 3–8, written with the prolog that defines their operators) keep their groups and nested groups (`u` … `U`), between and inside clipping groups; EPS and EMF/WMF import nest clips (and groups) at most 128 deep, so a hostile file can't exhaust the stack. DXF TEXT justified Fit or Aligned spans its two points (stretched, or scaled as a whole).+ - Affinity documents in (AF.1–AF.3): `.af` (Affinity 3) and `.afdesign`/`.afphoto`/`.afpub` (Affinity 1 and 2, container versions 8–12) open and place as editable art: layers and sublayers, groups (pass-through or isolated), artboards (with their names and backgrounds) and Publisher pages side by side, curves with live corners, parametric shapes (rectangles with corner radii, ellipses, polygons, stars, pies, triangles, trapezoids), compound shapes, solid/linear/elliptical gradient fills and strokes (weight, dashes, alignment, scale-with-object), clipping by nesting, vector and pixel masks, artistic and frame text with fonts, sizes, tracking, leading and alignment, placed images (their original JPEG/PNG) and pixel layers (8/16-bit RGB, CMYK), opacity, visibility, locking and blend modes, at the document's resolution in points. Effects, adjustments, brushes and pressure profiles, transparency gradients, master pages, symbol instances (imported as their cached picture), special shapes (cloud, heart, cog…, imported as ellipses) and Affinity-only blend modes are named in the import warning. A file whose native data can't be read opens as its embedded preview with the reason, and that preview can't be placed. Save never writes back over the Affinity file and there is no Affinity export. 22 public CC0/MIT/Apache-2.0 files, pinned and sha256-verified (`cargo xtask corpus --affinity`), must render within a few levels of the thumbnails Affinity saved in them; [scope, provenance and limits](crates/affinity/README.md).+ - Placed documents: File › Place of a `.vectorcraft` file links to it by default (`file.place`'s `link`): one locked object showing an artboard of the document (or its art's bounds), read the way placing it without Link reads it, its symbols, patterns and images kept apart from the document's; without Link (or from bytes, not a file) it is an editable copy as before. It stays vectors in every output (SVG, PDF, EPS, EMF, DXF), and so do placed documents inside it, read from their own files up to 8 levels deep (documents that place each other stop there). On screen they draw from bitmaps cached per file and zoom step, shared by every copy and made in the background (a placeholder until ready), so a sheet of them redraws in about a millisecond; exports and prints draw them exactly. Like linked images, a save keeps only a preview of each (JPEG when opaque) unless Include Linked Files; output, and zooming past the preview, read the file again, falling back to the preview with a warning when it is gone or changed. Saves for older versions write them as plain art. Links check, update, relink, Update Links on open, Link Info (the artboard's size), Placement Options, Break Link (also Embed, Object › Expand: the editable copy placing without Link gives, its resources joining the document), Edit Original (the document in a new tab) and the Links panel cover them; saving a document updates the open documents that place it. The native format (v4) keeps data of 8 KB or more after the JSON instead of base64 in it.- Place and the Links panel, Package, File Info, Print with print presets, PostScript output and print tiling, slices and Save for Web, Export for Screens and Asset Export, CSS Properties, PNG/PDF/SVG/text clipboard flavours; files copied in a file manager paste as art (SVG, PDF, EMF/WMF, bitmaps) on every desktop platform, and Linux/Wayland reads the compositor's clipboard (#398); on Linux the Paste menu checks the clipboard off the UI thread, so an X11 owner that never answers can't freeze the window (#510); screenshots and other copied pictures paste as embedded images at the view centre everywhere, the web included (#457).- **Performance:** 20k shapes + 1k texts render in 27 ms per full-retina frame (7.8 ms zoomed), 7× faster than the first version. The UI thread never blocks. The web build is 7.1 MB gzipped.- **Graphics processor:** the canvas is rasterized on the CPU and the GPU only composites it, so any GPU that can show the window will do. Preferences › Performance › Graphics Processor (`gpuPreference`) is Automatic by default: the power-saving GPU on Windows and macOS (the integrated one on hybrid-graphics laptops, where presenting from the discrete GPU made the window flicker, #306), and the GPU the desktop runs on under Linux, where KWin on an NVIDIA GPU refused frames from a Ryzen's integrated GPU and 0.5.0 crashed at startup (#502). Power Saving and High Performance pick a kind of GPU; `WGPU_POWER_PREF`, `WGPU_ADAPTER_NAME` and `WGPU_BACKEND` override them. The app picks among the adapters that can present to the window (native backends before OpenGL, hardware before software, and on Windows a GPU's DX12 adapter before its Vulkan one: Intel's Vulkan driver made the whole window flicker black, #545), and if the window fails on one while starting up it starts again without it instead of crashing; Help › About, `ui.inspect` and the log name the adapter in use. When the browser drops the page's WebGPU device or WebGL context, the web build writes recovery copies, starts again on new graphics with the same app and uploads its textures again; if it can't, it removes the stale canvas and says to reload, which offers the copies back. The desktop app writes the copies and says to restart (#369). On Windows and Linux the tools' cursors are OS cursors (bitmaps rasterized once per display scale), which the system moves itself: painted into the window, they trailed the pointer by the frames waiting to be shown, and the window now queues one frame instead of two (#444). macOS and the web still paint them (macOS sizes cursor bitmaps in points, eframe has no bitmap cursors on the web). Pens and touch drive the tools as the mouse does, and a tap pressed and lifted within one frame clicks where it tapped (#491); pen pressure reaches the Liquify tools' Use Pressure Pen on Windows, while winit 0.30 reports none on macOS or Linux and egui none on the web. On Linux, see `docs/development.md` for pens under Wayland.@@@ -172,12 -172,12 +175,12 @@@|---|---|---|---|| M0 | Skeleton + vertical slice | ✅ done | — || M1 | Selection, transform, layers, MCP | ✅ mostly done (transform reference point snaps to anchors/centres; rotated objects keep a rotated bounding box and their angle; Free Transform, Scale and Reflect along a rotated box pending) | 4–6 |- | M2 | Drawing tools + smart guides | ✅ mostly done (Flare, Reshape, Live Corners widget dragging and per-corner radii and kinds landed, on any path's corners; Shaper, the remaining Pen modifier nuances) | 15–20 |+ | M2 | Drawing tools + smart guides | ✅ mostly done (Flare, Reshape, Live Corners widget dragging and per-corner radii and kinds landed, on any path's corners; Shaper rough-shape recognition and orientation steps, the remaining Pen modifier nuances; Shaper Groups with editable sources and separate fill/stroke edits landed; construction widget/refinements pending) | 12–18 || M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Color Picker, Color panel, Color Guide, Color Themes, Edit Colors and Recolor Artwork; gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool, Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries. Left: freeform and mixed spot/process gradients export as stops or process colours to SVG/PDF; confirm the Scale Strokes & Effects default | 4–8 |-| M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out, EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, Asset Export, clipboard flavours, File Info. Left: DWG (use DXF), PSD placement as layers, overprint read back from PDF, polish | 3–6 |+| M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out, EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, Asset Export, clipboard flavours, File Info; AF.1–AF.3 add Affinity import (native layers, artboards, vectors, text and images from Affinity 1–3 files; the embedded preview only as a warned fallback). Left: DWG (use DXF), PSD placement as layers, overprint read back from PDF, Affinity export, polish | 3–6 (existing scope; Affinity export unestimated) || 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 (Boolean precision on almost-horizontal edges fixed and the property tests made deterministic; Shape Builder gap detection, large-offset bug open) | 3–6 |- | M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | 🟡 Character/Paragraph Styles, Area Type Options (with Width/Height), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs, OpenType panel, Find Font, installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import, variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel, Hebrew/Arabic bidirectional text and Paragraph Direction done; tab leaders, spell check, vertical type pending | 45–60 |+ | M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | 🟡 Character/Paragraph Styles, per-paragraph paragraph attributes, Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs, OpenType panel, Find Font, installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import, variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel, inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; tab leaders, spell check, vertical type pending | 45–60 || M8 | Transform & distort (Puppet Warp, Liquify tools, Envelopes, Blends, Perspective Grid) | ✅ done (M8.1–M8.20 on 2026-10-06, fidelity pass): Liquify Tool Options with one shared brush, pen pressure, hold-to-apply, a safe scope and incremental strokes; tool options that last; Puppet Warp rotation, multi-select, Control bar and a rest-shape session that follows Undo; Width tool on compound paths; Envelope dialogs with preview, Reset with Warp/Mesh, full Envelope Options, type/images/symbols/appearance/gradients/patterns distorted on canvas and in every export, warps that keep their frame, Edit Contents, mesh handles and Control bar; Blend Options, anchor-targeted Blend tool, editable spine, keys picked on the canvas, faithful interpolation and knockout; Perspective Grid with Define Grid, presets, lock/snap/rulers, widgets, the 1–4 plane switch, movable planes, Perspective Selection scale/copy/perpendicular/Transform Again, and type and symbols truly projected with Edit Text. Left: Anti-Alias and Preserve Shape output, warp-envelope point editing, brush interpolation in blends, Free Transform/Scale/Reflect along a rotated box | 2–4 || M9 | Live effects (+ 3D & Materials) | 🟡 2D effects done incl. Effect → Pathfinder and Color Adjustments; SVG Filters, Document Raster Effects Settings, 3D pending | 86–135 || M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG `<pattern>`/PDF export) and live Repeat (radial/grid/mirror) done; brushes/symbols in progress | 23–37 |diff --cc crates/engine/src/cmd/fileio/affinity.rsindex 53c37c401,000000000..e6e10e33bmode 100644,000000..100644--- a/crates/engine/src/cmd/fileio/affinity.rs+++ b/crates/engine/src/cmd/fileio/affinity.rs@@@ -1,509 -1,0 +1,509 @@@+//! Affinity documents (`.af`, `.afdesign`, `.afphoto`, `.afpub`): the native layers, curves,+//! shapes, artboards, text and images that `vectorcraft-affinity` reads, mapped to editable+//! VectorCraft art. Whatever the reader could not map is listed in the warnings. A file whose+//! native document can't be read opens as its embedded preview instead, with a warning that says+//! why, and can't be placed.++use std::io::Cursor;+use std::sync::Arc;++use kurbo::{Affine, BezPath, Point, Rect, Vec2};+use vectorcraft_affinity::model::{self as af, Align as AfAlign, Blend, Kind, Pixels};+use vectorcraft_affinity::paint::{self as ap, Cap, GradientKind as AfKind, Join};+use vectorcraft_color::{BlendMode, Color, Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop, Paint};+use vectorcraft_doc::appearance::{Appearance, AppearanceItem, Dash, FillLayer, LineCap, LineJoin, StrokeAlign, StrokeLayer};+use vectorcraft_doc::geom::{FillRule, PathData, shapes};+use vectorcraft_doc::text::{CharStyle, Justify, TextKind, TextObject, TextRun};+use vectorcraft_doc::{Artboard, Document, ImageObject, LayerColor, Node, NodeKind, OpacityMask};++use super::load::{err, raster_doc};+use crate::Result;++/// What an Affinity file opened as.+pub(super) struct Imported {+ pub doc: Document,+ pub warnings: Vec<String>,+ /// Only the embedded preview: never placed, used as a template or mined for styles.+ pub preview_only: bool,+}++pub(super) fn import(name: &str, bytes: &[u8]) -> Result<Imported> {+ match vectorcraft_affinity::read(bytes, vectorcraft_affinity::Limits::default()) {+ Ok(d) => {+ let mut b = Builder { doc: Document::new(0.0, 0.0), warnings: Vec::new(), k: 72.0 / d.dpi, layer: 0 };+ b.document(&d)?;+ let mut warnings = d.warnings.iter().map(|w| format!("Affinity: not imported or approximated: {w}.")).collect::<Vec<_>>();+ warnings.extend(b.warnings.iter().map(|w| format!("Affinity: {w}.")));+ Ok(Imported { doc: b.doc, warnings, preview_only: false })+ }+ Err(native) => {+ let (doc, w) = preview(name, bytes, &native)?;+ Ok(Imported { doc, warnings: vec![w], preview_only: true })+ }+ }+}++/// The embedded preview, for files whose native document can't be read.+fn preview(name: &str, bytes: &[u8], native: &vectorcraft_affinity::Error) -> Result<(Document, String)> {+ let p = vectorcraft_affinity::preview(bytes).map_err(|e| err(format!("{native}; its embedded preview can't be read either ({e})")))?;+ // `raster_doc` normally probes PNG dimensions and keeps its encoded bytes. Verify this+ // untrusted preview's complete pixels first, so corrupt data cannot create a blank image.+ let mut reader = image::ImageReader::with_format(Cursor::new(p.png), image::ImageFormat::Png);+ let mut limits = image::Limits::default();+ limits.max_image_width = Some(4096);+ limits.max_image_height = Some(4096);+ limits.max_alloc = Some(128 << 20);+ reader.limits(limits);+ let _pixels = reader.decode().map_err(err)?;+ let d = raster_doc(name, p.png)?;+ Ok((+ d,+ format!(+ "The native Affinity document could not be read ({native}). Opened only its embedded {}×{} PNG preview, which may be smaller than the document: no layers, vectors, text or pages. Save a new copy; the Affinity source cannot be saved back. Export SVG or PDF from Affinity for editable vectors.",+ p.width, p.height+ ),+ ))+}++struct Builder {+ doc: Document,+ warnings: Vec<String>,+ /// Points per document pixel.+ k: f64,+ /// Layers made so far (their colours cycle).+ layer: u8,+}++fn rect_of(r: af::Rect) -> Rect {+ Rect::new(r.x0, r.y0, r.x1, r.y1)+}++fn affine(a: af::Affine) -> Affine {+ Affine::new(a.0)+}++impl Builder {+ fn warn(&mut self, w: &str) {+ if !self.warnings.iter().any(|x| x == w) {+ self.warnings.push(w.to_string());+ }+ }++ fn document(&mut self, d: &af::Document) -> Result<()> {+ // Spreads (Publisher pages) sit side by side, 36 pt apart; a single spread keeps its origin.+ let mut layers = Vec::new();+ let mut artboards = Vec::new();+ let mut x = 0.0;+ for (i, spread) in d.spreads.iter().enumerate() {+ let shift = if i == 0 { 0.0 } else { x - spread.bounds.x0 * self.k };+ let to_doc = Affine::translate((shift, 0.0)) * Affine::scale(self.k);+ let before = artboards.len();+ let mut loose: Vec<Arc<Node>> = Vec::new();+ for n in &spread.nodes {+ let top = match &n.kind {+ Kind::Layer => self.node(n, to_doc, &mut artboards, true),+ Kind::Artboard { .. } => self.node(n, to_doc, &mut artboards, true).map(|art| self.layer_of(&n.name, art, n.visible, n.locked)),+ _ => {+ if let Some(art) = self.node(n, to_doc, &mut artboards, false) {+ loose.push(art);+ }+ continue;+ }+ };+ if !loose.is_empty() {+ layers.push(self.layer_with(None, std::mem::take(&mut loose)));+ }+ layers.extend(top);+ }+ if !loose.is_empty() {+ layers.push(self.layer_with(None, loose));+ }+ // Without artboards, each page (or the spread) becomes one.+ if artboards.len() == before {+ let rects = if spread.pages.is_empty() { vec![spread.bounds] } else { spread.pages.clone() };+ for r in rects {+ let name = format!("{} {}", if d.spreads.len() > 1 || spread.pages.len() > 1 { "Page" } else { "Artboard" }, artboards.len() + 1);+ artboards.push((name, to_doc.transform_rect_bbox(rect_of(r))));+ }+ }+ x = artboards.iter().map(|(_, r)| r.x1).fold(x, f64::max) + 36.0;+ if spread.transparent && i == 0 {+ self.warn("transparent page backgrounds show as white artboards");+ }+ }+ self.doc.artboards = artboards+ .into_iter()+ .enumerate()+ .filter(|(_, (_, r))| r.width() > 0.0 && r.height() > 0.0)+ .map(|(i, (name, rect))| Artboard { id: i as u32 + 1, name, rect, show_center_mark: false, show_cross_hairs: false })+ .collect();+ if self.doc.artboards.is_empty() {+ return Err(err("the Affinity document has no page with a size"));+ }+ // Bottom to top, as Affinity lists them.+ self.doc.layers = layers;+ if self.doc.layers.is_empty() {+ let empty = self.layer_with(None, Vec::new());+ self.doc.layers.push(empty);+ }+ Ok(())+ }++ fn layer_with(&mut self, name: Option<&str>, children: Vec<Arc<Node>>) -> Arc<Node> {+ let id = self.doc.alloc_id();+ self.layer = self.layer.wrapping_add(1);+ let label = name.map(str::to_string).unwrap_or_else(|| format!("Layer {}", self.layer));+ let mut n = Node::layer(id, &label, LayerColor::Preset(self.layer % 9));+ if let Some(c) = n.children_mut() {+ *c = children;+ }+ Arc::new(n)+ }++ /// An artboard at the top level becomes a layer of its name holding its clip group.+ fn layer_of(&mut self, name: &str, art: Arc<Node>, visible: bool, locked: bool) -> Arc<Node> {+ let mut l = (*self.layer_with(Some(if name.is_empty() { "Artboard" } else { name }), vec![art])).clone();+ l.visible = visible;+ l.locked = locked;+ Arc::new(l)+ }++ fn base(&mut self, n: &af::Node, kind: NodeKind) -> Node {+ let mut out = Node::new(self.doc.alloc_id(), kind);+ out.name = (!n.name.is_empty()).then(|| n.name.clone());+ out.visible = n.visible;+ out.locked = n.locked;+ out.opacity = n.opacity as f32;+ out.blend = self.blend(n.blend);+ out+ }++ fn blend(&mut self, b: Blend) -> BlendMode {+ match b {+ Blend::Normal | Blend::PassThrough => BlendMode::Normal,+ Blend::Darken => BlendMode::Darken,+ Blend::Multiply => BlendMode::Multiply,+ Blend::ColorBurn => BlendMode::ColorBurn,+ Blend::Lighten => BlendMode::Lighten,+ Blend::Screen => BlendMode::Screen,+ Blend::ColorDodge => BlendMode::ColorDodge,+ Blend::Overlay => BlendMode::Overlay,+ Blend::SoftLight => BlendMode::SoftLight,+ Blend::HardLight => BlendMode::HardLight,+ Blend::Difference => BlendMode::Difference,+ Blend::Exclusion => BlendMode::Exclusion,+ Blend::Hue => BlendMode::Hue,+ Blend::Saturation => BlendMode::Saturation,+ Blend::Color => BlendMode::Color,+ Blend::Luminosity => BlendMode::Luminosity,+ _ => {+ self.warn("blend modes VectorCraft doesn't have (Add, Linear Light, Vivid Light, Pin Light, Hard Mix, Subtract, Darker/Lighter Colour, Average, Negation, Reflect, Glow, Erase) import as Normal");+ BlendMode::Normal+ }+ }+ }++ /// One Affinity node (and its subtree) as VectorCraft art; `to_doc` maps document pixels to+ /// points. `layer_level`: the node is directly in a spread or a layer, so a layer stays a layer.+ fn node(&mut self, n: &af::Node, to_doc: Affine, boards: &mut Vec<(String, Rect)>, layer_level: bool) -> Option<Arc<Node>> {+ let child_level = matches!(n.kind, Kind::Layer) && layer_level;+ let children: Vec<Arc<Node>> = n.children.iter().filter_map(|c| self.node(c, to_doc, boards, child_level)).collect();+ let mut out = match &n.kind {+ Kind::Layer if layer_level => {+ let mut l = (*self.layer_with(Some(if n.name.is_empty() { "Layer" } else { &n.name }), children)).clone();+ l.visible = n.visible;+ l.locked = n.locked;+ l.opacity = n.opacity as f32;+ l.blend = self.blend(n.blend);+ l+ }+ Kind::Layer | Kind::Group => {+ let mut g = self.base(n, NodeKind::Group { children, clip: false });+ // Affinity groups isolate their blending unless they pass through.+ g.isolate = n.blend != Blend::PassThrough;+ g+ }+ Kind::Shape { path, fills, strokes, even_odd } => {+ let data = self.path(path, to_doc);+ let rule = if *even_odd { FillRule::EvenOdd } else { FillRule::NonZero };+ let appearance = self.appearance(fills, strokes, to_doc);+ if children.is_empty() {+ let mut p = self.base(n, NodeKind::Path { path: data, rule, live: None, clipping: false, guide: false });+ p.appearance = appearance;+ p+ } else {+ // A shape clips its children: VectorCraft's clipping path keeps its paint, its+ // fill behind the clipped art and its stroke over it, as Affinity draws it.+ let mut clip = Node::new(self.doc.alloc_id(), NodeKind::Path { path: data, rule, live: None, clipping: true, guide: false });+ clip.appearance = appearance;+ let mut kids = vec![Arc::new(clip)];+ kids.extend(children);+ self.base(n, NodeKind::Group { children: kids, clip: true })+ }+ }+ Kind::Artboard { rect, background } => {+ let r = to_doc.transform_rect_bbox(rect_of(*rect));+ boards.push((if n.name.is_empty() { format!("Artboard {}", boards.len() + 1) } else { n.name.clone() }, r));+ let mut clip = Node::new(+ self.doc.alloc_id(),+ NodeKind::Path { path: shapes::rectangle(r), rule: FillRule::NonZero, live: None, clipping: true, guide: false },+ );+ clip.appearance = self.appearance(background, &[], to_doc);+ let mut kids = vec![Arc::new(clip)];+ kids.extend(children);+ let mut g = self.base(n, NodeKind::Group { children: kids, clip: true });+ g.name = Some(if n.name.is_empty() { "Artboard".into() } else { n.name.clone() });+ g+ }+ Kind::Text(t) => {+ let text = self.text(t, to_doc);+ let mut node = self.base(n, NodeKind::Text(Box::new(text)));+ if !children.is_empty() {+ let mut kids = vec![Arc::new(node)];+ kids.extend(children);+ node = Node::group(self.doc.alloc_id(), kids);+ }+ node+ }+ Kind::Image(img) => match self.image(img, to_doc) {+ Some(kind) => self.base(n, kind),+ None if children.is_empty() => return None,+ None => self.base(n, NodeKind::Group { children, clip: false }),+ },+ Kind::Unsupported if children.is_empty() => return None,+ Kind::Unsupported => self.base(n, NodeKind::Group { children, clip: false }),+ };+ if let Some(img) = &n.pixel_mask {+ // A pixel mask: its grey levels show (white) or hide (black) the node, and nothing+ // shows outside it, as an opacity mask that clips.+ if let Some(kind) = self.image(img, to_doc) {+ let art = Node::new(self.doc.alloc_id(), kind);+ out.mask = Some(Box::new(OpacityMask::new(art, true)));+ }+ }+ if let Some(mask) = &n.mask {+ // A vector mask: the node shows only inside it.+ let clip = Node::new(+ self.doc.alloc_id(),+ NodeKind::Path { path: self.path(mask, to_doc), rule: FillRule::NonZero, live: None, clipping: true, guide: false },+ );+ let (opacity, blend, visible, name) = (out.opacity, out.blend, out.visible, out.name.clone());+ out.opacity = 1.0;+ out.blend = BlendMode::Normal;+ let mut g = Node::new(self.doc.alloc_id(), NodeKind::Group { children: vec![Arc::new(clip), Arc::new(out)], clip: true });+ (g.opacity, g.blend, g.visible, g.name) = (opacity, blend, visible, name);+ out = g;+ }+ Some(Arc::new(out))+ }++ fn path(&self, p: &af::Path, to_doc: Affine) -> PathData {+ let mut bp = BezPath::new();+ for s in &p.subpaths {+ let pt = |q: af::Point| Point::new(q.x, q.y);+ bp.move_to(pt(s.start));+ for [c1, c2, e] in &s.segments {+ if c1 == c2 && c2 == e {+ bp.line_to(pt(*e));+ } else {+ bp.curve_to(pt(*c1), pt(*c2), pt(*e));+ }+ }+ if s.closed {+ bp.close_path();+ }+ }+ PathData::from_bezpath(&(to_doc * bp))+ }++ fn color(c: ap::Color) -> (Color, f32) {+ let f = |v: f64| v.clamp(0.0, 1.0) as f32;+ match c {+ ap::Color::Rgb { r, g, b, a } => (Color::Rgb { r: f(r), g: f(g), b: f(b) }, f(a)),+ ap::Color::Cmyk { c, m, y, k, a } => (Color::Cmyk { c: f(c), m: f(m), y: f(y), k: f(k) }, f(a)),+ ap::Color::Gray { v, a } => (Color::Gray { k: 1.0 - f(v) }, f(a)),+ ap::Color::Lab { l, a, b, alpha } => (Color::Lab { l: l as f32, a: a as f32, b: b as f32 }, f(alpha)),+ }+ }++ /// A paint and the opacity its colour's alpha becomes.+ fn paint(&mut self, p: &ap::Paint, to_doc: Affine) -> Option<(Paint, f32)> {+ match p {+ ap::Paint::None => None,+ ap::Paint::Solid(c) => {+ let (color, a) = Self::color(*c);+ Some((Paint::solid(color), a))+ }+ ap::Paint::Gradient(g) => {+ let stops = g+ .stops+ .iter()+ .map(|s| {+ let (color, opacity) = Self::color(s.color);+ let mut stop = GradientStop::new(s.offset as f32, color);+ stop.opacity = opacity;+ stop.midpoint = s.half_point().clamp(0.13, 0.87) as f32;+ stop+ })+ .collect();+ let m = to_doc * affine(g.transform);+ let (o, x, y) = (m * Point::ZERO, m * Point::new(1.0, 0.0), m * Point::new(0.0, 1.0));+ let kind = match g.kind {+ AfKind::Linear => GradientKind::Linear,+ AfKind::Radial => GradientKind::Radial,+ AfKind::Conical => {+ self.warn("conical gradients import as radial gradients");+ GradientKind::Radial+ }+ };+ let (u, v): (Vec2, Vec2) = (x - o, y - o);+ if kind == GradientKind::Radial && u.hypot() > 0.0 && (u.dot(v) / (u.hypot() * v.hypot().max(1e-12))).abs() > 0.01 {+ self.warn("skewed elliptical gradients import as upright ellipses");+ }+ let aspect = if u.hypot() > 0.0 { (v.hypot() / u.hypot()).clamp(0.01, 100.0) } else { 1.0 };+ let geom = GradientGeom { start: o, end: x, aspect: if kind == GradientKind::Radial { aspect } else { 1.0 }, focal: None };+ let mut gp = GradientPaint::new(Gradient { kind, stops });+ gp.angle = (-(u.y)).atan2(u.x).to_degrees();+ gp.geom = Some(geom);+ Some((Paint::Gradient(Box::new(gp)), 1.0))+ }+ }+ }++ fn appearance(&mut self, fills: &[ap::Paint], strokes: &[ap::Stroke], to_doc: Affine) -> Appearance {+ let mut items = Vec::new();+ let mut above = Vec::new();+ for f in fills {+ if let Some((paint, opacity)) = self.paint(f, to_doc) {+ let mut l = FillLayer::new(paint);+ l.opacity = opacity;+ items.push(AppearanceItem::Fill(l));+ }+ }+ for s in strokes {+ let Some((paint, opacity)) = self.paint(&s.paint, to_doc) else { continue };+ let mut l = StrokeLayer::new(paint, s.width * self.k);+ l.opacity = opacity;+ l.cap = match s.cap {+ Cap::Butt => LineCap::Butt,+ Cap::Round => LineCap::Round,+ Cap::Square => LineCap::Square,+ };+ l.join = match s.join {+ Join::Miter => LineJoin::Miter,+ Join::Round => LineJoin::Round,+ Join::Bevel => LineJoin::Bevel,+ };+ l.miter_limit = s.miter_limit;+ l.align = match s.align {+ ap::Align::Center => StrokeAlign::Center,+ ap::Align::Inside => StrokeAlign::Inside,+ ap::Align::Outside => StrokeAlign::Outside,+ };+ l.dash = s.dash.as_ref().map(|(pattern, phase)| Dash {+ pattern: pattern.iter().map(|v| v * self.k).collect(),+ offset: phase * self.k,+ align_corners: false,+ });+ if s.behind {+ items.insert(0, AppearanceItem::Stroke(l));+ } else {+ above.push(AppearanceItem::Stroke(l));+ }+ }+ items.extend(above);+ Appearance { items, ..Appearance::default() }+ }++ fn text(&mut self, t: &af::Text, to_doc: Affine) -> TextObject {+ let origin = match t.frame {+ Some(f) => Point::new(f.x0, f.y0),+ None => Point::new(t.anchor.x, t.anchor.y),+ };+ // Text space: origin at the anchor (or frame corner), the transform's uniform scale moved+ // into the type size so sizes read in points.+ let m = to_doc * affine(t.transform) * Affine::translate(origin.to_vec2());+ let c = m.as_coeffs();+ let k = (c[0] * c[3] - c[1] * c[2]).abs().sqrt().max(1e-9);+ let xf = m * Affine::scale(1.0 / k);+ let mut obj = TextObject::point(Point::ZERO, "", CharStyle::default());+ obj.xf = xf;+ obj.runs = t+ .runs+ .iter()+ .map(|r| {+ let mut style =+ CharStyle { font_family: if r.family.is_empty() { r.postscript.clone() } else { r.family.clone() }, ..CharStyle::default() };+ style.font_style = font_style(r.weight, r.italic);+ style.size = r.size * k;+ style.leading = r.leading.map(|l| l * k);+ style.tracking = r.tracking * 1000.0;+ style.fill = match self.paint(&r.fill, to_doc) {+ Some((p, a)) => {+ if a < 0.999 {+ self.warn("translucent text colours import opaque");+ }+ p+ }+ None => Paint::None,+ };+ // Affinity separates paragraphs with U+2029 and lines with U+2028.- TextRun { text: r.text.replace(['\u{2029}', '\u{2028}'], "\n"), style }++ TextRun::new(r.text.replace(['\u{2029}', '\u{2028}'], "\n"), style)+ })+ .collect();+ obj.para.justify = match t.align {+ AfAlign::Left => Justify::Left,+ AfAlign::Center => Justify::Center,+ AfAlign::Right => Justify::Right,+ AfAlign::Justify => Justify::JustifyLeft,+ };+ if let Some(f) = t.frame {+ obj.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, (f.x1 - f.x0) * k, (f.y1 - f.y0) * k)) };+ }+ obj+ }++ fn image(&mut self, img: &af::Image, to_doc: Affine) -> Option<NodeKind> {+ let bytes = match &img.pixels {+ Pixels::Encoded(b) => b.clone(),+ Pixels::Rgba8(rgba) => {+ let buf = image::RgbaImage::from_raw(img.width, img.height, rgba.clone())?;+ let mut png = Vec::new();+ buf.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).ok()?;+ png+ }+ };+ let r = match super::load::raster_image(&bytes) {+ Ok(r) => r,+ Err(_) => {+ self.warn("an embedded image that could not be decoded was left out");+ return None;+ }+ };+ // The pixel grid maps onto the Affinity image's own size, whatever the stored file's.+ let sx = img.width as f64 / f64::from(r.width.max(1));+ let sy = img.height as f64 / f64::from(r.height.max(1));+ let xf = to_doc * affine(img.transform) * Affine::scale_non_uniform(sx, sy);+ self.doc.images.entry(r.key.clone()).or_insert(r.blob);+ Some(NodeKind::Image(ImageObject { key: r.key, width: r.width, height: r.height, xf, link: None, placement: Default::default() }))+ }+}++fn font_style(weight: i64, italic: bool) -> String {+ let w = match weight {+ ..=150 => "Thin",+ 151..=250 => "ExtraLight",+ 251..=325 => "Light",+ 326..=450 => "Regular",+ 451..=550 => "Medium",+ 551..=650 => "SemiBold",+ 651..=750 => "Bold",+ 751..=850 => "ExtraBold",+ _ => "Black",+ };+ match (w, italic) {+ ("Regular", true) => "Italic".into(),+ (w, true) => format!("{w} Italic"),+ (w, false) => w.into(),+ }+}diff --cc crates/engine/src/cmd/place/mod.rsindex c5bbc1bbd,68e4a58cc..9fee1ce57--- a/crates/engine/src/cmd/place/mod.rs+++ b/crates/engine/src/cmd/place/mod.rs@@@ -177,17 -196,7 +197,17 @@@ fn load(p: &Value, cmd: &str, board: Op// Of the open options, only a DXF drawing's apply (the colour mode stays the file's).let o = fileio::LoadOptions { dxf: opts.dxf, ..Default::default() };let mut l = fileio::load_with(src.name, &src.bytes, &o)?;+ // An Affinity file whose native document couldn't be read is only its preview: it+ // must never silently stand in for the art.+ if l.preview_only {+ return Err(bad(+ cmd,+ format!(+ "{name}: only this Affinity file's embedded preview could be read; use File › Open to see it with its warning, or export SVG or PDF from Affinity before placing"+ ),+ ));+ }- // Linked images (a native document's) show their files, found from its folder.+ // Linked images show their files, found from its folder.super::links::resolve(&mut l.doc, src.path, false);(l.doc, l.warnings)}diff --cc crates/engine/src/cmd/swatchlib.rsindex 3097b2341,00462b8e4..54a498988--- a/crates/engine/src/cmd/swatchlib.rs+++ b/crates/engine/src/cmd/swatchlib.rs@@@ -351,15 -359,11 +359,14 @@@ fn load(s: &mut Session, p: &Value) ->const C: &str = "swatch.library.load";let (info, lib) = s.swatch_libraries.load(p, C, |bytes, file| {// A library file, or a document whose swatches become the library.- match std::str::from_utf8(bytes).ok().filter(|t| palette_io::sniff(t)) {- Some(t) => palette_io::read(t, stem(file)).map_err(|e| bad(C, e)),- None => {- let loaded = super::fileio::load(file, bytes).map_err(|e| bad(C, e.to_string()))?;- if loaded.preview_only {- return Err(bad(C, "only this Affinity file's embedded preview could be read; use File › Open to see it with its warning"));- }- document_library(&loaded.doc, &[], stem(file).to_string(), C)+ if palette_io::sniff_bytes(bytes) {+ palette_io::read_bytes(bytes, stem(file)).map_err(|e| bad(C, e))+ } else {- let doc = super::fileio::load(file, bytes).map_err(|e| bad(C, e.to_string()))?.doc;- document_library(&doc, &[], stem(file).to_string(), C)++ let loaded = super::fileio::load(file, bytes).map_err(|e| bad(C, e.to_string()))?;++ if loaded.preview_only {++ return Err(bad(C, "only this Affinity file's embedded preview could be read; use File › Open to see it with its warning"));+ }++ document_library(&loaded.doc, &[], stem(file).to_string(), C)}})?;Ok(json!({"library": info.id, "name": info.name, "count": lib.len()}))