mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-10-14 19:26:56 -04:00
Fix #918: PSD and PSB files open and place as their merged image
File › Place and File › Open read PSD and PSB files: the merged image every such document carries after its layers, which is what a linked PSD shows. A placed PSD links like any image, so the Links panel updates and relinks it, and it is sized by its ResolutionInfo resource. The reader is written from the public file format specification. It reads Bitmap, Grayscale, Duotone, Indexed, RGB, CMYK (through the colour settings' CMYK) and Lab, at 1, 8, 16 and 32 bits per channel (32-bit values are linear), raw, PackBits or zipped with or without prediction. A document with transparency stores its merged image on white with the alpha in the first extra channel. It comes back with straight colours, also for 16- and 32-bit files, which say so in their Lr16/Lr32 block. Multichannel files are refused with a message. The file is untrusted: every read is bounds-checked and the image's size is checked against the decode budget before anything is allocated. PSB is a read-only format of its own, so exports never write a PSD under a .psb name. The desktop packaging still doesn't associate either extension with VectorCraft (UNASSOCIATED_EXTS): they belong to raster editors. Layers (import options) are left for later. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
be51213f0d
commit
0eb4ce5e98
17 files changed
+796
-39
No files matched your search
+4
-4
@@ -4,7 +4,7 @@ VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adob
|
||||
|
||||
This file tracks **how far we are and what's left**. Time estimates are wall-clock hours of continuous Claude Opus 5.5 agent work (including builds and the CI gate), given both for **one agent** and for **4–6 parallel agents** on disjoint crates. They are counted from the remaining work (see [Parity estimate](#parity-estimate)), calibrated against measured throughput, and updated as work lands.
|
||||
|
||||
_Last updated: 2026-10-10 (after placed documents (File › Place of a `.vectorcraft` file, linked), M4.14–M4.98, M8.1–M8.20, M14.4–M14.7, the MCP prompts, resource templates, completions and logging, the 2026-10-07 issue fixes, the Layers panel rework and the 2026-10-08 community contributions: Pen and shape-tool modifiers, path editing, Layers, Artboards, Swatches/Brushes and dialogs, Japanese composition and PDF text, Hebrew/Arabic type, interface languages (Spanish among them), the font menu, saved selections, MCP and EPS, the missing-font export warning (#319), open paths in the Shape Builder (#374), PDF/`.ai` import keeping strokes live and hidden and nested layers (#372), per-corner Live Corners (#381), SVG type opening at the size it draws at (#396), the Wayland clipboard with copied-file paste (#398), ruler guides that can be selected, moved and deleted (#414), two batches of Preferences options that were stored but unused (#394), skeleton reads with `document.find` for large documents over MCP (#416) and anchors dragged with Direct Selection snapping to points, segments and smart guides, clipped SVG layers opening as clipping layers (#420), PDF/`.ai` layers read on pages of tens of millions of operators (#419), Document Color Mode putting RGB greys on the black plate on request and converting pattern tiles (#421) and movable dialogs with Offset Path's Joins dropdown (#423) and numeric fields scrubbed by dragging their label (#400), stroke weight presets in the stroke unit (#426), the Appearance panel's Opacity popup (#430), type on a path brackets, flip and Type on a Path Options that keep the type in place (#429), Layers rows dragged with a ghost and dropped on the trash or New Layer (#435), tool flyouts opening on a right or corner press (#436), tool flyouts torn off into floating toolbars (#437), the Shape Builder's erase mode deleting edges too (#439), installed fonts registered outside the font folders and fonts installed while the app runs listed in the font menus (#443), alike circular corners on rectangles that aren't square (#442), tool cursors as OS cursors so the pointer no longer trails over the canvas (#444), artboards copied and pasted with their art (#446), guides dragged out of the rulers snapping to the art's side midpoints and the artboards, artboard guides (#451), the toolbar's double arrow and Window › Toolbars › Double Column switching between one and two columns in any window height (#455), the Smart Guides display options and Snapping Tolerance (#394), Font Size and Leading combo boxes with preset lists in the Character and Properties panels and the Control bar (#458), screenshots pasted from the clipboard on macOS, Windows and the web (#457), the Properties panel's Fill and Stroke matching the Control bar's, Illustrator's Window menu panel keys (Shift+F7 for Align…) and Alt-wheel zoom whatever the wheel preference (Discord feedback), the point/area type widget (Discord feedback), groups in legacy Illustrator .ai files (Discord feedback), a rotating desktop log file (#465), image controls in the Control bar and Properties panel: Image Trace with its presets, Mask, Crop Image, Embed/Unembed, and an Image Trace object's preset, Expand and Release (Discord feedback), the Pen working as the Anchor Point tool with Alt held over a selected path's handles and anchors, and anchor buttons that convert, connect and cut paths at the selected anchors (Discord feedback), Japanese hanging punctuation (burasagari, #463), Escape leaving Presentation Mode with no screen mode saved across restarts, documents dropped on the desktop app opening as tabs of their own and a note that an `.ai` file's art off its artboards isn't in the part read (#472), Add/Delete Anchor Point tool icons drawn from the Pen tool's (#479), EPS import running more of PostScript Level 3 (patterns, Type 3 fonts, mesh shadings, masked images, VM and resource probes), and a preview that stands in saying why (Discord feedback, #466, #469, #474), chords with modifiers recorded in Edit › Keyboard Shortcuts (#487), Type Object Selection by Path Only (#394), Anti-aliased Artwork (#394), Show Pixel Grid (#394), pen and touch taps pressed and lifted within one frame clicking where they tapped and the Linux/Wayland pen-tablet workaround (#491), bounding-box resizes landing on the other objects' anchors and centres with labels, and the Rotate, Scale, Shear and Reflect tools snapping their drags (#482), Shift-drag marquees that toggle the objects or anchors they reach and a Lasso whose Alt subtraction keeps the rest of the selection (#483), the mouse wheel stepping the focused numeric field, the dialogs' and preferences' drag values made such fields (#485), Show The Home Screen When No Documents Are Open (#394), Numbers Without Units Are Points (#394), Auto-Collapse Iconic Panels (#394), the Contextual Task Bar moved by its handle and its More Options menu pinning and resetting its position, a designed macOS DMG windoLine truncated
|
||||
_Last updated: 2026-10-10 (after placed documents (File › Place of a `.vectorcraft` file, linked), M4.14–M4.98, M8.1–M8.20, M14.4–M14.7, the MCP prompts, resource templates, completions and logging, the 2026-10-07 issue fixes, the Layers panel rework and the 2026-10-08 community contributions: Pen and shape-tool modifiers, path editing, Layers, Artboards, Swatches/Brushes and dialogs, Japanese composition and PDF text, Hebrew/Arabic type, interface languages (Spanish among them), the font menu, saved selections, MCP and EPS, the missing-font export warning (#319), open paths in the Shape Builder (#374), PDF/`.ai` import keeping strokes live and hidden and nested layers (#372), per-corner Live Corners (#381), SVG type opening at the size it draws at (#396), the Wayland clipboard with copied-file paste (#398), ruler guides that can be selected, moved and deleted (#414), two batches of Preferences options that were stored but unused (#394), skeleton reads with `document.find` for large documents over MCP (#416) and anchors dragged with Direct Selection snapping to points, segments and smart guides, clipped SVG layers opening as clipping layers (#420), PDF/`.ai` layers read on pages of tens of millions of operators (#419), Document Color Mode putting RGB greys on the black plate on request and converting pattern tiles (#421) and movable dialogs with Offset Path's Joins dropdown (#423) and numeric fields scrubbed by dragging their label (#400), stroke weight presets in the stroke unit (#426), the Appearance panel's Opacity popup (#430), type on a path brackets, flip and Type on a Path Options that keep the type in place (#429), Layers rows dragged with a ghost and dropped on the trash or New Layer (#435), tool flyouts opening on a right or corner press (#436), tool flyouts torn off into floating toolbars (#437), the Shape Builder's erase mode deleting edges too (#439), installed fonts registered outside the font folders and fonts installed while the app runs listed in the font menus (#443), alike circular corners on rectangles that aren't square (#442), tool cursors as OS cursors so the pointer no longer trails over the canvas (#444), artboards copied and pasted with their art (#446), guides dragged out of the rulers snapping to the art's side midpoints and the artboards, artboard guides (#451), the toolbar's double arrow and Window › Toolbars › Double Column switching between one and two columns in any window height (#455), the Smart Guides display options and Snapping Tolerance (#394), Font Size and Leading combo boxes with preset lists in the Character and Properties panels and the Control bar (#458), screenshots pasted from the clipboard on macOS, Windows and the web (#457), the Properties panel's Fill and Stroke matching the Control bar's, Illustrator's Window menu panel keys (Shift+F7 for Align…) and Alt-wheel zoom whatever the wheel preference (Discord feedback), the point/area type widget (Discord feedback), groups in legacy Illustrator .ai files (Discord feedback), a rotating desktop log file (#465), image controls in the Control bar and Properties panel: Image Trace with its presets, Mask, Crop Image, Embed/Unembed, and an Image Trace object's preset, Expand and Release (Discord feedback), the Pen working as the Anchor Point tool with Alt held over a selected path's handles and anchors, and anchor buttons that convert, connect and cut paths at the selected anchors (Discord feedback), Japanese hanging punctuation (burasagari, #463), Escape leaving Presentation Mode with no screen mode saved across restarts, documents dropped on the desktop app opening as tabs of their own and a note that an `.ai` file's art off its artboards isn't in the part read (#472), Add/Delete Anchor Point tool icons drawn from the Pen tool's (#479), EPS import running more of PostScript Level 3 (patterns, Type 3 fonts, mesh shadings, masked images, VM and resource probes), and a preview that stands in saying why (Discord feedback, #466, #469, #474), chords with modifiers recorded in Edit › Keyboard Shortcuts (#487), Type Object Selection by Path Only (#394), Anti-aliased Artwork (#394), Show Pixel Grid (#394), pen and touch taps pressed and lifted within one frame clicking where they tapped and the Linux/Wayland pen-tablet workaround (#491), bounding-box resizes landing on the other objects' anchors and centres with labels, and the Rotate, Scale, Shear and Reflect tools snapping their drags (#482), Shift-drag marquees that toggle the objects or anchors they reach and a Lasso whose Alt subtraction keeps the rest of the selection (#483), the mouse wheel stepping the focused numeric field, the dialogs' and preferences' drag values made such fields (#485), Show The Home Screen When No Documents Are Open (#394), Numbers Without Units Are Points (#394), Auto-Collapse Iconic Panels (#394), the Contextual Task Bar moved by its handle and its More Options menu pinning and resetting its position, a designed macOS DMG windoLine truncated
|
||||
|
||||
## Where we are
|
||||
|
||||
@@ -38,7 +38,7 @@ since 2026-10-01.
|
||||
| **Large missing subsystems** | 0–20% | 3D & Materials (0%), Photoshop-style raster effects and the Effect Gallery (~8 of ~56 filters), SVG Filters, CJK composition (vertical type with kinsoku, tate-chu-yoko and the font's vertical metrics; ruby, mojikumi and proportional vertical metrics open), Variables (data merge), scripting |
|
||||
| **Interaction fidelity:** modifiers, cursors, small behaviours | ~30–40% | The dedicated pass hasn't started, and there has been no side-by-side session with Illustrator yet. A power user notices this first |
|
||||
| **Look & feel** | ~75–80% | Measured against Illustrator 2026 screenshots (2026-10-02); the panels added since haven't been re-measured |
|
||||
| **File interop** | ~85% | SVG/SVGZ, PDF and PDF-compatible `.ai`, EPS, DXF, EMF/WMF, raster formats, PSD export, Place and Links, Package, Print, clipboard flavours. Affinity documents (Affinity 1–3) open natively as editable art, checked against 51 pinned public files (33 current `.af`), with selected saved-thumbnail comparisons and every-board native/SVG/PDF/PSD checks for current files; Affinity export is missing and effects, adjustments and brushes don't import. Affinity isn't an Illustrator feature, so this doesn't raise the parity score. The editing copy inside an Illustrator EPS or `.ai` is read for its structure: layers, groups, names, hidden objects and type, colours, gradients, transparency, images and every artboard (see Out of scope for what it doesn't read yet); DWG has no open spec |
|
||||
| **File interop** | ~85% | SVG/SVGZ, PDF and PDF-compatible `.ai`, EPS, DXF, EMF/WMF, raster formats, PSD export and PSD/PSB placement (merged image), Place and Links, Package, Print, clipboard flavours. Affinity documents (Affinity 1–3) open natively as editable art, checked against 51 pinned public files (33 current `.af`), with selected saved-thumbnail comparisons and every-board native/SVG/PDF/PSD checks for current files; Affinity export is missing and effects, adjustments and brushes don't import. Affinity isn't an Illustrator feature, so this doesn't raise the parity score. The editing copy inside an Illustrator EPS or `.ai` is read for its structure: layers, groups, names, hidden objects and type, colours, gradients, transparency, images and every artboard (see Out of scope for what it doesn't read yet); DWG has no open spec |
|
||||
| **Bundled content:** brush, symbol, style and swatch libraries | ~30% | Ours are original and generated in code, and far fewer than Illustrator ships; brush and symbol libraries are still missing |
|
||||
| **Performance** | unverified | Multithreaded, off-thread rendering and caches are in place. The last budget run (2026-10-01, loaded machine) measured 290 ms for a 50k-path fit against a 16 ms budget. Re-run `vectorcraft-cli perf` on an idle machine |
|
||||
| **Robustness** | good, new | ~2,840 tests, property tests, no panics in shipped code (lints, the `guard` safety net, import fuzzing), Data Recovery. Missing: a corpus of real-world files, Windows/Linux/browser QA |
|
||||
@@ -171,7 +171,7 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist
|
||||
- **Files (M4):**
|
||||
- `.vectorcraft` (lossless JSON, compressed, atomic saves, save down to v1), Save As with a format chooser, Save a Copy, Revert, templates, Data Recovery after a crash (browser tabs hold their copies with Web Locks too, so a background tab's copies are never taken for a crash's, and a tab repairs copies another removed when it resumes: #367), background save and export. The desktop app writes its warnings and errors (graphics adapter, a lost graphics device, panics the guard recovered from) to standard error and to `logs/vectorcraft.log` next to the preferences, the two previous runs kept and each file capped at 16 MiB, so a launch without a terminal still leaves something to attach to a bug report (#465).
|
||||
- SVG/SVGZ in and out with SVG Options, Preserve Editing, symbols, filters, rich text and physical units (SVG type under a transform or `viewBox` scale opens at the size it draws at, the scale moved into its size, leading, baseline shift and strokes, a stretch, skew or rotation kept as its transform: #396; a top-level group with a clip path, such as a clipped Inkscape layer, opens as a layer with a clipping mask, its name kept: #420; hidden objects written hidden on Save and `convert`, and `data-*` attributes kept as the objects' own data: #522; top-level groups open as layers named from `data-name`, else the id, also when one more group (a transform on all the art, a `<switch>`) wraps them, hidden ones hidden, and a file whose art sits loose under a root `<svg>` with an id (or `data-name`), as one-layer exports write it, opens with its one layer named from it; nested groups stay groups, except the sublayers VectorCraft writes, marked `data-vc-layer`, and Inkscape sublayers, which open as sublayers in their layer's colour: #372); PDF and PDF-compatible `.ai` in and out (layers, with hidden ones kept hidden with their art and nested ones as sublayers, on pages of up to 64 million operators, art whose layer can't be told going to a hidden, non-printing layer rather than showing or printing: #419; strokes kept live, a fill and a stroke of one outline as one object; a type object's stroke written as each glyph's outline stroked back on the type, so it stays one editable object; lines wrapped in a frame (each wrapped line ending in a space, one left edge, leading and font) back as one area type object, left aligned or justified with its paragraph spacing, where laying it out breaks the lines where the file does; glyphs set apart by gaps wider than a space (a barcode's digit groups) keeping their places; layers stacked as the pages mark them even when one first paints on a later page, art ending a layer's marked content or a clip closing in a later layer kept in its own layer, and layers with no art kept empty: #508; art reaching past a plain PDF's page clipped to its crop box, as PDF viewers show it, each such object in a clip group of its own (a PDF-compatible `.ai` opens whole: #675); masks, editable text with type set along a curve coming back as type on a path, each artboard's art on its own page only, an `.ai`'s white page under its layers left out rather than coming in as art, spot colours, presets, security, marks and bleed, ICC output intents, raster effects, subset fonts, PDF/X, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3). CMYK images keep their ink amounts from PDF import (and from placed CMYK TIFFs) to PDF export: a CMYK JPEG passes through unchanged, others stay CMYK (DeviceCMYK, or ICC-based CMYK in PDF/X-3/X-4) unless the Output settings convert them; the canvas shows them through the working CMYK profile (#320). A masked CMYK image (`/SMask`, `/Mask` or a colour key) keeps its inks too, its alpha coming in as a greyscale opacity mask.
|
||||
- EPS and DXF in and out, EMF/WMF in and out; PNG (with PNG-8), JPEG, WebP, GIF, TIFF, BMP, Targa and layered PSD export. EPS import runs a PostScript Level 3 interpreter written from the PostScript Language Reference: resource categories and `resourceforall`, local and global VM (`currentglobal`/`setglobal`/`gcheck`), `clipsave`/`cliprestore`, subarrays and substrings that share storage, the standard dictionaries in `systemdict`, `dictstack`, `internaldict`, executable filters and strings, `load` by any key, `//name` immediate names, `token`, `execform`, user paths, `cshow`, `rootfont`, `cachestatus`, colour rendering and halftone queries, file `status` and data read with `flushfile`, and `pdfmark` marks dropped (Discord feedback, #466, #469, #474). Masked images (`ImageType 3` in its three interleavings) and reusable streams are read, and an image's several data sources are read in turn, as the reference defines (procedures that read one file get their own rows: such images came in banded, #498). `restore` puts dictionaries back as they were at the `save`, so programs that count their saves in a dictionary read to their end (part of #505). Tiling patterns come in as pattern swatches, uncoloured ones too; Type 3 fonts' glyphs as their outlines, spaced by `ashow`/`widthshow`/`xshow`/`kshow`; mesh and function-based shadings (types 1, 4–7) as gradient meshes; sampled functions (type 0) and Flate/LZW predictors are read. It is tested with programs written from the specification in the ways common generators use these features; Inkscape/cairo EPS files open as vectors. When a file's PostScript still can't be read, it opens as its TIFF preview, its Windows metafile preview (as vectors) or its EPSI preview, and the warning (in the status bar, `document.open`/`app.open`/MCP `open_file` replies and `vectorcraft-cli info`) names the error, the operator that raised it and the procedures it ran in. Legacy PostScript `.ai` files (Illustrator 3–8, written with the prolog that defines their operators) keep their groups and nested groups (`u` … `U`), between and inside clipping groups; EPS and EMF/WMF import nest clips (and groups) at most 128 deep, so a hostile file can't exhaust the stack. DXF TEXT justified Fit or Aligned spans its two points (stretched, or scaled as a whole). PDF export writes type as real, searchable text in embedded subset fonts by default, as Illustrator's PDF presets do (Convert Text to Outlines is an option; printer's marks stay shapes), so text-heavy PDFs stay small (#733). DXF export writes each fill as its outlines followed by its hatch, so laser and cutter software, which skips hatches, gets filled art and type too (#546).
|
||||
- EPS and DXF in and out, EMF/WMF in and out; PNG (with PNG-8), JPEG, WebP, GIF, TIFF, BMP, Targa and layered PSD export; PSD and PSB files open and place, linked or embedded, as their merged image in every colour mode and depth (#918). EPS import runs a PostScript Level 3 interpreter written from the PostScript Language Reference: resource categories and `resourceforall`, local and global VM (`currentglobal`/`setglobal`/`gcheck`), `clipsave`/`cliprestore`, subarrays and substrings that share storage, the standard dictionaries in `systemdict`, `dictstack`, `internaldict`, executable filters and strings, `load` by any key, `//name` immediate names, `token`, `execform`, user paths, `cshow`, `rootfont`, `cachestatus`, colour rendering and halftone queries, file `status` and data read with `flushfile`, and `pdfmark` marks dropped (Discord feedback, #466, #469, #474). Masked images (`ImageType 3` in its three interleavings) and reusable streams are read, and an image's several data sources are read in turn, as the reference defines (procedures that read one file get their own rows: such images came in banded, #498). `restore` puts dictionaries back as they were at the `save`, so programs that count their saves in a dictionary read to their end (part of #505). Tiling patterns come in as pattern swatches, uncoloured ones too; Type 3 fonts' glyphs as their outlines, spaced by `ashow`/`widthshow`/`xshow`/`kshow`; mesh and function-based shadings (types 1, 4–7) as gradient meshes; sampled functions (type 0) and Flate/LZW predictors are read. It is tested with programs written from the specification in the ways common generators use these features; Inkscape/cairo EPS files open as vectors. When a file's PostScript still can't be read, it opens as its TIFF preview, its Windows metafile preview (as vectors) or its EPSI preview, and the warning (in the status bar, `document.open`/`app.open`/MCP `open_file` replies and `vectorcraft-cli info`) names the error, the operator that raised it and the procedures it ran in. Legacy PostScript `.ai` files (Illustrator 3–8, written with the prolog that defines their operators) keep their groups and nested groups (`u` … `U`), between and inside clipping groups; EPS and EMF/WMF import nest clips (and groups) at most 128 deep, so a hostile file can't exhaust the stack. DXF TEXT justified Fit or Aligned spans its two points (stretched, or scaled as a whole). PDF export writes type as real, searchable text in embedded subset fonts by default, as Illustrator's PDF presets do (Convert Text to Outlines is an option; printer's marks stay shapes), so text-heavy PDFs stay small (#733). DXF export writes each fill as its outlines followed by its hatch, so laser and cutter software, which skips hatches, gets filled art and type too (#546).
|
||||
- Affinity documents in (AF.1–AF.4): `.af` (Affinity 3) and `.afdesign`/`.afphoto`/`.afpub` (Affinity 1 and 2, container versions 8–12) open and place as editable art: layers and sublayers, groups (pass-through or isolated), artboards (with their names and backgrounds) and Publisher pages side by side, curves with live corners, parametric shapes (rectangles with corner radii, ellipses, polygons, stars, pies, triangles, trapezoids), compound shapes, solid/linear/elliptical gradient fills and strokes (weight, dashes, alignment, scale-with-object), clipping by nesting, vector and pixel masks, artistic and frame text with fonts, sizes, tracking, leading and alignment, placed images (their original JPEG/PNG) and pixel layers (8/16-bit RGB, CMYK), opacity, visibility, locking and blend modes, at the document's resolution in points. Effects, adjustments, brushes and pressure profiles, transparency gradients, master pages, symbol instances (imported as their cached picture), special shapes (cloud, heart, cog…, imported as ellipses) and Affinity-only blend modes are named in the import warning. A file whose native data can't be read opens as its embedded preview with the reason, and that preview can't be placed. Save never writes back over the Affinity file and there is no Affinity export. AF.4 adds Affinity 3 artboard recognition and actual-outline clipping, source-backed JPEG/PNG raster tiles, Unicode text-run recovery, stored fallback/exact installed fonts, OpenType feature flags and compound-geometry limits. 51 public CC0/MIT/Apache-2.0 files (33 current `.af`), pinned and sha256-verified (`cargo xtask corpus --affinity`), test native retention and every-board native/SVG/PDF/PSD output for current files; selected files compare their saved thumbnails. No Affinity reopen or independent paired PSD oracle was available; [source audit and complex-font gaps](docs/affinity-validation.md); [scope, provenance and limits](crates/affinity/README.md).
|
||||
- Placed documents: File › Place of a `.vectorcraft` file links to it by default (`file.place`'s `link`): one locked object showing an artboard of the document (or its art's bounds), read the way placing it without Link reads it, its symbols, patterns and images kept apart from the document's; without Link (or from bytes, not a file) it is an editable copy as before. It stays vectors in every output (SVG, PDF, EPS, EMF, DXF), and so do placed documents inside it, read from their own files up to 8 levels deep (documents that place each other stop there). On screen they draw from bitmaps cached per file and zoom step, shared by every copy and made in the background (a placeholder until ready), so a sheet of them redraws in about a millisecond; exports and prints draw them exactly. Like linked images, a save keeps only a preview of each (JPEG when opaque) unless Include Linked Files; output, and zooming past the preview, read the file again, falling back to the preview with a warning when it is gone or changed. Saves for older versions write them as plain art. Links check, update, relink, Update Links on open, Link Info (the artboard's size), Placement Options, Break Link (also Embed, Object › Expand: the editable copy placing without Link gives, its resources joining the document), Edit Original (the document in a new tab) and the Links panel cover them; saving a document updates the open documents that place it. The native format (v4) keeps data of 8 KB or more after the JSON instead of base64 in it.
|
||||
- Place and the Links panel, Package (placed `.vectorcraft` documents packaged with their own linked files and fonts, relinked to the copies: #777), File Info, Print with print presets, PostScript output and print tiling, slices and Save for Web, Export for Screens and Asset Export, CSS Properties, PNG/PDF/SVG/text clipboard flavours; files copied in a file manager paste as art (SVG, PDF, EMF/WMF, bitmaps) on every desktop platform, and Linux/Wayland reads the compositor's clipboard (#398); on Linux the Paste menu checks the clipboard off the UI thread, so an X11 owner that never answers can't freeze the window (#510); screenshots and other copied pictures paste as embedded images at the view centre everywhere, the web included (#457).
|
||||
@@ -232,7 +232,7 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale)
|
||||
| Layers, artboards, document setup | 5 | 82% | Layers panel: a confirmation before deleting layers that hold art, Collect for Export, row context menus, the Layer Options dialog for several rows with mixed values, Paste Remembers Layers for sublayers, drag-scrolling a long panel while dragging rows; artboard preset polish (Move Artwork for artboard X/Y edits, Rearrange All Artboards, Document Setup, New Document and the rest of the Layers panel are done) | 4–7 |
|
||||
| View & navigation | 3 | 70% | New View/Edit Views, multiple windows/arrange, Snap to Pixel/Glyph (print tiling is done) | 9–14 |
|
||||
| Guides, grids, smart guides, snapping, rulers | 3 | 85% | global/video rulers, Spacing Guides' distance readouts and spacing for resized or drawn art, Smart Guides' angle and distance readouts while drawing, Alt swapping a ruler guide's orientation, ruler guides selected together with art (marquee, Shift-click), ruler guides as Layers rows with their own lock and hide (#451: Lock Guides locks them all; Make Guides paths are Layers rows already) (dragging existing guides is done, #414; new guides snapping to side midpoints and artboards, and artboard guides, #451; the drawing tools snapping, with Construction Guides, #506; Spacing Guides for moves, #394; moves snapping to the grid, #740; ruler guides pulling drawn points with Smart Guides on, and "center" and "anchor" labels while hovering with the Selection tool, #812) | 2–4 |
|
||||
| File formats | 6 | 85% | Affinity export, and the rest of Affinity import (effects, adjustments, brushes, master pages, live symbol instances), DWG (no open spec: DXF instead), PSD placement as layers, EPS checked against more real files users send (Inkscape files open as vectors; other generators' constructs are tested with programs written from the PostScript Language Reference only; CID-keyed CJK type and `CCITTFaxDecode` images not read), legacy `.ai` files saved without the prolog that defines their operators (their own operator set isn't read yet), the rest of Illustrator's editing data (appearances and live effects, symbols, pattern fills, brushes, placed files: #637), the remaining fidelity polish; EPS, DXF, EMF/WMF, TIFF, BMP, Targa, PSD export, SVGZ, PDF security, PDF/X, PDF layers, presets and Affinity import are done | 6–10 (existing scope; Affinity export unestimated) |
|
||||
| File formats | 6 | 85% | Affinity export, and the rest of Affinity import (effects, adjustments, brushes, master pages, live symbol instances), DWG (no open spec: DXF instead), PSD placement as layers (Photoshop Import Options; the merged image is done), EPS checked against more real files users send (Inkscape files open as vectors; other generators' constructs are tested with programs written from the PostScript Language Reference only; CID-keyed CJK type and `CCITTFaxDecode` images not read), legacy `.ai` files saved without the prolog that defines their operators (their own operator set isn't read yet), the rest of Illustrator's editing data (appearances and live effects, symbols, pattern fills, brushes, placed files: #637), the remaining fidelity polish; EPS, DXF, EMF/WMF, TIFF, BMP, Targa, PSD export, SVGZ, PDF security, PDF/X, PDF layers, presets and Affinity import are done | 6–10 (existing scope; Affinity export unestimated) |
|
||||
| Export for Screens, Asset Export, slices, Save for Web | 3 | 85% | polish only (all four are done) | 2–4 |
|
||||
| Print, colour management, separations, flattener | 3 | 80% | print preview fidelity (flattener presets in PDF and print, overprint in PDF and composite print, Print dialog, presets, PostScript, marks, separations, Print Tiling, print overprint/flattener/bitmap options and printer profile are done) | 1–2 |
|
||||
| Automation | 3 | 60% | Variables (data merge), scripting surface, batch | 8–12 |
|
||||
|
||||
@@ -621,13 +621,14 @@ mod tests {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Finder offers the app for every file File › Open reads (#295, #354), takes over no other
|
||||
/// app's files, and hands them to the app rather than to AppKit's document machinery.
|
||||
/// Finder offers the app for every file File › Open reads (#295, #354) but Photoshop documents
|
||||
/// (`UNASSOCIATED_EXTS`), takes over no other app's files, and hands them to the app rather than
|
||||
/// to AppKit's document machinery.
|
||||
#[test]
|
||||
fn the_macos_bundle_opens_every_readable_format() {
|
||||
let plist = include_str!("../../../packaging/macos/Info.plist.in");
|
||||
let declared = plist_extensions(plist);
|
||||
for e in fileio::OPEN_EXTS {
|
||||
for e in fileio::OPEN_EXTS.iter().filter(|e| !fileio::UNASSOCIATED_EXTS.contains(e)) {
|
||||
assert!(declared.contains(e), "Info.plist.in doesn't declare .{e}");
|
||||
}
|
||||
for e in &declared {
|
||||
|
||||
@@ -8,7 +8,7 @@ use vectorcraft_geom::Affine;
|
||||
|
||||
use super::super::*;
|
||||
use super::pdfimport::LoadOptions;
|
||||
use super::{Format, SAVE_FORMATS, absolute_path, file_stamp, format, format_for_name, read_file};
|
||||
use super::{Format, SAVE_FORMATS, absolute_path, file_stamp, format, format_for_name, psdread, read_file};
|
||||
use crate::EngineError;
|
||||
|
||||
/// A file read into a document, with its format and non-fatal import notes.
|
||||
@@ -76,6 +76,9 @@ pub fn detect(name: &str, bytes: &[u8]) -> Option<&'static Format> {
|
||||
if let Some(kind) = vectorcraft_metafile::sniff(bytes) {
|
||||
return format(kind.id());
|
||||
}
|
||||
if psdread::is_psd(bytes) {
|
||||
return format(if psdread::is_psb(bytes) { "psb" } else { "psd" });
|
||||
}
|
||||
if let Some(f) = image::guess_format(bytes).ok().and_then(image_format) {
|
||||
return Some(f);
|
||||
}
|
||||
@@ -355,37 +358,50 @@ const MAX_RASTER_ALLOC: u64 = if cfg!(target_arch = "wasm32") { 512 << 20 } else
|
||||
|
||||
/// Decode an image's header (and, for formats stored as PNG, its pixels). CMYK TIFFs are kept as
|
||||
/// they are, with their ink amounts ([`ImageBlob::cmyk`]); CMYK TIFFs with an alpha channel, which
|
||||
/// the decoder can't read, become RGBA in the active colour settings' CMYK.
|
||||
/// the decoder can't read, become RGBA in the active colour settings' CMYK, as do CMYK Photoshop
|
||||
/// documents, whose merged image is read ([`psdread`]).
|
||||
pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> {
|
||||
let ppi = super::ppi::resolution(bytes);
|
||||
if psdread::is_psd(bytes) {
|
||||
let cms = vectorcraft_color::cms::active();
|
||||
return as_png(psdread::decode(bytes, MAX_RASTER_ALLOC, |c| cms.cmyk_to_srgb(c, false)).map_err(err)?, ppi);
|
||||
}
|
||||
let mut reader = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().map_err(err)?;
|
||||
let mut limits = image::Limits::default();
|
||||
limits.max_alloc = Some(MAX_RASTER_ALLOC);
|
||||
reader.limits(limits);
|
||||
let kind = reader.format().ok_or_else(|| err("not an image VectorCraft reads (see document.formats)"))?;
|
||||
let f = image_format(kind).ok_or_else(|| err(format!("{kind:?} images can't be opened (see document.formats)")))?;
|
||||
let ppi = super::ppi::resolution(bytes);
|
||||
let cmyk = || ImageBlob::new(f.mime, bytes.to_vec()).cmyk().is_some();
|
||||
let (bytes, mime, (width, height)) = if matches!(f.id, "png" | "jpg" | "gif" | "webp") || (f.id == "tiff" && cmyk()) {
|
||||
(bytes.to_vec(), f.mime, reader.into_dimensions().map_err(err)?)
|
||||
} else {
|
||||
let cmyka = || {
|
||||
let cms = vectorcraft_color::cms::active();
|
||||
vectorcraft_doc::cmyk::cmyka_tiff_rgba(bytes, |c| cms.cmyk_to_srgb(c, false))
|
||||
};
|
||||
let img = match (f.id == "tiff").then(cmyka).flatten() {
|
||||
Some(img) => img,
|
||||
None => reader.decode().map_err(err)?.to_rgba8(),
|
||||
};
|
||||
let size = img.dimensions();
|
||||
let mut png = Vec::new();
|
||||
img.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).map_err(err)?;
|
||||
// The stored PNG keeps the file's resolution.
|
||||
let png = match ppi {
|
||||
Some(r) => super::ppi::with_png_resolution(&png, r),
|
||||
None => png,
|
||||
};
|
||||
(png, "image/png", size)
|
||||
if matches!(f.id, "png" | "jpg" | "gif" | "webp") || (f.id == "tiff" && cmyk()) {
|
||||
let (width, height) = reader.into_dimensions().map_err(err)?;
|
||||
return stored(bytes.to_vec(), f.mime, (width, height), ppi);
|
||||
}
|
||||
let cmyka = || {
|
||||
let cms = vectorcraft_color::cms::active();
|
||||
vectorcraft_doc::cmyk::cmyka_tiff_rgba(bytes, |c| cms.cmyk_to_srgb(c, false))
|
||||
};
|
||||
let img = match (f.id == "tiff").then(cmyka).flatten() {
|
||||
Some(img) => img,
|
||||
None => reader.decode().map_err(err)?.to_rgba8(),
|
||||
};
|
||||
as_png(img, ppi)
|
||||
}
|
||||
|
||||
/// `img` stored as a PNG that keeps the file's resolution.
|
||||
fn as_png(img: image::RgbaImage, ppi: Option<(f64, f64)>) -> Result<RasterImage> {
|
||||
let size = img.dimensions();
|
||||
let mut png = Vec::new();
|
||||
img.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).map_err(err)?;
|
||||
let png = match ppi {
|
||||
Some(r) => super::ppi::with_png_resolution(&png, r),
|
||||
None => png,
|
||||
};
|
||||
stored(png, "image/png", size, ppi)
|
||||
}
|
||||
|
||||
/// An image's encoded `bytes`, `width` × `height` pixels, ready to embed.
|
||||
fn stored(bytes: Vec<u8>, mime: &'static str, (width, height): (u32, u32), ppi: Option<(f64, f64)>) -> Result<RasterImage> {
|
||||
if width == 0 || height == 0 {
|
||||
return Err(err("the image is empty"));
|
||||
}
|
||||
|
||||
@@ -34,6 +34,7 @@ pub mod pdf;
|
||||
mod pdfimport;
|
||||
pub mod pngtext;
|
||||
pub mod ppi;
|
||||
pub mod psdread;
|
||||
mod save;
|
||||
mod screens;
|
||||
mod svg;
|
||||
@@ -558,10 +559,12 @@ pub const FORMATS: &[Format] = &[
|
||||
Format { id: "emf", label: "EMF", extensions: &["emf"], mime: "image/emf", read: true, write: true, raster: false, options: metafile::OPTIONS },
|
||||
Format { id: "wmf", label: "WMF", extensions: &["wmf"], mime: "image/wmf", read: true, write: true, raster: false, options: metafile::OPTIONS },
|
||||
Format { id: "tga", label: "Targa", extensions: &["tga"], mime: "image/x-tga", read: false, write: true, raster: true, options: TGA_OPTIONS },
|
||||
Format { id: "psd", label: "PSD", extensions: &["psd"], mime: "image/x-psd", read: false, write: true, raster: true, options: PSD_OPTIONS },
|
||||
Format { id: "psd", label: "PSD", extensions: &["psd"], mime: "image/x-psd", read: true, write: true, raster: true, options: PSD_OPTIONS },
|
||||
// Affinity Photo's `.afphoto` opens by its content but isn't listed: Finder shouldn't offer a
|
||||
// vector app for a raster editor's documents.
|
||||
reader("affinity", "Affinity", &["af", "afdesign", "afpub"], "application/vnd.affinity", false),
|
||||
// Photoshop's large document format: read like a PSD (its merged image), never written.
|
||||
reader("psb", "PSB", &["psb"], "image/x-psb", true),
|
||||
];
|
||||
|
||||
/// Every extension `document.open` reads (the "All readable files" filter of open dialogs).
|
||||
@@ -581,6 +584,8 @@ pub const OPEN_EXTS: &[&str] = &[
|
||||
"tif",
|
||||
"tiff",
|
||||
"bmp",
|
||||
"psd",
|
||||
"psb",
|
||||
"vctemplate",
|
||||
"dxf",
|
||||
"emf",
|
||||
@@ -591,6 +596,11 @@ pub const OPEN_EXTS: &[&str] = &[
|
||||
"afpub",
|
||||
];
|
||||
|
||||
/// Extensions in [`OPEN_EXTS`] the desktop packaging doesn't associate with VectorCraft: Photoshop
|
||||
/// documents belong to raster editors, so Finder and file managers don't offer a vector app for
|
||||
/// them (File › Open and Place still read them).
|
||||
pub const UNASSOCIATED_EXTS: &[&str] = &["psd", "psb"];
|
||||
|
||||
/// The extension that picks each writable format when exporting (the format's first; PNG-8 shares
|
||||
/// `.png` with PNG, so `.png` comes once), in [`FORMATS`] order.
|
||||
pub fn export_extensions() -> Vec<&'static str> {
|
||||
@@ -623,6 +633,8 @@ pub const PLACE_EXTS: &[&str] = &[
|
||||
"tif",
|
||||
"tiff",
|
||||
"bmp",
|
||||
"psd",
|
||||
"psb",
|
||||
"vctemplate",
|
||||
"dxf",
|
||||
"emf",
|
||||
@@ -979,6 +991,8 @@ mod tests_tiffbmp;
|
||||
mod tests_pdfx;
|
||||
#[cfg(test)]
|
||||
mod tests_psd;
|
||||
#[cfg(test)]
|
||||
mod tests_psdread;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests_epsimport;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Image resolution metadata (pixels per inch): PNG `pHYs`, JPEG JFIF density or EXIF, TIFF and
|
||||
//! WebP EXIF resolution tags, BMP pixels per metre. Place sizes an image by it (72 ppi when the file
|
||||
//! has none); images converted to PNG on import keep it as a `pHYs` chunk.
|
||||
//! WebP EXIF resolution tags, BMP pixels per metre, a Photoshop document's ResolutionInfo. Place
|
||||
//! sizes an image by it (72 ppi when the file has none); images converted to PNG on import keep it
|
||||
//! as a `pHYs` chunk.
|
||||
|
||||
const INCH_M: f64 = 0.0254;
|
||||
const INCH_CM: f64 = 2.54;
|
||||
@@ -18,6 +19,8 @@ pub fn resolution(bytes: &[u8]) -> Option<(f64, f64)> {
|
||||
webp(bytes)
|
||||
} else if bytes.starts_with(b"BM") {
|
||||
bmp(bytes)
|
||||
} else if super::psdread::is_psd(bytes) {
|
||||
super::psdread::resolution(bytes)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
@@ -0,0 +1,370 @@
|
||||
//! Reading Photoshop documents (PSD, and PSB, the large document format) for File › Open and
|
||||
//! File › Place (#918): the merged image, the flattened picture every PSD carries after its layers,
|
||||
//! as a linked PSD shows. Written from Adobe's public "Photoshop File Formats Specification"
|
||||
//! (<https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/>). Layers aren't read.
|
||||
//!
|
||||
//! Every mode Photoshop saves a merged image in is read: Bitmap, Grayscale, Duotone (as its
|
||||
//! grayscale data), Indexed, RGB, CMYK and Lab, at 1, 8, 16 and 32 bits per channel, stored raw,
|
||||
//! PackBits-compressed or zipped. The merged image of a document with transparency is stored on
|
||||
//! white with its alpha in the first extra channel: it comes back with straight colours. The file
|
||||
//! is untrusted: every read is checked and the image's size is capped before anything is
|
||||
//! allocated.
|
||||
|
||||
use std::io::Read;
|
||||
|
||||
use vectorcraft_color::cms::{Lab, lab::lab_to_srgb};
|
||||
|
||||
/// Photoshop's colour modes (the header's numbers), as far as the merged image is concerned.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Mode {
|
||||
Bitmap,
|
||||
Gray,
|
||||
Indexed,
|
||||
Rgb,
|
||||
Cmyk,
|
||||
Lab,
|
||||
}
|
||||
|
||||
impl Mode {
|
||||
/// The channels holding colour (an alpha channel may follow them).
|
||||
fn colors(self) -> usize {
|
||||
match self {
|
||||
Mode::Bitmap | Mode::Gray | Mode::Indexed => 1,
|
||||
Mode::Rgb | Mode::Lab => 3,
|
||||
Mode::Cmyk => 4,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Is `bytes` a Photoshop document (PSD or PSB)?
|
||||
pub fn is_psd(bytes: &[u8]) -> bool {
|
||||
bytes.starts_with(b"8BPS") && matches!(bytes.get(4..6), Some([0, 1] | [0, 2]))
|
||||
}
|
||||
|
||||
/// Is `bytes` a PSB, Photoshop's large document format?
|
||||
pub fn is_psb(bytes: &[u8]) -> bool {
|
||||
is_psd(bytes) && bytes.get(4..6) == Some(&[0, 2])
|
||||
}
|
||||
|
||||
const TRUNCATED: &str = "the PSD file is cut short";
|
||||
const DAMAGED: &str = "the PSD file's header is damaged";
|
||||
|
||||
/// Big-endian reads through `b`, each checked against its end.
|
||||
struct Reader<'a> {
|
||||
b: &'a [u8],
|
||||
at: usize,
|
||||
}
|
||||
|
||||
impl<'a> Reader<'a> {
|
||||
fn new(b: &'a [u8]) -> Self {
|
||||
Self { b, at: 0 }
|
||||
}
|
||||
fn take(&mut self, n: usize) -> Result<&'a [u8], String> {
|
||||
let s = self.at.checked_add(n).and_then(|end| self.b.get(self.at..end)).ok_or(TRUNCATED)?;
|
||||
self.at += n;
|
||||
Ok(s)
|
||||
}
|
||||
fn array<const N: usize>(&mut self) -> Result<[u8; N], String> {
|
||||
self.take(N)?.try_into().map_err(|_| TRUNCATED.to_string())
|
||||
}
|
||||
fn u8(&mut self) -> Result<u8, String> {
|
||||
self.array::<1>().map(|[v]| v)
|
||||
}
|
||||
fn u16(&mut self) -> Result<u16, String> {
|
||||
self.array().map(u16::from_be_bytes)
|
||||
}
|
||||
fn u32(&mut self) -> Result<u32, String> {
|
||||
self.array().map(u32::from_be_bytes)
|
||||
}
|
||||
/// A section length: 4 bytes in a PSD, 8 in a PSB.
|
||||
fn length(&mut self, psb: bool) -> Result<usize, String> {
|
||||
let n = if psb { self.array().map(u64::from_be_bytes)? } else { u64::from(self.u32()?) };
|
||||
usize::try_from(n).map_err(|_| TRUNCATED.to_string())
|
||||
}
|
||||
/// A section: its length, then that many bytes.
|
||||
fn section(&mut self, psb: bool) -> Result<&'a [u8], String> {
|
||||
let n = self.length(psb)?;
|
||||
self.take(n)
|
||||
}
|
||||
fn rest(&self) -> &'a [u8] {
|
||||
self.b.get(self.at..).unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
/// The fixed-size header and the sections before the image data.
|
||||
struct Header<'a> {
|
||||
psb: bool,
|
||||
channels: usize,
|
||||
width: u32,
|
||||
height: u32,
|
||||
depth: u16,
|
||||
mode: Mode,
|
||||
/// Colour mode data: an indexed image's palette (256 reds, then greens, then blues).
|
||||
palette: &'a [u8],
|
||||
/// The image resources.
|
||||
resources: &'a [u8],
|
||||
/// The layer and mask information.
|
||||
layers: &'a [u8],
|
||||
}
|
||||
|
||||
fn header<'a>(r: &mut Reader<'a>) -> Result<Header<'a>, String> {
|
||||
if !is_psd(r.b) {
|
||||
return Err("not a PSD file".into());
|
||||
}
|
||||
r.take(4)?;
|
||||
let psb = r.u16()? == 2;
|
||||
r.take(6)?;
|
||||
let channels = usize::from(r.u16()?);
|
||||
let height = r.u32()?;
|
||||
let width = r.u32()?;
|
||||
let depth = r.u16()?;
|
||||
let mode = match r.u16()? {
|
||||
0 => Mode::Bitmap,
|
||||
// Duotone documents keep their grayscale data in the merged image.
|
||||
1 | 8 => Mode::Gray,
|
||||
2 => Mode::Indexed,
|
||||
3 => Mode::Rgb,
|
||||
4 => Mode::Cmyk,
|
||||
9 => Mode::Lab,
|
||||
7 => return Err("Multichannel PSD files can't be read: save it in RGB, CMYK or Grayscale mode".into()),
|
||||
m => return Err(format!("the PSD file has an unknown colour mode ({m})")),
|
||||
};
|
||||
let max_side = if psb { 300_000 } else { 30_000 };
|
||||
if !(1..=56).contains(&channels) || channels < mode.colors() || !(1..=max_side).contains(&width) || !(1..=max_side).contains(&height) {
|
||||
return Err(DAMAGED.into());
|
||||
}
|
||||
let depth_ok = match mode {
|
||||
Mode::Bitmap => depth == 1,
|
||||
Mode::Indexed => depth == 8,
|
||||
Mode::Cmyk | Mode::Lab => matches!(depth, 8 | 16),
|
||||
Mode::Gray | Mode::Rgb => matches!(depth, 8 | 16 | 32),
|
||||
};
|
||||
if !depth_ok {
|
||||
return Err(format!("{depth}-bit PSD files in this colour mode can't be read"));
|
||||
}
|
||||
let palette = r.section(false)?;
|
||||
let resources = r.section(false)?;
|
||||
let layers = r.section(psb)?;
|
||||
Ok(Header { psb, channels, width, height, depth, mode, palette, resources, layers })
|
||||
}
|
||||
|
||||
/// The resolution a Photoshop document declares (pixels per inch, across and down), from its
|
||||
/// ResolutionInfo resource (1005).
|
||||
pub fn resolution(bytes: &[u8]) -> Option<(f64, f64)> {
|
||||
let mut r = Reader::new(bytes);
|
||||
let h = header(&mut r).ok()?;
|
||||
let mut r = Reader::new(h.resources);
|
||||
while !r.rest().is_empty() {
|
||||
r.take(4).ok()?;
|
||||
let id = r.u16().ok()?;
|
||||
// A Pascal string padded to an even size, length byte included.
|
||||
let name = usize::from(r.u8().ok()?);
|
||||
r.take(name + (name + 1) % 2).ok()?;
|
||||
let size = usize::try_from(r.u32().ok()?).ok()?;
|
||||
let data = r.take(size).ok()?;
|
||||
r.take(size % 2).ok()?;
|
||||
if id == 0x03ed {
|
||||
let mut d = Reader::new(data);
|
||||
// Fixed 16.16 values, each with its unit (1: per inch, 2: per centimetre) and the
|
||||
// unit the size is shown in.
|
||||
let mut axis = || -> Option<f64> {
|
||||
let v = f64::from(d.u32().ok()?) / 65536.0;
|
||||
let unit = d.u16().ok()?;
|
||||
d.u16().ok()?;
|
||||
Some(if unit == 2 { v * 2.54 } else { v })
|
||||
};
|
||||
return Some((axis()?, axis()?));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Does the merged image keep its transparency in the first extra channel? Yes when the layer
|
||||
/// count is negative: in the layer info, or for 16- and 32-bit documents (whose layer info is
|
||||
/// empty) in their `Lr16` / `Lr32` block.
|
||||
fn merged_alpha(layers: &[u8], psb: bool) -> bool {
|
||||
let count_negative = |info: &[u8]| info.get(..2).is_some_and(|c| i16::from_be_bytes([c[0], c[1]]) < 0);
|
||||
let mut r = Reader::new(layers);
|
||||
let Ok(info) = r.section(psb) else { return false };
|
||||
if !info.is_empty() {
|
||||
return count_negative(info);
|
||||
}
|
||||
// The global layer mask info, then tagged blocks: signature, key, length (8 bytes for the
|
||||
// layer blocks of a PSB), data padded to 4 bytes.
|
||||
if r.section(false).is_err() {
|
||||
return false;
|
||||
}
|
||||
while r.rest().len() >= 12 {
|
||||
let (Ok(_), Ok(key)) = (r.take(4), r.array::<4>()) else { return false };
|
||||
let layer_block = matches!(&key, b"Lr16" | b"Lr32" | b"Layr");
|
||||
let long = layer_block || matches!(&key, b"LMsk" | b"Mt16" | b"Mt32" | b"Mtrn" | b"Alph" | b"FMsk" | b"lnk2" | b"FEid" | b"FXid" | b"PxSD");
|
||||
let Ok(data) = r.section(psb && long) else {
|
||||
return false;
|
||||
};
|
||||
if layer_block {
|
||||
return count_negative(data);
|
||||
}
|
||||
if r.take((4 - data.len() % 4) % 4).is_err() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// The most bytes one channel row may take (a PSB at 32 bits).
|
||||
fn row_bytes(width: usize, depth: u16) -> usize {
|
||||
if depth == 1 { width.div_ceil(8) } else { width * usize::from(depth / 8) }
|
||||
}
|
||||
|
||||
/// Undo PackBits: `src` into `dst` (a row; a short or overlong run leaves the rest as it is).
|
||||
fn unpack_bits(mut src: &[u8], dst: &mut [u8]) {
|
||||
let mut at = 0;
|
||||
while let Some((&n, rest)) = src.split_first() {
|
||||
src = rest;
|
||||
let n = n as i8;
|
||||
if n >= 0 {
|
||||
let len = usize::from(n.unsigned_abs()) + 1;
|
||||
let (run, rest) = src.split_at(len.min(src.len()));
|
||||
src = rest;
|
||||
for &b in run {
|
||||
if let Some(d) = dst.get_mut(at) {
|
||||
*d = b;
|
||||
}
|
||||
at += 1;
|
||||
}
|
||||
} else if n != -128 {
|
||||
let Some((&b, rest)) = src.split_first() else { break };
|
||||
src = rest;
|
||||
let len = usize::from(n.unsigned_abs()) + 1;
|
||||
for d in dst.iter_mut().skip(at).take(len) {
|
||||
*d = b;
|
||||
}
|
||||
at += len;
|
||||
}
|
||||
if at >= dst.len() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The first `channels` channels of the image data (after its compression method), each as
|
||||
/// `height` rows of `row` bytes, one after the other.
|
||||
fn channel_data(data: &[u8], h: &Header<'_>, channels: usize, row: usize) -> Result<Vec<u8>, String> {
|
||||
let (rows, all) = (h.height as usize, h.channels);
|
||||
let mut r = Reader::new(data);
|
||||
let method = r.u16()?;
|
||||
let wanted = channels * rows * row;
|
||||
match method {
|
||||
0 => r.take(wanted).map(<[u8]>::to_vec),
|
||||
1 => {
|
||||
// Every row's byte count (4 bytes each in a PSB), channel by channel: those of the
|
||||
// channels read, then the others'.
|
||||
let size = if h.psb { 4 } else { 2 };
|
||||
let counts = r.take(channels * rows * size)?;
|
||||
r.take((all - channels) * rows * size)?;
|
||||
let counts = counts.chunks_exact(size).map(|c| c.iter().fold(0usize, |n, &b| n << 8 | usize::from(b)));
|
||||
let mut out = vec![0; wanted];
|
||||
for (dst, n) in out.chunks_exact_mut(row).zip(counts) {
|
||||
unpack_bits(r.take(n)?, dst);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
2 | 3 => {
|
||||
let mut out = Vec::new();
|
||||
flate2::read::ZlibDecoder::new(r.rest())
|
||||
.take(wanted as u64)
|
||||
.read_to_end(&mut out)
|
||||
.map_err(|e| format!("the PSD file's image data can't be read: {e}"))?;
|
||||
if out.len() < wanted {
|
||||
return Err(TRUNCATED.into());
|
||||
}
|
||||
if method == 3 {
|
||||
// Each row stores the difference from the sample before it.
|
||||
match h.depth {
|
||||
8 => out.chunks_exact_mut(row).for_each(|r| (1..r.len()).for_each(|i| r[i] = r[i].wrapping_add(r[i - 1]))),
|
||||
16 => out.chunks_exact_mut(row).for_each(|r| {
|
||||
let mut prev = 0u16;
|
||||
for s in r.as_chunks_mut::<2>().0 {
|
||||
prev = prev.wrapping_add(u16::from_be_bytes(*s));
|
||||
*s = prev.to_be_bytes();
|
||||
}
|
||||
}),
|
||||
_ => return Err("zipped 32-bit PSD image data with prediction can't be read".into()),
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
m => Err(format!("the PSD file's image data uses an unknown compression ({m})")),
|
||||
}
|
||||
}
|
||||
|
||||
/// sRGB's transfer curve, for 32-bit documents, whose values are linear.
|
||||
fn srgb_encode(v: f32) -> f32 {
|
||||
if v <= 0.003_130_8 { v * 12.92 } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 }
|
||||
}
|
||||
|
||||
/// Sample `x` of a channel row, 0..1.
|
||||
fn sample(row: &[u8], x: usize, depth: u16, linear: bool) -> f32 {
|
||||
match depth {
|
||||
1 => {
|
||||
// Bitmap: a set bit is black.
|
||||
let bit = row.get(x / 8).map_or(0, |b| (b >> (7 - x % 8)) & 1);
|
||||
if bit == 1 { 0.0 } else { 1.0 }
|
||||
}
|
||||
16 => row.get(x * 2..x * 2 + 2).map_or(0.0, |s| f32::from(u16::from_be_bytes([s[0], s[1]])) / 65535.0),
|
||||
32 => {
|
||||
let v = row.get(x * 4..x * 4 + 4).map_or(0.0, |s| f32::from_be_bytes([s[0], s[1], s[2], s[3]]));
|
||||
let v = if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 };
|
||||
if linear { srgb_encode(v) } else { v }
|
||||
}
|
||||
_ => row.get(x).map_or(0.0, |&b| f32::from(b) / 255.0),
|
||||
}
|
||||
}
|
||||
|
||||
fn byte(v: f32) -> u8 {
|
||||
(v.clamp(0.0, 1.0) * 255.0).round() as u8
|
||||
}
|
||||
|
||||
/// A Photoshop document's merged image as straight RGBA. CMYK converts through `cmyk` (ink
|
||||
/// amounts 0..1 → sRGB). Fails, without allocating, when the image would need more than
|
||||
/// `max_alloc` bytes.
|
||||
pub fn decode(bytes: &[u8], max_alloc: u64, cmyk: impl Fn([f32; 4]) -> [f32; 3]) -> Result<image::RgbaImage, String> {
|
||||
let mut r = Reader::new(bytes);
|
||||
let h = header(&mut r)?;
|
||||
let colors = h.mode.colors();
|
||||
let alpha = h.channels > colors && merged_alpha(h.layers, h.psb);
|
||||
let channels = colors + usize::from(alpha);
|
||||
let (w, rows) = (h.width as usize, h.height as usize);
|
||||
let row = row_bytes(w, h.depth);
|
||||
// The channels read and the RGBA image made of them.
|
||||
let need = (channels as u64 * row as u64).saturating_add(4 * w as u64).saturating_mul(rows as u64);
|
||||
if need > max_alloc {
|
||||
return Err(format!("the PSD image is too large to read ({} × {} pixels)", h.width, h.height));
|
||||
}
|
||||
let data = channel_data(r.rest(), &h, channels, row)?;
|
||||
let mut out = image::RgbaImage::new(h.width, h.height);
|
||||
let linear = h.depth == 32;
|
||||
for (y, line) in out.rows_mut().enumerate() {
|
||||
let planes: Vec<&[u8]> = (0..channels).map(|c| data.get((c * rows + y) * row..(c * rows + y + 1) * row).unwrap_or_default()).collect();
|
||||
for (x, px) in line.enumerate() {
|
||||
let v = |c: usize| planes.get(c).map_or(0.0, |p| sample(p, x, h.depth, linear && c < colors));
|
||||
let rgb = match h.mode {
|
||||
Mode::Bitmap | Mode::Gray => [v(0); 3],
|
||||
Mode::Indexed => {
|
||||
let i = usize::from(byte(v(0)));
|
||||
[0, 256, 512].map(|at| h.palette.get(at + i).map_or(0.0, |&c| f32::from(c) / 255.0))
|
||||
}
|
||||
Mode::Rgb => [v(0), v(1), v(2)],
|
||||
// Inks are stored as 1 − amount.
|
||||
Mode::Cmyk => cmyk([0, 1, 2, 3].map(|c| 1.0 - v(c))),
|
||||
Mode::Lab => lab_to_srgb(Lab { l: v(0) * 100.0, a: v(1) * 255.0 - 128.0, b: v(2) * 255.0 - 128.0 }),
|
||||
};
|
||||
let a = if alpha { v(colors) } else { 1.0 };
|
||||
// The merged image is stored on white: take the white back out.
|
||||
let straight = |c: f32| if a <= 0.0 { 0.0 } else { (c - (1.0 - a)) / a };
|
||||
let rgb = if alpha { rgb.map(straight) } else { rgb };
|
||||
px.0 = [byte(rgb[0]), byte(rgb[1]), byte(rgb[2]), byte(a)];
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
@@ -77,7 +77,7 @@ fn psd_is_listed_with_its_options_and_writes_one_file_per_artboard() {
|
||||
let psd = r["formats"].as_array().unwrap().iter().find(|f| f["id"] == "psd").unwrap().clone();
|
||||
assert_eq!(
|
||||
(psd["label"].as_str(), psd["write"].as_bool(), psd["read"].as_bool(), psd["raster"].as_bool()),
|
||||
(Some("PSD"), Some(true), Some(false), Some(true))
|
||||
(Some("PSD"), Some(true), Some(true), Some(true))
|
||||
);
|
||||
for k in ["colorModel", "layers", "maxEditability", "hiddenLayers", "embedIcc", "ppi", "antiAlias", "background"] {
|
||||
assert!(psd["options"].get(k).is_some(), "psd takes {k}");
|
||||
|
||||
@@ -0,0 +1,244 @@
|
||||
//! Reading Photoshop documents (#918): the merged image of every colour mode, depth and
|
||||
//! compression, PSB files, transparency, the resolution, and damaged files refused without a panic.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::psdread::{decode, is_psd, resolution};
|
||||
use super::*;
|
||||
|
||||
/// A Photoshop document built from its parts: `version` 1 (PSD) or 2 (PSB), the header's fields,
|
||||
/// then the colour mode data, resources, layer and mask section and image data as given.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn psd(
|
||||
version: u16,
|
||||
channels: u16,
|
||||
(w, h): (u32, u32),
|
||||
depth: u16,
|
||||
mode: u16,
|
||||
palette: &[u8],
|
||||
resources: &[u8],
|
||||
layers: &[u8],
|
||||
image: &[u8],
|
||||
) -> Vec<u8> {
|
||||
let mut f = b"8BPS".to_vec();
|
||||
f.extend(version.to_be_bytes());
|
||||
f.extend([0; 6]);
|
||||
f.extend(channels.to_be_bytes());
|
||||
f.extend(h.to_be_bytes());
|
||||
f.extend(w.to_be_bytes());
|
||||
f.extend(depth.to_be_bytes());
|
||||
f.extend(mode.to_be_bytes());
|
||||
for part in [palette, resources] {
|
||||
f.extend((part.len() as u32).to_be_bytes());
|
||||
f.extend(part);
|
||||
}
|
||||
if version == 2 {
|
||||
f.extend((layers.len() as u64).to_be_bytes());
|
||||
} else {
|
||||
f.extend((layers.len() as u32).to_be_bytes());
|
||||
}
|
||||
f.extend(layers);
|
||||
f.extend(image);
|
||||
f
|
||||
}
|
||||
|
||||
/// Raw image data: the compression method (0), then the planes.
|
||||
fn raw(planes: &[&[u8]]) -> Vec<u8> {
|
||||
let mut d = vec![0, 0];
|
||||
planes.iter().for_each(|p| d.extend(*p));
|
||||
d
|
||||
}
|
||||
|
||||
/// A layer and mask section whose layer info holds just the layer `count` (negative: the merged
|
||||
/// image's first extra channel is its transparency).
|
||||
fn layer_count(count: i16, psb: bool) -> Vec<u8> {
|
||||
let mut s = if psb { 2u64.to_be_bytes().to_vec() } else { 2u32.to_be_bytes().to_vec() };
|
||||
s.extend(count.to_be_bytes());
|
||||
s
|
||||
}
|
||||
|
||||
/// Straight sRGB through a naive CMYK conversion (tests don't depend on colour settings).
|
||||
fn naive(c: [f32; 4]) -> [f32; 3] {
|
||||
[0, 1, 2].map(|i| (1.0 - c[i]) * (1.0 - c[3]))
|
||||
}
|
||||
|
||||
fn pixels(f: &[u8]) -> Vec<[u8; 4]> {
|
||||
decode(f, 1 << 30, naive).unwrap().pixels().map(|p| p.0).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_colour_mode_and_depth_reads() {
|
||||
// Grayscale, 16 bits.
|
||||
let g = psd(1, 1, (2, 1), 16, 1, &[], &[], &[], &raw(&[&[0, 0, 0xff, 0xff]]));
|
||||
assert!(is_psd(&g));
|
||||
assert_eq!(pixels(&g), [[0, 0, 0, 255], [255, 255, 255, 255]]);
|
||||
// Bitmap: a set bit is black.
|
||||
let b = psd(1, 1, (9, 1), 1, 0, &[], &[], &[], &raw(&[&[0b1000_0000, 0b1000_0000]]));
|
||||
let px = pixels(&b);
|
||||
assert_eq!((px[0], px[1], px[8]), ([0, 0, 0, 255], [255, 255, 255, 255], [0, 0, 0, 255]));
|
||||
// Indexed: 256 reds, greens, blues.
|
||||
let mut palette = vec![0; 768];
|
||||
(palette[1], palette[257], palette[513]) = (10, 20, 30);
|
||||
let i = psd(1, 1, (1, 1), 8, 2, &palette, &[], &[], &raw(&[&[1]]));
|
||||
assert_eq!(pixels(&i), [[10, 20, 30, 255]]);
|
||||
// RGB, 32 bits: linear values, shown through sRGB's curve.
|
||||
let half = 0.5f32.to_be_bytes();
|
||||
let r = psd(1, 3, (1, 1), 32, 3, &[], &[], &[], &raw(&[&half, &half, &1.0f32.to_be_bytes()]));
|
||||
assert_eq!(pixels(&r), [[188, 188, 255, 255]]);
|
||||
// CMYK, inks stored as 255 − amount: 100 % K is black, no ink white.
|
||||
let c = psd(1, 4, (2, 1), 8, 4, &[], &[], &[], &raw(&[&[255, 255], &[255, 255], &[255, 255], &[0, 255]]));
|
||||
assert_eq!(pixels(&c), [[0, 0, 0, 255], [255, 255, 255, 255]]);
|
||||
// Lab: L 100, a 0, b 0 is white.
|
||||
let l = psd(1, 3, (1, 1), 8, 9, &[], &[], &[], &raw(&[&[255], &[128], &[128]]));
|
||||
assert!(pixels(&l)[0].iter().all(|&v| v >= 253), "{:?}", pixels(&l));
|
||||
// Duotone keeps its grayscale data in the merged image.
|
||||
assert_eq!(pixels(&psd(1, 1, (1, 1), 8, 8, &[0; 40], &[], &[], &raw(&[&[64]]))), [[64, 64, 64, 255]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transparency_comes_back_straight_and_extra_channels_without_it_stay_out() {
|
||||
// Half-transparent red, stored on white: (255, 127, 127) with alpha 128.
|
||||
let planes: [&[u8]; 4] = [&[255], &[127], &[127], &[128]];
|
||||
let with = psd(1, 4, (1, 1), 8, 3, &[], &[], &layer_count(-1, false), &raw(&planes));
|
||||
let [r, g, b, a] = pixels(&with)[0];
|
||||
assert!(r == 255 && g <= 1 && b <= 1 && a == 128, "{:?}", [r, g, b, a]);
|
||||
// A flat document's extra channel is a saved selection, not transparency.
|
||||
let flat = psd(1, 4, (1, 1), 8, 3, &[], &[], &[], &raw(&planes));
|
||||
assert_eq!(pixels(&flat), [[255, 127, 127, 255]]);
|
||||
// A 16-bit document says so in its Lr16 block (its layer info is empty).
|
||||
let mut layers = 0u32.to_be_bytes().to_vec();
|
||||
layers.extend(0u32.to_be_bytes());
|
||||
layers.extend(b"8BIMLr16");
|
||||
layers.extend(4u32.to_be_bytes());
|
||||
layers.extend((-1i16).to_be_bytes());
|
||||
layers.extend([0, 0]);
|
||||
let wide: [&[u8]; 4] = [&[0xff, 0xff], &[0x7f, 0x7f], &[0x7f, 0x7f], &[0x80, 0x80]];
|
||||
let deep = psd(1, 4, (1, 1), 16, 3, &[], &[], &layers, &raw(&wide));
|
||||
let [r, g, _, a] = pixels(&deep)[0];
|
||||
assert!(r == 255 && g <= 1 && a == 128, "{:?}", pixels(&deep));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packbits_zip_and_psb_files_read() {
|
||||
// PackBits in a PSB: 4-byte row counts, transparency from a negative layer count.
|
||||
let mut rle = vec![0, 1];
|
||||
for _ in 0..4 {
|
||||
rle.extend(2u32.to_be_bytes());
|
||||
}
|
||||
for v in [200u8, 100, 50, 255] {
|
||||
rle.extend([0xfe, v]); // a run of three
|
||||
}
|
||||
let big = psd(2, 4, (3, 1), 8, 3, &[], &[], &layer_count(-1, true), &rle);
|
||||
assert_eq!(pixels(&big), [[200, 100, 50, 255]; 3]);
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("document.open", &json!({"name": "big.psb", "dataBase64": vectorcraft_format::base64_encode(&big)})).unwrap();
|
||||
assert_eq!(r["format"], "psb");
|
||||
// Zipped with prediction, 16 bits: each sample is the difference from the one before.
|
||||
let deltas: Vec<u8> = [0x1000u16, 0x1000, 0x1000].iter().flat_map(|d| d.to_be_bytes()).collect();
|
||||
let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default());
|
||||
std::io::Write::write_all(&mut z, &deltas).unwrap();
|
||||
let mut zip = vec![0, 3];
|
||||
zip.extend(z.finish().unwrap());
|
||||
let px = pixels(&psd(1, 1, (3, 1), 16, 1, &[], &[], &[], &zip));
|
||||
assert_eq!(px.iter().map(|p| p[0]).collect::<Vec<_>>(), [16, 32, 48]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_resolution_resource_sizes_the_placed_image() {
|
||||
// ResolutionInfo (1005): 300 ppi across, 118.11 per cm (300 ppi) down.
|
||||
let mut res = b"8BIM".to_vec();
|
||||
res.extend(0x03edu16.to_be_bytes());
|
||||
res.extend([0, 0]); // an empty name, padded
|
||||
res.extend(16u32.to_be_bytes());
|
||||
res.extend((300u32 << 16).to_be_bytes());
|
||||
res.extend([0, 1, 0, 1]);
|
||||
res.extend(((118.11f64 * 65536.0) as u32).to_be_bytes());
|
||||
res.extend([0, 2, 0, 1]);
|
||||
let f = psd(1, 3, (300, 150), 8, 3, &[], &res, &[], &raw(&[&[9; 45_000], &[9; 45_000], &[9; 45_000]]));
|
||||
let (x, y) = resolution(&f).unwrap();
|
||||
assert!((x - 300.0).abs() < 1e-9 && (y - 300.0).abs() < 0.01, "{x} {y}");
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
|
||||
let r = s.execute("file.place", &json!({"name": "photo.psd", "dataBase64": vectorcraft_format::base64_encode(&f)})).unwrap();
|
||||
assert!(
|
||||
(r["width"].as_f64().unwrap() - 72.0).abs() < 0.01 && (r["height"].as_f64().unwrap() - 36.0).abs() < 0.01,
|
||||
"an inch by half an inch: {r}"
|
||||
);
|
||||
}
|
||||
|
||||
/// A 60 × 40 pt document: a red square on a transparent page, and a half-transparent blue one.
|
||||
fn art() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 60, "height": 40})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 30, "height": 40})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 40, "y": 0, "width": 20, "height": 40})).unwrap();
|
||||
s.execute("transparency.set", &json!({"opacity": 50})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn exported(s: &mut Session, p: Value) -> Vec<u8> {
|
||||
let r = s.execute("document.export", &p).unwrap();
|
||||
vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn psd_exports_open_and_place_again() {
|
||||
let mut s = art();
|
||||
let png = image::load_from_memory(&exported(&mut s, json!({"format": "png"}))).unwrap().to_rgba8();
|
||||
for (options, what) in [(json!({}), "layered RGB"), (json!({"layers": false}), "flat RGB"), (json!({"colorModel": "gray"}), "grey")] {
|
||||
let f = exported(&mut s, merge(json!({"format": "psd"}), options));
|
||||
let back = decode(&f, 1 << 30, naive).unwrap();
|
||||
assert_eq!(back.dimensions(), png.dimensions(), "{what}");
|
||||
let (red, clear, blue) = (back.get_pixel(10, 20).0, back.get_pixel(35, 20).0, back.get_pixel(50, 20).0);
|
||||
if what == "layered RGB" {
|
||||
assert_eq!((red, clear[3]), ([255, 0, 0, 255], 0), "{what}");
|
||||
assert!(blue[2] >= 250 && blue[0] <= 3 && (blue[3] as i32 - png.get_pixel(50, 20).0[3] as i32).abs() <= 1, "{what}: {blue:?}");
|
||||
} else if what == "flat RGB" {
|
||||
assert_eq!((red, clear), ([255, 0, 0, 255], [255, 255, 255, 255]), "{what}: flat files are on white");
|
||||
} else {
|
||||
assert!(red[0] == red[1] && red[3] == 255, "{what}: {red:?}");
|
||||
}
|
||||
// Open and Place take it by its content, whatever its name.
|
||||
let r = s.execute("document.open", &json!({"name": "back.bin", "dataBase64": vectorcraft_format::base64_encode(&f)})).unwrap();
|
||||
assert_eq!(r["format"], "psd", "{what}");
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!((d.artboards[0].rect.width() - 60.0).abs() < 1e-6, "{what}");
|
||||
}
|
||||
let r = s.execute("document.formats", &json!({})).unwrap();
|
||||
assert!(r["readable"].as_array().unwrap().iter().any(|v| v == "psd"));
|
||||
assert!(PLACE_EXTS.contains(&"psd") && PLACE_EXTS.contains(&"psb") && OPEN_EXTS.contains(&"psb"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn damaged_and_unsupported_files_are_refused_without_a_panic() {
|
||||
let good = psd(2, 4, (3, 2), 8, 3, &[], &[], &layer_count(-1, true), &raw(&[&[1; 6], &[2; 6], &[3; 6], &[4; 6]]));
|
||||
assert!(decode(&good, 1 << 30, naive).is_ok());
|
||||
for n in 0..good.len() {
|
||||
assert!(decode(&good[..n], 1 << 30, naive).is_err(), "cut at {n}");
|
||||
let _ = resolution(&good[..n]);
|
||||
}
|
||||
// Every byte changed in turn: an error or an image, never a panic.
|
||||
for i in 0..good.len() {
|
||||
for v in [0, 1, 0x7f, 0x80, 0xff] {
|
||||
let mut f = good.clone();
|
||||
f[i] = v;
|
||||
let _ = decode(&f, 1 << 30, naive);
|
||||
let _ = resolution(&f);
|
||||
}
|
||||
}
|
||||
// An image too large for the memory allowed is refused before anything is allocated.
|
||||
let huge = psd(2, 3, (300_000, 300_000), 16, 3, &[], &[], &[], &[0, 0]);
|
||||
assert!(decode(&huge, 1 << 30, naive).unwrap_err().contains("too large"));
|
||||
// Multichannel, and depths a mode doesn't have.
|
||||
assert!(decode(&psd(1, 2, (1, 1), 8, 7, &[], &[], &[], &raw(&[&[0], &[0]])), 1 << 30, naive).unwrap_err().contains("Multichannel"));
|
||||
assert!(decode(&psd(1, 4, (1, 1), 32, 4, &[], &[], &[], &[0, 0]), 1 << 30, naive).is_err());
|
||||
// A placed file with a damaged image reports it.
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let cut = &good[..good.len() - 3];
|
||||
assert!(s.execute("file.place", &json!({"name": "cut.psd", "dataBase64": vectorcraft_format::base64_encode(cut)})).is_err());
|
||||
}
|
||||
@@ -127,6 +127,36 @@ fn a_placed_link_records_the_file_and_the_document_saves_only_a_preview() {
|
||||
assert_eq!(saved["images"][&im.key]["proxy"], Value::Null, "an embedded image shows it too");
|
||||
}
|
||||
|
||||
/// A flat `w`×`h` Photoshop document of one colour (raw RGB, no layers).
|
||||
fn psd(w: u32, h: u32, rgb: [u8; 3]) -> Vec<u8> {
|
||||
let mut f = b"8BPS\0\x01\0\0\0\0\0\0\0\x03".to_vec();
|
||||
f.extend(h.to_be_bytes());
|
||||
f.extend(w.to_be_bytes());
|
||||
f.extend([0, 8, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
|
||||
for v in rgb {
|
||||
f.extend(std::iter::repeat_n(v, (w * h) as usize));
|
||||
}
|
||||
f
|
||||
}
|
||||
|
||||
/// #918: a Photoshop document placed linked shows its merged image, and updates when it changes.
|
||||
#[test]
|
||||
fn a_linked_photoshop_document_places_and_updates() {
|
||||
let dir = Folder::new("psd");
|
||||
let pic = dir.file("art/photo.psd");
|
||||
write(&pic, &psd(600, 300, RED));
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &pic);
|
||||
let link = image(&s, id).link.unwrap();
|
||||
assert_eq!(link.path, pic);
|
||||
assert!(near(centre_colour(&s.doc().unwrap().doc), RED));
|
||||
write(&pic, &psd(400, 400, BLUE));
|
||||
assert_eq!(s.execute("links.update", &json!({})).unwrap(), json!({"updated": [id.0], "missing": []}));
|
||||
let im = image(&s, id);
|
||||
assert_eq!((im.width, im.height), (400, 400));
|
||||
assert!(near(centre_colour(&s.doc().unwrap().doc), BLUE));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_relative_path_finds_the_file_after_the_folder_moves() {
|
||||
let a = Folder::new("move-a");
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Untrusted files never crash the app: garbage, truncated, mutated and hostile SVG, PDF and DXF input,
|
||||
//! mutated raster images placed with File → Place, and swatch (`.vcswatches`, `.gpl`, `.ase`), graphic style (`.vcstyles`) and flattener preset
|
||||
//! mutated raster images (Photoshop documents among them) placed with File → Place, and swatch (`.vcswatches`, `.gpl`, `.ase`), graphic style (`.vcstyles`) and flattener preset
|
||||
//! (`.vcflattener`) libraries, and native files (compressed, damaged, saved for older versions),
|
||||
//! must load as an error or as a document that then renders and exports, without a panic; nor may
|
||||
//! bitmaps, PDF and text pasted from other apps, nor EMF and WMF pictures (damaged files, records
|
||||
@@ -945,6 +945,19 @@ fn raster_samples() -> Vec<(&'static str, Vec<u8>)> {
|
||||
out.push((name, b));
|
||||
}
|
||||
out[0].1 = vectorcraft_engine::cmd::fileio::ppi::with_png_resolution(&out[0].1, (300.0, 150.0));
|
||||
// A layered PSD with transparency (as VectorCraft exports it), and a PackBits PSB by hand.
|
||||
let mut s = rich_session();
|
||||
let r = s.execute("document.export", &json!({"format": "psd", "ppi": 2})).unwrap();
|
||||
out.push(("a.psd", vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap()));
|
||||
let mut psb = b"8BPS\0\x02\0\0\0\0\0\0\0\x04\0\0\0\x02\0\0\0\x03\0\x08\0\x03".to_vec();
|
||||
psb.extend([0; 8]);
|
||||
psb.extend(10u64.to_be_bytes());
|
||||
psb.extend(2u64.to_be_bytes());
|
||||
psb.extend((-1i16).to_be_bytes());
|
||||
psb.extend([0, 1]);
|
||||
psb.extend((0..8).flat_map(|_| 2u32.to_be_bytes()));
|
||||
psb.extend((0..8u8).flat_map(|v| [0xfe, v * 30]));
|
||||
out.push(("a.psb", psb));
|
||||
out
|
||||
}
|
||||
|
||||
@@ -954,7 +967,7 @@ proptest! {
|
||||
/// Mutated image headers (resolution metadata, chunk and segment lengths) never crash reading
|
||||
/// their resolution or placing them.
|
||||
#[test]
|
||||
fn mutated_images_place_without_panics(which in 0usize..4, cut in 0usize..400, edits in prop::collection::vec((0usize..120, any::<u8>()), 0..12)) {
|
||||
fn mutated_images_place_without_panics(which in 0usize..6, cut in 0usize..4000, edits in prop::collection::vec((0usize..120, any::<u8>()), 0..12)) {
|
||||
let (name, mut bytes) = raster_samples().swap_remove(which);
|
||||
for (at, b) in edits {
|
||||
if let Some(x) = bytes.get_mut(at) {
|
||||
|
||||
@@ -3861,3 +3861,13 @@ axis Both Ambos
|
||||
@msg automation path rejected: cannot resolve {path}: {e} ruta de automatización rechazada: no se puede resolver {path}: {e}
|
||||
@msg automation path rejected: parent traversal below a folder that doesn't exist: {path} ruta de automatización rechazada: sube (..) desde una carpeta que no existe: {path}
|
||||
@msg automation path rejected: reserved device names are not allowed: {path} ruta de automatización rechazada: no se permiten nombres de dispositivo reservados: {path}
|
||||
@msg Multichannel PSD files can't be read: save it in RGB, CMYK or Grayscale mode Los archivos PSD en modo Multicanal no se pueden leer: guárdalo en modo RGB, CMYK o Escala de grises
|
||||
@msg not a PSD file no es un documento PSD
|
||||
@msg the PSD file has an unknown colour mode ({m}) el archivo PSD tiene un modo de color desconocido ({m})
|
||||
@msg the PSD file's image data uses an unknown compression ({m}) los datos de imagen del archivo PSD usan una compresión desconocida ({m})
|
||||
@msg the PSD image is too large to read ({_1} × {_2} pixels) la imagen PSD es demasiado grande para leerla ({_1} × {_2} píxeles)
|
||||
@msg zipped 32-bit PSD image data with prediction can't be read no se pueden leer datos de imagen PSD de 32 bits comprimidos en ZIP con predicción
|
||||
@msg {depth}-bit PSD files in this colour mode can't be read los archivos PSD de {depth} bits en este modo de color no se pueden leer
|
||||
@msg the PSD file is cut short el archivo PSD está incompleto
|
||||
@msg the PSD file's header is damaged el encabezado del archivo PSD está dañado
|
||||
@msg the PSD file's image data can't be read: {e} no se pueden leer los datos de imagen del archivo PSD: {e}
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -3872,3 +3872,13 @@ axis Both Les deux
|
||||
@msg automation path rejected: cannot resolve {path}: {e} chemin d’automatisation refusé : impossible de résoudre {path} : {e}
|
||||
@msg automation path rejected: parent traversal below a folder that doesn't exist: {path} chemin d’automatisation refusé : remonte (..) depuis un dossier qui n’existe pas : {path}
|
||||
@msg automation path rejected: reserved device names are not allowed: {path} chemin d’automatisation refusé : les noms de périphériques réservés ne sont pas autorisés : {path}
|
||||
@msg Multichannel PSD files can't be read: save it in RGB, CMYK or Grayscale mode Les fichiers PSD en mode Multicouche ne peuvent pas être lus : enregistrez-le en mode RVB, CMJN ou Niveaux de gris
|
||||
@msg not a PSD file ce n'est pas un document PSD
|
||||
@msg the PSD file has an unknown colour mode ({m}) le fichier PSD a un mode colorimétrique inconnu ({m})
|
||||
@msg the PSD file's image data uses an unknown compression ({m}) les données d'image du fichier PSD utilisent une compression inconnue ({m})
|
||||
@msg the PSD image is too large to read ({_1} × {_2} pixels) l'image PSD est trop grande pour être lue ({_1} × {_2} pixels)
|
||||
@msg zipped 32-bit PSD image data with prediction can't be read les données d'image PSD 32 bits compressées en ZIP avec prédiction ne peuvent pas être lues
|
||||
@msg {depth}-bit PSD files in this colour mode can't be read les fichiers PSD {depth} bits dans ce mode colorimétrique ne peuvent pas être lus
|
||||
@msg the PSD file is cut short le fichier PSD est tronqué
|
||||
@msg the PSD file's header is damaged l'en-tête du fichier PSD est endommagé
|
||||
@msg the PSD file's image data can't be read: {e} les données d'image du fichier PSD ne peuvent pas être lues : {e}
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -3861,3 +3861,13 @@ axis Both Entrambi
|
||||
@msg automation path rejected: cannot resolve {path}: {e} percorso di automazione rifiutato: impossibile risolvere {path}: {e}
|
||||
@msg automation path rejected: parent traversal below a folder that doesn't exist: {path} percorso di automazione rifiutato: risale (..) da una cartella che non esiste: {path}
|
||||
@msg automation path rejected: reserved device names are not allowed: {path} percorso di automazione rifiutato: i nomi di dispositivo riservati non sono consentiti: {path}
|
||||
@msg Multichannel PSD files can't be read: save it in RGB, CMYK or Grayscale mode I file PSD in modalità Multicanale non possono essere letti: salvalo in modalità RGB, CMYK o Scala di grigio
|
||||
@msg not a PSD file non è un documento PSD
|
||||
@msg the PSD file has an unknown colour mode ({m}) il file PSD ha un metodo colore sconosciuto ({m})
|
||||
@msg the PSD file's image data uses an unknown compression ({m}) i dati immagine del file PSD usano una compressione sconosciuta ({m})
|
||||
@msg the PSD image is too large to read ({_1} × {_2} pixels) l'immagine PSD è troppo grande per essere letta ({_1} × {_2} pixel)
|
||||
@msg zipped 32-bit PSD image data with prediction can't be read i dati immagine PSD a 32 bit compressi ZIP con previsione non possono essere letti
|
||||
@msg {depth}-bit PSD files in this colour mode can't be read i file PSD a {depth} bit in questo metodo colore non possono essere letti
|
||||
@msg the PSD file is cut short il file PSD è troncato
|
||||
@msg the PSD file's header is damaged l'intestazione del file PSD è danneggiata
|
||||
@msg the PSD file's image data can't be read: {e} i dati immagine del file PSD non possono essere letti: {e}
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -3853,3 +3853,13 @@ theme Appearance 外観
|
||||
@msg automation path rejected: cannot resolve {path}: {e} 自動化のパスを拒否しました: {path} を解決できません: {e}
|
||||
@msg automation path rejected: parent traversal below a folder that doesn't exist: {path} 自動化のパスを拒否しました: 存在しないフォルダーから上の階層 (..) へ移動しています: {path}
|
||||
@msg automation path rejected: reserved device names are not allowed: {path} 自動化のパスを拒否しました: 予約済みのデバイス名は使用できません: {path}
|
||||
@msg Multichannel PSD files can't be read: save it in RGB, CMYK or Grayscale mode マルチチャンネルの PSD ファイルは読み込めません:RGB、CMYK またはグレースケールモードで保存してください
|
||||
@msg not a PSD file PSD ドキュメントではありません
|
||||
@msg the PSD file has an unknown colour mode ({m}) PSD ファイルのカラーモードが不明です({m})
|
||||
@msg the PSD file's image data uses an unknown compression ({m}) PSD ファイルの画像データの圧縮方式が不明です({m})
|
||||
@msg the PSD image is too large to read ({_1} × {_2} pixels) PSD 画像が大きすぎて読み込めません({_1} × {_2} ピクセル)
|
||||
@msg zipped 32-bit PSD image data with prediction can't be read 予測付き ZIP 圧縮の 32 bit PSD 画像データは読み込めません
|
||||
@msg {depth}-bit PSD files in this colour mode can't be read このカラーモードの {depth} bit PSD ファイルは読み込めません
|
||||
@msg the PSD file is cut short PSD ファイルが途中で切れています
|
||||
@msg the PSD file's header is damaged PSD ファイルのヘッダーが破損しています
|
||||
@msg the PSD file's image data can't be read: {e} PSD ファイルの画像データを読み込めません:{e}
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -3859,3 +3859,13 @@ axis Both Оба
|
||||
@msg automation path rejected: cannot resolve {path}: {e} путь автоматизации отклонён: не удаётся определить {path}: {e}
|
||||
@msg automation path rejected: parent traversal below a folder that doesn't exist: {path} путь автоматизации отклонён: переход вверх (..) из несуществующей папки: {path}
|
||||
@msg automation path rejected: reserved device names are not allowed: {path} путь автоматизации отклонён: зарезервированные имена устройств недопустимы: {path}
|
||||
@msg Multichannel PSD files can't be read: save it in RGB, CMYK or Grayscale mode Файлы PSD в режиме «Многоканальный» не читаются: сохраните его в режиме RGB, CMYK или «Градации серого»
|
||||
@msg not a PSD file это не документ PSD
|
||||
@msg the PSD file has an unknown colour mode ({m}) у файла PSD неизвестный цветовой режим ({m})
|
||||
@msg the PSD file's image data uses an unknown compression ({m}) данные изображения файла PSD используют неизвестное сжатие ({m})
|
||||
@msg the PSD image is too large to read ({_1} × {_2} pixels) изображение PSD слишком велико для чтения ({_1} × {_2} пикс.)
|
||||
@msg zipped 32-bit PSD image data with prediction can't be read 32-битные данные изображения PSD со сжатием ZIP с предсказанием не читаются
|
||||
@msg {depth}-bit PSD files in this colour mode can't be read {depth}-битные файлы PSD в этом цветовом режиме не читаются
|
||||
@msg the PSD file is cut short файл PSD обрезан
|
||||
@msg the PSD file's header is damaged заголовок файла PSD повреждён
|
||||
@msg the PSD file's image data can't be read: {e} не удаётся прочитать данные изображения файла PSD: {e}
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -3844,3 +3844,13 @@ axis Both Обидві
|
||||
@msg automation path rejected: cannot resolve {path}: {e} шлях автоматизації відхилено: не вдається визначити {path}: {e}
|
||||
@msg automation path rejected: parent traversal below a folder that doesn't exist: {path} шлях автоматизації відхилено: перехід угору (..) з папки, якої не існує: {path}
|
||||
@msg automation path rejected: reserved device names are not allowed: {path} шлях автоматизації відхилено: зарезервовані імена пристроїв не дозволені: {path}
|
||||
@msg Multichannel PSD files can't be read: save it in RGB, CMYK or Grayscale mode Файли PSD у режимі «Багатоканальний» не читаються: збережіть його в режимі RGB, CMYK або «Відтінки сірого»
|
||||
@msg not a PSD file це не документ PSD
|
||||
@msg the PSD file has an unknown colour mode ({m}) файл PSD має невідомий колірний режим ({m})
|
||||
@msg the PSD file's image data uses an unknown compression ({m}) дані зображення файлу PSD використовують невідоме стиснення ({m})
|
||||
@msg the PSD image is too large to read ({_1} × {_2} pixels) зображення PSD завелике для читання ({_1} × {_2} пікс.)
|
||||
@msg zipped 32-bit PSD image data with prediction can't be read 32-бітні дані зображення PSD зі стисненням ZIP із передбаченням не читаються
|
||||
@msg {depth}-bit PSD files in this colour mode can't be read {depth}-бітні файли PSD у цьому колірному режимі не читаються
|
||||
@msg the PSD file is cut short файл PSD обрізаний
|
||||
@msg the PSD file's header is damaged заголовок файлу PSD пошкоджено
|
||||
@msg the PSD file's image data can't be read: {e} не вдається прочитати дані зображення файлу PSD: {e}
|
||||
|
Can't render this file because it contains an unexpected character in line 659 and column 40.
|
+9
-3
@@ -275,7 +275,7 @@ objects' fills or strokes differ (`fillMixed` / `strokeMixed`, drawn as a "?" pr
|
||||
| `invoke_menu` | `{command, params?}` | Invokes a menu item by command id. Includes UI commands such as `view.*` and `window.*` in remote mode. |
|
||||
| `open_panel` | `{panel}` | Remote only. `panel` is a panel id (`layers`, `swatches`, `colorGuide`, …, as `window.panel` takes) or its display label (`"Color Guide"`), in any case. |
|
||||
| `screenshot` | `{path?, scale?, artboard?, window?}` | Returns MCP image content (`image/png`, base64) plus a text block. Renders the artboard; `window:true` captures the app window (remote only). With `path` the backend (the headless session or the app) writes the PNG there too. |
|
||||
| `open_file` | `{path}` | Opens any readable file as a new active document: `.vectorcraft`/`.drawcraft`, `.vctemplate`, `.svg`/`.svgz`, `.pdf`/`.ai`, `.ait`, `.eps`, `.dxf`, `.emf`, `.wmf`, PNG, JPEG, GIF, WebP, TIFF, BMP (an image opens as a document of its pixel size). Templates (`.vctemplate`, `.ait`) open as a new untitled document. PDF, `.ai` and SVG files saved with Preserve Editing reopen as the document they carry. The reply is `document.open`'s: its `warnings` say what didn't come in as it was (an EPS whose PostScript can't be read opens as its preview, and the warning names the PostScript error, the operator and the procedure). `run_command document.formats` lists the formats. |
|
||||
| `open_file` | `{path}` | Opens any readable file as a new active document: `.vectorcraft`/`.drawcraft`, `.vctemplate`, `.svg`/`.svgz`, `.pdf`/`.ai`, `.ait`, `.eps`, `.dxf`, `.emf`, `.wmf`, PNG, JPEG, GIF, WebP, TIFF, BMP, PSD/PSB (an image opens as a document of its pixel size; a Photoshop file as its merged image). Templates (`.vctemplate`, `.ait`) open as a new untitled document. PDF, `.ai` and SVG files saved with Preserve Editing reopen as the document they carry. The reply is `document.open`'s: its `warnings` say what didn't come in as it was (an EPS whose PostScript can't be read opens as its preview, and the warning names the PostScript error, the operator and the procedure). `run_command document.formats` lists the formats. |
|
||||
| `save_file` | `{path?}` | Runs `document.save`: the document's own file in its own format (native `.vectorcraft` unless it was opened from or saved as SVG, PDF or a restorable `.ai`; then `warnings` say what that format loses). A path's extension picks the format (`.vectorcraft`, `.vctemplate`, `.pdf`, `.svg`, `.svgz`, `.ai`: a PDF carrying the native document, which reopens editable). |
|
||||
| `export` | `{path?, format?, scale?, artboard?, range?, selection?, outlineText?, options?}` | `svg`, `svgz`, `pdf`, `eps`, `dxf`, `emf`, `wmf`, `png`, `jpg`, `webp`, `gif`, `png8` (an indexed `.png`), `tiff`, `bmp`, `tga`, `psd` (layered), `txt` (the document's text), `vectorcraft` or `template` (a native template). The tool's `format` enum and `document.formats` list them, generated from the engine's format table. When `format` is omitted, it comes from the path's extension. PDF writes one page per artboard: all of them, or `artboard` (0-based) / `range` (`"1-3, 5"`, 1-based); the other formats write one artboard. `options` carries more format options (e.g. `{"quality": 80}` for JPEG). `selection: true` exports the selected objects cropped to their bounds (the reply adds their `bounds`, and reports `format` and the encoder's `warnings` as a whole-document export does); `outlineText: true` writes SVG text as paths. Template layers are left out, live effects are kept, and exporting `vectorcraft` never changes the document's path. Without `path` the bytes come back as `dataBase64`. Both backends run the same `document.export` call. |
|
||||
| `add_text` | `{text, x?, y?, width?, height?, path?, mode?, pathEffect?, size?, font?, color?}` | Point type at (x, y); area type with `width`/`height`; or `path` + `mode` (`area`/`onPath`) to flow text in or along a path, with `pathEffect` (`rainbow`, `skew`, `3dRibbon`, `stairStep`, `gravity`). |
|
||||
@@ -1690,7 +1690,7 @@ passed straight back to `file.new`. Print presets and sizes without `units` star
|
||||
|
||||
`file.place` puts another file's art into the active document as one undo step without touching the clipboard:
|
||||
a raster image at 100% of its physical size (the resolution its file declares, else 72 ppi; linked to its `path`
|
||||
unless `link: false`), an SVG as one group, a PDF/.ai page as one clipped group, with the images, symbols, patterns
|
||||
unless `link: false`; a Photoshop document as its merged image), an SVG as one group, a PDF/.ai page as one clipped group, with the images, symbols, patterns
|
||||
and swatches it uses. A VectorCraft document read from `path` is a placed document: one locked object showing its
|
||||
artboard `page` (or, with `crop: "bounding"`, its art's bounds), linked to the file and read again when it changes
|
||||
(see Linked images), and vectors in every output; with `link: false` (or from `dataBase64`) it is an editable copy
|
||||
@@ -2289,7 +2289,13 @@ show) is the flat render. `maxEditability: true` turns layers and sublayers into
|
||||
named as the Layers panel names it (text objects by their text); layers with a clipping mask, an opacity mask, an
|
||||
appearance of their own or knockout stay one pixel layer. Hidden layers and objects are left out unless
|
||||
`hiddenLayers: true` writes them as hidden layers. `layers: false` writes one flat image, on white where nothing is
|
||||
drawn. Files are at most 30000 pixels a side; PSD files don't open in VectorCraft.
|
||||
drawn. Files are at most 30000 pixels a side.
|
||||
|
||||
Photoshop documents (`.psd`, and `.psb`, the large document format) open and place as their merged image, the
|
||||
flattened picture every Photoshop file carries (layers aren't read): Bitmap, Grayscale, Duotone, Indexed, RGB, CMYK
|
||||
(converted with the colour settings' CMYK) and Lab, at 1, 8, 16 and 32 bits per channel, sized by their resolution.
|
||||
A document with transparency keeps it. `file.place {path}` links the file like any image (`links.update` reads it
|
||||
again when it changes); Multichannel files are refused.
|
||||
|
||||
```json
|
||||
{"name":"export","arguments":{"path":"/tmp/poster.psd","options":{"ppi":300,"maxEditability":true}}}
|
||||
|
||||
Reference in new issue
Block a user