diff --git a/Cargo.lock b/Cargo.lock
index 9cea5c99c7..193dc09469 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4574,7 +4574,7 @@ dependencies = [
[[package]]
name = "vectorcraft"
-version = "0.14.0"
+version = "0.16.0"
dependencies = [
"arboard",
"block2 0.6.2",
@@ -4608,12 +4608,13 @@ dependencies = [
"winit",
"winresource",
"winsafe",
+ "x11rb",
"zbus",
]
[[package]]
name = "vectorcraft-affinity"
-version = "0.14.0"
+version = "0.16.0"
dependencies = [
"crc32fast",
"flate2",
@@ -4624,7 +4625,7 @@ dependencies = [
[[package]]
name = "vectorcraft-brush"
-version = "0.14.0"
+version = "0.16.0"
dependencies = [
"kurbo 0.13.1",
"serde",
@@ -4636,7 +4637,7 @@ dependencies = [
[[package]]
name = "vectorcraft-cad"
-version = "0.14.0"
+version = "0.16.0"
dependencies = [
"image",
"kurbo 0.13.1",
@@ -4652,7 +4653,7 @@ dependencies = [
[[package]]
name = "vectorcraft-cli"
-version = "0.14.0"
+version = "0.16.0"
dependencies = [
"log",
"objc2-core-foundation",
@@ -4674,7 +4675,7 @@ dependencies = [
[[package]]
name = "vectorcraft-color"
-version = "0.14.0"
+version = "0.16.0"
dependencies = [
"kurbo 0.13.1",
"moxcms",
@@ -4686,7 +4687,7 @@ dependencies = [
[[package]]
name = "vectorcraft-doc"
-version = "0.14.0"
+version = "0.16.0"
dependencies = [
"chrono",
"hayro-ccitt",
@@ -4705,7 +4706,7 @@ dependencies = [
[[package]]
name = "vectorcraft-effects"
-version = "0.14.0"
+version = "0.16.0"
dependencies = [
"image",
"kurbo 0.13.1",
@@ -4721,7 +4722,7 @@ dependencies = [
[[package]]
name = "vectorcraft-engine"
-version = "0.14.0"
+version = "0.16.0"
dependencies = [
"craft-docpath",
"crc32fast",
@@ -4759,7 +4760,7 @@ dependencies = [
[[package]]
name = "vectorcraft-eps"
-version = "0.14.0"
+version = "0.16.0"
dependencies = [
"fax",
"flate2",
@@ -4782,7 +4783,7 @@ dependencies = [
[[package]]
name = "vectorcraft-format"
-version = "0.14.0"
+version = "0.16.0"
dependencies = [
"flate2",
"proptest",
@@ -4797,7 +4798,7 @@ dependencies = [
[[package]]
name = "vectorcraft-geom"
-version = "0.14.0"
+version = "0.16.0"
dependencies = [
"kurbo 0.13.1",
"proptest",
@@ -4809,7 +4810,7 @@ dependencies = [
[[package]]
name = "vectorcraft-mcp"
-version = "0.14.0"
+version = "0.16.0"
dependencies = [
"image",
"log",
@@ -4828,7 +4829,7 @@ dependencies = [
[[package]]
name = "vectorcraft-metafile"
-version = "0.14.0"
+version = "0.16.0"
dependencies = [
"image",
"kurbo 0.13.1",
@@ -4842,7 +4843,7 @@ dependencies = [
[[package]]
name = "vectorcraft-pathops"
-version = "0.14.0"
+version = "0.16.0"
dependencies = [
"kurbo 0.13.1",
"linesweeper",
@@ -4854,7 +4855,7 @@ dependencies = [
[[package]]
name = "vectorcraft-pdf"
-version = "0.14.0"
+version = "0.16.0"
dependencies = [
"aes",
"chrono",
@@ -4885,7 +4886,7 @@ dependencies = [
[[package]]
name = "vectorcraft-plugins"
-version = "0.14.0"
+version = "0.16.0"
dependencies = [
"serde",
"serde_json",
@@ -4899,7 +4900,7 @@ dependencies = [
[[package]]
name = "vectorcraft-render"
-version = "0.14.0"
+version = "0.16.0"
dependencies = [
"flate2",
"gif",
@@ -4926,14 +4927,14 @@ dependencies = [
[[package]]
name = "vectorcraft-scriptcheck"
-version = "0.14.0"
+version = "0.16.0"
dependencies = [
"proptest",
]
[[package]]
name = "vectorcraft-svg"
-version = "0.14.0"
+version = "0.16.0"
dependencies = [
"craft-docpath",
"flate2",
@@ -4958,7 +4959,7 @@ dependencies = [
[[package]]
name = "vectorcraft-testkit"
-version = "0.14.0"
+version = "0.16.0"
dependencies = [
"fax",
"image",
@@ -4976,7 +4977,7 @@ dependencies = [
[[package]]
name = "vectorcraft-text"
-version = "0.14.0"
+version = "0.16.0"
dependencies = [
"harfrust 0.13.3",
"icu_segmenter",
@@ -4990,13 +4991,14 @@ dependencies = [
"unicode-segmentation",
"vectorcraft-doc",
"vectorcraft-geom",
+ "vello_cpu 0.2.0",
"windows-registry",
"write-fonts",
]
[[package]]
name = "vectorcraft-three-d"
-version = "0.14.0"
+version = "0.16.0"
dependencies = [
"vectorcraft-geom",
"vectorcraft-pathops",
@@ -5004,7 +5006,7 @@ dependencies = [
[[package]]
name = "vectorcraft-tools"
-version = "0.14.0"
+version = "0.16.0"
dependencies = [
"image",
"kurbo 0.13.1",
@@ -5020,7 +5022,7 @@ dependencies = [
[[package]]
name = "vectorcraft-trace"
-version = "0.14.0"
+version = "0.16.0"
dependencies = [
"image",
"kurbo 0.13.1",
@@ -5032,7 +5034,7 @@ dependencies = [
[[package]]
name = "vectorcraft-ui-egui"
-version = "0.14.0"
+version = "0.16.0"
dependencies = [
"bytemuck",
"craft-ui",
@@ -5068,7 +5070,7 @@ dependencies = [
[[package]]
name = "vectorcraft-web"
-version = "0.14.0"
+version = "0.16.0"
dependencies = [
"eframe",
"egui",
@@ -6106,7 +6108,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee"
[[package]]
name = "xtask"
-version = "0.14.0"
+version = "0.16.0"
dependencies = [
"serde_json",
]
diff --git a/Cargo.toml b/Cargo.toml
index 725ae7ce11..e6efb9342b 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"]
default-members = ["crates/*", "apps/vectorcraft", "apps/vectorcraft-cli", "xtask"]
[workspace.package]
-version = "0.14.0"
+version = "0.16.0"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.95"
diff --git a/README.md b/README.md
index 4023951e2c..d85cef156e 100644
--- a/README.md
+++ b/README.md
@@ -8,6 +8,10 @@
+
+
+
+
VectorCraft
@@ -202,10 +206,10 @@ the app with `WAYLAND_DISPLAY= vectorcraft`: the window then opens through XWayl
(see [`docs/development.md`](docs/development.md#linux-wayland-and-x11)).
On Linux with Wayland, under KDE Plasma 6.3 or later and under GNOME, VectorCraft doesn't respond to a drawing tablet's
-pen yet (#491, #2028). Open the window through XWayland instead, where the pen works as a mouse: set the same
-preference to **X11 (XWayland)**, or to **X11 (XWayland) When a Pen Is Attached** to use XWayland only when a pen is
-attached as VectorCraft starts, and restart; or start the app with `WAYLAND_DISPLAY= vectorcraft` (see
-[`docs/development.md`](docs/development.md#linux-wayland-and-x11)).
+pen yet (#491, #2028). Open the window through XWayland instead, where the pen works as a mouse and the app reads its
+pressure: set the same preference to **X11 (XWayland)**, or to **X11 (XWayland) When a Pen Is Attached** to use
+XWayland only when a pen is attached as VectorCraft starts, and restart; or start the app with
+`WAYLAND_DISPLAY= vectorcraft` (see [`docs/development.md`](docs/development.md#linux-wayland-and-x11)).
### Use it from Claude Code and other agents
@@ -238,8 +242,9 @@ Pathfinder and Shape Builder, paint, gradients, appearance and transparency, typ
files (SVG, PDF and PDF-compatible `.ai` with PDF/X, legacy version 7 `.ai` keeping layers, groups and type, EPS, DXF, EMF/WMF, raster formats, PSD out and PSD/PSB in as their merged image, 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
+and masks, text with each paragraph's indents, spacing and leading, tables (as text frames and lines), master
+pages, shadows, glows, outlines and overlays, embedded Affinity documents and images, with what didn't come in
+(adjustments, blurs, bevels, brushes…) 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. Current `.af` validation includes 33 pinned files, native save/reload
and every-board SVG/PDF/PSD export, with fixes for Affinity 3 artboards, source-backed JPEGs and text runs.
[Scope and limits](crates/affinity/README.md); [source audit and remaining gaps](docs/affinity-validation.md).
@@ -253,7 +258,7 @@ The scores are self-assessed from our code against public documentation;
- reliable exchange of .ai files (layer structure in real files; proprietary editing data isn't written);
- an interaction-fidelity pass covering every tool's modifiers and small behaviours;
- 3D and Materials beyond the initial live Revolve (Extrude & Bevel, Inflate, Rotate, materials);
-- most of the raster effects (9 of 57 still missing; Cutout, Film Grain, Neon Glow, Plastic Wrap, Poster Edges, Smudge Stick, Sponge and Watercolor are available under Artistic, Bas Relief, Chalk & Charcoal, Charcoal, Chrome, Graphic Pen, Halftone Pattern, Note Paper, Photocopy, Plaster, Reticulation, Stamp, Torn Edges and Water Paper under Sketch) and the Effect Gallery;
+- filter thumbnails and a preview area inside the Effect Gallery (the gallery itself and all 57 Photoshop-style raster filters, approximated, are in);
- CJK composition for vertical type (vertical type itself has initial support, with a Japanese interface);
- scripting, and the rest of Variables (image and graph kinds, dataset import);
- generative AI features.
diff --git a/ROADMAP.md b/ROADMAP.md
index 0033167071..54481f2d30 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -9,7 +9,7 @@
**Stage: alpha** · next: beta, ~13 points (ready for real work ~62% → ~75%, and reliable `.ai` exchange) and ~170–270 h away
-> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-22 · **Change:** minor (ruby (ふりがな) for live text: `type.ruby` sets or removes a reading over a byte range, above or below (right of the column in vertical type), aligned, sized and overhanging or squeezed; saved natively, laid out with line growth, drawn on the canvas and in SVG/PDF (outlines where ruby is present); headline numbers unchanged; previously:; 3D: original Standard, Diffuse, Top Left and Right lighting presets; command access, effective-setting recognition and preview/history; scores and estimates unchanged; Print: Japanese paper sizes in the Print dialog's Media list — JIS B4 257 × 364 mm, JIS B5 182 × 257 mm and JIS B6 128 × 182 mm beside the ISO B4/B5 (which keep their ISO 216 sizes), はがき, 往復はがき, 封筒 長形3号/長形4号/角形2号/角形3号 and 四六判; about 90 community PRs of 2026-10-19: Objects on Path, the Simplify slider, Pencil Edit Selected Paths in the middle of a path, Georgian, and more; Background Export progress dialog with Cancel, #2564; about 85 community PRs of 2026-10-18: Justification…, Word .docx placed as area type, CCITT Group 3 TIFF, Roman Hanging Punctuation, blend spines edited with the Anchor Point tool, shadows and glows in stack order, coloured 3D lights, a Dutch catalog completed; 3D lighting: one to ten colored lights, smooth colored Inflate, legacy white-light appearance preserved; surface batching and restored seam minimum; scores and estimates unchanged; about 145 community PRs of 2026-10-17: image-decode overflow guards, opaque floating panels, MCP export cancel and progress, editable Illustrator EPS import, scoped `doc_inspect`, Dutch, Danish and Indonesian, Simplified Chinese messages, screen-reader names; headline numbers unchanged; about 160 community PRs of 2026-10-15/16: PDF import crash fixes, Dimension tool, legacy `.ai` save, Intertwine, web pen input, Image Trace fixes, `.ai`/EPS/PDF import fidelity, Bulgarian, Greek, Swedish and Finnish catalogs; headline numbers unchanged) · **Target:** Adobe Illustrator 2026 (30.x)
+> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-23 · **Change:** minor (OpenType SVG colour fonts draw and export as vector art; previously: COLR colour fonts (v0 and v1) draw and export as vector art; previously: G2: the Effect Gallery shipped (#2883): Effect › Effect Gallery… browses the Artistic, Brush Strokes, Distort, Sketch, Stylize and Texture filters, edits each filter's settings, builds an ordered stack (add, reorder, hide, remove) with a live canvas preview, and OK applies it as separate appearance effects in one undo step; remaining: filter thumbnails and a preview area inside the dialog; G2 estimate 4–6 → 1–2 h; Raster effects 82% → 85% (power-user view 49% → 52%), estimated, a modest move because the named missing dialog landed without thumbnails or an in-dialog preview; previously: colour emoji fonts with bitmap glyphs (`sbix`, `CBDT`) draw and export; headline numbers unchanged; previously:; Affinity import AF.5: master pages, tables, paragraph formats, shadows, glows, outlines, overlays and embedded documents; ruby (ふりがな) for live text: `type.ruby` sets or removes a reading over a byte range, above or below (right of the column in vertical type), aligned, sized and overhanging or squeezed; saved natively, laid out with line growth, drawn on the canvas and in SVG/PDF (outlines where ruby is present); headline numbers unchanged; previously:; 3D: original Standard, Diffuse, Top Left and Right lighting presets; command access, effective-setting recognition and preview/history; scores and estimates unchanged; Print: Japanese paper sizes in the Print dialog's Media list — JIS B4 257 × 364 mm, JIS B5 182 × 257 mm and JIS B6 128 × 182 mm beside the ISO B4/B5 (which keep their ISO 216 sizes), はがき, 往復はがき, 封筒 長形3号/長形4号/角形2号/角形3号 and 四六判; about 90 community PRs of 2026-10-19: Objects on Path, the Simplify slider, Pencil Edit Selected Paths in the middle of a path, Georgian, and more; Background Export progress dialog with Cancel, #2564; about 85 community PRs of 2026-10-18: Justification…, Word .docx placed as area type, CCITT Group 3 TIFF, Roman Hanging Punctuation, blend spines edited with the Anchor Point tool, shadows and glows in stack order, coloured 3D lights, a Dutch catalog completed; 3D lighting: one to ten colored lights, smooth colored Inflate, legacy white-light appearance preserved; surface batching and restored seam minimum; scores and estimates unchanged; about 145 community PRs of 2026-10-17: image-decode overflow guards, opaque floating panels, MCP export cancel and progress, editable Illustrator EPS import, scoped `doc_inspect`, Dutch, Danish and Indonesian, Simplified Chinese messages, screen-reader names; headline numbers unchanged; about 160 community PRs of 2026-10-15/16: PDF import crash fixes, Dimension tool, legacy `.ai` save, Intertwine, web pen input, Image Trace fixes, `.ai`/EPS/PDF import fidelity, Bulgarian, Greek, Swedish and Finnish catalogs; headline numbers unchanged) · **Target:** Adobe Illustrator 2026 (30.x)
VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adobe Illustrator workflow. It runs
on macOS, Windows, Linux, FreeBSD and the web (WASM), and agents can drive all of it over MCP, the CLI and a JSON
@@ -29,7 +29,7 @@ blocking it ([Alpha gate](docs/roadmap.md#alpha-gate)).
| | Value | Kind |
|---|---|---|
-| **Feature breadth** (Illustrator's menu items, tools, effects, formats exist) | **~88%** | measured in part: menu items 348/375 wired (92.8%), tools 89/92, Illustrator effects 46/50, Photoshop effects 54/57, 3D 4/4 (initial types, no materials) |
+| **Feature breadth** (Illustrator's menu items, tools, effects, formats exist) | **~88%** | measured in part: menu items 348/375 wired (92.8%), tools 89/92, Illustrator effects 46/50, Photoshop effects 57/57, 3D 4/4 (initial types, no materials) |
| **Feature depth** (weighted by use, scored by behaviour) | **~75%** | estimated |
| **To beta** | **~170–270 h** one agent · ~50–80 h with 4–6 agents | estimated |
| **To full parity** | **~360–590 h** one agent · ~95–165 h with 4–6 agents | estimated |
@@ -76,7 +76,7 @@ The dimension hours overlap (feature rows hold some UI, format and AI work), so
| Strokes, brushes, width profiles | 88% | 8–15 |
| Appearance, transparency, graphic styles, masks | 97% | 1–2 |
| Live vector effects | 85% | 6–10 |
-| Raster effects (Effect Gallery) — [effects-parity.md](docs/effects-parity.md) | 82% | 8–14 |
+| Raster effects (Effect Gallery) — [effects-parity.md](docs/effects-parity.md) | 85% | 1–2 |
| 3D and Materials | ~25% | 30–55 |
| Type core — [type-parity.md](docs/type-parity.md) | 80% | 14–19 |
| Type advanced (CJK, spelling, Touch Type) | 50% | 20–28 |
@@ -123,12 +123,19 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
2. **`.ai` files from real users** (G9): layer structure, guides, speed: 10–20 h.
3. **Launch and stability on real machines** (G10): 20–35 h.
4. **Core-tool correctness** (G11: Shape Builder regions, Asset Export borders): 8–15 h.
-5. **Raster effects** (G2) alongside: the 10 remaining filters (7 Artistic, 2 Sketch, 1 more) and the Effect Gallery, 8–14 h.
+5. **Raster effects** (G2) alongside: the Effect Gallery's filter thumbnails and in-dialog preview area (the gallery and every Photoshop-style filter are in), 1–2 h.
6. **Then:** type core and advanced type (G4), the Illustrator 2026 additions (G13), 3D (G3).
## Progress log
+- 2026-10-23: OpenType SVG colour fonts draw as vector art: each glyph's SVG document is read by the SVG importer, in the text's colours where it asks for them, and draws, exports and outlines as COLR glyphs do; all colour font formats are now drawn.
+- 2026-10-23: COLR colour fonts (v0 and v1, as in Noto Color Emoji's vector build, Segoe UI Emoji, Nabla) draw as vector art: their layers' colours, gradients, clips and blend modes on the canvas and in SVG, EPS, legacy `.ai` and PDF, and as editable paths with Create Outlines; glyphs using sweep gradients or compositing modes are drawn as images of the glyph.
+- 2026-10-22: The Effect Gallery shipped (#2883): Effect › Effect Gallery… browses the Artistic, Brush Strokes, Distort, Sketch, Stylize and Texture filters, edits each filter's settings, builds an ordered stack (add, reorder, hide, remove) with a live canvas preview, and OK applies it as separate appearance effects in one undo step. Filter thumbnails and a preview area inside the dialog remain ([Filter Gallery overview](https://helpx.adobe.com/photoshop/desktop/effects-filters/get-started-with-filters/filter-gallery.html)). Raster effects 82% → 85% (estimated); headline numbers unchanged.
+- 2026-10-22: Colour emoji fonts with bitmap glyphs draw and export: `sbix` (Apple Color Emoji, macOS's emoji font) and `CBDT` (bitmap Noto Color Emoji) glyphs show as their pictures on the canvas, whatever the type's fill, scale and turn with the type, and export to PDF (in the font's Type 3 glyphs, or as images), SVG (images when type is outlined; live text leaves emoji to the viewer), EPS and legacy `.ai` (images); Create Outlines turns them into embedded images. Fonts with bitmaps but no outlines, such as Noto Color Emoji, are now found among the installed fonts. COLR and OpenType SVG fonts remain; headline numbers unchanged.
+
+- 2026-10-22: Effect › Sketch › Conté Crayon: a black crayon in the dark areas and a white one in the light areas, on mid-grey paper whose texture (Brick, Burlap, Canvas, Sandstone; Scaling, Relief, Light Direction, Invert) breaks the strokes, with Foreground Level and Background Level; an original approximation, defaults unverified. Every Photoshop-style filter is now in (57/57); the Effect Gallery remains (4–6 h).
- 2026-10-22: Ruby (ふりがな) for live text: `type.ruby` sets or removes a reading over a byte range of the selected type — above it in horizontal type, right of the column in vertical type (or below/left), start/centre/end aligned, at 1–100% of the base size (default half), overhanging or squeezed to the base width. It is saved in the native file, laid out with its line growing (following lines move on), drawn on the canvas, and written in SVG and PDF as outlines where ruby is present. UI panel and type on a path are next. Headline numbers unchanged.
+- 2026-10-22: PDF accessibility: titled exports set `/ViewerPreferences << /DisplayDocTitle true >>`, so viewers show the document title rather than the file name and title checks can pass (#3646). Headline numbers unchanged.
- 2026-10-14: Document fonts register every explicitly supplied craft-fonts family after the existing Japanese, Arabic and Thai prefix; optional empty input remains supported. Headline scores and estimates are unchanged.
@@ -142,6 +149,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
| 2026-10-18 | Exported and saved files can repeat their bytes: PNG, PDF, EPS, legacy `.ai`, packaged zips and `.vectorcraft` saves recorded the wall-clock time they were made in, so the same commands run twice gave different bytes though the pixels matched. `SOURCE_DATE_EPOCH` now stands in for the clock in everything a file records, as the reproducible-builds specification defines it; a date a command is given still wins, and a malformed value is ignored rather than refusing the export. The recovery heartbeat and the seed PDF encryption draws on keep the real clock, so a password-protected PDF still differs between runs (#2880). Headline numbers unchanged. |
| 2026-10-18 | About 85 community PRs landed in two batches through the full gate, with our fixes on top. New: Word `.docx` files place as area type with their formatting (#2766), CCITT Group 3 TIFF files open (#2770), Paragraph panel menu › Roman Hanging Punctuation (#2775), the Anchor Point tool edits blend spine points and handles (#2643, fixes #2544), shadows and glows each draw from the art with the effects before them, without the old exponential cost (#2395), one to ten coloured lights in 3D effects (#2706), Artboard Options X and Y with a reference point (#2739), more Contextual Task Bar actions (#2471), Optical Margin Alignment for a whole thread (#2773), History panel Step Backward/Forward and Set History Limit (#2764), Edit › Undo and Redo name the step as the History panel does (#2774), bounding-box handles snap to the grid, pixels and guides (#2715), Ctrl/Cmd+A in the Artboards panel (#2761), Tabs panel menu items (#2742), Import Data Sets defines variables from header cells (#2736), a Linux option to use X11 when a pen is attached (#2717). Fidelity and robustness: variable fonts named by their default weight and fallback glyphs keep bold and italic (#2733, #2732), legacy `.ai` layer names in Windows Latin-1 (#2722), WMF window mapping (#2721), Magic Wand inside isolation (#2720), type values out of range in files are clamped (#2728, #2757), raster effects stay responsive in drags (#2745), exports and Save for Web report undecodable images (#2762, #2737, #2684), Windows-safe exported file names (#2738), a marquee skips a Shaper Group's originals (#2772). Second batch: an export progress dialog with Cancel on the shared cancel token (#2564), CMYK gradient meshes drawn several times faster within a 16 MB cap (#2802), Paragraph panel menu › Justification… with file values clamped (#2771), Edit › Clear History (#2843), SVG image links keep their spelling (#2837, fixes main's Windows test failures), the Linux save dialog through the XDG portal (#2783), RGB input stored as CMYK in CMYK documents (#2812), legacy `.ai` export of images and radial highlights (#2801, #2807), `.ai` import notes for damaged editing data, page sizes and variable libraries (#2799, #2800, #2842), PDF and `.ai` keep their creation date (#2838), undecodable images left out of PDF exports with a note (#2790), MCP input waits for queue room (#2776), slice, snapping, selection, type and accessibility fixes (#2794–#2797, #2805, #2806, #2809, #2815, #2844–#2846), dropdowns close after a keyboard pick (#2824), plug-in dialogs scroll (#2840). Languages: the Dutch catalog completed (#2730). Headline numbers unchanged (estimated). |
| 2026-10-19 | About 90 community PRs landed in batches through the full gate, with our fixes on top (formatting, catalog rows, small correctness fixes). New: Objects on Path (#3066), Object › Path › Simplify's slider with Auto-Simplify and More Options (#2555), Pencil Edit Selected Paths redraws the middle of a selected path (#2905), Pencil Tool Options' Alt key toggles to Smooth Tool (#2685), 3D solids built from each stroke's outline (#3049), Live Paint Selection Tool Options (#3052), Locate Selected Objects in the Layers panel (#3033), Snap to Unit for tab stops (#3039), DXF circles and arcs as native entities (#2962), Targa files (#2765), a Georgian interface (#2045), Traditional Chinese status and error messages (#2784), the web page's `window.vectorcraft` control channel (#2943), `select.color` (#2939), reproducible export bytes with `SOURCE_DATE_EPOCH` (#2947), Spacing Guides on resizes (#2966) and measurement labels on more tools. Fixed: number fields step to the next whole unit (#2916), a click away from edited type makes no new text (#2922), inch rulers in halves (#2951), Recent cards in New Document (#2904), Japanese W-weights in SVG (#2896), the point-type baseline marker (#2897) and the Reshape tool's falloff (#2900). Headline numbers unchanged. |
+| 2026-10-21 | Affinity import (AF.5), brought over from DesignCraft's (storytold/designcraft#291): master pages show on the pages that use them (a locked layer at the bottom); tables open as a text frame per cell and a line per edge; each paragraph keeps its alignment, indents, spacing and leading; frame text takes its text scale, not its frame's; drop shadows and outer glows become live effects, outlines strokes, colour and gradient overlays are baked into the paint; embedded Affinity documents open as editable content, and their artboards no longer become artboards; large pixel layers come in at a reduced resolution; text placed as Affinity places it (lines of differently aligned paragraphs, a frame's first baseline at cap height, last lines whose descenders hang out of the frame), underlines and strikethrough, line breaks inside paragraphs, table cells taller than their row, no stroke on shapes whose stroke style is None, CMYK pixel layers (phone photos in CMYK documents) shown through the document's own CMYK profile instead of the profile-free formula and its blue cast, outlines on stroked shapes. Headline numbers unchanged. Hostile files stay bounded (one budget for the whole read, embedded documents included; overlay work; master page copies), covered by the import fuzzer and limit tests. |
| 2026-10-17 | Background Export shows a progress dialog: the file being exported, the artboard count and a bar, Cancel (Esc) and Continue in Background. It runs on the shared cancel token of #2546, so a cancelled export writes no file and keeps no half-drawn pattern tile or effect raster; translated in every language with complete menus (#2564). Headline numbers unchanged. |
| 2026-10-17 | About 145 community PRs landed in six batches, each through the full gate, plus our fixes on top. Crashes and hostile input: an image's RGBA size is checked from its header before decoding, without overflowing, in the renderer, sampling, recoloring and Crop Image (#2442, #2468, #2407), PDF Add Around and huge art are clamped (#2440), graph axis labels past i64, `+` in hex colours and XML ids are handled (#2610, #2470, #2447), Document Raster Effects resolutions open in range (#2579), Batch names stay in their folder (#2504). Regressions: floating panel groups are opaque again while the docked card keeps its rounded corners (#2499), the Wayland pointer returns over panels (#2502). New: MCP cancels long exports, answers while one runs and reports progress (#2546), `doc_inspect` takes ids, kind and paging (#2543), raster export of a page rectangle (#2511), `text.create` returns bounds (#2478), PDF presets and ICC profiles persist (#2547), screen-reader names for widgets (#2611), Expand on Intertwine (#2622, fixes #2540), Duplicate/Copy/Cut of several artboards (#2567), print presets by name (#2607), TSV data sets (#2608), planar TIFF (#2598), Alt-click a swatch onto a gradient stop (#2623), Shift-click ranges in Links, Graphic Styles and Libraries (#2612, #2613, #2618), Space+Shift rotates the view (#2601), Presentation Mode keys (#2583), Small Caps and super/subscript buttons (#2508). Fidelity: editable vector art from Illustrator EPS (#2571), `.ai` Drop Shadow Darkness (#2513), overprint preview with Darken (#2514), Generic CMYK black round-trips (#2503), PNG sRGB chunk (#2519), kerning at a caret (#2518), tab widths in justified area type (#2487), Transform copies keep their own gradients (#2486), smooth Zig Zag (#2475), Live Corners round up to their neighbours (#2484), kerning across style runs (#2554), SVG letter spacing on justified lines (#2574), Dimension tool snapping (#2482), gradient chips (#2495), Transform panel flips and percentages (#2400, #2404). Later the same day: PostScript `.ps` and `.epsf` files open (#2461), EPS images with CCITTFax compression draw (#2445), Illustrator 3 EPS without layers (#2436), `.ai` type opacity and blend modes (#2420), envelope meshes and compound holes in `.ai` (#2410, #2444), CMYK image soft masks in PDF export (#2448), Show Transparency Grid saved with the document (#2488), Save Selection in the Layers panel menu (#2483), Character and Paragraph Reset Panel (#2479, #2438), Cmd/Ctrl+Shift double-click releases a guide (#2467), Shift+Enter keeps a field active (#2431), Shift keeps reshaped handles perpendicular (#2425), emptied type keeps its style (#2464), Smart Blur radius (#2443), freeform gradients recolour (#2397), mesh slivers (#2456), Recolor wheel handles in CMYK (#2454), and six Image Trace fixes (#2387, #2584, #2586–#2589). Fifth batch: Optical Margin Alignment (#2563), Window › Blend panel (#2573), graph column designs (#2406), Live Paint Gap Options (#2424), the SVG Interactivity panel (#2437), RTF placed as area type (#2524), the Touch Type tool (#2469), pattern fills expand into clipped tiles (#2616), Save and Export ask before replacing a file an added extension names (#2619), the Artboard tool's Control bar and Contextual Task Bar (#2559, #2556), Alt-click New Artboard for its options (#2496), Shift-click in Brushes (#2562), the Move dialog remembers the last move (#2542), PDF export uses the document's assigned profiles (#2536), Printer Setup opens the selected printer's preferences on Windows (#2577). Sixth batch: Effect › Artistic › Cutout, Neon Glow and Poster Edges (#2453), View › Rulers › Change to Global / Artboard Rulers (#2416), Symbol Options 9-slice guides (#2512), Create Gradient Mesh on an embedded image (#2538), Rotate View cursors and the Mac trackpad rotation gesture (#2594, #2644), choice parameters as dropdowns in the inline effect editor (#2582), Group Selection picks and moves one path of a compound path (part of #2441), Shift-click ranges in the Artboards panel (#2626), Lock Variables (#2631), a layer dropped under the last row goes to the bottom (#2632), and robustness work: huge selections draw bounded overlays (#2635, #2645, part of #2460), values out of range in presets and files are clamped (#2656), whole-number checks for counts (#2638, #2659), exports warn about overset type (#2628), symbol instances measured by their art (#2614), colour-managed Eyedropper in CMYK documents (#2664). Later: Effect › Rasterize (#2409), variable-font axis sliders in the Character panel (#2710), Image Trace Create Strokes on an exact distance transform with Guo–Hall thinning and a skeleton graph (#2703–#2705), Auto Color keeps rare colours (#2702), large images trace with a warning (#2700), a 1e9 pt input bound on Reshape Segment, Convert Anchor Point and the Pencil (#2709), task-bar Connect, Corner and Smooth for selected anchors (#2697), PDF 0 w strokes import as hairlines (#2696), threading text from the out port (#2713, part of #2572), a panel per swatch library with Persistent (#2714, #2603), installed plug-ins kept across restarts (#2695, #2541). Languages: Dutch, Danish and Indonesian complete (#2393), Simplified Chinese status and error messages (#2578), translated file filters and presets (#2590). Headline numbers unchanged (estimated). |
| 2026-10-16 | Symbol Options › Export Type (Graphic or Movie Clip, default Movie Clip) with Registration; `symbol.options` / `symbol.list` (G5).
@@ -189,6 +197,11 @@ The full pre-standard record of what landed is kept in [docs/roadmap.md](docs/ro
| Date | Change | Summary |
|---|---|---|
+| 2026-10-23 | minor | Progress log row for OpenType SVG colour fonts; headline numbers unchanged. |
+| 2026-10-23 | minor | Progress log row for COLR colour fonts; headline numbers unchanged. |
+| 2026-10-22 | minor | G2: the Effect Gallery shipped (#2883): Effect › Effect Gallery… browses the Artistic, Brush Strokes, Distort, Sketch, Stylize and Texture filters, edits each filter's settings, builds an ordered stack (add, reorder, hide, remove) with a live canvas preview, and OK applies it as separate appearance effects in one undo step; remaining: filter thumbnails and a preview area inside the dialog; G2 estimate 4–6 → 1–2 h; Raster effects 82% → 85% (power-user view 49% → 52%), estimated, a modest move because the named missing dialog landed without thumbnails or an in-dialog preview. |
+| 2026-10-22 | minor | Progress log row for colour emoji fonts with bitmap glyphs; headline numbers unchanged. |
+| 2026-10-22 | minor | Effects: Sketch › Conté Crayon; measured Photoshop-style filters 57/57, the Effect Gallery remains (G2 estimate 4–6 h). |
| 2026-10-21 | minor | 3D: original Standard, Diffuse, Top Left and Right lighting presets; command access, effective-setting recognition and preview/history; scores and estimates unchanged |
| 2026-10-21 | minor | Print: Japanese paper sizes in the Print dialog's Media list (JIS B4/B5/B6, はがき, 往復はがき, 封筒 長形3号/長形4号/角形2号/角形3号, 四六判); ISO B4/B5 keep their sizes, and a paper is named by id or label, any case and spacing. Headline numbers unchanged. |
| 2026-10-17 | minor | Colored Inflate: shared membrane normals and smooth RGB vector ramps replace flat polygon bands; channel groups are batched per solid-fill surface. White-light Inflate retains its original polygons, paint composition and seam joins; the 0.05 seam minimum is restored. Scores and hour estimates unchanged. |
diff --git a/apps/vectorcraft-cli/src/main.rs b/apps/vectorcraft-cli/src/main.rs
index d3d94870a9..10a859ac5a 100644
--- a/apps/vectorcraft-cli/src/main.rs
+++ b/apps/vectorcraft-cli/src/main.rs
@@ -1,8 +1,8 @@
//! `vectorcraft-cli`: VectorCraft from the command line.
//!
//! ```text
-//! vectorcraft-cli mcp [--connect 127.0.0.1:7979 | --headless] [--automation-read-root DIR] [--automation-write-root DIR]
-//! vectorcraft-cli run [--in FILE] [--cmd id [--params '{json}']]... [--export out.svg]... [--scale 2]
+//! vectorcraft-cli mcp [--connect 127.0.0.1:7979 | --headless] [--automation-read-root DIR]... [--automation-write-root DIR]...
+//! vectorcraft-cli run [--in FILE] [--cmd id [--params '{json}'] | --commands FILE|-]... [--export out.svg]... [--scale 2]
//! vectorcraft-cli commands
//! vectorcraft-cli convert IN OUT [--scale 2] [--artboard 0 | --range 1-3,5] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit]
//! vectorcraft-cli info FILE
@@ -68,19 +68,24 @@ const USAGE: &str = "\
vectorcraft-cli — VectorCraft automation
USAGE:
- vectorcraft-cli mcp [--connect ADDR | --headless] [--automation-read-root DIR] [--automation-write-root DIR]
+ vectorcraft-cli mcp [--connect ADDR | --headless] [--automation-read-root DIR]... [--automation-write-root DIR]...
Run the MCP server on stdio. Default: connect to a running app at 127.0.0.1:7979
(vectorcraft --control 7979), falling back to a headless in-process session.
--automation-read-root / --automation-write-root confine the files the agent's commands read
(open, place, relink, library loads…) and write (save, export, package, library saves…) to
- DIR, links followed; a root left out grants none of its access. They imply --headless: a
- running app enforces its own (vectorcraft --control PORT --automation-read-root DIR …).
+ DIR, links followed; each may be given more than once, a path inside any of its folders being
+ allowed, and a kind left out grants none of its access. They imply --headless: a running app
+ enforces its own (vectorcraft --control PORT --automation-read-root DIR …).
- vectorcraft-cli run [--in FILE] [--cmd ID [--params JSON]]... [--export FILE]... [--scale N]
+ vectorcraft-cli run [--in FILE] [--cmd ID [--params JSON] | --commands FILE|-]... [--export FILE]... [--scale N]
Headless batch: open FILE (any readable format) or start a new document, run commands in
order, export each FILE in the format its extension picks (see Writable formats; a .ait FILE
is a template, written as file.saveAsTemplate writes it). --scale sizes raster exports
(pixels per point, default 1); other formats leave it out. Prints one JSON result per step.
+ --commands reads steps from FILE, or from standard input for -, where it stands among the
+ --cmd and --export steps: a JSON array of {\"command\": ID, \"params\": {...}} (or \"id\" for
+ \"command\"), or one such object per line (JSON Lines), at most 64 MiB and 100000 steps.
+ Errors name the step, counting from 0 as \"$N\" references do.
vectorcraft-cli commands
Print the command catalogue as JSON.
@@ -177,7 +182,7 @@ fn with_stores(mut h: Headless) -> Headless {
fn mcp(args: &[String]) -> Result<(), String> {
let mut connect: Option = None;
let mut headless = false;
- let (mut read_root, mut write_root): (Option, Option) = (None, None);
+ let (mut read_roots, mut write_roots): (Vec, Vec) = (vec![], vec![]);
let mut it = args.iter();
while let Some(a) = it.next() {
// The roots also come as `--flag=DIR`, as the other Craft apps take them.
@@ -190,10 +195,7 @@ fn mcp(args: &[String]) -> Result<(), String> {
"--headless" => headless = true,
"--automation-read-root" | "--automation-write-root" => {
let dir = inline.or_else(|| it.next().cloned()).ok_or_else(|| format!("{flag} needs a folder"))?;
- let slot = if flag == "--automation-read-root" { &mut read_root } else { &mut write_root };
- if slot.replace(dir).is_some() {
- return Err(format!("{flag} is given twice: it takes one folder"));
- }
+ if flag == "--automation-read-root" { read_roots.push(dir) } else { write_roots.push(dir) }
}
other => return Err(format!("unknown mcp option `{other}`")),
}
@@ -201,7 +203,9 @@ fn mcp(args: &[String]) -> Result<(), String> {
if headless && connect.is_some() {
return Err("use either --connect or --headless".into());
}
- let roots = AutomationRoots::new(read_root.as_deref().map(Path::new), write_root.as_deref().map(Path::new))?;
+ let read: Vec<&Path> = read_roots.iter().map(Path::new).collect();
+ let write: Vec<&Path> = write_roots.iter().map(Path::new).collect();
+ let roots = AutomationRoots::new(&read, &write)?;
if roots.is_some() && connect.is_some() {
return Err("--automation-read-root and --automation-write-root confine the headless server; a running app enforces its own roots: start it with `vectorcraft --control --automation-read-root --automation-write-root `"
.into());
@@ -209,8 +213,7 @@ fn mcp(args: &[String]) -> Result<(), String> {
let backend: Box = if let Some(roots) = roots {
// Every thread of this process, not only the server's: nothing reaches past the roots.
file_access::confine_process(roots.clone());
- let show = |root: Option<&Path>| root.map_or_else(|| "none".to_string(), |r| r.display().to_string());
- eprintln!("vectorcraft-cli: files confined: read root {}, write root {}", show(roots.read_root()), show(roots.write_root()));
+ eprintln!("vectorcraft-cli: files confined: {}", roots.describe());
Box::new(Headless::with_document().with_automation_roots(Some(roots)))
} else if headless {
Box::new(with_stores(Headless::with_document()))
@@ -338,28 +341,127 @@ enum Step {
Export(String),
}
+/// Most bytes `run --commands` reads from a file or standard input: the steps are untrusted input.
+const MAX_COMMANDS_BYTES: u64 = 64 * 1024 * 1024;
+/// Most steps one `run --commands` takes.
+const MAX_COMMANDS_STEPS: usize = 100_000;
+
+/// The text of `--commands source`: the file `source`, or standard input for `-`, refused past
+/// [`MAX_COMMANDS_BYTES`].
+fn read_commands(source: &str) -> Result {
+ use std::io::Read;
+ let mut bytes = vec![];
+ let read = if source == "-" {
+ std::io::stdin().lock().take(MAX_COMMANDS_BYTES + 1).read_to_end(&mut bytes)
+ } else {
+ std::fs::File::open(source).and_then(|f| f.take(MAX_COMMANDS_BYTES + 1).read_to_end(&mut bytes))
+ };
+ read.map_err(|e| format!("--commands {source}: {e}"))?;
+ if bytes.len() as u64 > MAX_COMMANDS_BYTES {
+ return Err(format!("--commands {source}: more than {} MiB of steps", MAX_COMMANDS_BYTES / (1024 * 1024)));
+ }
+ String::from_utf8(bytes).map_err(|_| format!("--commands {source}: not UTF-8 text"))
+}
+
+/// The steps of `--commands source` from its `text`: a JSON array of `{"command": ID, "params":
+/// {…}}` objects (`"id"` may stand for `"command"`, as in MCP's `command_batch`), or one such object
+/// per line (JSON Lines, blank lines skipped). `first` is the run's index of the first of them
+/// (the `N` of `"$N"`), which an error names with the entry's place in the text.
+fn parse_commands(source: &str, text: &str, first: usize) -> Result, String> {
+ // Notepad on Windows starts UTF-8 files with a byte order mark.
+ let text = text.strip_prefix('\u{feff}').unwrap_or(text);
+ let too_many = || format!("--commands {source}: more than {MAX_COMMANDS_STEPS} steps");
+ // Each entry with where it is in the text: its line for JSON Lines.
+ let mut entries: Vec<(Option, Value)> = vec![];
+ if text.trim_start().starts_with('[') {
+ let v: Value = serde_json::from_str(text).map_err(|e| format!("--commands {source}: {e}"))?;
+ let Value::Array(items) = v else { return Err(format!("--commands {source}: not a JSON array")) };
+ if items.len() > MAX_COMMANDS_STEPS {
+ return Err(too_many());
+ }
+ entries.extend(items.into_iter().map(|v| (None, v)));
+ } else {
+ for (n, line) in text.lines().enumerate().filter(|(_, l)| !l.trim().is_empty()) {
+ if entries.len() == MAX_COMMANDS_STEPS {
+ return Err(too_many());
+ }
+ let v = serde_json::from_str(line).map_err(|e| format!("--commands {source}: step {} (line {}): {e}", first + entries.len(), n + 1))?;
+ entries.push((Some(n + 1), v));
+ }
+ }
+ entries
+ .into_iter()
+ .enumerate()
+ .map(|(k, (line, v))| {
+ command_step(v).map_err(|e| {
+ let place = line.map_or_else(|| format!("entry {}", k + 1), |l| format!("line {l}"));
+ format!("--commands {source}: step {} ({place}): {e}", first + k)
+ })
+ })
+ .collect()
+}
+
+/// The step of one `--commands` entry, `{"command": ID, "params": {…}}`.
+fn command_step(v: Value) -> Result {
+ let Value::Object(mut o) = v else { return Err("a step must be an object such as {\"command\": \"select.all\", \"params\": {}}".into()) };
+ let id = match (o.remove("command"), o.remove("id")) {
+ (Some(Value::String(id)), None) | (None, Some(Value::String(id))) => id,
+ (Some(_), Some(_)) => return Err("give `command` or `id`, not both".into()),
+ (None, None) => return Err("no `command`".into()),
+ _ => return Err("`command` must be a string, a command id".into()),
+ };
+ let params = match o.remove("params") {
+ None | Some(Value::Null) => json!({}),
+ Some(p @ Value::Object(_)) => p,
+ Some(_) => return Err(format!("`params` of {id} must be a JSON object")),
+ };
+ if let Some(key) = o.keys().next() {
+ return Err(format!("unknown key `{key}`: a step has `command` (or `id`) and `params`"));
+ }
+ Ok(Step::Cmd(id, params))
+}
+
fn run(args: &[String]) -> Result<(), String> {
let mut input: Option = None;
let mut steps: Vec = vec![];
+ // The step of the `--cmd` just given, which a `--params` sets.
+ let mut params_for: Option = None;
+ let mut stdin_read = false;
let mut scale = 1.0;
let mut it = args.iter();
while let Some(a) = it.next() {
let mut val = |what: &str| it.next().cloned().ok_or_else(|| format!("{a} needs {what}"));
match a.as_str() {
"--in" | "-i" => input = Some(val("a file")?),
- "--cmd" | "-c" => steps.push(Step::Cmd(val("a command id")?, json!({}))),
+ "--cmd" | "-c" => {
+ steps.push(Step::Cmd(val("a command id")?, json!({})));
+ params_for = Some(steps.len() - 1);
+ }
"--params" | "-p" => {
let raw = val("JSON")?;
let p: Value = serde_json::from_str(&raw).map_err(|e| format!("--params {raw}: {e}"))?;
if !p.is_object() {
return Err(format!("--params must be a JSON object, got {raw}"));
}
- match steps.last_mut() {
+ match params_for.and_then(|i| steps.get_mut(i)) {
Some(Step::Cmd(_, params)) => *params = p,
_ => return Err("--params must follow a --cmd".into()),
}
}
- "--export" | "-o" => steps.push(Step::Export(val("a file")?)),
+ "--commands" => {
+ let source = val("a file, or - for standard input")?;
+ if source == "-" && std::mem::replace(&mut stdin_read, true) {
+ return Err("--commands - is given twice: standard input is read once".into());
+ }
+ let text = read_commands(&source)?;
+ let read = parse_commands(&source, &text, steps.len())?;
+ steps.extend(read);
+ params_for = None;
+ }
+ "--export" | "-o" => {
+ steps.push(Step::Export(val("a file")?));
+ params_for = None;
+ }
"--scale" | "-s" => {
let raw = val("a number")?;
scale = raw.parse::().map_err(|_| format!("--scale {raw}: not a number"))?;
@@ -394,10 +496,12 @@ fn run(args: &[String]) -> Result<(), String> {
// Each step's result, for later steps to refer to (`"$1.id"`, see `vectorcraft_engine::steps`).
let mut results = vec![];
for step in steps {
+ // The step's index, as `"$N"` names its result.
+ let n = results.len();
let r = match step {
Step::Cmd(id, params) => {
- let params = vectorcraft_engine::steps::resolve(¶ms, &results).map_err(|e| format!("{id}: {e}"))?;
- let r = h.call("engine.execute", json!({"command": id, "params": params})).map_err(|e| format!("{id}: {e}"))?;
+ let params = vectorcraft_engine::steps::resolve(¶ms, &results).map_err(|e| format!("step {n} ({id}): {e}"))?;
+ let r = h.call("engine.execute", json!({"command": id, "params": params})).map_err(|e| format!("step {n} ({id}): {e}"))?;
emit(json!({"step": "cmd", "command": id, "result": r}))?;
r
}
@@ -407,7 +511,7 @@ fn run(args: &[String]) -> Result<(), String> {
} else {
h.call("app.export", with_pixel_scale(json!({"path": path}), &path, scale))
};
- let r = r.map_err(|e| format!("export {path}: {e}"))?;
+ let r = r.map_err(|e| format!("step {n}: export {path}: {e}"))?;
emit(json!({"step": "export", "result": r}))?;
r
}
diff --git a/apps/vectorcraft-cli/src/perf.rs b/apps/vectorcraft-cli/src/perf.rs
index 3aa1db6a44..ef6f299f31 100644
--- a/apps/vectorcraft-cli/src/perf.rs
+++ b/apps/vectorcraft-cli/src/perf.rs
@@ -23,13 +23,16 @@ impl Rng {
}
}
+/// The synthetic document's page, in points.
+const SYNTHETIC_PAGE: (f64, f64) = (1600.0, 1200.0);
+
/// `n` mixed paths (ellipses with strokes, translucent rectangles, stroked stars) on a 1600×1200 page.
pub fn synthetic(n: usize) -> Result {
- let mut d = Document::new(1600.0, 1200.0);
+ let mut d = Document::new(SYNTHETIC_PAGE.0, SYNTHETIC_PAGE.1);
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);
+ let (x, y, s) = (r.next() * SYNTHETIC_PAGE.0, r.next() * SYNTHETIC_PAGE.1, 3.0 + r.next() * 22.0);
let c = Color::rgb(r.next() as f32, r.next() as f32, r.next() as f32);
let id = d.alloc_id();
let mut node = match i % 3 {
@@ -296,6 +299,27 @@ fn deep(n: usize) -> Result<(), String> {
rows.push(("render 4 embedded 24 MP photos with 3 renderers (cold)".into(), ms));
note("after rendering the photos with 3 renderers");
}
+ // An SVG with one embedded picture opened from its text, as picture-heavy SVGs come: the
+ // importer's passes over the text before usvg reads it, most of which is the data URL. The
+ // picture is the synthetic page drawn at 1.25x (about 2 MB as a PNG; the row names its size);
+ // the hidden rectangle is a marker, so the prepass walks the tree as it does for a file that
+ // has one, instead of returning at its first check.
+ {
+ let k = 1.25;
+ let (w, h) = ((SYNTHETIC_PAGE.0 * k).round() as u32, (SYNTHETIC_PAGE.1 * k).round() as u32);
+ let photo = Renderer::new().render(&synthetic(3000)?, w, h, Affine::scale(k), &opts).to_png()?;
+ let data = vectorcraft_svg::base64_encode(&photo);
+ let svg = format!(
+ r#" "#
+ );
+ // One import checked first, so a failure is reported rather than timed; the same text
+ // imports the same way each time. Its document is kept for the memory reading.
+ let imported = vectorcraft_svg::import_with_report(&svg).map_err(|e| e.to_string())?;
+ let ms = median_ms(5, || drop(vectorcraft_svg::import_with_report(&svg)));
+ rows.push((format!("import SVG, one embedded {} KB PNG", photo.len() / 1024), ms));
+ note("after the import of an embedded picture");
+ drop(imported);
+ }
// Output hashes, to compare builds: the SVG export and a save → open → save round trip.
let fnv = |b: &[u8]| b.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, &x| (h ^ u64::from(x)).wrapping_mul(0x100_0000_01b3));
let doc = synthetic(n)?;
diff --git a/apps/vectorcraft-cli/tests/cli.rs b/apps/vectorcraft-cli/tests/cli.rs
index b376a139fd..e0d035e876 100644
--- a/apps/vectorcraft-cli/tests/cli.rs
+++ b/apps/vectorcraft-cli/tests/cli.rs
@@ -84,11 +84,125 @@ fn scale_sizes_raster_exports_only() {
fn run_reports_errors() {
let out = Command::new(BIN).args(["run", "--cmd", "nope.nothing"]).output().unwrap();
assert!(!out.status.success());
- assert!(String::from_utf8_lossy(&out.stderr).contains("nope.nothing"));
+ let stderr = String::from_utf8_lossy(&out.stderr).to_string();
+ assert!(stderr.contains("step 0 (nope.nothing)"), "{stderr}");
let out = Command::new(BIN).args(["run", "--params", "{}"]).output().unwrap();
assert!(!out.status.success());
}
+/// The JSON lines `run` printed.
+fn json_lines(stdout: &[u8]) -> Vec {
+ String::from_utf8_lossy(stdout).lines().map(|l| serde_json::from_str(l).unwrap()).collect()
+}
+
+/// #3147: `run --commands FILE` reads its steps from a JSON array (`command` or `id`), runs them
+/// where the option stands among `--cmd` and `--export`, and they count with those for `"$N"`; a
+/// placed file's `dataBase64` longer than a Windows command line holds fits.
+#[test]
+fn run_reads_steps_from_a_commands_file() {
+ let steps = tmp("steps.json");
+ let svg = tmp("steps.svg");
+ // Base64 of an SVG well past 32,767 characters, the most a Windows command line holds.
+ let padding = "x".repeat(40_000);
+ let placed = format!(
+ r##" "##
+ );
+ let data = vectorcraft_format::base64_encode(placed.as_bytes());
+ assert!(data.len() > 32_767);
+ let file = json!([
+ {"command": "shape.rectangle", "params": {"x": 10, "y": 10, "width": 50, "height": 30}},
+ {"command": "file.place", "params": {"name": "code.svg", "dataBase64": data}},
+ {"id": "object.setProps", "params": {"id": "$2.ids.0", "name": "barcode"}},
+ ]);
+ std::fs::write(&steps, serde_json::to_string_pretty(&file).unwrap()).unwrap();
+ let out = Command::new(BIN)
+ .args(["run", "--cmd", "file.new", "--params", r#"{"width":200,"height":100}"#, "--commands", steps.to_str().unwrap()])
+ .args(["--cmd", "document.node", "--params", r#"{"id":"$2.ids.0"}"#, "--export", svg.to_str().unwrap()])
+ .output()
+ .unwrap();
+ assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
+ let lines = json_lines(&out.stdout);
+ let ran: Vec<&str> = lines.iter().map(|l| l["command"].as_str().unwrap_or("export")).collect();
+ assert_eq!(ran, ["file.new", "shape.rectangle", "file.place", "object.setProps", "document.node", "export"]);
+ // `$2` in the file and in the `--cmd` after it is the placed art.
+ assert_eq!(lines[4]["result"]["name"], "barcode", "{}", lines[4]);
+ let written = std::fs::read_to_string(&svg).unwrap();
+ assert!(written.contains("118833") && written.contains("barcode"), "{written}");
+}
+
+/// `run --commands -` reads JSON Lines from standard input: a byte order mark, blank lines and
+/// CRLF line ends are fine, and the first step may be `file.new`.
+#[test]
+fn run_reads_json_lines_from_standard_input() {
+ let svg = tmp("stdin.svg");
+ let mut child = Command::new(BIN)
+ .args(["run", "--commands", "-", "--export", svg.to_str().unwrap()])
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .spawn()
+ .unwrap();
+ let text = "\u{feff}{\"command\":\"file.new\",\"params\":{\"width\":120,\"height\":80}}\n\n{\"command\":\"shape.ellipse\",\"params\":{\"x\":10,\"y\":10,\"width\":40,\"height\":30}}\r\n{\"id\":\"paint.setFill\",\"params\":{\"color\":\"#3366ff\"}}\n";
+ child.stdin.take().unwrap().write_all(text.as_bytes()).unwrap();
+ let out = child.wait_with_output().unwrap();
+ assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
+ let lines = json_lines(&out.stdout);
+ assert_eq!(lines.len(), 4);
+ assert_eq!(lines[0]["command"], "file.new");
+ assert!(std::fs::read_to_string(&svg).unwrap().contains("3366ff"));
+}
+
+/// Malformed `--commands` input stops the run before any step runs, naming the step (counted from
+/// 0 with the `--cmd` before it) and the entry or line; input past the size and step limits is
+/// refused; a step that fails names its number.
+#[test]
+fn run_refuses_malformed_commands_naming_the_step() {
+ let fails = |args: &[&str]| {
+ let out = Command::new(BIN).args(args).stdin(Stdio::null()).output().unwrap();
+ assert!(!out.status.success(), "{args:?}");
+ (String::from_utf8_lossy(&out.stderr).to_string(), json_lines(&out.stdout).len())
+ };
+ let bad = |name: &str, text: &[u8], wanted: &[&str]| {
+ let path = tmp(name);
+ std::fs::write(&path, text).unwrap();
+ let (e, printed) = fails(&["run", "--cmd", "file.new", "--commands", path.to_str().unwrap()]);
+ assert!(wanted.iter().all(|w| e.contains(w)), "{name}: {e}");
+ assert_eq!(printed, 0, "{name}: nothing runs");
+ };
+ bad("number.json", b"[1]", &["step 1 (entry 1)", "must be an object"]);
+ bad("both.json", br#"[{"command":"select.all"},{"command":"select.all","id":"select.none"}]"#, &["step 2 (entry 2)", "not both"]);
+ bad("no-command.json", br#"[{"params":{}}]"#, &["step 1 (entry 1)", "no `command`"]);
+ bad("id-number.json", br#"[{"command":3}]"#, &["`command` must be a string"]);
+ bad("params-array.json", br#"[{"command":"select.all","params":[1]}]"#, &["`params` of select.all must be a JSON object"]);
+ bad("typo.json", br#"[{"command":"select.all","param":{}}]"#, &["unknown key `param`"]);
+ bad("broken.json", b"[{\"command\":", &["--commands", "broken.json"]);
+ bad("lines.jsonl", b"{\"command\":\"select.all\"}\n\n{oops}\n", &["step 2 (line 3)"]);
+ bad("line-array.jsonl", b"{\"command\":\"select.all\"}\n[1]\n", &["step 2 (line 2)"]);
+ bad("latin1.json", b"[{\"command\":\"select.all\",\"params\":{\"name\":\"\xe9\"}}]", &["not UTF-8"]);
+ let many = "{\"command\":\"select.all\"}\n".repeat(100_001);
+ bad("many.jsonl", many.as_bytes(), &["more than 100000 steps"]);
+ // Past 64 MiB (a sparse file: nothing is written).
+ let huge = tmp("huge.json");
+ std::fs::File::create(&huge).unwrap().set_len(64 * 1024 * 1024 + 1).unwrap();
+ let (e, _) = fails(&["run", "--commands", huge.to_str().unwrap()]);
+ assert!(e.contains("more than 64 MiB"), "{e}");
+ let (e, _) = fails(&["run", "--commands", tmp("missing.json").to_str().unwrap()]);
+ assert!(e.contains("missing.json"), "{e}");
+ // `--params` sets the `--cmd` just before it, never a step of the file.
+ let ok = tmp("ok.json");
+ std::fs::write(&ok, br#"[{"command":"select.all"}]"#).unwrap();
+ let (e, _) = fails(&["run", "--cmd", "select.all", "--commands", ok.to_str().unwrap(), "--params", "{}"]);
+ assert!(e.contains("--params must follow a --cmd"), "{e}");
+ let (e, _) = fails(&["run", "--commands", "-", "--commands", "-"]);
+ assert!(e.contains("standard input is read once"), "{e}");
+ // A step that fails is named by its number, after the steps before it ran.
+ let failing = tmp("failing.json");
+ std::fs::write(&failing, br#"[{"command":"select.all"},{"command":"nope.nothing"}]"#).unwrap();
+ let (e, printed) = fails(&["run", "--cmd", "file.new", "--commands", failing.to_str().unwrap()]);
+ assert!(e.contains("step 2 (nope.nothing)"), "{e}");
+ assert_eq!(printed, 2);
+}
+
#[test]
fn mcp_headless_over_stdio() {
let mut child = Command::new(BIN).args(["mcp", "--headless"]).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null()).spawn().unwrap();
@@ -130,6 +244,58 @@ fn mcp_automation_roots_in_a_folder_an_earlier_run_left() {
automation_roots(&empty_dir(dir).join("roots"));
}
+/// #3546: each root flag may be given more than once: a path inside any of the read roots opens,
+/// one inside any of the write roots is written, and everything else, a write root's sibling read
+/// root included, is refused.
+#[test]
+fn mcp_automation_roots_take_several_folders() {
+ let base = tmp("several-roots");
+ for d in ["in", "in2", "out", "out2", "outside"] {
+ std::fs::create_dir_all(base.join(d)).unwrap();
+ }
+ let svg = r#" "#;
+ for f in ["in/a.svg", "in2/b.svg", "outside/c.svg"] {
+ std::fs::write(base.join(f), svg).unwrap();
+ }
+ let dir = |d: &str| base.join(d).to_string_lossy().into_owned();
+ let file = |d: &str, f: &str| base.join(d).join(f).to_string_lossy().into_owned();
+ let mut child = Command::new(BIN)
+ .args(["mcp", "--automation-read-root", &dir("in"), &format!("--automation-read-root={}", dir("in2"))])
+ .args(["--automation-write-root", &dir("out"), "--automation-write-root", &dir("out2")])
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .spawn()
+ .unwrap();
+ let call = |id: u64, name: &str, args: Value| json!({"jsonrpc":"2.0","id":id,"method":"tools/call","params":{"name":name,"arguments":args}});
+ let calls = [
+ (call(1, "open_file", json!({"path": file("in", "a.svg")})), false),
+ (call(2, "open_file", json!({"path": file("in2", "b.svg")})), false),
+ (call(3, "open_file", json!({"path": file("outside", "c.svg")})), true),
+ (call(4, "export", json!({"path": file("out", "a.png")})), false),
+ (call(5, "export", json!({"path": file("out2", "b.png")})), false),
+ (call(6, "export", json!({"path": file("outside", "c.png")})), true),
+ (call(7, "export", json!({"path": file("in2", "d.png")})), true),
+ (call(8, "open_file", json!({"path": file("out2", "b.png")})), true),
+ ];
+ {
+ let mut stdin = child.stdin.take().unwrap();
+ for (m, _) in &calls {
+ writeln!(stdin, "{m}").unwrap();
+ }
+ }
+ let out = child.wait_with_output().unwrap();
+ assert!(out.status.success());
+ let stderr = String::from_utf8_lossy(&out.stderr);
+ assert!(stderr.contains("files confined: read ") && stderr.contains("; write "), "{stderr}");
+ let replies: Vec = String::from_utf8(out.stdout).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect();
+ let errors: Vec = replies.iter().map(|r| r["result"]["isError"] == true).collect();
+ assert_eq!(errors, calls.iter().map(|(_, e)| *e).collect::>(), "{replies:?}");
+ assert!(replies[2]["result"]["content"][0]["text"].as_str().unwrap().contains("outside the read roots"), "{}", replies[2]);
+ assert!(base.join("out/a.png").is_file() && base.join("out2/b.png").is_file());
+ assert!(!base.join("outside/c.png").exists() && !base.join("in2/d.png").exists());
+}
+
fn automation_roots(base: &std::path::Path) {
for d in ["in", "out", "outside"] {
std::fs::create_dir_all(base.join(d)).unwrap();
@@ -153,7 +319,7 @@ fn automation_roots(base: &std::path::Path) {
assert!(!out.status.success() && err.contains(why), "{args:?}: {err}");
};
fails(&["mcp", "--automation-read-root", &dir("missing")], "cannot open the automation read root");
- fails(&["mcp", "--automation-read-root", &dir("in"), "--automation-read-root", &dir("out")], "given twice");
+ fails(&["mcp", "--automation-read-root", &dir("in"), "--automation-read-root", &dir("missing")], "cannot open the automation read root");
fails(&["mcp", "--automation-write-root"], "needs a folder");
fails(&["mcp", "--connect", "127.0.0.1:1", &format!("--automation-write-root={}", dir("out"))], "a running app enforces its own roots");
diff --git a/apps/vectorcraft/Cargo.toml b/apps/vectorcraft/Cargo.toml
index 196e1679c3..86235afbbc 100644
--- a/apps/vectorcraft/Cargo.toml
+++ b/apps/vectorcraft/Cargo.toml
@@ -51,8 +51,10 @@ winsafe = { version = "0.0.29", default-features = false, features = ["user"], o
# DirectWrite's system font collection (src/system_fonts.rs): fonts that font services such as
# Adobe Fonts load in place (#579). MIT OR Apache-2.0, already in the build through accesskit.
+# Win32_UI_WindowsAndMessaging has `MSG` and `WM_POINTERDOWN`, which src/windows_stylus.rs uses to
+# read a pen's barrel button from its pointer messages.
[target.'cfg(all(windows, not(target_vendor = "win7")))'.dependencies]
-windows = { version = "0.62", features = ["Win32_Graphics_DirectWrite"] }
+windows = { version = "0.62", features = ["Win32_Graphics_DirectWrite", "Win32_UI_WindowsAndMessaging"] }
[target.'cfg(target_os = "macos")'.dependencies]
# The macOS menu bar (src/mac_menu.rs): Tauri's menu crate, AppKit menus behind a safe API (no GTK
@@ -78,6 +80,10 @@ pollster = "1"
[target.'cfg(target_os = "linux")'.dependencies]
# GNOME/Wayland needs client-side window controls without a bundled title font.
winit = { version = "0.30", default-features = false, features = ["wayland-csd-adwaita-notitle"] }
+# A drawing tablet's pen pressure under X11 and XWayland (src/tablet.rs): XInput2 raw events on a
+# second X connection, x11rb's pure-Rust `RustConnection`. MIT OR Apache-2.0, already in the build
+# through winit with the `xinput` feature.
+x11rb = { version = "0.13", default-features = false, features = ["xinput"] }
# Asks the Wayland compositor which GPU it draws with (linux-dmabuf feedback, src/compositor_gpu.rs),
# so Automatic draws on that one. Both are already in the build through winit.
diff --git a/apps/vectorcraft/src/automation_args.rs b/apps/vectorcraft/src/automation_args.rs
index 26157b76d2..979f42e7bd 100644
--- a/apps/vectorcraft/src/automation_args.rs
+++ b/apps/vectorcraft/src/automation_args.rs
@@ -6,29 +6,29 @@ use std::ffi::OsString;
use std::path::PathBuf;
pub struct AutomationArgs {
- pub read_root: Option,
- pub write_root: Option,
+ pub read_roots: Vec,
+ pub write_roots: Vec,
read_given: bool,
write_given: bool,
}
impl AutomationArgs {
+ /// The roots the environment gives (`VECTORCRAFT_AUTOMATION_READ_ROOT` / `_WRITE_ROOT`), until
+ /// the command line gives its own.
pub fn new(read_root: Option, write_root: Option) -> Self {
- Self { read_root, write_root, read_given: false, write_given: false }
+ Self { read_roots: read_root.into_iter().collect(), write_roots: write_root.into_iter().collect(), read_given: false, write_given: false }
}
- /// Returns whether this argument is a root flag. CLI values override environment defaults
- /// once; a second occurrence is an error, including when the two spellings are mixed.
+ /// Returns whether this argument is a root flag. Each flag may be given more than once (#3546),
+ /// in either spelling: the first replaces the environment's root of its kind, the others add
+ /// folders.
pub fn consume(&mut self, arg: &str, args: &mut impl Iterator- ) -> Result
{
let (flag, inline) = arg.split_once('=').map_or((arg, None), |(flag, value)| (flag, Some(value)));
- let (root, given) = match flag {
- "--automation-read-root" => (&mut self.read_root, &mut self.read_given),
- "--automation-write-root" => (&mut self.write_root, &mut self.write_given),
+ let (roots, given) = match flag {
+ "--automation-read-root" => (&mut self.read_roots, &mut self.read_given),
+ "--automation-write-root" => (&mut self.write_roots, &mut self.write_given),
_ => return Ok(false),
};
- if *given {
- return Err(format!("{flag} given twice"));
- }
let value = match inline {
Some(value) => value.to_owned(),
None => {
@@ -42,8 +42,10 @@ impl AutomationArgs {
if value.is_empty() {
return Err(format!("{flag} needs a non-empty folder"));
}
- *root = Some(value.into());
- *given = true;
+ if !std::mem::replace(given, true) {
+ roots.clear();
+ }
+ roots.push(value.into());
Ok(true)
}
}
@@ -97,17 +99,24 @@ mod tests {
use super::*;
#[test]
- fn roots_override_environment_once_and_leave_other_arguments() {
- let mut roots = AutomationArgs::new(Some("environment".into()), None);
+ fn roots_override_environment_and_add_up() {
+ let mut roots = AutomationArgs::new(Some("environment".into()), Some("environment out".into()));
let mut args = ["a folder".to_owned(), "drawing.svg".to_owned()].into_iter();
assert!(roots.consume("--automation-read-root", &mut args).unwrap());
assert!(roots.consume("--automation-write-root=out", &mut args).unwrap());
assert!(!roots.consume("--in-window-menus", &mut args).unwrap());
- assert_eq!(roots.read_root, Some("a folder".into()));
- assert_eq!(roots.write_root, Some("out".into()));
+ assert_eq!(roots.read_roots, [PathBuf::from("a folder")]);
+ assert_eq!(roots.write_roots, [PathBuf::from("out")]);
assert_eq!(args.next().as_deref(), Some("drawing.svg"));
- assert!(roots.consume("--automation-read-root=other", &mut args).is_err());
- assert_eq!(roots.read_root, Some("a folder".into()));
+ // #3546: a flag given again adds a folder, in either spelling.
+ assert!(roots.consume("--automation-read-root=other", &mut args).unwrap());
+ assert!(roots.consume("--automation-write-root", &mut ["out2".to_owned()].into_iter()).unwrap());
+ assert_eq!(roots.read_roots, [PathBuf::from("a folder"), PathBuf::from("other")]);
+ assert_eq!(roots.write_roots, [PathBuf::from("out"), PathBuf::from("out2")]);
+ // A kind the command line leaves alone keeps the environment's root.
+ let mut roots = AutomationArgs::new(Some("environment".into()), Some("environment out".into()));
+ assert!(roots.consume("--automation-read-root=a", &mut std::iter::empty()).unwrap());
+ assert_eq!(roots.write_roots, [PathBuf::from("environment out")]);
}
#[test]
@@ -117,11 +126,15 @@ mod tests {
let mut roots = AutomationArgs::new(Some("read".into()), Some("write".into()));
let mut args = operand.map(str::to_owned).into_iter();
assert!(roots.consume(flag, &mut args).is_err(), "{flag} {operand:?}");
- assert_eq!(roots.read_root, Some("read".into()));
- assert_eq!(roots.write_root, Some("write".into()));
+ assert_eq!(roots.read_roots, [PathBuf::from("read")]);
+ assert_eq!(roots.write_roots, [PathBuf::from("write")]);
}
let mut roots = AutomationArgs::new(None, None);
assert!(roots.consume(&format!("{flag}="), &mut std::iter::empty()).is_err());
+ // A bad second folder is an error too, and keeps the first.
+ assert!(roots.consume(&format!("{flag}=first"), &mut std::iter::empty()).unwrap());
+ assert!(roots.consume(flag, &mut std::iter::empty()).is_err());
+ assert_eq!([roots.read_roots.len(), roots.write_roots.len()].iter().sum::(), 1);
}
}
@@ -130,8 +143,8 @@ mod tests {
let mut roots = AutomationArgs::new(None, None);
assert!(roots.consume("--automation-read-root=-folder", &mut std::iter::empty()).unwrap());
assert!(roots.consume("--automation-write-root", &mut ["./-folder".to_owned()].into_iter()).unwrap());
- assert_eq!(roots.read_root, Some("-folder".into()));
- assert_eq!(roots.write_root, Some("./-folder".into()));
+ assert_eq!(roots.read_roots, [PathBuf::from("-folder")]);
+ assert_eq!(roots.write_roots, [PathBuf::from("./-folder")]);
}
fn control(args: &[&str]) -> Result, String> {
diff --git a/apps/vectorcraft/src/linux_stylus.rs b/apps/vectorcraft/src/linux_stylus.rs
new file mode 100644
index 0000000000..f86a9cc536
--- /dev/null
+++ b/apps/vectorcraft/src/linux_stylus.rs
@@ -0,0 +1,116 @@
+//! Linux pen tablets: winit reports barrel buttons as [`winit::event::MouseButton::Other`]
+//! (for example `BTN_STYLUS`), and egui-winit drops those before they reach the UI (#3632).
+
+use eframe::AppCreator;
+use winit::application::ApplicationHandler;
+use winit::event::{DeviceEvent, DeviceId, StartCause, WindowEvent};
+use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop};
+use winit::window::WindowId;
+
+use eframe::UserEvent;
+
+/// `BTN_STYLUS` and neighbours (`linux/input-event-codes.h`): pen barrel buttons Wayland passes
+/// through the pointer protocol as non-standard mouse buttons.
+const BTN_STYLUS: u16 = 0x014b;
+const BTN_STYLUS2: u16 = 0x014c;
+const BTN_STYLUS3: u16 = 0x014d;
+
+/// Like [`eframe::run_native`], but turns pen barrel buttons into mouse buttons egui understands.
+pub fn run_native(app_name: &str, mut native_options: eframe::NativeOptions, app_creator: AppCreator<'_>) -> eframe::Result {
+ let mut builder = EventLoop::::with_user_event();
+ if let Some(hook) = native_options.event_loop_builder.take() {
+ hook(&mut builder);
+ }
+ let event_loop = builder.build().map_err(eframe::Error::WinitEventLoop)?;
+ event_loop.set_control_flow(ControlFlow::Poll);
+ let inner = eframe::create_native(app_name, native_options, app_creator, &event_loop);
+ let mut app = Forwarder { inner };
+ event_loop.run_app(&mut app).map_err(eframe::Error::WinitEventLoop)?;
+ Ok(())
+}
+
+struct Forwarder<'a> {
+ inner: eframe::EframeWinitApplication<'a>,
+}
+
+impl ApplicationHandler for Forwarder<'_> {
+ fn resumed(&mut self, event_loop: &ActiveEventLoop) {
+ self.inner.resumed(event_loop);
+ }
+
+ fn window_event(&mut self, event_loop: &ActiveEventLoop, window_id: WindowId, event: WindowEvent) {
+ self.inner.window_event(event_loop, window_id, map_window_event(event));
+ }
+
+ fn new_events(&mut self, event_loop: &ActiveEventLoop, cause: StartCause) {
+ self.inner.new_events(event_loop, cause);
+ }
+
+ fn user_event(&mut self, event_loop: &ActiveEventLoop, event: UserEvent) {
+ self.inner.user_event(event_loop, event);
+ }
+
+ fn device_event(&mut self, event_loop: &ActiveEventLoop, device_id: DeviceId, event: DeviceEvent) {
+ self.inner.device_event(event_loop, device_id, event);
+ }
+
+ fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
+ self.inner.about_to_wait(event_loop);
+ }
+
+ fn suspended(&mut self, event_loop: &ActiveEventLoop) {
+ self.inner.suspended(event_loop);
+ }
+
+ fn exiting(&mut self, event_loop: &ActiveEventLoop) {
+ self.inner.exiting(event_loop);
+ }
+
+ fn memory_warning(&mut self, event_loop: &ActiveEventLoop) {
+ self.inner.memory_warning(event_loop);
+ }
+}
+
+/// Map a tablet button code winit labels `MouseButton::Other` to a standard mouse button.
+pub(crate) fn map_tablet_button(code: u16) -> Option {
+ use winit::event::MouseButton;
+ match code {
+ BTN_STYLUS | BTN_STYLUS2 => Some(MouseButton::Right),
+ BTN_STYLUS3 => Some(MouseButton::Middle),
+ _ => None,
+ }
+}
+
+fn map_window_event(event: WindowEvent) -> WindowEvent {
+ if let WindowEvent::MouseInput { device_id, state, button: winit::event::MouseButton::Other(code), .. } = event
+ && let Some(button) = map_tablet_button(code)
+ {
+ WindowEvent::MouseInput { device_id, state, button }
+ } else {
+ event
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use winit::event::{ElementState, MouseButton};
+
+ #[test]
+ fn stylus_barrel_buttons_become_secondary_clicks() {
+ assert_eq!(map_tablet_button(BTN_STYLUS), Some(MouseButton::Right));
+ assert_eq!(map_tablet_button(BTN_STYLUS2), Some(MouseButton::Right));
+ assert_eq!(map_tablet_button(BTN_STYLUS3), Some(MouseButton::Middle));
+ assert_eq!(map_tablet_button(0x110), None);
+ }
+
+ #[test]
+ fn window_mouse_input_is_remapped_before_eframe() {
+ let device_id = winit::event::DeviceId::dummy();
+ let press = WindowEvent::MouseInput { device_id, state: ElementState::Pressed, button: MouseButton::Other(BTN_STYLUS) };
+ let mapped = map_window_event(press);
+ assert!(matches!(mapped, WindowEvent::MouseInput { button: MouseButton::Right, state: ElementState::Pressed, .. }));
+ let release = map_window_event(WindowEvent::MouseInput { device_id, state: ElementState::Released, button: MouseButton::Other(BTN_STYLUS2) });
+ assert!(matches!(release, WindowEvent::MouseInput { button: MouseButton::Right, state: ElementState::Released, .. }));
+ }
+}
diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs
index 94a82abeef..b819ff185a 100644
--- a/apps/vectorcraft/src/main.rs
+++ b/apps/vectorcraft/src/main.rs
@@ -1,6 +1,6 @@
//! VectorCraft desktop app.
//!
-//! Usage: `vectorcraft [--control [--automation-read-root ] [--automation-write-root ]]
+//! Usage: `vectorcraft [--control [--automation-read-root ]... [--automation-write-root ]...]
//! [--in-window-menus] [files…]`, `vectorcraft --version`, `vectorcraft --help` (or `-h`)
//!
//! `--in-window-menus` (or `VECTORCRAFT_IN_WINDOW_MENUS=1`) keeps the menus inside the window on
@@ -30,6 +30,8 @@ mod control_server;
mod cursor_theme;
#[cfg(feature = "wgpu")]
mod gpu;
+#[cfg(target_os = "linux")]
+mod linux_stylus;
mod logging;
#[cfg(target_os = "macos")]
mod mac_fonts;
@@ -49,8 +51,10 @@ mod prefs_dir;
mod printing;
#[cfg(all(windows, not(target_vendor = "win7")))]
mod system_fonts;
+mod tablet;
mod window;
mod window_frame;
+mod windows_stylus;
mod xwayland;
use vectorcraft_engine::Session;
@@ -70,6 +74,12 @@ struct App {
frames: u64,
/// Keeps the custom title bar's window borderless (Windows, #1758).
window_frame: Option,
+ /// The main window; used to read and set maximized state the UI layer does not see on Linux (#3635).
+ winit_window: Option>,
+ /// A saved or fitted geometry asked for maximize once the window is mapped (Linux).
+ pending_maximize: bool,
+ /// Frames left to retry [`window::apply_pending_maximize`].
+ maximize_tries: u8,
}
impl eframe::App for App {
@@ -89,6 +99,9 @@ impl eframe::App for App {
if self.app.services.native_menu.is_some() {
mac_menu::raw_input_hook(raw);
}
+ // A pen contact with the barrel button held presses the secondary button (Windows Ink).
+ #[cfg(all(windows, not(target_vendor = "win7")))]
+ windows_stylus::raw_input_hook(raw);
file_access::unconfined(|| self.app.raw_input_hook(raw));
}
#[cfg_attr(not(target_os = "macos"), allow(unused_variables))]
@@ -147,7 +160,15 @@ impl App {
open_files(&mut self.app, open_documents::take());
}
self.app.logic(ctx);
- window::track(ctx, &mut self.app.ui.window);
+ if self.pending_maximize {
+ if let Some(w) = &self.winit_window {
+ self.pending_maximize = window::apply_pending_maximize(w, true, &mut self.maximize_tries);
+ } else {
+ self.pending_maximize = false;
+ }
+ }
+ let host_maximized = self.winit_window.as_ref().map(|w| w.is_maximized());
+ window::track(ctx, &mut self.app.ui.window, host_maximized);
if self.app.ui.status == "quit" {
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
}
@@ -526,6 +547,12 @@ fn start_pick(request: PickRequest, parent: &Parent, ui: &egui::Context) -> Opti
fn services(parent: Parent, ui: egui::Context) -> Services {
use winit::raw_window_handle::{HasWindowHandle as _, RawWindowHandle};
let wayland = parent.as_ref().and_then(|w| w.window_handle().ok()).is_some_and(|h| matches!(h.as_raw(), RawWindowHandle::Wayland(_)));
+ // A window on X11 (XWayland included) reads a tablet pen's pressure itself (#764).
+ #[cfg(target_os = "linux")]
+ let x11 = parent
+ .as_ref()
+ .and_then(|w| w.window_handle().ok())
+ .is_some_and(|h| matches!(h.as_raw(), RawWindowHandle::Xlib(_) | RawWindowHandle::Xcb(_)));
let (p1, p2, p3, p4, p5) = (parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent);
#[cfg(target_os = "macos")]
let sampled_ui = ui.clone();
@@ -539,6 +566,8 @@ fn services(parent: Parent, ui: egui::Context) -> Services {
dialogs_are_sheets: cfg!(target_os = "macos"),
wayland,
no_cursor_theme: wayland && cursor_theme::theme_missing(),
+ #[cfg(target_os = "linux")]
+ stylus: if x11 { tablet::start() } else { None },
read: Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))),
write: Some(Box::new(write_file)),
exists: Some(Box::new(|p: &str| std::path::Path::new(p).exists())),
@@ -725,7 +754,9 @@ Options:
--control Start the localhost JSON-lines control server on
(or VECTORCRAFT_CONTROL_PORT)
--automation-read-root Confine the files control requests read to
+ (may be given more than once)
--automation-write-root Confine the files control requests write to
+ (may be given more than once)
--in-window-menus Keep the menus inside the window on macOS
(or VECTORCRAFT_IN_WINDOW_MENUS=1)
--version Print the version and exit
@@ -774,7 +805,7 @@ fn main() -> std::process::ExitCode {
_ => files.push(a),
}
}
- let automation_args::AutomationArgs { read_root, write_root, .. } = roots_args;
+ let automation_args::AutomationArgs { read_roots, write_roots, .. } = roots_args;
// After the arguments: `--control` and `--version` win over a bad environment value.
let control_port = match control.port {
Some(port) => Some(port),
@@ -813,12 +844,14 @@ fn main() -> std::process::ExitCode {
// The roots confine the control channel: a bad one keeps the app from starting rather than
// leaving agents unconfined. Without a control port there is nothing to confine.
let roots = if control_port.is_none() {
- if read_root.is_some() || write_root.is_some() {
+ if !read_roots.is_empty() || !write_roots.is_empty() {
log::warn!("--automation-read-root and --automation-write-root confine the control channel: ignored without --control");
}
None
} else {
- match AutomationRoots::new(read_root.as_deref(), write_root.as_deref()) {
+ let read: Vec<&std::path::Path> = read_roots.iter().map(std::path::PathBuf::as_path).collect();
+ let write: Vec<&std::path::Path> = write_roots.iter().map(std::path::PathBuf::as_path).collect();
+ match AutomationRoots::new(&read, &write) {
Ok(roots) => roots,
Err(e) => {
log::error!("{e}");
@@ -890,6 +923,18 @@ fn main() -> std::process::ExitCode {
}
options
};
+ // With Windows Ink, winit reports a pen as a touch and drops its barrel button; the message
+ // hook notes each pointer contact and whether it starts with the barrel button held
+ // (`windows_stylus`).
+ #[cfg(all(windows, not(target_vendor = "win7")))]
+ let options = {
+ use winit::platform::windows::EventLoopBuilderExtWindows as _;
+ let mut options = options;
+ options.event_loop_builder = Some(Box::new(|builder| {
+ builder.with_msg_hook(windows_stylus::msg_hook);
+ }));
+ options
+ };
#[cfg(feature = "wgpu")]
let options = {
let mut options = options;
@@ -934,9 +979,18 @@ fn main() -> std::process::ExitCode {
#[cfg(feature = "wgpu")]
let created = startup.clone();
// A panic that ends the window (egui-wgpu's own, #502) is caught here: never a crash.
+ let run = |options: eframe::NativeOptions, app_creator: eframe::AppCreator<'_>| {
+ #[cfg(target_os = "linux")]
+ {
+ linux_stylus::run_native("VectorCraft", options, app_creator)
+ }
+ #[cfg(not(target_os = "linux"))]
+ {
+ eframe::run_native("VectorCraft", options, app_creator)
+ }
+ };
let outcome = vectorcraft_engine::guard::catch_panic(|| {
- eframe::run_native(
- "VectorCraft",
+ run(
options,
Box::new(move |cc| {
let mut session = Session::new();
@@ -949,11 +1003,15 @@ fn main() -> std::process::ExitCode {
// which takes over from the copy the preferences file used to hold.
prefs_dir::attach_pdf_preset_store(&mut app.session);
// Fit the window to its monitor, or put it back where it was (still hidden).
- if let Some(w) = cc.winit_window() {
- app.ui.window = Some(window::restore(w, saved_window));
+ let winit_window = cc.winit_window().cloned();
+ if let Some(w) = &winit_window {
+ let g = window::restore(w, saved_window);
+ app.ui.window = Some(g);
#[cfg(windows)]
set_taskbar_icon(w);
}
+ // Linux may not map the window before the first frames, so a saved maximize is retried then (#3635).
+ let pending_maximize = cfg!(target_os = "linux") && app.ui.window.as_ref().is_some_and(|g| g.maximized);
// 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);
@@ -1015,7 +1073,7 @@ fn main() -> std::process::ExitCode {
// Everywhere the app doesn't say whose work it is (worker threads), the
// roots hold: unconfined is only what the person at the keyboard does.
file_access::confine_process(roots.clone());
- log::info!("control channel confined to the automation roots: read {:?}, write {:?}", roots.read_root(), roots.write_root());
+ log::info!("control channel confined to the automation roots: {}", roots.describe());
}
}
#[cfg(target_os = "macos")]
@@ -1034,7 +1092,16 @@ fn main() -> std::process::ExitCode {
created.ready();
// The content and the pointer stay aligned on Windows (#1758).
let window_frame = window_frame::service(cc, custom_titlebar);
- Ok(Box::new(App { app, graphics_loss, graphics_lost: false, frames: 0, window_frame }))
+ Ok(Box::new(App {
+ app,
+ graphics_loss,
+ graphics_lost: false,
+ frames: 0,
+ window_frame,
+ winit_window,
+ pending_maximize,
+ maximize_tries: 8,
+ }))
}),
)
});
diff --git a/apps/vectorcraft/src/tablet.rs b/apps/vectorcraft/src/tablet.rs
new file mode 100644
index 0000000000..58b1afeeb7
--- /dev/null
+++ b/apps/vectorcraft/src/tablet.rs
@@ -0,0 +1,356 @@
+//! Linux: a drawing tablet's pen pressure under X11, XWayland included (#764). winit 0.30 hands a
+//! pen to the window there as a mouse, without its pressure, so the app reads the pressure from
+//! XInput2 itself and writes it into the UI's [`StylusFeed`] (`Services::stylus`), which the canvas
+//! reads.
+//!
+//! The reader opens a second connection to the X server (x11rb's `RustConnection`, without
+//! `unsafe` or libxcb) and selects XInput2 raw events for every device on the root window. Raw
+//! events reach every client that selects them, also while winit holds the pointer grab of a
+//! drag, and name the device that moved. A pointer device with an "Abs Pressure" valuator is a pen
+//! (xf86-input-wacom, xf86-input-libinput and XWayland give a pen's pressure axis that label),
+//! unless its XInput type is a touchpad's or a touchscreen's: its pressure, scaled from the
+//! valuator's range to 0..1, goes into the feed. Any other pointer
+//! device moving sets the feed to `None`. Raw events carry only the valuators that changed, so
+//! the last pressure of each pen is kept.
+//!
+//! The reader starts only for a window on X11. On native Wayland, `DISPLAY` names an XWayland
+//! that receives none of the window's input.
+//!
+//! The mapping and the reader come from PhotoCraft's `crates/tablet` (`xi.rs` and `x11.rs`), with
+//! the pressure axis only.
+#![cfg_attr(not(target_os = "linux"), allow(dead_code))]
+
+use std::collections::HashMap;
+
+use vectorcraft_ui_egui::stylus::StylusFeed;
+
+/// Valuator numbers from this one on are ignored (the protocol allows 65,535; tablets have fewer
+/// than 16).
+const MAX_AXES: u16 = 64;
+
+/// Devices kept (a server could list thousands).
+const MAX_DEVICES: usize = 256;
+
+/// The XInput types of finger devices (`XI_TOUCHPAD` and `XI_TOUCHSCREEN`): xf86-input-evdev labels
+/// a touchpad's or a touchscreen's pressure axis "Abs Pressure" too, and they are not pens.
+const FINGER_TYPES: &[&str] = &["TOUCHPAD", "TOUCHSCREEN"];
+
+/// The "Abs Pressure" valuator of a pen: its number in a raw event's valuator mask, and its range.
+#[derive(Clone, Copy, Debug, PartialEq)]
+struct Axis {
+ number: u16,
+ min: f64,
+ max: f64,
+}
+
+impl Axis {
+ /// A raw value of this valuator as a pressure of 0..1; a value that is not a number is a
+ /// mouse's, 1.
+ fn pressure(&self, v: f64) -> f32 {
+ if !v.is_finite() {
+ return 1.0;
+ }
+ let span = self.max - self.min;
+ let unit = if span.is_finite() && span > 0.0 { (v - self.min) / span } else { v };
+ unit.clamp(0.0, 1.0) as f32
+ }
+}
+
+/// A pointer device the X server lists.
+#[derive(Clone, Copy, Debug, PartialEq)]
+struct Device {
+ id: u16,
+ /// The pressure valuator: a pen has one, a mouse, a touchpad or a touchscreen has none.
+ pressure: Option,
+}
+
+impl Device {
+ /// From what the X server lists for the device: its XInput type (`ListInputDevices`), and each
+ /// valuator's number, label, minimum and maximum (`XIQueryDevice`).
+ fn new(id: u16, kind: Option<&str>, valuators: impl IntoIterator- ) -> Self {
+ let finger = kind.is_some_and(|k| FINGER_TYPES.contains(&k));
+ let pressure = valuators
+ .into_iter()
+ .filter(|(number, ..)| *number < MAX_AXES)
+ .find(|(_, label, ..)| label == "Abs Pressure")
+ .map(|(number, _, min, max)| Axis { number, min, max })
+ .filter(|_| !finger);
+ Self { id, pressure }
+ }
+}
+
+/// What a raw event means for the feed.
+#[derive(Clone, Copy, Debug, PartialEq)]
+enum Update {
+ /// Nothing: a device the last listing didn't have (a master, or one added since).
+ Keep,
+ /// The pressure of a pen, or `None` for another pointer.
+ Set(Option
),
+}
+
+/// The pointer devices and the last pressure of each pen.
+#[derive(Debug, Default)]
+struct Pens {
+ devices: HashMap,
+ last: HashMap,
+}
+
+impl Pens {
+ /// Replace the device list (at the start, and when devices come and go or change).
+ fn set_devices(&mut self, devices: impl IntoIterator- ) {
+ self.devices = devices.into_iter().take(MAX_DEVICES).map(|d| (d.id, d)).collect();
+ self.last.retain(|id, _| self.devices.contains_key(id));
+ }
+
+ /// A raw motion or button event of device `id`, with the valuators that changed.
+ fn handle(&mut self, id: u16, valuators: impl IntoIterator
- ) -> Update {
+ let Some(device) = self.devices.get(&id) else { return Update::Keep };
+ let Some(axis) = device.pressure else { return Update::Set(None) };
+ let last = self.last.entry(id).or_insert(0.0);
+ for (number, v) in valuators {
+ if number == axis.number {
+ *last = axis.pressure(v);
+ }
+ }
+ Update::Set(Some(*last))
+ }
+
+ /// A raw event as the X server sends it: its valuator mask and the values of the valuators
+ /// set in it. A pen's pressure or another pointer's `None` goes into `feed`.
+ fn raw_event(&mut self, feed: &StylusFeed, id: u16, mask: &[u32], values: &[f64]) {
+ if let Update::Set(pressure) = self.handle(id, valuators(mask, values)) {
+ feed.set(pressure);
+ }
+ }
+}
+
+/// The values a raw event carries: the valuator numbers set in `mask` (32 to a word, lowest bit
+/// first), each paired in order with one of `values`. Mask bits past the last value are ignored.
+fn valuators<'a>(mask: &'a [u32], values: &'a [f64]) -> impl Iterator
- + 'a {
+ let numbers = mask
+ .iter()
+ .enumerate()
+ .flat_map(|(w, bits)| (0..32u32).filter(move |b| bits & (1 << b) != 0).map(move |b| w.saturating_mul(32).saturating_add(b as usize)));
+ numbers.zip(values.iter().copied()).filter_map(|(n, v)| u16::try_from(n).ok().map(|n| (n, v)))
+}
+
+/// An X 32.32 fixed-point value.
+fn fp3232(integral: i32, frac: u32) -> f64 {
+ f64::from(integral) + f64::from(frac) / 4_294_967_296.0
+}
+
+/// Start reading pen pressure for a window on X11: the feed the reader writes into, or `None`
+/// (logged) when the X server can't be reached or has no XInput 2.1.
+#[cfg(target_os = "linux")]
+pub fn start() -> Option
{
+ let feed = StylusFeed::default();
+ match x11::spawn(feed.clone()) {
+ Ok(()) => Some(feed),
+ Err(e) => {
+ log::warn!("tablet pressure: {e}");
+ None
+ }
+ }
+}
+
+#[cfg(target_os = "linux")]
+mod x11 {
+ use std::collections::HashMap;
+
+ use vectorcraft_ui_egui::stylus::StylusFeed;
+ use x11rb::connection::{Connection as _, RequestConnection as _};
+ use x11rb::protocol::Event;
+ use x11rb::protocol::xinput::{self, ConnectionExt as _, DeviceClassData, DeviceType, XIEventMask};
+ use x11rb::protocol::xproto::ConnectionExt as _;
+ use x11rb::rust_connection::RustConnection;
+
+ use super::{Device, MAX_AXES, MAX_DEVICES, Pens, fp3232};
+
+ /// `XIAllDevices`: every device, the slave devices that name a pen included.
+ const ALL_DEVICES: u16 = 0;
+
+ /// Connect to `$DISPLAY` (the display winit opened the window on), check for XInput 2.1 (raw
+ /// events for every client that selects them), select the raw events, and read them on a
+ /// thread of its own until the connection closes.
+ pub fn spawn(feed: StylusFeed) -> Result<(), String> {
+ let (conn, screen) = RustConnection::connect(None).map_err(|e| format!("can't connect to the X server: {e}"))?;
+ let root = conn.setup().roots.get(screen).map(|s| s.root).ok_or_else(|| format!("X screen {screen} not found"))?;
+ let version =
+ conn.xinput_xi_query_version(2, 2).map_err(|e| e.to_string())?.reply().map_err(|e| format!("the X server has no XInput 2: {e}"))?;
+ if (version.major_version, version.minor_version) < (2, 1) {
+ return Err(format!("the X server has XInput {}.{}, and raw events need 2.1", version.major_version, version.minor_version));
+ }
+ let mask = XIEventMask::RAW_MOTION
+ | XIEventMask::RAW_BUTTON_PRESS
+ | XIEventMask::RAW_BUTTON_RELEASE
+ | XIEventMask::HIERARCHY
+ | XIEventMask::DEVICE_CHANGED;
+ conn.xinput_xi_select_events(root, &[xinput::EventMask { deviceid: ALL_DEVICES, mask: vec![mask] }])
+ .map_err(|e| e.to_string())?
+ .check()
+ .map_err(|e| format!("XISelectEvents failed: {e}"))?;
+ let mut pens = Pens::default();
+ pens.set_devices(query_devices(&conn));
+ std::thread::Builder::new()
+ .name("vectorcraft-tablet-x11".into())
+ .spawn(move || run(&conn, &mut pens, &feed))
+ .map(drop)
+ .map_err(|e| format!("can't start the tablet thread: {e}"))
+ }
+
+ fn run(conn: &RustConnection, pens: &mut Pens, feed: &StylusFeed) {
+ // A connection error (the display went away) ends the loop; an event that x11rb cannot
+ // parse is skipped, and `Pens` bounds what the rest can hold.
+ while let Ok(raw) = conn.wait_for_raw_event() {
+ let Ok(event) = conn.parse_event(&raw) else { continue };
+ match event {
+ Event::XinputRawMotion(e) | Event::XinputRawButtonPress(e) | Event::XinputRawButtonRelease(e) => {
+ let values: Vec = e.axisvalues.iter().map(|v| fp3232(v.integral, v.frac)).collect();
+ pens.raw_event(feed, e.deviceid, &e.valuator_mask, &values);
+ }
+ Event::XinputHierarchy(_) | Event::XinputDeviceChanged(_) => pens.set_devices(query_devices(conn)),
+ _ => {}
+ }
+ }
+ }
+
+ /// The slave pointer devices with their pressure valuators (none on any error).
+ fn query_devices(conn: &RustConnection) -> Vec {
+ let Ok(reply) = conn.xinput_xi_query_device(ALL_DEVICES).map_err(drop).and_then(|c| c.reply().map_err(drop)) else { return Vec::new() };
+ let kinds = device_kinds(conn);
+ let mut out = Vec::new();
+ for info in reply.infos.iter().take(MAX_DEVICES) {
+ if info.type_ != DeviceType::SLAVE_POINTER && info.type_ != DeviceType::FLOATING_SLAVE {
+ continue;
+ }
+ let valuators = info.classes.iter().take(usize::from(MAX_AXES)).filter_map(|c| match &c.data {
+ DeviceClassData::Valuator(v) => {
+ let label = atom_name(conn, v.label)?;
+ Some((v.number, label, fp3232(v.min.integral, v.min.frac), fp3232(v.max.integral, v.max.frac)))
+ }
+ _ => None,
+ });
+ out.push(Device::new(info.deviceid, kinds.get(&info.deviceid).map(String::as_str), valuators.collect::>()));
+ }
+ out
+ }
+
+ /// Each device's XInput type name, by device id (none on any error).
+ fn device_kinds(conn: &RustConnection) -> HashMap {
+ let Ok(reply) = conn.xinput_list_input_devices().map_err(drop).and_then(|c| c.reply().map_err(drop)) else { return HashMap::new() };
+ reply.devices.iter().take(MAX_DEVICES).filter_map(|d| Some((u16::from(d.device_id), atom_name(conn, d.device_type)?))).collect()
+ }
+
+ fn atom_name(conn: &RustConnection, atom: u32) -> Option {
+ if atom == 0 {
+ return None;
+ }
+ let reply = conn.get_atom_name(atom).ok()?.reply().ok()?;
+ Some(String::from_utf8_lossy(&reply.name).into_owned())
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// The valuators of a Wacom pen as the X server lists them: x and y, then pressure from 0 to
+ /// 65,535.
+ fn pen_valuators() -> Vec<(u16, String, f64, f64)> {
+ vec![
+ (0, "Abs X".to_string(), 0.0, 44704.0),
+ (1, "Abs Y".to_string(), 0.0, 27940.0),
+ (2, "Abs Pressure".to_string(), 0.0, 65535.0),
+ (3, "Abs Tilt X".to_string(), -64.0, 63.0),
+ ]
+ }
+
+ fn pen(id: u16) -> Device {
+ Device::new(id, Some("STYLUS"), pen_valuators())
+ }
+
+ fn mouse(id: u16) -> Device {
+ Device::new(id, Some("MOUSE"), [(0, "Rel X".to_string(), -1.0, -1.0), (1, "Rel Y".to_string(), -1.0, -1.0)])
+ }
+
+ #[test]
+ fn the_mask_pairs_valuator_numbers_with_values() {
+ let v: Vec<_> = valuators(&[0b10_0101, 1], &[1.0, 2.0, 3.0, 4.0]).collect();
+ assert_eq!(v, vec![(0, 1.0), (2, 2.0), (5, 3.0), (32, 4.0)]);
+ // Fewer values than mask bits (malformed): the values that are there.
+ assert_eq!(valuators(&[u32::MAX; 4], &[7.0]).count(), 1);
+ assert_eq!(valuators(&[], &[7.0]).count(), 0);
+ }
+
+ #[test]
+ fn a_device_with_an_abs_pressure_valuator_is_a_pen() {
+ assert_eq!(pen(9).pressure, Some(Axis { number: 2, min: 0.0, max: 65535.0 }));
+ assert_eq!(mouse(12).pressure, None);
+ let pad = Device::new(13, Some("PAD"), [(5, "Abs Wheel".to_string(), 0.0, 71.0)]);
+ assert_eq!(pad.pressure, None, "a tablet's pad is no pen");
+ let far = Device::new(14, Some("STYLUS"), [(MAX_AXES, "Abs Pressure".to_string(), 0.0, 1.0)]);
+ assert_eq!(far.pressure, None, "valuator numbers past the limit are ignored");
+ // The types libinput and XWayland give pens, and a device whose type wasn't listed.
+ for kind in [Some("TABLET"), Some("ERASER"), Some("xwayland-tablet stylus"), None] {
+ assert!(Device::new(15, kind, pen_valuators()).pressure.is_some(), "{kind:?}");
+ }
+ // xf86-input-evdev labels a touchpad's and a touchscreen's finger pressure "Abs Pressure".
+ for kind in ["TOUCHPAD", "TOUCHSCREEN"] {
+ assert_eq!(Device::new(16, Some(kind), pen_valuators()).pressure, None, "{kind}");
+ }
+ }
+
+ #[test]
+ fn a_pens_valuator_becomes_its_pressure_and_another_pointer_clears_it() {
+ let mut pens = Pens::default();
+ pens.set_devices([pen(9), mouse(12)]);
+ let feed = StylusFeed::default();
+ pens.raw_event(&feed, 9, &[0b101], &[100.0, 32767.5]);
+ assert_eq!(feed.held(), Some(0.5));
+ // Raw events carry only the valuators that changed: a move without pressure keeps it.
+ pens.raw_event(&feed, 9, &[0b1], &[200.0]);
+ assert_eq!(feed.held(), Some(0.5));
+ pens.raw_event(&feed, 9, &[0b100], &[65535.0]);
+ assert_eq!(feed.held(), Some(1.0));
+ // The mouse moves: no pen pressure until the pen moves again.
+ pens.raw_event(&feed, 12, &[0b1], &[3.0]);
+ assert_eq!(feed.held(), None);
+ pens.raw_event(&feed, 9, &[0b1], &[300.0]);
+ assert_eq!(feed.held(), Some(1.0), "the pen's last pressure");
+ // A master device or one not listed yet changes nothing.
+ pens.raw_event(&feed, 2, &[0b100], &[0.0]);
+ assert_eq!(feed.held(), Some(1.0));
+ // A pen whose first event carries no pressure is hovering: it presses with 0.
+ pens.set_devices([pen(9), pen(10)]);
+ pens.raw_event(&feed, 10, &[0b1], &[5.0]);
+ assert_eq!(feed.press(), Some(0.0));
+ }
+
+ #[test]
+ fn hostile_device_data_gives_a_pressure_within_0_to_1() {
+ let ranges = [(5.0, 5.0), (1.0, -1.0), (f64::NEG_INFINITY, f64::INFINITY), (f64::NAN, f64::NAN)];
+ for (min, max) in ranges {
+ let mut pens = Pens::default();
+ pens.set_devices([Device::new(1, None, [(2, "Abs Pressure".to_string(), min, max)])]);
+ for v in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, f64::MAX, f64::MIN, -0.0, 1e300, 0.5] {
+ let Update::Set(Some(p)) = pens.handle(1, [(2, v)]) else { panic!("{min}..{max}: {v} gave no pressure") };
+ assert!((0.0..=1.0).contains(&p), "{min}..{max}: {v} gave {p}");
+ }
+ }
+ let mut pens = Pens::default();
+ pens.set_devices((0..2000u16).map(|i| Device::new(i, None, [])));
+ assert!(pens.devices.len() <= MAX_DEVICES, "the device list is bounded");
+ // Values for valuators the pen doesn't have are ignored.
+ pens.set_devices([pen(3)]);
+ let Update::Set(Some(p)) = pens.handle(3, valuators(&[u32::MAX; 2048], &[0.5; 4096]).collect::>()) else {
+ panic!("the pen gave no pressure")
+ };
+ assert!(p < 0.001, "{p}");
+ }
+
+ #[test]
+ fn fixed_point_values() {
+ assert_eq!(fp3232(3, 1 << 31), 3.5);
+ assert_eq!(fp3232(-2, 0), -2.0);
+ }
+}
diff --git a/apps/vectorcraft/src/window.rs b/apps/vectorcraft/src/window.rs
index e953264237..abe60f69ff 100644
--- a/apps/vectorcraft/src/window.rs
+++ b/apps/vectorcraft/src/window.rs
@@ -110,7 +110,8 @@ fn fit(size: [f32; 2], room: [f32; 2]) -> [f32; 2] {
}
/// Size and place the new window (eframe shows it after drawing the first frame) and return its
-/// geometry.
+/// geometry. On Linux the window may not be mapped yet, so [`apply_pending_maximize`] must run
+/// until the host reports maximized (fixes #3635).
pub fn restore(window: &winit::window::Window, saved: Option) -> WindowGeometry {
let handles: Vec<_> = window.available_monitors().collect();
let monitors: Vec = handles.iter().map(|m| Monitor::new(m.position(), m.size(), m.scale_factor())).collect();
@@ -121,22 +122,41 @@ pub fn restore(window: &winit::window::Window, saved: Option) ->
}
// Returns the new size when it applies at once; either way the window gets it.
let _ = window.request_inner_size(LogicalSize::new(g.size[0], g.size[1]));
+ #[cfg(not(target_os = "linux"))]
if g.maximized {
window.set_maximized(true);
}
g
}
+/// Keep asking the host to maximize until it sticks, or give up after a few frames.
+pub fn apply_pending_maximize(window: &winit::window::Window, want: bool, tries: &mut u8) -> bool {
+ if !want {
+ return false;
+ }
+ if window.is_maximized() {
+ return false;
+ }
+ if *tries == 0 {
+ return false;
+ }
+ *tries -= 1;
+ window.set_maximized(true);
+ true
+}
+
/// Per frame: remember the window's geometry for the next launch. Minimized or full screen keeps
/// the last one; maximized only sets its flag, so un-maximizing next time restores the last size.
-pub fn track(ctx: &egui::Context, geometry: &mut Option) {
+/// `host_maximized` is the window manager's idea of maximized when egui does not report it (#3635).
+pub fn track(ctx: &egui::Context, geometry: &mut Option, host_maximized: Option) {
let zoom = ctx.zoom_factor();
ctx.input(|i| {
let v = i.viewport();
if v.minimized == Some(true) || v.fullscreen == Some(true) {
return;
}
- if v.maximized == Some(true) {
+ let maximized = v.maximized == Some(true) || host_maximized == Some(true);
+ if maximized {
if let Some(g) = geometry {
g.maximized = true;
}
@@ -222,7 +242,7 @@ mod tests {
let mut frame = |info: egui::ViewportInfo| {
let mut input = egui::RawInput::default();
input.viewports.insert(egui::ViewportId::ROOT, info);
- ctx.run_ui(input, |ui| track(ui.ctx(), &mut geometry)).textures_delta.clear();
+ ctx.run_ui(input, |ui| track(ui.ctx(), &mut geometry, None)).textures_delta.clear();
geometry
};
let rect = egui::Rect::from_min_size(egui::pos2(20.0, 30.0), egui::vec2(1000.0, 600.0));
@@ -253,4 +273,19 @@ mod tests {
let back: vectorcraft_ui_egui::UiState = serde_json::from_value(json).unwrap();
assert_eq!(back.window, None);
}
+
+ #[test]
+ fn the_host_maximized_flag_is_remembered_when_egui_does_not_report_it() {
+ let ctx = egui::Context::default();
+ let mut geometry = Some(WindowGeometry { pos: Some([10, 20]), size: [800.0, 600.0], maximized: false });
+ let rect = egui::Rect::from_min_size(egui::pos2(0.0, 0.0), egui::vec2(1920.0, 1080.0));
+ let mut input = egui::RawInput::default();
+ input.viewports.insert(
+ egui::ViewportId::ROOT,
+ egui::ViewportInfo { inner_rect: Some(rect), outer_rect: Some(rect), maximized: None, ..Default::default() },
+ );
+ let mut out = ctx.run_ui(input, |ui| track(ui.ctx(), &mut geometry, Some(true)));
+ out.textures_delta.clear();
+ assert_eq!(geometry, Some(WindowGeometry { pos: Some([10, 20]), size: [800.0, 600.0], maximized: true }));
+ }
}
diff --git a/apps/vectorcraft/src/windows_stylus.rs b/apps/vectorcraft/src/windows_stylus.rs
new file mode 100644
index 0000000000..cf17976b5c
--- /dev/null
+++ b/apps/vectorcraft/src/windows_stylus.rs
@@ -0,0 +1,299 @@
+//! Windows pen tablets: with Windows Ink, winit reports a pen in contact as a touch and drops its
+//! barrel button, and egui-winit presses the primary button for the touch it makes the pointer,
+//! so a pen pressed with its barrel button held clicks and drags with the left button. The
+//! `WM_POINTERDOWN` message winit is about to handle still has the barrel button's state in its
+//! second-button flag ("analogous to a mouse right button down",
+//! ): [`msg_hook`] notes
+//! it, and [`raw_input_hook`] makes the primary button of that contact the secondary one.
+#![cfg_attr(not(all(windows, not(target_vendor = "win7"))), allow(dead_code))]
+
+use std::cell::RefCell;
+
+use egui::{Event, Modifiers, PointerButton, Pos2, TouchId, TouchPhase};
+
+/// `POINTER_MESSAGE_FLAG_SECONDBUTTON` (`winuser.h`): in the high word of a pointer message's
+/// `wParam`, a pen in contact with its barrel button pressed.
+const POINTER_MESSAGE_FLAG_SECONDBUTTON: usize = 0x0020;
+/// At most this many pointer contacts wait for their touch event.
+const MAX_PENDING: usize = 16;
+
+thread_local! {
+ static STROKES: RefCell = RefCell::new(BarrelStrokes::default());
+}
+
+/// winit's message hook (`EventLoopBuilderExtWindows::with_msg_hook`), which winit calls for each
+/// message it takes from the thread's queue, before dispatching it: notes each pointer contact's id
+/// and whether the barrel button was held.
+/// It never consumes the message.
+#[cfg(all(windows, not(target_vendor = "win7")))]
+#[allow(unsafe_code)]
+pub fn msg_hook(msg: *const std::ffi::c_void) -> bool {
+ use windows::Win32::UI::WindowsAndMessaging::{MSG, WM_POINTERDOWN};
+ // SAFETY: winit passes the `MSG` that `PeekMessageW` has just filled, which lives for this
+ // call; `as_ref` gives `None` for a null pointer.
+ let Some(msg) = (unsafe { msg.cast::().as_ref() }) else {
+ return false;
+ };
+ if msg.message == WM_POINTERDOWN {
+ STROKES.with(|s| {
+ if let Ok(mut s) = s.try_borrow_mut() {
+ s.pointer_down(msg.wParam.0);
+ }
+ });
+ }
+ false
+}
+
+/// Before egui reads a frame's input: the primary button of a contact that started with the
+/// barrel button held becomes the secondary button.
+pub fn raw_input_hook(raw: &mut egui::RawInput) {
+ STROKES.with(|s| {
+ if let Ok(mut s) = s.try_borrow_mut() {
+ s.rewrite(&mut raw.events);
+ }
+ });
+}
+
+/// The pen contacts that press the secondary button.
+#[derive(Default)]
+struct BarrelStrokes {
+ /// Each `WM_POINTERDOWN`'s pointer id and whether the barrel button was held, oldest first,
+ /// until the touch of that contact starts.
+ pending: Vec<(u64, bool)>,
+ /// The contact whose touch started with the barrel button held, until it ends, the same pointer
+ /// starts another contact, or another contact starts with the barrel button held.
+ right: Option,
+}
+
+/// A contact that started with the barrel button held.
+#[derive(Clone, Copy, Debug, PartialEq)]
+struct Right {
+ id: TouchId,
+ /// Its secondary button is down: the press went to egui and the release has not.
+ down: bool,
+}
+
+impl BarrelStrokes {
+ /// A `WM_POINTERDOWN` with this `wParam`, whose low word is the pointer id and whose high word
+ /// holds the pointer flags.
+ fn pointer_down(&mut self, wparam: usize) {
+ if self.pending.len() >= MAX_PENDING {
+ self.pending.remove(0);
+ }
+ self.pending.push(((wparam & 0xffff) as u64, (wparam >> 16) & POINTER_MESSAGE_FLAG_SECONDBUTTON != 0));
+ }
+
+ /// Makes the primary button of the right contact the secondary one. egui-winit sends a touch's
+ /// pointer button with the touch event it comes from: the press after the touch's start and
+ /// the pointer's move to it, the release right after its end. A canceled contact, or one
+ /// whose end never came (Windows does not promise one), gets a secondary release of its own.
+ fn rewrite(&mut self, events: &mut Vec) {
+ let release = |pos: Pos2| Event::PointerButton { pos, button: PointerButton::Secondary, pressed: false, modifiers: Modifiers::NONE };
+ let mut out = Vec::with_capacity(events.len() + 1);
+ // The button event that comes next for the right contact: `Some(true)` for its press,
+ // `Some(false)` for its release.
+ let mut next = None;
+ for mut event in events.drain(..) {
+ let mut after = None;
+ match &mut event {
+ Event::Touch { id, phase, pos, .. } => {
+ let (id, phase, pos) = (*id, *phase, *pos);
+ if phase == TouchPhase::Start {
+ // Each start decides afresh, from the oldest contact of its pointer still waiting.
+ let barrel = match self.pending.iter().position(|&(p, _)| p == id.0) {
+ Some(i) => self.pending.remove(i).1,
+ None => false,
+ };
+ if let Some(r) = self.right
+ && (barrel || r.id == id)
+ {
+ if r.down {
+ out.push(release(pos));
+ }
+ self.right = None;
+ }
+ if barrel {
+ self.right = Some(Right { id, down: false });
+ }
+ }
+ next = None;
+ if let Some(r) = self.right.filter(|r| r.id == id) {
+ match phase {
+ TouchPhase::Start => next = Some(true),
+ TouchPhase::Move => {}
+ TouchPhase::End => {
+ self.right = None;
+ next = Some(false);
+ }
+ TouchPhase::Cancel => {
+ self.right = None;
+ if r.down {
+ after = Some(release(pos));
+ }
+ }
+ }
+ }
+ }
+ Event::PointerMoved(_) if next == Some(true) => {}
+ Event::PointerButton { button, pressed, .. } if next == Some(*pressed) && *button == PointerButton::Primary => {
+ *button = PointerButton::Secondary;
+ if let Some(r) = self.right.as_mut() {
+ r.down = *pressed;
+ }
+ next = None;
+ }
+ _ => next = None,
+ }
+ out.push(event);
+ out.extend(after);
+ }
+ *events = out;
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use egui::{TouchDeviceId, pos2};
+
+ /// `POINTER_MESSAGE_FLAG_INRANGE`, `_INCONTACT` and `_FIRSTBUTTON` (`winuser.h`): a pen tip
+ /// touching down.
+ const TIP: usize = 0x0002 | 0x0004 | 0x0010;
+ /// `POINTER_MESSAGE_FLAG_INRANGE` and `_INCONTACT` with the barrel button.
+ const BARREL: usize = 0x0002 | 0x0004 | POINTER_MESSAGE_FLAG_SECONDBUTTON;
+
+ fn down(strokes: &mut BarrelStrokes, id: usize, flags: usize) {
+ strokes.pointer_down((flags << 16) | id);
+ }
+
+ /// The events egui reads after the hook.
+ fn rewrite(strokes: &mut BarrelStrokes, events: &[Event]) -> Vec {
+ let mut events = events.to_vec();
+ strokes.rewrite(&mut events);
+ events
+ }
+
+ fn touch(id: u64, phase: TouchPhase) -> Event {
+ Event::Touch { device_id: TouchDeviceId(1), id: TouchId(id), phase, pos: pos2(10.0, 20.0), force: Some(0.5) }
+ }
+
+ fn button(button: PointerButton, pressed: bool) -> Event {
+ Event::PointerButton { pos: pos2(10.0, 20.0), button, pressed, modifiers: Modifiers::NONE }
+ }
+
+ /// What egui-winit sends for the touch that drives the pointer.
+ fn start(id: u64) -> Vec {
+ vec![touch(id, TouchPhase::Start), Event::PointerMoved(pos2(10.0, 20.0)), button(PointerButton::Primary, true)]
+ }
+
+ fn end(id: u64) -> Vec {
+ vec![touch(id, TouchPhase::End), button(PointerButton::Primary, false), Event::PointerGone]
+ }
+
+ fn buttons(events: &[Event]) -> Vec<(PointerButton, bool)> {
+ events.iter().filter_map(|e| if let Event::PointerButton { button, pressed, .. } = e { Some((*button, *pressed)) } else { None }).collect()
+ }
+
+ const SECONDARY_DOWN: (PointerButton, bool) = (PointerButton::Secondary, true);
+ const SECONDARY_UP: (PointerButton, bool) = (PointerButton::Secondary, false);
+ const PRIMARY_DOWN: (PointerButton, bool) = (PointerButton::Primary, true);
+ const PRIMARY_UP: (PointerButton, bool) = (PointerButton::Primary, false);
+
+ #[test]
+ fn a_pen_contact_with_the_barrel_button_presses_the_secondary_button() {
+ let mut strokes = BarrelStrokes::default();
+ down(&mut strokes, 7, BARREL);
+ assert_eq!(buttons(&rewrite(&mut strokes, &start(7))), [SECONDARY_DOWN]);
+ let moved = [touch(7, TouchPhase::Move), Event::PointerMoved(pos2(15.0, 25.0))];
+ assert_eq!(rewrite(&mut strokes, &moved), moved);
+ assert_eq!(buttons(&rewrite(&mut strokes, &end(7))), [SECONDARY_UP]);
+ assert_eq!(strokes.right, None, "the next contact starts afresh");
+ assert!(strokes.pending.is_empty());
+ }
+
+ #[test]
+ fn a_pen_contact_with_the_tip_alone_keeps_the_primary_button() {
+ let mut strokes = BarrelStrokes::default();
+ down(&mut strokes, 7, TIP);
+ let events = [start(7), end(7)].concat();
+ assert_eq!(rewrite(&mut strokes, &events), events);
+ }
+
+ #[test]
+ fn contacts_of_a_pen_within_one_frame_keep_their_order() {
+ // A tap with the barrel button held, then one with the tip alone, before the next frame.
+ let mut strokes = BarrelStrokes::default();
+ down(&mut strokes, 7, BARREL);
+ down(&mut strokes, 7, TIP);
+ let events = rewrite(&mut strokes, &[start(7), end(7), start(7), end(7)].concat());
+ assert_eq!(buttons(&events), [SECONDARY_DOWN, SECONDARY_UP, PRIMARY_DOWN, PRIMARY_UP]);
+ }
+
+ #[test]
+ fn a_mouse_button_right_after_a_barrel_contact_keeps_its_button() {
+ let mut strokes = BarrelStrokes::default();
+ down(&mut strokes, 7, BARREL);
+ let events = [start(7), vec![button(PointerButton::Primary, true)], end(7), vec![button(PointerButton::Primary, false)]].concat();
+ assert_eq!(buttons(&rewrite(&mut strokes, &events)), [SECONDARY_DOWN, PRIMARY_DOWN, SECONDARY_UP, PRIMARY_UP]);
+ }
+
+ #[test]
+ fn other_touches_and_the_mouse_keep_the_primary_button_during_a_barrel_contact() {
+ let mut strokes = BarrelStrokes::default();
+ down(&mut strokes, 7, BARREL);
+ down(&mut strokes, 9, TIP);
+ let events = [start(7), start(9), vec![button(PointerButton::Primary, true)], end(9)].concat();
+ assert_eq!(buttons(&rewrite(&mut strokes, &events)), [SECONDARY_DOWN, PRIMARY_DOWN, PRIMARY_DOWN, PRIMARY_UP]);
+ assert_eq!(strokes.right, Some(Right { id: TouchId(7), down: true }), "the barrel contact goes on");
+ }
+
+ #[test]
+ fn a_contact_after_a_lost_end_releases_the_secondary_button_first() {
+ let mut strokes = BarrelStrokes::default();
+ down(&mut strokes, 7, BARREL);
+ rewrite(&mut strokes, &start(7));
+ // No end arrives for that contact; the pen touches down again with the tip alone.
+ down(&mut strokes, 7, TIP);
+ let events = rewrite(&mut strokes, &[start(7), end(7)].concat());
+ assert_eq!(buttons(&events), [SECONDARY_UP, PRIMARY_DOWN, PRIMARY_UP]);
+ assert_eq!(strokes.right, None);
+ // Another pen's barrel contact takes over from one whose end was lost.
+ down(&mut strokes, 7, BARREL);
+ rewrite(&mut strokes, &start(7));
+ down(&mut strokes, 8, BARREL);
+ let events = rewrite(&mut strokes, &[start(8), end(8)].concat());
+ assert_eq!(buttons(&events), [SECONDARY_UP, SECONDARY_DOWN, SECONDARY_UP]);
+ }
+
+ #[test]
+ fn a_canceled_barrel_contact_releases_the_secondary_button() {
+ let mut strokes = BarrelStrokes::default();
+ down(&mut strokes, 7, BARREL);
+ let events = rewrite(&mut strokes, &[start(7), vec![touch(7, TouchPhase::Cancel), Event::PointerGone]].concat());
+ assert_eq!(buttons(&events), [SECONDARY_DOWN, SECONDARY_UP]);
+ assert_eq!(strokes.right, None);
+ }
+
+ #[test]
+ fn a_barrel_contact_that_never_pressed_releases_nothing() {
+ // A finger drives the pointer, so egui-winit sends no button for the pen.
+ let mut strokes = BarrelStrokes::default();
+ down(&mut strokes, 7, BARREL);
+ let events = [vec![touch(7, TouchPhase::Start)], vec![touch(7, TouchPhase::Cancel)]].concat();
+ assert_eq!(rewrite(&mut strokes, &events), events);
+ down(&mut strokes, 7, BARREL);
+ down(&mut strokes, 7, TIP);
+ let events = [vec![touch(7, TouchPhase::Start)], start(7)].concat();
+ assert_eq!(buttons(&rewrite(&mut strokes, &events)), [PRIMARY_DOWN]);
+ }
+
+ #[test]
+ fn contacts_whose_touch_never_arrives_are_bounded() {
+ let mut strokes = BarrelStrokes::default();
+ for id in 0..40 {
+ down(&mut strokes, id, BARREL);
+ }
+ assert_eq!(strokes.pending.len(), MAX_PENDING);
+ assert_eq!(strokes.pending.last(), Some(&(39, true)));
+ }
+}
diff --git a/apps/vectorcraft/tests/automation_args.rs b/apps/vectorcraft/tests/automation_args.rs
index 67e2ec846c..8156ff6784 100644
--- a/apps/vectorcraft/tests/automation_args.rs
+++ b/apps/vectorcraft/tests/automation_args.rs
@@ -60,11 +60,17 @@ fn missing_empty_or_option_operands_fail_before_startup() {
}
}
+/// #3546: a root flag may be given more than once, in either spelling; a bad later operand still
+/// stops the app before it starts.
#[test]
-fn duplicate_roots_fail_for_both_spellings() {
+fn repeated_roots_are_accepted_for_both_spellings() {
for flag in ["--automation-read-root", "--automation-write-root"] {
- rejects(&[flag, ".", &format!("{flag}=.")], &format!("{flag} given twice"));
- rejects(&[&format!("{flag}=."), flag, "."], &format!("{flag} given twice"));
+ let out = Command::new(BIN).args([flag, ".", format!("{flag}=.").as_str(), flag, "./", "--version"]).output().unwrap();
+ assert!(out.status.success(), "{flag}: {}", String::from_utf8_lossy(&out.stderr));
+ assert_eq!(String::from_utf8(out.stdout).unwrap(), format!("vectorcraft {}\n", env!("CARGO_PKG_VERSION")));
+ assert!(out.stderr.is_empty());
+ rejects(&[flag, ".", flag, ""], &format!("{flag} needs a non-empty folder"));
+ rejects(&[&format!("{flag}=."), flag], &format!("{flag} needs a folder"));
}
}
diff --git a/contributors/people.toml b/contributors/people.toml
index 5643212674..f8c6512390 100644
--- a/contributors/people.toml
+++ b/contributors/people.toml
@@ -154,3 +154,8 @@ display_name = "Don Omondi"
[people.alpha-rock]
display_name = "Aditya Sisodiya"
+
+[people.Ronfo2013]
+real_name = "Angelo Bernardini"
+display_name = "Angelo Bernardini"
+sync_github_name = false
diff --git a/crates/affinity/README.md b/crates/affinity/README.md
index 4ffdbabd88..8986dae57e 100644
--- a/crates/affinity/README.md
+++ b/crates/affinity/README.md
@@ -11,6 +11,7 @@ Affinity files.
| Affinity | VectorCraft |
|---|---|
| Pages, Publisher spreads (one or two pages) | artboards, spreads side by side |
+| Master pages (`MpCh`) shown on pages through master page instances (`MPIN`: master, page offset, master page, count) | a locked "Master A, B…" layer at the bottom holding each master page's objects on the pages that show it |
| Artboards (legacy `ABEn` or Affinity 3 `phrp`/`aprp`), with name, paint and any transform | artboards plus a clip group with the actual vector outline, background and stroke |
| Layers (`Scop`), groups (`Grup`), pass-through or isolated | layers and sublayers, groups |
| Curves (`PCrv`): cubic subpaths, closed flags, live corners (`CnrD`) | paths (multi-subpath curves fill even-odd) |
@@ -21,22 +22,24 @@ Affinity files.
| Pixel masks (`MRst`, attached or as a layer in a group) | opacity mask |
| Solid fills: RGBA, HSLA, CMYK, grey, Lab (D50) | fill appearance (alpha as fill opacity) |
| Linear, elliptical and radial gradients with Affinity's midpoint bias | gradients (the bias as the midpoint where the blend is half way) |
-| Strokes: weight, scale with object, dash pattern and phase, alignment, miter limit, behind the fill | stroke appearance |
+| Strokes: weight, scale with object, dash pattern and phase, alignment, miter limit, behind the fill; a stroke whose style is None (every shape stores one, black and 1 px) is left out | stroke appearance |
| Fill layers (`FRst`) | filled rectangles |
-| Artistic and frame text: Unicode scalar-indexed runs, stored fallback font, family/weight/style, boolean OpenType features, all caps, size, tracking, fixed leading, colour, paragraph alignment, first baseline | point type and area type |
+| Artistic and frame text: Unicode scalar-indexed runs, stored fallback font, family/weight/style, boolean OpenType features, all caps, underline, strikethrough, size, tracking, horizontal scale, fixed leading, colour, outlined characters, first baseline; each paragraph's alignment, indents, space before and after, fixed and automatic leading; frame text sized by its text scale (`FTxS`), not its frame's transform | point type and area type, one paragraph style per paragraph; artistic text whose paragraphs align differently keeps them aligned within its longest line (by indents), as Affinity draws it; a frame's first line hangs from its capitals' tops, and a frame whose last lines' descenders hang out of it is made just tall enough to show them; line breaks inside a paragraph become paragraphs without spacing between them; table cells place their text as Affinity does (centred from the capitals' tops to the last baseline, reaching out of a cell too short for it) |
+| Tables (`TxtT`): grid, cell text, merged cells, cell insets and vertical alignment, the line on every cell edge | a group of area type per cell and a stroked line per edge (VectorCraft has no tables) |
| Placed images (`ImgN`): the original JPEG/PNG embedded in the file | embedded images |
-| Pixel layers (`Rstr`): RGBA 8/16-bit and CMYK 8-bit tiles, cropped to their content; source-backed RGBA8 JPEG/PNG tiles with matching dimensions and zero origin | embedded PNG images |
-| Embedded documents and symbols (`EmbN`) | the picture Affinity cached of them |
+| Pixel layers (`Rstr`): RGBA 8/16-bit and CMYK 8-bit tiles, cropped to their content; source-backed RGBA8 JPEG/PNG tiles with matching dimensions and zero origin; the document's CMYK colour profile (`CMYP`) | embedded PNG images; CMYK layers through the document's profile (relative colorimetric, black-point compensation, as Affinity converts them), or, without one, CMYK images that keep their inks |
+| Embedded Affinity documents (`EmbN` with an `EmDc` entry), four deep at most | their first page's content, editable (their artboards only clip, they don't become artboards; their master pages are left out); other embedded documents and symbols as the picture Affinity cached of them |
+| Layer effects: drop shadows, outer glows, inner shadows; outlines; colour and gradient overlays in any blend mode | Stylize › Drop Shadow and Outer Glow, Inner Glow at the edge (approximated); one more stroke on shapes (around their own stroke), the characters' stroke on text; overlays baked into fill, stroke, text colours and pixels (a group's over its children's) |
| Opacity, visibility, lock, names, the blend modes VectorCraft has | the same |
Everything else is reported in the import warnings, one line per kind with a count, never
-dropped silently: layer effects, adjustment layers and live filters, brush and pressure strokes,
-transparency gradients, fill opacity, bitmap fills, master pages, conical gradients (as radial),
+dropped silently: bevel, blur and other layer effects, adjustment layers and live filters, brush and pressure strokes,
+transparency gradients, fill opacity, bitmap fills, master pages based on other master pages, conical gradients (as radial),
special shapes (cloud, heart, cog, callouts, arrows…, imported as their bounding ellipse), corner
types other than round or straight, stars with rounded points, several fills or strokes on one object (the
-active one is used), outlined or scaled text, text fields such as page numbers, frames with
-columns or a curved outline, paragraph indents/spacing, mixed paragraph alignments, unsupported font selectors, grey/Lab/32-bit pixels, CMYK pixels (converted to RGB without the
-document's profile) and Affinity-only blend modes (Add, Linear Light… as Normal).
+active one is used), skewed or flipped text, characters of different transparency in one text, text fields such as page numbers, text threading, frames with
+columns or a curved outline, table cell fills, unsupported font selectors, grey/Lab/32-bit pixels, CMYK pixels with transparency in a document
+without a CMYK profile (converted through VectorCraft's working CMYK profile) and Affinity-only blend modes (Add, Linear Light… as Normal).
When the native document can't be read at all, the engine opens the embedded PNG preview instead,
with a warning that names the reason; that preview can't be placed, used as a template or mined
@@ -78,10 +81,22 @@ of CC0 sample files.
* **Read-only.** Nothing is written in Affinity's format; export waits until someone can check
written files in Affinity itself.
-The reader also has an independent copy in PhotoCraft's `photocraft-affinity`.
+The reader also has independent copies in PhotoCraft's `photocraft-affinity` and DesignCraft's
+`designcraft-affinity`. Tables, paragraph formats, text scale, master pages, layer effects,
+overlays, embedded documents, large pixel layers and HEIC photos were added in DesignCraft
+([storytold/designcraft#291](https://github.com/storytold/designcraft/pull/291)) and brought back
+here, from the same public fixtures and the thumbnails of documents their owners made, used only
+locally. Automatic leading (the font size plus the font's line gap, for artistic and frame text)
+was fitted on the thumbnails of one such local document with 56 artboards and on the public Patchy
+text-frame fixture.
## Validation
+* `engine/tests/affinity_features.rs` covers pages, several artboards per canvas and per spread,
+ master pages, tables, paragraph formats, text scale, layer effects, overlays and embedded
+ documents (whose artboards don't become artboards) on synthetic documents, and mutates them.
+ `engine/tests/affinity_local.rs` compares every artboard of local documents with their thumbnail
+ when `AFFINITY_SAMPLES` points at a folder (never in CI; nothing is committed).
* Unit tests on synthetic containers built by the `synth` feature (stored, zlib and zstd entries,
checksums, budgets, cycles, hostile streams, every truncation) and property tests of random
mutations.
@@ -104,9 +119,14 @@ The reader also has an independent copy in PhotoCraft's `photocraft-affinity`.
pass CI. Run locally with `AFFINITY_CORPUS_REQUIRED=1` for the same strict gate.
* Synthetic engine regressions cover nested, rotated and curved artboards, negative origins,
multiple spreads and resolution conversion, alongside text recovery and native save/export.
-* `engine/tests/import_fuzz.rs` mutates a synthetic native document's stream and archive and checks
- that whatever opens also renders and exports; `fuzz/` has `cargo-fuzz` targets for the whole
- reader (`container`) and the object stream (`stream`):
+* `engine/tests/import_fuzz.rs` mutates a synthetic native document's stream and archive, and
+ documents with layer effects, colour overlays (also over tables), line styles, paragraph and
+ character formats, tables, master pages, CMYK pixel layers and embedded documents (the embedding
+ and the embedded stream), and checks that whatever opens also renders and exports.
+ `tests/import_limits.rs` builds hostile documents against the limits below: grids of 16 million
+ cells, grids and stories shared by many layers, 200 000 paragraphs, a document embedded hundreds
+ of times. `fuzz/` has `cargo-fuzz` targets for the whole reader (`container`) and the object
+ stream (`stream`):
```sh
cd crates/affinity
@@ -132,11 +152,23 @@ anything is allocated: a value takes about 40 bytes in memory however few it too
those 189 public documents uses 3.3 million), 384 levels of object nesting, 128 levels of layers, 500 000 layers, four million curve
nodes per curve; compound outlines also cap recursion at 128 levels, operand visits at 100 000
and cumulative geometry work at four million, rejecting cycles and partial results on limits.
-Pie sweeps normalize finite angles in constant time. Pixel layers are limited to 64 megapixels
-(cropped to their content first); gradients to 1024 stops. Text collection is bounded to a
-million characters per node before allocation, with a cumulative 16 MiB budget for owned font
-names, features and gradient stops. Exhaustion warns and uses default attributes for remaining
-text, preserving its characters.
+Pie sweeps normalize finite angles in constant time. Pixel layers are decoded at no more than 64
+megapixels each (cropped to their content first; larger ones are read at a half, a quarter… of
+their resolution) and 512 megapixels for the whole document; pixel masks are read only over what
+they mask (all of it under artistic text, whose glyphs only the layout places). One budget covers
+the whole read: layers, pixels, 16 million characters of stories and 262 144 table cells, so
+content that many layers link, or a document embedded many times, can't multiply them. Embedded
+documents nest four deep at most; both of their readings are charged to that budget and to the
+importing document's archive limits, also when they fail part of the way. Tables have at most
+4096 rows and columns and 65 536 cells, and 64 layer effects per node are read. Gradients are
+limited to 1024 stops. Text collection is bounded to a million characters per node before
+allocation, with a cumulative 16 MiB budget for owned font names (256 bytes at most each),
+features and gradient stops; paragraph formats are matched to runs by binary search. Exhaustion
+warns and uses default attributes for remaining text, preserving its characters. Colour and
+gradient overlays share one work budget per import (`overlay::MAX_WORK`: the nodes and pixels
+each is baked into); past it they are left out, and said. In VectorCraft, master pages are
+copied onto at most as many objects, characters and pixels as a document may hold, a few times
+over, and objects beyond `MAX_COORD` of the origin are left out.
Every archive entry's CRC-32 and size must match. Malformed input returns an `Error`; the
crate has no panics outside tests.
diff --git a/crates/affinity/src/container.rs b/crates/affinity/src/container.rs
index 31179a3a0e..6b1df95103 100644
--- a/crates/affinity/src/container.rs
+++ b/crates/affinity/src/container.rs
@@ -263,6 +263,21 @@ impl<'a> Archive<'a> {
}
/// Extract an entry by name: decompress, undo the byte predictor and verify the CRC.
+ /// What is left of the limits for documents embedded in this one.
+ pub(crate) fn remaining(&self) -> Limits {
+ Limits { max_entry: self.limits.max_entry, max_total: self.limits.max_total.saturating_sub(self.extracted) }
+ }
+
+ /// Count `n` bytes extracted elsewhere (from embedded documents) against this import.
+ pub(crate) fn charge(&mut self, n: usize) -> Result<(), Error> {
+ let total = self.extracted.checked_add(n).ok_or(Error::Limit("document too large"))?;
+ if total > self.limits.max_total {
+ return Err(Error::Limit("document too large"));
+ }
+ self.extracted = total;
+ Ok(())
+ }
+
pub fn read(&mut self, name: &str) -> Result, Error> {
let e = self.entries.get(name).ok_or(Error::Malformed("missing archive entry"))?.clone();
let size = usize::try_from(e.size).map_err(|_| Error::Limit("archive entry too large"))?;
diff --git a/crates/affinity/src/lib.rs b/crates/affinity/src/lib.rs
index 4be46c7770..38d86a8990 100644
--- a/crates/affinity/src/lib.rs
+++ b/crates/affinity/src/lib.rs
@@ -14,6 +14,7 @@ mod access;
pub mod container;
mod geometry;
pub mod model;
+pub mod overlay;
pub mod paint;
pub mod preview;
mod raster;
diff --git a/crates/affinity/src/model.rs b/crates/affinity/src/model.rs
index 298e32be21..5a1feaab41 100644
--- a/crates/affinity/src/model.rs
+++ b/crates/affinity/src/model.rs
@@ -1,4 +1,4 @@
-//! The document model VectorCraft imports: spreads, artboards, layers, groups, curves, shapes,
+//! The document model the Craft apps import: spreads, artboards, layers, groups, curves, shapes,
//! text and images, with transforms composed into document space. Anything else is reported
//! by [`Document::warnings`] instead of being dropped silently.
@@ -175,17 +175,54 @@ pub struct TextRun {
/// Boolean OpenType feature overrides, as tags or `-tag` for disabled features.
pub features: Vec,
pub all_caps: bool,
+ /// Underlined characters (`Ints` slot 0 is 1; identified on underlined words in a document its
+ /// owner made, all other characters there and in the public corpus have 0).
+ pub underline: bool,
+ /// Struck-through characters (`Ints` slot 1 is 1; identified the same way, on prices struck
+ /// through in another document its owner made).
+ pub strikethrough: bool,
/// Font size in document pixels, before the node's transform.
pub size: f64,
/// Tracking in em.
pub tracking: f64,
+ /// Horizontal scale of the glyphs (1 = as designed).
+ pub h_scale: f64,
/// Fixed line pitch in document pixels, when the run overrides automatic leading.
pub leading: Option,
pub fill: Paint,
+ /// Outlined characters: the outline's paint and width (node space).
+ pub stroke: Option,
+ /// The run's paragraph: alignment, indents and spacing.
+ pub paragraph: Paragraph,
}
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+/// Paragraph alignment, indents, spacing and leading, in node space (document pixels before the
+/// node's text scale).
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub struct Paragraph {
+ pub align: Align,
+ /// Indent of every line but the first, from the left.
+ pub left: f64,
+ pub right: f64,
+ /// Indent of the first line, from the left.
+ pub first: f64,
+ pub space_before: f64,
+ pub space_after: f64,
+ /// Fixed distance between baselines, when the paragraph sets one.
+ pub leading: Option,
+ /// Automatic leading as a multiple of the font's own line height (ascent plus descent).
+ pub auto_leading: f64,
+}
+
+impl Default for Paragraph {
+ fn default() -> Self {
+ Self { align: Align::Left, left: 0.0, right: 0.0, first: 0.0, space_before: 0.0, space_after: 0.0, leading: None, auto_leading: 1.0 }
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Align {
+ #[default]
Left,
Center,
Right,
@@ -202,12 +239,69 @@ pub struct Text {
pub frame: Option,
/// Node space to document pixels.
pub transform: Affine,
+ /// Node space to document pixels for the type (its linear part matters): artistic text scales
+ /// with its node, frame text only with its frame's text scale.
+ pub text_transform: Affine,
+}
+
+/// Vertical alignment of a table cell's text.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum VAlign {
+ Top,
+ Center,
+ Bottom,
+}
+
+#[derive(Debug, Clone, PartialEq)]
+pub struct TableCell {
+ pub runs: Vec,
+ /// Space between the cell edges and its text, in node space: left, top, right, bottom.
+ pub inset: [f64; 4],
+ pub valign: VAlign,
+ /// Part of the cell to its left (merged): it has no text of its own.
+ pub merged_left: bool,
+}
+
+/// A table: a grid of cells with text, and a line on every cell edge.
+#[derive(Debug, Clone, PartialEq)]
+pub struct Table {
+ /// Column boundaries (one more than the columns), increasing, in node space.
+ pub columns: Vec,
+ /// Row boundaries (one more than the rows), increasing, in node space.
+ pub rows: Vec,
+ /// Row by row.
+ pub cells: Vec,
+ /// Vertical edges row by row, one more per row than the columns; `None` draws no line, and
+ /// the list is empty when the file's didn't match the grid.
+ pub vertical: Vec>,
+ /// Horizontal edges boundary by boundary (one more than the rows), one per column (empty
+ /// as `vertical` can be).
+ pub horizontal: Vec >,
+ /// Node space to document pixels.
+ pub transform: Affine,
+ /// Node space to document pixels for the cells' type: resizing a table moves its grid, not
+ /// its type.
+ pub text_transform: Affine,
+}
+
+impl Table {
+ pub fn ncols(&self) -> usize {
+ self.columns.len().saturating_sub(1)
+ }
+ pub fn nrows(&self) -> usize {
+ self.rows.len().saturating_sub(1)
+ }
}
#[derive(Debug, Clone, PartialEq)]
pub enum Pixels {
/// Straight-alpha RGBA, 8 bits per channel, row by row.
Rgba8(Vec),
+ /// A CMYK pixel layer: cyan, magenta, yellow and black ink amounts (0 none, 255 full) and
+ /// straight alpha, 8 bits each, row by row. Left in CMYK for the importer to show through a
+ /// colour profile: the profile-free formula turns the extra cyan of a separation's neutrals
+ /// into a blue cast.
+ Cmyka8(Vec),
/// The original file a placed image was made from (PNG, JPEG…), as embedded.
Encoded(Vec),
}
@@ -246,11 +340,78 @@ pub enum Kind {
even_odd: bool,
},
Text(Text),
+ Table(Table),
Image(Image),
+ /// A master page shown on this spread's pages: pages `page..page + count` show the master
+ /// spread [`Document::masters`]`[master]`'s pages from `master_page` on.
+ MasterInstance {
+ master: usize,
+ page: usize,
+ master_page: usize,
+ count: usize,
+ },
/// Something this reader does not import; its children are still imported.
Unsupported,
}
+/// A layer effect. Lengths are document pixels; `angle` is the direction the shadow is offset in
+/// (radians, clockwise from +x as y points down: π/2 puts it below).
+#[derive(Debug, Clone, PartialEq)]
+pub enum Effect {
+ DropShadow {
+ color: crate::paint::Color,
+ opacity: f64,
+ radius: f64,
+ distance: f64,
+ angle: f64,
+ },
+ InnerShadow {
+ color: crate::paint::Color,
+ opacity: f64,
+ radius: f64,
+ distance: f64,
+ angle: f64,
+ },
+ OuterGlow {
+ color: crate::paint::Color,
+ opacity: f64,
+ radius: f64,
+ },
+ /// An outline of `width` around the node's shape: `align` 0 outside, 1 inside, 2 centred.
+ Outline {
+ color: crate::paint::Color,
+ opacity: f64,
+ width: f64,
+ align: u16,
+ },
+ /// Bevel and emboss: lit and shaded edges `size` wide. `angle` is the light's azimuth
+ /// (radians, counter-clockwise from +x with y up), `depth` Affinity's depth (5 by default);
+ /// `inner` is false for the outer, emboss and pillow kinds.
+ Bevel {
+ size: f64,
+ depth: f64,
+ angle: f64,
+ highlight: crate::paint::Color,
+ highlight_opacity: f64,
+ shadow: crate::paint::Color,
+ shadow_opacity: f64,
+ inner: bool,
+ },
+ /// Colour overlay: everything the node paints takes `color`, laid over it in `blend` mode at
+ /// `opacity` (the node's own alpha is kept).
+ ColorOverlay {
+ color: crate::paint::Color,
+ opacity: f64,
+ blend: Blend,
+ },
+ /// Gradient overlay: a colour overlay whose colour comes from `gradient` (document pixels).
+ GradientOverlay {
+ gradient: crate::paint::Gradient,
+ opacity: f64,
+ blend: Blend,
+ },
+}
+
#[derive(Debug, Clone, PartialEq)]
pub struct Node {
pub class: Tag,
@@ -264,6 +425,8 @@ pub struct Node {
pub mask: Option,
/// Pixel mask: grey levels (white shows the node, black hides it); outside it the node is hidden.
pub pixel_mask: Option,
+ /// Layer effects the importer can show or bake in (others are reported).
+ pub effects: Vec,
/// Bottom to top.
pub children: Vec,
}
@@ -285,12 +448,21 @@ pub struct Document {
/// Pixels per inch: all geometry is in document pixels at this resolution.
pub dpi: f64,
pub spreads: Vec,
+ /// Master spreads, which [`Kind::MasterInstance`] nodes show on pages.
+ pub masters: Vec,
/// Application that last saved the file, as stored (`Affinity 3.0.2`), when present.
pub saved_by: Option,
/// Content that was not imported or was approximated, one line per kind, deduplicated.
pub warnings: Vec,
+ /// The document's CMYK colour profile (an ICC file), when it embeds one: the root's `CMYP`,
+ /// which each CMYK pixel layer's colour settings (`Prof`) also name, with relative
+ /// colorimetric intent and black-point compensation in every document checked.
+ pub cmyk_profile: Option>,
}
+/// Largest embedded colour profile kept (real CMYK profiles are a few megabytes).
+const MAX_PROFILE_BYTES: usize = 32 << 20;
+
/// Deepest layer nesting followed; deeper content is reported, not imported.
const MAX_TREE_DEPTH: usize = 128;
/// Total layer nodes imported.
@@ -300,6 +472,32 @@ const MAX_NODES: usize = 500_000;
/// count the bytes extracted from it, and a layer of one flat colour needs none (#1704).
const MAX_LAYER_PIXELS: u64 = 512 << 20;
+/// Embedded documents inside embedded documents are followed this deep.
+const MAX_EMBED_DEPTH: usize = 4;
+/// Characters of all stories together (a story may be shared by many text layers).
+const MAX_DOCUMENT_CHARS: usize = 16 << 20;
+/// Table cells of all tables together (each becomes a text object with its edge lines).
+const MAX_DOCUMENT_CELLS: usize = 1 << 18;
+
+/// What a whole read may still use. Shared objects can be linked from many layers, and embedded
+/// documents are read with what their embedding document left, so linking or embedding the
+/// same content many times can't multiply the work.
+#[derive(Clone, Copy, Debug)]
+pub(crate) struct Budget {
+ /// Layer nodes ([`MAX_NODES`] in all).
+ pub(crate) nodes: usize,
+ /// Pixels the pixel layers may decode ([`MAX_LAYER_PIXELS`] in all).
+ pub(crate) pixels: u64,
+ /// Characters of stories ([`MAX_DOCUMENT_CHARS`] in all).
+ pub(crate) chars: usize,
+ /// Table cells ([`MAX_DOCUMENT_CELLS`] in all).
+ pub(crate) cells: usize,
+}
+
+impl Budget {
+ pub(crate) const FULL: Budget = Budget { nodes: MAX_NODES, pixels: MAX_LAYER_PIXELS, chars: MAX_DOCUMENT_CHARS, cells: MAX_DOCUMENT_CELLS };
+}
+
/// Read a document: archive, `doc.dat` and the model.
pub fn read(bytes: &[u8], limits: Limits) -> Result {
read_within(bytes, limits, MAX_LAYER_PIXELS)
@@ -307,35 +505,81 @@ pub fn read(bytes: &[u8], limits: Limits) -> Result {
/// [`read`], its pixel layers holding at most `pixels` pixels together.
pub(crate) fn read_within(bytes: &[u8], limits: Limits, pixels: u64) -> Result {
- let mut archive = Archive::open(bytes, limits)?;
+ read_at(bytes, limits, &mut Budget { pixels, ..Budget::FULL }, Affine::IDENTITY, 0).document
+}
+
+/// A document read by [`read_at`] (or why it couldn't be), with the bytes its archive extracted
+/// either way.
+struct ReadAt {
+ document: Result,
+ extracted: usize,
+}
+
+/// Read a document whose spreads are placed by `base` (for embedded documents, nested `depth`
+/// deep). What it uses is taken from `budget`, also when it fails part of the way.
+fn read_at(bytes: &[u8], limits: Limits, budget: &mut Budget, base: Affine, depth: usize) -> ReadAt {
+ let mut archive = match Archive::open(bytes, limits) {
+ Ok(a) => a,
+ Err(e) => return ReadAt { document: Err(e), extracted: 0 },
+ };
+ let document = read_archive(&mut archive, budget, base, depth);
+ ReadAt { document, extracted: archive.extracted() }
+}
+
+fn read_archive(archive: &mut Archive, budget: &mut Budget, base: Affine, depth: usize) -> Result {
let doc = archive.read("doc.dat")?;
let s = stream::parse(&doc)?;
- let mut reader = Reader::new(&s, &mut archive);
- reader.pixels_left = pixels;
- reader.document()
+ let mut reader = Reader::new(&s, archive, base, depth);
+ reader.budget = *budget;
+ let document = reader.document();
+ *budget = reader.budget;
+ document
}
pub(crate) struct Reader<'s, 'a, 'b> {
pub(crate) s: &'s Stream,
pub(crate) archive: &'b mut Archive<'a>,
pub(crate) dpi: f64,
- warnings: BTreeMap,
- nodes: usize,
+ pub(crate) warnings: BTreeMap,
active: HashSet,
- /// Pixels the pixel layers still to come may decode ([`MAX_LAYER_PIXELS`] in all).
- pub(crate) pixels_left: u64,
+ /// Where the spreads go: the identity, or an embedding document's placement.
+ base: Affine,
+ /// The linear part of `base`, which also scales frame text.
+ pub(crate) type_base: Affine,
+ /// How deep inside embedded documents this one is.
+ depth: usize,
+ /// An embedded document's content, waiting to become its node's children.
+ pending: Option>,
+ /// The master spreads, in the order of [`Document::masters`].
+ master_ids: Vec,
+ /// What the rest of the read may use.
+ pub(crate) budget: Budget,
}
impl<'s, 'a, 'b> Reader<'s, 'a, 'b> {
- fn new(s: &'s Stream, archive: &'b mut Archive<'a>) -> Self {
- Self { s, archive, dpi: 72.0, warnings: BTreeMap::new(), nodes: 0, active: HashSet::new(), pixels_left: MAX_LAYER_PIXELS }
+ pub(crate) fn new(s: &'s Stream, archive: &'b mut Archive<'a>, base: Affine, depth: usize) -> Self {
+ let [a, b, c, d, ..] = base.0;
+ Self {
+ s,
+ archive,
+ dpi: 72.0,
+ warnings: BTreeMap::new(),
+ active: HashSet::new(),
+ base,
+ type_base: Affine([a, b, c, d, 0.0, 0.0]),
+ depth,
+ pending: None,
+ master_ids: Vec::new(),
+ budget: Budget::FULL,
+ }
}
pub(crate) fn warn(&mut self, what: impl Into) {
*self.warnings.entry(what.into()).or_default() += 1;
}
- fn document(mut self) -> Result {
+ /// The document.
+ fn document(&mut self) -> Result {
let s = self.s;
let root = s.root;
self.dpi = s.obj(root, b"UVCn").and_then(|u| s.f64(u, b"UPPI")).filter(|d| *d > 0.0 && *d < 100_000.0).unwrap_or(72.0);
@@ -347,40 +591,65 @@ impl<'s, 'a, 'b> Reader<'s, 'a, 'b> {
}
});
let doc = s.obj(root, b"DocR").ok_or(Error::Malformed("document has no root node"))?;
+ self.master_ids = s.objs(doc, b"MpCh").into_iter().filter(|m| s.is(*m, b"Sprd")).collect();
let mut spreads = Vec::new();
for spread in s.objs(doc, b"Chld") {
- if !s.is(spread, b"Sprd") {
- self.warn("an unknown kind of page");
- continue;
+ if let Some(sp) = self.spread(doc, spread)? {
+ spreads.push(sp);
}
- let pages = pages(s, spread);
- let default_size =
- s.floats::<2>(doc, b"DfSz").filter(|[w, h]| *w > 0.0 && *h > 0.0).map(|[w, h]| Rect { x0: 0.0, y0: 0.0, x1: w, y1: h });
- let bounds = s.floats::<4>(spread, b"SprB").map(rect).or_else(|| pages.iter().copied().reduce(union)).or(default_size).unwrap_or(Rect {
- x0: 0.0,
- y0: 0.0,
- x1: 0.0,
- y1: 0.0,
- });
- let transparent = s.bool(spread, b"SprT").unwrap_or(false);
- let (nodes, mask) = self.children(spread, Affine::IDENTITY, 0)?;
- if mask.is_some() {
- self.warn("mask layers directly on a page (imported without them)");
- }
- spreads.push(Spread { bounds, pages, transparent, nodes });
}
if spreads.is_empty() {
return Err(Error::Malformed("document has no pages"));
}
- if !s.objs(doc, b"MpCh").is_empty() {
- self.warn("master pages (their content is not placed on the pages that use them)");
+ let mut masters = Vec::new();
+ for master in self.master_ids.clone() {
+ match self.spread(doc, master)? {
+ Some(sp) => masters.push(sp),
+ // Keep the indices of `MasterInstance::master` valid.
+ None => masters.push(Spread {
+ bounds: Rect { x0: 0.0, y0: 0.0, x1: 0.0, y1: 0.0 },
+ pages: Vec::new(),
+ transparent: true,
+ nodes: Vec::new(),
+ }),
+ }
}
- let warnings = self.warnings.into_iter().map(|(w, n)| if n > 1 { format!("{w} ({n}×)") } else { w }).collect();
- Ok(Document { dpi: self.dpi, spreads, saved_by, warnings })
+ let cmyk_profile = s
+ .obj(root, b"CMYP")
+ .and_then(|p| s.bytes(p, b"Data"))
+ .filter(|b| b.len() <= MAX_PROFILE_BYTES && b.get(16..20) == Some(b"CMYK".as_slice()))
+ .map(<[u8]>::to_vec);
+ let warnings = std::mem::take(&mut self.warnings).into_iter().map(|(w, n)| if n > 1 { format!("{w} ({n}×)") } else { w }).collect();
+ Ok(Document { dpi: self.dpi, spreads, masters, saved_by, warnings, cmyk_profile })
}
- /// The children of `parent`, and the pixel mask a mask layer among them puts on the parent.
- fn children(&mut self, parent: ObjId, world: Affine, depth: usize) -> Result<(Vec, Option), Error> {
+ /// A spread (`Sprd`) of the document `doc`, or of its master spreads.
+ fn spread(&mut self, doc: ObjId, spread: ObjId) -> Result, Error> {
+ let s = self.s;
+ if !s.is(spread, b"Sprd") {
+ self.warn("an unknown kind of page");
+ return Ok(None);
+ }
+ let pages = pages(s, spread);
+ let default_size = s.floats::<2>(doc, b"DfSz").filter(|[w, h]| *w > 0.0 && *h > 0.0).map(|[w, h]| Rect { x0: 0.0, y0: 0.0, x1: w, y1: h });
+ let bounds = s.floats::<4>(spread, b"SprB").map(rect).or_else(|| pages.iter().copied().reduce(union)).or(default_size).unwrap_or(Rect {
+ x0: 0.0,
+ y0: 0.0,
+ x1: 0.0,
+ y1: 0.0,
+ });
+ let transparent = s.bool(spread, b"SprT").unwrap_or(false);
+ let (nodes, mask) = self.children(spread, self.base, 0)?;
+ if mask.is_some() {
+ self.warn("mask layers directly on a page (imported without them)");
+ }
+ Ok(Some(Spread { bounds, pages, transparent, nodes }))
+ }
+
+ /// The children of `parent`, and the mask layer among them that masks the parent (with its
+ /// placement), read later over just what it masks.
+ #[allow(clippy::type_complexity)]
+ fn children(&mut self, parent: ObjId, world: Affine, depth: usize) -> Result<(Vec, Option<(ObjId, Affine)>), Error> {
let s = self.s;
let mut out = Vec::new();
let mut mask = None;
@@ -391,10 +660,10 @@ impl<'s, 'a, 'b> Reader<'s, 'a, 'b> {
continue;
}
let local = s.floats::<6>(c, b"Xfrm").map(Affine::from_xfrm).unwrap_or(Affine::IDENTITY);
- match crate::raster::mask(self, c, local.then(world))? {
- Some(m) if mask.is_none() => mask = Some(m),
- Some(_) => self.warn("several pixel masks on one layer (only the first is used)"),
- None => {}
+ if mask.is_none() {
+ mask = Some((c, local.then(world)));
+ } else {
+ self.warn("several pixel masks on one layer (only the first is used)");
}
continue;
}
@@ -411,10 +680,10 @@ impl<'s, 'a, 'b> Reader<'s, 'a, 'b> {
self.warn("layers nested deeper than 128 levels");
return Ok(None);
}
- self.nodes += 1;
- if self.nodes > MAX_NODES {
+ let Some(left) = self.budget.nodes.checked_sub(1) else {
return Err(Error::Limit("too many layers"));
- }
+ };
+ self.budget.nodes = left;
// A node that contains itself (a shared object linked back into its own subtree).
if !self.active.insert(id) {
self.warn("a layer that contains itself");
@@ -441,15 +710,28 @@ impl<'s, 'a, 'b> Reader<'s, 'a, 'b> {
} else {
self.kind(id, class, world, parent)?
};
+ // This node's embedded content, before its children's `node` calls can take it.
+ let embedded = self.pending.take();
// A compound's children are its operands, already merged into its outline.
- let (children, child_mask) = if class == Tag::of(b"Comp") { (Vec::new(), None) } else { self.children(id, world, depth)? };
- let (mask, attached_mask) = self.attached_masks(id, world)?;
+ let (mut children, child_mask) = if class == Tag::of(b"Comp") { (Vec::new(), None) } else { self.children(id, world, depth)? };
+ if let Some(embedded) = embedded {
+ children.extend(embedded);
+ }
+ // Pixel masks are read only over what they mask (they can span a whole spread at print
+ // resolution, a gigapixel).
+ let over = mask_extent(&kind, &children);
+ let child_mask = match child_mask {
+ Some((c, at)) => crate::raster::mask(self, c, at, over)?,
+ None => None,
+ };
+ let (mask, attached_mask) = self.attached_masks(id, world, over)?;
let pixel_mask = attached_mask.or(child_mask);
self.active.remove(&id);
- if s.objs(id, b"FiEf").iter().any(|e| s.bool(*e, b"Enab") != Some(false)) {
- self.warn("layer effects (shadows, glows, outlines, bevels…)");
- }
- Ok(Some(Node { class, name, visible, locked, opacity, blend, kind, mask, pixel_mask, children }))
+ let mut node = Node { class, name, visible, locked, opacity, blend, kind, mask, pixel_mask, effects: Vec::new(), children };
+ // Gradient overlays are laid out over the node's bounds, also while it is hidden.
+ let bounds = tree_bounds(&node);
+ node.effects = self.effects(id, world, bounds);
+ Ok(Some(node))
}
fn kind(&mut self, id: ObjId, class: Tag, world: Affine, parent: Affine) -> Result {
@@ -471,6 +753,13 @@ impl<'s, 'a, 'b> Reader<'s, 'a, 'b> {
let (fills, strokes) = paint::node_paint(self, id, world);
Kind::Shape { path: local.transformed(world), fills, strokes, even_odd }
}
+ b"TxtT" => match crate::text::table(self, id, world) {
+ Some(t) => Kind::Table(t),
+ None => {
+ self.warn("tables that could not be read");
+ Kind::Unsupported
+ }
+ },
b"TxtA" | b"TxtF" | b"TxtC" => match crate::text::read(self, id, world) {
Some(t) => Kind::Text(t),
None => {
@@ -482,15 +771,35 @@ impl<'s, 'a, 'b> Reader<'s, 'a, 'b> {
Some(img) => Kind::Image(img),
None => Kind::Unsupported,
},
- b"EmbN" => match crate::raster::embedded(self, id, world)? {
- Some(img) => {
- self.warn("embedded documents and symbols (imported as pictures of them)");
- Kind::Image(img)
+ b"MPIN" => {
+ // `SLnk` links the instance with the master spread it shows.
+ let linked = s.obj(id, b"SLnk").map(|l| s.objs(l, b"ILOb")).unwrap_or_default();
+ let master = linked.iter().find_map(|o| self.master_ids.iter().position(|m| m == o));
+ let at = |t: &[u8; 4], default: usize| s.int(id, t).and_then(|v| usize::try_from(v).ok()).unwrap_or(default).min(4096);
+ match master {
+ Some(master) => Kind::MasterInstance { master, page: at(b"PgOf", 0), master_page: at(b"MPOf", 0), count: at(b"PgCt", 1) },
+ None => {
+ self.warn("master page instances without their master");
+ Kind::Unsupported
+ }
}
- None => {
- self.warn("embedded documents and symbols without a cached picture");
- Kind::Unsupported
+ }
+ b"EmbN" => match self.embedded_document(id, world) {
+ // The embedded document itself, as editable content.
+ Some(nodes) => {
+ self.pending = Some(nodes);
+ Kind::Group
}
+ None => match crate::raster::embedded(self, id, world)? {
+ Some(img) => {
+ self.warn("embedded documents and symbols (imported as pictures of them)");
+ Kind::Image(img)
+ }
+ None => {
+ self.warn("embedded documents and symbols without a cached picture");
+ Kind::Unsupported
+ }
+ },
},
b"FRst" => {
// A fill layer paints its whole bitmap area; its gradient lives in page space.
@@ -515,9 +824,89 @@ impl<'s, 'a, 'b> Reader<'s, 'a, 'b> {
})
}
+ /// The enabled layer effects (`FiEf`) of node `id`. The angle convention was measured on the
+ /// public MIT fx fixture (Patchy): an angle of π/2 with offset 10 shadows 10 below.
+ fn effects(&mut self, id: ObjId, world: Affine, bounds: Option) -> Vec {
+ let s = self.s;
+ let mut out = Vec::new();
+ for e in s.objs(id, b"FiEf").into_iter().take(64) {
+ if s.bool(e, b"Enab") == Some(false) {
+ continue;
+ }
+ // "Scale with object": lengths follow the node's transform; otherwise they are absolute.
+ let k = if s.bool(e, b"SclO") == Some(true) { world.scale() } else { 1.0 };
+ let len = |t: &[u8; 4]| s.f64(e, t).filter(|v| v.is_finite() && *v >= 0.0 && *v < 1e6).unwrap_or(0.0) * k;
+ let opacity = s.f64(e, b"Opac").filter(|v| v.is_finite()).unwrap_or(1.0).clamp(0.0, 1.0);
+ let angle = s.f64(e, b"Angl").filter(|v| v.is_finite()).unwrap_or(0.0);
+ let color = s.obj(e, b"Colr").and_then(|c| crate::paint::color(self, c));
+ let class = s.class(e).map(|c| c.0.to_be_bytes());
+ match (class.as_ref(), color) {
+ (Some(b"Shad"), Some(color)) => out.push(Effect::DropShadow { color, opacity, radius: len(b"Radi"), distance: len(b"Offs"), angle }),
+ (Some(b"InnS"), Some(color)) => out.push(Effect::InnerShadow { color, opacity, radius: len(b"Radi"), distance: len(b"Offs"), angle }),
+ (Some(b"OutG"), Some(color)) => out.push(Effect::OuterGlow { color, opacity, radius: len(b"Radi") }),
+ (Some(b"Strk"), Some(color)) if s.enumeration(e, b"Ftyp").is_none_or(|(t, _)| t == 0) => {
+ let align = s.enumeration(e, b"Alig").map_or(0, |(a, _)| a);
+ out.push(Effect::Outline { color, opacity, width: len(b"Radi"), align });
+ }
+ (Some(b"Strk"), _) => self.warn("gradient outline effects (left out)"),
+ (Some(b"BevE" | b"EmbE"), _) => {
+ // No radius, no bevel (as Affinity draws it).
+ let size = len(b"Radi");
+ if size > 0.0 {
+ let white = crate::paint::Color::Rgb { r: 1.0, g: 1.0, b: 1.0, a: 1.0 };
+ let black = crate::paint::Color::Rgb { r: 0.0, g: 0.0, b: 0.0, a: 1.0 };
+ let highlight = s.obj(e, b"HiCl").and_then(|c| crate::paint::color(self, c)).unwrap_or(white);
+ let shadow = s.obj(e, b"ShCl").and_then(|c| crate::paint::color(self, c)).unwrap_or(black);
+ let shadow_opacity = s.f64(e, b"ShOp").filter(|v| v.is_finite()).unwrap_or(0.75).clamp(0.0, 1.0);
+ let depth = s.f64(e, b"Dept").filter(|v| v.is_finite()).unwrap_or(5.0);
+ let azimuth = s.f64(e, b"Azim").filter(|v| v.is_finite()).unwrap_or(std::f64::consts::FRAC_PI_4 * 3.0);
+ let inner = s.enumeration(e, b"Beve").is_none_or(|(k, _)| k == 0);
+ out.push(Effect::Bevel { size, depth, angle: azimuth, highlight, highlight_opacity: opacity, shadow, shadow_opacity, inner });
+ }
+ }
+ (Some(b"ColO"), Some(color)) => {
+ let blend = self.effect_blend(e);
+ out.push(Effect::ColorOverlay { color, opacity, blend });
+ }
+ (Some(b"GrdO"), _) => {
+ let blend = self.effect_blend(e);
+ // The gradient's unit space spans the node's bounding box from -1 to 1, centred
+ // on it (y down): checked against the stored previews of real documents.
+ let space =
+ bounds.map(|b| Affine([(b.x1 - b.x0) / 2.0, 0.0, 0.0, (b.y1 - b.y0) / 2.0, (b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0]));
+ match (s.obj(e, b"GrFl"), space) {
+ (Some(fill), Some(space)) => match paint::descriptor(self, fill, space) {
+ Some(Paint::Gradient(gradient)) => out.push(Effect::GradientOverlay { gradient, opacity, blend }),
+ Some(Paint::Solid(color)) => out.push(Effect::ColorOverlay { color, opacity, blend }),
+ _ => {}
+ },
+ // Nothing visible to lay it over.
+ (Some(_), None) => {}
+ (None, _) => self.warn("gradient overlay effects that could not be read (left out)"),
+ }
+ }
+ (Some(b"ColO"), None) => self.warn("colour overlay effects that could not be read (left out)"),
+ (Some(b"Gaus"), _) => self.warn("blur effects (left out)"),
+ _ => self.warn("layer effects of other kinds (left out)"),
+ }
+ }
+ out
+ }
+
+ /// A layer effect's blend mode (`BlnM`); unknown modes are Normal (warned).
+ fn effect_blend(&mut self, e: ObjId) -> Blend {
+ match self.s.enumeration(e, b"BlnM") {
+ None => Blend::Normal,
+ Some((i, v)) => Blend::from_enum(i, v).unwrap_or_else(|| {
+ self.warn("an unknown blend mode (imported as Normal)");
+ Blend::Normal
+ }),
+ }
+ }
+
/// Vector shapes attached to a node (`AdCh`) mask it: it shows only inside their outlines;
/// an attached mask layer is a pixel mask. Adjustments attached the same way are reported.
- fn attached_masks(&mut self, id: ObjId, world: Affine) -> Result<(Option, Option), Error> {
+ fn attached_masks(&mut self, id: ObjId, world: Affine, over: Option) -> Result<(Option, Option), Error> {
let s = self.s;
let attached = s.objs(id, b"AdCh");
let mut mask: Option = None;
@@ -534,7 +923,7 @@ impl<'s, 'a, 'b> Reader<'s, 'a, 'b> {
}
} else if class == Tag::of(b"MRst") {
let local = s.floats::<6>(a, b"Xfrm").map(Affine::from_xfrm).unwrap_or(Affine::IDENTITY).then(world);
- match crate::raster::mask(self, a, local)? {
+ match crate::raster::mask(self, a, local, over)? {
Some(m) if pixels.is_none() => pixels = Some(m),
Some(_) => self.warn("several pixel masks on one layer (only the first is used)"),
None => {}
@@ -546,6 +935,93 @@ impl<'s, 'a, 'b> Reader<'s, 'a, 'b> {
Ok((mask, pixels))
}
+ /// The content of an Affinity document embedded in this one (`EmbN` whose `EmbC` entry holds
+ /// `EmDc`, four more bytes and a complete Affinity document): its first spread's nodes,
+ /// placed so the centre of its page, first artboard or content is the node's origin.
+ fn embedded_document(&mut self, id: ObjId, world: Affine) -> Option> {
+ let s = self.s;
+ let entry = s.obj(id, b"Bitm").and_then(|b| s.obj(b, b"EmCn")).and_then(|c| s.entry(c, b"EmbC"))?.to_string();
+ if entry.is_empty() {
+ return None;
+ }
+ if self.depth >= MAX_EMBED_DEPTH {
+ self.warn("embedded documents nested more than four deep");
+ return None;
+ }
+ let data = self.archive.read(&entry).ok()?;
+ let inner = data.strip_prefix(b"EmDc").and_then(|d| d.get(4..))?;
+ if !crate::is_affinity(inner) {
+ return None;
+ }
+ // A first reading finds its page and resolution, the second places it.
+ // Both readings are charged to the budget and the archive's limits, also when they fail:
+ // each does the work.
+ let mut budget = self.budget;
+ let probe = read_at(inner, self.archive.remaining(), &mut budget, Affine::IDENTITY, self.depth + 1);
+ self.budget = budget;
+ if self.archive.charge(probe.extracted).is_err() {
+ self.warn("embedded documents beyond the size limit (left out)");
+ return None;
+ }
+ let probe = match probe.document {
+ Ok(d) => d,
+ Err(e) => {
+ self.warn(format!("embedded documents that could not be read ({e})"));
+ return None;
+ }
+ };
+ let spread = probe.spreads.first()?;
+ // `PBBx` 2 places the content's own bounds (as with a cached picture); otherwise its page.
+ let content = s.obj(id, b"Bitm").and_then(|b| s.enumeration(b, b"PBBx")).is_some_and(|(k, _)| k == 2);
+ let first_board = spread.nodes.iter().find_map(|n| if let Kind::Artboard { rect, .. } = &n.kind { Some(*rect) } else { None });
+ let page = if content { None } else { spread.pages.first().copied().or(first_board) };
+ let page = page.or_else(|| nodes_bounds(&spread.nodes)).unwrap_or(spread.bounds);
+ // Its pixels aren't needed any more: never hold both readings' at once.
+ drop(probe);
+ // Its document pixels are the node's units, whatever either document's resolution.
+ let k = 1.0;
+ let (cx, cy) = ((page.x0 + page.x1) / 2.0, (page.y0 + page.y1) / 2.0);
+ let base = Affine([k, 0.0, 0.0, k, -cx * k, -cy * k]).then(world);
+ if !base.is_finite() {
+ self.warn("embedded documents with an invalid placement");
+ return None;
+ }
+ let mut budget = self.budget;
+ let placed = read_at(inner, self.archive.remaining(), &mut budget, base, self.depth + 1);
+ self.budget = budget;
+ if self.archive.charge(placed.extracted).is_err() {
+ self.warn("embedded documents beyond the size limit (left out)");
+ return None;
+ }
+ let doc = placed.document.ok()?;
+ for w in doc.warnings {
+ self.warn(format!("{w} [in embedded documents]"));
+ }
+ if doc.spreads.len() > 1 {
+ self.warn("embedded documents with several pages (the first is used)");
+ }
+ let mut nodes = doc.spreads.into_iter().next()?.nodes;
+ // Its master page instances count its own masters, which aren't kept: in this document
+ // they would show other masters.
+ fn strip_masters(nodes: &mut [Node], depth: usize) -> bool {
+ let mut found = false;
+ for n in nodes {
+ if matches!(n.kind, Kind::MasterInstance { .. }) {
+ n.kind = Kind::Unsupported;
+ found = true;
+ }
+ if depth < MAX_TREE_DEPTH {
+ found |= strip_masters(&mut n.children, depth + 1);
+ }
+ }
+ found
+ }
+ if strip_masters(&mut nodes, 0) {
+ self.warn("master pages of embedded documents (left out)");
+ }
+ Some(nodes)
+ }
+
fn artboard(&mut self, id: ObjId, world: Affine) -> Kind {
let s = self.s;
let Some(b) = s.floats::<4>(id, b"ShpB").map(rect).filter(|b| b.x1 > b.x0 && b.y1 > b.y0) else {
@@ -580,6 +1056,96 @@ impl<'s, 'a, 'b> Reader<'s, 'a, 'b> {
}
}
+/// The bounds of what visible `nodes` draw (control points of outlines, corners of images, frames
+/// and tables), in document pixels.
+pub fn nodes_bounds(nodes: &[Node]) -> Option {
+ let mut out = None;
+ walk_bounds(nodes, true, 0, &mut out);
+ out
+}
+
+/// The bounds of `node` and everything in it, hidden or not.
+fn tree_bounds(node: &Node) -> Option {
+ let mut out = None;
+ walk_bounds(std::slice::from_ref(node), false, 0, &mut out);
+ out
+}
+
+fn walk_bounds(nodes: &[Node], visible_only: bool, depth: usize, out: &mut Option) {
+ if depth > MAX_TREE_DEPTH {
+ return;
+ }
+ for n in nodes.iter().filter(|n| n.visible || !visible_only) {
+ kind_points(&n.kind, &mut |p| add_point(out, p));
+ walk_bounds(&n.children, visible_only, depth + 1, out);
+ }
+}
+
+/// What a pixel mask over a node of `kind` with `children` is read over: the bounds of what they
+/// draw, strokes included, or `None` (all of the mask) when some of it has no bounds known here:
+/// artistic text, whose glyphs only the layout places.
+fn mask_extent(kind: &Kind, children: &[Node]) -> Option {
+ fn visit(kind: &Kind, children: &[Node], depth: usize, out: &mut Option) -> bool {
+ if depth > MAX_TREE_DEPTH || matches!(kind, Kind::Text(t) if t.frame.is_none()) {
+ return false;
+ }
+ let mut own = kind_bounds(kind);
+ if let (Some(r), Kind::Shape { strokes, .. } | Kind::Artboard { strokes, .. }) = (own, kind) {
+ // As far as a stroke can reach out of its path, miter joins included.
+ let reach = strokes.iter().map(|s| s.width * s.miter_limit.clamp(1.0, 10.0)).filter(|w| w.is_finite()).fold(0.0, f64::max);
+ own = Some(Rect { x0: r.x0 - reach, y0: r.y0 - reach, x1: r.x1 + reach, y1: r.y1 + reach });
+ }
+ if let Some(r) = own {
+ *out = Some(out.map_or(r, |o| union(o, r)));
+ }
+ children.iter().filter(|n| n.visible).all(|n| visit(&n.kind, &n.children, depth + 1, out))
+ }
+ let mut out = None;
+ if visit(kind, children, 0, &mut out) { out } else { None }
+}
+
+/// The bounds of what one node's own kind draws (not its children): its outline's points, its
+/// image's or frame's corners, or artistic text's anchor.
+pub fn kind_bounds(kind: &Kind) -> Option {
+ let mut out = None;
+ kind_points(kind, &mut |p| add_point(&mut out, p));
+ out
+}
+
+fn add_point(out: &mut Option, p: Point) {
+ if p.x.is_finite() && p.y.is_finite() {
+ let r = Rect { x0: p.x, y0: p.y, x1: p.x, y1: p.y };
+ *out = Some(out.map_or(r, |o| union(o, r)));
+ }
+}
+
+fn kind_points(kind: &Kind, add: &mut dyn FnMut(Point)) {
+ let corners = |r: Rect, m: Affine| [(r.x0, r.y0), (r.x1, r.y0), (r.x1, r.y1), (r.x0, r.y1)].map(|(x, y)| m.apply(Point { x, y }));
+ match kind {
+ Kind::Shape { path, .. } | Kind::Artboard { path, .. } => {
+ for sp in &path.subpaths {
+ add(sp.start);
+ for seg in &sp.segments {
+ seg.iter().for_each(|p| add(*p));
+ }
+ }
+ }
+ Kind::Image(img) => {
+ corners(Rect { x0: 0.0, y0: 0.0, x1: f64::from(img.width), y1: f64::from(img.height) }, img.transform).into_iter().for_each(add)
+ }
+ Kind::Text(t) => match t.frame {
+ Some(f) => corners(f, t.transform).into_iter().for_each(add),
+ None => add(t.transform.apply(t.anchor)),
+ },
+ Kind::Table(t) => {
+ if let (Some(&x0), Some(&x1), Some(&y0), Some(&y1)) = (t.columns.first(), t.columns.last(), t.rows.first(), t.rows.last()) {
+ corners(Rect { x0, y0, x1, y1 }, t.transform).into_iter().for_each(add);
+ }
+ }
+ Kind::Layer | Kind::Group | Kind::Unsupported | Kind::MasterInstance { .. } => {}
+ }
+}
+
/// Page rectangles: `SpMd.PagR[].rctp` (Publisher 2, Affinity 3) or `SprB` split into `PagC`
/// equal pages (Publisher 1 facing spreads).
fn pages(s: &Stream, spread: ObjId) -> Vec {
diff --git a/crates/affinity/src/overlay.rs b/crates/affinity/src/overlay.rs
new file mode 100644
index 0000000000..170c50ec38
--- /dev/null
+++ b/crates/affinity/src/overlay.rs
@@ -0,0 +1,663 @@
+//! Colour and gradient overlays. VectorCraft has no such effect, so an overlay is baked into what
+//! its node paints: fill, stroke and text colours, and pixels. The overlay lies over the node's
+//! own paint in its blend mode at its opacity, inside the node's alpha (which it keeps).
+//!
+//! Blend modes follow the W3C Compositing and Blending formulas; the modes PDF lacks (Vivid
+//! Light, Linear Light, Pin Light, Hard Mix, Add, Subtract, Average, Negation, Reflect, Glow,
+//! Darker/Lighter Color) use their usual definitions.
+
+use std::borrow::Cow;
+
+use crate::model::{Affine, Blend, Effect, Image, Kind, Node, Pixels, Point};
+use crate::paint::{Color, Gradient, GradientKind, Paint, Stop, Stroke};
+
+/// Deepest subtree an overlay is baked into (the reader bounds trees well below this).
+const MAX_DEPTH: usize = 256;
+
+/// Most pixels an overlay is baked into per image.
+const MAX_PIXELS: usize = 64 << 20;
+
+/// Work the overlays of one import may take together: each overlay counts the nodes and pixels
+/// of the subtree it is baked into (which is copied once more for them all). Nested overlays
+/// and shared content would otherwise multiply it; past it, overlays are left out and said.
+pub const MAX_WORK: u64 = 1 << 29;
+
+#[derive(Clone, Copy)]
+enum Source<'a> {
+ Solid(Color),
+ Gradient(&'a Gradient),
+}
+
+#[derive(Clone, Copy)]
+struct Overlay<'a> {
+ source: Source<'a>,
+ opacity: f64,
+ blend: Blend,
+}
+
+/// `node` with its colour and gradient overlays baked in, and those of everything in it
+/// (borrowed unchanged when `node` has none, or when what is left of `work`, see [`MAX_WORK`],
+/// can't pay for copying it). `warn` hears what could only be approximated or was left out.
+pub fn apply<'a>(node: &'a Node, work: &mut u64, warn: &mut dyn FnMut(&str)) -> Cow<'a, Node> {
+ if overlays(&node.effects).is_empty() {
+ return Cow::Borrowed(node);
+ }
+ let Some(left) = work.checked_sub(subtree_cost(node, *work, 0)) else {
+ warn("overlay effects beyond the work one import may take (left out)");
+ return Cow::Borrowed(node);
+ };
+ *work = left;
+ let mut out = node.clone();
+ bake_tree(&mut out, work, 0, warn);
+ Cow::Owned(out)
+}
+
+/// The visible colour and gradient overlays among `effects`.
+fn overlays(effects: &[Effect]) -> Vec> {
+ effects
+ .iter()
+ .filter_map(|e| match e {
+ Effect::ColorOverlay { color, opacity, blend } => Some(Overlay { source: Source::Solid(*color), opacity: *opacity, blend: *blend }),
+ Effect::GradientOverlay { gradient, opacity, blend } => {
+ Some(Overlay { source: Source::Gradient(gradient), opacity: *opacity, blend: *blend })
+ }
+ _ => None,
+ })
+ .filter(|o| o.opacity > 0.0)
+ .collect()
+}
+
+fn is_overlay(e: &Effect) -> bool {
+ matches!(e, Effect::ColorOverlay { .. } | Effect::GradientOverlay { .. })
+}
+
+/// Bakes the overlays of `node` and its subtree into their paint, innermost first: an overlay
+/// lies over what its node shows, its children's overlays included. Each overlay pays for the
+/// subtree it is baked into out of `work`; past it, it is left out (and said).
+fn bake_tree(node: &mut Node, work: &mut u64, depth: usize, warn: &mut dyn FnMut(&str)) {
+ if depth > MAX_DEPTH {
+ return;
+ }
+ for c in &mut node.children {
+ bake_tree(c, work, depth + 1, warn);
+ }
+ if !node.effects.iter().any(is_overlay) {
+ return;
+ }
+ let (effects, rest): (Vec, Vec) = std::mem::take(&mut node.effects).into_iter().partition(is_overlay);
+ node.effects = rest;
+ let overlays = overlays(&effects);
+ if overlays.is_empty() {
+ return;
+ }
+ let count = u64::try_from(overlays.len()).unwrap_or(u64::MAX);
+ let cost = subtree_cost(node, *work / count, 0).saturating_mul(count);
+ let Some(left) = work.checked_sub(cost) else {
+ warn("overlay effects beyond the work one import may take (left out)");
+ return;
+ };
+ *work = left;
+ for o in &overlays {
+ if matches!(o.blend, Blend::Erase | Blend::PassThrough) {
+ warn("overlay effects in a blend mode VectorCraft doesn't have (imported as Normal)");
+ }
+ bake_node(node, o, 0, warn);
+ }
+}
+
+/// Nodes and pixels in `node`'s subtree, counted only until they pass `limit`.
+fn subtree_cost(node: &Node, limit: u64, depth: usize) -> u64 {
+ if depth > MAX_DEPTH {
+ return 0;
+ }
+ let mut cost: u64 = match &node.kind {
+ Kind::Image(img) => (u64::from(img.width) * u64::from(img.height)).saturating_add(1),
+ Kind::Text(t) => u64::try_from(t.runs.len()).unwrap_or(u64::MAX).saturating_add(1),
+ Kind::Table(t) => u64::try_from(t.cells.len()).unwrap_or(u64::MAX).saturating_add(1),
+ _ => 1,
+ };
+ for c in &node.children {
+ if cost > limit {
+ break;
+ }
+ cost = cost.saturating_add(subtree_cost(c, limit - cost, depth + 1));
+ }
+ cost
+}
+
+fn bake_node(node: &mut Node, o: &Overlay, depth: usize, warn: &mut dyn FnMut(&str)) {
+ if depth > MAX_DEPTH {
+ return;
+ }
+ match &mut node.kind {
+ Kind::Shape { fills, strokes, .. } => {
+ for f in fills.iter_mut() {
+ *f = paint(f, o, warn);
+ }
+ strokes.iter_mut().for_each(|s| stroke(s, o, warn));
+ }
+ Kind::Artboard { background, strokes, .. } => {
+ for f in background.iter_mut() {
+ *f = paint(f, o, warn);
+ }
+ strokes.iter_mut().for_each(|s| stroke(s, o, warn));
+ }
+ Kind::Text(t) => {
+ for r in &mut t.runs {
+ r.fill = paint(&r.fill, o, warn);
+ if let Some(s) = &mut r.stroke {
+ stroke(s, o, warn);
+ }
+ }
+ }
+ Kind::Table(t) => {
+ for c in &mut t.cells {
+ for r in &mut c.runs {
+ r.fill = paint(&r.fill, o, warn);
+ if let Some(s) = &mut r.stroke {
+ stroke(s, o, warn);
+ }
+ }
+ }
+ for s in t.vertical.iter_mut().chain(t.horizontal.iter_mut()).flatten() {
+ stroke(s, o, warn);
+ }
+ }
+ Kind::Image(img) => {
+ if !pixels(img, o) {
+ warn("overlay effects on images too large to recolour (left out)");
+ }
+ }
+ Kind::Layer | Kind::Group | Kind::Unsupported | Kind::MasterInstance { .. } => {}
+ }
+ for e in &mut node.effects {
+ match e {
+ Effect::Outline { color, .. } => *color = over(*color, o.source.at_solid(), o),
+ Effect::DropShadow { .. } | Effect::InnerShadow { .. } | Effect::OuterGlow { .. } | Effect::Bevel { .. } => {}
+ Effect::ColorOverlay { .. } | Effect::GradientOverlay { .. } => {}
+ }
+ }
+ for c in &mut node.children {
+ bake_node(c, o, depth + 1, warn);
+ }
+}
+
+fn stroke(s: &mut Stroke, o: &Overlay, warn: &mut dyn FnMut(&str)) {
+ s.paint = paint(&s.paint, o, warn);
+}
+
+/// A paint with the overlay over it.
+fn paint(p: &Paint, o: &Overlay, warn: &mut dyn FnMut(&str)) -> Paint {
+ match (p, o.source) {
+ (Paint::None, _) => Paint::None,
+ (Paint::Solid(c), Source::Solid(s)) => Paint::Solid(over(*c, s, o)),
+ (Paint::Gradient(g), Source::Solid(s)) => {
+ Paint::Gradient(Gradient { stops: g.stops.iter().map(|st| Stop { color: over(st.color, s, o), ..*st }).collect(), ..g.clone() })
+ }
+ // Over one colour, the result is the overlay's gradient with each stop laid over it.
+ (Paint::Solid(c), Source::Gradient(g)) => {
+ Paint::Gradient(Gradient { stops: g.stops.iter().map(|st| Stop { color: over(*c, st.color, o), ..*st }).collect(), ..g.clone() })
+ }
+ (Paint::Gradient(base), Source::Gradient(g)) => {
+ if !(o.blend == Blend::Normal && o.opacity >= 1.0) {
+ warn("gradient overlays on gradients (approximated)");
+ }
+ // Exact when the overlay covers it; otherwise over the base gradient's average colour.
+ let avg = average(base);
+ Paint::Gradient(Gradient { stops: g.stops.iter().map(|st| Stop { color: over(avg, st.color, o), ..*st }).collect(), ..g.clone() })
+ }
+ }
+}
+
+impl Source<'_> {
+ /// One colour for the source (a gradient's average) where only one fits.
+ fn at_solid(&self) -> Color {
+ match self {
+ Source::Solid(c) => *c,
+ Source::Gradient(g) => average(g),
+ }
+ }
+}
+
+fn average(g: &Gradient) -> Color {
+ let n = g.stops.len().max(1) as f64;
+ let (mut r, mut gr, mut b, mut a) = (0.0, 0.0, 0.0, 0.0);
+ for s in &g.stops {
+ let [sr, sg, sb] = rgb(s.color);
+ r += sr;
+ gr += sg;
+ b += sb;
+ a += s.color.alpha();
+ }
+ Color::Rgb { r: r / n, g: gr / n, b: b / n, a: a / n }
+}
+
+/// `source` laid over `base` in the overlay's mode and opacity; `base`'s alpha is kept.
+fn over(base: Color, source: Color, o: &Overlay) -> Color {
+ let k = (o.opacity * source.alpha()).clamp(0.0, 1.0);
+ let alpha = base.alpha();
+ // Normal mixes within the colour model when both share it, so CMYK stays CMYK.
+ if matches!(o.blend, Blend::Normal | Blend::PassThrough | Blend::Erase) {
+ let mix = |a: f64, b: f64| a + (b - a) * k;
+ match (base, source) {
+ (Color::Cmyk { c, m, y, k: kk, .. }, Color::Cmyk { c: c2, m: m2, y: y2, k: k2, .. }) => {
+ return Color::Cmyk { c: mix(c, c2), m: mix(m, m2), y: mix(y, y2), k: mix(kk, k2), a: alpha };
+ }
+ (Color::Gray { v, .. }, Color::Gray { v: v2, .. }) => return Color::Gray { v: mix(v, v2), a: alpha },
+ (_, s) if k >= 1.0 => return with_alpha(s, alpha),
+ _ => {}
+ }
+ }
+ let b = rgb(base);
+ let s = rgb(source);
+ let blended = blend(o.blend, b, s);
+ let [r, g, bl] = [0, 1, 2].map(|i| b[i] + (blended[i] - b[i]) * k);
+ Color::Rgb { r, g, b: bl, a: alpha }
+}
+
+fn with_alpha(c: Color, a: f64) -> Color {
+ match c {
+ Color::Rgb { r, g, b, .. } => Color::Rgb { r, g, b, a },
+ Color::Cmyk { c, m, y, k, .. } => Color::Cmyk { c, m, y, k, a },
+ Color::Gray { v, .. } => Color::Gray { v, a },
+ Color::Lab { l, a: la, b, .. } => Color::Lab { l, a: la, b, alpha: a },
+ }
+}
+
+/// sRGB components (0..1) of a colour. CMYK uses the profile-free formula (the engine shows the
+/// node's other CMYK colours through the document's profile), Lab its D50 sRGB colour.
+fn rgb(c: Color) -> [f64; 3] {
+ let f = |v: f64| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 };
+ match c {
+ Color::Rgb { r, g, b, .. } => [f(r), f(g), f(b)],
+ Color::Gray { v, .. } => [f(v); 3],
+ Color::Cmyk { c, m, y, k, .. } => {
+ let w = 1.0 - f(k);
+ [(1.0 - f(c)) * w, (1.0 - f(m)) * w, (1.0 - f(y)) * w]
+ }
+ Color::Lab { l, a, b, .. } => lab_to_srgb(l, a, b).map(f),
+ }
+}
+
+/// CIE L*a*b* (D50) to sRGB, through XYZ and the Bradford adaptation to D65.
+fn lab_to_srgb(l: f64, a: f64, b: f64) -> [f64; 3] {
+ let finite = |v: f64| if v.is_finite() { v } else { 0.0 };
+ let (l, a, b) = (finite(l), finite(a), finite(b));
+ let fy = (l + 16.0) / 116.0;
+ let (fx, fz) = (fy + a / 500.0, fy - b / 200.0);
+ let inv = |t: f64| if t > 6.0 / 29.0 { t * t * t } else { 3.0 * (6.0f64 / 29.0).powi(2) * (t - 4.0 / 29.0) };
+ // D50 white.
+ let (x, y, z) = (0.964_22 * inv(fx), inv(fy), 0.825_21 * inv(fz));
+ // XYZ (D50) to linear sRGB, Bradford-adapted.
+ let r = 3.133_856 * x - 1.616_867 * y - 0.490_615 * z;
+ let g = -0.978_768 * x + 1.916_142 * y + 0.033_454 * z;
+ let bl = 0.071_945 * x - 0.228_991 * y + 1.405_243 * z;
+ let gamma = |v: f64| if v <= 0.003_130_8 { 12.92 * v } else { 1.055 * v.max(0.0).powf(1.0 / 2.4) - 0.055 };
+ [gamma(r), gamma(g), gamma(bl)]
+}
+
+/// Bake the overlay into an image's pixels. False if they couldn't be read or are too many.
+fn pixels(img: &mut Image, o: &Overlay) -> bool {
+ let Some(n) = (img.width as usize).checked_mul(img.height as usize).filter(|n| *n <= MAX_PIXELS) else { return false };
+ let Some(len) = n.checked_mul(4) else { return false };
+ let mut px = match &img.pixels {
+ Pixels::Rgba8(p) => match p.get(..len) {
+ Some(p) => p.to_vec(),
+ None => return false,
+ },
+ Pixels::Encoded(bytes) => match decode(bytes, img.width, img.height) {
+ Some(p) => p,
+ None => return false,
+ },
+ // An overlay is blended in RGB: CMYK pixels take the profile-free formula here.
+ Pixels::Cmyka8(p) => match p.get(..n.saturating_mul(5)) {
+ Some(p) if p.len() == n * 5 => p
+ .as_chunks::<5>()
+ .0
+ .iter()
+ .flat_map(|[c, m, y, k, a]| {
+ let w = 255 - u16::from(*k);
+ let ch = |v: u8| ((u16::from(255 - v) * w + 127) / 255) as u8;
+ [ch(*c), ch(*m), ch(*y), *a]
+ })
+ .collect(),
+ _ => return false,
+ },
+ };
+ let width = img.width.max(1) as usize;
+ // A solid source is converted once; a gradient is sampled at each pixel's centre.
+ let solid = match o.source {
+ Source::Solid(c) => Some((rgb(c), c.alpha())),
+ Source::Gradient(_) => None,
+ };
+ let to_unit = match o.source {
+ Source::Gradient(g) => match invert(g.transform) {
+ Some(m) => Some((img.transform.then(m), g)),
+ None => return false,
+ },
+ Source::Solid(_) => None,
+ };
+ for (i, p) in px.as_chunks_mut::<4>().0.iter_mut().enumerate() {
+ if p[3] == 0 {
+ continue;
+ }
+ let (s, sa) = match (solid, &to_unit) {
+ (Some(s), _) => s,
+ (None, Some((m, g))) => {
+ let q = m.apply(Point { x: (i % width) as f64 + 0.5, y: (i / width) as f64 + 0.5 });
+ let c = sample(g, q);
+ (rgb(c), c.alpha())
+ }
+ (None, None) => continue,
+ };
+ let k = (o.opacity * sa).clamp(0.0, 1.0);
+ let b = [p[0], p[1], p[2]].map(|v| f64::from(v) / 255.0);
+ let m = blend(o.blend, b, s);
+ for c in 0..3 {
+ p[c] = ((b[c] + (m[c] - b[c]) * k).clamp(0.0, 1.0) * 255.0).round() as u8;
+ }
+ }
+ img.pixels = Pixels::Rgba8(px);
+ true
+}
+
+/// An encoded original's RGBA pixels, decoded only if it is `width` × `height` as its layer says.
+fn decode(bytes: &[u8], width: u32, height: u32) -> Option> {
+ let probe = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().ok()?;
+ if probe.into_dimensions().ok()? != (width, height) {
+ return None;
+ }
+ let mut reader = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().ok()?;
+ let mut limits = image::Limits::default();
+ limits.max_image_width = Some(width);
+ limits.max_image_height = Some(height);
+ limits.max_alloc = u64::try_from(MAX_PIXELS).ok().map(|n| n * 8);
+ reader.limits(limits);
+ Some(reader.decode().ok()?.into_rgba8().into_raw())
+}
+
+/// The gradient's colour at unit-space point `q`.
+fn sample(g: &Gradient, q: Point) -> Color {
+ let t = match g.kind {
+ GradientKind::Linear => q.x,
+ GradientKind::Radial => q.x.hypot(q.y),
+ GradientKind::Conical => q.y.atan2(q.x).rem_euclid(std::f64::consts::TAU) / std::f64::consts::TAU,
+ };
+ let t = if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.0 };
+ let (Some(first), Some(last)) = (g.stops.first(), g.stops.last()) else { return Color::Rgb { r: 0.0, g: 0.0, b: 0.0, a: 0.0 } };
+ if t <= first.offset {
+ return first.color;
+ }
+ for w in g.stops.windows(2) {
+ let [a, b] = [&w[0], &w[1]];
+ if t <= b.offset {
+ let span = b.offset - a.offset;
+ let u = if span > 1e-9 { (t - a.offset) / span } else { 1.0 };
+ // Affinity's midpoint bias (see `Stop::half_point`).
+ let k = 1.0 + 8.0 * (a.bias - 0.5).abs();
+ let u = if a.bias >= 0.5 { u.powf(k) } else { 1.0 - (1.0 - u).powf(k) };
+ let (x, y) = (rgb(a.color), rgb(b.color));
+ let [r, g, bl] = [0, 1, 2].map(|i| x[i] + (y[i] - x[i]) * u);
+ return Color::Rgb { r, g, b: bl, a: a.color.alpha() + (b.color.alpha() - a.color.alpha()) * u };
+ }
+ }
+ last.color
+}
+
+fn invert(m: Affine) -> Option {
+ let [a, b, c, d, e, f] = m.0;
+ let det = a * d - b * c;
+ if !(det.is_finite() && det.abs() > 1e-12) {
+ return None;
+ }
+ let (ia, ib, ic, id) = (d / det, -b / det, -c / det, a / det);
+ Some(Affine([ia, ib, ic, id, -(ia * e + ic * f), -(ib * e + id * f)]))
+}
+
+/// The blend of backdrop `b` and source `s` (sRGB, 0..1).
+fn blend(mode: Blend, b: [f64; 3], s: [f64; 3]) -> [f64; 3] {
+ use Blend::*;
+ let sep = |f: fn(f64, f64) -> f64| [0, 1, 2].map(|i| f(b[i], s[i]).clamp(0.0, 1.0));
+ match mode {
+ Normal | PassThrough | Erase => s,
+ Darken => sep(f64::min),
+ Lighten => sep(f64::max),
+ Multiply => sep(|b, s| b * s),
+ Screen => sep(screen),
+ ColorBurn => sep(burn),
+ ColorDodge => sep(dodge),
+ Blend::Overlay => sep(|b, s| hard_light(s, b)),
+ HardLight => sep(hard_light),
+ SoftLight => sep(soft_light),
+ Difference => sep(|b, s| (b - s).abs()),
+ Exclusion => sep(|b, s| b + s - 2.0 * b * s),
+ Add => sep(|b, s| b + s),
+ Subtract => sep(|b, s| b - s),
+ VividLight => sep(|b, s| if s <= 0.5 { burn(b, 2.0 * s) } else { dodge(b, 2.0 * s - 1.0) }),
+ LinearLight => sep(|b, s| b + 2.0 * s - 1.0),
+ PinLight => sep(|b, s| if s <= 0.5 { b.min(2.0 * s) } else { b.max(2.0 * s - 1.0) }),
+ HardMix => sep(|b, s| if b + s >= 1.0 { 1.0 } else { 0.0 }),
+ Average => sep(|b, s| (b + s) / 2.0),
+ Negation => sep(|b, s| 1.0 - (1.0 - b - s).abs()),
+ Reflect => sep(reflect),
+ Glow => sep(|b, s| reflect(s, b)),
+ DarkerColor => {
+ if lum(s) < lum(b) {
+ s
+ } else {
+ b
+ }
+ }
+ LighterColor => {
+ if lum(s) > lum(b) {
+ s
+ } else {
+ b
+ }
+ }
+ Hue => set_lum(set_sat(s, sat(b)), lum(b)),
+ Saturation => set_lum(set_sat(b, sat(s)), lum(b)),
+ Blend::Color => set_lum(s, lum(b)),
+ Luminosity => set_lum(b, lum(s)),
+ }
+}
+
+fn screen(b: f64, s: f64) -> f64 {
+ b + s - b * s
+}
+
+fn burn(b: f64, s: f64) -> f64 {
+ if b >= 1.0 {
+ 1.0
+ } else if s <= 0.0 {
+ 0.0
+ } else {
+ 1.0 - ((1.0 - b) / s).min(1.0)
+ }
+}
+
+fn dodge(b: f64, s: f64) -> f64 {
+ if b <= 0.0 {
+ 0.0
+ } else if s >= 1.0 {
+ 1.0
+ } else {
+ (b / (1.0 - s)).min(1.0)
+ }
+}
+
+fn hard_light(b: f64, s: f64) -> f64 {
+ if s <= 0.5 { b * 2.0 * s } else { screen(b, 2.0 * s - 1.0) }
+}
+
+fn soft_light(b: f64, s: f64) -> f64 {
+ if s <= 0.5 {
+ b - (1.0 - 2.0 * s) * b * (1.0 - b)
+ } else {
+ let d = if b <= 0.25 { ((16.0 * b - 12.0) * b + 4.0) * b } else { b.sqrt() };
+ b + (2.0 * s - 1.0) * (d - b)
+ }
+}
+
+fn reflect(b: f64, s: f64) -> f64 {
+ if s >= 1.0 { 1.0 } else { (b * b / (1.0 - s)).min(1.0) }
+}
+
+fn lum(c: [f64; 3]) -> f64 {
+ 0.3 * c[0] + 0.59 * c[1] + 0.11 * c[2]
+}
+
+fn clip_color(c: [f64; 3]) -> [f64; 3] {
+ let l = lum(c);
+ let n = c[0].min(c[1]).min(c[2]);
+ let x = c[0].max(c[1]).max(c[2]);
+ c.map(|v| {
+ let mut v = v;
+ if n < 0.0 && l - n > 1e-12 {
+ v = l + (v - l) * l / (l - n);
+ }
+ if x > 1.0 && x - l > 1e-12 {
+ v = l + (v - l) * (1.0 - l) / (x - l);
+ }
+ v.clamp(0.0, 1.0)
+ })
+}
+
+fn set_lum(c: [f64; 3], l: f64) -> [f64; 3] {
+ let d = l - lum(c);
+ clip_color(c.map(|v| v + d))
+}
+
+fn sat(c: [f64; 3]) -> f64 {
+ c[0].max(c[1]).max(c[2]) - c[0].min(c[1]).min(c[2])
+}
+
+fn set_sat(c: [f64; 3], s: f64) -> [f64; 3] {
+ let max = c[0].max(c[1]).max(c[2]);
+ let min = c[0].min(c[1]).min(c[2]);
+ if max - min <= 1e-12 {
+ return [0.0; 3];
+ }
+ c.map(|v| (v - min) * s / (max - min))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn solid(c: Color, opacity: f64, blend: Blend) -> Node {
+ Node {
+ class: crate::stream::Tag::of(b"ShpN"),
+ name: String::new(),
+ visible: true,
+ locked: false,
+ opacity: 1.0,
+ blend: Blend::Normal,
+ kind: Kind::Shape {
+ path: Default::default(),
+ fills: vec![Paint::Solid(Color::Rgb { r: 1.0, g: 0.5, b: 0.0, a: 1.0 })],
+ strokes: vec![],
+ even_odd: false,
+ },
+ mask: None,
+ pixel_mask: None,
+ effects: vec![Effect::ColorOverlay { color: c, opacity, blend }],
+ children: vec![],
+ }
+ }
+
+ fn fill(n: &Node) -> Color {
+ match &n.kind {
+ Kind::Shape { fills, .. } => match fills.first() {
+ Some(Paint::Solid(c)) => *c,
+ other => panic!("{other:?}"),
+ },
+ other => panic!("{other:?}"),
+ }
+ }
+
+ #[test]
+ fn a_full_colour_overlay_replaces_the_fill_and_keeps_its_alpha() {
+ let white = Color::Rgb { r: 1.0, g: 1.0, b: 1.0, a: 1.0 };
+ let n = apply(&solid(white, 1.0, Blend::Normal), &mut { MAX_WORK }, &mut |_| {}).into_owned();
+ assert_eq!(fill(&n), white);
+ assert!(n.effects.is_empty(), "the overlay is baked, not kept");
+ // Half way, mixed in RGB.
+ let n = apply(&solid(white, 0.5, Blend::Normal), &mut { MAX_WORK }, &mut |_| {}).into_owned();
+ assert_eq!(fill(&n), Color::Rgb { r: 1.0, g: 0.75, b: 0.5, a: 1.0 });
+ }
+
+ #[test]
+ fn blend_modes_follow_their_formulas() {
+ let b = [0.25, 0.5, 1.0];
+ assert_eq!(blend(Blend::Multiply, b, [0.5; 3]), [0.125, 0.25, 0.5]);
+ assert_eq!(blend(Blend::Screen, b, [0.5; 3]), [0.625, 0.75, 1.0]);
+ assert_eq!(blend(Blend::VividLight, [0.5; 3], [0.75; 3]), [1.0; 3]);
+ assert_eq!(blend(Blend::HardMix, [0.5; 3], [0.6; 3]), [1.0; 3]);
+ // Color keeps the backdrop's luminosity with the source's hue and saturation.
+ let c = blend(Blend::Color, [0.5; 3], [1.0, 0.0, 0.0]);
+ assert!((lum(c) - 0.5).abs() < 1e-9 && c[0] > c[1] && (c[1] - c[2]).abs() < 1e-9, "{c:?}");
+ }
+
+ #[test]
+ fn overlays_recolour_pixels_inside_their_alpha() {
+ let mut n = solid(Color::Rgb { r: 0.0, g: 0.0, b: 1.0, a: 1.0 }, 1.0, Blend::Normal);
+ n.kind = Kind::Image(Image { width: 2, height: 1, pixels: Pixels::Rgba8(vec![255, 0, 0, 255, 255, 0, 0, 0]), transform: Affine::IDENTITY });
+ let out = apply(&n, &mut { MAX_WORK }, &mut |_| {}).into_owned();
+ let Kind::Image(img) = &out.kind else { panic!() };
+ assert_eq!(img.pixels, Pixels::Rgba8(vec![0, 0, 255, 255, 255, 0, 0, 0]));
+ }
+
+ #[test]
+ fn a_gradient_overlay_over_one_colour_becomes_that_gradient() {
+ let g = Gradient {
+ kind: GradientKind::Linear,
+ stops: vec![
+ Stop { offset: 0.0, color: Color::Rgb { r: 0.0, g: 0.0, b: 0.0, a: 1.0 }, bias: 0.5 },
+ Stop { offset: 1.0, color: Color::Rgb { r: 1.0, g: 1.0, b: 1.0, a: 1.0 }, bias: 0.5 },
+ ],
+ transform: Affine([10.0, 0.0, 0.0, 10.0, 0.0, 0.0]),
+ };
+ let mut n = solid(Color::Rgb { r: 0.0, g: 0.0, b: 0.0, a: 1.0 }, 1.0, Blend::Normal);
+ n.effects = vec![Effect::GradientOverlay { gradient: g.clone(), opacity: 1.0, blend: Blend::Normal }];
+ let out = apply(&n, &mut { MAX_WORK }, &mut |_| {}).into_owned();
+ let Kind::Shape { fills, .. } = &out.kind else { panic!() };
+ assert_eq!(fills.first(), Some(&Paint::Gradient(g)));
+ }
+
+ #[test]
+ fn a_group_overlay_lies_over_its_childrens_overlays() {
+ let red = Color::Rgb { r: 1.0, g: 0.0, b: 0.0, a: 1.0 };
+ let blue = Color::Rgb { r: 0.0, g: 0.0, b: 1.0, a: 1.0 };
+ let mut group = solid(red, 0.5, Blend::Normal);
+ group.kind = Kind::Group;
+ group.children = vec![solid(blue, 1.0, Blend::Normal)];
+ // The copy (2 nodes), the child's overlay (1) and the group's (2).
+ let mut work = 5;
+ let out = apply(&group, &mut work, &mut |_| {}).into_owned();
+ assert_eq!(work, 0);
+ let child = out.children.first().unwrap();
+ // Blue first, then half of the group's red over it.
+ assert_eq!(fill(child), Color::Rgb { r: 0.5, g: 0.0, b: 0.5, a: 1.0 });
+ assert!(out.effects.is_empty() && child.effects.is_empty(), "both overlays are baked");
+ // With no work left for the group's overlay, the child's still applies.
+ let mut warnings = Vec::new();
+ let out = apply(&group, &mut { 4 }, &mut |w| warnings.push(w.to_string())).into_owned();
+ assert_eq!(fill(out.children.first().unwrap()), blue);
+ assert!(warnings.iter().any(|w| w.contains("beyond the work")), "{warnings:?}");
+ }
+
+ #[test]
+ fn overlays_stop_at_the_work_one_import_may_take() {
+ let mut n = solid(Color::Rgb { r: 0.0, g: 0.0, b: 1.0, a: 1.0 }, 1.0, Blend::Normal);
+ n.kind = Kind::Image(Image { width: 4, height: 4, pixels: Pixels::Rgba8(vec![255; 64]), transform: Affine::IDENTITY });
+ // 16 pixels and the node, for the copy and for the overlay: 34.
+ let mut work = 40;
+ let mut warnings = Vec::new();
+ assert!(matches!(apply(&n, &mut work, &mut |w| warnings.push(w.to_string())), Cow::Owned(_)));
+ assert_eq!((work, warnings.len()), (6, 0));
+ assert!(matches!(apply(&n, &mut work, &mut |w| warnings.push(w.to_string())), Cow::Borrowed(_)));
+ assert_eq!(work, 6);
+ assert!(warnings.iter().any(|w| w.contains("beyond the work")), "{warnings:?}");
+ }
+}
diff --git a/crates/affinity/src/paint.rs b/crates/affinity/src/paint.rs
index c4ebff8446..3eea677955 100644
--- a/crates/affinity/src/paint.rs
+++ b/crates/affinity/src/paint.rs
@@ -126,6 +126,9 @@ pub struct Stroke {
/// Gradient stops per gradient.
const MAX_STOPS: usize = 1024;
+/// Dash and gap lengths per dash pattern (a pattern has a few; strokes and text runs copy theirs).
+const MAX_DASHES: usize = 64;
+
fn floats(v: &Value) -> Option> {
match v {
Value::Floats(f) => Some(f.clone()),
@@ -283,7 +286,7 @@ pub(crate) fn node_paint(r: &mut Reader, id: ObjId, local: Affine) -> (Vec Option {
+pub(crate) fn stroke(r: &mut Reader, pen: ObjId, ldsc: ObjId, local: Affine, behind: bool) -> Option {
let s = r.s;
let paint = descriptor(r, pen, local)?;
if paint == Paint::None {
@@ -295,6 +298,13 @@ fn stroke(r: &mut Reader, pen: ObjId, ldsc: ObjId, local: Affine, behind: bool)
let scales = s.bool(ldsc, b"LDSc").unwrap_or(true);
let width = if scales { weight * local.scale() } else { weight };
let data = s.bytes(lsty, b"Data").unwrap_or_default();
+ // Byte 10 is the stroke's style: 0 none, 1 solid, 2 dashed, 3 a brush. A shape without a
+ // stroke still stores one (black, 1 px wide), with style 0. Identified on two documents their
+ // owner made, where every such stroke is invisible in Affinity's own PDF export, and checked
+ // against the public corpus's thumbnails.
+ if data.get(10) == Some(&0) {
+ return None;
+ }
let miter_limit = data.get(0..8).and_then(|b| b.try_into().ok()).map(f64::from_le_bytes).filter(|m| m.is_finite() && *m >= 1.0).unwrap_or(4.0);
// Cap and join bytes are only partly understood: (0, 0) is butt/miter in every clean sample;
// (2, 2) ends plain lines square and brush lines round; joins import round, which never
@@ -312,6 +322,10 @@ fn stroke(r: &mut Reader, pen: ObjId, ldsc: ObjId, local: Affine, behind: bool)
_ => Align::Center,
};
let dash = match s.field(lsty, b"Patn") {
+ Some(Value::Array(a)) if a.len() > MAX_DASHES => {
+ r.warn("dash patterns of more than 64 lengths (imported as solid lines)");
+ None
+ }
Some(Value::Array(a)) if data.get(10) == Some(&2) || !a.is_empty() => {
let mut v: Vec = a.iter().filter_map(|x| if let Value::Float(f) = x { Some(*f) } else { None }).collect();
while v.len() >= 2 && v.iter().rev().take(2).all(|x| *x == 0.0) {
diff --git a/crates/affinity/src/raster.rs b/crates/affinity/src/raster.rs
index 98334717d3..d458c08a7d 100644
--- a/crates/affinity/src/raster.rs
+++ b/crates/affinity/src/raster.rs
@@ -39,6 +39,9 @@ pub(crate) fn node_image(r: &mut Reader, id: ObjId, world: Affine) -> Result {}
Ok(bytes) => return Ok(Some(Image { width, height, pixels: Pixels::Encoded(bytes), transform: world })),
Err(Error::Limit(e)) => return Err(Error::Limit(e)),
Err(_) => r.warn("an embedded image file that could not be read (its cached pixels were used)"),
@@ -66,8 +69,17 @@ pub(crate) fn node_image(r: &mut Reader, id: ObjId, world: Affine) -> Result Result, Error> {
+/// An ISO base media file holding a HEIF image (HEIC, AVIF): `ftyp` with an image brand.
+fn is_heif(bytes: &[u8]) -> bool {
+ bytes.get(4..8) == Some(b"ftyp".as_slice())
+ && bytes.get(8..12).is_some_and(|brand| {
+ [b"heic", b"heix", b"hevc", b"hevx", b"heim", b"heis", b"mif1", b"msf1", b"avif", b"avis"].iter().any(|b| brand == b.as_slice())
+ })
+}
+
+/// A mask layer (`MRst`): one channel of coverage as grey pixels (white shows, black hides), read
+/// over `over` (document pixels) when given; outside its pixels a mask hides everything.
+pub(crate) fn mask(r: &mut Reader, id: ObjId, world: Affine, over: Option) -> Result, Error> {
let s = r.s;
let Some(bitmap) = s.obj(id, b"Bitm") else { return Ok(None) };
let width = s.int(bitmap, b"BmpW").and_then(|v| u32::try_from(v).ok()).unwrap_or(0);
@@ -76,7 +88,41 @@ pub(crate) fn mask(r: &mut Reader, id: ObjId, world: Affine) -> Result c,
+ // What it masks lies outside it: all hidden, which one black pixel says as well.
+ Some(None) => return Ok(Some(Image { width: 1, height: 1, pixels: Pixels::Rgba8(vec![0, 0, 0, 255]), transform: world })),
+ None => (0, 0, width, height),
+ };
+ decode(r, bitmap, crop, world)
+}
+
+/// The bitmap pixels (x0, y0, x1, y1) of a `width` × `height` bitmap placed by `world` that cover
+/// document rectangle `over`, one pixel wider all round; `None` if they don't overlap.
+fn crop_to(over: crate::model::Rect, world: Affine, width: u32, height: u32) -> Option<(u32, u32, u32, u32)> {
+ let inv = invert(world)?;
+ let pts = [(over.x0, over.y0), (over.x1, over.y0), (over.x1, over.y1), (over.x0, over.y1)].map(|(x, y)| inv.apply(crate::model::Point { x, y }));
+ let (mut x0, mut y0, mut x1, mut y1) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
+ for p in pts {
+ if !(p.x.is_finite() && p.y.is_finite()) {
+ return Some((0, 0, width, height));
+ }
+ (x0, y0, x1, y1) = (x0.min(p.x), y0.min(p.y), x1.max(p.x), y1.max(p.y));
+ }
+ let clamp = |v: f64, max: u32| v.clamp(0.0, f64::from(max)) as u32;
+ let (cx0, cy0, cx1, cy1) =
+ (clamp(x0.floor() - 1.0, width), clamp(y0.floor() - 1.0, height), clamp(x1.ceil() + 1.0, width), clamp(y1.ceil() + 1.0, height));
+ (cx1 > cx0 && cy1 > cy0).then_some((cx0, cy0, cx1, cy1))
+}
+
+fn invert(m: Affine) -> Option {
+ let [a, b, c, d, e, f] = m.0;
+ let det = a * d - b * c;
+ if !(det.is_finite() && det.abs() > 1e-12) {
+ return None;
+ }
+ let (ia, ib, ic, id) = (d / det, -b / det, -c / det, a / det);
+ Some(Affine([ia, ib, ic, id, -(ia * e + ic * f), -(ib * e + id * f)]))
}
/// An embedded document or symbol instance (`EmbN`), as the picture of it Affinity caches.
@@ -99,33 +145,41 @@ pub(crate) fn embedded(r: &mut Reader, id: ObjId, world: Affine) -> Result Result, Error> {
+ decode_within(r, bitmap, crop, world, MAX_PIXELS)
+}
+
+/// [`decode`] with at most `max_pixels` decoded pixels.
+fn decode_within(r: &mut Reader, bitmap: ObjId, crop: (u32, u32, u32, u32), world: Affine, max_pixels: u64) -> Result , Error> {
let s = r.s;
let (x0, y0, x1, y1) = crop;
if x1 <= x0 || y1 <= y0 {
return Ok(None);
}
let (w, h) = (x1 - x0, y1 - y0);
- let pixels = u64::from(w) * u64::from(h);
- if pixels > MAX_PIXELS {
- r.warn("pixel layers larger than 64 megapixels");
- return Ok(None);
+ // Larger layers (mostly masks of whole spreads) are read at a half, a quarter… of their
+ // resolution: every `step`th pixel of every `step`th row.
+ let mut step = 1u32;
+ while u64::from(w.div_ceil(step)) * u64::from(h.div_ceil(step)) > max_pixels {
+ step *= 2;
+ if step > 1 << 12 {
+ r.warn("pixel layers too large to read (left out)");
+ return Ok(None);
+ }
}
// Before anything is allocated: a layer's tiles can be flat colour, with nothing to extract.
- let Some(left) = r.pixels_left.checked_sub(pixels) else {
+ let pixels = u64::from(w.div_ceil(step)) * u64::from(h.div_ceil(step));
+ let Some(left) = r.budget.pixels.checked_sub(pixels) else {
r.warn("pixel layers beyond the pixels one document may hold");
return Ok(None);
};
- r.pixels_left = left;
+ r.budget.pixels = left;
let format = s.enumeration(bitmap, b"Frmt").map(|(f, _)| f);
let (channels, bps) = match format {
Some(0) => (4, 1),
Some(1) => (4, 2),
Some(6) => (1, 1),
Some(7) => (1, 2),
- Some(4) => {
- r.warn("CMYK pixel layers (converted to RGB without the document's colour profile)");
- (5, 1)
- }
+ Some(4) => (5, 1),
_ => {
r.warn("pixel layers in grey, Lab or 32-bit formats");
return Ok(None);
@@ -152,11 +206,48 @@ fn decode(r: &mut Reader, bitmap: ObjId, crop: (u32, u32, u32, u32), world: Affi
} else {
None
};
+ // Tiles kept only in an original that can't be decoded here are left empty (transparent). Where
+ // a tile's colour is in the original but its alpha is stored, as in CMYK layers, it would come
+ // out opaque white instead: such a layer (a HEIC photo in a CMYK document) is left out, and said.
+ if needs_source && source.is_none() && channels > 1 {
+ let states = |c: usize| match s.field(bitmap, &tag(b"Sta", c)) {
+ Some(Value::Array(a)) => a.clone(),
+ _ => Vec::new(),
+ };
+ let alpha = states(channels);
+ let blank = (1..channels).any(|c| states(c).iter().enumerate().any(|(i, v)| *v == Value::UInt(5) && alpha.get(i) != Some(&Value::UInt(5))));
+ if blank {
+ r.warn("placed images whose pixels are only in an original the reader can't decode, such as HEIC photos (left out)");
+ return Ok(None);
+ }
+ }
+ if step > 1 {
+ // Its stored tiles must fit what is left of the import's extraction budget.
+ let stored: usize = (1..=channels).map(|c| tiles_in(s, bitmap, c, bps, (x0, y0, w, h)).len()).sum();
+ if stored.saturating_mul(TILE_BYTES) > r.archive.remaining().max_total {
+ r.warn("pixel layers too large to read (left out)");
+ return Ok(None);
+ }
+ r.warn("pixel layers larger than 64 megapixels (read at a lower resolution)");
+ }
let mut cache = CachedPixels { tiles: HashMap::new(), source };
for c in 1..=channels {
- planes.push(plane(r, bitmap, c, bps, (x0, y0, w, h), &mut cache)?);
+ planes.push(plane(r, bitmap, c, bps, (x0, y0, w, h), step, &mut cache)?);
}
+ let (w, h) = (w.div_ceil(step), h.div_ceil(step));
let n = (w as usize) * (h as usize);
+ let k = f64::from(step);
+ let transform = Affine([k, 0.0, 0.0, k, f64::from(x0), f64::from(y0)]).then(world);
+ if channels == 5 {
+ // Ink amounts and alpha as stored (8 bits), interleaved.
+ let mut cmyka = vec![0u8; n * 5];
+ for (i, px) in cmyka.as_chunks_mut::<5>().0.iter_mut().enumerate() {
+ for (c, v) in px.iter_mut().enumerate() {
+ *v = planes.get(c).and_then(|p| p.get(i)).copied().unwrap_or(0);
+ }
+ }
+ return Ok(Some(Image { width: w, height: h, pixels: Pixels::Cmyka8(cmyka), transform }));
+ }
let mut rgba = vec![0u8; n * 4];
let sample = |p: &Vec, i: usize| -> f64 {
if bps == 2 {
@@ -167,17 +258,9 @@ fn decode(r: &mut Reader, bitmap: ObjId, crop: (u32, u32, u32, u32), world: Affi
};
for (i, px) in rgba.as_chunks_mut::<4>().0.iter_mut().enumerate() {
let v: Vec = planes.iter().map(|p| sample(p, i)).collect();
- let (r2, g, b, a) = if channels == 1 {
- (v[0], v[0], v[0], 1.0)
- } else if channels == 5 {
- let k = 1.0 - v[3];
- ((1.0 - v[0]) * k, (1.0 - v[1]) * k, (1.0 - v[2]) * k, v[4])
- } else {
- (v[0], v[1], v[2], v[3])
- };
+ let (r2, g, b, a) = if channels == 1 { (v[0], v[0], v[0], 1.0) } else { (v[0], v[1], v[2], v[3]) };
px.copy_from_slice(&[r2, g, b, a].map(|c| (c.clamp(0.0, 1.0) * 255.0).round() as u8));
}
- let transform = Affine([1.0, 0.0, 0.0, 1.0, f64::from(x0), f64::from(y0)]).then(world);
Ok(Some(Image { width: w, height: h, pixels: Pixels::Rgba8(rgba), transform }))
}
@@ -229,28 +312,57 @@ fn tag(prefix: &[u8; 3], c: usize) -> [u8; 4] {
[prefix[0], prefix[1], prefix[2], b'0' + c as u8]
}
-/// One channel of level 0, cropped to (x0, y0, w, h) pixels; `bps` bytes per sample.
+/// Channel `c`'s tile grid: (tiles across, tiles down, each tile's state).
+fn grid(s: &stream::Stream, bitmap: ObjId, c: usize, bps: usize) -> (usize, usize, Vec) {
+ let width = s.int(bitmap, b"BmpW").and_then(|v| usize::try_from(v).ok()).unwrap_or(0);
+ let height = s.int(bitmap, b"BmpH").and_then(|v| usize::try_from(v).ok()).unwrap_or(0);
+ let tw = s.int(bitmap, &tag(b"TWi", c)).and_then(|v| usize::try_from(v).ok()).unwrap_or_else(|| width.saturating_mul(bps).div_ceil(TILE));
+ let th = s.int(bitmap, &tag(b"THi", c)).and_then(|v| usize::try_from(v).ok()).unwrap_or_else(|| height.div_ceil(TILE));
+ let states: Vec = match s.field(bitmap, &tag(b"Sta", c)) {
+ Some(Value::Array(a)) => a.iter().map(|v| if let Value::UInt(u) = v { u8::try_from(*u).unwrap_or(255) } else { 255 }).collect(),
+ _ => Vec::new(),
+ };
+ (tw, th, states)
+}
+
+/// The stored tiles (state 4) of channel `c` that overlap the crop, by their index in `Idx`.
+fn tiles_in(s: &stream::Stream, bitmap: ObjId, c: usize, bps: usize, (x0, y0, w, h): (u32, u32, u32, u32)) -> Vec {
+ let (tw, th, states) = grid(s, bitmap, c, bps);
+ let (bx0, bx1) = (x0 as usize * bps, (x0 + w) as usize * bps);
+ let (py0, py1) = (y0 as usize, (y0 + h) as usize);
+ let mut out = Vec::new();
+ let mut next = 0usize;
+ for (t, state) in states.iter().enumerate().take(tw.saturating_mul(th)) {
+ if *state != 4 {
+ continue;
+ }
+ let (ox, oy) = ((t % tw.max(1)) * TILE, (t / tw.max(1)) * TILE);
+ if !(ox >= bx1 || ox + TILE <= bx0 || oy >= py1 || oy + TILE <= py0) {
+ out.push(next);
+ }
+ next += 1;
+ }
+ out
+}
+
+/// One channel of level 0, cropped to (x0, y0, w, h) pixels and taking every `step`th pixel of
+/// every `step`th row; `bps` bytes per sample.
fn plane(
r: &mut Reader,
bitmap: ObjId,
c: usize,
bps: usize,
(x0, y0, w, h): (u32, u32, u32, u32),
+ step: u32,
cache: &mut CachedPixels,
) -> Result, Error> {
let CachedPixels { tiles: cache, source } = cache;
let s = r.s;
- let width = s.int(bitmap, b"BmpW").and_then(|v| usize::try_from(v).ok()).unwrap_or(0);
- let height = s.int(bitmap, b"BmpH").and_then(|v| usize::try_from(v).ok()).unwrap_or(0);
- let tw = s.int(bitmap, &tag(b"TWi", c)).and_then(|v| usize::try_from(v).ok()).unwrap_or_else(|| (width * bps).div_ceil(TILE));
- let th = s.int(bitmap, &tag(b"THi", c)).and_then(|v| usize::try_from(v).ok()).unwrap_or_else(|| height.div_ceil(TILE));
- let states: Vec = match s.field(bitmap, &tag(b"Sta", c)) {
- Some(Value::Array(a)) => a.iter().map(|v| if let Value::UInt(u) = v { u8::try_from(*u).unwrap_or(255) } else { 255 }).collect(),
- _ => Vec::new(),
- };
+ let (tw, th, states) = grid(s, bitmap, c, bps);
let tiles = s.objs(bitmap, &tag(b"Idx", c));
- let row = (w as usize) * bps;
- let mut out = vec![0u8; row * h as usize];
+ let at = Crop { bps, x0: x0 as usize, y0: y0 as usize, w: w as usize, h: h as usize, step: step.max(1) as usize };
+ let row = at.w.div_ceil(at.step) * bps;
+ let mut out = vec![0u8; row * at.h.div_ceil(at.step)];
let (bx0, bx1) = (x0 as usize * bps, (x0 + w) as usize * bps);
let (py0, py1) = (y0 as usize, (y0 + h) as usize);
let mut next = 0usize;
@@ -267,7 +379,7 @@ fn plane(
continue;
}
let name = s.entry(blck, b"Data").ok_or(Error::Malformed("pixel tile without data"))?.to_string();
- if !cache.contains_key(&name) {
+ let read = |r: &mut Reader| -> Result, Error> {
let mut data = r.archive.read(&name)?;
// Older files wrap a tile in a one-field stream: header, then a 64 KiB blob.
if data.len() == TILE_BYTES + 22 && data.starts_with(b"\x00\xffKS") {
@@ -276,10 +388,20 @@ fn plane(
if data.len() != TILE_BYTES {
return Err(Error::Malformed("pixel tile size"));
}
+ Ok(data)
+ };
+ // A layer read at a lower resolution is too large to keep its tiles around.
+ if at.step > 1 {
+ let tile = read(r)?;
+ copy(&mut out, &at, (ox, oy), |x, y| tile.get(y * TILE + x).copied().unwrap_or(0));
+ continue;
+ }
+ if !cache.contains_key(&name) {
+ let data = read(r)?;
cache.insert(name.clone(), data);
}
let tile = cache.get(&name).ok_or(Error::Malformed("pixel tile"))?;
- copy(&mut out, row, (bx0, py0, bx1, py1), (ox, oy), |x, y| tile.get(y * TILE + x).copied().unwrap_or(0));
+ copy(&mut out, &at, (ox, oy), |x, y| tile.get(y * TILE + x).copied().unwrap_or(0));
continue;
}
3 => {
@@ -289,9 +411,7 @@ fn plane(
5 => {
if let Some((source_width, pixels)) = source.as_ref() {
let (ox, oy) = (tx * TILE, ty * TILE);
- copy(&mut out, row, (bx0, py0, bx1, py1), (ox, oy), |x, y| {
- pixels.get(((oy + y) * source_width + ox + x) * 4 + c - 1).copied().unwrap_or(0)
- });
+ copy(&mut out, &at, (ox, oy), |x, y| pixels.get(((oy + y) * source_width + ox + x) * 4 + c - 1).copied().unwrap_or(0));
continue;
}
r.warn("pixel layers drawn from an embedded image (left empty)");
@@ -300,17 +420,38 @@ fn plane(
_ => return Err(Error::Malformed("unknown pixel tile state")),
};
if let Some(v) = fill {
- copy(&mut out, row, (bx0, py0, bx1, py1), (tx * TILE, ty * TILE), |_, _| v);
+ copy(&mut out, &at, (tx * TILE, ty * TILE), |_, _| v);
}
}
Ok(out)
}
-/// Copy the overlap of a tile at byte column `ox`, row `oy` into the cropped plane.
-fn copy(out: &mut [u8], row: usize, (bx0, py0, bx1, py1): (usize, usize, usize, usize), (ox, oy): (usize, usize), at: impl Fn(usize, usize) -> u8) {
- for y in oy.max(py0)..(oy + TILE).min(py1) {
+/// Where a plane's pixels come from: the crop (pixels) and the sampling step.
+struct Crop {
+ bps: usize,
+ x0: usize,
+ y0: usize,
+ w: usize,
+ h: usize,
+ step: usize,
+}
+
+/// Copy the overlap of a tile at byte column `ox`, row `oy` into the cropped plane, keeping every
+/// `step`th pixel of every `step`th row.
+fn copy(out: &mut [u8], c: &Crop, (ox, oy): (usize, usize), at: impl Fn(usize, usize) -> u8) {
+ let row = c.w.div_ceil(c.step) * c.bps;
+ let (bx0, bx1) = (c.x0 * c.bps, (c.x0 + c.w) * c.bps);
+ for y in oy.max(c.y0)..(oy + TILE).min(c.y0 + c.h) {
+ if !(y - c.y0).is_multiple_of(c.step) {
+ continue;
+ }
+ let out_row = (y - c.y0) / c.step * row;
for x in ox.max(bx0)..(ox + TILE).min(bx1) {
- if let Some(b) = out.get_mut((y - py0) * row + (x - bx0)) {
+ let px = x / c.bps - c.x0;
+ if !px.is_multiple_of(c.step) {
+ continue;
+ }
+ if let Some(b) = out.get_mut(out_row + px / c.step * c.bps + x % c.bps) {
*b = at(x - ox, y - oy);
}
}
@@ -323,6 +464,15 @@ mod tests {
use crate::model::Kind;
use crate::synth::{self, F, Method, tag};
+ #[test]
+ fn heif_originals_are_recognised_by_their_brand() {
+ assert!(is_heif(b"\0\0\0\x18ftypheic\0\0\0\0"));
+ assert!(is_heif(b"\0\0\0\x1cftypavif"));
+ assert!(!is_heif(b"\0\0\0\x18ftypisom"), "a video is not a photo");
+ assert!(!is_heif(&png()));
+ assert!(!is_heif(b"ftyp"));
+ }
+
fn png() -> Vec {
let pixels = image::RgbaImage::from_fn(300, 2, |x, y| image::Rgba([(x % 251) as u8, (y * 31) as u8, 77, 255]));
let mut bytes = std::io::Cursor::new(Vec::new());
@@ -333,18 +483,29 @@ mod tests {
/// An original synthetic mixed source/cache bitmap. It exercises reader recovery,
/// not a claim that Affinity itself accepts the synthetic container.
fn fixture(source: &[u8], origin: i32) -> Vec {
+ fixture_in(source, origin, false)
+ }
+
+ /// `cmyk`: a CMYK bitmap whose colour tiles are all in the source and whose alpha is stored.
+ fn fixture_in(source: &[u8], origin: i32, cmyk: bool) -> Vec {
+ let channels = if cmyk { 5 } else { 4 };
let mut bitmap = vec![
- (tag(b"Frmt"), F::Enum(0, 0)),
+ (tag(b"Frmt"), F::Enum(if cmyk { 4 } else { 0 }, 0)),
(tag(b"BmpW"), F::I32(300)),
(tag(b"BmpH"), F::I32(2)),
(tag(b"LInf"), F::I32(origin)),
(tag(b"TInf"), F::I32(0)),
(tag(b"Bckg"), F::Entry("c/1".into())),
];
- for c in 1..=4 {
+ for c in 1..=channels {
+ let states = match (cmyk, c) {
+ (false, _) => vec![5, 4],
+ (true, 5) => vec![4, 4],
+ (true, _) => vec![5, 5],
+ };
bitmap.push((tag(&super::tag(b"TWi", c)), F::I32(2)));
bitmap.push((tag(&super::tag(b"THi", c)), F::I32(1)));
- bitmap.push((tag(&super::tag(b"Sta", c)), F::U8s(vec![5, 4])));
+ bitmap.push((tag(&super::tag(b"Sta", c)), F::U8s(states)));
bitmap.push((
tag(&super::tag(b"Idx", c)),
F::Shared(vec![F::Def(c as u32, vec![tag(b"Blck")], vec![(tag(b"Data"), F::Entry(format!("d/{c}")))])]),
@@ -369,18 +530,44 @@ mod tests {
blob.extend((source.len() as u32).to_le_bytes());
blob.extend(source);
let block = synth::stream(&[(tag(b"Data"), F::Raw(blob))]);
- let tiles: Vec<_> = [200u8, 10, 30, 255].into_iter().map(|v| vec![v; TILE_BYTES]).collect();
- synth::container(
- &[
- ("doc.dat", &doc, Method::Zlib),
- ("c/1", &block, Method::Zlib),
- ("d/1", &tiles[0], Method::Zlib),
- ("d/2", &tiles[1], Method::Zlib),
- ("d/3", &tiles[2], Method::Zlib),
- ("d/4", &tiles[3], Method::Zlib),
- ],
- None,
- )
+ let tiles: Vec<_> = [200u8, 10, 30, 255, 255].into_iter().map(|v| vec![v; TILE_BYTES]).collect();
+ let names: Vec = (1..=channels).map(|c| format!("d/{c}")).collect();
+ let mut entries = vec![("doc.dat", doc.as_slice(), Method::Zlib), ("c/1", block.as_slice(), Method::Zlib)];
+ for (name, tile) in names.iter().zip(&tiles) {
+ entries.push((name.as_str(), tile.as_slice(), Method::Zlib));
+ }
+ synth::container(&entries, None)
+ }
+
+ #[test]
+ fn a_cmyk_layer_whose_colours_are_only_in_an_unreadable_original_is_left_out_not_white() {
+ let doc = crate::read(&fixture_in(b"\0\0\0\x18ftypheic not decodable", 0, true), crate::Limits::default()).unwrap();
+ assert!(doc.warnings.iter().any(|w| w.starts_with("placed images whose pixels are only in an original")), "{:?}", doc.warnings);
+ assert!(matches!(doc.spreads[0].nodes[0].kind, Kind::Unsupported), "{:?}", doc.spreads[0].nodes[0].kind);
+ }
+
+ #[test]
+ fn layers_over_the_pixel_budget_are_read_at_a_lower_resolution() {
+ let bytes = fixture(&png(), 0);
+ let mut archive = crate::Archive::open(&bytes, crate::Limits::default()).unwrap();
+ let doc = archive.read("doc.dat").unwrap();
+ let s = stream::parse(&doc).unwrap();
+ let bitmap = s.objects.iter().position(|o| o.class == Tag::of(b"DyBm")).unwrap();
+ let mut r = Reader::new(&s, &mut archive, Affine::IDENTITY, 0);
+ // 20 × 2 pixels over a budget of 10: every other pixel of every other row.
+ let image = decode_within(&mut r, bitmap, (250, 0, 270, 2), Affine::IDENTITY, 10).unwrap().unwrap();
+ assert_eq!((image.width, image.height), (10, 1));
+ assert_eq!(image.transform, Affine([2.0, 0.0, 0.0, 2.0, 250.0, 0.0]), "each pixel covers two");
+ let Pixels::Rgba8(pixels) = &image.pixels else { panic!() };
+ for x in 0..10 {
+ let sx = 2 * x;
+ let expected = if sx + 250 < 256 { [((sx + 250) % 251) as u8, 0, 77, 255] } else { [200, 10, 30, 255] };
+ assert_eq!(&pixels[x * 4..x * 4 + 4], &expected, "pixel {x}");
+ }
+ assert!(r.warnings.contains_key("pixel layers larger than 64 megapixels (read at a lower resolution)"));
+ // Within budget, nothing changes.
+ let image = decode_within(&mut r, bitmap, (250, 0, 270, 2), Affine::IDENTITY, 40).unwrap().unwrap();
+ assert_eq!((image.width, image.height), (20, 2));
}
#[test]
diff --git a/crates/affinity/src/tests.rs b/crates/affinity/src/tests.rs
index 006f9e7bda..817012fa70 100644
--- a/crates/affinity/src/tests.rs
+++ b/crates/affinity/src/tests.rs
@@ -261,6 +261,32 @@ mod archive {
assert!(matches!(a.read("doc.dat"), Err(Error::Limit(_))));
}
+ // Regression test for #1710: ruzstd 0.9.0 let a block decompress to more than its frame's
+ // window allows (RUSTSEC-2026-0344), so a crafted entry made the decoder produce far more than
+ // the format permits for a block. 0.9.1 refuses it.
+ #[test]
+ fn a_zstd_block_larger_than_its_frames_window_is_refused() {
+ const LEN: u32 = 100_000;
+ let plain = vec![0x61u8; LEN as usize];
+ let file = synth::container(&[("doc.dat", &plain, Method::Zstd)], None);
+ // A Zstandard frame with a 1 KiB window (descriptor byte 0, window byte 0) holding one RLE
+ // block, the last, that repeats a byte LEN times: block header = last | RLE << 1 | LEN << 3.
+ let mut frame = vec![0x28, 0xB5, 0x2F, 0xFD, 0x00, 0x00];
+ frame.extend((1 | (1 << 1) | (LEN << 3)).to_le_bytes().get(..3).unwrap());
+ frame.push(0x61);
+ // Swap it in for the entry's compressed bytes (they follow the "#Fil" tag at offset 72).
+ let fat = u64::from_le_bytes(file[16..24].try_into().unwrap()) as usize;
+ let old_len = u64::from_le_bytes(file[fat + 59 + 21..fat + 59 + 29].try_into().unwrap()) as usize;
+ let mut swapped = file[..76].to_vec();
+ swapped.extend(&frame);
+ swapped.extend(&file[76 + old_len..]);
+ let new_fat = fat - old_len + frame.len();
+ swapped[16..24].copy_from_slice(&(new_fat as u64).to_le_bytes());
+ swapped[new_fat + 59 + 21..new_fat + 59 + 29].copy_from_slice(&(frame.len() as u64).to_le_bytes());
+ let mut a = Archive::open(&swapped, Limits::default()).unwrap();
+ assert!(a.read("doc.dat").is_err(), "a block of {LEN} bytes was decompressed from a frame with a 1 KiB window");
+ }
+
#[test]
fn a_declared_size_smaller_than_the_data_is_rejected_not_truncated() {
let big = vec![7u8; 1 << 20];
diff --git a/crates/affinity/src/text.rs b/crates/affinity/src/text.rs
index 2b632cab32..1a3b6e5442 100644
--- a/crates/affinity/src/text.rs
+++ b/crates/affinity/src/text.rs
@@ -2,7 +2,7 @@
//! leading, the paragraph alignment and the first baseline. Layout (line breaks in frames, kerning,
//! OpenType features) is left to the importing application.
-use crate::model::{Affine, Align, Point, Reader, Text, TextRun, rect};
+use crate::model::{Affine, Align, Paragraph, Point, Reader, Table, TableCell, Text, TextRun, VAlign, rect};
use crate::paint::{self, Color, Paint};
use crate::stream::{ObjId, Value};
@@ -11,92 +11,16 @@ const MAX_CHARS: usize = 1 << 20;
/// Shared character attributes must not amplify into unbounded font/feature/gradient data.
const MAX_ATTRIBUTE_BYTES: usize = 16 << 20;
+/// Ends a table cell in a table's story (Affinity's break glyph of kind 4).
+pub const CELL_BREAK: char = '\u{1F}';
+
pub(crate) fn read(r: &mut Reader, id: ObjId, world: Affine) -> Option {
let s = r.s;
let story = s.obj(id, b"StSt")?;
let frame = s.obj(id, b"TxtH")?;
let artistic = s.is(frame, b"ArFr");
let bounds = s.floats::<4>(frame, b"FrmB").map(rect)?;
- let mut runs = Vec::new();
- let mut align = None;
- let mut total = 0usize;
- let mut placeholders = false;
- let mut attribute_budget = Some(MAX_ATTRIBUTE_BYTES);
- for block in s.objs(story, b"Blok") {
- let Some(glyphs) = s.obj(block, b"Glyp") else {
- r.warn("a text block without readable characters (left out)");
- continue;
- };
- // Bound collection itself, including placeholders, before allocating the character buffer.
- let budget = MAX_CHARS - total;
-
- let mut chars: Vec = match s.str(glyphs, b"Utf8") {
- Some(t) => t.chars().take(budget + 1).collect(),
- None => {
- // Inline objects (page numbers, anchors) each take one index before the segment text.
- let segments = s.objs(glyphs, b"Mixd");
- if segments.is_empty() {
- r.warn("a text block without readable characters (left out)");
- continue;
- }
- let mut v = Vec::new();
- for seg in segments {
- let inline = s.objs(seg, b"Glys").len();
- v.extend(std::iter::repeat_n('\u{FFFC}', inline.min(budget + 1 - v.len())));
- placeholders |= inline > 0;
- v.extend(s.str(seg, b"Utf8").unwrap_or_default().chars().take(budget + 1 - v.len()));
- if v.len() > budget {
- break;
- }
- }
- v
- }
- };
- let truncated = chars.len() > budget;
- if truncated {
- chars.truncate(budget);
- r.warn("text longer than a million characters (truncated)");
- }
- total += chars.len();
- let mut start = 0usize;
- for run in s.obj(block, b"GAtt").map(|g| s.objs(g, b"Runs")).unwrap_or_default() {
- let Some(index) = s.int(run, b"Indx").and_then(|v| usize::try_from(v).ok()) else {
- r.warn("invalid text attribute range (bounded; unassigned characters use defaults)");
- continue;
- };
- let end = index.min(chars.len());
- if index > chars.len() || end < start {
- r.warn("invalid text attribute range (bounded; unassigned characters use defaults)");
- }
- if end <= start {
- continue;
- }
- let text = characters(&chars, start, end);
- start = end;
- push_run(r, &mut runs, s.obj(run, b"Item"), text, world, &mut attribute_budget);
- }
- if start < chars.len() {
- let text = characters(&chars, start, chars.len());
- push_run(r, &mut runs, None, text, world, &mut attribute_budget);
- }
- for paragraph in s.obj(block, b"PAtt").map(|p| s.objs(p, b"Runs")).unwrap_or_default() {
- if let Some(attrs) = s.obj(paragraph, b"Item") {
- let paragraph = paragraph_align(r, attrs);
- match align {
- None => align = Some(paragraph),
- Some(first) if first != paragraph => r.warn("mixed paragraph alignments (the first alignment is used)"),
- _ => {}
- }
- }
- }
- if truncated {
- break;
- }
- }
- if placeholders {
- r.warn("text fields such as page numbers (left out of the text)");
- }
- let align = align.unwrap_or(Align::Left);
+ let (runs, align) = story_runs(r, story, world);
let first_baseline = bounds.y0 + s.f64(frame, b"ArtV").unwrap_or(0.0);
let anchor_x = match align {
Align::Center => (bounds.x0 + bounds.x1) / 2.0,
@@ -111,19 +35,256 @@ pub(crate) fn read(r: &mut Reader, id: ObjId, world: Affine) -> Option {
r.warn("text frames with a curved outline (imported as rectangular frames)");
}
}
- Some(Text { runs, align, anchor: Point { x: anchor_x, y: first_baseline }, frame: if artistic { None } else { Some(bounds) }, transform: world })
+ let text_transform = if artistic { world } else { text_scale(r, id).then(r.type_base) };
+ Some(Text {
+ runs,
+ align,
+ anchor: Point { x: anchor_x, y: first_baseline },
+ frame: if artistic { None } else { Some(bounds) },
+ transform: world,
+ text_transform,
+ })
+}
+
+/// Rows and columns a table may have.
+const MAX_TABLE_LINES: usize = 4096;
+/// Cells a table may have (rows × columns): each becomes a text object with its edge lines.
+const MAX_TABLE_CELLS: usize = 1 << 16;
+
+/// A table node (`TxtT`): the grid, the cells' text and the lines on the cell edges.
+pub(crate) fn table(r: &mut Reader, id: ObjId, world: Affine) -> Option {
+ let s = r.s;
+ let story = s.obj(id, b"StSt")?;
+ let tabl = s.obj(id, b"TxtH").and_then(|h| s.obj(h, b"Tabl"))?;
+ let bounds = |pos: Option| -> Option> {
+ let Some(Value::Array(a)) = pos.and_then(|p| s.field(p, b"Posn")) else { return None };
+ let v: Vec = a.iter().take(MAX_TABLE_LINES + 2).map(float).collect::>()?;
+ (v.len() >= 2 && v.len() <= MAX_TABLE_LINES + 1 && v.windows(2).all(|w| w[1] >= w[0])).then_some(v)
+ };
+ let columns = bounds(s.obj(tabl, b"CPos"))?;
+ let rows = bounds(s.obj(tabl, b"RPos"))?;
+ let (ncols, nrows) = (columns.len() - 1, rows.len() - 1);
+ let count = ncols.checked_mul(nrows)?;
+ if count > MAX_TABLE_CELLS {
+ r.warn("tables with more than 65536 cells (left out)");
+ return None;
+ }
+ let Some(left) = r.budget.cells.checked_sub(count) else {
+ r.warn("tables beyond the cells one document may hold (left out)");
+ return None;
+ };
+ r.budget.cells = left;
+ let cell_objs = s.obj(tabl, b"Cell").map(|c| s.objs(c, b"Cell")).unwrap_or_default();
+ // Formatting that doesn't match the grid would land on the wrong cells (and merging them,
+ // move text between cells): only text then.
+ let cell_objs = if cell_objs.len() == count {
+ cell_objs
+ } else {
+ r.warn("tables whose cells don't match their grid (cell formatting left out)");
+ Vec::new()
+ };
+ let blank = || TableCell { runs: Vec::new(), inset: [0.0; 4], valign: VAlign::Top, merged_left: false };
+ let mut cells: Vec = (0..count).map(|_| blank()).collect();
+ for (i, (cell, obj)) in cells.iter_mut().zip(&cell_objs).enumerate() {
+ if let Some(inset) = s.floats::<4>(*obj, b"Inse").filter(|v| v.iter().all(|x| x.is_finite() && *x >= 0.0)) {
+ cell.inset = inset;
+ }
+ cell.valign = match s.enumeration(*obj, b"AliY").map(|(i, _)| i) {
+ Some(1) => VAlign::Center,
+ Some(2) => VAlign::Bottom,
+ _ => VAlign::Top,
+ };
+ // A cell merged into the one on its left; the first column has nothing to its left.
+ cell.merged_left = i % ncols != 0 && s.bool(*obj, b"BrLf") == Some(true);
+ }
+ // The story holds the text of every cell that isn't merged away, row by row, each ended by a
+ // cell break.
+ let owner_list: Vec = (0..count).filter(|i| cells.get(*i).is_some_and(|c| !c.merged_left)).collect();
+ let mut owners = owner_list.into_iter();
+ let mut target = owners.next();
+ let mut extra = false;
+ let (runs, _) = story_runs(r, story, world);
+ for run in runs {
+ let mut parts = run.text.split(CELL_BREAK).peekable();
+ while let Some(part) = parts.next() {
+ if !part.is_empty() {
+ match target.and_then(|i| cells.get_mut(i)) {
+ Some(cell) => cell.runs.push(TextRun { text: part.to_string(), ..run.clone() }),
+ None => extra = true,
+ }
+ }
+ if parts.peek().is_some() {
+ target = owners.next();
+ }
+ }
+ }
+ if extra {
+ r.warn("table text beyond its last cell (left out)");
+ }
+ let mut edges = |tag: &[u8; 4], expected: usize| -> Vec> {
+ let objs = s.obj(tabl, tag).map(|e| s.objs(e, b"Edge")).unwrap_or_default();
+ if objs.len() != expected {
+ r.warn("tables whose lines don't match their grid (lines left out)");
+ return Vec::new();
+ }
+ objs.into_iter()
+ .map(|e| match (s.obj(e, b"Fill"), s.obj(e, b"Line")) {
+ (Some(pen), Some(line)) => paint::stroke(r, pen, line, world, false),
+ _ => None,
+ })
+ .collect()
+ };
+ let vertical = edges(b"CEdg", (ncols + 1) * nrows);
+ let horizontal = edges(b"REdg", ncols * (nrows + 1));
+ if let Some(format) = s.obj(tabl, b"TFmt") {
+ let filled =
+ s.objs(format, b"Clls").into_iter().filter_map(|c| s.obj(c, b"Fill")).any(|f| s.obj(f, b"FDeF").is_some_and(|d| !s.is(d, b"FilN")));
+ if filled {
+ r.warn("table cell fills (left out)");
+ }
+ }
+ let text_transform = text_scale(r, id).then(r.type_base);
+ Some(Table { columns, rows, cells, vertical, horizontal, transform: world, text_transform })
+}
+
+/// A story's character runs, each with its paragraph's format, and the first paragraph's
+/// alignment. Table cells end with [`CELL_BREAK`].
+pub(crate) fn story_runs(r: &mut Reader, story: ObjId, world: Affine) -> (Vec, Align) {
+ let s = r.s;
+ let mut runs = Vec::new();
+ let mut first_align = None;
+ let mut total = 0usize;
+ let mut placeholders = false;
+ let mut attribute_budget = Some(MAX_ATTRIBUTE_BYTES);
+ for block in s.objs(story, b"Blok") {
+ let Some(glyphs) = s.obj(block, b"Glyp") else {
+ r.warn("a text block without readable characters (left out)");
+ continue;
+ };
+ // Bound collection itself, including placeholders, before allocating the character buffer:
+ // by the story's limit and by what the document's other stories left.
+ let budget = (MAX_CHARS - total).min(r.budget.chars.saturating_sub(total));
+
+ let mut chars: Vec = match s.str(glyphs, b"Utf8") {
+ Some(t) => t.chars().take(budget + 1).collect(),
+ None => {
+ // Inline objects (page numbers, anchors, cell ends) each take one index before
+ // the segment text.
+ let segments = s.objs(glyphs, b"Mixd");
+ if segments.is_empty() {
+ r.warn("a text block without readable characters (left out)");
+ continue;
+ }
+ let mut v = Vec::new();
+ for seg in segments {
+ for inline in s.objs(seg, b"Glys") {
+ if v.len() > budget {
+ break;
+ }
+ if s.is(inline, b"BrGl") && s.enumeration(inline, b"HdBk").is_some_and(|(kind, _)| kind == 4) {
+ v.push(CELL_BREAK);
+ } else {
+ v.push('\u{FFFC}');
+ placeholders = true;
+ }
+ }
+ v.extend(s.str(seg, b"Utf8").unwrap_or_default().chars().take((budget + 1).saturating_sub(v.len())));
+ if v.len() > budget {
+ break;
+ }
+ }
+ v
+ }
+ };
+ let truncated = chars.len() > budget;
+ if truncated {
+ chars.truncate(budget);
+ if budget < MAX_CHARS - total {
+ r.warn("text beyond the characters one document may hold (truncated)");
+ } else {
+ r.warn("text longer than a million characters (truncated)");
+ }
+ }
+ total += chars.len();
+ // Paragraph formats by end index; a run without an index covers the rest of the block.
+ let mut paragraphs: Vec<(usize, Paragraph)> = Vec::new();
+ let mut open: Option = None;
+ for run in s.obj(block, b"PAtt").map(|p| s.objs(p, b"Runs")).unwrap_or_default() {
+ let Some(attrs) = s.obj(run, b"Item") else { continue };
+ let a = paragraph(r, attrs);
+ first_align.get_or_insert(a.align);
+ match s.int(run, b"Indx").and_then(|v| usize::try_from(v).ok()) {
+ Some(end) => paragraphs.push((end, a)),
+ None => match open {
+ None => open = Some(a),
+ Some(first) if first != a => r.warn("mixed paragraph formats in one block (the first is used)"),
+ _ => {}
+ },
+ }
+ }
+ // Sorted by end (they are in order in every file), so both lookups below are binary
+ // searches: a block can have as many paragraphs and runs as characters.
+ paragraphs.sort_by_key(|(end, _)| *end);
+ let align_at = |i: usize| paragraphs.get(paragraphs.partition_point(|(end, _)| *end <= i)).map(|(_, a)| *a).or(open).unwrap_or_default();
+ let mut cuts: Vec = paragraphs.iter().map(|(end, _)| *end).filter(|e| *e < chars.len()).collect();
+ cuts.dedup();
+ let push = |r: &mut Reader, runs: &mut Vec, attrs: Option, from: usize, to: usize, budget: &mut Option| {
+ // Split at paragraph ends so every run has one paragraph format.
+ let inside = cuts.get(cuts.partition_point(|c| *c <= from)..cuts.partition_point(|c| *c < to)).unwrap_or_default();
+ let mut a = from;
+ for &c in inside.iter().chain(std::iter::once(&to)) {
+ push_run(r, runs, attrs, characters(&chars, a, c), world, budget, align_at(a));
+ a = c;
+ }
+ };
+ let mut start = 0usize;
+ for run in s.obj(block, b"GAtt").map(|g| s.objs(g, b"Runs")).unwrap_or_default() {
+ let Some(index) = s.int(run, b"Indx").and_then(|v| usize::try_from(v).ok()) else {
+ r.warn("invalid text attribute range (bounded; unassigned characters use defaults)");
+ continue;
+ };
+ let end = index.min(chars.len());
+ if index > chars.len() || end < start {
+ r.warn("invalid text attribute range (bounded; unassigned characters use defaults)");
+ }
+ if end <= start {
+ continue;
+ }
+ push(r, &mut runs, s.obj(run, b"Item"), start, end, &mut attribute_budget);
+ start = end;
+ }
+ if start < chars.len() {
+ push(r, &mut runs, None, start, chars.len(), &mut attribute_budget);
+ }
+ if truncated {
+ break;
+ }
+ }
+ r.budget.chars = r.budget.chars.saturating_sub(total);
+ if placeholders {
+ r.warn("text fields such as page numbers (left out of the text)");
+ }
+ (runs, first_align.unwrap_or(Align::Left))
}
fn characters(chars: &[char], start: usize, end: usize) -> String {
chars.get(start..end).unwrap_or_default().iter().filter(|c| **c != '\0' && **c != '\u{FFFC}').collect()
}
-fn push_run(r: &mut Reader, runs: &mut Vec, attrs: Option, text: String, world: Affine, attribute_budget: &mut Option) {
+fn push_run(
+ r: &mut Reader,
+ runs: &mut Vec,
+ attrs: Option,
+ text: String,
+ world: Affine,
+ attribute_budget: &mut Option,
+ paragraph: Paragraph,
+) {
if text.is_empty() {
return;
}
let run = match attrs {
- Some(attrs) if attribute_budget.is_some() => run_attrs(r, attrs, text, world, attribute_budget),
+ Some(attrs) if attribute_budget.is_some() => TextRun { paragraph, ..run_attrs(r, attrs, text, world, attribute_budget) },
_ => {
// This is a recovery policy, not an assertion about unspecified Affinity attributes.
if attrs.is_none() {
@@ -137,10 +298,15 @@ fn push_run(r: &mut Reader, runs: &mut Vec, attrs: Option, text:
italic: false,
features: Vec::new(),
all_caps: false,
+ underline: false,
+ strikethrough: false,
size: 12.0 * r.dpi / 72.0,
tracking: 0.0,
+ h_scale: 1.0,
leading: None,
fill: Paint::Solid(Color::Gray { v: 0.0, a: 1.0 }),
+ stroke: None,
+ paragraph,
}
}
};
@@ -195,13 +361,33 @@ fn run_attrs(r: &mut Reader, attrs: ObjId, text: String, world: Affine, attribut
fill = Paint::Solid(Color::Gray { v: 0.0, a: 1.0 });
}
}
- if attribute_budget.is_some() && objects.get(1).copied().flatten().and_then(|f| paint::descriptor(r, f, world)).is_some_and(|p| p != Paint::None)
- {
- r.warn("outlined (stroked) text");
- }
- if slot(doubles, 10, float).is_some_and(|h| (h - 1.0).abs() > 1e-3) {
- r.warn("horizontally scaled text");
+ // Outlined characters: `Objs` 1 is the outline's paint, 2 its line style (as for shapes).
+ let mut stroke = match (attribute_budget.is_some(), objects.get(1).copied().flatten(), objects.get(2).copied().flatten()) {
+ (true, Some(pen), Some(style)) => paint::stroke(r, pen, style, Affine::IDENTITY, false),
+ _ => None,
+ };
+ // Its gradient stops and dashes are owned data too, charged like the fill's.
+ if let Some(st) = &stroke {
+ let stops = match &st.paint {
+ Paint::Gradient(g) => g.stops.len().saturating_mul(std::mem::size_of::()),
+ _ => 0,
+ };
+ let dash = st.dash.as_ref().map_or(0, |(d, _)| d.len().saturating_mul(std::mem::size_of::()));
+ if !charge_attributes(r, attribute_budget, stops.saturating_add(dash)) {
+ stroke = None;
+ }
}
+ // Underline (slot 0) and strikethrough (slot 1): 1 is a single line.
+ let mut decoration = |i: usize| match slot(ints, i, int) {
+ Some(1) => true,
+ Some(0) | None => false,
+ Some(_) => {
+ r.warn("text decorations of an unknown kind (left out)");
+ false
+ }
+ };
+ let (underline, strikethrough) = (decoration(0), decoration(1));
+ let h_scale = slot(doubles, 10, float).filter(|h| *h > 0.0 && *h < 100.0).unwrap_or(1.0);
// A resolved font is populated on the emoji run of the public Affinity 3 text-runs file
// (Courier New requested, Segoe UI Emoji stored in RFnt). Empty RFnt records are common.
// Source: https://github.com/SethRobinson/Patchy/tree/de84eab550758b30fa062e479f5778cce7693b73/test-fixtures/af
@@ -220,8 +406,8 @@ fn run_attrs(r: &mut Reader, attrs: ObjId, text: String, world: Affine, attribut
if font.and_then(|f| s.int(f, b"Widh")).is_some_and(|w| w != 5) {
r.warn("font width variants (exact face depends on the installed PostScript font)");
}
- let postscript = metadata_string(r, attribute_budget, font.and_then(|f| s.str(f, b"Post")).unwrap_or_default());
- let family = metadata_string(r, attribute_budget, font.and_then(|f| s.str(f, b"Famy")).unwrap_or_default());
+ let postscript = font_name(r, attribute_budget, font.and_then(|f| s.str(f, b"Post")).unwrap_or_default());
+ let family = font_name(r, attribute_budget, font.and_then(|f| s.str(f, b"Famy")).unwrap_or_default());
let (features, all_caps) = font_features(r, objects.get(7).copied().flatten(), attribute_budget);
let weight = font.and_then(|f| s.int(f, b"Wegt")).unwrap_or(400);
let weight = if (1..=1000).contains(&weight) {
@@ -238,10 +424,15 @@ fn run_attrs(r: &mut Reader, attrs: ObjId, text: String, world: Affine, attribut
italic: font.and_then(|f| s.bool(f, b"Ital")).unwrap_or(false),
features,
all_caps,
+ underline,
+ strikethrough,
size,
tracking,
+ h_scale,
leading,
fill,
+ stroke,
+ paragraph: Paragraph::default(),
}
}
@@ -260,6 +451,17 @@ fn charge_attributes(r: &mut Reader, budget: &mut Option, bytes: usize) -
}
}
+/// Longest font name kept (OpenType names are far shorter); every run and paragraph carries it.
+const MAX_FONT_NAME: usize = 256;
+
+fn font_name(r: &mut Reader, budget: &mut Option, value: &str) -> String {
+ if value.len() > MAX_FONT_NAME {
+ r.warn("font names longer than 256 bytes (the default font is used)");
+ return String::new();
+ }
+ metadata_string(r, budget, value)
+}
+
fn metadata_string(r: &mut Reader, budget: &mut Option, value: &str) -> String {
let bytes = value.len().saturating_add(std::mem::size_of::());
if value.is_empty() || !charge_attributes(r, budget, bytes) { String::new() } else { value.to_owned() }
@@ -303,13 +505,18 @@ fn font_features(r: &mut Reader, attrs: Option, attribute_budget: &mut Op
(features, all_caps)
}
-fn paragraph_align(r: &mut Reader, p: ObjId) -> Align {
- // Nonzero offsets in these slots are present in the public text-indent and text-para-spacing
- // fixtures. Their layout is not represented by this importer; retain text and report the gap.
- if (1..=6).any(|i| slot(r.s.field(p, b"Doub"), i, float).is_some_and(|v| v.abs() > 1e-9)) {
- r.warn("paragraph indents or spacing (imported with defaults)");
- }
- match slot(r.s.field(p, b"Ints"), 0, int) {
+/// A paragraph's alignment, indents, spacing and leading. The `Doub` slots: 0 the automatic
+/// leading as a multiple of the font's line height (1 in every document checked), 1 fixed leading
+/// (when `Ints` slot 1 is 2; in every paragraph checked the two go together), 2 indent of the
+/// lines after the first, 3 right indent, 4 indent of the first line, 5 space before, 6 space
+/// after. Slots 2, 4, 5 and 6 were identified on the public MIT text-indent and text-para-spacing
+/// fixtures (Patchy) by measuring their thumbnails, slot 1 by measuring the baseline pitch in the
+/// thumbnail of a document whose owner made it earlier.
+fn paragraph(r: &mut Reader, p: ObjId) -> Paragraph {
+ let doubles = r.s.field(p, b"Doub");
+ let ints = r.s.field(p, b"Ints");
+ let at = |i: usize| slot(doubles, i, float).filter(|v| v.abs() < 1e6).unwrap_or(0.0);
+ let align = match slot(ints, 0, int) {
Some(1) => Align::Center,
Some(2) => Align::Right,
Some(3) => Align::Justify,
@@ -318,5 +525,29 @@ fn paragraph_align(r: &mut Reader, p: ObjId) -> Align {
r.warn("an unknown paragraph alignment (imported as left)");
Align::Left
}
+ };
+ let leading = match slot(ints, 1, int) {
+ Some(2) => Some(at(1)).filter(|l| *l > 0.0),
+ Some(0) | None => None,
+ Some(_) => {
+ r.warn("paragraph leading of an unknown kind (imported as automatic)");
+ None
+ }
+ };
+ let auto_leading = slot(doubles, 0, float).filter(|v| *v > 0.0 && *v < 100.0).unwrap_or(1.0);
+ Paragraph { align, left: at(2), right: at(3), first: at(4), space_before: at(5).max(0.0), space_after: at(6).max(0.0), leading, auto_leading }
+}
+
+/// The scale a text frame or table gives its type (`FTxS`, stored like `Xfrm`): none unless set.
+/// Neither the frame's own transform nor its groups' scale its type (checked against the
+/// thumbnails of tables and frames inside scaled groups).
+fn text_scale(r: &mut Reader, id: ObjId) -> Affine {
+ match r.s.floats::<6>(id, b"FTxS").map(Affine::from_xfrm) {
+ Some(m) if m.is_finite() && m.scale() > 1e-9 => Affine([m.0[0], m.0[1], m.0[2], m.0[3], 0.0, 0.0]),
+ Some(_) => {
+ r.warn("text frames with an invalid text scale (imported unscaled)");
+ Affine::IDENTITY
+ }
+ None => Affine::IDENTITY,
}
}
diff --git a/crates/affinity/tests/import_limits.rs b/crates/affinity/tests/import_limits.rs
new file mode 100644
index 0000000000..9a955116f0
--- /dev/null
+++ b/crates/affinity/tests/import_limits.rs
@@ -0,0 +1,182 @@
+//! Crafted documents can't make the reader allocate or work without bound: tables, shared
+//! stories, paragraphs and embedded documents stay within the whole read's budget, however often
+//! a file links or embeds the same content. Original synthetic documents in the reader's
+//! accepted schema; no Affinity software or files were used.
+#![cfg(feature = "synth")]
+#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
+
+mod support {
+ pub mod text_fixture;
+}
+
+use support::text_fixture::*;
+use vectorcraft_affinity::{
+ Document, Error, Limits,
+ model::{Kind, Node},
+ read,
+ synth::{self, F, Method, tag},
+};
+
+type Field = (vectorcraft_affinity::stream::Tag, F);
+
+/// A document of one spread holding `nodes`, plus these other archive entries.
+fn file(nodes: Vec, entries: &[(&str, &[u8])]) -> Vec {
+ let spread = F::Obj(tag(b"Sprd"), vec![(tag(b"SprB"), F::F64s(vec![0.0, 0.0, 400.0, 300.0])), (tag(b"Chld"), F::Shared(nodes))]);
+ let mut root = vec![(tag(b"DocR"), F::Obj(tag(b"DocN"), vec![(tag(b"Chld"), F::Shared(vec![spread]))]))];
+ let mut next_id = 1000;
+ for (_, value) in &mut root {
+ shared_objects(value, &mut next_id);
+ }
+ let data = synth::stream(&root);
+ let mut all = vec![("doc.dat", data.as_slice(), Method::Zlib)];
+ all.extend(entries.iter().map(|(name, bytes)| (*name, *bytes, Method::Stored)));
+ synth::container(&all, None)
+}
+
+fn open(nodes: Vec) -> Document {
+ read(&file(nodes, &[]), Limits::default()).unwrap()
+}
+
+fn all(nodes: &[Node]) -> Vec<&Node> {
+ let mut out = Vec::new();
+ for n in nodes {
+ out.push(n);
+ out.extend(all(&n.children));
+ }
+ out
+}
+
+fn warned(d: &Document, needle: &str) -> bool {
+ d.warnings.iter().any(|w| w.contains(needle))
+}
+
+fn story(text: &str) -> F {
+ F::Obj(tag(b"Stry"), vec![(tag(b"Blok"), F::Shared(vec![block(utf8(text), vec![run(text.chars().count() as i32, None)], &[])]))])
+}
+
+fn artistic(story: F) -> F {
+ F::Obj(
+ tag(b"TxtA"),
+ vec![
+ (tag(b"StSt"), story),
+ (tag(b"TxtH"), F::Obj(tag(b"ArFr"), vec![(tag(b"FrmB"), F::F64s(vec![0.0, 0.0, 100.0, 20.0])), (tag(b"ArtV"), F::F64(16.0))])),
+ ],
+ )
+}
+
+/// A table frame (`TbFr`) with a grid of `cols` × `rows` cells and no cell objects or lines.
+fn grid(cols: usize, rows: usize) -> Vec {
+ let pos = |n: usize| {
+ let v: Vec = (0..=n).map(|i| i as f64).collect();
+ F::Obj(tag(b"TPos"), vec![(tag(b"Posn"), array_f64(b"Posn", &v))])
+ };
+ let table = F::Obj(tag(b"Tabl"), vec![(tag(b"CPos"), pos(cols)), (tag(b"RPos"), pos(rows))]);
+ vec![(tag(b"FrmB"), F::F64s(vec![0.0, 0.0, cols as f64, rows as f64])), (tag(b"Tabl"), table)]
+}
+
+fn table(frame: F) -> F {
+ F::Obj(tag(b"TxtT"), vec![(tag(b"StSt"), story("A")), (tag(b"TxtH"), frame)])
+}
+
+fn tables(d: &Document) -> Vec<&vectorcraft_affinity::model::Table> {
+ all(&d.spreads[0].nodes).into_iter().filter_map(|n| if let Kind::Table(t) = &n.kind { Some(t) } else { None }).collect()
+}
+
+#[test]
+fn a_table_of_more_than_65536_cells_is_left_out_before_its_cells_are_made() {
+ // 4096 × 4096 is within each dimension's limit but 16.7 million cells.
+ let d = open(vec![table(F::Obj(tag(b"TbFr"), grid(4096, 4096))), table(F::Obj(tag(b"TbFr"), grid(256, 256)))]);
+ let t = tables(&d);
+ assert_eq!(t.len(), 1);
+ assert_eq!((t[0].cells.len(), t[0].vertical.len(), t[0].horizontal.len()), (65536, 0, 0), "no lines when they don't match");
+ assert!(warned(&d, "tables with more than 65536 cells"), "{:?}", d.warnings);
+}
+
+#[test]
+fn tables_sharing_one_grid_stay_within_the_cells_of_one_document() {
+ // One 65536-cell grid linked from five tables: four fill the document's 262144 cells.
+ let shared = F::Def(2_000_000, vec![tag(b"TbFr")], grid(256, 256));
+ let d = open((0..5).map(|i| table(if i == 0 { shared.clone() } else { F::Ref(2_000_000) })).collect());
+ assert_eq!(tables(&d).len(), 4);
+ assert!(warned(&d, "tables beyond the cells one document may hold"), "{:?}", d.warnings);
+}
+
+#[test]
+fn a_shared_story_is_read_within_the_characters_of_one_document() {
+ // A story of a million characters linked from twenty text layers: 16 million in all.
+ let text = "x".repeat(1 << 20);
+ let shared = F::Def(2_000_000, vec![tag(b"Stry")], vec![(tag(b"Blok"), F::Shared(vec![block(utf8(&text), vec![run(1 << 20, None)], &[])]))]);
+ let d = open((0..20).map(|i| artistic(if i == 0 { shared.clone() } else { F::Ref(2_000_000) })).collect());
+ let chars: usize = all(&d.spreads[0].nodes)
+ .into_iter()
+ .filter_map(|n| if let Kind::Text(t) = &n.kind { Some(t.runs.iter().map(|r| r.text.len()).sum::()) } else { None })
+ .sum();
+ assert_eq!(chars, 16 << 20);
+ assert!(warned(&d, "text beyond the characters one document may hold"), "{:?}", d.warnings);
+}
+
+#[test]
+fn many_paragraphs_and_runs_are_matched_in_about_linear_time() {
+ // 200 000 paragraphs, each with its own run and format.
+ let n = 200_000;
+ let text = "a\u{2029}".repeat(n);
+ let fmt =
+ |end: usize| vec![(tag(b"Indx"), F::I32(end as i32)), (tag(b"Item"), F::Obj(tag(b"PAtt"), vec![(tag(b"Ints"), array_i32(b"Ints", &[1]))]))];
+ let blk = F::Obj(
+ tag(b"StBl"),
+ vec![
+ (tag(b"Glyp"), utf8(&text)),
+ (tag(b"GAtt"), F::Obj(tag(b"GlAS"), vec![(tag(b"Runs"), F::Objs(tag(b"GlAR"), (1..=n).map(|i| run(2 * i as i32, None)).collect()))])),
+ (tag(b"PAtt"), F::Obj(tag(b"PaAS"), vec![(tag(b"Runs"), F::Objs(tag(b"PaAR"), (1..=n).map(|i| fmt(2 * i)).collect()))])),
+ ],
+ );
+ let started = std::time::Instant::now();
+ let d = open(vec![artistic(F::Obj(tag(b"Stry"), vec![(tag(b"Blok"), F::Shared(vec![blk]))]))]);
+ let Kind::Text(t) = &d.spreads[0].nodes[0].kind else { panic!("text") };
+ assert_eq!(t.runs.len(), n);
+ // (About half a second; quadratic matching took over half a minute on the same machine.)
+ assert!(started.elapsed().as_secs() < 10, "{:?}", started.elapsed());
+}
+
+/// A shape node of `size` px.
+fn rect(size: f64) -> F {
+ F::Obj(tag(b"ShpN"), vec![(tag(b"ShpB"), F::F64s(vec![0.0, 0.0, size, size])), (tag(b"Shpe"), F::Obj(tag(b"ShNR"), vec![]))])
+}
+
+/// An instance of the embedded document in archive entry `edc/1`, with `children` of its own.
+fn embedded(children: Vec) -> F {
+ let content = F::Obj(tag(b"EmbC"), vec![(tag(b"EmbC"), F::Entry("edc/1".into()))]);
+ let mut fields = vec![(tag(b"Bitm"), F::Obj(tag(b"EmbR"), vec![(tag(b"EmCn"), content)]))];
+ if !children.is_empty() {
+ fields.push((tag(b"Chld"), F::Shared(children)));
+ }
+ F::Obj(tag(b"EmbN"), fields)
+}
+
+fn embedding(inner: &[u8], nodes: Vec) -> Vec {
+ let mut entry = b"EmDc\0\0\0\0".to_vec();
+ entry.extend_from_slice(inner);
+ file(nodes, &[("edc/1", &entry)])
+}
+
+#[test]
+fn an_embedded_documents_content_stays_with_its_node() {
+ // Read before the node's own children, which must not take it.
+ let inner = file(vec![rect(10.0), rect(20.0)], &[]);
+ let d = read(&embedding(&inner, vec![embedded(vec![rect(5.0)])]), Limits::default()).unwrap();
+ let node = &d.spreads[0].nodes[0];
+ assert_eq!(node.children.len(), 3, "its own child and the embedded document's two shapes");
+ assert!(node.children.iter().all(|c| c.children.is_empty()));
+}
+
+#[test]
+fn embedding_one_document_many_times_shares_one_budget() {
+ // 2000 shapes, embedded 300 times and read twice each: 1.2 million nodes, past the 500 000
+ // a whole read may take (each embedding used to have an allowance of its own).
+ let inner = file((0..2000).map(|_| rect(10.0)).collect(), &[]);
+ let outer = embedding(&inner, (0..300).map(|_| embedded(Vec::new())).collect());
+ assert!(matches!(read(&outer, Limits::default()), Err(Error::Limit(_))));
+ // Embedded fewer times, it opens.
+ let d = read(&embedding(&inner, (0..50).map(|_| embedded(Vec::new())).collect()), Limits::default()).unwrap();
+ assert_eq!(all(&d.spreads[0].nodes).len(), 50 + 50 * 2000);
+}
diff --git a/crates/affinity/tests/raster.rs b/crates/affinity/tests/raster.rs
index e477b4d26b..173bc9158d 100644
--- a/crates/affinity/tests/raster.rs
+++ b/crates/affinity/tests/raster.rs
@@ -103,13 +103,16 @@ fn rotated_scaled_pixels_keep_the_full_affine_transform() {
}
#[test]
-fn cmyk_and_lab_losses_are_reported() {
+fn cmyk_pixels_stay_cmyk_and_lab_losses_are_reported() {
+ // CMYK layers keep their inks for the importer to convert through a colour profile.
let Some((_, cmyk, images)) = read_fixture("patchy-cmyk.af") else { return };
assert_eq!(images.len(), 1);
assert_eq!((images[0].width, images[0].height), (64, 48));
- let Pixels::Rgba8(pixels) = &images[0].pixels else { panic!() };
- assert_eq!(crc32fast::hash(pixels), 0x5872bb76);
- assert_eq!(cmyk.warnings, ["CMYK pixel layers (converted to RGB without the document's colour profile)"]);
+ let Pixels::Cmyka8(pixels) = &images[0].pixels else { panic!() };
+ assert_eq!(pixels.len(), 64 * 48 * 5);
+ assert_eq!(crc32fast::hash(pixels), 0x56b1f659);
+ assert!(cmyk.warnings.is_empty(), "{:?}", cmyk.warnings);
+ assert_eq!(cmyk.cmyk_profile, None, "this file embeds no profile");
let (_, lab, images) = read_fixture("patchy-lab.af").unwrap();
assert!(images.is_empty());
assert_eq!(lab.warnings, ["pixel layers in grey, Lab or 32-bit formats"]);
diff --git a/crates/affinity/tests/support/affinity3-signatures.txt b/crates/affinity/tests/support/affinity3-signatures.txt
index fb6c94b29f..779a58552e 100644
--- a/crates/affinity/tests/support/affinity3-signatures.txt
+++ b/crates/affinity/tests/support/affinity3-signatures.txt
@@ -1,33 +1,33 @@
-affinity3-mexican-guy.af dpi=300;spreads=1;model_crc32=df3c417b;counts={"depth": 8, "fills": 169, "gradients": 0, "groups": 23, "nodes": 283, "opacity": 1, "segments": 1491, "shapes": 260, "strokes": 114, "subpaths": 264};boards=[];fonts={};warnings=["brush and pressure strokes (imported as plain strokes) (114×)", "layer effects (shadows, glows, outlines, bevels…) (156×)"]
-affinity3-mexican-man.af dpi=300;spreads=1;model_crc32=d0387de4;counts={"depth": 7, "fills": 277, "gradients": 2, "groups": 29, "nodes": 903, "segments": 3225, "shapes": 874, "strokes": 559, "subpaths": 881};boards=[];fonts={};warnings=["brush and pressure strokes (imported as plain strokes) (545×)", "layer effects (shadows, glows, outlines, bevels…) (245×)"]
-affinity3-mexican-woman.af dpi=300;spreads=1;model_crc32=b966f693;counts={"depth": 9, "fills": 527, "gradients": 0, "groups": 28, "nodes": 595, "segments": 3562, "shapes": 567, "strokes": 60, "subpaths": 570};boards=[];fonts={};warnings=["brush and pressure strokes (imported as plain strokes) (54×)", "layer effects (shadows, glows, outlines, bevels…) (278×)"]
-affinity3-playing-cards.af dpi=300;spreads=1;model_crc32=ac448123;counts={"depth": 5, "fills": 363, "gradients": 0, "groups": 758, "nodes": 1350, "segments": 4864, "shapes": 592, "strokes": 288, "subpaths": 656};boards=[];fonts={};warnings=["brush and pressure strokes (imported as plain strokes)", "layer effects (shadows, glows, outlines, bevels…) (339×)"]
-patchy-adjust-curves.af dpi=72;spreads=1;model_crc32=10a37502;counts={"depth": 1, "images": 1, "nodes": 2, "unsupported": 1};boards=[];fonts={};warnings=["adjustment layers"]
-patchy-adjust-hsl.af dpi=72;spreads=1;model_crc32=c65409b4;counts={"depth": 1, "images": 1, "nodes": 2, "unsupported": 1};boards=[];fonts={};warnings=["adjustment layers"]
-patchy-artboards.af dpi=72;spreads=1;model_crc32=f1ae5644;counts={"artboards": 2, "depth": 2, "fills": 2, "gradients": 0, "nodes": 4, "segments": 7, "shapes": 2, "strokes": 0, "subpaths": 2};boards=["board-a:0.0000,0.0000,80.0000,60.0000", "board-b:100.0000,10.0000,160.0000,70.0000"];fonts={};warnings=[]
-patchy-blend-affinity.af dpi=72;spreads=1;model_crc32=f6691ff9;counts={"depth": 2, "fills": 8, "gradients": 0, "images": 1, "layers": 1, "nodes": 10, "segments": 24, "shapes": 8, "strokes": 0, "subpaths": 8};boards=[];fonts={};warnings=["an unknown blend mode (imported as Normal) (2×)"]
-patchy-cmyk.af dpi=72;spreads=1;model_crc32=5145b5a1;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=["CMYK pixel layers (converted to RGB without the document's colour profile)"]
-patchy-dpi300.af dpi=300;spreads=1;model_crc32=0c23e7c8;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
-patchy-embedded-jpeg.af dpi=72;spreads=1;model_crc32=090c674b;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
-patchy-fx-blur.af dpi=72;spreads=1;model_crc32=3f1b8b44;counts={"depth": 1, "images": 2, "nodes": 2};boards=[];fonts={};warnings=["layer effects (shadows, glows, outlines, bevels…) (2×)"]
-patchy-fx-gradient.af dpi=72;spreads=1;model_crc32=e868c992;counts={"depth": 1, "images": 3, "nodes": 3};boards=[];fonts={};warnings=["layer effects (shadows, glows, outlines, bevels…) (3×)"]
-patchy-fx.af dpi=72;spreads=1;model_crc32=5a1c34ac;counts={"depth": 1, "images": 5, "nodes": 5};boards=[];fonts={};warnings=["layer effects (shadows, glows, outlines, bevels…) (5×)"]
-patchy-group.af dpi=72;spreads=1;model_crc32=c217ab38;counts={"depth": 2, "images": 3, "layers": 1, "nodes": 4};boards=[];fonts={};warnings=[]
-patchy-incremental-chain.af dpi=72;spreads=1;model_crc32=63ad778e;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=["layer effects (shadows, glows, outlines, bevels…)"]
-patchy-lab.af dpi=72;spreads=1;model_crc32=01e8a926;counts={"depth": 1, "nodes": 1, "unsupported": 1};boards=[];fonts={};warnings=["pixel layers in grey, Lab or 32-bit formats"]
-patchy-lazy-placed.af dpi=72;spreads=1;model_crc32=9ce9937e;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
-patchy-live-filter.af dpi=72;spreads=1;model_crc32=30c5f8ee;counts={"depth": 2, "fills": 2, "gradients": 0, "nodes": 4, "segments": 6, "shapes": 2, "strokes": 0, "subpaths": 2, "unsupported": 2};boards=[];fonts={};warnings=["adjustment layers", "unknown layers"]
-patchy-rgba16.af dpi=72;spreads=1;model_crc32=1bb23571;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
-patchy-rgba8.af dpi=72;spreads=1;model_crc32=1bb23571;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
-patchy-shapes-2.af dpi=72;spreads=1;model_crc32=7828d3cd;counts={"depth": 1, "fills": 12, "gradients": 0, "nodes": 12, "segments": 62, "shapes": 12, "strokes": 0, "subpaths": 12};boards=[];fonts={};warnings=["cloud, heart, cog, callout, arrow, tear and other special shapes (imported as their bounding ellipse) (9×)"]
-patchy-shapes.af dpi=72;spreads=1;model_crc32=7519f5fe;counts={"depth": 1, "fills": 4, "gradients": 0, "nodes": 4, "segments": 28, "shapes": 4, "strokes": 0, "subpaths": 4};boards=[];fonts={};warnings=[]
-patchy-text-artistic.af dpi=72;spreads=1;model_crc32=b6137f6e;counts={"depth": 1, "nodes": 1, "text_chars": 5, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialMT:400:false"};warnings=[]
-patchy-text-caps.af dpi=72;spreads=1;model_crc32=b5527e72;counts={"depth": 1, "nodes": 2, "text_chars": 21, "text_runs": 2, "texts": 2};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font) (2×)"]
-patchy-text-frame.af dpi=72;spreads=1;model_crc32=7a2cd32d;counts={"depth": 1, "nodes": 1, "text_chars": 11, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialMT:400:false"};warnings=["paragraph indents or spacing (imported with defaults)"]
-patchy-text-indent.af dpi=72;spreads=1;model_crc32=30ee834c;counts={"depth": 1, "nodes": 2, "text_chars": 104, "text_runs": 2, "texts": 2};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font) (2×)", "paragraph indents or spacing (imported with defaults) (2×)"]
-patchy-text-para-spacing.af dpi=72;spreads=1;model_crc32=3d580ad2;counts={"depth": 1, "nodes": 1, "text_chars": 13, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font)", "paragraph indents or spacing (imported with defaults)"]
-patchy-text-rotated.af dpi=72;spreads=1;model_crc32=ad77772a;counts={"depth": 1, "nodes": 1, "text_chars": 7, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font)"]
-patchy-text-runs.af dpi=72;spreads=1;model_crc32=a8da3052;counts={"depth": 1, "nodes": 1, "text_chars": 7, "text_runs": 5, "texts": 1};boards=[];fonts={"Arial:ArialNarrow:400:false", "Courier New:CourierNewPSMT:400:false", "Segoe UI Emoji:SegoeUIEmoji:400:false", "Times New Roman:TimesNewRomanPSMT:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font)", "paragraph indents or spacing (imported with defaults)", "text uses a stored fallback font (imported with that font)"]
-patchy-transform.af dpi=72;spreads=1;model_crc32=f8807611;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
-patchy-vector-mask.af dpi=72;spreads=1;model_crc32=1851fd90;counts={"depth": 1, "fills": 2, "gradients": 0, "nodes": 2, "segments": 7, "shapes": 2, "strokes": 0, "subpaths": 2, "vector_masks": 1};boards=[];fonts={};warnings=["unknown layers attached to other layers (imported without them)"]
-patchy-vector.af dpi=72;spreads=1;model_crc32=b89a91d3;counts={"depth": 1, "fills": 3, "gradients": 0, "nodes": 4, "segments": 17, "shapes": 4, "strokes": 2, "subpaths": 5};boards=[];fonts={};warnings=[]
+affinity3-mexican-guy.af dpi=300;spreads=1;model_crc32=d23a6900;counts={"depth": 8, "fills": 169, "gradients": 0, "groups": 23, "nodes": 283, "opacity": 1, "segments": 1491, "shapes": 260, "strokes": 114, "subpaths": 264};boards=[];fonts={};warnings=["blur effects (left out) (156×)", "brush and pressure strokes (imported as plain strokes) (114×)"]
+affinity3-mexican-man.af dpi=300;spreads=1;model_crc32=b8cecb1c;counts={"depth": 7, "fills": 277, "gradients": 2, "groups": 29, "nodes": 903, "segments": 3225, "shapes": 874, "strokes": 540, "subpaths": 881};boards=[];fonts={};warnings=["blur effects (left out) (244×)", "brush and pressure strokes (imported as plain strokes) (534×)"]
+affinity3-mexican-woman.af dpi=300;spreads=1;model_crc32=23d1e39c;counts={"depth": 9, "fills": 527, "gradients": 0, "groups": 28, "nodes": 595, "segments": 3562, "shapes": 567, "strokes": 60, "subpaths": 570};boards=[];fonts={};warnings=["blur effects (left out) (278×)", "brush and pressure strokes (imported as plain strokes) (54×)"]
+affinity3-playing-cards.af dpi=300;spreads=1;model_crc32=cafb7572;counts={"depth": 5, "fills": 363, "gradients": 0, "groups": 758, "nodes": 1350, "segments": 4864, "shapes": 592, "strokes": 17, "subpaths": 656};boards=[];fonts={};warnings=["blur effects (left out) (309×)", "brush and pressure strokes (imported as plain strokes)"]
+patchy-adjust-curves.af dpi=72;spreads=1;model_crc32=36ab962f;counts={"depth": 1, "images": 1, "nodes": 2, "unsupported": 1};boards=[];fonts={};warnings=["adjustment layers"]
+patchy-adjust-hsl.af dpi=72;spreads=1;model_crc32=e2eac05e;counts={"depth": 1, "images": 1, "nodes": 2, "unsupported": 1};boards=[];fonts={};warnings=["adjustment layers"]
+patchy-artboards.af dpi=72;spreads=1;model_crc32=0037a28e;counts={"artboards": 2, "depth": 2, "fills": 2, "gradients": 0, "nodes": 4, "segments": 7, "shapes": 2, "strokes": 0, "subpaths": 2};boards=["board-a:0.0000,0.0000,80.0000,60.0000", "board-b:100.0000,10.0000,160.0000,70.0000"];fonts={};warnings=[]
+patchy-blend-affinity.af dpi=72;spreads=1;model_crc32=8497c917;counts={"depth": 2, "fills": 8, "gradients": 0, "images": 1, "layers": 1, "nodes": 10, "segments": 24, "shapes": 8, "strokes": 0, "subpaths": 8};boards=[];fonts={};warnings=["an unknown blend mode (imported as Normal) (2×)"]
+patchy-cmyk.af dpi=72;spreads=1;model_crc32=56754ce9;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
+patchy-dpi300.af dpi=300;spreads=1;model_crc32=2561f9d3;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
+patchy-embedded-jpeg.af dpi=72;spreads=1;model_crc32=ab4b6fbf;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
+patchy-fx-blur.af dpi=72;spreads=1;model_crc32=29b5083b;counts={"depth": 1, "images": 2, "nodes": 2};boards=[];fonts={};warnings=["blur effects (left out) (2×)"]
+patchy-fx-gradient.af dpi=72;spreads=1;model_crc32=96cd10be;counts={"depth": 1, "images": 3, "nodes": 3};boards=[];fonts={};warnings=[]
+patchy-fx.af dpi=72;spreads=1;model_crc32=7c8d4d20;counts={"depth": 1, "images": 5, "nodes": 5};boards=[];fonts={};warnings=[]
+patchy-group.af dpi=72;spreads=1;model_crc32=dc37ab6c;counts={"depth": 2, "images": 3, "layers": 1, "nodes": 4};boards=[];fonts={};warnings=[]
+patchy-incremental-chain.af dpi=72;spreads=1;model_crc32=38c9c5f4;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
+patchy-lab.af dpi=72;spreads=1;model_crc32=df3a4e40;counts={"depth": 1, "nodes": 1, "unsupported": 1};boards=[];fonts={};warnings=["pixel layers in grey, Lab or 32-bit formats"]
+patchy-lazy-placed.af dpi=72;spreads=1;model_crc32=8776a8a0;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
+patchy-live-filter.af dpi=72;spreads=1;model_crc32=12235fe9;counts={"depth": 2, "fills": 2, "gradients": 0, "nodes": 4, "segments": 6, "shapes": 2, "strokes": 0, "subpaths": 2, "unsupported": 2};boards=[];fonts={};warnings=["adjustment layers", "unknown layers"]
+patchy-rgba16.af dpi=72;spreads=1;model_crc32=688b2475;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
+patchy-rgba8.af dpi=72;spreads=1;model_crc32=688b2475;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
+patchy-shapes-2.af dpi=72;spreads=1;model_crc32=886e9852;counts={"depth": 1, "fills": 12, "gradients": 0, "nodes": 12, "segments": 62, "shapes": 12, "strokes": 0, "subpaths": 12};boards=[];fonts={};warnings=["cloud, heart, cog, callout, arrow, tear and other special shapes (imported as their bounding ellipse) (9×)"]
+patchy-shapes.af dpi=72;spreads=1;model_crc32=c1790e97;counts={"depth": 1, "fills": 4, "gradients": 0, "nodes": 4, "segments": 28, "shapes": 4, "strokes": 0, "subpaths": 4};boards=[];fonts={};warnings=[]
+patchy-text-artistic.af dpi=72;spreads=1;model_crc32=1d33192c;counts={"depth": 1, "nodes": 1, "text_chars": 5, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialMT:400:false"};warnings=[]
+patchy-text-caps.af dpi=72;spreads=1;model_crc32=24e52518;counts={"depth": 1, "nodes": 2, "text_chars": 21, "text_runs": 2, "texts": 2};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font) (2×)"]
+patchy-text-frame.af dpi=72;spreads=1;model_crc32=3bff8ef9;counts={"depth": 1, "nodes": 1, "text_chars": 11, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialMT:400:false"};warnings=[]
+patchy-text-indent.af dpi=72;spreads=1;model_crc32=dc36dfc5;counts={"depth": 1, "nodes": 2, "text_chars": 104, "text_runs": 2, "texts": 2};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font) (2×)"]
+patchy-text-para-spacing.af dpi=72;spreads=1;model_crc32=6408f39b;counts={"depth": 1, "nodes": 1, "text_chars": 13, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font)"]
+patchy-text-rotated.af dpi=72;spreads=1;model_crc32=3d1de559;counts={"depth": 1, "nodes": 1, "text_chars": 7, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font)"]
+patchy-text-runs.af dpi=72;spreads=1;model_crc32=7820b881;counts={"depth": 1, "nodes": 1, "text_chars": 7, "text_runs": 5, "texts": 1};boards=[];fonts={"Arial:ArialNarrow:400:false", "Courier New:CourierNewPSMT:400:false", "Segoe UI Emoji:SegoeUIEmoji:400:false", "Times New Roman:TimesNewRomanPSMT:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font)", "text uses a stored fallback font (imported with that font)"]
+patchy-transform.af dpi=72;spreads=1;model_crc32=8d56df84;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
+patchy-vector-mask.af dpi=72;spreads=1;model_crc32=80ca946a;counts={"depth": 1, "fills": 2, "gradients": 0, "nodes": 2, "segments": 7, "shapes": 2, "strokes": 0, "subpaths": 2, "vector_masks": 1};boards=[];fonts={};warnings=["unknown layers attached to other layers (imported without them)"]
+patchy-vector.af dpi=72;spreads=1;model_crc32=b36a9767;counts={"depth": 1, "fills": 3, "gradients": 0, "nodes": 4, "segments": 17, "shapes": 4, "strokes": 2, "subpaths": 5};boards=[];fonts={};warnings=[]
diff --git a/crates/affinity/tests/support/features.rs b/crates/affinity/tests/support/features.rs
index 31d3eb53fe..f7024feb62 100644
--- a/crates/affinity/tests/support/features.rs
+++ b/crates/affinity/tests/support/features.rs
@@ -35,7 +35,12 @@ pub fn signature(doc: &Document) -> String {
}
"texts"
}
+ Kind::Table(t) => {
+ *counts.entry("table_cells").or_default() += t.cells.len();
+ "tables"
+ }
Kind::Image(_) => "images",
+ Kind::MasterInstance { .. } => "master_instances",
Kind::Unsupported => "unsupported",
};
*counts.entry(key).or_default() += 1;
diff --git a/crates/affinity/tests/support/text_fixture.rs b/crates/affinity/tests/support/text_fixture.rs
index d629253d3c..574a0ca38a 100644
--- a/crates/affinity/tests/support/text_fixture.rs
+++ b/crates/affinity/tests/support/text_fixture.rs
@@ -140,7 +140,7 @@ pub const IDENTITY: [f64; 6] = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0];
// Shared arrays require definitions/references, whereas inline fields use Obj. Give the original
// fixture objects independent shared IDs without making the fixture descriptions noisy.
-fn shared_objects(value: &mut F, next_id: &mut u32) {
+pub fn shared_objects(value: &mut F, next_id: &mut u32) {
match value {
F::Shared(items) => {
for item in items {
diff --git a/crates/affinity/tests/text.rs b/crates/affinity/tests/text.rs
index 8d6a203e51..db984652b5 100644
--- a/crates/affinity/tests/text.rs
+++ b/crates/affinity/tests/text.rs
@@ -11,7 +11,7 @@ mod support {
use support::text_fixture::*;
use vectorcraft_affinity::{
Document, Limits,
- model::{Align, Kind, Text},
+ model::{Align, Kind, Paragraph, Text},
paint::{Color, Paint},
synth::{F, tag},
};
@@ -108,7 +108,7 @@ fn mixed_paragraph_alignments_are_explicitly_reported() {
let d = read(vec![block(utf8("one\u{2029}"), vec![run(4, None)], &[2]), block(utf8("two"), vec![run(3, None)], &[0, 1])]);
assert_eq!(content(text(&d)), "one\u{2029}two");
assert_eq!(text(&d).align, Align::Right);
- assert!(warning(&d, "mixed paragraph alignments"));
+ assert!(warning(&d, "mixed paragraph formats"));
}
#[test]
@@ -194,10 +194,22 @@ fn real_affinity3_text_fixtures_confirm_unicode_and_caps_fields() {
assert_eq!(texts.len(), 2);
assert!(texts[0].runs[0].all_caps);
assert_eq!(texts[1].runs[0].features, ["smcp"]);
- for name in ["patchy-text-indent.af", "patchy-text-para-spacing.af"] {
+ // Indents and paragraph spacing are read (values in document pixels, as these fixtures set
+ // them in Affinity's paragraph panel).
+ let paragraphs = |name: &str| -> Vec {
let d = load(name);
- assert!(warning(&d, "paragraph indents or spacing"), "{name}: {:?}", d.warnings);
- }
+ assert!(!warning(&d, "paragraph"), "{name}: {:?}", d.warnings);
+ d.spreads[0]
+ .nodes
+ .iter()
+ .filter_map(|n| if let Kind::Text(t) = &n.kind { Some(t) } else { None })
+ .flat_map(|t| t.runs.iter().map(|r| r.paragraph))
+ .collect()
+ };
+ let p = paragraphs("patchy-text-indent.af");
+ assert_eq!(p.iter().map(|p| (p.left, p.first, p.space_after)).collect::>(), [(40.0, 0.0, 12.0), (0.0, 25.0, 12.0)]);
+ let p = paragraphs("patchy-text-para-spacing.af");
+ assert_eq!(p.iter().map(|p| (p.space_before, p.space_after)).collect::>(), [(9.0, 17.0)]);
}
proptest::proptest! {
@@ -247,9 +259,19 @@ fn excessive_feature_settings_are_bounded_and_reported() {
assert!(warning(&d, "more than 256 text feature settings"));
}
+#[test]
+fn font_names_longer_than_256_bytes_are_dropped() {
+ // Each paragraph and run carries its font's name: a huge one would be copied with each.
+ let d = read(vec![block(utf8("x"), vec![run(1, Some(attrs(&"F".repeat(257), "Inter-Regular", 400, false, 12.0)))], &[])]);
+ let r = &text(&d).runs[0];
+ assert!(r.family.is_empty() && r.postscript == "Inter-Regular");
+ assert!(warning(&d, "font names longer than 256 bytes"));
+}
+
#[test]
fn shared_font_metadata_amplification_is_bounded_without_losing_characters() {
- let mut a = attrs(&"F".repeat(16 * 1024), &"P".repeat(16 * 1024), 400, false, 12.0);
+ // The longest font names kept (see `font_names_longer_than_256_bytes_are_dropped`).
+ let mut a = attrs(&"F".repeat(256), &"P".repeat(256), 400, false, 12.0);
if let F::Obj(_, fields) = &mut a {
let settings = F::Obj(
tag(b"OtAt"),
@@ -266,11 +288,12 @@ fn shared_font_metadata_amplification_is_bounded_without_losing_characters() {
}
let F::Obj(class, fields) = a else { panic!("attributes must be an object") };
let mut runs = vec![run(1, Some(F::Def(42, vec![class], fields)))];
- runs.extend((2..=1000).map(|end| run(end, Some(F::Ref(42)))));
- let d = read(vec![block(utf8(&"x".repeat(1000)), runs, &[])]);
+ // About 7.7 kB of names and features per run: the budget runs out after about 2200 runs.
+ runs.extend((2..=4000).map(|end| run(end, Some(F::Ref(42)))));
+ let d = read(vec![block(utf8(&"x".repeat(4000)), runs, &[])]);
let t = text(&d);
- assert_eq!(content(t), "x".repeat(1000));
- assert_eq!(t.runs.len(), 1000);
+ assert_eq!(content(t), "x".repeat(4000));
+ assert_eq!(t.runs.len(), 4000);
let metadata: usize = t
.runs
.iter()
@@ -279,7 +302,7 @@ fn shared_font_metadata_amplification_is_bounded_without_losing_characters() {
.map(|s| s.len() + std::mem::size_of::())
.sum();
assert!(metadata <= 16 << 20, "shared metadata was amplified to {metadata} bytes");
- assert_eq!(t.runs[0].family.len(), 16 * 1024);
+ assert_eq!(t.runs[0].family.len(), 256);
assert_eq!(t.runs[0].features.len(), 256);
assert!(t.runs.last().unwrap().family.is_empty());
assert!(t.runs.last().unwrap().features.is_empty());
@@ -320,3 +343,39 @@ fn shared_gradient_attributes_are_bounded_without_losing_characters() {
assert!(warning(&d, "text attribute budget exceeded"));
assert!(!warning(&d, "text without character attributes"), "budget recovery must not claim source attributes are absent");
}
+
+#[test]
+fn shared_gradient_outlines_are_bounded_without_losing_characters() {
+ let color =
+ F::Def(43, vec![tag(b"RGBA")], vec![(tag(b"_col"), F::Struct([0.2f32, 0.4, 0.6, 1.0].iter().flat_map(|v| v.to_le_bytes()).collect()))]);
+ let mut colors = vec![color];
+ colors.extend((1..1024).map(|_| F::Ref(43)));
+ let positions = (0..1024).map(|i| [(i as f32) / 1023.0, 0.5].iter().flat_map(|v| v.to_le_bytes()).collect()).collect();
+ let pen = F::Obj(
+ tag(b"FilG"),
+ vec![(tag(b"Grad"), F::Obj(tag(b"Grad"), vec![(tag(b"Cols"), F::Shared(colors)), (tag(b"Posn"), F::Records(8, positions))]))],
+ );
+ let style = F::Obj(tag(b"LSty"), vec![(tag(b"Wght"), F::F64(2.0))]);
+ // `Objs` 1 and 2: the outline's paint and line style, shared by every run.
+ let attrs = F::Def(42, vec![tag(b"GAtt")], vec![(tag(b"Objs"), F::Shared(vec![solid(1.0), pen, style]))]);
+ let mut runs = vec![run(1, Some(attrs))];
+ runs.extend((2..=1000).map(|end| run(end, Some(F::Ref(42)))));
+ let d = read(vec![block(utf8(&"x".repeat(1000)), runs, &[])]);
+ let t = text(&d);
+ assert_eq!(content(t), "x".repeat(1000));
+ assert_eq!(t.runs.len(), 1000);
+ let stop_count: usize = t
+ .runs
+ .iter()
+ .filter_map(|r| r.stroke.as_ref())
+ .map(|s| match &s.paint {
+ Paint::Gradient(g) => g.stops.len(),
+ _ => 0,
+ })
+ .sum();
+ assert!(stop_count * std::mem::size_of::() <= 16 << 20);
+ let Some(Paint::Gradient(first)) = t.runs[0].stroke.as_ref().map(|s| &s.paint) else { panic!("the first outline must fit") };
+ assert_eq!(first.stops.len(), 1024);
+ assert!(t.runs.last().unwrap().stroke.is_none());
+ assert!(warning(&d, "text attribute budget exceeded"));
+}
diff --git a/crates/brush/src/tests.rs b/crates/brush/src/tests.rs
index 1a7dc61ff5..8c04e102bd 100644
--- a/crates/brush/src/tests.rs
+++ b/crates/brush/src/tests.rs
@@ -687,3 +687,81 @@ fn pieces_leave_out_what_draws_a_brushed_stroke_by_name() {
assert_eq!(fills, [Paint::Pattern { pattern: "plain".into(), xf: vectorcraft_geom::Affine::IDENTITY }, Paint::None]);
}
}
+
+/// Anchors a brushed stroke emitted, which is what the output budget counts.
+fn anchors(nodes: &[Node]) -> usize {
+ nodes
+ .iter()
+ .map(|n| match &n.kind {
+ NodeKind::Path { path, .. } => path.subpaths.iter().map(|s| s.anchors.len()).sum::(),
+ _ => 0,
+ })
+ .sum()
+}
+
+/// A path of `subpaths` long parallel lines, each long enough to want more tiles than the
+/// per-run cap allows.
+fn many_long_subpaths(subpaths: usize) -> BezPath {
+ let mut bp = BezPath::new();
+ for i in 0..subpaths {
+ let y = i as f64 * 50.0;
+ bp.move_to((0.0, y));
+ bp.line_to((300_000.0, y));
+ }
+ bp
+}
+
+/// #3594: the per-factor caps are per track, and a path has as many tracks as it has subpaths,
+/// so they multiply instead of bounding. Measured before the budget: 20,000 nodes and 320,000
+/// anchors for one subpath, and exactly N times that for N, so sixteen gave 5,120,000.
+#[test]
+fn pattern_output_is_capped_across_subpaths_not_only_per_run() {
+ let brush = pattern_brush(PatternFit::Stretch, false);
+ let one = stroke_pieces(&Document::new(1.0, 1.0), &brush, &many_long_subpaths(1), &stroke(1.0));
+ assert_eq!(one.len(), 20_000, "one track still fills its own per-run cap");
+ let a1 = anchors(&one);
+ assert!(a1 < 2_000_000, "one track stays under the total budget: {a1}");
+
+ // Sixteen tracks would be sixteen times that without a total budget.
+ // Four tracks are 4 x 320,000 anchors, still inside the budget, so nothing is cut: the
+ // budget must not bite before the per-factor caps have actually multiplied past it.
+ let four = stroke_pieces(&Document::new(1.0, 1.0), &brush, &many_long_subpaths(4), &stroke(1.0));
+ assert_eq!(four.len(), 4 * 20_000, "four tracks are under the budget and keep every piece");
+ assert_eq!(anchors(&four), 4 * a1);
+
+ // Sixteen would be 5,120,000 anchors. The budget is what stops it, not the per-run caps.
+ let many = stroke_pieces(&Document::new(1.0, 1.0), &brush, &many_long_subpaths(16), &stroke(1.0));
+ let an = anchors(&many);
+ assert!(an <= 2_000_000, "sixteen subpaths must not exceed the budget: {an}");
+ assert!(an > anchors(&four), "but more is drawn than four tracks' worth: {an}");
+ assert!(many.len() < 16 * 20_000, "and fewer pieces than the per-run caps alone would allow: {}", many.len());
+}
+
+/// The same for scatter, whose per-track guard is also 20,000 copies.
+#[test]
+fn scatter_output_is_capped_across_subpaths() {
+ let b = Brush {
+ name: "s".into(),
+ kind: BrushKind::Scatter(Scatter { art: rect_art(4.0, 4.0), colorization: Colorization::None, ..Default::default() }),
+ };
+ let few = stroke_pieces(&Document::new(1.0, 1.0), &b, &many_long_subpaths(1), &stroke(1.0));
+ let per_track = anchors(&few);
+ assert!(per_track > 0, "one track draws something");
+ // Enough tracks that the per-track guards alone would pass the budget.
+ let tracks = 2_000_000 / per_track + 4;
+ let many = stroke_pieces(&Document::new(1.0, 1.0), &b, &many_long_subpaths(tracks), &stroke(1.0));
+ let an = anchors(&many);
+ assert!(an <= 2_000_000, "{tracks} tracks must not exceed the budget: {an}");
+ assert!(an > per_track, "but more is drawn than one track's worth: {an}");
+ assert!(many.len() < tracks * few.len().max(1), "fewer copies than the per-track guards alone would allow");
+}
+
+/// A short, ordinary stroke is untouched by the budget: it is the absurd ones that are cut.
+#[test]
+fn an_ordinary_stroke_is_unaffected_by_the_budget() {
+ let brush = pattern_brush(PatternFit::Stretch, false);
+ let sq = shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)).to_bezpath();
+ let out = stroke_pieces(&Document::new(1.0, 1.0), &brush, &sq, &stroke(1.0));
+ assert_eq!(out.len(), 40, "ten tiles on each of the four sides, as before the budget");
+ assert!(anchors(&out) < 2_000_000);
+}
diff --git a/crates/brush/src/warp.rs b/crates/brush/src/warp.rs
index 35031741e1..9d61216a19 100644
--- a/crates/brush/src/warp.rs
+++ b/crates/brush/src/warp.rs
@@ -16,6 +16,21 @@ use crate::{ArtBrush, ArtScale, Direction, PatternBrush, PatternFit, Scatter, Va
const MAX_SEG: f64 = 1.5;
/// Hard cap on subdivisions per art segment.
const MAX_SUB: usize = 4000;
+/// Anchors one brushed stroke may emit in total, across every track, tile and copy.
+///
+/// Each factor is capped on its own (20,000 tiles a run, [`MAX_SUB`] subdivisions a segment,
+/// 20,000 copies a track), but those caps are per track and a path has as many tracks as it has
+/// subpaths, so they multiply rather than bound: one track at its cap measures 20,000 nodes and
+/// 320,000 anchors, and sixteen subpaths measure exactly sixteen times that (#3594). This is the
+/// cap on the product. The per-factor caps still shape each one.
+///
+/// The same figure as the stacked-effects budget (`effects::distort::MAX_COPY_ANCHORS`, #3578),
+/// and bounded the same way: per brushed stroke rather than per document, so many strokes that
+/// each reach it still add up. Six times what one track at its own cap draws, so it bites only
+/// where the caps were multiplying.
+const MAX_ANCHORS: usize = 2_000_000;
+/// Nodes [`anchors_of`] walks into before it gives up and charges the whole budget.
+const MAX_WALK: usize = 10_000;
/// Bend every path under `n` through `f`. Paths are flattened with `flat_tol` (art space) and
/// segments subdivided so none is longer than `max_du` along x. Stroke widths scale by
@@ -235,8 +250,11 @@ pub(crate) fn scatter(sc: &Scatter, bp: &BezPath, weight: f64, pressure: Option<
let (aw, ah) = (b.width().max(1e-3), b.height().max(1e-3));
let mut rng = Rng::new(seed_of(bp, name));
let [size_mode, spacing_mode, scatter_mode, rotation_mode] = sc.modes();
- let mut out = vec![];
+ let mut out = Budget::default();
for t in tracks(bp, 0.05) {
+ if out.full() {
+ break;
+ }
let l = t.len();
// The pen pressure at arc length `at` (half way without a recorded one).
let pressure_at = |at: f64| pressure.map_or(PressureProfile::MID, |p| p.at(if l > 1e-9 { at / l } else { 0.0 }));
@@ -270,10 +288,61 @@ pub(crate) fn scatter(sc: &Scatter, bp: &BezPath, weight: f64, pressure: Option<
let xf = Affine::translate(place.to_vec2()) * Affine::rotate(base - rot) * Affine::scale(size) * Affine::translate(-b.center().to_vec2());
let mut n = sc.art.clone();
n.transform(xf, true);
- out.push(n);
+ out.take(Some(n));
+ if out.full() {
+ break;
+ }
}
}
- out
+ out.out
+}
+
+/// Anchors `n` and its children hold. Walked with a stack rather than by recursion, and a tree
+/// deeper or wider than [`MAX_WALK`] nodes is charged the whole budget rather than undercounted,
+/// so an art tile cannot buy room by nesting.
+fn anchors_of(n: &Node) -> usize {
+ let (mut total, mut seen) = (0usize, 0usize);
+ let mut stack = vec![n];
+ while let Some(n) = stack.pop() {
+ seen += 1;
+ if seen > MAX_WALK {
+ return MAX_ANCHORS;
+ }
+ if let NodeKind::Path { path, .. } = &n.kind {
+ total = total.saturating_add(path.subpaths.iter().map(|s| s.anchors.len()).sum::());
+ }
+ if let Some(c) = n.children() {
+ stack.extend(c.iter().map(Arc::as_ref));
+ }
+ }
+ total
+}
+
+/// Brush output collected under [`MAX_ANCHORS`].
+///
+/// A piece is taken whole or not at all, so the art a brush places is never half-drawn; the
+/// total is therefore the budget plus at most one piece.
+#[derive(Default)]
+struct Budget {
+ out: Vec,
+ anchors: usize,
+}
+
+impl Budget {
+ /// Take a piece if there is room. `None` (art that could not be placed) costs nothing.
+ fn take(&mut self, n: Option) {
+ let Some(n) = n else { return };
+ if self.full() {
+ return;
+ }
+ self.anchors = self.anchors.saturating_add(anchors_of(&n));
+ self.out.push(n);
+ }
+
+ /// Whether the budget is spent, so the caller can stop walking the path.
+ fn full(&self) -> bool {
+ self.anchors >= MAX_ANCHORS
+ }
}
/// A tile placed on [s0, s1] of the track (stretched along, `cross` across).
@@ -291,8 +360,11 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec
let end = pb.end.as_ref().and_then(orient);
let tw = side.1.width() * k;
let gap = tw * pb.spacing.max(0.0) / 100.0;
- let mut out = vec![];
+ let mut out = Budget::default();
for t in tracks(bp, 0.05) {
+ if out.full() {
+ break;
+ }
let l = t.len();
if l <= 1e-9 {
continue;
@@ -314,7 +386,7 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec
* Affine::translate(-bb.center().to_vec2());
let mut n = art.clone();
n.transform(xf, true);
- out.push(n);
+ out.take(Some(n));
}
// Runs between corners (closed tracks wrap past the end).
let mut bounds: Vec = corners.iter().map(|c| c.1).collect();
@@ -346,7 +418,7 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec
{
let w = st.1.width() * k;
if b - a > w {
- out.extend(tile_on(&t, st, a, a + w, k));
+ out.take(tile_on(&t, st, a, a + w, k));
a += w;
}
}
@@ -356,7 +428,7 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec
{
let w = en.1.width() * k;
if b - a > w {
- out.extend(tile_on(&t, en, b - w, b, k));
+ out.take(tile_on(&t, en, b - w, b, k));
b -= w;
}
}
@@ -372,7 +444,10 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec
let (w, g) = (tw * f, gap * f);
for i in 0..n.min(20000) {
let s0 = a + i as f64 * (w + g);
- out.extend(tile_on(&t, &side, s0, s0 + w, k));
+ out.take(tile_on(&t, &side, s0, s0 + w, k));
+ if out.full() {
+ break;
+ }
}
}
PatternFit::AddSpace => {
@@ -381,7 +456,10 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec
let lead = if n == 1 { (avail - tw) / 2.0 } else { 0.0 };
for i in 0..n.min(20000) {
let s0 = a + lead + i as f64 * (tw + g.max(0.0));
- out.extend(tile_on(&t, &side, s0, s0 + tw, k));
+ out.take(tile_on(&t, &side, s0, s0 + tw, k));
+ if out.full() {
+ break;
+ }
}
}
PatternFit::Approximate => {
@@ -390,11 +468,14 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec
let lead = (avail - used) / 2.0;
for i in 0..n.min(20000) {
let s0 = a + lead + i as f64 * unit;
- out.extend(tile_on(&t, &side, s0, s0 + tw, k));
+ out.take(tile_on(&t, &side, s0, s0 + tw, k));
+ if out.full() {
+ break;
+ }
}
}
}
}
}
- out
+ out.out
}
diff --git a/crates/cad/src/import/build.rs b/crates/cad/src/import/build.rs
index b729d8000e..ff2e84bb82 100644
--- a/crates/cad/src/import/build.rs
+++ b/crates/cad/src/import/build.rs
@@ -3,7 +3,7 @@
//! dimensions, as groups), and colours, lineweights, linetypes and transparency resolved through
//! layers and blocks.
-use std::collections::HashMap;
+use std::collections::{HashMap, HashSet};
use std::rc::Rc;
use std::sync::Arc;
@@ -52,6 +52,9 @@ pub(crate) struct Build<'d, 'a> {
sensitive: HashMap,
/// Symbol names by block and what it inherits (`None`: the block has no art).
symbols: HashMap<(String, Inherit), Option>,
+ /// Names of the symbols made so far, and the next suffix to try for each label.
+ symbol_names: HashSet,
+ next_suffix: HashMap,
/// Blocks being drawn, outermost first.
stack: Vec,
/// Document space per drawing unit, and its symbols' (no translation).
@@ -108,6 +111,8 @@ impl<'d, 'a> Build<'d, 'a> {
bounds: HashMap::new(),
sensitive: HashMap::new(),
symbols: HashMap::new(),
+ symbol_names: HashSet::new(),
+ next_suffix: HashMap::new(),
stack: vec![],
map: Affine::IDENTITY,
symbol_map: Affine::IDENTITY,
@@ -584,7 +589,8 @@ impl<'d, 'a> Build<'d, 'a> {
let art = self.art(name, map, &key.1, depth);
let made = art.map(|art| {
let label = self.d.blocks.get(name).map_or(name, |b| b.name.as_str());
- let symbol = unique(label, |n| self.doc.symbols.iter().any(|s| s.name == n));
+ let symbol = unique(label, &mut self.next_suffix, &self.symbol_names);
+ self.symbol_names.insert(symbol.clone());
self.doc.symbols.push(Symbol { name: symbol.clone(), art: Arc::new(art) });
symbol
});
@@ -611,10 +617,17 @@ fn rgb_color([r, g, b]: [u8; 3]) -> Color {
Color::rgb8(r, g, b)
}
-/// `base`, or `base 2`, `base 3`… when taken.
-fn unique(base: &str, taken: impl Fn(&str) -> bool) -> String {
- if !taken(base) {
+/// `base`, or `base 2`, `base 3`… when taken; `next` remembers where each base left off.
+fn unique(base: &str, next: &mut HashMap, taken: &HashSet) -> String {
+ if !taken.contains(base) {
return base.to_string();
}
- (2..).map(|i| format!("{base} {i}")).find(|n| !taken(n)).unwrap_or_else(|| base.to_string())
+ let i = next.entry(base.to_string()).or_insert(2);
+ loop {
+ let name = format!("{base} {i}");
+ *i += 1;
+ if !taken.contains(&name) {
+ return name;
+ }
+ }
}
diff --git a/crates/cad/src/import/curve.rs b/crates/cad/src/import/curve.rs
index c913a8bd61..a348ce67ab 100644
--- a/crates/cad/src/import/curve.rs
+++ b/crates/cad/src/import/curve.rs
@@ -17,6 +17,8 @@ const MAX_DEPTH: u32 = 12;
const MAX_ELEMENTS: usize = 200_000;
/// The highest spline degree read.
const MAX_DEGREE: usize = 11;
+/// Spline weights below this fraction of the largest are read as this fraction.
+const MIN_RELATIVE_WEIGHT: f64 = 1e-100;
/// A polyline vertex: its point and the bulge of the segment that starts there (the tangent of a
/// quarter of the arc's angle; positive turns counter-clockwise).
@@ -121,7 +123,9 @@ struct H {
impl H {
fn lerp(self, o: Self, t: f64) -> Self {
- Self { x: self.x + (o.x - self.x) * t, y: self.y + (o.y - self.y) * t, w: self.w + (o.w - self.w) * t }
+ // Exact at both ends, so a weight far smaller than its neighbour's doesn't cancel to 0.
+ let s = 1.0 - t;
+ Self { x: self.x * s + o.x * t, y: self.y * s + o.y * t, w: self.w * s + o.w * t }
}
fn point(self) -> Option {
(self.w.abs() > 1e-300).then(|| Point::new(self.x / self.w, self.y / self.w)).filter(|p| p.x.is_finite() && p.y.is_finite())
@@ -139,7 +143,11 @@ pub(crate) fn nurbs(degree: usize, knots: &[f64], ctrl: &[Point], weights: Optio
if knots.windows(2).any(|w| w[1] < w[0]) {
return None;
}
- let weight = |i: usize| weights.and_then(|w| w.get(i)).copied().filter(|w| *w > 0.0 && w.is_finite()).unwrap_or(1.0);
+ let raw = |i: usize| weights.and_then(|w| w.get(i)).copied().filter(|w| *w > 0.0 && w.is_finite()).unwrap_or(1.0);
+ // Scaling all weights alike leaves the curve unchanged: relative to the largest, so tiny ones
+ // don't underflow, and floored so a weight tiny next to the others can't either.
+ let max_w = (0..n).map(raw).fold(0.0, f64::max);
+ let weight = |i: usize| (raw(i) / max_w).max(MIN_RELATIVE_WEIGHT);
let hs: Vec = ctrl.iter().enumerate().map(|(i, p)| H { x: p.x * weight(i), y: p.y * weight(i), w: weight(i) }).collect();
let rational = (0..n).any(|i| (weight(i) - weight(0)).abs() > 1e-12);
let (lo, hi) = ctrl.iter().fold((Point::new(f64::MAX, f64::MAX), Point::new(f64::MIN, f64::MIN)), |(lo, hi), p| {
@@ -225,6 +233,11 @@ fn fit(bp: &mut BezPath, bez: &[H], t0: f64, t1: f64, tol: f64, depth: u32) -> O
let (p3, d3) = eval(bez, t1)?;
let h = (t1 - t0) / 3.0;
let (c1, c2) = (p0 + d0 * h, p3 - d3 * h);
+ // Non-finite tangents never fit, so splitting wouldn't help: a line.
+ if ![c1, c2].iter().all(|p| p.x.is_finite() && p.y.is_finite()) {
+ bp.line_to(p3);
+ return Some(());
+ }
let cubic = kurbo::CubicBez::new(p0, c1, c2, p3);
let close = (1..8).all(|i| {
let s = f64::from(i) / 8.0;
@@ -371,6 +384,21 @@ mod tests {
}
}
+ #[test]
+ fn tiny_spline_weights_flatten_to_a_handful_of_pieces() {
+ // Degree 5, three knot spans: fitted, not exact.
+ let ctrl: Vec = (0..8).map(|i| Point::new(f64::from(i) * 10.0, if i % 2 == 0 { 0.0 } else { 30.0 })).collect();
+ let knots = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 2.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0];
+ let normal = nurbs(5, &knots, &ctrl, Some(&[1.0; 8])).unwrap().elements().len();
+ // Scaling every weight alike leaves the curve as it is.
+ let tiny = nurbs(5, &knots, &ctrl, Some(&[1e-200; 8])).unwrap().elements().len();
+ assert!(tiny <= normal + 8, "normal weights: {normal} elements, 1e-200 weights: {tiny} elements");
+ // Weights tiny next to the others don't split every span to the limit either.
+ let mixed = [1.0, 1e-200, 1.0, 1e-200, 1.0, 1e-200, 1.0, 1e-200];
+ let mixed = nurbs(5, &knots, &ctrl, Some(&mixed)).unwrap().elements().len();
+ assert!(mixed < 500, "mixed weights: {mixed} elements");
+ }
+
#[test]
fn fit_points_make_a_smooth_curve_through_them() {
let pts = [Point::new(0.0, 0.0), Point::new(10.0, 10.0), Point::new(20.0, 0.0)];
diff --git a/crates/cad/src/import/entity.rs b/crates/cad/src/import/entity.rs
index d11d6a35cc..f24f05596d 100644
--- a/crates/cad/src/import/entity.rs
+++ b/crates/cad/src/import/entity.rs
@@ -536,7 +536,9 @@ fn boundary(c: &mut Cursor<'_, '_>) -> Option {
// The boundary objects it was made from.
if let Some(n) = c.count(97) {
for _ in 0..n {
- c.opt(330);
+ if c.opt(330).is_none() {
+ break;
+ }
}
}
Some(bp)
diff --git a/crates/cad/src/import/tests.rs b/crates/cad/src/import/tests.rs
index 895b702262..4845e8d2a2 100644
--- a/crates/cad/src/import/tests.rs
+++ b/crates/cad/src/import/tests.rs
@@ -380,6 +380,27 @@ fn solid_hatches_fill_and_pattern_hatches_outline() {
assert!(square.appearance.fill().is_some_and(|f| !f.paint.is_none()));
}
+#[test]
+fn hatch_declaring_many_absent_source_handles_parses_quickly() {
+ let base = hatch("1");
+ let at = |code: i32, from: usize| from + base[from..].iter().position(|p| p.0 == code).unwrap();
+ let first = at(92, 0);
+ let end = at(97, first) + 1;
+ let mut boundary = base[first..end].to_vec();
+ *boundary.last_mut().unwrap() = (97, "10000000");
+ let n = 300;
+ let mut e: Vec<(i32, &'static str)> = base[..first].to_vec();
+ e[at(91, 0)] = (91, "300");
+ for _ in 0..n {
+ e.extend_from_slice(&boundary);
+ }
+ e.extend_from_slice(&base[end..]);
+ let start = std::time::Instant::now();
+ let r = open(&entities(&e), &points());
+ assert!(start.elapsed() < std::time::Duration::from_millis(400), "took {:?}", start.elapsed());
+ assert_eq!(r.document.layers[0].children().unwrap().len(), 1, "{:?}", r.warnings);
+}
+
/// A solid hatch: a loop of a line and a spline edge (`fit` its fit data, if any), followed by
/// `source` (the loop's source-object count and handles), and a square hole.
fn spline_edged_hatch(fit: &[(i32, &'static str)], source: &[(i32, &'static str)]) -> Vec<(i32, &'static str)> {
@@ -712,6 +733,27 @@ fn by_block_colours_make_a_symbol_per_look() {
assert_eq!(doc.symbols.len(), 1);
}
+#[test]
+fn many_by_block_looks_import_in_linear_time() {
+ let by_block: &[(i32, &str)] = &[(0, "LINE"), (8, "0"), (62, "0"), (10, "5"), (20, "5"), (11, "15"), (21, "5")];
+ let n = 4000;
+ let mut inserts: Vec<(i32, &'static str)> = vec![];
+ for i in 0..n {
+ let colour: &'static str = Box::leak((i + 1).to_string().into_boxed_str());
+ inserts.extend([(0, "INSERT"), (2, "Door"), (420, colour), (10, "0"), (20, "0")]);
+ }
+ let text = with_door(by_block, &inserts);
+ let start = std::time::Instant::now();
+ let doc = open(&text, &points()).document;
+ let took = start.elapsed();
+ let mut names: Vec<&str> = doc.symbols.iter().map(|s| s.name.as_str()).collect();
+ assert_eq!(names.len(), n);
+ names.sort_unstable();
+ names.dedup();
+ assert_eq!(names.len(), n, "names stay unique");
+ assert!(took < std::time::Duration::from_secs(4), "import took {took:?}");
+}
+
#[test]
fn array_inserts_attributes_and_dimensions() {
let inserts = [
diff --git a/crates/color/src/gradient.rs b/crates/color/src/gradient.rs
index 1c2b96c6e1..e97ca634aa 100644
--- a/crates/color/src/gradient.rs
+++ b/crates/color/src/gradient.rs
@@ -31,6 +31,75 @@ impl GradientKind {
}
}
+/// How a gradient mixes the colours between its stops (the Gradient panel's Method).
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+pub enum GradientMethod {
+ /// Mixed in display RGB, as gradients always were.
+ #[default]
+ Classic,
+ /// Mixed in a perceptual colour space (OKLab), so the steps look even to the eye: blue to
+ /// yellow passes through a light blue-grey rather than a dull mid grey.
+ Perceptual,
+}
+
+impl GradientMethod {
+ /// Parse a method name (`classic`, `perceptual`; any case).
+ pub fn parse(s: &str) -> Option {
+ [Self::Classic, Self::Perceptual].into_iter().find(|m| m.label().eq_ignore_ascii_case(s))
+ }
+ pub fn label(self) -> &'static str {
+ match self {
+ Self::Classic => "Classic",
+ Self::Perceptual => "Perceptual",
+ }
+ }
+ pub fn is_classic(&self) -> bool {
+ *self == Self::Classic
+ }
+ /// `a` and `b` mixed at `t` (0..1): in display RGB (Classic), or in OKLab (Perceptual: an
+ /// RGB colour between the two).
+ pub fn mix(self, a: &Color, b: &Color, t: f32) -> Color {
+ match self {
+ Self::Classic => Color::lerp(a, b, t),
+ Self::Perceptual => {
+ use crate::libraries::{oklab_to_srgb, srgb_to_oklab};
+ let (p, q, t) = (srgb_to_oklab(a.to_rgb()), srgb_to_oklab(b.to_rgb()), f64::from(t));
+ let [r, g, bl] = oklab_to_srgb(p[0] + (q[0] - p[0]) * t, p[1] + (q[1] - p[1]) * t, p[2] + (q[2] - p[2]) * t);
+ let c = |v: f64| if v.is_finite() { v.clamp(0.0, 1.0) as f32 } else { 0.0 };
+ Color::rgb(c(r), c(g), c(bl))
+ }
+ }
+ }
+}
+
+/// How far (display RGB, 0..1) the straight line between a Perceptual gradient's neighbouring
+/// expanded stops may stray from the perceptual mix: under half a colour level.
+const PERCEPTUAL_TOLERANCE: f32 = 0.4 / 255.0;
+/// Most times each half of a Perceptual gradient's segment (either side of its midpoint) is
+/// halved to keep within [`PERCEPTUAL_TOLERANCE`].
+const PERCEPTUAL_DEPTH: u32 = 10;
+
+/// The mix positions (0..1, after `v0`, before `v1`) between which display RGB mixed linearly
+/// stays within [`PERCEPTUAL_TOLERANCE`] of the perceptual mix of `a` and `b`: the span halved
+/// where a straight line strays, at most [`PERCEPTUAL_DEPTH`] times, in order.
+fn perceptual_steps(a: &Color, b: &Color, (v0, v1): (f32, f32), depth: u32, out: &mut Vec) {
+ let at = |v: f32| GradientMethod::Perceptual.mix(a, b, v).to_rgb();
+ let (c0, c1) = (at(v0), at(v1));
+ let stray = [0.25, 0.5, 0.75]
+ .into_iter()
+ .flat_map(|u: f32| {
+ let c = at(v0 + (v1 - v0) * u);
+ (0..3).map(move |k| (c0[k] + (c1[k] - c0[k]) * u - c[k]).abs())
+ })
+ .fold(0.0, f32::max);
+ if depth < PERCEPTUAL_DEPTH && stray > PERCEPTUAL_TOLERANCE {
+ let m = (v0 + v1) / 2.0;
+ perceptual_steps(a, b, (v0, m), depth + 1, out);
+ out.push(m);
+ perceptual_steps(a, b, (m, v1), depth + 1, out);
+ }
+}
+
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct GradientStop {
/// 0..=1 along the gradient.
@@ -75,19 +144,39 @@ fn half() -> f32 {
pub struct Gradient {
pub kind: GradientKind,
pub stops: Vec,
+ /// Dither: a fill of this gradient is drawn as pixels with fine noise of up to a colour level
+ /// added, which hides the steps (banding) between the levels 8-bit colour has.
+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]
+ pub dither: bool,
+ /// How the colours between the stops are mixed (Classic unless set; written only when not).
+ #[serde(default, skip_serializing_if = "GradientMethod::is_classic")]
+ pub method: GradientMethod,
}
impl Default for Gradient {
/// Illustrator's default "White, Black" gradient.
fn default() -> Self {
- Self { kind: GradientKind::Linear, stops: vec![GradientStop::new(0.0, Color::WHITE), GradientStop::new(1.0, Color::BLACK)] }
+ Self::new(GradientKind::Linear, vec![GradientStop::new(0.0, Color::WHITE), GradientStop::new(1.0, Color::BLACK)])
}
}
impl Gradient {
- /// Colour and opacity at `t` (honours midpoints).
+ /// A gradient of `kind` through `stops`, with the default options.
+ pub fn new(kind: GradientKind, stops: Vec) -> Self {
+ Self { kind, stops, dither: false, method: GradientMethod::Classic }
+ }
+ /// Colour and opacity at `t` (honours midpoints and the method).
pub fn sample(&self, t: f32) -> (Color, f32) {
- self.sample_with(t, Color::lerp)
+ self.sample_with(t, |a, b, v| self.method.mix(a, b, v))
+ }
+ /// [`Self::sample`], a Classic gradient's neighbouring stop colours of one model mixed in it
+ /// (CMYK stays CMYK; [`Color::lerp_keep_model`]) rather than in display RGB, a Perceptual
+ /// gradient's as [`Self::sample`] mixes them.
+ pub fn sample_keep_model(&self, t: f32) -> (Color, f32) {
+ match self.method {
+ GradientMethod::Classic => self.sample_with(t, Color::lerp_keep_model),
+ m => self.sample_with(t, |a, b, v| m.mix(a, b, v)),
+ }
}
/// [`Gradient::sample`] with neighbouring stop colours mixed by `mix` (e.g. in their own colour
/// model rather than display RGB).
@@ -115,20 +204,47 @@ impl Gradient {
None => (Color::BLACK, 1.0),
}
}
- /// Stops expanded so that midpoints are represented as explicit stops (for renderers without midpoints).
+ /// Stops expanded so that midpoints are represented as explicit stops (for renderers without
+ /// midpoints), and a Perceptual gradient's segments as stops on its curve (for renderers that
+ /// mix linearly; within [`PERCEPTUAL_TOLERANCE`] of it).
pub fn expanded_stops(&self) -> Vec<(f32, Color, f32)> {
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).
+ /// on the gradient's own stops and a Perceptual gradient's other in-between stops).
pub fn expanded(&self) -> impl Iterator- )> + '_ {
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 next = self.stops.get(i + 1);
+ let off_centre = (s.midpoint - 0.5).abs() > 1e-3;
+ // Classic: a stop at the midpoint, when it is off-centre.
+ let classic = next.filter(|_| off_centre && self.method.is_classic()).map(|n| {
let t = s.offset + (n.offset - s.offset) * s.midpoint;
let (c, o) = self.sample(t);
(t, c, o, Some(s.midpoint))
});
- std::iter::once((s.offset, s.color, s.opacity, None)).chain(mid)
+ // Perceptual: stops along the mix (`v`) where a straight line would stray from it, the
+ // midpoint (v = ½) among them, placed through the midpoint as [`Self::sample`] maps them.
+ let perceptual = next.filter(|_| !self.method.is_classic()).map(|n| {
+ let mut vs = Vec::new();
+ perceptual_steps(&s.color, &n.color, (0.0, 0.5), 1, &mut vs);
+ vs.push(0.5);
+ perceptual_steps(&s.color, &n.color, (0.5, 1.0), 1, &mut vs);
+ let m = s.midpoint.clamp(0.01, 0.99);
+ vs.into_iter().map(move |v| {
+ let mid = v == 0.5;
+ let u = if mid {
+ s.midpoint
+ } else if v < 0.5 {
+ 2.0 * v * m
+ } else {
+ m + (v - 0.5) * 2.0 * (1.0 - m)
+ };
+ let t = s.offset + (n.offset - s.offset) * u;
+ let o = s.opacity + (n.opacity - s.opacity) * v;
+ (t, self.method.mix(&s.color, &n.color, v), o, (mid && off_centre).then_some(s.midpoint))
+ })
+ });
+ std::iter::once((s.offset, s.color, s.opacity, None)).chain(classic).chain(perceptual.into_iter().flatten())
})
}
/// The same ramp the other way round: the stops in reverse order at mirrored offsets, each
@@ -172,7 +288,7 @@ impl Gradient {
);
}
stops.push(stop(1.0, to));
- Gradient { kind: GradientKind::Linear, stops }
+ Gradient::new(GradientKind::Linear, stops)
}
}
@@ -534,6 +650,117 @@ impl GradientPaint {
f.transform(a);
}
}
+ /// Is this gradient drawn as pixels rather than as a vector gradient when it paints a fill
+ /// (`fill`) or a stroke (SVG and PDF draw such gradients as images): a freeform gradient, a
+ /// dithered fill (dither applies to fills only), or a Perceptual one (its colours don't mix
+ /// linearly between the stops, as SVG's and PDF's gradients do)?
+ pub fn draws_as_pixels(&self, fill: bool) -> bool {
+ self.gradient.kind == GradientKind::Freeform || (fill && self.gradient.dither) || !self.gradient.method.is_classic()
+ }
+ /// A linear or radial gradient placed on box `bounds` as a `cols` × `rows` grid of
+ /// unpremultiplied RGBA8 pixels over `area`, row by row, each sampled at its centre (colours
+ /// as `rgb` gives them, mixed as the renderer mixes them: [`Ramp`]). Dithered and painting a
+ /// fill (`fill`; dither applies to fills only), each colour channel of pixel (column, row) gets
+ /// [`dither_noise`] before it is rounded to a level.
+ pub fn pixels(
+ &self,
+ bounds: Rect,
+ area: Rect,
+ cols: u16,
+ rows: u16,
+ fill: bool,
+ rgb: &dyn Fn(&Color) -> [f32; 3],
+ ) -> impl Iterator
- + use<> {
+ self.pixels_within(bounds, area, cols, rows, [0..cols, 0..rows], fill, rgb)
+ }
+ /// [`Self::pixels`] for the cells in columns `cells[0]` and rows `cells[1]` of the grid only,
+ /// row by row: the same pixels, noise and all, the whole grid has there.
+ #[allow(clippy::too_many_arguments)]
+ pub fn pixels_within(
+ &self,
+ bounds: Rect,
+ area: Rect,
+ cols: u16,
+ rows: u16,
+ cells: [std::ops::Range
; 2],
+ fill: bool,
+ rgb: &dyn Fn(&Color) -> [f32; 3],
+ ) -> impl Iterator- + use<> {
+ let (kind, geom, dither) = (self.gradient.kind, self.resolve(bounds), fill && self.gradient.dither);
+ let ramp = Ramp::new(&self.gradient, rgb);
+ let (cw, ch) = (area.width() / f64::from(cols.max(1)), area.height() / f64::from(rows.max(1)));
+ let (x0, y0) = (area.x0, area.y0);
+ let [across, down] = cells.map(|r| u32::from(r.start)..u32::from(r.end));
+ down.flat_map(move |j| across.clone().map(move |i| (i, j))).map(move |(i, j)| {
+ let p = Point::new(x0 + (f64::from(i) + 0.5) * cw, y0 + (f64::from(j) + 0.5) * ch);
+ let c = ramp.at(geom.param_at(kind, p) as f32);
+ let level = |k: usize| {
+ let noise = if dither { dither_noise(i, j, k as u32) } else { 0.0 };
+ (c[k].clamp(0.0, 1.0) * 255.0 + noise).round().clamp(0.0, 255.0) as u8
+ };
+ [level(0), level(1), level(2), (c[3].clamp(0.0, 1.0) * 255.0).round() as u8]
+ })
+ }
+}
+
+/// A gradient's colours ready to be sampled pixel by pixel, in a colour space of the caller's
+/// (display RGB, or an ink's coverage): its stops, midpoints and a Perceptual gradient's
+/// in-between colours as stops (as [`Gradient::expanded_stops`]), each turned into that space
+/// once, with colour and opacity mixed linearly between them, each on its own (as the renderer's
+/// vector gradients mix them).
+pub struct Ramp {
+ stops: Vec<(f32, [f32; 4])>,
+}
+
+impl Ramp {
+ pub fn new(g: &Gradient, rgb: &dyn Fn(&Color) -> [f32; 3]) -> Self {
+ let stops = g
+ .expanded()
+ .map(|(t, c, o, _)| {
+ let [r, gr, b] = rgb(&c);
+ (t, [r, gr, b, o])
+ })
+ .collect();
+ Self { stops }
+ }
+ /// Unpremultiplied colour and opacity at `t`, padded past the ends (transparent black
+ /// without stops).
+ pub fn at(&self, t: f32) -> [f32; 4] {
+ let Some(&(t0, first)) = self.stops.first() else { return [0.0; 4] };
+ // Not after the first stop (or not a number): its colour.
+ if t.partial_cmp(&t0) != Some(std::cmp::Ordering::Greater) {
+ return first;
+ }
+ for w in self.stops.windows(2) {
+ let ((a, ca), (b, cb)) = (w[0], w[1]);
+ if t <= b {
+ let u = if b - a > 1e-9 { (t - a) / (b - a) } else { 1.0 };
+ return std::array::from_fn(|k| ca[k] + (cb[k] - ca[k]) * u);
+ }
+ }
+ self.stops.last().map_or([0.0; 4], |s| s.1)
+ }
+}
+
+/// Seed of [`dither_noise`]: fixed, so a dithered gradient draws and exports the same pixels on
+/// every run.
+const DITHER_SEED: u32 = 0x5eed_d17e;
+
+/// An integer hash that mixes every input bit into every output bit (the "lowbias32" mix).
+fn mix32(mut v: u32) -> u32 {
+ v ^= v >> 16;
+ v = v.wrapping_mul(0x7feb_352d);
+ v ^= v >> 15;
+ v = v.wrapping_mul(0x846c_a68b);
+ v ^ (v >> 16)
+}
+
+/// Dither noise for colour channel `channel` of pixel (`x`, `y`), in colour levels: -1..1,
+/// densest around 0 (the sum of two uniform values: noise that hides steps between levels without
+/// a pattern of its own), the same for the same pixel on every run.
+pub fn dither_noise(x: u32, y: u32, channel: u32) -> f32 {
+ let h = mix32(x ^ mix32(y ^ mix32(channel ^ DITHER_SEED)));
+ ((h & 0xffff) as f32 + (h >> 16) as f32) / 65535.0 - 1.0
}
#[cfg(test)]
@@ -582,9 +809,8 @@ mod tests {
#[test]
fn reverse_mirrors_midpoints() {
let stop = |offset, hex, midpoint| GradientStop { midpoint, ..GradientStop::new(offset, Color::from_hex(hex).unwrap()) };
- let two = Gradient { kind: GradientKind::Linear, stops: vec![stop(0.0, "#ff0000", 0.2), stop(1.0, "#0000ff", 0.5)] };
- let three =
- Gradient { kind: GradientKind::Linear, stops: vec![stop(0.0, "#ff0000", 0.2), stop(0.3, "#00ff00", 0.8), stop(1.0, "#0000ff", 0.5)] };
+ let two = Gradient::new(GradientKind::Linear, vec![stop(0.0, "#ff0000", 0.2), stop(1.0, "#0000ff", 0.5)]);
+ let three = Gradient::new(GradientKind::Linear, vec![stop(0.0, "#ff0000", 0.2), stop(0.3, "#00ff00", 0.8), stop(1.0, "#0000ff", 0.5)]);
for g in [two, three] {
let mut r = g.clone();
r.reverse();
@@ -825,4 +1051,161 @@ mod tests {
h.keep_focal_from(&before);
assert!(close(h.focal.unwrap(), Point::new(0.0, -20.0)), "{h:?}");
}
+
+ #[test]
+ fn pixels_sample_the_ramp_at_each_cell_centre() {
+ // White → black left to right over a 10 × 2 box, a midpoint at 30% and a half-opaque end.
+ let mut g = GradientPaint::new(Gradient::default());
+ g.gradient.stops[0].midpoint = 0.3;
+ g.gradient.stops[1].opacity = 0.5;
+ let b = Rect::new(0.0, 0.0, 10.0, 2.0);
+ let px: Vec<[u8; 4]> = g.pixels(b, b, 10, 2, true, &Color::to_rgb).collect();
+ assert_eq!(px.len(), 20);
+ let ramp = Ramp::new(&g.gradient, &Color::to_rgb);
+ for (i, p) in px.iter().take(10).enumerate() {
+ let c = ramp.at((i as f32 + 0.5) / 10.0).map(|v| (v * 255.0).round() as u8);
+ assert_eq!(*p, c, "pixel {i}");
+ }
+ assert_eq!(px[3], px[13], "rows alike");
+ // The midpoint stop: grey at 30%; padded past the ends.
+ assert!((ramp.at(0.3)[0] - 0.5).abs() < 0.02, "{:?}", ramp.at(0.3));
+ assert_eq!(ramp.at(-1.0), [1.0, 1.0, 1.0, 1.0]);
+ assert_eq!(ramp.at(2.0), [0.0, 0.0, 0.0, 0.5]);
+ assert_eq!(ramp.at(f32::NAN), [1.0, 1.0, 1.0, 1.0]);
+ }
+
+ fn blue_yellow(method: GradientMethod) -> Gradient {
+ let mut g = Gradient::new(
+ GradientKind::Linear,
+ vec![GradientStop::new(0.0, Color::rgb(0.0, 0.0, 1.0)), GradientStop::new(1.0, Color::rgb(1.0, 1.0, 0.0))],
+ );
+ g.method = method;
+ g
+ }
+
+ /// Illustrator 30's Perceptual method mixes colours in a perceptually even way
+ /// (https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-gradients/control-perceptual-interpolation-in-gradients.html).
+ /// Here that is OKLab: blue → yellow passes through a light blue-grey, not the flat mid grey
+ /// a display RGB mix gives, and its lightness climbs evenly.
+ #[test]
+ fn perceptual_blue_to_yellow_is_not_the_grey_rgb_mix() {
+ let classic = blue_yellow(GradientMethod::Classic).sample(0.5).0.to_rgb();
+ assert!(classic.iter().all(|v| (v - 0.5).abs() < 1e-5), "classic: the RGB mix {classic:?}");
+ let p = blue_yellow(GradientMethod::Perceptual);
+ let [r, g, b] = p.sample(0.5).0.to_rgb();
+ assert!(b > r + 0.1 && b > g + 0.05, "a blue-grey, not grey: {:?}", [r, g, b]);
+ assert!(r + g + b > 1.5 + 0.2, "lighter than the RGB mix: {:?}", [r, g, b]);
+ let lightness = |t: f32| crate::libraries::to_oklab(&p.sample(t).0)[0];
+ let steps: Vec
= (0..4).map(|k| lightness((k + 1) as f32 / 4.0) - lightness(k as f32 / 4.0)).collect();
+ assert!(steps.iter().all(|d| (d - steps[0]).abs() < 1e-3), "even lightness steps: {steps:?}");
+ // Ends and opacity as before.
+ assert_eq!(p.sample(0.0).0.to_hex(), "#0000ff");
+ assert_eq!(p.sample(1.0).0.to_hex(), "#ffff00");
+ }
+
+ /// Renderers mix linearly between stops: a Perceptual segment becomes stops on the perceptual
+ /// curve (the midpoint diamond among them), more where it bends, close enough that the linear
+ /// ramp between them stays within half a colour level of the curve; a segment that hardly
+ /// bends needs few.
+ #[test]
+ fn perceptual_segments_expand_into_stops_on_the_curve() {
+ let pairs = [
+ (Color::rgb(0.0, 0.0, 1.0), Color::rgb(1.0, 1.0, 0.0)),
+ (Color::BLACK, Color::rgb(1.0, 0.0, 0.0)),
+ (Color::rgb(0.0, 1.0, 0.0), Color::rgb(1.0, 0.0, 1.0)),
+ (Color::cmyk(0.0, 0.0, 0.0, 1.0), Color::WHITE),
+ ];
+ for (a, b) in pairs {
+ let mut p = Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, a), GradientStop::new(1.0, b)]);
+ p.method = GradientMethod::Perceptual;
+ p.stops[0].midpoint = 0.3;
+ p.stops[1].opacity = 0.5;
+ let ex: Vec<_> = p.expanded().collect();
+ assert!((3..=100).contains(&ex.len()), "{a:?} → {b:?}: {} stops", ex.len());
+ assert!(ex.windows(2).all(|w| w[0].0 < w[1].0), "in order");
+ assert_eq!(ex.iter().filter(|s| s.3.is_some()).count(), 1, "one stop stands for the midpoint");
+ assert!(ex.iter().any(|s| s.3 == Some(0.3) && (s.0 - 0.3).abs() < 1e-6));
+ let ramp = Ramp::new(&p, &Color::to_rgb);
+ for k in 0..=2000 {
+ let t = k as f32 / 2000.0;
+ let (c, o) = p.sample(t);
+ let [r, g, b] = c.to_rgb();
+ let off = [r, g, b, o].iter().zip(ramp.at(t)).map(|(x, y)| (x - y).abs()).fold(0.0, f32::max);
+ assert!(off < 0.5 / 255.0, "{a:?} → {b:?} at {t}: {off}");
+ }
+ }
+ let mut flat = Gradient::new(
+ GradientKind::Linear,
+ vec![GradientStop::new(0.0, Color::rgb(0.2, 0.4, 0.6)), GradientStop::new(1.0, Color::rgb(0.25, 0.45, 0.6))],
+ );
+ flat.method = GradientMethod::Perceptual;
+ assert_eq!(flat.expanded().count(), 3, "the ends and the midpoint");
+ }
+
+ /// Classic gradients expand as they always did: their stops, and a stop at each off-centre
+ /// midpoint, sampled in display RGB (so the renderer draws the same pixels as before).
+ #[test]
+ fn classic_gradients_expand_as_before() {
+ let mut g = Gradient::new(
+ GradientKind::Linear,
+ vec![
+ GradientStop { midpoint: 0.2, ..GradientStop::new(0.0, Color::rgb(0.0, 0.0, 1.0)) },
+ GradientStop { opacity: 0.4, ..GradientStop::new(0.45, Color::cmyk(0.1, 0.8, 0.0, 0.2)) },
+ GradientStop { midpoint: 0.87, ..GradientStop::new(0.6, Color::rgb(1.0, 1.0, 0.0)) },
+ GradientStop::new(1.0, Color::gray(0.3)),
+ ],
+ );
+ // The expansion gradients had before they had a method.
+ let before: Vec<_> = g
+ .stops
+ .iter()
+ .enumerate()
+ .flat_map(|(i, s)| {
+ let mid = g.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) = g.sample_with(t, Color::lerp);
+ (t, c, o, Some(s.midpoint))
+ });
+ std::iter::once((s.offset, s.color, s.opacity, None)).chain(mid)
+ })
+ .collect();
+ assert_eq!(g.expanded().collect::>(), before);
+ assert_eq!(before.len(), 6);
+ assert_eq!(g.sample(0.3), g.sample_with(0.3, Color::lerp));
+ assert_eq!(g.sample_keep_model(0.5), g.sample_with(0.5, Color::lerp_keep_model));
+ g.method = GradientMethod::Perceptual;
+ assert_eq!(g.sample_keep_model(0.5), g.sample(0.5), "perceptual: one mix");
+ }
+
+ /// The method is written only when Perceptual, so files from before it (and Classic
+ /// gradients) read as Classic and new Classic files stay as they were.
+ #[test]
+ fn method_is_saved_only_when_perceptual() {
+ let classic = serde_json::to_value(Gradient::default()).unwrap();
+ assert!(classic.get("method").is_none(), "{classic}");
+ let old: Gradient = serde_json::from_value(serde_json::json!({"kind": "Linear", "stops": []})).unwrap();
+ assert_eq!(old.method, GradientMethod::Classic);
+ let p = blue_yellow(GradientMethod::Perceptual);
+ let v = serde_json::to_value(&p).unwrap();
+ assert_eq!(v["method"], "Perceptual");
+ assert_eq!(serde_json::from_value::(v).unwrap(), p);
+ assert_eq!(GradientMethod::parse("perceptual"), Some(GradientMethod::Perceptual));
+ assert_eq!(GradientMethod::parse("CLASSIC"), Some(GradientMethod::Classic));
+ assert_eq!(GradientMethod::parse("smooth"), None);
+ }
+
+ /// SVG and PDF can't mix colours perceptually: a Perceptual gradient is drawn as pixels there,
+ /// as Illustrator rasterises perceptual gradients saved as PDF or SVG, as a fill or a stroke,
+ /// dithered or not.
+ #[test]
+ fn perceptual_gradients_draw_as_pixels() {
+ for fill in [true, false] {
+ assert!(!GradientPaint::new(blue_yellow(GradientMethod::Classic)).draws_as_pixels(fill));
+ assert!(GradientPaint::new(blue_yellow(GradientMethod::Perceptual)).draws_as_pixels(fill));
+ let mut radial = blue_yellow(GradientMethod::Perceptual);
+ radial.kind = GradientKind::Radial;
+ radial.dither = true;
+ assert!(GradientPaint::new(radial).draws_as_pixels(fill));
+ }
+ }
}
diff --git a/crates/color/src/lib.rs b/crates/color/src/lib.rs
index 46439d29d0..9af14253d4 100644
--- a/crates/color/src/lib.rs
+++ b/crates/color/src/lib.rs
@@ -16,7 +16,7 @@ pub mod swatch;
pub use blend::BlendMode;
pub use freeform::{Freeform, FreeformMode, FreeformPoint};
-pub use gradient::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop};
+pub use gradient::{Gradient, GradientGeom, GradientKind, GradientMethod, GradientPaint, GradientStop};
pub use libraries::SwatchLibrary;
pub use swatch::{Swatch, SwatchGroup, default_swatches};
@@ -146,6 +146,8 @@ impl Color {
} else {
60.0 * ((r - g) / d + 4.0)
};
+ // f32 rounding in rem_euclid can yield exactly 360; wrap back to 0.
+ let h = if h >= 360.0 { 0.0 } else { h };
let s = if max <= 0.0 { 0.0 } else { d / max };
[h, s, max]
}
@@ -378,6 +380,18 @@ impl Paint {
_ => None,
}
}
+ /// This stroke paint as the fill of the stroke's outline, so the outline looks as the stroke
+ /// did: without dither, which strokes ignore ([`GradientPaint::draws_as_pixels`]).
+ pub fn stroke_as_fill(&self) -> Paint {
+ match self {
+ Paint::Gradient(g) if g.gradient.dither => {
+ let mut g = g.clone();
+ g.gradient.dither = false;
+ Paint::Gradient(g)
+ }
+ p => p.clone(),
+ }
+ }
/// 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 }
@@ -426,6 +440,12 @@ impl Paint {
mod tests {
use super::*;
+ #[test]
+ fn hue_below_360() {
+ let h = Color::Rgb { r: 1.0, g: 0.0, b: 1e-7 }.to_hsb()[0];
+ assert!((0.0..360.0).contains(&h), "hue {h}");
+ }
+
#[test]
fn hex_roundtrip() {
let c = Color::from_hex("#ff8000").unwrap();
diff --git a/crates/color/src/libraries.rs b/crates/color/src/libraries.rs
index 163038777f..e96760d5c5 100644
--- a/crates/color/src/libraries.rs
+++ b/crates/color/src/libraries.rs
@@ -98,7 +98,7 @@ pub fn builtin_library(id: &str) -> Option> {
// ---------- colour construction ----------
/// sRGB (0..=1, gamma encoded) of OKLab `(l, a, b)`, unclamped.
-fn oklab_to_srgb(l: f64, a: f64, b: f64) -> [f64; 3] {
+pub(crate) fn oklab_to_srgb(l: f64, a: f64, b: f64) -> [f64; 3] {
let l_ = l + 0.396_337_777_4 * a + 0.215_803_757_3 * b;
let m_ = l - 0.105_561_345_8 * a - 0.063_854_172_8 * b;
let s_ = l - 0.089_484_177_5 * a - 1.291_485_548_0 * b;
@@ -113,7 +113,12 @@ fn oklab_to_srgb(l: f64, a: f64, b: f64) -> [f64; 3] {
/// OKLab `[l, a, b]` of a colour's display RGB.
pub fn to_oklab(c: &Color) -> [f64; 3] {
- let [r, g, b] = c.to_rgb_uncalibrated().map(|v| {
+ srgb_to_oklab(c.to_rgb_uncalibrated())
+}
+
+/// OKLab `[l, a, b]` of sRGB `rgb` (0..=1, gamma encoded).
+pub(crate) fn srgb_to_oklab(rgb: [f32; 3]) -> [f64; 3] {
+ let [r, g, b] = rgb.map(|v| {
let v = f64::from(v);
if v <= 0.040_45 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) }
});
@@ -171,7 +176,7 @@ fn group(name: &str, swatches: Vec) -> 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 { opacity, ..GradientStop::new(offset, color) }).collect();
- Swatch { name: name.into(), paint: Paint::Gradient(Box::new(GradientPaint::new(Gradient { kind, stops }))), global: false, spot: false }
+ Swatch { name: name.into(), paint: Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(kind, stops)))), global: false, spot: false }
}
/// `n` steps of OKLCH lightness from `l0` to `l1`, chroma `c(t)` and hue `h(t)` (`t` in 0..=1),
diff --git a/crates/color/src/palette_io.rs b/crates/color/src/palette_io.rs
index eed4d5a942..065e06eed9 100644
--- a/crates/color/src/palette_io.rs
+++ b/crates/color/src/palette_io.rs
@@ -721,13 +721,13 @@ mod tests {
}
fn sample() -> SwatchLibrary {
- let grad = Paint::Gradient(Box::new(GradientPaint::new(Gradient {
- kind: GradientKind::Linear,
- stops: vec![
+ let grad = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(
+ GradientKind::Linear,
+ vec![
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 {
name: "Brand */ Colours".into(),
swatches: vec![
@@ -822,15 +822,15 @@ mod tests {
name: "Positions".into(),
swatches: vec![Swatch {
name: "Ramp".into(),
- paint: Paint::Gradient(Box::new(GradientPaint::new(Gradient {
+ paint: Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(
kind,
- stops: vec![
+ vec![
GradientStop::new(0.0, Color::BLACK),
GradientStop::new(0.125, Color::rgb8(255, 0, 0)),
GradientStop::new(0.12890625, Color::WHITE),
GradientStop::new(1.0, Color::rgb8(0, 0, 255)),
],
- }))),
+ )))),
global: false,
spot: false,
}],
diff --git a/crates/color/src/swatch.rs b/crates/color/src/swatch.rs
index 21f9af988b..12ae31220a 100644
--- a/crates/color/src/swatch.rs
+++ b/crates/color/src/swatch.rs
@@ -123,13 +123,13 @@ fn base_swatches() -> (Vec, Vec) {
.collect();
let grad = |name: &str, a: &str, b: &str, kind: GradientKind| Swatch {
name: name.into(),
- paint: Paint::Gradient(Box::new(crate::GradientPaint::new(Gradient {
+ paint: Paint::Gradient(Box::new(crate::GradientPaint::new(Gradient::new(
kind,
- stops: vec![
+ vec![
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,
spot: false,
};
diff --git a/crates/doc/src/blend.rs b/crates/doc/src/blend.rs
index 8ba6fb174f..7bf88ac164 100644
--- a/crates/doc/src/blend.rs
+++ b/crates/doc/src/blend.rs
@@ -89,7 +89,7 @@ fn resample_stops(g: &Gradient, offsets: &[f32]) -> Gradient {
out.stops = offsets
.iter()
.map(|&o| {
- let (color, opacity) = g.sample_with(o, lerp_color);
+ let (color, opacity) = g.sample_keep_model(o);
let (swatch, tint) = link_at(g, o);
GradientStop { opacity, swatch, tint, ..GradientStop::new(o, color) }
})
diff --git a/crates/doc/src/cancel.rs b/crates/doc/src/cancel.rs
index bff510707f..e38b0ab817 100644
--- a/crates/doc/src/cancel.rs
+++ b/crates/doc/src/cancel.rs
@@ -92,6 +92,15 @@ pub fn check() -> Result<(), Cancelled> {
if is_cancelled() { Err(Cancelled) } else { Ok(()) }
}
+/// Run `f` with this thread's token still in effect and its progress reports dropped: for work
+/// that reports its own steps around calls that report theirs (each file of a batch export).
+pub fn quiet(f: impl FnOnce() -> T) -> T {
+ match CURRENT.with(|c| c.borrow().as_ref().map(|s| s.token.clone())) {
+ Some(token) => scope(&token, None, f),
+ None => f(),
+ }
+}
+
/// Report that `done` of `total` steps (0: unknown) are finished. A no-op outside a [`scope`]
/// that has a sink.
pub fn progress(done: u64, total: u64, what: &str) {
@@ -139,4 +148,25 @@ mod tests {
progress(2, 3, "after");
assert_eq!(*seen.borrow(), vec![(1, 3, "page".to_string())]);
}
+
+ #[test]
+ fn quiet_work_reports_nothing_and_can_still_be_cancelled() {
+ let seen = Rc::new(RefCell::new(vec![]));
+ let sink: ProgressSink = {
+ let seen = seen.clone();
+ Rc::new(move |d, t, w| seen.borrow_mut().push((d, t, w.to_string())))
+ };
+ let t = CancelToken::new();
+ scope(&t, Some(sink), || {
+ progress(0, 2, "file");
+ quiet(|| {
+ progress(0, 1, "artboard");
+ t.cancel();
+ assert_eq!(check(), Err(Cancelled));
+ });
+ progress(1, 2, "file");
+ });
+ assert_eq!(*seen.borrow(), vec![(0, 2, "file".to_string()), (1, 2, "file".to_string())]);
+ assert_eq!(quiet(check), Ok(()), "outside a scope nothing is cancelled");
+ }
}
diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs
index 63aad85213..9f954603c7 100644
--- a/crates/doc/src/lib.rs
+++ b/crates/doc/src/lib.rs
@@ -44,6 +44,7 @@ pub mod perspective;
mod pixels;
pub use pixels::MAX_RASTER_ALLOC;
pub mod placed_document;
+pub mod plugin_data;
pub mod profiles;
pub mod puppet;
pub mod range;
@@ -105,11 +106,11 @@ pub use metadata::{CopyrightStatus, DocMetadata};
pub use node::Knockout;
pub use node::Scaling;
pub use node::{Extras, ExtrasMut, ImageObject, LAYER_COLORS, LayerColor, LiveShape, Node, NodeExtras, NodeId, NodeKind, OpacityMask};
-pub use node::{ImageMap, MAX_SVG_SCRIPTS, ObjectAttributes, SVG_EVENTS};
+pub use node::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, ObjectAttributes, SVG_EVENTS};
pub use orient::OrientedBox;
pub use pattern::{Overlap, PatternDef, PatternEdit, RepeatKind, RepeatSpec, TileType};
pub use perspective::PerspectiveAttachment;
-pub use placed_document::PlacedDocument;
+pub use placed_document::{PageBox, PlacedDocument};
pub use profiles::ColorProfiles;
pub use puppet::{PuppetPin, PuppetPins};
pub use rastersettings::{RasterColorModel, RasterEffectsSettings};
@@ -378,7 +379,9 @@ fn parse_measure(s: &str, default: Unit) -> Option