From c599522061ca64e51fe7a93db87140a698c14fde Mon Sep 17 00:00:00 2001 From: bflatastic Date: Fri, 9 Oct 2026 18:52:54 +0700 Subject: [PATCH] Fix #735: Illustrator EPS and .ai files match their page in Fit to Artwork Bounds and the page check - Fit to Artwork Bounds fits the art exports draw: hidden objects and layers, guides and template layers don't count, and the bounds stop at a layer's clip. - The comparison with the page catches an object one draws that the other doesn't (pixels whose neighbours all differ, away from type), a light colour against white, and, for an EPS whose page is its art's box, art the layers print outside it. - textAs: outlines opens a .ai whose type shows from its PDF part, which has the outlines. - document.open takes editingData: false to open an Illustrator EPS or .ai as its page or PDF part only, for print pipelines. Part of #637. Co-Authored-By: Claude Opus 5.5 --- ROADMAP.md | 4 +- crates/engine/src/cmd/fileio/load.rs | 13 +- crates/engine/src/cmd/fileio/mod.rs | 2 +- crates/engine/src/cmd/fileio/pdfimport.rs | 14 +- .../engine/src/cmd/fileio/tests_aiimport.rs | 49 ++++ crates/engine/src/cmd/layer.rs | 14 +- crates/engine/tests/import_fuzz.rs | 8 +- crates/eps/src/import/mod.rs | 12 +- crates/eps/src/import/native.rs | 222 +++++++++++++++--- crates/eps/src/import/tests_native.rs | 80 ++++++- crates/eps/src/lib.rs | 2 +- crates/render/src/encode/mod.rs | 4 +- crates/render/src/encode/tests.rs | 32 +++ crates/render/src/lib.rs | 2 +- crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + docs/mcp.md | 14 +- 21 files changed, 413 insertions(+), 65 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 77ad12b4..c832adf9 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -4,7 +4,7 @@ VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adob This file tracks **how far we are and what's left**. Time estimates are wall-clock hours of continuous Claude Opus 5.5 agent work (including builds and the CI gate), given both for **one agent** and for **4–6 parallel agents** on disjoint crates. They are counted from the remaining work (see [Parity estimate](#parity-estimate)), calibrated against measured throughput, and updated as work lands. -_Last updated: 2026-10-09 (after placed documents (File › Place of a `.vectorcraft` file, linked), M4.14–M4.98, M8.1–M8.20, M14.4–M14.7, the MCP prompts, resource templates, completions and logging, the 2026-10-07 issue fixes, the Layers panel rework and the 2026-10-08 community contributions: Pen and shape-tool modifiers, path editing, Layers, Artboards, Swatches/Brushes and dialogs, Japanese composition and PDF text, Hebrew/Arabic type, interface languages (Spanish among them), the font menu, saved selections, MCP and EPS, the missing-font export warning (#319), open paths in the Shape Builder (#374), PDF/`.ai` import keeping strokes live and hidden and nested layers (#372), per-corner Live Corners (#381), SVG type opening at the size it draws at (#396), the Wayland clipboard with copied-file paste (#398), ruler guides that can be selected, moved and deleted (#414), two batches of Preferences options that were stored but unused (#394), skeleton reads with `document.find` for large documents over MCP (#416) and anchors dragged with Direct Selection snapping to points, segments and smart guides, clipped SVG layers opening as clipping layers (#420), PDF/`.ai` layers read on pages of tens of millions of operators (#419), Document Color Mode putting RGB greys on the black plate on request and converting pattern tiles (#421) and movable dialogs with Offset Path's Joins dropdown (#423) and numeric fields scrubbed by dragging their label (#400), stroke weight presets in the stroke unit (#426), the Appearance panel's Opacity popup (#430), type on a path brackets, flip and Type on a Path Options that keep the type in place (#429), Layers rows dragged with a ghost and dropped on the trash or New Layer (#435), tool flyouts opening on a right or corner press (#436), tool flyouts torn off into floating toolbars (#437), the Shape Builder's erase mode deleting edges too (#439), installed fonts registered outside the font folders and fonts installed while the app runs listed in the font menus (#443), alike circular corners on rectangles that aren't square (#442), tool cursors as OS cursors so the pointer no longer trails over the canvas (#444), artboards copied and pasted with their art (#446), guides dragged out of the rulers snapping to the art's side midpoints and the artboards, artboard guides (#451), the toolbar's double arrow and Window › Toolbars › Double Column switching between one and two columns in any window height (#455), the Smart Guides display options and Snapping Tolerance (#394), Font Size and Leading combo boxes with preset lists in the Character and Properties panels and the Control bar (#458), screenshots pasted from the clipboard on macOS, Windows and the web (#457), the Properties panel's Fill and Stroke matching the Control bar's, Illustrator's Window menu panel keys (Shift+F7 for Align…) and Alt-wheel zoom whatever the wheel preference (Discord feedback), the point/area type widget (Discord feedback), groups in legacy Illustrator .ai files (Discord feedback), a rotating desktop log file (#465), image controls in the Control bar and Properties panel: Image Trace with its presets, Mask, Crop Image, Embed/Unembed, and an Image Trace object's preset, Expand and Release (Discord feedback), the Pen working as the Anchor Point tool with Alt held over a selected path's handles and anchors, and anchor buttons that convert, connect and cut paths at the selected anchors (Discord feedback), Japanese hanging punctuation (burasagari, #463), Escape leaving Presentation Mode with no screen mode saved across restarts, documents dropped on the desktop app opening as tabs of their own and a note that an `.ai` file's art off its artboards isn't in the part read (#472), Add/Delete Anchor Point tool icons drawn from the Pen tool's (#479), EPS import running more of PostScript Level 3 (patterns, Type 3 fonts, mesh shadings, masked images, VM and resource probes), and a preview that stands in saying why (Discord feedback, #466, #469, #474), chords with modifiers recorded in Edit › Keyboard Shortcuts (#487), Type Object Selection by Path Only (#394), Anti-aliased Artwork (#394), Show Pixel Grid (#394), pen and touch taps pressed and lifted within one frame clicking where they tapped and the Linux/Wayland pen-tablet workaround (#491), bounding-box resizes landing on the other objects' anchors and centres with labels, and the Rotate, Scale, Shear and Reflect tools snapping their drags (#482), Shift-drag marquees that toggle the objects or anchors they reach and a Lasso whose Alt subtraction keeps the rest of the selection (#483), the mouse wheel stepping the focused numeric field, the dialogs' and preferences' drag values made such fields (#485), Show The Home Screen When No Documents Are Open (#394), Numbers Without Units Are Points (#394), Auto-Collapse Iconic Panels (#394), the Contextual Task Bar moved by its handle and its More Options menu pinning and resetting its position, a designed macOS DMG window (#493), panels, panel groups and the Tools panel undocking into floating panels that move, stack and dock again (#495), the 0.5.0 startup crash on dual-GPU Linux desktops under Wayland fixed: the desktop's own GPU by default and a restart on the next GPU when one can't show the window (#502), path editing while drawing: Cmd/Ctrl with the Pen borrowing Direct Selection and drawing on afterwards, Pen+Alt reshaping segments, handles of a whole selected path dragging, and handle drags no longer re-gathering snap targets every move (#494), the Control bar's and Properties panel's Convert buttons for a path selected as a whole with Direct Selection, the Pen and the anchor tools (#504), the Pen closing a path dragged out of its first anchor every time, without flicker (#501), the Paste menu checking the system clipboard on a background thread on Linux so an X11 clipboard owner that never answers no longer freezes the window (#510), PDF/`.ai` import keeping a type object's outline stroke on the type, wrapped lines as area type, barcode digits in place and layers in the file's stacking order (#508), the Italian interface (#514), EPS images with several data sources read in turn (#498), `restore` undoing dictionary changes in EPS import (part of #505), the macOS menu bar laid out as a Mac app's (the VectorCraft menu with Settings, Language and Appearance, the system's Hide, Services and Window items; owner's request), Object › Image Trace › Make tracing with the Default preset instead of asking for a preset's name (#543), the rulers' unit menu (#528), Live Corners on stars, polygons and pen paths (#511), the drawing tools snapping to Smart Guides as the Selection tool does, with Construction Guides (#506), the in-window menus' Select All, Cut, Copy and Paste acting on the text field they were opened from (#516), Windows rendering through DX12 before Vulkan (#545), Image Trace tracing colour layers in parallel and refusing traces too large for memory, with the canvas outlining huge selections by their bounds (#525), SVGs of chosen artboards holding only the art over each artboard (#550), the font menu scrolling only its list, under a search field and filters that stay put (#555), a click on an object of a selection making it the key object that Align aligns to and Distribute Spacing spaces from, drawn with a thicker outline (#541), Shape Builder merges taken from the planar map itself, so merged regions leave no inner edge, hairline gap or spur in their outline (#569), `.ai` written by the exports and the CLI (`--export`, `convert`) as Save As writes it (#526), SVG round trips keeping hidden objects and `data-*` attributes (#522), the gradient stop popover staying open after the click that opens it from the Gradient panel (#577), standard ligatures kept under small tracking and dropped only past about −8% / +22% of a word space or when the character asks for them (#583), the Color panel keeping its height as warnings come and go so a drag on its spectrum no longer flickers near white (#578), fonts that font services such as Adobe Fonts load on Windows, listed through DirectWrite (#579), `.ai` files writing their layers and sublayers as PDF layers, hidden ones with their art, and PDF layers nested in layers importing as sublayers (#372), file dialogs on Linux shown off the UI thread so the compositor no longer finds the window not responding, and parented to the window on Linux and Windows (#592), anchors and handle ends picked from 2 px past their drawn size before the segments through them (#593), an image copied in a browser pasting as the picture, not its address (#597), the Free Transform widget with Constrain, Free Transform, Perspective Distort and Free Distort (#598), touch gestures: a two-finger tap undoes and a three-finger tap redoes (#585), the font menus' live preview staying on the text instead of flickering on and off every frame (#563), Edit Artboards showing the active artboard in the Properties panel with New Artboard, Delete Artboard and Exit (#530), the same DirectWrite fonts in `vectorcraft-cli` and its MCP server (#579), SVG layers keeping their names when wrapped and sublayers round-tripping through SVG (#372), a Layers panel that lays out only the rows in view and keeps a document's open rows in its file (#638), a panel dropped on the dock lights up the icon column it goes back to and pops out of its icon (#649), Image Trace's View modes and an Advanced section that stays as it was left (part of #641), Image Trace's Palette: Limited, Full Tone, Automatic and Document Library (part of #641), Image Trace's Create Strokes: line art traced as stroked centre lines (part of #641), a dual-GPU Mac falling back to its other GPU when one fails to start (#651), two fingers dragged on a touch screen panning the canvas (part of #449), the Home screen's Recent Files and a double-clicked New Document preset creating the document (part of #663), quitting no longer crashing on Macs with a Touch Bar (#661), Animated Zoom, Large Tabs, Scale Cursor Proportional to UI and anti-aliased bitmaps in Pixel Preview acting (part of #394), Smart Guides › Spacing Guides (part of #394), Edit Artboards' Properties choosing an artboard's size preset and flipping it between portrait and landscape (#671), Preferences › Type › Additional Fonts Folder loading the fonts of a folder you choose (#683), Canvas Color's light, medium and dark grey (part of #663), a document tab's close box after its title on Windows and Linux, before it on macOS (part of #673), Rearrange All Artboards' layouts (a grid by row or by column, one row, one column) and right-to-left order, one click away in the Properties and Artboards panels (#681), User Interface › Show Tool Group Labels and Cmd+, opening Settings on the Mac (part of #663), the Windows taskbar and Alt+Tab showing VectorCraft's icon, a click with a selection tool making its artboard the active one, and Paste in Place, in Front and in Back pasting onto the active artboard (#693), Photoshop-style raster effects on a pixel-filter pipeline: Effect › Blur › Radial Blur and Smart Blur, Effect › Sharpen › Unsharp Mask (part of gap 2), the Properties panel's number fields all one width (#696), the rotate cursor drawn as a curved double arrow (#701), the Templates folder in the desktop's own documents folder, made when missing (#703), PDF and .ai glyphs whose ToUnicode names no character (U+FFFD) taking their character from the embedded font or keeping their outlines, with a warning (#708), Illustrator EPS and `.ai` files opening from their editing data with their colours, gradients, transparency, images, names and every artboard (part of #637), `.ai` files saved without PDF compatibility opening from their editing data (part of #637); see [Honest assessment](#honest-assessment-2026-10-05))._ +_Last updated: 2026-10-09 (after placed documents (File › Place of a `.vectorcraft` file, linked), M4.14–M4.98, M8.1–M8.20, M14.4–M14.7, the MCP prompts, resource templates, completions and logging, the 2026-10-07 issue fixes, the Layers panel rework and the 2026-10-08 community contributions: Pen and shape-tool modifiers, path editing, Layers, Artboards, Swatches/Brushes and dialogs, Japanese composition and PDF text, Hebrew/Arabic type, interface languages (Spanish among them), the font menu, saved selections, MCP and EPS, the missing-font export warning (#319), open paths in the Shape Builder (#374), PDF/`.ai` import keeping strokes live and hidden and nested layers (#372), per-corner Live Corners (#381), SVG type opening at the size it draws at (#396), the Wayland clipboard with copied-file paste (#398), ruler guides that can be selected, moved and deleted (#414), two batches of Preferences options that were stored but unused (#394), skeleton reads with `document.find` for large documents over MCP (#416) and anchors dragged with Direct Selection snapping to points, segments and smart guides, clipped SVG layers opening as clipping layers (#420), PDF/`.ai` layers read on pages of tens of millions of operators (#419), Document Color Mode putting RGB greys on the black plate on request and converting pattern tiles (#421) and movable dialogs with Offset Path's Joins dropdown (#423) and numeric fields scrubbed by dragging their label (#400), stroke weight presets in the stroke unit (#426), the Appearance panel's Opacity popup (#430), type on a path brackets, flip and Type on a Path Options that keep the type in place (#429), Layers rows dragged with a ghost and dropped on the trash or New Layer (#435), tool flyouts opening on a right or corner press (#436), tool flyouts torn off into floating toolbars (#437), the Shape Builder's erase mode deleting edges too (#439), installed fonts registered outside the font folders and fonts installed while the app runs listed in the font menus (#443), alike circular corners on rectangles that aren't square (#442), tool cursors as OS cursors so the pointer no longer trails over the canvas (#444), artboards copied and pasted with their art (#446), guides dragged out of the rulers snapping to the art's side midpoints and the artboards, artboard guides (#451), the toolbar's double arrow and Window › Toolbars › Double Column switching between one and two columns in any window height (#455), the Smart Guides display options and Snapping Tolerance (#394), Font Size and Leading combo boxes with preset lists in the Character and Properties panels and the Control bar (#458), screenshots pasted from the clipboard on macOS, Windows and the web (#457), the Properties panel's Fill and Stroke matching the Control bar's, Illustrator's Window menu panel keys (Shift+F7 for Align…) and Alt-wheel zoom whatever the wheel preference (Discord feedback), the point/area type widget (Discord feedback), groups in legacy Illustrator .ai files (Discord feedback), a rotating desktop log file (#465), image controls in the Control bar and Properties panel: Image Trace with its presets, Mask, Crop Image, Embed/Unembed, and an Image Trace object's preset, Expand and Release (Discord feedback), the Pen working as the Anchor Point tool with Alt held over a selected path's handles and anchors, and anchor buttons that convert, connect and cut paths at the selected anchors (Discord feedback), Japanese hanging punctuation (burasagari, #463), Escape leaving Presentation Mode with no screen mode saved across restarts, documents dropped on the desktop app opening as tabs of their own and a note that an `.ai` file's art off its artboards isn't in the part read (#472), Add/Delete Anchor Point tool icons drawn from the Pen tool's (#479), EPS import running more of PostScript Level 3 (patterns, Type 3 fonts, mesh shadings, masked images, VM and resource probes), and a preview that stands in saying why (Discord feedback, #466, #469, #474), chords with modifiers recorded in Edit › Keyboard Shortcuts (#487), Type Object Selection by Path Only (#394), Anti-aliased Artwork (#394), Show Pixel Grid (#394), pen and touch taps pressed and lifted within one frame clicking where they tapped and the Linux/Wayland pen-tablet workaround (#491), bounding-box resizes landing on the other objects' anchors and centres with labels, and the Rotate, Scale, Shear and Reflect tools snapping their drags (#482), Shift-drag marquees that toggle the objects or anchors they reach and a Lasso whose Alt subtraction keeps the rest of the selection (#483), the mouse wheel stepping the focused numeric field, the dialogs' and preferences' drag values made such fields (#485), Show The Home Screen When No Documents Are Open (#394), Numbers Without Units Are Points (#394), Auto-Collapse Iconic Panels (#394), the Contextual Task Bar moved by its handle and its More Options menu pinning and resetting its position, a designed macOS DMG window (#493), panels, panel groups and the Tools panel undocking into floating panels that move, stack and dock again (#495), the 0.5.0 startup crash on dual-GPU Linux desktops under Wayland fixed: the desktop's own GPU by default and a restart on the next GPU when one can't show the window (#502), path editing while drawing: Cmd/Ctrl with the Pen borrowing Direct Selection and drawing on afterwards, Pen+Alt reshaping segments, handles of a whole selected path dragging, and handle drags no longer re-gathering snap targets every move (#494), the Control bar's and Properties panel's Convert buttons for a path selected as a whole with Direct Selection, the Pen and the anchor tools (#504), the Pen closing a path dragged out of its first anchor every time, without flicker (#501), the Paste menu checking the system clipboard on a background thread on Linux so an X11 clipboard owner that never answers no longer freezes the window (#510), PDF/`.ai` import keeping a type object's outline stroke on the type, wrapped lines as area type, barcode digits in place and layers in the file's stacking order (#508), the Italian interface (#514), EPS images with several data sources read in turn (#498), `restore` undoing dictionary changes in EPS import (part of #505), the macOS menu bar laid out as a Mac app's (the VectorCraft menu with Settings, Language and Appearance, the system's Hide, Services and Window items; owner's request), Object › Image Trace › Make tracing with the Default preset instead of asking for a preset's name (#543), the rulers' unit menu (#528), Live Corners on stars, polygons and pen paths (#511), the drawing tools snapping to Smart Guides as the Selection tool does, with Construction Guides (#506), the in-window menus' Select All, Cut, Copy and Paste acting on the text field they were opened from (#516), Windows rendering through DX12 before Vulkan (#545), Image Trace tracing colour layers in parallel and refusing traces too large for memory, with the canvas outlining huge selections by their bounds (#525), SVGs of chosen artboards holding only the art over each artboard (#550), the font menu scrolling only its list, under a search field and filters that stay put (#555), a click on an object of a selection making it the key object that Align aligns to and Distribute Spacing spaces from, drawn with a thicker outline (#541), Shape Builder merges taken from the planar map itself, so merged regions leave no inner edge, hairline gap or spur in their outline (#569), `.ai` written by the exports and the CLI (`--export`, `convert`) as Save As writes it (#526), SVG round trips keeping hidden objects and `data-*` attributes (#522), the gradient stop popover staying open after the click that opens it from the Gradient panel (#577), standard ligatures kept under small tracking and dropped only past about −8% / +22% of a word space or when the character asks for them (#583), the Color panel keeping its height as warnings come and go so a drag on its spectrum no longer flickers near white (#578), fonts that font services such as Adobe Fonts load on Windows, listed through DirectWrite (#579), `.ai` files writing their layers and sublayers as PDF layers, hidden ones with their art, and PDF layers nested in layers importing as sublayers (#372), file dialogs on Linux shown off the UI thread so the compositor no longer finds the window not responding, and parented to the window on Linux and Windows (#592), anchors and handle ends picked from 2 px past their drawn size before the segments through them (#593), an image copied in a browser pasting as the picture, not its address (#597), the Free Transform widget with Constrain, Free Transform, Perspective Distort and Free Distort (#598), touch gestures: a two-finger tap undoes and a three-finger tap redoes (#585), the font menus' live preview staying on the text instead of flickering on and off every frame (#563), Edit Artboards showing the active artboard in the Properties panel with New Artboard, Delete Artboard and Exit (#530), the same DirectWrite fonts in `vectorcraft-cli` and its MCP server (#579), SVG layers keeping their names when wrapped and sublayers round-tripping through SVG (#372), a Layers panel that lays out only the rows in view and keeps a document's open rows in its file (#638), a panel dropped on the dock lights up the icon column it goes back to and pops out of its icon (#649), Image Trace's View modes and an Advanced section that stays as it was left (part of #641), Image Trace's Palette: Limited, Full Tone, Automatic and Document Library (part of #641), Image Trace's Create Strokes: line art traced as stroked centre lines (part of #641), a dual-GPU Mac falling back to its other GPU when one fails to start (#651), two fingers dragged on a touch screen panning the canvas (part of #449), the Home screen's Recent Files and a double-clicked New Document preset creating the document (part of #663), quitting no longer crashing on Macs with a Touch Bar (#661), Animated Zoom, Large Tabs, Scale Cursor Proportional to UI and anti-aliased bitmaps in Pixel Preview acting (part of #394), Smart Guides › Spacing Guides (part of #394), Edit Artboards' Properties choosing an artboard's size preset and flipping it between portrait and landscape (#671), Preferences › Type › Additional Fonts Folder loading the fonts of a folder you choose (#683), Canvas Color's light, medium and dark grey (part of #663), a document tab's close box after its title on Windows and Linux, before it on macOS (part of #673), Rearrange All Artboards' layouts (a grid by row or by column, one row, one column) and right-to-left order, one click away in the Properties and Artboards panels (#681), User Interface › Show Tool Group Labels and Cmd+, opening Settings on the Mac (part of #663), the Windows taskbar and Alt+Tab showing VectorCraft's icon, a click with a selection tool making its artboard the active one, and Paste in Place, in Front and in Back pasting onto the active artboard (#693), Photoshop-style raster effects on a pixel-filter pipeline: Effect › Blur › Radial Blur and Smart Blur, Effect › Sharpen › Unsharp Mask (part of gap 2), the Properties panel's number fields all one width (#696), the rotate cursor drawn as a curved double arrow (#701), the Templates folder in the desktop's own documents folder, made when missing (#703), PDF and .ai glyphs whose ToUnicode names no character (U+FFFD) taking their character from the embedded font or keeping their outlines, with a warning (#708), Illustrator EPS and `.ai` files opening from their editing data with their colours, gradients, transparency, images, names and every artboard (part of #637), `.ai` files saved without PDF compatibility opening from their editing data (part of #637), guides left out of raster exports and Fit to Artwork Bounds, hidden art left out of Fit to Artwork Bounds, Illustrator files compared with their page object by object, and `editingData: false` opening only what the page prints (#735); see [Honest assessment](#honest-assessment-2026-10-05))._ ## Where we are @@ -252,7 +252,7 @@ lossless SVG/PDF export of live effects with SVG filters, a documented JSON form command, gesture and dialog drivable by agents (MCP, CLI, control channel). ## Out of scope (by design or by law) -- **Native `.ai` private data, beyond its structure:** the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths, clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours), linear and radial gradients, opacity, blend modes, isolation and knockout, embedded images with their alpha channel, guides, and every artboard where it is. An object with several fills or strokes, effects or a brush comes in as its drawn look (a group named after it). Type that shows comes from the page, which draws it, into its text object's place (no group around it); type that doesn't (hidden layers and objects, art off the page) is made from the file's text document (characters, font, size, colour, alignment and where it is, for point type), and area type and type on a path in it are left out with a note. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type made from the text document and other type left out with a note. Symbols, pattern fills, placed files and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike); the page is used when they differ by more than 5%. A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. +- **Native `.ai` private data, beyond its structure:** the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths, clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours), linear and radial gradients, opacity, blend modes, isolation and knockout, embedded images with their alpha channel, guides, and every artboard where it is. An object with several fills or strokes, effects or a brush comes in as its drawn look (a group named after it). Type that shows comes from the page, which draws it, into its text object's place (no group around it); type that doesn't (hidden layers and objects, art off the page) is made from the file's text document (characters, font, size, colour, alignment and where it is, for point type), and area type and type on a path in it are left out with a note. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type made from the text document and other type left out with a note. Symbols, pattern fills, placed files and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5%, where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. - **Adobe cloud services** (Libraries sync, Adobe Fonts, Firefly/generative): these are pluggable provider APIs, not built in. - **Adobe's bundled assets** (swatch/brush/symbol libraries, presets, icons): ours are original. diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index c0c80fe6..080d2434 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -137,11 +137,12 @@ pub fn load(name: &str, bytes: &[u8]) -> Result { /// layers and hidden objects as they were, and the art outside its artboard (its PDF part has /// only what is on the artboards), as an EPS of the editor is read. Anything else as it was. fn through_editing_data(bytes: &[u8], opts: &LoadOptions, doc: Document, warnings: Vec) -> (Document, Vec) { - if opts.pages.is_some() || !opts.layers { + if opts.pages.is_some() || !opts.layers || !opts.editing_data { return (doc, warnings); } let Some(private) = vectorcraft_pdf::illustrator_data(bytes, opts.password.as_deref()) else { return (doc, warnings) }; - let (doc, mut warnings) = vectorcraft_eps::layered_ai(&private, doc, warnings); + let outlined = opts.text_as == vectorcraft_pdf::TextAs::Outlines; + let (doc, mut warnings) = vectorcraft_eps::layered_ai(&private, doc, warnings, outlined); // The note that the art outside the artboard is lost is the reason the layers weren't read. if warnings.iter().any(|w| w.starts_with("the file's layers weren't read from its editing data")) { return (doc, warnings); @@ -151,10 +152,10 @@ fn through_editing_data(bytes: &[u8], opts: &LoadOptions, doc: Document, warning } /// A `.ai` saved without PDF compatibility (its PDF part is a placeholder page) from the editor's -/// own copy of its art alone: `None` when the file has none (or pages are picked, or layers are -/// off), an error when it can't be read. +/// own copy of its art alone: `None` when the file has none (or pages are picked, or layers or the +/// editing data are off), an error when it can't be read. fn from_editing_data_alone(bytes: &[u8], opts: &LoadOptions) -> Option)>> { - if opts.pages.is_some() || !opts.layers { + if opts.pages.is_some() || !opts.layers || !opts.editing_data { return None; } let private = vectorcraft_pdf::illustrator_data(bytes, opts.password.as_deref())?; @@ -178,7 +179,7 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result _ if format.id == "eps" || vectorcraft_pdf::is_postscript(bytes) => { let editing = vectorcraft_eps::has_native(bytes).then_some((true, || vectorcraft_eps::native(bytes))); restore_or_import(editing, || { - let r = vectorcraft_eps::import(bytes).map_err(|e| err(format!("can't open `{}`: {e}", file_name(name))))?; + let r = vectorcraft_eps::import_with(bytes, opts.editing_data).map_err(|e| err(format!("can't open `{}`: {e}", file_name(name))))?; Ok((r.document, r.warnings)) })? } diff --git a/crates/engine/src/cmd/fileio/mod.rs b/crates/engine/src/cmd/fileio/mod.rs index f124726f..4dcdf976 100644 --- a/crates/engine/src/cmd/fileio/mod.rs +++ b/crates/engine/src/cmd/fileio/mod.rs @@ -82,7 +82,7 @@ pub fn specs() -> Vec { "Open Document", [], None, - "{path} or {name, dataBase64}, PDF/.ai: pages?: \"2-3, 5\" (1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page) | false (one layer per page, without the art that is off; Save then asks for a name), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), DXF: dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again). Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks)", + "{path} or {name, dataBase64}, PDF/.ai: pages?: \"2-3, 5\" (1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page) | false (one layer per page, without the art that is off; Save then asks for a name), editingData?: true (default: an EPS or .ai that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai whose type shows opens from its PDF part with textAs: outlines) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), DXF: dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again). Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks)", always, load::open ), diff --git a/crates/engine/src/cmd/fileio/pdfimport.rs b/crates/engine/src/cmd/fileio/pdfimport.rs index 3df3ade8..32de950b 100644 --- a/crates/engine/src/cmd/fileio/pdfimport.rs +++ b/crates/engine/src/cmd/fileio/pdfimport.rs @@ -32,6 +32,10 @@ pub struct LoadOptions { pub layers: bool, /// How a DXF drawing comes in (the `dxf` param, see [`super::dxfimport`]). pub dxf: vectorcraft_cad::ImportOptions, + /// An Illustrator EPS or `.ai` that carries the editing copy of its art opens from it (its + /// layers, hidden objects and the art outside its artboards); else only what its page or PDF + /// part prints comes in. + pub editing_data: bool, } impl Default for LoadOptions { @@ -45,6 +49,7 @@ impl Default for LoadOptions { text_as: TextAs::default(), layers: true, dxf: Default::default(), + editing_data: true, } } } @@ -52,7 +57,8 @@ impl Default for LoadOptions { impl LoadOptions { /// From command params: `pages` (`"2-3, 5"`, a page number or `"all"`), `page` (one page, when /// `pages` isn't given), `cropTo` (or `crop`), `password`, `colorMode` (`rgb` | `cmyk`) with `grays`, - /// `textAs` (`text` | `outlines`), `layers` (true | false) and `dxf` (the DXF import options). + /// `textAs` (`text` | `outlines`), `layers` (true | false), `editingData` (true | false) and `dxf` + /// (the DXF import options). pub fn from_params(cmd: &str, p: &Value) -> Result { let pages = match p.get("pages").filter(|v| !v.is_null()).or_else(|| p.get("page").filter(|v| !v.is_null())) { None => None, @@ -75,8 +81,12 @@ impl LoadOptions { None => true, Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "layers must be true or false"))?, }; + let editing_data = match p.get("editingData").filter(|v| !v.is_null()) { + None => true, + Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "editingData must be true or false"))?, + }; let dxf = super::dxfimport::options(cmd, p.get("dxf"))?; - Ok(Self { pages, crop, password, color_mode, grays, text_as, layers, dxf }) + Ok(Self { pages, crop, password, color_mode, grays, text_as, layers, dxf, editing_data }) } /// Does the document read only part of the file, or read it differently (a page range, another diff --git a/crates/engine/src/cmd/fileio/tests_aiimport.rs b/crates/engine/src/cmd/fileio/tests_aiimport.rs index ae3acc5e..01ec2a92 100644 --- a/crates/engine/src/cmd/fileio/tests_aiimport.rs +++ b/crates/engine/src/cmd/fileio/tests_aiimport.rs @@ -108,3 +108,52 @@ fn an_ai_file_saved_without_its_pdf_part_opens_from_its_editing_data() { let e = open(&mut s, "plain.ai", &ai::ai(b"", PLACEHOLDER), json!({})).unwrap_err().to_string(); assert!(e.contains("placeholder"), "{e}"); } + +#[test] +fn editing_data_false_opens_only_what_the_page_prints() { + let mut s = Session::new(); + for (name, file) in [("art.eps", ai::eps(&ai::sample_data(), ai::page_ps())), ("art.ai", ai::ai(&compressed(&ai::sample_data()), ai::page_pdf()))] + { + let r = open(&mut s, name, &file, json!({"editingData": false})).unwrap(); + let layers = &s.doc().unwrap().doc.layers; + assert_eq!(layers.len(), 1, "{name}: {r}"); + assert_ne!(names(layers), ["Art"], "{name}: the page's layer"); + } + let e = open(&mut s, "art.eps", &ai::eps(&ai::sample_data(), ai::page_ps()), json!({"editingData": "no"})).unwrap_err().to_string(); + assert!(e.contains("editingData must be true or false"), "{e}"); + // A file that is only its editing data can't open without it. + let e = open(&mut s, "art.ai", &ai::ai(&compressed(&ai::sample_data()), PLACEHOLDER), json!({"editingData": false})).unwrap_err().to_string(); + assert!(e.contains("placeholder"), "{e}"); +} + +#[test] +fn fit_to_artwork_bounds_leaves_out_the_hidden_art_and_guides_the_editing_data_has() { + // A shown square; a hidden one and a long guide far from it, which the page doesn't draw. + let art = + format!("0 g\n{}f\n1 Xw\n{}f\n0 Xw\n-500 20 m\n700 20 L\n(N) *\n", ai::rect(10.0, 10.0, 50.0, 50.0), ai::rect(150.0, 60.0, 190.0, 95.0)); + let data = ai::editing_data(200.0, 100.0, &ai::layer("Art", &art)); + let mut s = Session::new(); + let r = open(&mut s, "fit.eps", &ai::eps(data.as_bytes(), "0 setgray 10 10 40 40 rectfill\n"), json!({})).unwrap(); + let layer = &s.doc().unwrap().doc.layers[0]; + let kids = layer.children().unwrap(); + assert_eq!(kids.len(), 3, "{r}"); + assert!(!kids[1].visible && matches!(kids[2].kind, NodeKind::Path { guide: true, .. })); + s.execute("artboard.fitToArt", &json!({})).unwrap(); + // The square, 50 to 90 down the 100-point page. + assert_eq!(s.doc().unwrap().doc.artboards[0].rect, vectorcraft_geom::Rect::new(10.0, 50.0, 50.0, 90.0)); +} + +#[test] +fn type_asked_for_as_outlines_opens_a_file_whose_type_shows_from_its_pdf_part() { + let text = "/AI11Text :\n0 /FreeUndo ,\n0 /FrameIndex ,\n0 /StoryIndex ,\n;\n"; + let data = ai::editing_data(200.0, 100.0, &ai::layer("Art", &format!("0 g\n{}f\n{text}", ai::rect(10.0, 10.0, 50.0, 50.0)))); + let file = ai::ai(&compressed(data.as_bytes()), "0 g 10 10 40 40 re f BT /F1 12 Tf 100 50 Td (Hi) Tj ET"); + let mut s = Session::new(); + // As type, the page's type goes into the text object of the layers. + let r = open(&mut s, "type.ai", &file, json!({})).unwrap(); + assert_eq!(names(&s.doc().unwrap().doc.layers), ["Art"], "{r}"); + // As outlines, only the PDF part has them. + let r = open(&mut s, "type.ai", &file, json!({"textAs": "outlines"})).unwrap(); + assert!(r["warnings"].to_string().contains("outlines"), "{r}"); + assert_ne!(names(&s.doc().unwrap().doc.layers), ["Art"], "{r}"); +} diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index bc49386a..2bae10ab 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -139,7 +139,15 @@ pub fn specs() -> Vec { has_doc, artboard_set ), - cmd!("artboard.fitToArt", "Fit to Artwork Bounds", ["Object", "Artboards"], None, "{index?}", has_doc, artboard_fit_art), + cmd!( + "artboard.fitToArt", + "Fit to Artwork Bounds", + ["Object", "Artboards"], + None, + "{index?} the artboard fits the art that shows (with its strokes and effects; hidden objects and layers, guides and template layers don't count)", + has_doc, + artboard_fit_art + ), cmd!("artboard.fitToSelection", "Fit to Selected Art", ["Object", "Artboards"], None, "{index?}", has_selection, artboard_fit_sel), cmd!( "layer.clippingMask.toggle", @@ -810,9 +818,11 @@ fn rect_map(from: Rect, to: Rect) -> Option { xf.is_finite().then_some(xf) } +/// The artboard fits the art that exports draw: hidden objects and layers, guides and template +/// layers don't count. fn artboard_fit_art(s: &mut Session, p: &Value) -> Result { let i = p.get("index").and_then(Value::as_u64).unwrap_or(0) as usize; - let b = s.doc()?.doc.art_bounds().ok_or_else(|| EngineError::Other("no artwork".into()))?; + let b = vectorcraft_render::encode::art_bounds(&s.doc()?.doc).ok_or_else(|| EngineError::Other("no artwork".into()))?; s.execute("artboard.setProps", &json!({"index": i, "x": b.x0, "y": b.y0, "width": b.width(), "height": b.height()})) } diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index d7e2ef40..f50ac1fa 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -1731,7 +1731,7 @@ proptest! { *x = b; } } - survive("mutated .ai editing data", || Some(vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![]).0))?; + survive("mutated .ai editing data", || Some(vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false).0))?; } } @@ -1886,9 +1886,13 @@ proptest! { fn ai_hostile_editing_data_never_panics(tokens in prop::collection::vec(arb_ai_token(), 0..80)) { use vectorcraft_testkit::ai; let data = ai::editing_data(200.0, 100.0, &format!("%AI5_BeginLayer\n1 1 1 1 0 0 1 0 79 128 255 0 50 0 Lb\n(L) Ln\n{}\nLB\n", tokens.join(" "))); - survive("hostile editing data", || Some(vectorcraft_eps::layered_ai(data.as_bytes(), Document::new(200.0, 100.0), vec![]).0))?; + survive("hostile editing data", || Some(vectorcraft_eps::layered_ai(data.as_bytes(), Document::new(200.0, 100.0), vec![], false).0))?; + survive("hostile editing data, type as outlines", || Some(vectorcraft_eps::layered_ai(data.as_bytes(), Document::new(200.0, 100.0), vec![], true).0))?; let eps = ai::eps(data.as_bytes(), ai::page_ps()); survive("hostile editing data in an EPS", || vectorcraft_engine::cmd::fileio::load("x.eps", &eps).ok().map(|l| l.doc))?; + // An EPS whose page is its art's box, not its artboard: what prints outside it is compared too. + let boxed = ai::eps(data.replace("%AI3_Cropmarks: 0 0 200 100", "%AI3_Cropmarks: -50 -50 300 200").as_bytes(), ai::page_ps()); + survive("hostile editing data in an EPS of its art's box", || vectorcraft_engine::cmd::fileio::load("x.eps", &boxed).ok().map(|l| l.doc))?; } /// The testkit's sample damaged, as it is and compressed, in EPS and `.ai` files. diff --git a/crates/eps/src/import/mod.rs b/crates/eps/src/import/mod.rs index 9ce6e72b..8dac8a78 100644 --- a/crates/eps/src/import/mod.rs +++ b/crates/eps/src/import/mod.rs @@ -166,8 +166,15 @@ fn reason(e: &PsError, fault: Option<&Fault>) -> String { } } -/// Read an EPS or PostScript file (its first page). +/// Read an EPS or PostScript file (its first page), an Illustrator EPS through the editing copy of +/// its art when it carries one (see `native`). pub fn import(bytes: &[u8]) -> Result { + import_with(bytes, true) +} + +/// [`import`], an Illustrator EPS through the editing copy of its art only when `editing_data` +/// (else what its page prints, as any EPS). +pub fn import_with(bytes: &[u8], editing_data: bool) -> Result { let (ps, _) = crate::sections(bytes).ok_or("the file's preview header points outside the file")?; if !ps.starts_with(b"%!") { return Err("this is not a PostScript file".into()); @@ -189,7 +196,8 @@ pub fn import(bytes: &[u8]) -> Result { } let drew = !out.drawn.is_empty(); let why = match (&result, drew) { - (Ok(()), true) => return Ok(native::layered(ps, finish(out))), + (Ok(()), true) if editing_data => return Ok(native::layered(ps, finish(out))), + (Ok(()), true) => return Ok(finish(out)), (Ok(()), false) => "it draws nothing VectorCraft's PostScript reader can show".to_string(), (Err(e), _) => reason(e, fault.as_ref()), }; diff --git a/crates/eps/src/import/native.rs b/crates/eps/src/import/native.rs index 6c4e2bf5..26febde8 100644 --- a/crates/eps/src/import/native.rs +++ b/crates/eps/src/import/native.rs @@ -15,7 +15,9 @@ //! //! What a layer that shows has that `ai` doesn't read makes the file come in as its page, as it did //! before; on a layer that doesn't show it is left out of that layer, with a warning. The page is -//! also the safety net: when the layers' art looks different from it, the page is used. +//! also the safety net: when the layers' art looks different from it (one draws an object the +//! other doesn't, or much of it differs; an EPS whose page is its art's box has nothing printed +//! outside it), the page is used. //! //! Where a file doesn't match what this module expects, it is left alone and its page is imported. @@ -550,10 +552,49 @@ fn as_printed(doc: &Document) -> Option { hide(&mut d.layers).then_some(d) } -/// The lightness (0 to 255, Rec. 601 weights) of a premultiplied pixel seen on white. -fn lightness(p: &[u8; 4]) -> u8 { - let on_white = |c: u8| u32::from(c) + 255 - u32::from(p[3]).min(255); - ((on_white(p[0]) * 299 + on_white(p[1]) * 587 + on_white(p[2]) * 114) / 1000).min(255) as u8 +/// A premultiplied pixel seen on white. +fn on_white(p: &[u8; 4]) -> [u32; 3] { + let paper = 255 - u32::from(p[3]).min(255); + [0, 1, 2].map(|i| (u32::from(p[i]) + paper).min(255)) +} + +/// The lightness (0 to 255, Rec. 601 weights) of a pixel seen on white. +fn lightness([r, g, b]: [u32; 3]) -> u32 { + (r * 299 + g * 587 + b * 114) / 1000 +} + +/// How far (0 to 255) a pixel seen on white is from white: how much ink it has. +fn ink([r, g, b]: [u32; 3]) -> u32 { + 255 - r.min(g).min(b) +} + +/// How far apart two pixels' lightness, or their ink where one is white, may be for them to look +/// alike. +const SAME_PIXEL: u32 = 48; +/// The most ink a pixel seen as white has. +const WHITE: u32 = 8; + +/// Do two pixels look different: in lightness, or one inked (as a light yellow is) where the other +/// is white? +fn differ(p: &[u8; 4], q: &[u8; 4]) -> bool { + let (p, q) = (on_white(p), on_white(q)); + let (a, b) = (ink(p), ink(q)); + lightness(p).abs_diff(lightness(q)) > SAME_PIXEL || (a.min(b) <= WHITE && a.abs_diff(b) > SAME_PIXEL) +} + +/// How much two documents draw differently: the share (0 to 1) of the pixels that differ, and of +/// those whose neighbours all differ too, away from type (where one draws an object that the other +/// doesn't, not the edges of one drawn a little differently, or type laid out a little +/// differently: a line the page sets in pieces is laid out afresh as one). +#[derive(Clone, Copy)] +struct Difference { + any: f64, + solid: f64, +} + +/// The scale the comparisons draw a region at: about 400 pixels along its longer side. +fn compare_scale(r: Rect) -> f64 { + (400.0 / r.width().max(r.height()).max(1.0)).min(4.0) } /// The page drawn once, to weigh the layers' art against it: [`Self::difference`] draws the layers @@ -561,6 +602,8 @@ fn lightness(p: &[u8; 4]) -> u8 { /// can share their keys and not their pixels, so the two don't share one). struct PageView { page: vectorcraft_render::Rendered, + /// Where the page's own type is, in its pixels. + page_type: Vec, layers: vectorcraft_render::Renderer, scale: f64, } @@ -568,36 +611,118 @@ struct PageView { impl PageView { fn new(frame: &Frame<'_>) -> Self { let ra = frame.page_rect; - let scale = (400.0 / ra.width().max(ra.height()).max(1.0)).min(4.0); + let scale = compare_scale(ra); // Drawn on nothing and then seen on white: blending modes have no page to blend with, as in // the app that wrote the file. let page = vectorcraft_render::Renderer::new().render_region(frame.page, ra, scale, false); - Self { page, layers: vectorcraft_render::Renderer::new(), scale } + let mut page_type = vec![]; + type_areas(&frame.page.layers, ra, scale, &mut page_type); + Self { page, page_type, layers: vectorcraft_render::Renderer::new(), scale } } - /// How much `b` on `rb` (a rectangle the page's size) draws differently from the page (0 to 1), - /// each seen on white. Pixels are compared by lightness: the page of an RGB document is written in - /// the colours' CMYK equivalents, and what the comparison looks for is art that is missing or out - /// of place. - fn difference(&mut self, b: &Document, rb: Rect) -> f64 { + /// How `b` on `rb` (a rectangle the page's size) draws differently from the page ([`compared`]). + fn difference(&mut self, b: &Document, rb: Rect) -> Difference { // The page doesn't print what isn't printed. let printed = as_printed(b); let b = printed.as_ref().unwrap_or(b); - let (x, y) = (&self.page, self.layers.render_region(b, rb, self.scale, false)); - if x.width != y.width || x.height != y.height { - return 1.0; - } - let differing = - x.pixels.as_chunks::<4>().0.iter().zip(y.pixels.as_chunks::<4>().0).filter(|(p, q)| lightness(p).abs_diff(lightness(q)) > 48).count(); - differing as f64 / (f64::from(x.width) * f64::from(x.height)).max(1.0) + let y = self.layers.render_region(b, rb, self.scale, false); + let mut areas = self.page_type.clone(); + type_areas(&b.layers, rb, self.scale, &mut areas); + compared(&self.page, &y, &areas) } } +/// How `a` on `ra` and `b` on `rb` (rectangles of the same size) draw differently ([`compared`]), +/// for a region other than the page's ([`PageView`] draws that one once). +fn difference(a: &Document, ra: Rect, b: &Document, rb: Rect) -> Difference { + let printed = as_printed(b); + let b = printed.as_ref().unwrap_or(b); + let scale = compare_scale(ra); + // A renderer each: the two documents' images can share their keys and not their pixels. + let x = vectorcraft_render::Renderer::new().render_region(a, ra, scale, false); + let y = vectorcraft_render::Renderer::new().render_region(b, rb, scale, false); + let mut areas = vec![]; + type_areas(&a.layers, ra, scale, &mut areas); + type_areas(&b.layers, rb, scale, &mut areas); + compared(&x, &y, &areas) +} + +/// How two drawings of the same size differ, each drawn on nothing and seen on white, away from +/// the type in `areas` (pixels). Pixels are compared by lightness, and by whether they are inked +/// at all ([`differ`]): the page of an RGB document is written in the colours' CMYK equivalents, +/// and what the comparison looks for is art that is missing or out of place. +fn compared(x: &vectorcraft_render::Rendered, y: &vectorcraft_render::Rendered, areas: &[Rect]) -> Difference { + if x.width != y.width || x.height != y.height { + return Difference { any: 1.0, solid: 1.0 }; + } + let differs: Vec = x.pixels.as_chunks::<4>().0.iter().zip(y.pixels.as_chunks::<4>().0).map(|(p, q)| differ(p, q)).collect(); + let (w, h) = (x.width as usize, x.height as usize); + let at = |i: usize, j: usize| j.checked_mul(w).and_then(|row| row.checked_add(i)).and_then(|k| differs.get(k)).copied().unwrap_or(false); + let typed = covered(areas, w, h); + // A pixel on the region's edge has neighbours outside it, which don't count as differing. + let solid = (1..h.saturating_sub(1)) + .flat_map(|j| (1..w.saturating_sub(1)).map(move |i| (i, j))) + .filter(|&(i, j)| !typed.get(j * w + i).copied().unwrap_or(true) && (j - 1..=j + 1).all(|n| (i - 1..=i + 1).all(|m| at(m, n)))) + .count(); + let area = (w as f64 * h as f64).max(1.0); + Difference { any: differs.iter().filter(|d| **d).count() as f64 / area, solid: solid as f64 / area } +} + +/// Where the type that shows in `nodes` is, in pixels of `region` drawn at `scale` (with a margin +/// for the strokes round it). +fn type_areas(nodes: &[Arc], region: Rect, scale: f64, out: &mut Vec) { + for n in nodes.iter().filter(|n| n.visible) { + if let NodeKind::Text(_) = n.kind + && let Some(b) = n.visual_bounds() + { + let px = + |r: Rect| Rect::new((r.x0 - region.x0) * scale, (r.y0 - region.y0) * scale, (r.x1 - region.x0) * scale, (r.y1 - region.y0) * scale); + out.push(px(b.inflate(OUTLINE_REACH, OUTLINE_REACH))); + } else if let Some(c) = n.children() { + type_areas(c, region, scale, out); + } + } +} + +/// Which of `w` × `h` pixels (row by row) lie in one of `areas`. +fn covered(areas: &[Rect], w: usize, h: usize) -> Vec { + // Each area adds one inside it: corners marked, then summed along the rows and down the columns. + let stride = w + 1; + let mut count = vec![0i64; stride * (h + 1)]; + let clamp = |v: f64, max: usize| if v.is_finite() { v.clamp(0.0, max as f64) as usize } else { 0 }; + for r in areas { + let (x0, y0, x1, y1) = (clamp(r.x0.floor(), w), clamp(r.y0.floor(), h), clamp(r.x1.ceil(), w), clamp(r.y1.ceil(), h)); + for (x, y, d) in [(x0, y0, 1), (x1, y0, -1), (x0, y1, -1), (x1, y1, 1)] { + if let Some(c) = count.get_mut(y * stride + x) { + *c += d; + } + } + } + for row in count.chunks_mut(stride) { + let mut run = 0; + for c in row { + run += *c; + *c = run; + } + } + let mut column = vec![0i64; stride]; + for row in count.chunks_mut(stride) { + for (c, sum) in row.iter_mut().zip(column.iter_mut()) { + *sum += *c; + *c = *sum; + } + } + (0..h).flat_map(|j| (0..w).map(move |i| (i, j))).map(|(i, j)| count.get(j * stride + i).is_some_and(|c| *c > 0)).collect() +} + /// More of the page than this differing between the layers' art and the page's own, and the /// layers aren't used. const MAX_DIFFERENCE: f64 = 0.05; /// More than this and the import says so. const NOTABLE_DIFFERENCE: f64 = 0.002; +/// More of the page than this where one draws an object that the other doesn't (see +/// [`Difference`]), and the layers aren't used: about a centimetre square on a letter page. +const MAX_SOLID_DIFFERENCE: f64 = 0.001; /// Which box of the editing copy is the page. #[derive(Clone, Copy)] @@ -616,13 +741,17 @@ struct Frame<'a> { page_rect: Rect, /// The same area in the layers' document. rect: Rect, + /// The page holds all the art that prints (an EPS's page is its art's box, unless it was + /// saved as its artboard): the layers print nothing outside it. + whole: bool, } /// The document of the editing copy `data`, with the text (and strokes round it) of `visible`, the /// file read as its page, put in its text objects → the document and its notes. Without a page /// (a `.ai` saved without its PDF part), its type is made from the file's text document alone and -/// nothing is compared. -fn build(data: &[u8], visible: Option<&Document>, page: Page) -> Result<(Document, Vec), String> { +/// nothing is compared. `outlined`: the page's type was read as outlines, so it has none to put in +/// the text objects. +fn build(data: &[u8], visible: Option<&Document>, page: Page, outlined: bool) -> Result<(Document, Vec), String> { let Structure { mut doc, to_doc, bbox, artboard, template, hidden_unread, slot_names, warnings } = ai::read(data)?; let (mut shown, mut hidden) = (vec![], vec![]); let mut frame = None; @@ -648,10 +777,18 @@ fn build(data: &[u8], visible: Option<&Document>, page: Page) -> Result<(Documen Arc::make_mut(n).transform(shift, false); } } - frame = Some(Frame { page: visible, page_rect, rect }); + // An EPS saved as its artboard has the art outside it left out of its page. + let artboard_page = + artboard.is_some_and(|a| [a.x0 - art_box.x0, a.y0 - art_box.y0, a.x1 - art_box.x1, a.y1 - art_box.y1].iter().all(|d| d.abs() <= 1.0)); + let whole = matches!(page, Page::Art) && !artboard_page; + frame = Some(Frame { page: visible, page_rect, rect, whole }); } let mut infos = vec![]; collect_slots(&doc.layers, true, &mut infos); + // Type asked for as outlines is the page's: the text objects that show can't be filled. + if outlined && infos.iter().any(|i| i.shown) { + return Err("its type is to come in as outlines, which only its page has".into()); + } if infos.iter().all(|i| !i.shown) && !shown.is_empty() { return Err("its page has text, and its layers have no text objects to put it in".into()); } @@ -753,7 +890,7 @@ fn prune_unseen(frame: &Frame<'_>, view: &mut PageView, doc: &mut Document) -> u if found.is_empty() || found.len() > MAX_WEIGHED { return 0; } - let mut with = view.difference(doc, rect); + let mut with = view.difference(doc, rect).any; let mut removed = 0; for (id, bounds) in found { if bounds.is_none_or(|b| b.intersect(rect).is_zero_area()) { @@ -763,7 +900,7 @@ fn prune_unseen(frame: &Frame<'_>, view: &mut PageView, doc: &mut Document) -> u if !take_out(&mut without.layers, id, true) { continue; } - let d = view.difference(&without, rect); + let d = view.difference(&without, rect).any; if d - with <= UNSEEN_MARGIN { take_out(&mut doc.layers, id, false); with = d; @@ -773,17 +910,30 @@ fn prune_unseen(frame: &Frame<'_>, view: &mut PageView, doc: &mut Document) -> u removed } -/// Do the layers' art and the page's own look alike? An error says they don't; `Ok` has the note -/// to give when they differ a little. +/// How far (points) the art the layers print may reach past a page that holds it all. +const PAST_THE_PAGE: f64 = 1.0; + +/// Do the layers' art and the page's own look alike (where the page holds all the art that prints, +/// also round it)? An error says they don't; `Ok` has the note to give when they differ a little. fn compare(frame: &Frame<'_>, view: &mut PageView, layered: &Document) -> Result, String> { - let diff = view.difference(layered, frame.rect); - if diff > MAX_DIFFERENCE { - return Err(format!("the art on them differs from the page's in {:.0}% of it", diff * 100.0)); + let mut diff = view.difference(layered, frame.rect); + if frame.whole + && let Some(art) = vectorcraft_render::encode::art_bounds(as_printed(layered).as_ref().unwrap_or(layered)) + .filter(|a| !frame.rect.inflate(PAST_THE_PAGE, PAST_THE_PAGE).contains_rect(*a)) + { + // The page and the art the layers print beyond it, each in its own document's place. + let all = frame.rect.union(art); + let (dx, dy) = (frame.page_rect.x0 - frame.rect.x0, frame.page_rect.y0 - frame.rect.y0); + let round = difference(frame.page, Rect::new(all.x0 + dx, all.y0 + dy, all.x1 + dx, all.y1 + dy), layered, all); + diff = Difference { any: diff.any.max(round.any), solid: diff.solid.max(round.solid) }; } - Ok((diff > NOTABLE_DIFFERENCE).then(|| { + if diff.any > MAX_DIFFERENCE || diff.solid > MAX_SOLID_DIFFERENCE { + return Err(format!("the art on them differs from the page's in {:.1}% of it", diff.any * 100.0)); + } + Ok((diff.any > NOTABLE_DIFFERENCE).then(|| { format!( "the art on the layers differs from the file's own page in about {:.1}% of it (brush strokes, live effects and the like that the layers' data doesn't describe)", - diff * 100.0 + diff.any * 100.0 ) })) } @@ -794,7 +944,7 @@ fn compare(frame: &Frame<'_>, view: &mut PageView, layered: &Document) -> Result /// has one that can't be used, `visible` with a warning that says why. pub(super) fn layered(ps: &[u8], visible: Imported) -> Imported { let Some(data) = ai::eps_data(ps) else { return visible }; - let result = data.and_then(|data| build(&data, Some(&visible.document), Page::Art)); + let result = data.and_then(|data| build(&data, Some(&visible.document), Page::Art, false)); match result { Ok((document, mut warnings)) => { for w in &visible.warnings { @@ -816,12 +966,14 @@ pub(super) fn layered(ps: &[u8], visible: Imported) -> Imported { /// `AIPrivateData` streams) instead, as [`layered`] reads an EPS: with the layers and objects of the /// file, its artboards, and the art that lies outside them, which its PDF part doesn't have. /// `warnings` are the notes of reading the PDF part; the notes returned are those, and the layers'. -pub fn layered_ai(private: &[u8], visible: Document, warnings: Vec) -> (Document, Vec) { +/// `outlined`: the PDF part's type was read as outlines (a file whose type shows then comes in as +/// its PDF part). +pub fn layered_ai(private: &[u8], visible: Document, warnings: Vec, outlined: bool) -> (Document, Vec) { let Ok(data) = ai::decode_private(private) else { return (visible, warnings) }; if !data.windows(15).any(|w| w == b"%AI5_BeginLayer") { return (visible, warnings); } - match build(&data, Some(&visible), Page::Artboard) { + match build(&data, Some(&visible), Page::Artboard, outlined) { Ok((done, notes)) => { let mut all = warnings; all.extend(notes.into_iter().filter(|n| !all.contains(n)).collect::>()); @@ -839,7 +991,7 @@ pub fn layered_ai(private: &[u8], visible: Document, warnings: Vec) -> ( /// alone (`private`, the joined `AIPrivateData` streams) → the document and the import's notes. pub fn ai_alone(private: &[u8]) -> Result<(Document, Vec), String> { let data = ai::decode_private(private)?; - build(&data, None, Page::Artboard) + build(&data, None, Page::Artboard, false) } #[cfg(test)] diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index 1483b5cf..2140553f 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -215,7 +215,7 @@ fn pdf_part(x: f64, y: f64) -> Document { fn an_ai_file_gets_its_layers_and_the_art_outside_its_artboard() { // A square on the artboard, and one above it (the artboard is y 0 to 100 here). let art = native(&(layer("Jig", true, &square(10, 10)) + &layer("Parts", true, &square(30, 110)) + &layer("Old", false, &square(60, 60)))); - let (d, warnings) = crate::layered_ai(&private(&art), pdf_part(10.0, 86.0), vec!["a note".into()]); + let (d, warnings) = crate::layered_ai(&private(&art), pdf_part(10.0, 86.0), vec!["a note".into()], false); assert_eq!(names(&d), ["Jig", "Parts", "Old"], "{warnings:?}"); assert_eq!(warnings, ["a note"], "nothing else to say"); let above = d.layers[1].children().unwrap()[0].visual_bounds().unwrap(); @@ -227,12 +227,12 @@ fn an_ai_file_gets_its_layers_and_the_art_outside_its_artboard() { fn an_ai_file_that_cant_be_read_through_its_editing_data_keeps_its_pdf_part() { let pdf = pdf_part(10.0, 86.0); // No editing data this reads. - let (d, w) = crate::layered_ai(b"nothing", pdf.clone(), vec![]); + let (d, w) = crate::layered_ai(b"nothing", pdf.clone(), vec![], false); assert_eq!(d.layers.len(), pdf.layers.len()); assert!(w.is_empty()); // Editing data that isn't for this page. let other = native(&layer("Jig", true, &square(10, 10))).replace("%AI3_Cropmarks: 0 0 100 100", "%AI3_Cropmarks: 0 0 50 50"); - let (d, w) = crate::layered_ai(&private(&other), pdf.clone(), vec![]); + let (d, w) = crate::layered_ai(&private(&other), pdf.clone(), vec![], false); assert_eq!(names(&d), names(&pdf)); assert!(w.iter().any(|w| w.contains("different page")), "{w:?}"); } @@ -280,7 +280,7 @@ fn custom_colours_open_paths_and_planar_group_marks_are_read() { let body = "0.1 0.2 0.3 0.4 (Spot) 0 x\n0 0 0 1 (Edge) 0 X\n10 10 m\n14 10 L\n14 14 L\n10 14 L\nf\n\ 0.8 0.1 0 0 62.7 -28 -42 (Blue) 0 2 Xx\n(Adobe Planar Group) 1 0 0 XP\n20 20 m\n24 20 L\n24 24 L\nH\nF"; let r = import(&older_eps( - "0 0 0 0 setcmykcolor 10 10 moveto 14 10 lineto 14 14 lineto 10 14 lineto closepath fill", + "0.1 0.2 0.3 0.4 setcmykcolor 10 10 moveto 14 10 lineto 14 14 lineto 10 14 lineto closepath fill 0.8 0.1 0 0 setcmykcolor 20 20 moveto 24 20 lineto 24 24 lineto closepath fill", &native(&layer("Art", true, body)), )) .unwrap(); @@ -399,9 +399,9 @@ fn shown_type_keeps_the_pages_and_type_off_the_page_comes_from_the_text_document fn a_text_object_written_as_comments_is_read_like_any_other() { let doc = text_document(&[("Hi\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]); let commented: String = text_object(0).lines().map(|l| format!("%_{l}\n")).collect(); - let art = native_with_text(&layer("Spare", false, &(square(10, 10) + "\n" + &commented)), &doc); + let art = native_with_text(&(layer("Back", true, &square(10, 10)) + &layer("Spare", false, &commented)), &doc); let r = import(&eps(&page_square(10, 10), &art)).unwrap(); - let texts = text_of(&r.document.layers[0]); + let texts = text_of(&r.document.layers[1]); assert_eq!(texts.len(), 1, "{:?}", r.warnings); assert_eq!(texts[0].plain_text(), "Hi"); } @@ -453,9 +453,9 @@ fn a_commented_copy_of_a_story_that_has_a_plain_text_object_is_not_another_objec let doc = text_document(&[("One\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0), ("Two\r", 0, (8300.0, 8180.0), (0.0, 0.0), 0.0)]); let commented = |story| -> String { text_object(story).lines().map(|l| format!("%_{l}\n")).collect() }; let body = text_object(0) + &commented(0) + &commented(1); - let art = native_with_text(&layer("Spare", false, &body), &doc); + let art = native_with_text(&(layer("Back", true, &square(10, 10)) + &layer("Spare", false, &body)), &doc); let r = import(&eps(&page_square(10, 10), &art)).unwrap(); - let texts: Vec = text_of(&r.document.layers[0]).iter().map(|t| t.plain_text()).collect(); + let texts: Vec = text_of(&r.document.layers[1]).iter().map(|t| t.plain_text()).collect(); assert_eq!(texts, ["One", "Two"], "{:?}", r.warnings); } @@ -542,3 +542,67 @@ fn an_ai_file_without_its_pdf_part_reads_its_layers_and_makes_its_type() { assert!(!notes.iter().any(|n| n.contains("order the page paints")), "{notes:?}"); assert!(crate::ai_alone(b"%AI24_ZStandard_Data nothing").is_err()); } + +#[test] +fn an_object_the_page_doesnt_draw_makes_the_file_come_in_as_its_page() { + // A 20-point square that the page doesn't draw: 4% of the page, and an object all the same. + let extra = "0 0 1 0 k\n50 50 m\n70 50 L\n70 70 L\n50 70 L\nf"; + let art = native(&layer("Back", true, &(square(10, 10) + "\n" + extra))); + let r = import(&eps(&page_square(10, 10), &art)).unwrap(); + assert_eq!(names(&r.document), ["Layer 1"], "{:?}", r.warnings); + assert!(r.warnings.iter().any(|w| w.contains("layers weren't read") && w.contains("differs from the page's")), "{:?}", r.warnings); +} + +/// An EPS whose page is its art's box `[x0 y0 x1 y1]` (not its artboard, 0 0 100 100), drawing +/// `page`, with the editing copy of `layers`. +fn eps_of_art(art_box: [u32; 4], page: &str, layers: &str) -> Vec { + let [x0, y0, x1, y1] = art_box; + let native = native(layers).replace( + "%%BoundingBox: 0 0 100 100\n%%HiResBoundingBox: 0 0 100 100", + &format!("%%BoundingBox: {x0} {y0} {x1} {y1}\n%%HiResBoundingBox: {x0} {y0} {x1} {y1}"), + ); + String::from_utf8(eps(page, &native)) + .unwrap() + .replacen("%%BoundingBox: 0 0 100 100", &format!("%%BoundingBox: {x0} {y0} {x1} {y1}"), 1) + .into_bytes() +} + +#[test] +fn art_the_layers_print_outside_an_eps_page_of_its_art_makes_it_come_in_as_its_page() { + // The page is the box of the art it prints, round the square at (10, 10). + let file = |far: &str| eps_of_art([10, 10, 14, 14], &page_square(10, 10), &(layer("Art", true, &square(10, 10)) + far)); + // A square the layers print far from it: the page would have it. + let r = import(&file(&layer("Far", true, &square(80, 80)))).unwrap(); + assert_eq!(names(&r.document), ["Layer 1"], "{:?}", r.warnings); + assert!(r.warnings.iter().any(|w| w.contains("layers weren't read")), "{:?}", r.warnings); + // Hidden, or on a layer that doesn't print, the page doesn't have it. + let r = import(&file(&layer("Far", false, &square(80, 80)))).unwrap(); + assert_eq!(names(&r.document), ["Art", "Far"], "{:?}", r.warnings); + let not_printed = format!("%AI5_BeginLayer\n1 1 1 0 0 0 1 0 79 128 255 0 50 0 Lb\n(Notes) Ln\n{}\nLB\n%AI5_EndLayer--\n", square(80, 80)); + let r = import(&file(¬_printed)).unwrap(); + assert_eq!(names(&r.document), ["Art", "Notes"], "{:?}", r.warnings); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); +} + +#[test] +fn an_eps_saved_as_its_artboard_keeps_the_art_outside_it() { + // The page is the artboard (0 0 100 100): the art beyond it is the pasteboard's. + let art = native(&(layer("Art", true, &square(10, 10)) + &layer("Scraps", true, &square(120, 10)))); + let r = import(&eps(&page_square(10, 10), &art)).unwrap(); + assert_eq!(names(&r.document), ["Art", "Scraps"], "{:?}", r.warnings); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); +} + +#[test] +fn type_asked_for_as_outlines_leaves_a_file_whose_type_shows_as_its_pdf_part() { + let doc = text_document(&[("Hi\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]); + // Type that shows: the PDF part's outlines are its type, which the text objects can't hold. + let shown = native_with_text(&layer("Art", true, &(square(10, 10) + "\n" + &text_object(0))), &doc); + let (d, w) = crate::layered_ai(&private(&shown), pdf_part(10.0, 86.0), vec![], true); + assert_eq!(names(&d), ["Layer 1"], "{w:?}"); + assert!(w.iter().any(|w| w.contains("layers weren't read") && w.contains("outlines")), "{w:?}"); + // Type only on a hidden layer: the layers come in. + let hidden = native_with_text(&(layer("Art", true, &square(10, 10)) + &layer("Notes", false, &text_object(0))), &doc); + let (d, w) = crate::layered_ai(&private(&hidden), pdf_part(10.0, 86.0), vec![], true); + assert_eq!(names(&d), ["Art", "Notes"], "{w:?}"); +} diff --git a/crates/eps/src/lib.rs b/crates/eps/src/lib.rs index 56a7ec21..7959f960 100644 --- a/crates/eps/src/lib.rs +++ b/crates/eps/src/lib.rs @@ -34,7 +34,7 @@ mod ps; mod scene; mod tiff; -pub use import::{Imported, ai_alone, family_style, import, is_loss, layered_ai}; +pub use import::{Imported, ai_alone, family_style, import, import_with, is_loss, layered_ai}; pub use print::{PrintJob, PrintPage, print}; use vectorcraft_doc::Document; diff --git a/crates/render/src/encode/mod.rs b/crates/render/src/encode/mod.rs index fd8338bb..d3fd5054 100644 --- a/crates/render/src/encode/mod.rs +++ b/crates/render/src/encode/mod.rs @@ -86,7 +86,7 @@ impl RasterExportOptions { self.ppi / 72.0 } - /// What the renderer draws for `format`: template layers left out, over the background + /// What the renderer draws for `format`: template layers and guides left out, over the background /// (white for a JPEG or a flat PSD without one). pub fn render_options(&self, format: RasterFormat) -> RenderOptions { let flat = format == RasterFormat::Jpeg || (format == RasterFormat::Psd && !self.psd.layers); @@ -193,7 +193,7 @@ fn drawn_bounds(n: &Node) -> Option { } match &n.kind { NodeKind::Layer { template: true, .. } | NodeKind::Path { guide: true, .. } => None, - NodeKind::Layer { children, .. } | NodeKind::Group { children, clip: false } => { + NodeKind::Layer { children, clip: false, .. } | NodeKind::Group { children, clip: false } => { children.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, drawn_bounds(c))) } _ if fx::has_fx(n) => fx::visual_bounds(n), diff --git a/crates/render/src/encode/tests.rs b/crates/render/src/encode/tests.rs index e5192e78..43233ae1 100644 --- a/crates/render/src/encode/tests.rs +++ b/crates/render/src/encode/tests.rs @@ -189,3 +189,35 @@ fn art_bounds_cover_visible_art_only() { let empty = Document::new(10.0, 10.0); assert_eq!(art_bounds(&empty), None); } + +/// A black path round `r` in the first layer of `d`, made a guide when `guide`. +fn add_rect(d: &mut Document, r: Rect, guide: bool) { + let id = d.alloc_id(); + let mut n = Node::path(id, shapes::rectangle(r), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0)); + if let NodeKind::Path { guide: g, .. } = &mut n.kind { + *g = guide; + } + let l = d.layers[0].id; + d.insert(Some(l), 0, n).unwrap(); +} + +#[test] +fn guides_dont_count_in_the_arts_bounds() { + let mut d = circle_doc(); + add_rect(&mut d, Rect::new(0.0, 15.0, 400.0, 15.0), true); + let b = art_bounds(&d).unwrap(); + assert!((b.x0 - 5.3).abs() < 1e-6 && (b.x1 - 31.1).abs() < 1e-6, "the guide doesn't count: {b:?}"); +} + +#[test] +fn art_bounds_end_at_a_clipping_layers_clip() { + let mut d = Document::new(40.0, 30.0); + // The layer clips its art to its first object (added last): what lies beyond isn't drawn. + add_rect(&mut d, Rect::new(-100.0, -100.0, 200.0, 200.0), false); + add_rect(&mut d, Rect::new(2.0, 3.0, 20.0, 10.0), false); + let layer = std::sync::Arc::make_mut(&mut d.layers[0]); + if let NodeKind::Layer { clip, .. } = &mut layer.kind { + *clip = true; + } + assert_eq!(art_bounds(&d), Some(Rect::new(2.0, 3.0, 20.0, 10.0))); +} diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 9a9899a7..156a3fe2 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -582,7 +582,7 @@ impl Renderer { } /// Render one artboard (or any document rect) at `scale` pixels per point, transparent or on white, - /// as exported: template layers are left out. + /// as exported: template layers and guides are left out. pub fn render_region(&mut self, doc: &Document, region: Rect, scale: f64, white: bool) -> Rendered { let opts = RenderOptions { background: white.then_some([255, 255, 255, 255]), skip_templates: true, ..Default::default() }; self.render_region_with(doc, region, scale, &opts) diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 6d87027b..62677621 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -3170,6 +3170,7 @@ axis Both Ambos @msg its editing data is for a different page sus datos de edición son de otra página @msg its layers use {_1}, which aren't read yet sus capas usan {_1}, que aún no se leen @msg its page has text, and its layers have no text objects to put it in su página tiene texto y sus capas no tienen objetos de texto donde ponerlo +@msg its type is to come in as outlines, which only its page has su texto debe llegar como contornos, y solo su página los tiene @msg the art on them differs from the page's in {_1}% of it el arte de las capas difiere del de la página en el {_1} % de su superficie @msg `to` must be "corner" or "smooth" `to` debe ser "corner" o "smooth" @msg BMP files are RGB or grayscale: colorModel rgb or gray los archivos BMP son RGB o en escala de grises: colorModel rgb o gray diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 7e3b4820..4faafcb7 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3167,6 +3167,7 @@ axis Both Les deux @msg its editing data is for a different page ses données de modification concernent une autre page @msg its layers use {_1}, which aren't read yet ses calques utilisent {_1}, qui ne sont pas encore lus @msg its page has text, and its layers have no text objects to put it in sa page contient du texte, et ses calques n’ont aucun objet texte où le mettre +@msg its type is to come in as outlines, which only its page has son texte doit être importé sous forme de contours vectorisés, que seule sa page contient @msg the art on them differs from the page's in {_1}% of it le dessin des calques diffère de celui de la page sur {_1} % de sa surface @msg `to` must be "corner" or "smooth" `to` doit être "corner" ou "smooth" @msg BMP files are RGB or grayscale: colorModel rgb or gray Les fichiers BMP sont en RVB ou en niveaux de gris : colorModel rgb ou gray diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 1c1208f8..6532854a 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -3170,6 +3170,7 @@ axis Both Entrambi @msg its editing data is for a different page i suoi dati di modifica sono di un'altra pagina @msg its layers use {_1}, which aren't read yet i suoi livelli usano {_1}, che non vengono ancora letti @msg its page has text, and its layers have no text objects to put it in la sua pagina ha del testo e i suoi livelli non hanno oggetti di testo in cui metterlo +@msg its type is to come in as outlines, which only its page has il suo testo deve arrivare come contorni, che ha solo la sua pagina @msg the art on them differs from the page's in {_1}% of it l'illustrazione dei livelli differisce da quella della pagina per il {_1}% della sua superficie @msg `to` must be "corner" or "smooth" `to` deve essere "corner" o "smooth" @msg BMP files are RGB or grayscale: colorModel rgb or gray I file BMP sono RGB o in scala di grigi: colorModel rgb o gray diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 37310f43..fa38398c 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3177,6 +3177,7 @@ theme Appearance 外観 @msg it has more than one artboard アートボードが複数あります @msg its editing data has no layers 編集データにレイヤーがありません @msg its editing data is damaged 編集データが破損しています +@msg its type is to come in as outlines, which only its page has 文字をアウトラインとして読み込む設定ですが、アウトラインはページにしかありません @msg {_1} files {_1} 個のファイル @msg A browser with WebGPU or WebGL2 is required. WebGPU または WebGL2 に対応したブラウザーが必要です。 @msg Loading VectorCraft… VectorCraft を読み込んでいます… diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index b8b804da..6f88ab3e 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -3166,6 +3166,7 @@ axis Both Оба @msg its editing data is for a different page его данные для редактирования относятся к другой странице @msg its layers use {_1}, which aren't read yet его слои используют {_1}, что пока не читается @msg its page has text, and its layers have no text objects to put it in на его странице есть текст, а на слоях нет текстовых объектов, куда его поместить +@msg its type is to come in as outlines, which only its page has его текст должен прийти в виде контуров, а они есть только на его странице @msg the art on them differs from the page's in {_1}% of it изображение на слоях отличается от изображения на странице на {_1} % площади @msg `to` must be "corner" or "smooth" `to` должно быть "corner" или "smooth" @msg BMP files are RGB or grayscale: colorModel rgb or gray файлы BMP бывают RGB или в оттенках серого: colorModel rgb или gray diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index e3778469..4d00da15 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -3153,6 +3153,7 @@ axis Both Обидві @msg its editing data is for a different page його дані для редагування відносяться до іншої сторінки @msg its layers use {_1}, which aren't read yet його шари використовують {_1}, що поки не читається @msg its page has text, and its layers have no text objects to put it in на його сторінці є текст, а на шарах немає текстових об’єктів, куди його помістити +@msg its type is to come in as outlines, which only its page has його текст має прийти у вигляді контурів, а вони є лише на його сторінці @msg the art on them differs from the page's in {_1}% of it зображення на шарах відрізняється від зображення на сторінці на {_1} % площі @msg `to` must be "corner" or "smooth" `to` має бути "corner" або "smooth" @msg BMP files are RGB or grayscale: colorModel rgb or gray Файли BMP бувають RGB або у відтінках сірого: colorModel rgb або gray diff --git a/docs/mcp.md b/docs/mcp.md index a673e4f6..c4ee8a06 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -416,7 +416,19 @@ strokes, effects or a brush comes in as its drawn look (a group named after it). text object's place; hidden point type is made from the file's text document. A file whose editing data has symbols, pattern fills, placed files or anything else the reader doesn't read on a layer that shows, or whose layers look different from its page, opens as before: an EPS as its printed page, a `.ai` file from its PDF content (where plain -groups open ungrouped), with a warning saying why. +groups open ungrouped), with a warning saying why. Layers look different when they draw an object the page doesn't (or +miss one it draws), and, for an EPS whose page is the box of its art, when they print art outside it. With +`textAs: "outlines"` a `.ai` file whose type shows opens from its PDF content, which has the type's outlines. + +The document then has what the file's page doesn't print: hidden objects and layers, layers that don't print, guides and +the art outside the artboards, as the app that wrote the file shows them. Exports and `artboard.fitToArt` leave out the +hidden art, the guides and template layers; an EPS's artboard is the file's artboard, not the page's bounding box. A +print pipeline that wants only what the page prints opens the file with `editingData: false` (default `true`): +an EPS as its page, a `.ai` file from its PDF content (a `.ai` saved without PDF compatibility then can't be opened). + +```json +{"name":"run_command","arguments":{"command":"document.open","params":{"path":"/tmp/label.eps","editingData":false}}} +``` Opening a PDF (or `.ai`) imports every page as an artboard and layer; `document.open` takes `pages` ("2-3, 5", 1-based), `cropTo` (`bounding` (the art's bounds), `art`, `crop` (default), `trim`, `bleed`, `media`: the box each artboard gets)