Compare commits
22
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b4c89f7301 | ||
|
|
20c1a1621e | ||
|
|
d57134a308 | ||
|
|
9449c92136 | ||
|
|
d62ecfe33a | ||
|
|
c738400ebb | ||
|
|
c71af3079c | ||
|
|
7fb2c47006 | ||
|
|
a61aa93c1c | ||
|
|
552945f4e7 | ||
|
|
7bf002af2b | ||
|
|
3da4080b5e | ||
|
|
0eb4ce5e98 | ||
|
|
be51213f0d | ||
|
|
fe2d2ca173 | ||
|
|
b3ed7df2a4 | ||
|
|
93fb184939 | ||
|
|
2ef32bb1a2 | ||
|
|
5ccbbcca3f | ||
|
|
11beb8fff1 | ||
|
|
04eb5e52c8 | ||
|
|
de3f53b24d |
No files matched your search
@@ -201,10 +201,10 @@ For the experimental, unsupported 64-bit Windows 7 build, see [Windows 7 instruc
|
||||
VectorCraft is under active development. [**ROADMAP.md**](ROADMAP.md) covers what ships today, the
|
||||
milestones, and honest time-to-parity estimates.
|
||||
|
||||
**Where we are (2026-10-09):** roughly 69–75% of Illustrator's features exist and work, and about 40–55% of
|
||||
**Where we are (2026-10-10):** roughly 69–75% of Illustrator's features exist and work, and about 40–55% of
|
||||
"a power user can't tell the difference". Everyday vector illustration is close to usable: drawing and path tools,
|
||||
Pathfinder and Shape Builder, paint, gradients, appearance and transparency, type with styles, threading and Hebrew/Arabic bidirectional layout, and
|
||||
files (SVG, PDF and PDF-compatible `.ai` with PDF/X, EPS, DXF, EMF/WMF, raster formats and PSD, Print, Package).
|
||||
files (SVG, PDF and PDF-compatible `.ai` with PDF/X, EPS, DXF, EMF/WMF, raster formats, PSD out and PSD/PSB in as their merged image, Print, Package).
|
||||
Affinity documents (`.af` from Affinity 3, `.afdesign`, `.afpub` and, by their content, `.afphoto` from Affinity 1 and 2) open
|
||||
and place natively: layers, groups, artboards and pages, curves and shapes, fills, gradients and strokes, clipping
|
||||
and masks, text and images, with what didn't come in (effects, adjustments, brushes, master pages…) listed in the
|
||||
|
||||
+12
-12
@@ -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
|
||||
|
||||
@@ -35,10 +35,10 @@ since 2026-10-01.
|
||||
|---|---|---|
|
||||
| **Breadth:** menus, tools and panels exist | ~90% | 13 menu items still stubbed; every tool implemented except Touch Type; 51 panel modules |
|
||||
| **Depth:** each feature behaves like Illustrator | ~69–75% | Strong: paint, appearance and colour (M3), Pathfinder and booleans, selection, drawing, files (M4). Weak: advanced type (~45%; inline symbols in text are beyond parity and don't raise it), brushes and symbols (in progress), raster effects (~20%) |
|
||||
| **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 |
|
||||
| **Large missing subsystems** | 0–20% | 3D & Materials (0%), Photoshop-style raster effects and the Effect Gallery (~10 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 |
|
||||
@@ -53,13 +53,13 @@ Ordered by how much each gap blocks someone from switching. Sizes are one-agent
|
||||
1. **Interaction fidelity:** go tool by tool and panel by panel against `plan/illustrator/05-tools.md`,
|
||||
`06-panels.md` and `09-shortcuts.md`, covering modifier keys, cursors, the Properties panel per context and
|
||||
isolation mode. The Shaper’s rough-square recognition and shape orientation steps are corrected; Shaper Groups now retain editable originals for region merges/punches and separate fill/stroke edits; their construction-mode widget and gesture refinements remain. 60–90 h.
|
||||
2. **Photoshop-style raster effects and the Effect Gallery:** about 47 filters (Artistic, Brush Strokes, Distort,
|
||||
Sketch, Stylize, Texture, Video) and the Effect Gallery. The pixel-filter pipeline is in place
|
||||
2. **Photoshop-style raster effects and the Effect Gallery:** about 45 filters (Artistic, Brush Strokes, Distort,
|
||||
Sketch, Stylize, Texture) and the Effect Gallery. The pixel-filter pipeline is in place
|
||||
(`vectorcraft_effects::pixel`: the object rendered offscreen, filtered in stack order with Gaussian Blur and
|
||||
Feather, cached while panning, images in PDF/SVG/Expand Appearance) with Blur › Radial Blur and Smart Blur
|
||||
(Normal mode only), Pixelate › Color Halftone, Crystallize, Mezzotint and Pointillize, Sharpen › Unsharp Mask and
|
||||
Stylize › Glowing Edges; each new filter is now one function, a catalogue row, menu and translations. Parallelizes
|
||||
well across agents. 24–37 h.
|
||||
(Normal mode only), Pixelate › Color Halftone, Crystallize, Mezzotint and Pointillize, Sharpen › Unsharp Mask,
|
||||
Stylize › Glowing Edges and Video › De-Interlace and NTSC Colors; each new filter is now one function, a catalogue row, menu and translations. Parallelizes
|
||||
well across agents. 23–36 h.
|
||||
3. **3D and Materials:** Extrude & Bevel, Revolve, Inflate and Rotate with lighting and materials, using a software
|
||||
renderer in its own crate (layering allows it below L6), with output in SVG/PDF as rasters or projected vectors.
|
||||
The largest single gap. 50–80 h.
|
||||
@@ -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).
|
||||
@@ -223,7 +223,7 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale)
|
||||
| Strokes, brushes, width profiles | 5 | 89% | Scatter, Art and Pattern Brush Options (Calligraphic and Bristle done), brush libraries (generated in code), pen pressure on macOS (the windowing layer reports none there), brushes driven by pen tilt, bearing and barrel rotation (6D art pens) | 10–18 |
|
||||
| Appearance, transparency, graphic styles, masks | 5 | 98% | raster effect reach in preview bounds (flattener presets apply in PDF, EPS and print) | 1–2 |
|
||||
| Live vector effects | 5 | 85% | Outline Object, Pathfinder Hard/Soft Mix and Trap, SVG Filters, the Transform effect's Transform Objects/Patterns and Scale Strokes & Effects options | 6–10 |
|
||||
| Raster effects (Effect Gallery, Document Raster Effects Settings) | 4 | 28% | ~47 Photoshop-style filters (Artistic, Brush Strokes, Distort, Sketch, Stylize, Texture, Video), Smart Blur's Edge Only / Overlay Edge modes and the Effect Gallery; Document Raster Effects Settings, raster effects in PDF, the pixel-filter pipeline, Radial Blur, Smart Blur, Unsharp Mask, Glowing Edges and Pixelate (Color Halftone, Crystallize, Mezzotint, Pointillize) are done | 24–37 |
|
||||
| Raster effects (Effect Gallery, Document Raster Effects Settings) | 4 | 29% | ~45 Photoshop-style filters (Artistic, Brush Strokes, Distort, Sketch, Stylize, Texture), Smart Blur's Edge Only / Overlay Edge modes and the Effect Gallery; Document Raster Effects Settings, raster effects in PDF, the pixel-filter pipeline, Radial Blur, Smart Blur, Unsharp Mask, Glowing Edges, Pixelate (Color Halftone, Crystallize, Mezzotint, Pointillize) and Video (De-Interlace, NTSC Colors) are done | 23–36 |
|
||||
| 3D and Materials | 4 | 0% | Extrude & Bevel, Revolve, Inflate, Rotate, lighting, materials (software renderer) | 50–80 |
|
||||
| Type core | 9 | 80% | Middle Eastern features beyond bidi layout and Paragraph Direction (Character Direction, digit types, kashidas, the Middle Eastern composers, editable bidirectional SVG text, a split caret where directions meet); Hyphenation… and Justification… options (Every-line Composer for justified and ragged text, per object, is done; it is tuned by eye, not yet compared side by side with Illustrator; mixed type sizes in a paragraph still break single-line), Optical Margin Alignment, paragraph spacing limit for vertically justified area type, hidden characters, paragraph attributes in the Type tool's copy and paste (the characters keep their styles, the paragraphs take the destination's), mixed-value display in the Paragraph panel for a selection across differing paragraphs, Transform Again after a type-area resize (it scales the type), partial selection of type-area anchors by marquee | 14–19 |
|
||||
| Type advanced | 4 | 50% | CJK composition for vertical type (ruby, mojikumi beyond Line-end Punctuation Half Width — the other sets (and their paragraph-start bracket and indent rules), custom kinsoku sets (beyond Hard, Soft and None) and the Mojikumi Settings dialog —, proportional vertical metrics, manual tate-chu-yoko), variable font axis sliders (named instances are styles), tab leaders, spell check (open dictionary), Touch Type, Retype; vertical point/area/path type and Type Orientation have initial support (beyond parity, not scored: inline symbols in text) | 20–28 |
|
||||
@@ -232,12 +232,12 @@ 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 |
|
||||
| UI chrome (panels, contextual Properties, workspaces, prefs) | 6 | 78% | macOS native menu dismissal fixed (M14.8); remaining: Variables, SVG Interactivity, Properties per context, Consolidate All Windows, floating panels outside the app window and docked into any group, context menus beyond the canvas (Links, Asset Export, CSS Properties, Attributes and the canvas context menu are done), about 17 Preferences options stored but not yet acted on (#394: Highlight Alternate Glyphs, Open Documents As Tabs, Real-time Drawing, hyphenation language, Appearance of Black, devices…) | 14–22 |
|
||||
| Libraries, Links, Package | 2 | 80% | the Libraries panel is local only (no cloud by design: libraries are files on this machine) and has no shared libraries, linked graphics or gradients and patterns as items yet; its graphics, colours and text styles are done (#745); Links and Package are done; placed VectorCraft documents are done (linked by default, vectors in every output, previews, Break Link, Expand, Edit Original, refresh on save) | 2–3 |
|
||||
| Libraries, Links, Package | 2 | 82% | the Libraries panel is local only (no cloud by design: libraries are files on this machine) and has no shared libraries, linked graphics or gradients and patterns as items yet; its graphics, colours and text styles (#745) and its search, groups and library export/import as `.vclibrary` files (#926) are done; Links and Package are done; placed VectorCraft documents are done (linked by default, vectors in every output, previews, Break Link, Expand, Edit Original, refresh on save) | 2–3 |
|
||||
| **Feature parity** | **103** | **~75%** | | **~210–330** |
|
||||
| Interaction-fidelity pass (side by side with Illustrator: every tool modifier, cursor, dialog, Properties context) | | | | 60–90 |
|
||||
| Hardening (big-file corpus, fuzzing, cross-platform and browser QA, accessibility, packaging) | | | | 50–80 |
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -144,6 +144,7 @@ const WARP: &[&str] = &["Effect", "Warp"];
|
||||
const BLUR: &[&str] = &["Effect", "Blur"];
|
||||
const SHARPEN: &[&str] = &["Effect", "Sharpen"];
|
||||
const PIXELATE: &[&str] = &["Effect", "Pixelate"];
|
||||
const VIDEO: &[&str] = &["Effect", "Video"];
|
||||
const PATHFINDER: &[&str] = &["Effect", "Pathfinder"];
|
||||
const PLUGINS: &[&str] = &["Effect", "Plug-ins"];
|
||||
const ADJUST: &[&str] = &["Effect", "Color Adjustments"];
|
||||
@@ -331,6 +332,20 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
|
||||
"{cellSize: pt 3..300 (5)} redraws the object as randomly placed dots of its colours on a white canvas",
|
||||
json!({"cellSize": 5.0}),
|
||||
),
|
||||
r(
|
||||
"video.deinterlace",
|
||||
"De-Interlace…",
|
||||
VIDEO,
|
||||
"{eliminate: \"odd\"|\"even\" (\"odd\"; which field lines are taken out), create: \"duplication\"|\"interpolation\" (\"duplication\"; a line taken out becomes a copy of the line above, or the average of the lines above and below)} the field lines are the rows of the document's raster grid (Document Raster Effects Settings › Resolution), numbered from 1 at the top of the page",
|
||||
json!({"eliminate": "odd", "create": "duplication"}),
|
||||
),
|
||||
r(
|
||||
"video.ntscColors",
|
||||
"NTSC Colors",
|
||||
VIDEO,
|
||||
"{} makes colours a television signal can't carry (luma plus chroma past 110 % of white, or luma minus chroma below −20 %) less saturated, keeping their brightness",
|
||||
json!({}),
|
||||
),
|
||||
];
|
||||
v.extend([
|
||||
g(
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Photoshop-style raster effects (Effect › Blur › Radial Blur and Smart Blur, Pixelate › Color
|
||||
//! Halftone, Crystallize, Mezzotint and Pointillize, Sharpen › Unsharp Mask, and Stylize › Glowing
|
||||
//! Edges): filters over premultiplied RGBA8 pixels.
|
||||
//! Halftone, Crystallize, Mezzotint and Pointillize, Sharpen › Unsharp Mask, Stylize › Glowing
|
||||
//! Edges, and Video › De-Interlace and NTSC Colors): filters over premultiplied RGBA8 pixels.
|
||||
//!
|
||||
//! - Every distance is in document units (points) and becomes pixels through the raster's
|
||||
//! [`PixelSpace::px`], so an effect looks the same at any zoom and at any Document Raster Effects
|
||||
@@ -13,6 +13,7 @@ mod blur;
|
||||
mod edges;
|
||||
mod pixelate;
|
||||
mod sharpen;
|
||||
mod video;
|
||||
|
||||
use serde_json::Value;
|
||||
use vectorcraft_geom::{Affine, Point, Rect};
|
||||
@@ -22,7 +23,7 @@ use crate::util::{num, text};
|
||||
pub use pixelate::{MEZZOTINT_TYPES, Mezzotint};
|
||||
|
||||
/// The Photoshop-style effect ids (all raster effects, see [`crate::is_raster`]).
|
||||
pub const PIXEL_EFFECTS: [&str; 8] = [
|
||||
pub const PIXEL_EFFECTS: [&str; 10] = [
|
||||
"blur.radial",
|
||||
"blur.smart",
|
||||
"pixelate.colorHalftone",
|
||||
@@ -31,6 +32,8 @@ pub const PIXEL_EFFECTS: [&str; 8] = [
|
||||
"pixelate.pointillize",
|
||||
"sharpen.unsharpMask",
|
||||
"stylize.glowingEdges",
|
||||
"video.deinterlace",
|
||||
"video.ntscColors",
|
||||
];
|
||||
|
||||
/// A Photoshop-style raster effect with its parameters read and clamped to their ranges. Lengths
|
||||
@@ -59,6 +62,11 @@ pub enum PixelFx {
|
||||
/// Pixelate › Pointillize: random dots about `cell` across of the object's colours on a white
|
||||
/// canvas.
|
||||
Pointillize { cell: f64 },
|
||||
/// Video › De-Interlace: the odd (or `even`) field lines made again from the others, by
|
||||
/// duplication or, with `interpolate`, by averaging.
|
||||
DeInterlace { even: bool, interpolate: bool },
|
||||
/// Video › NTSC Colors: colours a television signal can't carry made less saturated.
|
||||
NtscColors,
|
||||
}
|
||||
|
||||
/// What a raster's colour channels hold, for the filters that treat them apart (Color Halftone
|
||||
@@ -89,6 +97,9 @@ pub struct PixelSpace {
|
||||
pub center: Point,
|
||||
/// What the colour channels hold.
|
||||
pub channels: Channels,
|
||||
/// The height of a line of the document's raster grid (document units: 72 / Document Raster
|
||||
/// Effects Settings › Resolution), the fields De-Interlace works on.
|
||||
pub line: f64,
|
||||
}
|
||||
|
||||
/// Effect `id`'s parameters `p` (defaults merged in) as a [`PixelFx`]; `None` for other effects.
|
||||
@@ -126,6 +137,11 @@ pub(crate) fn parse(id: &str, p: &Value) -> Option<PixelFx> {
|
||||
"pixelate.crystallize" => PixelFx::Crystallize { cell: num(p, "cellSize", 10.0).clamp(3.0, 300.0) },
|
||||
"pixelate.mezzotint" => PixelFx::Mezzotint { kind: Mezzotint::parse(text(p, "type", "fineDots")) },
|
||||
"pixelate.pointillize" => PixelFx::Pointillize { cell: num(p, "cellSize", 5.0).clamp(3.0, 300.0) },
|
||||
"video.deinterlace" => PixelFx::DeInterlace {
|
||||
even: text(p, "eliminate", "odd").eq_ignore_ascii_case("even"),
|
||||
interpolate: text(p, "create", "duplication").eq_ignore_ascii_case("interpolation"),
|
||||
},
|
||||
"video.ntscColors" => PixelFx::NtscColors,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -143,7 +159,7 @@ impl PixelFx {
|
||||
PixelFx::SmartBlur { radius, .. } => radius,
|
||||
PixelFx::UnsharpMask { .. } => 0.0,
|
||||
PixelFx::GlowingEdges { width, smoothness, .. } => width.max(smoothness * 3.0),
|
||||
PixelFx::ColorHalftone { .. } | PixelFx::Mezzotint { .. } => 0.0,
|
||||
PixelFx::ColorHalftone { .. } | PixelFx::Mezzotint { .. } | PixelFx::DeInterlace { .. } | PixelFx::NtscColors => 0.0,
|
||||
// A crystal's or dot's point inside the object reaches out by up to its cell.
|
||||
PixelFx::Crystallize { cell } | PixelFx::Pointillize { cell } => 1.5 * cell,
|
||||
}
|
||||
@@ -163,6 +179,9 @@ impl PixelFx {
|
||||
PixelFx::Mezzotint { .. } => Some(0.0),
|
||||
// The dots' points, and the softened colour around them.
|
||||
PixelFx::Pointillize { cell } => Some(2.5 * cell),
|
||||
// The lines above and below.
|
||||
PixelFx::DeInterlace { .. } => Some(video::MAX_LINE),
|
||||
PixelFx::NtscColors => Some(0.0),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -180,6 +199,8 @@ impl PixelFx {
|
||||
PixelFx::Crystallize { cell } => pixelate::crystallize(px, w, h, space, cell),
|
||||
PixelFx::Mezzotint { kind } => pixelate::mezzotint(px, w, h, space, kind),
|
||||
PixelFx::Pointillize { cell } => pixelate::pointillize(px, w, h, space, cell),
|
||||
PixelFx::DeInterlace { even, interpolate } => video::deinterlace(px, w, h, space, even, interpolate),
|
||||
PixelFx::NtscColors => video::ntsc(px),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ use crate::{RasterFx, raster_effects};
|
||||
|
||||
/// A `w` × `h` raster whose pixels are document points (origin top-left).
|
||||
fn space(w: usize, h: usize) -> PixelSpace {
|
||||
PixelSpace { to_doc: Affine::IDENTITY, px: 1.0, center: Point::new(w as f64 / 2.0, h as f64 / 2.0), channels: Channels::Rgb }
|
||||
PixelSpace { to_doc: Affine::IDENTITY, px: 1.0, center: Point::new(w as f64 / 2.0, h as f64 / 2.0), channels: Channels::Rgb, line: 1.0 }
|
||||
}
|
||||
|
||||
fn image(w: usize, h: usize, f: impl Fn(usize, usize) -> [u8; 4]) -> Vec<u8> {
|
||||
@@ -224,7 +224,8 @@ fn lengths_are_document_units() {
|
||||
let edge = |scale: usize| image(40 * scale, 4, move |x, _| grey(if x < 20 * scale { 100 } else { 150 }));
|
||||
let run = |scale: usize| {
|
||||
let mut d = edge(scale);
|
||||
let s = PixelSpace { to_doc: Affine::scale(1.0 / scale as f64), px: 1.0 / scale as f64, center: Point::ZERO, channels: Channels::Rgb };
|
||||
let s =
|
||||
PixelSpace { to_doc: Affine::scale(1.0 / scale as f64), px: 1.0 / scale as f64, center: Point::ZERO, channels: Channels::Rgb, line: 1.0 };
|
||||
fx("sharpen.unsharpMask", json!({"amount": 100, "radius": 2})).apply(&mut d, 40 * scale, 4, &s);
|
||||
(0..40 * scale).filter(|x| at(&d, 40 * scale, *x, 2)[0] < 99).count()
|
||||
};
|
||||
@@ -253,7 +254,7 @@ fn gaussian_and_plane_blurs_keep_their_mass() {
|
||||
fn pixel_timings() {
|
||||
let (w, h) = (2000, 2000);
|
||||
let src = image(w, h, |x, y| [(x % 256) as u8, (y % 256) as u8, ((x ^ y) % 256) as u8, 255]);
|
||||
let s = PixelSpace { to_doc: Affine::IDENTITY, px: 1.0, center: Point::new(1000.0, 1000.0), channels: Channels::Rgb };
|
||||
let s = PixelSpace { to_doc: Affine::IDENTITY, px: 1.0, center: Point::new(1000.0, 1000.0), channels: Channels::Rgb, line: 1.0 };
|
||||
let cases = [
|
||||
("blur.radial", json!({"quality": "draft"})),
|
||||
("blur.radial", json!({"quality": "good"})),
|
||||
@@ -477,3 +478,50 @@ fn pixelate_patterns_follow_the_object_at_any_resolution() {
|
||||
assert_eq!(shifted, one, "{id}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Video › De-Interlace: lines 1, 3, 5… (or 2, 4, 6…) are made again from the others, by copying
|
||||
/// the line above or by averaging the lines above and below; the lines are the document's raster
|
||||
/// rows, whatever the raster's own resolution.
|
||||
#[test]
|
||||
fn deinterlace_remakes_one_field_from_the_other() {
|
||||
let (w, h) = (2, 6);
|
||||
// Line n (from 1) is grey 40 n.
|
||||
let src = image(w, h, |_, y| grey(40 * (y as u8 + 1)));
|
||||
let run = |p: serde_json::Value, s: &PixelSpace| {
|
||||
let mut d = src.clone();
|
||||
fx("video.deinterlace", p).apply(&mut d, w, h, s);
|
||||
(0..h).map(|y| at(&d, w, 1, y)[0]).collect::<Vec<_>>()
|
||||
};
|
||||
let s = space(w, h);
|
||||
// Odd lines (1, 3, 5) copy the line above; line 1 has none, so it takes line 2.
|
||||
assert_eq!(run(json!({}), &s), [80, 80, 80, 160, 160, 240]);
|
||||
assert_eq!(run(json!({"eliminate": "even"}), &s), [40, 40, 120, 120, 200, 200]);
|
||||
// Interpolated: the average of the lines around (one side at the edges).
|
||||
assert_eq!(run(json!({"eliminate": "even", "create": "interpolation"}), &s), [40, 80, 120, 160, 200, 200]);
|
||||
// Lines two pixels tall: lines 1 and 3 (pixels 0–1 and 4–5) copy their neighbour, row by row.
|
||||
let coarse = PixelSpace { line: 2.0, ..space(w, h) };
|
||||
assert_eq!(run(json!({}), &coarse), [120, 160, 120, 160, 120, 160]);
|
||||
// A damaged space changes nothing.
|
||||
assert_eq!(run(json!({}), &PixelSpace { line: f64::NAN, ..space(w, h) }), [40, 80, 120, 160, 200, 240]);
|
||||
}
|
||||
|
||||
/// Video › NTSC Colors: saturated yellow and cyan lose saturation (their composite signal is too
|
||||
/// strong) but keep their brightness; greys, dark colours and transparency stay as they are.
|
||||
#[test]
|
||||
fn ntsc_colors_tame_only_colours_too_strong_for_the_signal() {
|
||||
let (w, h) = (5, 1);
|
||||
let px = [[255, 255, 0, 255], [0, 255, 255, 255], [128, 128, 128, 255], [100, 20, 20, 255], [0, 0, 0, 0]];
|
||||
let mut d: Vec<u8> = px.concat();
|
||||
fx("video.ntscColors", json!({})).apply(&mut d, w, h, &space(w, h));
|
||||
let luma = |p: [u8; 4]| 0.299 * f64::from(p[0]) + 0.587 * f64::from(p[1]) + 0.114 * f64::from(p[2]);
|
||||
for (x, &a) in px.iter().enumerate() {
|
||||
let b = at(&d, w, x, 0);
|
||||
if x >= 2 {
|
||||
assert_eq!(b, a, "{x}: unchanged");
|
||||
continue;
|
||||
}
|
||||
let spread = |p: [u8; 4]| p[..3].iter().max().unwrap() - p[..3].iter().min().unwrap();
|
||||
assert!(spread(b) < spread(a), "{x}: less saturated {b:?}");
|
||||
assert!((luma(a) - luma(b)).abs() < 3.0, "{x}: as bright {a:?} {b:?}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
//! Effect › Video: De-Interlace and NTSC Colors.
|
||||
|
||||
use vectorcraft_geom::Point;
|
||||
|
||||
use super::PixelSpace;
|
||||
|
||||
/// The tallest field line De-Interlace reads across (document units): one pixel at the lowest
|
||||
/// document raster resolution, 1 ppi.
|
||||
pub(super) const MAX_LINE: f64 = 72.0;
|
||||
|
||||
/// De-Interlace: the odd (or, with `even`, the even) fields of the image are made again from the
|
||||
/// others. The fields are the lines of the document's raster grid (each [`PixelSpace::line`]
|
||||
/// tall, numbered from 1 at the top of the page): a line taken out becomes a copy of the line
|
||||
/// above it (the one below at the top), or with `interpolate` the average of the two.
|
||||
pub(super) fn deinterlace(px: &mut [[u8; 4]], w: usize, h: usize, space: &PixelSpace, even: bool, interpolate: bool) {
|
||||
let line = space.line;
|
||||
let to_px = space.to_doc.inverse();
|
||||
if !(line.is_finite() && line > 0.0 && to_px.is_finite() && space.to_doc.is_finite()) {
|
||||
return;
|
||||
}
|
||||
let src = px.to_vec();
|
||||
// The pixel holding document point `q`.
|
||||
let at = |q: Point| {
|
||||
let p = to_px * q;
|
||||
(p.x >= 0.0 && p.y >= 0.0 && p.x < w as f64 && p.y < h as f64).then(|| src.get(p.y as usize * w + p.x as usize).copied()).flatten()
|
||||
};
|
||||
for (i, out) in px.iter_mut().enumerate().take(w.saturating_mul(h)) {
|
||||
let q = space.to_doc * Point::new((i % w) as f64 + 0.5, (i / w) as f64 + 0.5);
|
||||
let k = (q.y / line).floor();
|
||||
// Line k + 1: odd lines have an even k.
|
||||
if !k.is_finite() || ((k as i64).rem_euclid(2) == 1) != even {
|
||||
continue;
|
||||
}
|
||||
let (above, below) = (at(Point::new(q.x, q.y - line)), at(Point::new(q.x, q.y + line)));
|
||||
let made = match (interpolate, above, below) {
|
||||
(true, Some(a), Some(b)) => Some([0, 1, 2, 3].map(|c| (u16::from(a[c]) + u16::from(b[c])).div_ceil(2) as u8)),
|
||||
(_, a, b) => a.or(b),
|
||||
};
|
||||
if let Some(v) = made {
|
||||
*out = v;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// NTSC Colors: colours a television's composite signal can't carry are made less saturated,
|
||||
/// keeping their brightness. In YIQ, the luma plus the chroma's amplitude must stay within 110 %
|
||||
/// of white and the luma minus it above −20 %; a colour past either has its chroma cut to fit.
|
||||
pub(super) fn ntsc(px: &mut [[u8; 4]]) {
|
||||
for p in px.iter_mut() {
|
||||
let a = f32::from(p[3]) / 255.0;
|
||||
if a <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
// Straight colour (the pixels are premultiplied).
|
||||
let [r, g, b] = [p[0], p[1], p[2]].map(|v| (f32::from(v) / 255.0 / a).min(1.0));
|
||||
let y = 0.299 * r + 0.587 * g + 0.114 * b;
|
||||
let (i, q) = (0.596 * r - 0.274 * g - 0.322 * b, 0.211 * r - 0.523 * g + 0.312 * b);
|
||||
let c = i.hypot(q);
|
||||
let mut keep = 1.0f32;
|
||||
if y + c > 1.1 {
|
||||
keep = keep.min((1.1 - y) / c);
|
||||
}
|
||||
if y - c < -0.2 {
|
||||
keep = keep.min((y + 0.2) / c);
|
||||
}
|
||||
if keep >= 1.0 || !keep.is_finite() {
|
||||
continue;
|
||||
}
|
||||
let (i, q) = (i * keep.max(0.0), q * keep.max(0.0));
|
||||
let rgb = [y + 0.956 * i + 0.621 * q, y - 0.272 * i - 0.647 * q, y - 1.106 * i + 1.703 * q];
|
||||
let [r, g, b] = rgb.map(|v| (v.clamp(0.0, 1.0) * a * 255.0).round() as u8);
|
||||
*p = [r, g, b, p[3]];
|
||||
}
|
||||
}
|
||||
@@ -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",
|
||||
@@ -640,11 +652,13 @@ fn format_filters() -> impl Iterator<Item = (&'static str, &'static [&'static st
|
||||
}
|
||||
|
||||
/// Open-dialog filters: "All readable files" first, then one per readable format, then swatch
|
||||
/// libraries (which open in the library panel), flattener, PDF and print presets (imported).
|
||||
/// libraries (which open in the library panel), Libraries panel libraries, flattener, PDF and print
|
||||
/// presets (imported).
|
||||
pub fn open_filters() -> impl Iterator<Item = (&'static str, &'static [&'static str])> {
|
||||
std::iter::once(("All readable files", OPEN_EXTS))
|
||||
.chain(format_filters())
|
||||
.chain(std::iter::once(("Swatch libraries", super::swatchlib::LIBRARY_EXTS)))
|
||||
.chain(std::iter::once(("Libraries", super::library::LIBRARY_EXTS)))
|
||||
.chain(std::iter::once(("Flattener presets", super::flatten::PRESET_EXTS)))
|
||||
.chain(std::iter::once(("PDF presets", super::pdfcmds::PRESET_EXTS)))
|
||||
.chain(std::iter::once(("Print presets", super::printpresets::PRESET_EXTS)))
|
||||
@@ -979,6 +993,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)
|
||||
}
|
||||
@@ -157,7 +157,11 @@ fn open_exts_cover_every_readable_format() {
|
||||
}
|
||||
let filters: Vec<_> = open_filters().collect();
|
||||
assert_eq!(filters[0], ("All readable files", OPEN_EXTS));
|
||||
assert_eq!(filters.len(), 6 + FORMATS.iter().filter(|f| f.read).count(), "and swatch libraries, flattener, PDF and print presets, plug-ins");
|
||||
assert_eq!(
|
||||
filters.len(),
|
||||
7 + FORMATS.iter().filter(|f| f.read).count(),
|
||||
"and swatch libraries, libraries, flattener, PDF and print presets, plug-ins"
|
||||
);
|
||||
assert_eq!(filters.last(), Some(&("Plug-ins", crate::cmd::plugin::EXTS)), "File › Open installs plug-ins");
|
||||
}
|
||||
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
@@ -4,7 +4,10 @@
|
||||
//! live for the session only. A graphic is kept as a native document with a PNG thumbnail: adding
|
||||
//! one copies the selection as Copy does, and placing it pastes a copy as Paste does (its images,
|
||||
//! symbols, patterns and swatches come along; a swatch name the document gives another colour is
|
||||
//! merged into the document's).
|
||||
//! merged into the document's). Items can be put in user-named groups, and a library can be
|
||||
//! exported to a `.vclibrary` file and imported from one (#926).
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Map, Value, json};
|
||||
@@ -16,10 +19,20 @@ use crate::Clipboard;
|
||||
|
||||
/// The extension of a library file.
|
||||
pub const LIBRARY_EXT: &str = "vclibrary";
|
||||
/// The extensions of library files (open dialogs).
|
||||
pub const LIBRARY_EXTS: &[&str] = &[LIBRARY_EXT];
|
||||
/// Bytes a library file may have when read (graphics with large images included).
|
||||
const MAX_FILE: u64 = 512 << 20;
|
||||
/// Items of one kind a library may hold.
|
||||
const MAX_ITEMS: usize = 10_000;
|
||||
/// Groups a library may hold.
|
||||
const MAX_GROUPS: usize = 1_000;
|
||||
/// Characters of a library, group or item name kept from a file.
|
||||
const MAX_NAME: usize = 256;
|
||||
/// Base64 bytes a graphic's thumbnail may have (a 256-pixel PNG is far smaller).
|
||||
const MAX_THUMBNAIL: usize = 4 << 20;
|
||||
/// Pixels a side a thumbnail may claim (they are made at most 256).
|
||||
const MAX_THUMBNAIL_SIDE: u32 = 1024;
|
||||
|
||||
/// A library: its name and its items, newest last.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
@@ -34,6 +47,38 @@ pub struct Library {
|
||||
pub para_styles: Vec<TextStyleDef>,
|
||||
#[serde(default)]
|
||||
pub graphics: Vec<LibraryGraphic>,
|
||||
/// User-named groups of its items, in the order they were made (#926); an item is in one
|
||||
/// group at most, the others are ungrouped. Files written before groups have none.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub groups: Vec<LibraryGroup>,
|
||||
}
|
||||
|
||||
/// A user-named group of a library's items.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct LibraryGroup {
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub items: Vec<ItemRef>,
|
||||
}
|
||||
|
||||
/// A library item: its kind and its key (its name; a graphic's id).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub struct ItemRef {
|
||||
pub kind: ItemKind,
|
||||
pub item: String,
|
||||
}
|
||||
|
||||
/// What a library item is, as groups name it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum ItemKind {
|
||||
Color,
|
||||
CharStyle,
|
||||
ParaStyle,
|
||||
Graphic,
|
||||
/// A kind this version doesn't know (a newer one wrote it): dropped when the file is read.
|
||||
#[serde(other)]
|
||||
Unknown,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
@@ -87,7 +132,7 @@ impl Libraries {
|
||||
})
|
||||
.and_then(|b| serde_json::from_slice::<Library>(&b).ok());
|
||||
if let Some(mut lib) = lib {
|
||||
lib.cap();
|
||||
lib.sanitize();
|
||||
self.libs.push((id, lib));
|
||||
}
|
||||
}
|
||||
@@ -120,12 +165,15 @@ impl Libraries {
|
||||
|
||||
/// A new empty library called `name` → its id.
|
||||
fn create(&mut self, name: &str) -> Result<String> {
|
||||
let base: String = name.chars().map(|c| if c.is_alphanumeric() || c == ' ' || c == '-' || c == '_' { c } else { '-' }).collect();
|
||||
let base = base.trim();
|
||||
let base = if base.is_empty() { "Library" } else { base };
|
||||
self.insert(Library { name: name.to_string(), ..Default::default() })
|
||||
}
|
||||
|
||||
/// `lib` as a new library, its file named after it, made the current one → its id.
|
||||
fn insert(&mut self, lib: Library) -> Result<String> {
|
||||
let base = file_stem_for(&lib.name);
|
||||
let taken = |id: &str| self.libs.iter().any(|(i, _)| i.eq_ignore_ascii_case(id)) || self.file_exists(id);
|
||||
let id = std::iter::once(base.to_string()).chain((2..).map(|n| format!("{base} {n}"))).find(|id| !taken(id)).unwrap_or_default();
|
||||
self.libs.push((id.clone(), Library { name: name.to_string(), ..Default::default() }));
|
||||
let id = std::iter::once(base.clone()).chain((2..).map(|n| format!("{base} {n}"))).find(|id| !taken(id)).unwrap_or_default();
|
||||
self.libs.push((id.clone(), lib));
|
||||
if let Err(e) = self.save(&id) {
|
||||
self.libs.retain(|(i, _)| i != &id);
|
||||
return Err(e);
|
||||
@@ -194,15 +242,123 @@ impl Libraries {
|
||||
}
|
||||
|
||||
impl Library {
|
||||
/// At most [`MAX_ITEMS`] of each kind (a hand-edited file may hold more).
|
||||
fn cap(&mut self) {
|
||||
/// Every item as (kind, key: its name, a graphic's id, name shown): colours, then character
|
||||
/// and paragraph styles, then graphics.
|
||||
pub fn items(&self) -> impl Iterator<Item = (ItemKind, &str, &str)> {
|
||||
fn styles(kind: ItemKind, list: &[TextStyleDef]) -> impl Iterator<Item = (ItemKind, &str, &str)> {
|
||||
list.iter().map(move |t| (kind, t.name.as_str(), t.name.as_str()))
|
||||
}
|
||||
self.colors
|
||||
.iter()
|
||||
.map(|c| (ItemKind::Color, c.name.as_str(), c.name.as_str()))
|
||||
.chain(styles(ItemKind::CharStyle, &self.char_styles))
|
||||
.chain(styles(ItemKind::ParaStyle, &self.para_styles))
|
||||
.chain(self.graphics.iter().map(|g| (ItemKind::Graphic, g.id.as_str(), g.name.as_str())))
|
||||
}
|
||||
|
||||
/// The group of each grouped item: (kind, key) → its index in [`Library::groups`].
|
||||
pub fn group_index(&self) -> HashMap<(ItemKind, &str), usize> {
|
||||
self.groups.iter().enumerate().flat_map(|(i, g)| g.items.iter().map(move |r| ((r.kind, r.item.as_str()), i))).collect()
|
||||
}
|
||||
|
||||
/// Group `name` (else the one of that name ignoring case): its index.
|
||||
fn group_position(&self, name: &str) -> Option<usize> {
|
||||
let lower = name.to_lowercase();
|
||||
self.groups.iter().position(|g| g.name == name).or_else(|| self.groups.iter().position(|g| g.name.to_lowercase() == lower))
|
||||
}
|
||||
|
||||
/// Item `item` of `kind` (a graphic by id, else by name) as a group names it.
|
||||
fn item_ref(&self, kind: ItemKind, item: &str) -> Option<ItemRef> {
|
||||
let found = self.items().find(|(k, key, _)| *k == kind && *key == item);
|
||||
let found = found.or_else(|| self.items().find(|(k, _, name)| *k == kind && kind == ItemKind::Graphic && *name == item));
|
||||
found.map(|(kind, key, _)| ItemRef { kind, item: key.to_string() })
|
||||
}
|
||||
|
||||
/// Take `r` out of its group.
|
||||
fn ungroup(&mut self, r: &ItemRef) {
|
||||
for g in &mut self.groups {
|
||||
g.items.retain(|x| x != r);
|
||||
}
|
||||
}
|
||||
|
||||
/// Make a library read from a file (hand-edited, imported) safe and consistent: at most
|
||||
/// [`MAX_ITEMS`] items of each kind and [`MAX_GROUPS`] groups, names clipped to [`MAX_NAME`]
|
||||
/// characters and unique within their kind (a repeated one gets a number), sizes finite, a
|
||||
/// thumbnail only when it is a small PNG, and groups holding only items there are, each in one
|
||||
/// group at most.
|
||||
fn sanitize(&mut self) {
|
||||
clip(&mut self.name);
|
||||
self.colors.truncate(MAX_ITEMS);
|
||||
self.char_styles.truncate(MAX_ITEMS);
|
||||
self.para_styles.truncate(MAX_ITEMS);
|
||||
self.graphics.truncate(MAX_ITEMS);
|
||||
self.groups.truncate(MAX_GROUPS);
|
||||
uniquify(self.colors.iter_mut().map(|c| &mut c.name), "Color", " ", false);
|
||||
uniquify(self.char_styles.iter_mut().map(|t| &mut t.name), "Character Style", " ", false);
|
||||
uniquify(self.para_styles.iter_mut().map(|t| &mut t.name), "Paragraph Style", " ", false);
|
||||
uniquify(self.graphics.iter_mut().map(|g| &mut g.name), "Graphic", " ", false);
|
||||
uniquify(self.graphics.iter_mut().map(|g| &mut g.id), "graphic", "-", false);
|
||||
uniquify(self.groups.iter_mut().map(|g| &mut g.name), "Group", " ", true);
|
||||
for g in &mut self.graphics {
|
||||
for v in [&mut g.width, &mut g.height] {
|
||||
if !(v.is_finite() && *v >= 0.0) {
|
||||
*v = 0.0;
|
||||
}
|
||||
}
|
||||
if !thumbnail_ok(&g.thumbnail) {
|
||||
g.thumbnail.clear();
|
||||
}
|
||||
}
|
||||
let mut groups = std::mem::take(&mut self.groups);
|
||||
let present: HashSet<(ItemKind, &str)> = self.items().map(|(k, key, _)| (k, key)).collect();
|
||||
let mut seen = HashSet::new();
|
||||
for g in &mut groups {
|
||||
g.items.retain(|r| present.contains(&(r.kind, r.item.as_str())) && seen.insert(r.clone()));
|
||||
}
|
||||
self.groups = groups;
|
||||
}
|
||||
}
|
||||
|
||||
/// `name` cut to [`MAX_NAME`] characters.
|
||||
fn clip(name: &mut String) {
|
||||
if let Some((at, _)) = name.char_indices().nth(MAX_NAME) {
|
||||
name.truncate(at);
|
||||
}
|
||||
}
|
||||
|
||||
/// Clip each of `names` ([`clip`]) and make it unique among them (ignoring case when `fold`): an
|
||||
/// empty one becomes `fallback`, a repeated one gets a number after `sep` (`Blue 2`).
|
||||
fn uniquify<'a>(names: impl Iterator<Item = &'a mut String>, fallback: &str, sep: &str, fold: bool) {
|
||||
let key = |n: &str| if fold { n.to_lowercase() } else { n.to_string() };
|
||||
let mut seen = HashSet::new();
|
||||
for name in names {
|
||||
clip(name);
|
||||
if name.trim().is_empty() {
|
||||
*name = fallback.to_string();
|
||||
}
|
||||
if seen.contains(&key(name)) {
|
||||
let base = name.clone();
|
||||
*name = (2..).map(|n| format!("{base}{sep}{n}")).find(|n| !seen.contains(&key(n))).unwrap_or_default();
|
||||
}
|
||||
seen.insert(key(name));
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `b64` is empty or a PNG of at most [`MAX_THUMBNAIL_SIDE`] pixels a side, judged by its
|
||||
/// header: the panel decodes it.
|
||||
fn thumbnail_ok(b64: &str) -> bool {
|
||||
if b64.is_empty() {
|
||||
return true;
|
||||
}
|
||||
// 32 base64 characters: 24 bytes, the signature then the IHDR chunk's length, type, width and
|
||||
// height.
|
||||
let Some(head) = b64.get(..32).filter(|_| b64.len() <= MAX_THUMBNAIL).and_then(vectorcraft_format::base64_decode) else { return false };
|
||||
let side = |at: usize| {
|
||||
head.get(at..at + 4).and_then(|b| <[u8; 4]>::try_from(b).ok()).map(u32::from_be_bytes).is_some_and(|v| (1..=MAX_THUMBNAIL_SIDE).contains(&v))
|
||||
};
|
||||
head.starts_with(b"\x89PNG\r\n\x1a\n") && head.get(12..16) == Some(b"IHDR".as_slice()) && side(16) && side(20)
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn library_paths(dir: &str) -> Vec<String> {
|
||||
let Ok(rd) = std::fs::read_dir(dir) else { return vec![] };
|
||||
@@ -234,6 +390,14 @@ fn remove_file(_: &str) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Library `name` as a file name without its extension: letters, digits, spaces, `-` and `_`
|
||||
/// kept, other characters as `-` ("Library" when nothing is left).
|
||||
pub fn file_stem_for(name: &str) -> String {
|
||||
let safe: String = name.chars().map(|c| if c.is_alphanumeric() || c == ' ' || c == '-' || c == '_' { c } else { '-' }).collect();
|
||||
let safe = safe.trim();
|
||||
if safe.is_empty() { "Library".to_string() } else { safe.to_string() }
|
||||
}
|
||||
|
||||
fn stem_of(path: &str) -> String {
|
||||
std::path::Path::new(path).file_stem().map_or_else(String::new, |s| s.to_string_lossy().into_owned())
|
||||
}
|
||||
@@ -260,6 +424,16 @@ impl Kind {
|
||||
_ => return Err(bad(cmd, "kind must be graphic, fillColor, strokeColor, charStyle or paraStyle")),
|
||||
})
|
||||
}
|
||||
|
||||
/// The kind as a group names it (fill and stroke colours are one list).
|
||||
fn item_kind(self) -> ItemKind {
|
||||
match self {
|
||||
Kind::Graphic => ItemKind::Graphic,
|
||||
Kind::FillColor | Kind::StrokeColor => ItemKind::Color,
|
||||
Kind::CharStyle => ItemKind::CharStyle,
|
||||
Kind::ParaStyle => ItemKind::ParaStyle,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
@@ -269,7 +443,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Libraries",
|
||||
[],
|
||||
None,
|
||||
"{} → {libraries: [{id, name, graphics, colors, charStyles, paraStyles} (counts)], current: the current library's id or null, folder: the library folder, or null when libraries last for the session only (the web, headless)}",
|
||||
"{} → {libraries: [{id, name, graphics, colors, charStyles, paraStyles, groups} (counts)], current: the current library's id or null, folder: the library folder, or null when libraries last for the session only (the web, headless)}",
|
||||
always,
|
||||
list
|
||||
),
|
||||
@@ -278,7 +452,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Library",
|
||||
[],
|
||||
None,
|
||||
"{library?: id or name (default: the current library)} → {id, name, graphics: [{id, name, width, height, thumbnail: PNG base64}], colors: [{name, hex, color}], charStyles: [{name, attrs}], paraStyles: [{name, attrs}]}",
|
||||
"{library?: id or name (default: the current library)} → {id, name, graphics: [{id, name, width, height, thumbnail: PNG base64}], colors: [{name, hex, color}], charStyles: [{name, attrs}], paraStyles: [{name, attrs}], groups: [{name, items: [{kind: color|charStyle|paraStyle|graphic, item: name (graphic: id)}]}] (an item is in one group at most; the others are ungrouped)}",
|
||||
always,
|
||||
get
|
||||
),
|
||||
@@ -336,7 +510,69 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
use_item
|
||||
),
|
||||
cmd!("library.removeItem", "Delete Library Item", [], None, "{library?, kind, item: name (graphic: id or name)} → null", always, remove_item),
|
||||
cmd!(
|
||||
"library.removeItem",
|
||||
"Delete Library Item",
|
||||
[],
|
||||
None,
|
||||
"{library?, kind, item: name (graphic: id or name)} delete an item (out of its group too) → null",
|
||||
always,
|
||||
remove_item
|
||||
),
|
||||
cmd!(
|
||||
"library.createGroup",
|
||||
"New Library Group",
|
||||
[],
|
||||
None,
|
||||
"{library?, name?: \"Group\" (a name the library's groups have, ignoring case, gets a number), items?: [{kind, item}] (moved into it out of their groups)} a new group of items, after the others → {library, group: its name}",
|
||||
always,
|
||||
create_group
|
||||
),
|
||||
cmd!(
|
||||
"library.renameGroup",
|
||||
"Rename Library Group",
|
||||
[],
|
||||
None,
|
||||
"{library?, group: name, name} rename a group (another group's name, ignoring case, is an error) → {library, group: the new name}",
|
||||
always,
|
||||
rename_group
|
||||
),
|
||||
cmd!(
|
||||
"library.deleteGroup",
|
||||
"Delete Library Group",
|
||||
[],
|
||||
None,
|
||||
"{library?, group: name} delete a group: its items stay in the library, ungrouped → {library, ungrouped: how many}",
|
||||
always,
|
||||
delete_group
|
||||
),
|
||||
cmd!(
|
||||
"library.moveItem",
|
||||
"Move Library Item to Group",
|
||||
[],
|
||||
None,
|
||||
"{library?, kind, item: name (graphic: id or name), group?: name (null or none: out of its group)} put an item in a group (out of the one it was in) → {library, kind, item, group: name or null}",
|
||||
always,
|
||||
move_item
|
||||
),
|
||||
cmd!(
|
||||
query "library.export",
|
||||
"Export Library",
|
||||
[],
|
||||
None,
|
||||
"{library?: id or name (default: the current library), path?} write a library (its colours, styles, graphics with their art and thumbnails, and groups) as a .vclibrary file (JSON, as libraries are kept) → {path, name}; without path → {data: the file's text, name}",
|
||||
always,
|
||||
export
|
||||
),
|
||||
cmd!(
|
||||
query "library.import",
|
||||
"Import Library",
|
||||
[],
|
||||
None,
|
||||
"{path? | data?: file text | dataBase64?, name?: the library's name (default: the file's)} add the library of a .vclibrary file (as library.export writes) as a new library, made the current one; a name another library has gets a number (`Brand (2)`) → {id, name, graphics, colors, charStyles, paraStyles, groups (counts)}",
|
||||
always,
|
||||
import
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -362,6 +598,7 @@ fn counts(lib: &Library) -> Value {
|
||||
"colors": lib.colors.len(),
|
||||
"charStyles": lib.char_styles.len(),
|
||||
"paraStyles": lib.para_styles.len(),
|
||||
"groups": lib.groups.len(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -391,6 +628,7 @@ fn get(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"colors": lib.colors.iter().map(|c| json!({"name": c.name, "hex": c.color.to_hex(), "color": c.color})).collect::<Vec<_>>(),
|
||||
"charStyles": lib.char_styles.iter().map(|t| json!({"name": t.name, "attrs": t.attrs})).collect::<Vec<_>>(),
|
||||
"paraStyles": lib.para_styles.iter().map(|t| json!({"name": t.name, "attrs": t.attrs})).collect::<Vec<_>>(),
|
||||
"groups": lib.groups,
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -457,7 +695,8 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let base = given.clone().unwrap_or_else(|| g.name.clone());
|
||||
g.name = unique(&base, |n| lib.graphics.iter().any(|o| o.name == n));
|
||||
g.id = unique("graphic", |n| lib.graphics.iter().any(|o| o.id == n)).replace(' ', "-");
|
||||
// Ids are `graphic`, `graphic-2`…: taken ones are looked for as they are kept.
|
||||
g.id = unique("graphic", |n| lib.graphics.iter().any(|o| o.id == n.replace(' ', "-"))).replace(' ', "-");
|
||||
let v = json!({ "name": g.name, "id": g.id, "existing": false });
|
||||
lib.graphics.push(g);
|
||||
v
|
||||
@@ -682,22 +921,171 @@ fn remove_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (id, kind, item) = item_param(s, p, C)?;
|
||||
let item = item.to_string();
|
||||
s.libraries.change(&id, |lib| {
|
||||
let before = (lib.graphics.len(), lib.colors.len(), lib.char_styles.len(), lib.para_styles.len());
|
||||
let r = lib.item_ref(kind.item_kind(), &item).ok_or_else(|| bad(C, format!("the library has no item `{item}`")))?;
|
||||
match kind {
|
||||
Kind::Graphic => {
|
||||
let at = lib.graphics.iter().position(|g| g.id == item).or_else(|| lib.graphics.iter().position(|g| g.name == item));
|
||||
if let Some(i) = at {
|
||||
lib.graphics.remove(i);
|
||||
}
|
||||
}
|
||||
Kind::FillColor | Kind::StrokeColor => lib.colors.retain(|c| c.name != item),
|
||||
Kind::CharStyle => lib.char_styles.retain(|t| t.name != item),
|
||||
Kind::ParaStyle => lib.para_styles.retain(|t| t.name != item),
|
||||
}
|
||||
if before == (lib.graphics.len(), lib.colors.len(), lib.char_styles.len(), lib.para_styles.len()) {
|
||||
return Err(bad(C, format!("the library has no item `{item}`")));
|
||||
Kind::Graphic => lib.graphics.retain(|g| g.id != r.item),
|
||||
Kind::FillColor | Kind::StrokeColor => lib.colors.retain(|c| c.name != r.item),
|
||||
Kind::CharStyle => lib.char_styles.retain(|t| t.name != r.item),
|
||||
Kind::ParaStyle => lib.para_styles.retain(|t| t.name != r.item),
|
||||
}
|
||||
lib.ungroup(&r);
|
||||
Ok(())
|
||||
})?;
|
||||
ok()
|
||||
}
|
||||
|
||||
/// `p`'s `name`, trimmed and clipped, else `default`.
|
||||
fn name_param(p: &Value, default: &str) -> String {
|
||||
let mut name = str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()).unwrap_or(default).to_string();
|
||||
clip(&mut name);
|
||||
name
|
||||
}
|
||||
|
||||
/// `p`'s `group`.
|
||||
fn group_param<'a>(p: &'a Value, cmd: &str) -> Result<&'a str> {
|
||||
str_param(p, "group").ok_or_else(|| bad(cmd, "missing `group`"))
|
||||
}
|
||||
|
||||
/// Group `name` of `lib`: its index.
|
||||
fn group_at(lib: &Library, name: &str, cmd: &str) -> Result<usize> {
|
||||
lib.group_position(name).ok_or_else(|| bad(cmd, format!("the library has no group `{name}`")))
|
||||
}
|
||||
|
||||
fn create_group(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "library.createGroup";
|
||||
let id = library_id(s, p, C)?;
|
||||
let base = name_param(p, "Group");
|
||||
let wanted = match p.get("items") {
|
||||
None | Some(Value::Null) => vec![],
|
||||
Some(Value::Array(items)) if items.len() <= 4 * MAX_ITEMS => items
|
||||
.iter()
|
||||
.map(|v| Ok((Kind::of(v, C)?.item_kind(), str_param(v, "item").ok_or_else(|| bad(C, "each of `items` is {kind, item}"))?)))
|
||||
.collect::<Result<Vec<_>>>()?,
|
||||
Some(_) => return Err(bad(C, "`items` is a list of {kind, item}")),
|
||||
};
|
||||
let name = s.libraries.change(&id, |lib| {
|
||||
if lib.groups.len() >= MAX_GROUPS {
|
||||
return Err(bad(C, format!("the library holds {MAX_GROUPS} groups already")));
|
||||
}
|
||||
let refs = wanted
|
||||
.iter()
|
||||
.map(|&(kind, item)| lib.item_ref(kind, item).ok_or_else(|| bad(C, format!("the library has no item `{item}`"))))
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
let name = unique(&base, |n| lib.group_position(n).is_some());
|
||||
let mut items = vec![];
|
||||
let mut seen = HashSet::new();
|
||||
for r in refs {
|
||||
lib.ungroup(&r);
|
||||
if seen.insert(r.clone()) {
|
||||
items.push(r);
|
||||
}
|
||||
}
|
||||
lib.groups.push(LibraryGroup { name: name.clone(), items });
|
||||
Ok(name)
|
||||
})?;
|
||||
Ok(json!({ "library": id, "group": name }))
|
||||
}
|
||||
|
||||
fn rename_group(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "library.renameGroup";
|
||||
let id = library_id(s, p, C)?;
|
||||
let group = group_param(p, C)?;
|
||||
if str_param(p, "name").is_none_or(|n| n.trim().is_empty()) {
|
||||
return Err(bad(C, "missing `name`"));
|
||||
}
|
||||
let name = name_param(p, "");
|
||||
s.libraries.change(&id, |lib| {
|
||||
let i = group_at(lib, group, C)?;
|
||||
if lib.group_position(&name).is_some_and(|j| j != i) {
|
||||
return Err(bad(C, format!("the library has a group `{name}` already")));
|
||||
}
|
||||
if let Some(g) = lib.groups.get_mut(i) {
|
||||
g.name.clone_from(&name);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "library": id, "group": name }))
|
||||
}
|
||||
|
||||
fn delete_group(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "library.deleteGroup";
|
||||
let id = library_id(s, p, C)?;
|
||||
let group = group_param(p, C)?;
|
||||
let ungrouped = s.libraries.change(&id, |lib| {
|
||||
let i = group_at(lib, group, C)?;
|
||||
Ok(if i < lib.groups.len() { lib.groups.remove(i).items.len() } else { 0 })
|
||||
})?;
|
||||
Ok(json!({ "library": id, "ungrouped": ungrouped }))
|
||||
}
|
||||
|
||||
fn move_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "library.moveItem";
|
||||
let (id, kind, item) = item_param(s, p, C)?;
|
||||
let group = str_param(p, "group");
|
||||
let (key, to) = s.libraries.change(&id, |lib| {
|
||||
let r = lib.item_ref(kind.item_kind(), item).ok_or_else(|| bad(C, format!("the library has no item `{item}`")))?;
|
||||
let at = group.map(|g| group_at(lib, g, C)).transpose()?;
|
||||
lib.ungroup(&r);
|
||||
let key = r.item.clone();
|
||||
let to = at.and_then(|i| lib.groups.get_mut(i)).map(|g| {
|
||||
g.items.push(r);
|
||||
g.name.clone()
|
||||
});
|
||||
Ok((key, to))
|
||||
})?;
|
||||
Ok(json!({ "library": id, "kind": str_param(p, "kind"), "item": key, "group": to }))
|
||||
}
|
||||
|
||||
fn export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "library.export";
|
||||
let id = library_id(s, p, C)?;
|
||||
let lib = s.libraries.get(&id).ok_or_else(|| bad(C, format!("no library `{id}`")))?;
|
||||
let text = serde_json::to_string(lib).map_err(|e| bad(C, e.to_string()))?;
|
||||
let name = lib.name.clone();
|
||||
match str_param(p, "path") {
|
||||
Some(path) => {
|
||||
super::fileio::write_file(path, text.as_bytes())?;
|
||||
Ok(json!({ "path": path, "name": name }))
|
||||
}
|
||||
None => Ok(json!({ "data": text, "name": name })),
|
||||
}
|
||||
}
|
||||
|
||||
fn import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "library.import";
|
||||
let too_big = || bad(C, format!("the file is larger than {} MB", MAX_FILE >> 20));
|
||||
let bytes: std::borrow::Cow<[u8]> = match (str_param(p, "path"), str_param(p, "data"), str_param(p, "dataBase64")) {
|
||||
(Some(path), ..) => {
|
||||
if super::fileio::file_stamp(path).is_some_and(|(len, _)| len > MAX_FILE) {
|
||||
return Err(too_big());
|
||||
}
|
||||
super::fileio::read_file(path)?.into()
|
||||
}
|
||||
(None, Some(text), _) => text.as_bytes().into(),
|
||||
(None, None, Some(b64)) => vectorcraft_format::base64_decode(b64).ok_or_else(|| bad(C, "bad dataBase64"))?.into(),
|
||||
_ => return Err(bad(C, "give `path`, `data` or `dataBase64`")),
|
||||
};
|
||||
if bytes.len() as u64 > MAX_FILE {
|
||||
return Err(too_big());
|
||||
}
|
||||
let not_library = |e: String| bad(C, format!("not a library file: {e}"));
|
||||
let v: Value = serde_json::from_slice(&bytes).map_err(|e| not_library(e.to_string()))?;
|
||||
drop(bytes);
|
||||
// A library names itself; another file of ours (swatches, styles) says what it is.
|
||||
if !v.get("name").is_some_and(Value::is_string) || v.get("format").is_some_and(|f| f.as_str() != Some(LIBRARY_EXT)) {
|
||||
return Err(not_library("it has no library name".into()));
|
||||
}
|
||||
let mut lib: Library = serde_json::from_value(v).map_err(|e| not_library(e.to_string()))?;
|
||||
lib.sanitize();
|
||||
let base = str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()).unwrap_or(lib.name.trim()).to_string();
|
||||
let mut base = if base.is_empty() { "Library".to_string() } else { base };
|
||||
clip(&mut base);
|
||||
let taken = |n: &str| s.libraries.all().iter().any(|(_, l)| l.name.to_lowercase() == n.to_lowercase());
|
||||
lib.name = std::iter::once(base.clone()).chain((2..).map(|n| format!("{base} ({n})"))).find(|n| !taken(n)).unwrap_or(base);
|
||||
let mut r = json!({ "name": lib.name });
|
||||
if let (Some(o), Value::Object(c)) = (r.as_object_mut(), counts(&lib)) {
|
||||
o.extend(c);
|
||||
}
|
||||
r["id"] = json!(s.libraries.insert(lib)?);
|
||||
Ok(r)
|
||||
}
|
||||
@@ -196,7 +196,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Live Shape Properties",
|
||||
[],
|
||||
None,
|
||||
"{id?, ids?, radius?: pt, kind?: \"round\"|\"invertedRound\"|\"chamfer\", corners?: [i…], sides?: n, polygonAngle?: degrees (counterclockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counterclockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse)} (Live Corners on any path: radius and kind set its corners (anchors without handles between two straight sides): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius)",
|
||||
"{id?, ids?, radius?: pt, kind?: \"round\"|\"invertedRound\"|\"chamfer\", corners?: [i…], items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counterclockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counterclockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse)} (Live Corners on any path: radius and kind set its corners (anchors without handles between two straight sides): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius)",
|
||||
has_selection,
|
||||
set_live_shape
|
||||
),
|
||||
@@ -1083,8 +1083,32 @@ fn corners_param(p: &Value) -> Result<Option<BTreeSet<usize>>> {
|
||||
}
|
||||
|
||||
fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = targets(s, p)?;
|
||||
let corners = corners_param(p)?;
|
||||
// `items`: objects each with its own `corners`; else `ids` (or the selection) sharing them.
|
||||
let items = match p.get("items").filter(|v| !v.is_null()) {
|
||||
None => None,
|
||||
Some(Value::Array(a)) => Some(
|
||||
a.iter()
|
||||
.map(|it| {
|
||||
let id = it
|
||||
.get("id")
|
||||
.and_then(Value::as_u64)
|
||||
.map(NodeId)
|
||||
.ok_or_else(|| bad("object.setLiveShape", format!("each of `items` is {{id, corners?}} with an object id, not {it}")))?;
|
||||
Ok((id, corners_param(it)?))
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()?,
|
||||
),
|
||||
Some(v) => return Err(bad("object.setLiveShape", format!("`items` must be an array of {{id, corners?}}, not {v}"))),
|
||||
};
|
||||
let ids = match &items {
|
||||
Some(items) => items.iter().map(|(id, _)| *id).collect(),
|
||||
None => targets(s, p)?,
|
||||
};
|
||||
let shared = corners_param(p)?;
|
||||
let corners_of = |id: NodeId| match &items {
|
||||
Some(items) => items.iter().find(|(i, _)| *i == id).and_then(|(_, c)| c.clone()),
|
||||
None => shared.clone(),
|
||||
};
|
||||
let kind = p
|
||||
.get("kind")
|
||||
.filter(|v| !v.is_null())
|
||||
@@ -1154,6 +1178,7 @@ fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let partial = sel.anchors.get_mut(id);
|
||||
// The corners to edit, the Direct-Selected ones and the anchor layout before the edit.
|
||||
let Some(c) = LiveCorners::new(path, live.as_ref()) else { continue };
|
||||
let corners = corners_of(*id);
|
||||
let picked = match &corners {
|
||||
Some(k) if k.last().is_some_and(|k| *k >= c.base.anchor_count()) => {
|
||||
let n = c.base.anchor_count();
|
||||
|
||||
@@ -161,3 +161,181 @@ fn libraries_are_kept_in_files_across_sessions() {
|
||||
assert_eq!(run(&mut v, "library.list", json!({}))["libraries"], json!([]));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A library "Brand" holding a graphic, a colour and a character style, each added from the
|
||||
/// selection → (session, the graphic's id, the colour's name, the style's name).
|
||||
fn brand() -> (Session, String, String, String) {
|
||||
let mut s = session();
|
||||
run(&mut s, "library.create", json!({"name": "Brand"}));
|
||||
let r = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 20}))["id"].clone();
|
||||
run(&mut s, "paint.setFill", json!({"color": "#336699", "ids": [r]}));
|
||||
run(&mut s, "select.set", json!({"ids": [r]}));
|
||||
let g = run(&mut s, "library.add", json!({"kind": "graphic", "name": "Logo"}))["id"].as_str().unwrap().to_string();
|
||||
let c = run(&mut s, "library.add", json!({"kind": "fillColor"}))["name"].as_str().unwrap().to_string();
|
||||
let t = run(&mut s, "text.create", json!({"x": 10, "y": 80, "text": "Type", "size": 18}))["id"].clone();
|
||||
run(&mut s, "select.set", json!({"ids": [t]}));
|
||||
let st = run(&mut s, "library.add", json!({"kind": "charStyle"}))["name"].as_str().unwrap().to_string();
|
||||
(s, g, c, st)
|
||||
}
|
||||
|
||||
/// The current library's groups as `library.get` reports them: (name, [(kind, item)]).
|
||||
fn groups(s: &mut Session) -> Vec<(String, Vec<(String, String)>)> {
|
||||
let got = run(s, "library.get", json!({}));
|
||||
got["groups"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|g| {
|
||||
let items = g["items"].as_array().unwrap().iter().map(|r| (r["kind"].as_str().unwrap().into(), r["item"].as_str().unwrap().into()));
|
||||
(g["name"].as_str().unwrap().to_string(), items.collect())
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn refs(v: &[(&str, &str)]) -> Vec<(String, String)> {
|
||||
v.iter().map(|(k, i)| (k.to_string(), i.to_string())).collect()
|
||||
}
|
||||
|
||||
/// Graphics added one after another get ids of their own (the third used to repeat the second's).
|
||||
#[test]
|
||||
fn every_graphic_gets_an_id_of_its_own() {
|
||||
let mut s = session();
|
||||
run(&mut s, "library.create", json!({}));
|
||||
let mut ids = vec![];
|
||||
for x in [0, 30, 60, 90] {
|
||||
let r = run(&mut s, "shape.rectangle", json!({"x": x, "y": 0, "width": 10 + x, "height": 10}))["id"].clone();
|
||||
ids.push(run(&mut s, "library.add", json!({"kind": "graphic", "ids": [r]}))["id"].as_str().unwrap().to_string());
|
||||
}
|
||||
assert_eq!(ids, ["graphic", "graphic-2", "graphic-3", "graphic-4"]);
|
||||
}
|
||||
|
||||
/// Items go into user-named groups and back out (#926); deleting a group keeps its items.
|
||||
#[test]
|
||||
fn items_are_grouped_moved_and_ungrouped() {
|
||||
let (mut s, g, c, st) = brand();
|
||||
assert!(groups(&mut s).is_empty(), "no groups yet");
|
||||
// A group made with items; a graphic is named by its name or its id.
|
||||
let r = run(&mut s, "library.createGroup", json!({"name": "Logos", "items": [{"kind": "graphic", "item": "Logo"}]}));
|
||||
assert_eq!(r["group"], "Logos");
|
||||
assert_eq!(groups(&mut s), [("Logos".into(), refs(&[("graphic", &g)]))]);
|
||||
// A name taken (ignoring case) gets a number.
|
||||
assert_eq!(run(&mut s, "library.createGroup", json!({"name": "logos"}))["group"], "logos 2");
|
||||
run(&mut s, "library.renameGroup", json!({"group": "logos 2", "name": "Palette"}));
|
||||
assert!(s.execute("library.renameGroup", &json!({"group": "Palette", "name": "LOGOS"})).is_err(), "another group's name");
|
||||
assert!(s.execute("library.renameGroup", &json!({"group": "Nope", "name": "X"})).is_err());
|
||||
// Moving an item takes it out of the group it was in; a colour is named as fill or stroke.
|
||||
run(&mut s, "library.moveItem", json!({"kind": "strokeColor", "item": c, "group": "palette"}));
|
||||
run(&mut s, "library.moveItem", json!({"kind": "charStyle", "item": st, "group": "Palette"}));
|
||||
let moved = run(&mut s, "library.moveItem", json!({"kind": "graphic", "item": "Logo", "group": "Palette"}));
|
||||
assert_eq!((moved["item"].as_str(), moved["group"].as_str()), (Some(g.as_str()), Some("Palette")));
|
||||
assert_eq!(groups(&mut s), [("Logos".into(), vec![]), ("Palette".into(), refs(&[("color", &c), ("charStyle", &st), ("graphic", &g)]))]);
|
||||
// Without a group, out of its group.
|
||||
assert!(run(&mut s, "library.moveItem", json!({"kind": "fillColor", "item": c}))["group"].is_null());
|
||||
assert!(s.execute("library.moveItem", &json!({"kind": "fillColor", "item": c, "group": "Nope"})).is_err());
|
||||
assert!(s.execute("library.moveItem", &json!({"kind": "fillColor", "item": "#nope", "group": "Palette"})).is_err());
|
||||
assert!(s.execute("library.createGroup", &json!({"items": [{"kind": "graphic", "item": "nope"}]})).is_err(), "no such item");
|
||||
assert_eq!(groups(&mut s).len(), 2, "a failed command makes no group");
|
||||
// A deleted item leaves its group.
|
||||
run(&mut s, "library.removeItem", json!({"kind": "charStyle", "item": st}));
|
||||
assert_eq!(groups(&mut s)[1].1, refs(&[("graphic", &g)]));
|
||||
// A deleted group's items stay, ungrouped.
|
||||
assert_eq!(run(&mut s, "library.deleteGroup", json!({"group": "Palette"}))["ungrouped"], 1);
|
||||
assert_eq!(run(&mut s, "library.get", json!({}))["graphics"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(groups(&mut s), [("Logos".into(), vec![])]);
|
||||
assert_eq!(run(&mut s, "library.list", json!({}))["libraries"][0]["groups"], 1);
|
||||
}
|
||||
|
||||
/// A library goes out to a file with its art and groups and comes back as a new library, numbered
|
||||
/// when its name is taken; the graphic it brings places in a document (#926).
|
||||
#[test]
|
||||
fn a_library_is_exported_and_imported() {
|
||||
let (mut s, g, c, _) = brand();
|
||||
run(&mut s, "library.createGroup", json!({"name": "Logos", "items": [{"kind": "graphic", "item": g}, {"kind": "fillColor", "item": c}]}));
|
||||
let out = run(&mut s, "library.export", json!({}));
|
||||
assert_eq!(out["name"], "Brand");
|
||||
let data = out["data"].as_str().unwrap().to_string();
|
||||
let r = run(&mut s, "library.import", json!({"data": data}));
|
||||
let counts = ["graphics", "colors", "charStyles", "paraStyles", "groups"].map(|k| r[k].as_u64().unwrap());
|
||||
assert_eq!((r["name"].as_str(), counts), (Some("Brand (2)"), [1, 1, 1, 0, 1]));
|
||||
let id = r["id"].as_str().unwrap().to_string();
|
||||
assert_eq!(run(&mut s, "library.list", json!({}))["current"], id, "the imported library is the current one");
|
||||
let a = run(&mut s, "library.get", json!({"library": "Brand"}));
|
||||
let b = run(&mut s, "library.get", json!({"library": id}));
|
||||
for k in ["graphics", "colors", "charStyles", "paraStyles", "groups"] {
|
||||
assert_eq!(a[k], b[k], "{k}");
|
||||
}
|
||||
// Again: the next number; given a name, that name.
|
||||
let b64 = vectorcraft_format::base64_encode(data.as_bytes());
|
||||
assert_eq!(run(&mut s, "library.import", json!({"dataBase64": b64}))["name"], "Brand (3)");
|
||||
assert_eq!(run(&mut s, "library.import", json!({"data": data, "name": "Client"}))["name"], "Client");
|
||||
// Its graphic places in another document.
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
let placed = run(&mut s, "library.use", json!({"library": id, "kind": "graphic", "item": "Logo", "center": [50, 50]}));
|
||||
assert_eq!(placed["ids"].as_array().unwrap().len(), 1);
|
||||
// Not a library file.
|
||||
let swatches = json!({"format": "vcswatches", "name": "S"}).to_string();
|
||||
for bad in [json!({"data": "{not json"}), json!({"data": "[1, 2]"}), json!({"data": swatches}), json!({"dataBase64": "%%"}), json!({})] {
|
||||
assert!(s.execute("library.import", &bad).is_err(), "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A file written before groups loads; one with repeated names, groups naming items that aren't
|
||||
/// there or kinds this version doesn't know, and a thumbnail claiming a huge image is made safe.
|
||||
#[test]
|
||||
fn imported_libraries_are_made_consistent() {
|
||||
let mut s = session();
|
||||
let old = json!({"name": "Old", "colors": [{"name": "Red", "color": {"model": "rgb", "r": 1, "g": 0, "b": 0}}]});
|
||||
let r = run(&mut s, "library.import", json!({"data": old.to_string()}));
|
||||
assert_eq!((r["colors"].as_u64(), r["groups"].as_u64()), (Some(1), Some(0)));
|
||||
// A PNG header claiming 100000 × 100000 pixels.
|
||||
let mut png = b"\x89PNG\r\n\x1a\n\0\0\0\x0dIHDR".to_vec();
|
||||
png.extend(100_000u32.to_be_bytes());
|
||||
png.extend(100_000u32.to_be_bytes());
|
||||
png.extend([8, 6, 0, 0, 0]);
|
||||
let messy = json!({
|
||||
"name": " ",
|
||||
"colors": [{"name": "Red", "color": {"model": "rgb", "r": 1, "g": 0, "b": 0}}, {"name": "Red", "color": {"model": "rgb", "r": 0, "g": 1, "b": 0}}, {"name": "", "color": {"model": "rgb", "r": 0, "g": 0, "b": 1}}],
|
||||
"graphics": [
|
||||
{"id": "g", "name": "A", "width": 1, "height": 1, "data": "", "thumbnail": vectorcraft_format::base64_encode(&png)},
|
||||
{"id": "g", "name": "B", "width": -5, "height": 1, "data": ""}
|
||||
],
|
||||
"groups": [
|
||||
{"name": "One", "items": [{"kind": "color", "item": "Red 2"}, {"kind": "graphic", "item": "nope"}, {"kind": "brush", "item": "Red"}]},
|
||||
{"name": "one", "items": [{"kind": "color", "item": "Red 2"}, {"kind": "graphic", "item": "g-2"}]}
|
||||
]
|
||||
});
|
||||
let r = run(&mut s, "library.import", json!({"data": messy.to_string()}));
|
||||
assert_eq!(r["name"], "Library", "a blank name");
|
||||
let got = run(&mut s, "library.get", json!({}));
|
||||
let names: Vec<&str> = got["colors"].as_array().unwrap().iter().map(|c| c["name"].as_str().unwrap()).collect();
|
||||
assert_eq!(names, ["Red", "Red 2", "Color"]);
|
||||
let graphics = got["graphics"].as_array().unwrap();
|
||||
assert_eq!((graphics[0]["id"].as_str(), graphics[1]["id"].as_str()), (Some("g"), Some("g-2")));
|
||||
assert_eq!((graphics[0]["thumbnail"].as_str(), graphics[1]["width"].as_f64()), (Some(""), Some(0.0)));
|
||||
assert_eq!(
|
||||
got["groups"],
|
||||
json!([{"name": "One", "items": [{"kind": "color", "item": "Red 2"}]}, {"name": "one 2", "items": [{"kind": "graphic", "item": "g-2"}]}])
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_library_is_exported_to_a_file_and_imported_from_it() {
|
||||
let dir = vectorcraft_testkit::temp_dir("library-export");
|
||||
let path = dir.join("Brand.vclibrary").to_string_lossy().to_string();
|
||||
let (mut s, g, ..) = brand();
|
||||
run(&mut s, "library.createGroup", json!({"name": "Logos", "items": [{"kind": "graphic", "item": g}]}));
|
||||
assert_eq!(run(&mut s, "library.export", json!({"library": "Brand", "path": path}))["path"], path.as_str());
|
||||
let mut t = session();
|
||||
let r = run(&mut t, "library.import", json!({"path": path}));
|
||||
assert_eq!((r["name"].as_str(), r["graphics"].as_u64(), r["groups"].as_u64()), (Some("Brand"), Some(1), Some(1)));
|
||||
assert!(t.execute("library.import", &json!({"path": dir.join("missing.vclibrary").to_string_lossy()})).is_err());
|
||||
// Groups are kept in the library folder's files too.
|
||||
let folder = dir.join("folder").to_string_lossy().to_string();
|
||||
let mut u = session();
|
||||
u.libraries.set_dir(Some(folder.clone()));
|
||||
run(&mut u, "library.import", json!({"path": path}));
|
||||
let mut v = session();
|
||||
v.libraries.set_dir(Some(folder));
|
||||
assert_eq!(groups(&mut v), [("Logos".into(), refs(&[("graphic", &g)]))]);
|
||||
}
|
||||
@@ -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");
|
||||
|
||||
@@ -58,6 +58,25 @@ fn a_whole_rectangle_rounds_all_corners_and_given_corners_alone() {
|
||||
assert_eq!(corners(&s, id).1[3], CornerKind::Chamfer);
|
||||
}
|
||||
|
||||
/// #938: `items` rounds several objects in one step, each its own corners (or all of them).
|
||||
#[test]
|
||||
fn items_round_several_objects_each_its_own_corners() {
|
||||
let (mut s, a) = session();
|
||||
let b = NodeId(s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 100, "height": 60})).unwrap()["id"].as_u64().unwrap());
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
run(&mut s, json!({"items": [{"id": a.0, "corners": [2]}, {"id": b.0}], "radius": 6}));
|
||||
assert_eq!(corners(&s, a).0, [0.0, 0.0, 6.0, 0.0]);
|
||||
assert_eq!(corners(&s, b).0, [6.0; 4]);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one step");
|
||||
for p in [
|
||||
json!({"items": 3, "radius": 1}),
|
||||
json!({"items": [{"corners": [1]}], "radius": 1}),
|
||||
json!({"items": [{"id": a.0, "corners": [9]}], "radius": 1}),
|
||||
] {
|
||||
assert!(s.execute("object.setLiveShape", &p).is_err(), "{p}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_corners_and_kinds_are_errors() {
|
||||
let (mut s, id) = session();
|
||||
|
||||
@@ -21,6 +21,10 @@ const EFFECTS: [(&str, &str); 3] = [
|
||||
const PIXELATE: [(&str, &str); 4] =
|
||||
[("pixelate.colorHalftone", "{}"), ("pixelate.crystallize", "{}"), ("pixelate.mezzotint", "{}"), ("pixelate.pointillize", "{}")];
|
||||
|
||||
/// Effect › Video (NTSC Colors leaves the striped art's legal colours as they are: see
|
||||
/// `ntsc_colors_draws_saturated_yellow_safer`).
|
||||
const VIDEO: [(&str, &str); 1] = [("video.deinterlace", r#"{"create": "interpolation"}"#)];
|
||||
|
||||
/// A group of a red square and a darker red stripe across it; returns the group's id.
|
||||
fn striped() -> (Session, u64) {
|
||||
let mut s = Session::new();
|
||||
@@ -57,9 +61,11 @@ fn listed_applied_edited_and_undone() {
|
||||
let menus: Vec<Value> =
|
||||
EFFECTS.iter().map(|(id, _)| list["catalog"].as_array().unwrap().iter().find(|e| e["id"] == *id).unwrap()["menu"].clone()).collect();
|
||||
assert_eq!(menus, [json!(["Effect", "Blur"]), json!(["Effect", "Blur"]), json!(["Effect", "Sharpen"])]);
|
||||
for (id, _) in PIXELATE {
|
||||
let e = list["catalog"].as_array().unwrap().iter().find(|e| e["id"] == id).unwrap_or_else(|| panic!("{id} listed"));
|
||||
assert_eq!((&e["raster"], &e["menu"]), (&json!(true), &json!(["Effect", "Pixelate"])), "{id}");
|
||||
for (group, menu) in [(PIXELATE.as_slice(), "Pixelate"), (VIDEO.as_slice(), "Video"), ([("video.ntscColors", "{}")].as_slice(), "Video")] {
|
||||
for (id, _) in group {
|
||||
let e = list["catalog"].as_array().unwrap().iter().find(|e| e["id"] == *id).unwrap_or_else(|| panic!("{id} listed"));
|
||||
assert_eq!((&e["raster"], &e["menu"]), (&json!(true), &json!(["Effect", menu])), "{id}");
|
||||
}
|
||||
}
|
||||
// Junk parameters are stored as given and read clamped; the canvas still draws.
|
||||
for (id, _) in EFFECTS {
|
||||
@@ -80,7 +86,7 @@ fn listed_applied_edited_and_undone() {
|
||||
|
||||
#[test]
|
||||
fn each_effect_changes_the_canvas_and_draws_the_same_twice() {
|
||||
for (id, params) in EFFECTS.into_iter().chain(PIXELATE) {
|
||||
for (id, params) in EFFECTS.into_iter().chain(PIXELATE).chain(VIDEO) {
|
||||
let (mut s, g) = striped();
|
||||
let plain = render(&s);
|
||||
let params: Value = serde_json::from_str(params).unwrap();
|
||||
@@ -109,7 +115,7 @@ fn spin_blur_reaches_past_the_corners() {
|
||||
|
||||
#[test]
|
||||
fn pdf_and_svg_write_the_effected_object_as_an_image() {
|
||||
for (id, params) in EFFECTS.into_iter().chain(PIXELATE) {
|
||||
for (id, params) in EFFECTS.into_iter().chain(PIXELATE).chain(VIDEO) {
|
||||
let (mut s, g) = striped();
|
||||
let params: Value = serde_json::from_str(params).unwrap();
|
||||
s.execute("effect.apply", &json!({"effect": id, "ids": [g], "params": params})).unwrap();
|
||||
@@ -140,3 +146,22 @@ fn expand_appearance_makes_an_image() {
|
||||
s.execute("effect.expandAppearance", &json!({"ids": [g]})).unwrap();
|
||||
assert!(matches!(s.doc().unwrap().doc.node(NodeId(g)).unwrap().kind, NodeKind::Image(_)));
|
||||
}
|
||||
|
||||
/// Video › NTSC Colors on the canvas: a saturated yellow, too strong for a television signal, draws
|
||||
/// less saturated; the effect is listed and applies without options.
|
||||
#[test]
|
||||
fn ntsc_colors_draws_saturated_yellow_safer() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
|
||||
let id = s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ffff00", "ids": [id]})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true, "ids": [id]})).unwrap();
|
||||
let before = render(&s);
|
||||
s.execute("effect.apply", &json!({"effect": "video.ntscColors", "ids": [id]})).unwrap();
|
||||
let after = render(&s);
|
||||
let px = |r: &Rendered| r.pixel(100, 100);
|
||||
let (a, b) = (px(&before), px(&after));
|
||||
assert_eq!(&a[..3], &[255, 255, 0]);
|
||||
assert!(b[2] > 20 && b[0] < 255 && b[3] == 255, "less saturated: {b:?}");
|
||||
assert_eq!(after.pixels, render(&s).pixels, "deterministic");
|
||||
}
|
||||
@@ -282,6 +282,8 @@ fn structured_junk() {
|
||||
("effect.apply", json!({"effect": "pixelate.crystallize", "params": {"cellSize": -1e308}})),
|
||||
("effect.apply", json!({"effect": "pixelate.mezzotint", "params": {"type": 5}})),
|
||||
("effect.apply", json!({"effect": "pixelate.pointillize", "params": {"cellSize": "NaN"}})),
|
||||
("effect.apply", json!({"effect": "video.deinterlace", "params": {"eliminate": 7, "create": ["x"]}})),
|
||||
("effect.apply", json!({"effect": "video.ntscColors", "params": {"junk": 1e308}})),
|
||||
("effect.apply", json!({"effect": "no.such.effect"})),
|
||||
("effect.remove", json!({"index": 99})),
|
||||
("effect.setParams", json!({"index": 0, "params": null})),
|
||||
|
||||
@@ -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
|
||||
@@ -804,6 +804,53 @@ fn styles(what: &str, data: &str) -> Result<(), TestCaseError> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Libraries panel library file `data` imported, then each kind's first item used on the rich
|
||||
/// document and moved into its first group, the group deleted and the library exported (#926).
|
||||
fn libraries(what: &str, data: &str) -> Result<(), TestCaseError> {
|
||||
survive_library(what, "library.import", data, |s, r| {
|
||||
let lib = r["id"].clone();
|
||||
let Ok(got) = no_panic(s.execute("library.get", &json!({"library": lib}))) else { return };
|
||||
let _ = no_panic(s.execute("select.all", &json!({})));
|
||||
for (list, kind, key) in
|
||||
[("graphics", "graphic", "id"), ("colors", "fillColor", "name"), ("charStyles", "charStyle", "name"), ("paraStyles", "paraStyle", "name")]
|
||||
{
|
||||
if let Some(item) = got[list].get(0) {
|
||||
let _ = no_panic(s.execute("library.use", &json!({"library": lib, "kind": kind, "item": item[key]})));
|
||||
let to = json!({"library": lib, "kind": kind, "item": item[key], "group": got["groups"][0]["name"]});
|
||||
let _ = no_panic(s.execute("library.moveItem", &to));
|
||||
}
|
||||
}
|
||||
if let Some(g) = got["groups"].get(0) {
|
||||
let _ = no_panic(s.execute("library.deleteGroup", &json!({"library": lib, "group": g["name"]})));
|
||||
}
|
||||
let _ = no_panic(s.execute("library.export", &json!({"library": lib})));
|
||||
})
|
||||
}
|
||||
|
||||
/// A Libraries panel library of the rich document's first object (a graphic), a colour, its
|
||||
/// type's character and paragraph styles and a group, exported, made once.
|
||||
fn saved_library() -> String {
|
||||
static TEXT: std::sync::OnceLock<String> = std::sync::OnceLock::new();
|
||||
TEXT.get_or_init(|| {
|
||||
let mut s = rich_session();
|
||||
s.execute("library.create", &json!({"name": "Fuzz"})).unwrap();
|
||||
let first = s.doc().unwrap().doc.layers[0].children().unwrap()[0].id.0;
|
||||
let g = s.execute("library.add", &json!({"kind": "graphic", "ids": [first]})).unwrap()["id"].clone();
|
||||
s.execute("library.add", &json!({"kind": "fillColor", "color": "#336699"})).unwrap();
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
for kind in ["charStyle", "paraStyle"] {
|
||||
s.execute("library.add", &json!({"kind": kind})).unwrap();
|
||||
}
|
||||
s.execute(
|
||||
"library.createGroup",
|
||||
&json!({"name": "Logos", "items": [{"kind": "graphic", "item": g}, {"kind": "fillColor", "item": "#336699"}]}),
|
||||
)
|
||||
.unwrap();
|
||||
s.execute("library.export", &json!({})).unwrap()["data"].as_str().unwrap().to_string()
|
||||
})
|
||||
.clone()
|
||||
}
|
||||
|
||||
fn flattener_presets(what: &str, data: &str) -> Result<(), TestCaseError> {
|
||||
survive_library(what, "flattener.presets.import", data, |s, r| {
|
||||
let _ = no_panic(s.execute("select.all", &json!({})));
|
||||
@@ -865,11 +912,12 @@ proptest! {
|
||||
#![proptest_config(config())]
|
||||
|
||||
#[test]
|
||||
fn library_garbage_never_panics(s in ".{0,300}", head in prop::sample::select(vec!["", "GIMP Palette\n","{\"format\": \"vcswatches\", ", "{\"format\": \"vcstyles\", ", "{\"format\": \"vcflattener\", "])) {
|
||||
fn library_garbage_never_panics(s in ".{0,300}", head in prop::sample::select(vec!["", "GIMP Palette\n","{\"format\": \"vcswatches\", ", "{\"format\": \"vcstyles\", ", "{\"format\": \"vcflattener\", ", "{\"name\": \"L\", "])) {
|
||||
let data = format!("{head}{s}");
|
||||
swatches("swatch library garbage", &data)?;
|
||||
styles("style library garbage", &data)?;
|
||||
flattener_presets("flattener preset garbage", &data)?;
|
||||
libraries("library garbage", &data)?;
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -890,6 +938,14 @@ proptest! {
|
||||
flattener_presets("mutated flattener presets", &mutate_text(&text, cut, &edits))?;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mutated_libraries_never_panic(keep in 0.0f64..1.2, edits in prop::collection::vec(arb_edit(), 0..10)) {
|
||||
// Cut anywhere in the file (whole most of the time), the edits anywhere in it.
|
||||
let text = saved_library();
|
||||
let cut = (text.chars().count() as f64 * keep) as usize;
|
||||
libraries("mutated library", &mutate_text(&text, cut, &edits))?;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn swatch_exchange_garbage_never_panics(blocks in prop::collection::vec(arb_ase_block(), 0..12), tail in prop::collection::vec(any::<u8>(), 0..16)) {
|
||||
let mut bytes = b"ASEF\0\x01\0\0".to_vec();
|
||||
@@ -945,6 +1001,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 +1023,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) {
|
||||
|
||||
@@ -34,6 +34,9 @@ const MAX_PATH: usize = 1 << 20;
|
||||
const MAX_DRAWN: usize = 1 << 24;
|
||||
/// Samples taken of a shading function that isn't a plain interpolation.
|
||||
const SHADING_SAMPLES: usize = 32;
|
||||
/// Most bounds of a stitched linear function that become a gradient's stops: past it, the
|
||||
/// function is sampled like any other (each stop evaluates the whole function).
|
||||
const MAX_STITCH_STOPS: usize = 1024;
|
||||
|
||||
pub(super) const FAR_AWAY: &str = "objects far outside the page were left out";
|
||||
pub(super) const TOO_MUCH: &str = "the file draws more than VectorCraft reads: the rest was left out";
|
||||
@@ -1007,8 +1010,10 @@ impl Interp<'_> {
|
||||
let domain = nums(get("Domain"));
|
||||
let (d0, d1) = (domain.first().copied().unwrap_or(0.0), domain.get(1).copied().unwrap_or(1.0));
|
||||
let f = get("Function").ok_or(PsError::Ps("undefined", "Function".into()))?;
|
||||
// Where the colour changes: the ends, and the bounds of stitched linear functions.
|
||||
let ts: Vec<f64> = match linear_points(&f) {
|
||||
// Where the colour changes: the ends, and the bounds of stitched linear functions (unless
|
||||
// there are too many).
|
||||
let mut visits = 0;
|
||||
let ts: Vec<f64> = match linear_points(&f, 0, &mut visits).filter(|p| p.len() <= MAX_STITCH_STOPS) {
|
||||
Some(mut pts) => {
|
||||
pts.retain(|t| (d0.min(d1)..=d0.max(d1)).contains(t));
|
||||
pts.iter().map(|t| if d1 != d0 { (t - d0) / (d1 - d0) } else { 0.0 }).chain([0.0, 1.0]).collect()
|
||||
@@ -1085,16 +1090,21 @@ impl Interp<'_> {
|
||||
Ok(c0.iter().zip(&c1).map(|(a, b)| a + x * (b - a)).collect())
|
||||
}
|
||||
Some(3.0) => {
|
||||
let fs = get("Functions").and_then(|o| o.items().map(|i| i.to_vec())).unwrap_or_default();
|
||||
// Read the pieces through the borrow and clone only the one we recurse into: a
|
||||
// `Functions` array of millions (shared, or reached again through a cycle) must
|
||||
// not be copied on every call and at every live recursion level.
|
||||
let functions = get("Functions");
|
||||
let fs = functions.as_ref().and_then(Obj::items);
|
||||
let n = fs.map_or(0, Shared::len);
|
||||
let bounds = nums(get("Bounds"));
|
||||
let encode = nums(get("Encode"));
|
||||
let (lo, hi) = (domain.first().copied().unwrap_or(0.0), domain.get(1).copied().unwrap_or(1.0));
|
||||
let k = bounds.iter().take_while(|b| t >= **b).count().min(fs.len().saturating_sub(1));
|
||||
let k = bounds.iter().take_while(|b| t >= **b).count().min(n.saturating_sub(1));
|
||||
let a = if k == 0 { lo } else { bounds.get(k - 1).copied().unwrap_or(lo) };
|
||||
let b = bounds.get(k).copied().unwrap_or(hi);
|
||||
let (e0, e1) = (encode.get(2 * k).copied().unwrap_or(0.0), encode.get(2 * k + 1).copied().unwrap_or(1.0));
|
||||
let u = if b != a { e0 + (t - a) / (b - a) * (e1 - e0) } else { e0 };
|
||||
let g = fs.get(k).cloned().ok_or(PsError::Ps("rangecheck", "Functions".into()))?;
|
||||
let g = fs.and_then(|fs| fs.get(k)).ok_or(PsError::Ps("rangecheck", "Functions".into()))?;
|
||||
self.eval(&g, &[u], depth + 1)
|
||||
}
|
||||
_ => {
|
||||
@@ -1621,16 +1631,34 @@ fn is_mesh(sh: &DictRef) -> bool {
|
||||
}
|
||||
|
||||
/// Where a stitched function of linear interpolations changes slope (its bounds), when it is
|
||||
/// one; `None` for functions that must be sampled.
|
||||
fn linear_points(f: &Obj) -> Option<Vec<f64>> {
|
||||
/// one; `None` for functions that must be sampled. `depth` bounds the nesting the same way
|
||||
/// [`Interp::eval`] does (`> 8`) and `visits` (shared by the whole recursion, incremented on
|
||||
/// every call) bounds the total nodes looked at. Both are needed: the depth limit alone stops a
|
||||
/// function that refers to itself in a cycle, but not one that fans out through shared children
|
||||
/// (1025 references to a child a few levels deep is 1025^levels nodes without the visit cap). A
|
||||
/// well-formed stitch of linear pieces is one level, at most `MAX_STITCH_STOPS + 1` pieces, so it
|
||||
/// costs at most `MAX_STITCH_STOPS + 2` visits and is never cut off.
|
||||
fn linear_points(f: &Obj, depth: u32, visits: &mut usize) -> Option<Vec<f64>> {
|
||||
*visits += 1;
|
||||
if depth > 8 || *visits > 2 * (MAX_STITCH_STOPS + 1) {
|
||||
return None;
|
||||
}
|
||||
let Obj::Dict(d) = f else { return None };
|
||||
let d = d.borrow();
|
||||
let num = |k: &str| d.get(&Key::name(k)).and_then(Obj::as_num);
|
||||
match num("FunctionType")? {
|
||||
2.0 if num("N").unwrap_or(1.0) == 1.0 => Some(vec![]),
|
||||
3.0 => {
|
||||
let fs = d.get(&Key::name("Functions"))?.items()?.to_vec();
|
||||
if !fs.iter().all(|g| linear_points(g).is_some_and(|p| p.is_empty())) {
|
||||
let items = d.get(&Key::name("Functions"))?.items()?;
|
||||
// More pieces than the stop cap allows: sample the function instead (tested before
|
||||
// `to_vec`, so a huge `Functions` array is not copied only to be rejected). Each stop
|
||||
// runs [`Interp::eval`], which reads one piece, so a short `Bounds` with a huge
|
||||
// `Functions` would still be O(stops * Functions) to find each piece without this.
|
||||
if items.len() > MAX_STITCH_STOPS + 1 {
|
||||
return None;
|
||||
}
|
||||
let fs = items.to_vec();
|
||||
if !fs.iter().all(|g| linear_points(g, depth + 1, visits).is_some_and(|p| p.is_empty())) {
|
||||
return None;
|
||||
}
|
||||
d.get(&Key::name("Bounds"))?.items().map(|i| i.borrow().iter().filter_map(Obj::as_num).collect())
|
||||
|
||||
@@ -897,6 +897,99 @@ fn hostile_patterns_glyphs_and_shadings_end() {
|
||||
assert_eq!(objects(&r.document).len(), 1);
|
||||
}
|
||||
|
||||
/// The stops of the gradient `body` draws, after asserting it came in cleanly as one gradient.
|
||||
fn stitch_stops(body: &str) -> Vec<f32> {
|
||||
let r = read(body);
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let o = objects(&r.document);
|
||||
let [node] = o.as_slice() else { panic!("{o:?}") };
|
||||
let Some(Paint::Gradient(g)) = fill(node) else { panic!("{node:?}") };
|
||||
g.gradient.stops.iter().map(|s| s.offset).collect()
|
||||
}
|
||||
|
||||
/// A gradient stitched from linear pieces keeps their bounds as its stops up to the cap, and is
|
||||
/// sampled past it. The cap is on the pieces; a well-formed stitch has one more piece than bounds.
|
||||
#[test]
|
||||
fn gradients_stitched_from_linear_pieces_keep_or_sample_their_stops() {
|
||||
// `bounds` interior bounds at i / (bounds + 1), with one linear piece more than that.
|
||||
let stitched = |bounds: usize| {
|
||||
let pieces = bounds + 1;
|
||||
format!(
|
||||
"/F << /FunctionType 2 /Domain [0 1] /C0 [0] /C1 [1] /N 1 >> def \
|
||||
<< /ShadingType 2 /ColorSpace /DeviceGray /Coords [0 0 100 0] /Function << /FunctionType 3 /Domain [0 1] \
|
||||
/Functions [ {pieces} {{ F }} repeat ] /Bounds [ 1 1 {bounds} {{ {pieces} div }} for ] >> >> shfill"
|
||||
)
|
||||
};
|
||||
// A few pieces: the bounds are kept exactly as stops (three bounds -> five stops with the ends).
|
||||
assert_eq!(stitch_stops(&stitched(3)), vec![0.0, 0.25, 0.5, 0.75, 1.0]);
|
||||
// At the cap (1024 bounds, 1025 pieces) the 1024 bounds and the two ends are all kept.
|
||||
assert_eq!(stitch_stops(&stitched(1024)).len(), 1026);
|
||||
// One past it (1025 bounds, 1026 pieces) the function is sampled instead.
|
||||
assert_eq!(stitch_stops(&stitched(1025)).len(), 33);
|
||||
}
|
||||
|
||||
/// A malformed stitching function with a single piece but thousands of bounds is sampled, not
|
||||
/// turned into thousands of stops. This is the one case the stop-count `.filter` catches on its
|
||||
/// own: the one piece is under the Functions-length guard, so only the bound count is out of range.
|
||||
#[test]
|
||||
fn a_stitching_function_with_one_piece_but_many_bounds_is_sampled() {
|
||||
let stops = stitch_stops(
|
||||
"/F << /FunctionType 2 /Domain [0 1] /C0 [0] /C1 [1] /N 1 >> def \
|
||||
<< /ShadingType 2 /ColorSpace /DeviceGray /Coords [0 0 100 0] /Function << /FunctionType 3 /Domain [0 1] \
|
||||
/Functions [ F ] /Bounds [ 1 1 2000 { 2001 div } for ] >> >> shfill",
|
||||
);
|
||||
// Base keeps all 2000 bounds (2002 stops); the fix samples.
|
||||
assert_eq!(stops.len(), 33);
|
||||
}
|
||||
|
||||
/// A short `Bounds` with a `Functions` array one past the cap is sampled: without the length
|
||||
/// guard each of the ~1000 stops would read through the whole array to find its piece.
|
||||
#[test]
|
||||
fn a_gradient_with_a_functions_array_past_the_cap_is_sampled() {
|
||||
let stops = stitch_stops(
|
||||
"/F << /FunctionType 2 /Domain [0 1] /C0 [0] /C1 [1] /N 1 >> def \
|
||||
<< /ShadingType 2 /ColorSpace /DeviceGray /Coords [0 0 100 0] /Function << /FunctionType 3 /Domain [0 1] \
|
||||
/Functions [ 1026 { F } repeat ] /Bounds [ 1 1 1000 { 1001 div } for ] >> >> shfill",
|
||||
);
|
||||
// Base keeps the 1000 bounds (1002 stops); the fix samples.
|
||||
assert_eq!(stops.len(), 33);
|
||||
}
|
||||
|
||||
/// A stitching function (type 3) whose `Functions` array holds the function itself must not
|
||||
/// recurse without end: `linear_points` (depth- and visit-bounded) and `eval` (depth-bounded)
|
||||
/// both stop, so the shading raises an error instead of overflowing the stack (an abort
|
||||
/// `vectorcraft_engine::guard` can't catch, and on wasm there is no net at all).
|
||||
#[test]
|
||||
fn a_stitching_function_that_refers_to_itself_is_rejected_not_crashed() {
|
||||
let r = read(
|
||||
"0 0 10 10 rectfill \
|
||||
/F 5 dict def F /FunctionType 3 put F /Domain [0 1] put F /Bounds [] put F /Encode [0 1] put F /Functions [ F ] put \
|
||||
<< /ShadingType 2 /ColorSpace /DeviceGray /Coords [0 0 100 0] /Function F >> shfill",
|
||||
);
|
||||
// Not an abort: the reader stops at the error, keeps the rectangle drawn before it, and leaves
|
||||
// the rest of the program unread (see `import`: what follows the error is left out).
|
||||
assert_eq!(objects(&r.document).len(), 1);
|
||||
assert!(r.warnings.iter().any(|w| w.contains("read up to an error") && w.contains("Function")), "{:?}", r.warnings);
|
||||
}
|
||||
|
||||
/// A stitching function need not point at itself to blow up: a `Functions` array of 1025
|
||||
/// references to a child that holds 1025 references to a child ... is a tree of 1025^levels nodes
|
||||
/// though it is tiny in memory (the children are shared). The shared visit counter stops
|
||||
/// `linear_points` after about 2 * (MAX_STITCH_STOPS + 1) nodes, so it is sampled at once instead
|
||||
/// of being walked; on the unmodified reader this explores ~1025^3 nodes.
|
||||
#[test]
|
||||
fn a_deeply_shared_stitching_function_is_sampled_not_walked() {
|
||||
// leaf (linear) <- mid2[1025 leaf] <- mid1[1025 mid2] <- top[1025 mid1] (1000 bounds).
|
||||
let stops = stitch_stops(
|
||||
"/leaf << /FunctionType 2 /Domain [0 1] /C0 [0] /C1 [1] /N 1 >> def \
|
||||
/mid2 << /FunctionType 3 /Domain [0 1] /Bounds [] /Functions [ 1025 { leaf } repeat ] >> def \
|
||||
/mid1 << /FunctionType 3 /Domain [0 1] /Bounds [] /Functions [ 1025 { mid2 } repeat ] >> def \
|
||||
/top << /FunctionType 3 /Domain [0 1] /Bounds [ 1 1 1000 { 1001 div } for ] /Functions [ 1025 { mid1 } repeat ] >> def \
|
||||
<< /ShadingType 2 /ColorSpace /DeviceGray /Coords [0 0 100 0] /Function top >> shfill",
|
||||
);
|
||||
assert_eq!(stops.len(), 33);
|
||||
}
|
||||
|
||||
/// Executable strings and keys other than names (#474): `cvx` makes a string executable, and
|
||||
/// running it runs its text (PLRM 3rd ed. §3.3.1, `cvx`, `exec`); `load` takes any key (§8.2).
|
||||
/// A program closes its shading dictionaries with an executable string (`>>` at Level 2 and up,
|
||||
|
||||
@@ -503,6 +503,46 @@ fn matching_face(
|
||||
best.map(|(_, f)| f)
|
||||
}
|
||||
|
||||
/// The characters a glyph no mapping names is looked for among (#811): those single-byte fonts
|
||||
/// encode (ASCII, Latin-1, Latin Extended-A, general punctuation, the euro and trade mark signs,
|
||||
/// the fi and fl ligatures).
|
||||
const IDENTIFIABLE: [std::ops::RangeInclusive<u32>; 6] =
|
||||
[0x21..=0x7E, 0xA1..=0x17F, 0x2010..=0x2044, 0x20AC..=0x20AC, 0x2122..=0x2122, 0xFB01..=0xFB02];
|
||||
|
||||
/// The character whose glyph in installed `face` draws `embedded` (a glyph outline in thousandths
|
||||
/// of an em, y up): the first of [`IDENTIFIABLE`] with the same outline, point for point. A subset
|
||||
/// font embedded without a character map still carries the font's own outlines, so a glyph whose
|
||||
/// subset code names nothing is found this way. `None` when no glyph matches (another version of
|
||||
/// the font, or a glyph that is no character), and for empty glyphs, which every space draws.
|
||||
pub(crate) fn identify_glyph(face: &vectorcraft_text::FontFace, embedded: &BezPath) -> Option<char> {
|
||||
if embedded.elements().is_empty() {
|
||||
return None;
|
||||
}
|
||||
let k = 1000.0 / face.units_per_em();
|
||||
// Installed outlines are y-down in font units.
|
||||
let to_pdf = Affine::new([k, 0.0, 0.0, -k, 0.0, 0.0]);
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
IDENTIFIABLE.iter().cloned().flatten().filter_map(char::from_u32).find(|c| {
|
||||
let gid = face.glyph_for(*c);
|
||||
gid != 0 && same_shape(embedded, &(to_pdf * db.outline(face, gid).as_ref().clone()))
|
||||
})
|
||||
}
|
||||
|
||||
/// Do outlines `a` and `b` draw the same segments, every point within 2/1000 em (closing
|
||||
/// commands aside)?
|
||||
fn same_shape(a: &BezPath, b: &BezPath) -> bool {
|
||||
let drawn = |p: &BezPath| p.elements().iter().filter(|e| !matches!(e, PathEl::ClosePath)).copied().collect::<Vec<_>>();
|
||||
let (a, b) = (drawn(a), drawn(b));
|
||||
let near = |p: kurbo::Point, q: kurbo::Point| (p - q).hypot() <= 2.0;
|
||||
a.len() == b.len()
|
||||
&& a.iter().zip(&b).all(|(x, y)| match (x, y) {
|
||||
(PathEl::MoveTo(p), PathEl::MoveTo(q)) | (PathEl::LineTo(p), PathEl::LineTo(q)) => near(*p, *q),
|
||||
(PathEl::QuadTo(p1, p2), PathEl::QuadTo(q1, q2)) => near(*p1, *q1) && near(*p2, *q2),
|
||||
(PathEl::CurveTo(p1, p2, p3), PathEl::CurveTo(q1, q2, q3)) => near(*p1, *q1) && near(*p2, *q2) && near(*p3, *q3),
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
|
||||
/// The character of glyph `text` when its outline can be compared with an installed font's: a
|
||||
/// single character, and not CJK punctuation set vertically (its vertical form differs).
|
||||
fn comparable(text: &str, vertical: bool) -> Option<char> {
|
||||
@@ -666,6 +706,9 @@ struct Builder<'p> {
|
||||
/// Font (cache key) → the installed face that draws its glyphs, decided from its first glyph
|
||||
/// that can be compared ([`matching_face`]); `None`: its glyphs differ, so it stays outlines.
|
||||
matched: HashMap<u128, Option<Arc<vectorcraft_text::FontFace>>>,
|
||||
/// (Font, glyph) → the character its outline matches in the installed face, for glyphs no
|
||||
/// mapping names ([`Builder::identified_char`]).
|
||||
identified: HashMap<(u128, u32), Option<char>>,
|
||||
/// Per font: the installed version its type names, when it isn't the one its family and style
|
||||
/// resolve to (see `CharStyle::font_version`).
|
||||
versions: HashMap<u128, Option<String>>,
|
||||
@@ -817,6 +860,7 @@ impl<'p> Builder<'p> {
|
||||
cid_text: HashMap::new(),
|
||||
font_chars: HashMap::new(),
|
||||
matched: HashMap::new(),
|
||||
identified: HashMap::new(),
|
||||
versions: HashMap::new(),
|
||||
mask: None,
|
||||
masked: vec![],
|
||||
@@ -1286,6 +1330,17 @@ impl<'p> Builder<'p> {
|
||||
|
||||
/// The family and style of font `key` (drawing glyph `o`): the installed face of its PostScript
|
||||
/// name, else the available family its name reads as; whether it is available.
|
||||
/// The character of glyph `glyph` of font `key` that no mapping names, found by its outline in
|
||||
/// the installed face of the font's name ([`identify_glyph`]); cached per glyph.
|
||||
fn identified_char(&mut self, key: u128, glyph: u32, o: &hayro_interpret::font::OutlineGlyph) -> Option<char> {
|
||||
if let Some(c) = self.identified.get(&(key, glyph)) {
|
||||
return *c;
|
||||
}
|
||||
let c = self.font_name(key, o).face.and_then(|f| identify_glyph(&f, &o.outline()));
|
||||
self.identified.insert((key, glyph), c);
|
||||
c
|
||||
}
|
||||
|
||||
fn font_name(&mut self, key: u128, o: &hayro_interpret::font::OutlineGlyph) -> FontInfo {
|
||||
if let Some(n) = self.font_names.get(&key) {
|
||||
return n.clone();
|
||||
@@ -1345,7 +1400,9 @@ impl<'p> Builder<'p> {
|
||||
.font_chars
|
||||
.entry(key)
|
||||
.or_insert_with(|| o.font_data().and_then(|d| font_chars(d.data.as_ref().as_ref())).map(Arc::new));
|
||||
(chars.as_ref().and_then(|m| m.get(&glyph)).map(|c| BfString::Char(*c)), false)
|
||||
let named = chars.as_ref().and_then(|m| m.get(&glyph)).copied();
|
||||
// Still unnamed: the installed font may draw the same outline (#811).
|
||||
(named.or_else(|| self.identified_char(key, glyph, o)).map(BfString::Char), false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -248,17 +248,33 @@ fn digits_unnamed(text: &str) -> Vec<u8> {
|
||||
out
|
||||
}
|
||||
|
||||
/// #708: a glyph whose ToUnicode value is U+FFFD isn't type showing "�". This subset font has no
|
||||
/// character map of its own, so the digits keep their outlines, drawn as the file draws them, and
|
||||
/// a warning names the font.
|
||||
/// #708, #811: a glyph whose ToUnicode value is U+FFFD isn't type showing "�". This subset font
|
||||
/// has no character map of its own, but the font is installed: each digit is found by its outline
|
||||
/// there, so the whole text stays one type object, with no outlines left behind.
|
||||
#[test]
|
||||
fn glyphs_mapped_to_the_replacement_character_keep_their_outlines() {
|
||||
fn unnamed_glyphs_of_an_installed_font_are_found_by_their_outline() {
|
||||
let bytes = digits_unnamed("Tel 02-12345");
|
||||
let report = import_with_report(&bytes, &ImportOptions { text_as: TextAs::Text, ..Default::default() }).unwrap();
|
||||
let all = texts(&report.document).concat();
|
||||
assert!(!all.contains('\u{FFFD}') && all.contains("Tel"), "no replacement characters: {all:?}");
|
||||
assert!(ink(&report.document).width() > 50.0, "the digits are outlines");
|
||||
assert!(report.warnings.iter().any(|w| w.contains("U+FFFD")), "{:?}", report.warnings);
|
||||
assert_eq!(texts(&report.document), ["Tel 02-12345"]);
|
||||
let mut paths = 0;
|
||||
report.document.walk(|n| paths += usize::from(matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })));
|
||||
assert_eq!(paths, 0, "no outlines left: {:?}", report.warnings);
|
||||
assert!(!report.warnings.iter().any(|w| w.contains("U+FFFD")), "{:?}", report.warnings);
|
||||
}
|
||||
|
||||
/// #811: an outline is named only by a glyph that draws it exactly; one moved off its place, or an
|
||||
/// empty glyph (which every space draws), stays unnamed and keeps its outlines.
|
||||
#[test]
|
||||
fn glyphs_are_named_only_by_an_exact_outline() {
|
||||
let db = FontDb::global();
|
||||
let face = db.face("Source Sans 3", "Regular").unwrap();
|
||||
let k = 1000.0 / face.units_per_em();
|
||||
let pdf_space = |c: char| Affine::new([k, 0.0, 0.0, -k, 0.0, 0.0]) * db.outline(&face, face.glyph_for(c)).as_ref().clone();
|
||||
for c in ['R', 'a', '7', '&', 'é'] {
|
||||
assert_eq!(crate::import::identify_glyph(&face, &pdf_space(c)), Some(c));
|
||||
}
|
||||
assert_eq!(crate::import::identify_glyph(&face, &(Affine::translate((100.0, 0.0)) * pdf_space('R'))), None);
|
||||
assert_eq!(crate::import::identify_glyph(&face, &BezPath::new()), None);
|
||||
}
|
||||
|
||||
/// #708: where the embedded font program has a character map, a glyph's character comes from it.
|
||||
|
||||
@@ -601,7 +601,9 @@ impl Renderer {
|
||||
Ink::Display if f.doc.color_mode == vectorcraft_doc::ColorMode::Cmyk => effects::pixel::Channels::Cmyk,
|
||||
Ink::Display => effects::pixel::Channels::Rgb,
|
||||
};
|
||||
let space = effects::PixelSpace { to_doc, px, center: content.reach.center(), channels };
|
||||
// De-Interlace's field lines: the rows of the document's raster grid (1 to 2400 ppi).
|
||||
let ppi = Some(f.doc.raster_effects_ppi).filter(|v| v.is_finite()).unwrap_or(72.0).clamp(1.0, 2400.0);
|
||||
let space = effects::PixelSpace { to_doc, px, center: content.reach.center(), channels, line: 72.0 / ppi };
|
||||
let (wz, hz) = (wu as usize, hu as usize);
|
||||
for fx in chain {
|
||||
match fx {
|
||||
|
||||
+172
-69
@@ -1,8 +1,8 @@
|
||||
//! Live Corners: the widgets inside the corners of a selected path. The Selection tool shows them
|
||||
//! on a live rectangle or polygon, Direct Selection on any path (a star, a pen path) at each corner
|
||||
//! anchor: one without handles between two straight sides. Dragging one rounds (or sharpens) the
|
||||
//! corners whose widgets show together: every corner when the whole path is selected, those with a
|
||||
//! selected anchor when Direct Selection picked some. Alt-clicking a widget cycles their corner
|
||||
//! Live Corners: the widgets inside the corners of the selected paths. The Selection tool shows
|
||||
//! them on live rectangles and polygons, Direct Selection on any path (a star, a pen path) at each
|
||||
//! corner anchor: one without handles between two straight sides. Dragging one rounds (or
|
||||
//! sharpens) the corners whose widgets show together, on every selected path (#938): every corner
|
||||
//! of a path selected whole, those with a selected anchor when Direct Selection picked some. Alt-clicking a widget cycles their corner
|
||||
//! kind (round, inverted round, chamfer); double-clicking one opens the Corners dialog. The
|
||||
//! Selection and Direct Selection tools share this, and the canvas draws the widgets from the same
|
||||
//! geometry.
|
||||
@@ -38,10 +38,10 @@ struct Widget {
|
||||
at: Point,
|
||||
}
|
||||
|
||||
/// The corner widgets of a selection that is exactly one editable path with corners.
|
||||
/// The corner widgets of one selected path.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct CornerWidgets {
|
||||
pub id: NodeId,
|
||||
struct PathWidgets {
|
||||
id: NodeId,
|
||||
/// Maps the corners' space into the document (a live rectangle's own; else none).
|
||||
xf: Affine,
|
||||
/// The widgets that show (and which a drag edits), in anchor order.
|
||||
@@ -50,11 +50,10 @@ pub struct CornerWidgets {
|
||||
all: bool,
|
||||
}
|
||||
|
||||
impl CornerWidgets {
|
||||
/// The widgets at `zoom` (screen px per document point), if the selection has them: on any
|
||||
/// path with Direct Selection (`any_path`), on live rectangles and polygons with Selection.
|
||||
pub fn of(doc: &Document, selection: &Selection, zoom: f64, any_path: bool) -> Option<Self> {
|
||||
let [id] = selection.objects[..] else { return None };
|
||||
impl PathWidgets {
|
||||
/// The widgets of path `id` at `zoom` (screen px per document point), if it has any: any path
|
||||
/// with Direct Selection (`any_path`), live rectangles and polygons with Selection.
|
||||
fn of(doc: &Document, selection: &Selection, id: NodeId, zoom: f64, any_path: bool) -> Option<Self> {
|
||||
if !doc.is_editable(id) {
|
||||
return None;
|
||||
}
|
||||
@@ -86,13 +85,36 @@ impl CornerWidgets {
|
||||
(!widgets.is_empty()).then_some(Self { id, xf: lc.xf, widgets, all })
|
||||
}
|
||||
|
||||
/// The corners whose widgets show: anchor indices of the path's uncut outline.
|
||||
fn corners(&self) -> Vec<usize> {
|
||||
self.widgets.iter().map(|w| w.corner.index).collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// The corner widgets of the selected paths that have some.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct CornerWidgets {
|
||||
paths: Vec<PathWidgets>,
|
||||
}
|
||||
|
||||
impl CornerWidgets {
|
||||
/// The widgets at `zoom` (screen px per document point), if the selection has them: on any
|
||||
/// path with Direct Selection (`any_path`), on live rectangles and polygons with Selection.
|
||||
pub fn of(doc: &Document, selection: &Selection, zoom: f64, any_path: bool) -> Option<Self> {
|
||||
let paths: Vec<_> = selection.objects.iter().filter_map(|id| PathWidgets::of(doc, selection, *id, zoom, any_path)).collect();
|
||||
(!paths.is_empty()).then_some(Self { paths })
|
||||
}
|
||||
|
||||
/// Selection & Anchor Display → Hide Corner Widget for angles greater than: the widgets of
|
||||
/// corners wider than `max` degrees (in the document) hide; none if all do.
|
||||
pub fn within_angle(mut self, max: f64) -> Option<Self> {
|
||||
let n = self.widgets.len();
|
||||
self.widgets.retain(|w| w.angle <= max + 1e-9);
|
||||
self.all &= self.widgets.len() == n;
|
||||
(!self.widgets.is_empty()).then_some(self)
|
||||
for p in &mut self.paths {
|
||||
let n = p.widgets.len();
|
||||
p.widgets.retain(|w| w.angle <= max + 1e-9);
|
||||
p.all &= p.widgets.len() == n;
|
||||
}
|
||||
self.paths.retain(|p| !p.widgets.is_empty());
|
||||
(!self.paths.is_empty()).then_some(self)
|
||||
}
|
||||
|
||||
/// The widgets on show: [`Self::of`] with View → Show Corner Widget `on`, less those wider
|
||||
@@ -111,30 +133,61 @@ impl CornerWidgets {
|
||||
|
||||
/// The centres of the widgets that show.
|
||||
pub fn visible(&self) -> impl Iterator<Item = Point> + '_ {
|
||||
self.widgets.iter().map(|w| w.at)
|
||||
self.visible_on().map(|(_, at)| at)
|
||||
}
|
||||
|
||||
/// The corners whose widgets show: anchor indices of the path's uncut outline.
|
||||
/// The centres of the widgets that show, each with the object it belongs to.
|
||||
pub fn visible_on(&self) -> impl Iterator<Item = (NodeId, Point)> + '_ {
|
||||
self.paths.iter().flat_map(|p| p.widgets.iter().map(move |w| (p.id, w.at)))
|
||||
}
|
||||
|
||||
/// The corners whose widgets show, path after path: anchor indices of each path's uncut
|
||||
/// outline.
|
||||
pub fn corners(&self) -> Vec<usize> {
|
||||
self.widgets.iter().map(|w| w.corner.index).collect()
|
||||
self.paths.iter().flat_map(PathWidgets::corners).collect()
|
||||
}
|
||||
|
||||
/// The widget nearest to `p` within `tol` (document units).
|
||||
fn hit(&self, p: Point, tol: f64) -> Option<usize> {
|
||||
let d = |k: &usize| self.widgets.get(*k).map_or(f64::INFINITY, |w| w.at.distance(p));
|
||||
(0..self.widgets.len()).filter(|k| d(k) <= tol).min_by(|a, b| d(a).total_cmp(&d(b)))
|
||||
/// The widget nearest to `p` within `tol` (document units): its path's and its own index.
|
||||
fn hit(&self, p: Point, tol: f64) -> Option<(usize, usize)> {
|
||||
let d = |&(i, k): &(usize, usize)| self.widget(i, k).map_or(f64::INFINITY, |w| w.at.distance(p));
|
||||
self.paths
|
||||
.iter()
|
||||
.enumerate()
|
||||
.flat_map(|(i, path)| (0..path.widgets.len()).map(move |k| (i, k)))
|
||||
.filter(|ik| d(ik) <= tol)
|
||||
.min_by(|a, b| d(a).total_cmp(&d(b)))
|
||||
}
|
||||
|
||||
/// `object.setLiveShape` params setting `key` on the shown corners (every corner unless some
|
||||
/// are hidden, which `corners` then leaves out).
|
||||
fn widget(&self, path: usize, k: usize) -> Option<&Widget> {
|
||||
self.paths.get(path).and_then(|p| p.widgets.get(k))
|
||||
}
|
||||
|
||||
/// `object.setLiveShape` params setting `key` on the shown corners (every corner of a path
|
||||
/// unless some are hidden, which `corners` then leaves out): one path by its `id`, several as
|
||||
/// `items`.
|
||||
fn command(&self, key: &str, value: Value) -> Value {
|
||||
let mut p = Map::new();
|
||||
p.insert("id".into(), json!(self.id.0));
|
||||
p.insert(key.into(), value);
|
||||
if !self.all {
|
||||
p.insert("corners".into(), json!(self.corners()));
|
||||
let corners = |p: &PathWidgets| (!p.all).then(|| p.corners());
|
||||
let mut out = Map::new();
|
||||
match self.paths.as_slice() {
|
||||
[p] => {
|
||||
out.insert("id".into(), json!(p.id.0));
|
||||
if let Some(c) = corners(p) {
|
||||
out.insert("corners".into(), json!(c));
|
||||
}
|
||||
}
|
||||
paths => {
|
||||
let items: Vec<Value> = paths
|
||||
.iter()
|
||||
.map(|p| match corners(p) {
|
||||
Some(c) => json!({ "id": p.id.0, "corners": c }),
|
||||
None => json!({ "id": p.id.0 }),
|
||||
})
|
||||
.collect();
|
||||
out.insert("items".into(), Value::Array(items));
|
||||
}
|
||||
}
|
||||
Value::Object(p)
|
||||
out.insert(key.into(), value);
|
||||
Value::Object(out)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -151,11 +204,22 @@ pub fn over_widget(cx: &ToolContext, p: Point, any_path: bool) -> bool {
|
||||
CornerWidgets::for_tool(cx, any_path).and_then(|w| w.hit(p, cx.tol(5.0))).is_some()
|
||||
}
|
||||
|
||||
/// A double-click on a corner widget opens the Corners dialog for the shown corners.
|
||||
/// A double-click on a corner widget opens the Corners dialog for the shown corners of its path.
|
||||
pub fn double_click(cx: &ToolContext, p: Point, any_path: bool) -> Option<Action> {
|
||||
let w = CornerWidgets::for_tool(cx, any_path)?;
|
||||
w.hit(p, cx.tol(5.0))?;
|
||||
Some(Action::Dialog(DIALOG.into(), json!({ "id": w.id.0, "corners": w.corners() })))
|
||||
let (i, _) = w.hit(p, cx.tol(5.0))?;
|
||||
let path = w.paths.get(i)?;
|
||||
Some(Action::Dialog(DIALOG.into(), json!({ "id": path.id.0, "corners": path.corners() })))
|
||||
}
|
||||
|
||||
/// A path's uncut outline with its corners' radii and kinds, and the corners' space (to outline
|
||||
/// the corners at their largest).
|
||||
#[derive(Clone, Debug)]
|
||||
struct Outline {
|
||||
base: PathData,
|
||||
radii: Vec<f64>,
|
||||
kinds: Vec<CornerKind>,
|
||||
xf: Affine,
|
||||
}
|
||||
|
||||
/// Dragging a corner widget: the radius follows the pointer along the corner's bisector. An
|
||||
@@ -163,13 +227,10 @@ pub fn double_click(cx: &ToolContext, p: Point, any_path: bool) -> Option<Action
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct CornerDrag {
|
||||
widgets: CornerWidgets,
|
||||
/// The dragged widget (index into the shown ones).
|
||||
widget: usize,
|
||||
/// The path's uncut outline with its corners' radii and kinds (to outline the corners at
|
||||
/// their largest).
|
||||
base: PathData,
|
||||
radii: Vec<f64>,
|
||||
kinds: Vec<CornerKind>,
|
||||
/// The dragged widget: its path's and its own index among the shown ones.
|
||||
widget: (usize, usize),
|
||||
/// Each shown path's outline, in the order of [`CornerWidgets`]' paths.
|
||||
outlines: Vec<Outline>,
|
||||
start: Point,
|
||||
began: bool,
|
||||
alt: bool,
|
||||
@@ -185,20 +246,29 @@ impl CornerDrag {
|
||||
pub fn hit(cx: &ToolContext, ev: &PointerEvent, any_path: bool) -> Option<Self> {
|
||||
let (widgets, p) = (CornerWidgets::for_tool(cx, any_path)?, ev.pos);
|
||||
let widget = widgets.hit(p, cx.tol(5.0))?;
|
||||
let radius = widgets.widgets.get(widget)?.radius;
|
||||
let lc = cx.doc.node(widgets.id).and_then(LiveCorners::of)?;
|
||||
let n = lc.base.anchor_count();
|
||||
let (radii, kinds) = ((0..n).map(|k| lc.radius(k)).collect(), (0..n).map(|k| lc.kind(k)).collect());
|
||||
let base = lc.base.into_owned();
|
||||
Some(Self { widgets, widget, base, radii, kinds, start: p, began: false, alt: ev.mods.alt, radius, at_limit: false, at: p })
|
||||
let radius = widgets.widget(widget.0, widget.1)?.radius;
|
||||
let outlines = widgets
|
||||
.paths
|
||||
.iter()
|
||||
.map(|w| {
|
||||
let lc = cx.doc.node(w.id).and_then(LiveCorners::of)?;
|
||||
let n = lc.base.anchor_count();
|
||||
let (radii, kinds) = ((0..n).map(|k| lc.radius(k)).collect(), (0..n).map(|k| lc.kind(k)).collect());
|
||||
Some(Outline { base: lc.base.into_owned(), radii, kinds, xf: w.xf })
|
||||
})
|
||||
.collect::<Option<Vec<_>>>()?;
|
||||
Some(Self { widgets, widget, outlines, start: p, began: false, alt: ev.mods.alt, radius, at_limit: false, at: p })
|
||||
}
|
||||
|
||||
/// The start radius (as drawn: no larger than fits) plus the pointer's travel along the
|
||||
/// corner's bisector (in the corners' own units), from square to fully round; and whether the
|
||||
/// travel reached fully round.
|
||||
fn radius_at(&self, p: Point) -> (f64, bool) {
|
||||
let Some(w) = self.widgets.widgets.get(self.widget) else { return (self.radius, self.at_limit) };
|
||||
let inv = self.widgets.xf.inverse();
|
||||
let (path, k) = self.widget;
|
||||
let (Some(w), Some(xf)) = (self.widgets.widget(path, k), self.widgets.paths.get(path).map(|p| p.xf)) else {
|
||||
return (self.radius, self.at_limit);
|
||||
};
|
||||
let inv = xf.inverse();
|
||||
let max = w.corner.max_radius();
|
||||
let r = w.corner.fitted(w.radius) + w.corner.radius_change(inv * p - inv * self.start);
|
||||
(r.min(max).max(0.0), max > 0.0 && r >= max)
|
||||
@@ -206,25 +276,27 @@ impl CornerDrag {
|
||||
|
||||
/// The cuts of the edited corners that are at their largest radius, in document coordinates.
|
||||
fn corners_at_limit(&self) -> BezPath {
|
||||
let shown = &self.widgets.widgets;
|
||||
let mut radii = self.radii.clone();
|
||||
for w in shown {
|
||||
if let Some(r) = radii.get_mut(w.corner.index) {
|
||||
*r = self.radius;
|
||||
}
|
||||
}
|
||||
let full = |k: &usize| shown.iter().any(|w| w.corner.index == *k && self.radius >= w.corner.max_radius() - 1e-9);
|
||||
let (path, sources) = cut_corners(&self.base, &radii, &self.kinds);
|
||||
let mut out = BezPath::new();
|
||||
for (sp, from) in path.transformed(self.widgets.xf).subpaths.iter().zip(&sources) {
|
||||
// A corner's cut is the segment between its two anchors (the last one, for a closed
|
||||
// subpath's first corner).
|
||||
for i in 0..sp.segment_count() {
|
||||
let (a, b) = (from.get(i), from.get(i + 1).or(from.first()));
|
||||
if a == b && a.is_some_and(full) {
|
||||
let c = sp.segment(i);
|
||||
out.move_to(c.p0);
|
||||
out.curve_to(c.p1, c.p2, c.p3);
|
||||
for (shown, o) in self.widgets.paths.iter().zip(&self.outlines) {
|
||||
let shown = &shown.widgets;
|
||||
let mut radii = o.radii.clone();
|
||||
for w in shown {
|
||||
if let Some(r) = radii.get_mut(w.corner.index) {
|
||||
*r = self.radius;
|
||||
}
|
||||
}
|
||||
let full = |k: &usize| shown.iter().any(|w| w.corner.index == *k && self.radius >= w.corner.max_radius() - 1e-9);
|
||||
let (path, sources) = cut_corners(&o.base, &radii, &o.kinds);
|
||||
for (sp, from) in path.transformed(o.xf).subpaths.iter().zip(&sources) {
|
||||
// A corner's cut is the segment between its two anchors (the last one, for a
|
||||
// closed subpath's first corner).
|
||||
for i in 0..sp.segment_count() {
|
||||
let (a, b) = (from.get(i), from.get(i + 1).or(from.first()));
|
||||
if a == b && a.is_some_and(full) {
|
||||
let c = sp.segment(i);
|
||||
out.move_to(c.p0);
|
||||
out.curve_to(c.p1, c.p2, c.p3);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -249,7 +321,7 @@ impl CornerDrag {
|
||||
pub fn finish(self) -> Vec<Action> {
|
||||
if self.began {
|
||||
vec![Action::Commit]
|
||||
} else if let Some(w) = self.widgets.widgets.get(self.widget).filter(|_| self.alt) {
|
||||
} else if let Some(w) = self.widgets.widget(self.widget.0, self.widget.1).filter(|_| self.alt) {
|
||||
vec![Action::Exec("object.setLiveShape".into(), self.widgets.command("kind", json!(w.kind.next())))]
|
||||
} else {
|
||||
vec![]
|
||||
@@ -359,6 +431,37 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// #938: with two rectangles selected, both show their widgets, and a drag on either rounds
|
||||
/// the corners of both in one step; with Direct Selection, each its shown corners.
|
||||
#[test]
|
||||
fn widgets_of_several_selected_paths_drag_together() {
|
||||
let (mut d, a) = live_rect(0.0, Affine::translate((100.0, 100.0)));
|
||||
let live = LiveShape::Rectangle { w: 100.0, h: 100.0, radii: [0.0; 4], kinds: Default::default(), xf: Affine::translate((300.0, 100.0)) };
|
||||
let b = d.alloc_id();
|
||||
let mut n = Node::path(b, live.to_path(), Appearance::default_art());
|
||||
if let NodeKind::Path { live: slot, .. } = &mut n.kind {
|
||||
*slot = Some(live);
|
||||
}
|
||||
let l = d.layers[0].id;
|
||||
d.insert(Some(l), 1, n).unwrap();
|
||||
let mut s = selected(a);
|
||||
s.add(b);
|
||||
assert_eq!(pts(&CornerWidgets::of(&d, &s, 1.0, false).unwrap()).len(), 8);
|
||||
let p = paint();
|
||||
let cx = cx(&d, &s, &p);
|
||||
let mut t = crate::create("selection");
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 390.0, 191.0));
|
||||
let preview = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 375.0, 176.0));
|
||||
assert!((radius(&preview[1]) - 15.0).abs() < 1e-9);
|
||||
let Action::Preview(_, v) = &preview[1] else { panic!() };
|
||||
assert_eq!(v["items"], json!([{"id": a.0}, {"id": b.0}]));
|
||||
// Direct Selection with one anchor of the first: its corner, and the whole second.
|
||||
s.anchors.insert(a, [(0, 2)].into());
|
||||
let w = CornerWidgets::of(&d, &s, 1.0, true).unwrap();
|
||||
assert_eq!(w.corners(), [2, 0, 1, 2, 3]);
|
||||
assert_eq!(w.command("radius", json!(5.0)), json!({"items": [{"id": a.0, "corners": [2]}, {"id": b.0}], "radius": 5.0}));
|
||||
}
|
||||
|
||||
/// #442: on a 200 × 80 rectangle the widgets sit at the centres of the corners as drawn, also
|
||||
/// with a radius past half the shorter side; a drag past fully round stops every corner there
|
||||
/// and outlines them in red.
|
||||
|
||||
@@ -574,6 +574,14 @@ impl Tool for DirectSelectionTool {
|
||||
}
|
||||
}
|
||||
});
|
||||
// Objects without anchors to pick (type, images, symbols…) are selected whole when
|
||||
// the marquee touches them, as with the Selection tool (#927).
|
||||
for id in vectorcraft_doc::hit::marquee(cx.doc, r, cx.isolation, true) {
|
||||
let whole = cx.doc.node(id).is_some_and(|n| !matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }));
|
||||
if whole && !sel.iter().any(|(s, _)| *s == id) {
|
||||
sel.push((id, vec![]));
|
||||
}
|
||||
}
|
||||
sel.retain(|(id, _)| cx.doc.is_editable(*id));
|
||||
let items: Vec<Value> = sel.iter().map(|(id, v)| json!({"id": id.0, "anchors": anchors_json(v)})).collect();
|
||||
vec![Action::Exec("select.anchorsMany".into(), json!({"items": items, "mode": if toggle { "toggle" } else { "set" }}))]
|
||||
@@ -838,6 +846,28 @@ mod tests {
|
||||
let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 250.0, 150.0));
|
||||
assert_eq!(a, vec![Action::Exec("select.anchorsMany".into(), json!({"items": [{"id": id.0, "anchors": [[0, 1]]}], "mode": "set"}))]);
|
||||
}
|
||||
/// #927: a marquee across type selects the type object whole, beside the anchors it holds.
|
||||
#[test]
|
||||
fn marquee_selects_type_it_touches() {
|
||||
// The rectangle at (100, 100)–(200, 200) and area type at (300, 300).
|
||||
let (d, text) = doc_with_area_type();
|
||||
let rect = d.layers[0].children().and_then(|c| c.first()).map(|n| n.id).unwrap();
|
||||
let s = Selection::default();
|
||||
let p = paint();
|
||||
let cx = cx(&d, &s, &p);
|
||||
let mut t = DirectSelectionTool::new(false);
|
||||
// From empty canvas across the type to inside the rectangle (its bottom-right corner).
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 450.0, 450.0));
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 150.0, 150.0));
|
||||
let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 150.0, 150.0));
|
||||
let items = json!([{"id": rect.0, "anchors": [[0, 2]]}, {"id": text.0, "anchors": []}]);
|
||||
assert_eq!(a, vec![Action::Exec("select.anchorsMany".into(), json!({"items": items, "mode": "set"}))]);
|
||||
// Away from the type, only anchors.
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 150.0, 50.0));
|
||||
let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 250.0, 150.0));
|
||||
assert_eq!(a, vec![Action::Exec("select.anchorsMany".into(), json!({"items": [{"id": rect.0, "anchors": [[0, 1]]}], "mode": "set"}))]);
|
||||
}
|
||||
|
||||
/// Shift-drag a marquee: the anchors inside toggle (#483), with Group Selection too.
|
||||
#[test]
|
||||
fn shift_marquee_toggles_anchors() {
|
||||
|
||||
@@ -1701,8 +1701,8 @@ fn selection_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: &Xf) {
|
||||
app.session.prefs.hide_corner_widget_above,
|
||||
)
|
||||
{
|
||||
let color = c32(st.doc.layer_color(w.id));
|
||||
for sp in w.visible().map(|q| xf.to_screen(q)) {
|
||||
for (id, q) in w.visible_on() {
|
||||
let (sp, color) = (xf.to_screen(q), c32(st.doc.layer_color(id)));
|
||||
p.circle_filled(sp, 3.0, Color32::WHITE);
|
||||
p.circle_stroke(sp, 3.0, Stroke::new(1.0, color));
|
||||
p.circle_filled(sp, 1.0, color);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! The generic parameter dialog (`ui.paramDialog`): edits a command's parameters (`__command`,
|
||||
//! headed `__label`) and runs it on OK.
|
||||
//! headed `__label`) and runs it on OK, with the fixed ones in `__params` (not shown) added.
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
@@ -60,7 +60,10 @@ const VERTICAL_ALIGN: form::Choices = &[("Top", "top"), ("Center", "center"), ("
|
||||
/// Closes before running, so a dialog the command opens stays open.
|
||||
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
|
||||
let cmd = d.str("__command");
|
||||
let params = form::params(d);
|
||||
let mut params = form::params(d);
|
||||
if let (Some(o), Some(Value::Object(fixed))) = (params.as_object_mut(), d.fields.get("__params")) {
|
||||
o.extend(fixed.clone());
|
||||
}
|
||||
app.ui.dialog = None;
|
||||
// A tool's click-to-size shape (Flare) goes on the active perspective plane while the grid shows.
|
||||
let at = |x: &str, y: &str| Some(vectorcraft_geom::Point::new(params.get(x)?.as_f64()?, params.get(y)?.as_f64()?));
|
||||
|
||||
@@ -160,6 +160,8 @@ fn choices(effect: &str, key: &str) -> Option<form::Choices> {
|
||||
("blur.radial", "quality") => Some(&[("Draft", "draft"), ("Good", "good"), ("Best", "best")]),
|
||||
("blur.smart", "quality") => Some(&[("Low", "low"), ("Medium", "medium"), ("High", "high")]),
|
||||
("pixelate.mezzotint", "type") => Some(&vectorcraft_effects::pixel::MEZZOTINT_TYPES),
|
||||
("video.deinterlace", "eliminate") => Some(&[("Odd Fields", "odd"), ("Even Fields", "even")]),
|
||||
("video.deinterlace", "create") => Some(&[("Duplication", "duplication"), ("Interpolation", "interpolation")]),
|
||||
("path.offsetPath", "joins") => Some(&[("Miter", "miter"), ("Round", "round"), ("Bevel", "bevel")]),
|
||||
("distort.roughen" | "distort.zigZag", "points") => Some(&[("Smooth", "smooth"), ("Corner", "corner")]),
|
||||
_ => None,
|
||||
|
||||
@@ -357,6 +357,7 @@ pub(super) fn humanize(k: &str) -> String {
|
||||
"Channel4" => "Channel 4:".into(),
|
||||
"Include Cmy Blacks" => "Include Blacks with CMY:".into(),
|
||||
"Align To Path" => "Align to Path:".into(),
|
||||
"Create" => "Create New Fields by:".into(),
|
||||
_ => format!("{s}:"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
//! (`links.relink`), and with Apply to All the other missing files are looked for by name in its
|
||||
//! folder; Ignore keeps the images showing their saved preview, and with Apply to All ignores the
|
||||
//! rest. Afterwards, with Preferences › Update Links: Ask When Modified, the modified links are
|
||||
//! offered for update (`links.update`).
|
||||
//! offered for update (`links.update`). Files changed while the app was in the background are
|
||||
//! checked when its window comes back to the front ([`after_focus`]).
|
||||
//!
|
||||
//! Fields: `missing` (`[{name, path, ids}]`, the one asked about first), `modified` (the ids of
|
||||
//! images whose file was modified), `applyToAll`, `path` (the replacement file; picked when empty)
|
||||
@@ -74,6 +75,39 @@ fn ask_update(app: &mut VectorcraftApp, ids: Vec<Value>) {
|
||||
super::confirm::ask(app, tl!("Update Modified Links"), &detail, "links.update", json!({ "ids": ids }));
|
||||
}
|
||||
|
||||
/// A linked file as last seen: its path, and its size and modification time when it exists.
|
||||
pub(crate) type FileStamp = (String, Option<(u64, Option<std::time::SystemTime>)>);
|
||||
|
||||
/// The window came back to the front (#925): linked files of the active document changed
|
||||
/// meanwhile are read again with Update Links: Automatically, offered for update with Ask When
|
||||
/// Modified (once per change of a file), and left to the Links panel with Manually. Nothing is
|
||||
/// asked while a dialog is open.
|
||||
pub fn after_focus(app: &mut VectorcraftApp) {
|
||||
if cfg!(target_arch = "wasm32") || app.session.prefs.update_links == "manually" || app.ui.dialog.is_some() || app.session.active().is_none() {
|
||||
return;
|
||||
}
|
||||
let Ok(r) = app.session.execute("links.check", &json!({})) else { return };
|
||||
let rows: Vec<Value> = r["links"].as_array().into_iter().flatten().filter(|l| l["status"] == "modified").cloned().collect();
|
||||
if rows.is_empty() {
|
||||
return;
|
||||
}
|
||||
if app.session.prefs.update_links == "automatically" {
|
||||
// A failure shows in the status bar, as the Links panel's Update Link does.
|
||||
let _ = app.run("links.update", json!({ "ids": ids(&rows) }));
|
||||
return;
|
||||
}
|
||||
// The file each link reads (one found elsewhere after a move), its size and when it was last
|
||||
// changed (two changes can share a time on file systems that keep it coarsely).
|
||||
let stamp = |l: &Value| -> FileStamp {
|
||||
let path = l["found"].as_str().or(l["path"].as_str()).unwrap_or_default().to_string();
|
||||
let meta = std::fs::metadata(&path).ok();
|
||||
let at = meta.as_ref().map(|m| (m.len(), m.modified().ok()));
|
||||
(path, at)
|
||||
};
|
||||
let new: Vec<Value> = rows.into_iter().filter(|l| app.links_asked.insert(stamp(l))).collect();
|
||||
ask_update(app, ids(&new));
|
||||
}
|
||||
|
||||
fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let missing = d.fields.get("missing").and_then(Value::as_array).map_or(&[][..], Vec::as_slice);
|
||||
@@ -262,4 +296,58 @@ mod tests {
|
||||
assert!(app.ui.dialog.is_none());
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// #925: a linked file changed while the app was in the background follows Update Links when
|
||||
/// the window comes back to the front.
|
||||
#[test]
|
||||
fn a_link_changed_in_the_background_follows_update_links_on_focus() {
|
||||
let dir = std::env::temp_dir().join(format!("vectorcraft-focus-links-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.services.read = Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string())));
|
||||
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
|
||||
let pic = dir.join("a.png");
|
||||
// Each version a different size, so no two share a length and modification time.
|
||||
let mut version = 0;
|
||||
let mut change = || {
|
||||
version += 1;
|
||||
let mut out = vec![];
|
||||
image::RgbaImage::from_pixel(100 + version, 50, image::Rgba([40 * version as u8, 0, 0, 255]))
|
||||
.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png)
|
||||
.unwrap();
|
||||
std::fs::write(&pic, out).unwrap();
|
||||
};
|
||||
change();
|
||||
app.run("file.place", json!({"path": pic.to_string_lossy()})).unwrap();
|
||||
let modified = |app: &mut VectorcraftApp| app.run("links.check", json!({})).unwrap()["modified"].as_u64().unwrap();
|
||||
// The window coming to the front asks for the check.
|
||||
let mut raw = egui::RawInput { events: vec![egui::Event::WindowFocused(true)], ..Default::default() };
|
||||
app.raw_input_hook(&mut raw);
|
||||
assert!(app.links_check);
|
||||
// Ask When Modified (the default): asked once per change.
|
||||
change();
|
||||
after_focus(&mut app);
|
||||
let d = app.ui.dialog.take().expect("asks");
|
||||
assert_eq!(d.str("__command"), "links.update");
|
||||
after_focus(&mut app);
|
||||
assert!(app.ui.dialog.is_none(), "not twice for the same change");
|
||||
change();
|
||||
after_focus(&mut app);
|
||||
assert!(app.ui.dialog.is_some(), "a new change asks again");
|
||||
super::super::confirm(&mut app).unwrap();
|
||||
assert_eq!(modified(&mut app), 0);
|
||||
// Automatically: read again without asking.
|
||||
app.run("prefs.set", json!({"key": "updateLinks", "value": "automatically"})).unwrap();
|
||||
change();
|
||||
after_focus(&mut app);
|
||||
assert!(app.ui.dialog.is_none());
|
||||
assert_eq!(modified(&mut app), 0);
|
||||
// Manually: left to the Links panel.
|
||||
app.run("prefs.set", json!({"key": "updateLinks", "value": "manually"})).unwrap();
|
||||
change();
|
||||
after_focus(&mut app);
|
||||
assert!(app.ui.dialog.is_none());
|
||||
assert_eq!(modified(&mut app), 1);
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
}
|
||||
@@ -657,3 +657,6 @@
|
||||
Crystallize… Krystalizace…
|
||||
Mezzotint… Mezzotinta…
|
||||
Pointillize… Pointilismus…
|
||||
Video Video
|
||||
De-Interlace… Odstranit prokládání…
|
||||
NTSC Colors Barvy NTSC
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -2760,6 +2760,23 @@
|
||||
Add to Library Añadir a la biblioteca
|
||||
Delete Library Eliminar biblioteca
|
||||
Delete Library Item Eliminar elemento de la biblioteca
|
||||
No results Sin resultados
|
||||
No items in this library match “{query}”. Ningún elemento de esta biblioteca coincide con “{query}”.
|
||||
Right-click an item to move it into this group. Haz clic con el botón derecho en un elemento para moverlo a este grupo.
|
||||
New Group Nuevo grupo
|
||||
New Group… Nuevo grupo…
|
||||
Move to Group Mover al grupo
|
||||
No Group Sin grupo
|
||||
Rename Group… Cambiar nombre del grupo…
|
||||
Delete Group Eliminar grupo
|
||||
Import Library… Importar biblioteca…
|
||||
Export Library… Exportar biblioteca…
|
||||
Import Library Importar biblioteca
|
||||
Export Library Exportar biblioteca
|
||||
New Library Group Nuevo grupo de biblioteca
|
||||
Rename Library Group Cambiar nombre del grupo de biblioteca
|
||||
Delete Library Group Eliminar grupo de biblioteca
|
||||
Move Library Item to Group Mover elemento de la biblioteca al grupo
|
||||
Library Biblioteca
|
||||
Rename Library Cambiar nombre de la biblioteca
|
||||
Show Library Mostrar biblioteca
|
||||
@@ -3861,3 +3878,24 @@ 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}
|
||||
Video Video
|
||||
De-Interlace… Desentrelazar…
|
||||
De-Interlace Desentrelazar
|
||||
NTSC Colors Colores NTSC
|
||||
Eliminate Eliminar
|
||||
Create New Fields by Crear campos nuevos por
|
||||
Odd Fields Campos impares
|
||||
Even Fields Campos pares
|
||||
Duplication Duplicación
|
||||
Interpolation Interpolación
|
||||
@msg Imported library {name} Biblioteca {name} importada
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -2757,6 +2757,23 @@
|
||||
Add to Library Ajouter à la bibliothèque
|
||||
Delete Library Supprimer la bibliothèque
|
||||
Delete Library Item Supprimer l’élément de la bibliothèque
|
||||
No results Aucun résultat
|
||||
No items in this library match “{query}”. Aucun élément de cette bibliothèque ne correspond à « {query} ».
|
||||
Right-click an item to move it into this group. Cliquez avec le bouton droit sur un élément pour le placer dans ce groupe.
|
||||
New Group Nouveau groupe
|
||||
New Group… Nouveau groupe…
|
||||
Move to Group Déplacer vers le groupe
|
||||
No Group Aucun groupe
|
||||
Rename Group… Renommer le groupe…
|
||||
Delete Group Supprimer le groupe
|
||||
Import Library… Importer une bibliothèque…
|
||||
Export Library… Exporter la bibliothèque…
|
||||
Import Library Importer une bibliothèque
|
||||
Export Library Exporter la bibliothèque
|
||||
New Library Group Nouveau groupe de bibliothèque
|
||||
Rename Library Group Renommer le groupe de bibliothèque
|
||||
Delete Library Group Supprimer le groupe de bibliothèque
|
||||
Move Library Item to Group Déplacer l’élément de la bibliothèque vers un groupe
|
||||
Library Bibliothèque
|
||||
Rename Library Renommer la bibliothèque
|
||||
Show Library Afficher la bibliothèque
|
||||
@@ -3872,3 +3889,24 @@ 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}
|
||||
Video Vidéo
|
||||
De-Interlace… Désentrelacement…
|
||||
De-Interlace Désentrelacement
|
||||
NTSC Colors Couleurs NTSC
|
||||
Eliminate Supprimer
|
||||
Create New Fields by Créer des trames par
|
||||
Odd Fields Trames impaires
|
||||
Even Fields Trames paires
|
||||
Duplication Duplication
|
||||
Interpolation Interpolation
|
||||
@msg Imported library {name} Bibliothèque {name} importée
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -2760,6 +2760,23 @@
|
||||
Add to Library Aggiungi alla libreria
|
||||
Delete Library Elimina libreria
|
||||
Delete Library Item Elimina elemento della libreria
|
||||
No results Nessun risultato
|
||||
No items in this library match “{query}”. Nessun elemento di questa libreria corrisponde a “{query}”.
|
||||
Right-click an item to move it into this group. Fai clic con il pulsante destro su un elemento per spostarlo in questo gruppo.
|
||||
New Group Nuovo gruppo
|
||||
New Group… Nuovo gruppo…
|
||||
Move to Group Sposta nel gruppo
|
||||
No Group Nessun gruppo
|
||||
Rename Group… Rinomina gruppo…
|
||||
Delete Group Elimina gruppo
|
||||
Import Library… Importa libreria…
|
||||
Export Library… Esporta libreria…
|
||||
Import Library Importa libreria
|
||||
Export Library Esporta libreria
|
||||
New Library Group Nuovo gruppo di libreria
|
||||
Rename Library Group Rinomina gruppo di libreria
|
||||
Delete Library Group Elimina gruppo di libreria
|
||||
Move Library Item to Group Sposta elemento della libreria nel gruppo
|
||||
Library Libreria
|
||||
Rename Library Rinomina libreria
|
||||
Show Library Mostra libreria
|
||||
@@ -3861,3 +3878,24 @@ 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}
|
||||
Video Video
|
||||
De-Interlace… Deinterlaccia…
|
||||
De-Interlace Deinterlaccia
|
||||
NTSC Colors Colori NTSC
|
||||
Eliminate Elimina
|
||||
Create New Fields by Crea nuovi campi per
|
||||
Odd Fields Campi dispari
|
||||
Even Fields Campi pari
|
||||
Duplication Duplicazione
|
||||
Interpolation Interpolazione
|
||||
@msg Imported library {name} Libreria {name} importata
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -2496,6 +2496,23 @@
|
||||
Add to Library ライブラリに追加
|
||||
Delete Library ライブラリを削除
|
||||
Delete Library Item ライブラリ項目を削除
|
||||
No results 結果はありません
|
||||
No items in this library match “{query}”. このライブラリには「{query}」に一致する項目がありません。
|
||||
Right-click an item to move it into this group. 項目を右クリックすると、このグループに移動できます。
|
||||
New Group 新規グループ
|
||||
New Group… 新規グループ…
|
||||
Move to Group グループに移動
|
||||
No Group グループなし
|
||||
Rename Group… グループ名を変更…
|
||||
Delete Group グループを削除
|
||||
Import Library… ライブラリを読み込み…
|
||||
Export Library… ライブラリを書き出し…
|
||||
Import Library ライブラリを読み込み
|
||||
Export Library ライブラリを書き出し
|
||||
New Library Group 新規ライブラリグループ
|
||||
Rename Library Group ライブラリグループ名を変更
|
||||
Delete Library Group ライブラリグループを削除
|
||||
Move Library Item to Group ライブラリ項目をグループに移動
|
||||
Library ライブラリ
|
||||
Rename Library ライブラリ名を変更
|
||||
Show Library ライブラリを表示
|
||||
@@ -3853,3 +3870,24 @@ 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}
|
||||
Video ビデオ
|
||||
De-Interlace… インターレース解除…
|
||||
De-Interlace インターレース解除
|
||||
NTSC Colors NTSC カラー
|
||||
Eliminate 削除
|
||||
Create New Fields by 新規フィールドの作成
|
||||
Odd Fields 奇数フィールド
|
||||
Even Fields 偶数フィールド
|
||||
Duplication 複製
|
||||
Interpolation 補間
|
||||
@msg Imported library {name} ライブラリ {name} を読み込みました
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -2718,3 +2718,6 @@
|
||||
Crystallize… Cristalizar…
|
||||
Mezzotint… Meia-Tinta…
|
||||
Pointillize… Pontilhar…
|
||||
Video Vídeo
|
||||
De-Interlace… Desentrelaçar…
|
||||
NTSC Colors Cores NTSC
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -2756,6 +2756,23 @@
|
||||
Add to Library Добавить в библиотеку
|
||||
Delete Library Удалить библиотеку
|
||||
Delete Library Item Удалить элемент библиотеки
|
||||
No results Ничего не найдено
|
||||
No items in this library match “{query}”. В этой библиотеке нет элементов, соответствующих «{query}».
|
||||
Right-click an item to move it into this group. Щёлкните элемент правой кнопкой мыши, чтобы переместить его в эту группу.
|
||||
New Group Новая группа
|
||||
New Group… Новая группа…
|
||||
Move to Group Переместить в группу
|
||||
No Group Без группы
|
||||
Rename Group… Переименовать группу…
|
||||
Delete Group Удалить группу
|
||||
Import Library… Импортировать библиотеку…
|
||||
Export Library… Экспортировать библиотеку…
|
||||
Import Library Импортировать библиотеку
|
||||
Export Library Экспортировать библиотеку
|
||||
New Library Group Новая группа библиотеки
|
||||
Rename Library Group Переименовать группу библиотеки
|
||||
Delete Library Group Удалить группу библиотеки
|
||||
Move Library Item to Group Переместить элемент библиотеки в группу
|
||||
Library Библиотека
|
||||
Rename Library Переименовать библиотеку
|
||||
Show Library Показать библиотеку
|
||||
@@ -3859,3 +3876,24 @@ 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}
|
||||
Video Видео
|
||||
De-Interlace… Устранение чересстрочности…
|
||||
De-Interlace Устранение чересстрочности
|
||||
NTSC Colors Цвета NTSC
|
||||
Eliminate Удалить
|
||||
Create New Fields by Создать новые поля
|
||||
Odd Fields Нечётные поля
|
||||
Even Fields Чётные поля
|
||||
Duplication Дублированием
|
||||
Interpolation Интерполяцией
|
||||
@msg Imported library {name} Импортирована библиотека {name}
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -2752,6 +2752,23 @@
|
||||
Add to Library Додати до бібліотеки
|
||||
Delete Library Видалити бібліотеку
|
||||
Delete Library Item Видалити елемент бібліотеки
|
||||
No results Нічого не знайдено
|
||||
No items in this library match “{query}”. У цій бібліотеці немає елементів, що відповідають «{query}».
|
||||
Right-click an item to move it into this group. Клацніть елемент правою кнопкою миші, щоб перемістити його в цю групу.
|
||||
New Group Нова група
|
||||
New Group… Нова група…
|
||||
Move to Group Перемістити в групу
|
||||
No Group Без групи
|
||||
Rename Group… Перейменувати групу…
|
||||
Delete Group Видалити групу
|
||||
Import Library… Імпортувати бібліотеку…
|
||||
Export Library… Експортувати бібліотеку…
|
||||
Import Library Імпортувати бібліотеку
|
||||
Export Library Експортувати бібліотеку
|
||||
New Library Group Нова група бібліотеки
|
||||
Rename Library Group Перейменувати групу бібліотеки
|
||||
Delete Library Group Видалити групу бібліотеки
|
||||
Move Library Item to Group Перемістити елемент бібліотеки в групу
|
||||
Library Бібліотека
|
||||
Rename Library Перейменувати бібліотеку
|
||||
Show Library Показати бібліотеку
|
||||
@@ -3844,3 +3861,24 @@ 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}
|
||||
Video Відео
|
||||
De-Interlace… Усунення черезрядковості…
|
||||
De-Interlace Усунення черезрядковості
|
||||
NTSC Colors Кольори NTSC
|
||||
Eliminate Вилучити
|
||||
Create New Fields by Створити нові поля
|
||||
Odd Fields Непарні поля
|
||||
Even Fields Парні поля
|
||||
Duplication Дублюванням
|
||||
Interpolation Інтерполяцією
|
||||
@msg Imported library {name} Імпортовано бібліотеку {name}
|
||||
|
Can't render this file because it contains an unexpected character in line 659 and column 40.
|
@@ -2652,6 +2652,23 @@
|
||||
Add to Library 添加到库
|
||||
Delete Library 删除库
|
||||
Delete Library Item 删除库项目
|
||||
No results 无结果
|
||||
No items in this library match “{query}”. 此库中没有与“{query}”匹配的项目。
|
||||
Right-click an item to move it into this group. 右键单击项目可将其移到此组。
|
||||
New Group 新建组
|
||||
New Group… 新建组…
|
||||
Move to Group 移到组
|
||||
No Group 无组
|
||||
Rename Group… 重命名组…
|
||||
Delete Group 删除组
|
||||
Import Library… 导入库…
|
||||
Export Library… 导出库…
|
||||
Import Library 导入库
|
||||
Export Library 导出库
|
||||
New Library Group 新建库组
|
||||
Rename Library Group 重命名库组
|
||||
Delete Library Group 删除库组
|
||||
Move Library Item to Group 将库项目移到组
|
||||
Library 库
|
||||
Rename Library 重命名库
|
||||
Show Library 显示库
|
||||
@@ -3504,3 +3521,13 @@ axis Both 两者
|
||||
Draft 草稿
|
||||
Good 良好
|
||||
Best 最佳
|
||||
Video 视频
|
||||
De-Interlace… 逐行…
|
||||
De-Interlace 逐行
|
||||
NTSC Colors NTSC 颜色
|
||||
Eliminate 消除
|
||||
Create New Fields by 创建新场方式
|
||||
Odd Fields 奇数场
|
||||
Even Fields 偶数场
|
||||
Duplication 复制
|
||||
Interpolation 插值
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -2738,6 +2738,23 @@
|
||||
Add to Library 加入資料庫
|
||||
Delete Library 刪除資料庫
|
||||
Delete Library Item 刪除資料庫項目
|
||||
No results 沒有結果
|
||||
No items in this library match “{query}”. 此資料庫中沒有符合「{query}」的項目。
|
||||
Right-click an item to move it into this group. 在項目上按一下右鍵,即可將其移至此群組。
|
||||
New Group 新增群組
|
||||
New Group… 新增群組…
|
||||
Move to Group 移至群組
|
||||
No Group 無群組
|
||||
Rename Group… 重新命名群組…
|
||||
Delete Group 刪除群組
|
||||
Import Library… 匯入資料庫…
|
||||
Export Library… 匯出資料庫…
|
||||
Import Library 匯入資料庫
|
||||
Export Library 匯出資料庫
|
||||
New Library Group 新增資料庫群組
|
||||
Rename Library Group 重新命名資料庫群組
|
||||
Delete Library Group 刪除資料庫群組
|
||||
Move Library Item to Group 將資料庫項目移至群組
|
||||
Library 資料庫
|
||||
Rename Library 重新命名資料庫
|
||||
Show Library 顯示資料庫
|
||||
@@ -3282,3 +3299,13 @@ axis Both 兩者
|
||||
Draft 草稿
|
||||
Good 良好
|
||||
Best 最佳
|
||||
Video 視訊
|
||||
De-Interlace… 反交錯…
|
||||
De-Interlace 反交錯
|
||||
NTSC Colors NTSC 色彩
|
||||
Eliminate 消除
|
||||
Create New Fields by 建立新圖場以
|
||||
Odd Fields 奇數圖場
|
||||
Even Fields 偶數圖場
|
||||
Duplication 複製
|
||||
Interpolation 內插
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -15,8 +15,8 @@ use crate::{FilePick, Services, VectorcraftApp, dialogs};
|
||||
const TEMPLATE_EXTS: &[&str] = &["vctemplate", "ait", "vectorcraft", "drawcraft"];
|
||||
|
||||
/// Open bytes of any readable format as a new document (templates open untitled); swatch and
|
||||
/// graphic style library files open in the library panel and flattener, PDF, print and perspective
|
||||
/// grid presets files are imported. → `document.open`'s result for a document opened now (its
|
||||
/// graphic style library files open in the library panel, Libraries panel files are added to it,
|
||||
/// and flattener, PDF, print and perspective grid presets files are imported. → `document.open`'s result for a document opened now (its
|
||||
/// `warnings` say what didn't come in as it was), else null.
|
||||
pub fn open_bytes(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option<String>) -> Result<Value, String> {
|
||||
let ext = fileio::extension(name);
|
||||
@@ -39,6 +39,9 @@ pub fn open_bytes(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Opti
|
||||
app.status(format!("Imported {what}: {}", names.join(", ")));
|
||||
return Ok(Value::Null);
|
||||
}
|
||||
if vectorcraft_engine::cmd::library::LIBRARY_EXTS.contains(&ext.as_str()) {
|
||||
return crate::panels::libraries::import(app, json!({"data": String::from_utf8_lossy(bytes)})).map(|_| Value::Null);
|
||||
}
|
||||
let swatches = vectorcraft_engine::cmd::swatchlib::LIBRARY_EXTS.contains(&ext.as_str());
|
||||
if swatches || ext == vectorcraft_doc::style_libs::STYLES_EXT {
|
||||
let p = match path {
|
||||
|
||||
@@ -371,6 +371,12 @@ pub struct VectorcraftApp {
|
||||
/// The look for fonts installed or removed while the app was in the background, running
|
||||
/// ([`Self::refresh_installed_fonts`]): whether they were.
|
||||
font_check: Option<std::sync::mpsc::Receiver<bool>>,
|
||||
/// The window came back to the front: check the active document's linked files next frame
|
||||
/// ([`dialogs::missing_links::after_focus`]).
|
||||
pub(crate) links_check: bool,
|
||||
/// The changed linked files already offered for update (path, size and modification time), so
|
||||
/// coming back to the window doesn't ask about the same change twice.
|
||||
pub(crate) links_asked: std::collections::HashSet<dialogs::missing_links::FileStamp>,
|
||||
/// Keyboard pastes of something other than text (see [`shortcuts::PasteChord`]).
|
||||
pub(crate) paste_chord: shortcuts::PasteChord,
|
||||
/// Saves and exports running in the background (Preferences → File Handling).
|
||||
@@ -468,6 +474,8 @@ impl VectorcraftApp {
|
||||
clipboard_probe: None,
|
||||
picks: picks::Picks::default(),
|
||||
font_check: None,
|
||||
links_check: false,
|
||||
links_asked: Default::default(),
|
||||
paste_chord: Default::default(),
|
||||
background: Default::default(),
|
||||
recovery: Default::default(),
|
||||
@@ -881,6 +889,9 @@ impl VectorcraftApp {
|
||||
self.system_paste = wanted && self.system_clipboard_pasteable();
|
||||
}
|
||||
self.poll_font_check(ctx);
|
||||
if std::mem::take(&mut self.links_check) {
|
||||
dialogs::missing_links::after_focus(self);
|
||||
}
|
||||
picks::poll(self, ctx);
|
||||
background::poll(self);
|
||||
if !self.background.jobs.is_empty() {
|
||||
@@ -1014,7 +1025,10 @@ impl VectorcraftApp {
|
||||
match e {
|
||||
egui::Event::ModifiersChanged(m) => self.host_modifiers = *m,
|
||||
egui::Event::WindowFocused(false) => self.host_modifiers = egui::Modifiers::NONE,
|
||||
egui::Event::WindowFocused(true) => self.refresh_installed_fonts(),
|
||||
egui::Event::WindowFocused(true) => {
|
||||
self.refresh_installed_fonts();
|
||||
self.links_check = true;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3305,8 +3305,8 @@ fn font_items(english_names: bool) -> Vec<Item> {
|
||||
|
||||
/// The raster effects' submenus of the Effect menu (the Photoshop-style effects, below the
|
||||
/// vector effects): (submenu, the catalogue's menu path of its effects).
|
||||
const RASTER_MENUS: [(&str, &[&str]); 3] =
|
||||
[("Blur", &["Effect", "Blur"]), ("Pixelate", &["Effect", "Pixelate"]), ("Sharpen", &["Effect", "Sharpen"])];
|
||||
const RASTER_MENUS: [(&str, &[&str]); 4] =
|
||||
[("Blur", &["Effect", "Blur"]), ("Pixelate", &["Effect", "Pixelate"]), ("Sharpen", &["Effect", "Sharpen"]), ("Video", &["Effect", "Video"])];
|
||||
|
||||
/// The Effect menu, built from the effects catalogue (vector effects), plus raster effects.
|
||||
fn effect_menu() -> Vec<Item> {
|
||||
|
||||
@@ -95,6 +95,43 @@ fn dragged_stops(origin: &[GradientStop], i: usize, offset: f32, copy: bool, ove
|
||||
|
||||
// ---------- shared edits ----------
|
||||
|
||||
/// The Type row: Linear, Radial and Freeform for the paint behind the active proxy (one of them
|
||||
/// lit when it is a gradient). The Gradient panel's and the Properties panel's.
|
||||
pub(crate) fn type_row(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let kind = current(app).map(|g| g.gradient.kind);
|
||||
ui.horizontal(|ui| {
|
||||
widgets::dim_label(ui, tl!("Type:"));
|
||||
for (k, icon, tip) in [
|
||||
(GradientKind::Linear, "dc-grad-linear", tl!("Linear Gradient")),
|
||||
(GradientKind::Radial, "dc-grad-radial", tl!("Radial Gradient")),
|
||||
(GradientKind::Freeform, "dc-grad-freeform", tl!("Freeform Gradient")),
|
||||
] {
|
||||
if widgets::icon_button(ui, icon, tip, kind == Some(k), 24.0).clicked() {
|
||||
edit(app, json!({"kind": k.label().to_lowercase()}), Live::Released);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Set how the Gradient tool adds the points of the freeform gradient behind the active proxy.
|
||||
fn set_draw_mode(app: &mut VectorcraftApp, mode: FreeformMode) {
|
||||
edit(app, json!({ "mode": mode.label().to_lowercase() }), Live::Released);
|
||||
}
|
||||
|
||||
/// The Properties panel's Draw row for a freeform gradient: Points and Lines as radio buttons.
|
||||
pub(crate) fn draw_radios(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let Some(g) = current(app).filter(|g| g.gradient.kind == GradientKind::Freeform) else { return };
|
||||
let mode = shown_points(&g).mode;
|
||||
ui.horizontal(|ui| {
|
||||
widgets::dim_label(ui, tl!("Draw:"));
|
||||
for (m, label) in [(FreeformMode::Points, tl!("Points")), (FreeformMode::Lines, tl!("Lines"))] {
|
||||
if widgets::radio(ui, label, mode == m, true) && mode != m {
|
||||
set_draw_mode(app, m);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// The gradient behind the active proxy.
|
||||
fn current(app: &VectorcraftApp) -> Option<GradientPaint> {
|
||||
match active_paint(app) {
|
||||
@@ -184,18 +221,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
}
|
||||
ui.add_space(4.0);
|
||||
ui.vertical(|ui| {
|
||||
ui.horizontal(|ui| {
|
||||
widgets::dim_label(ui, tl!("Type:"));
|
||||
for (k, icon, tip) in [
|
||||
(GradientKind::Linear, "dc-grad-linear", tl!("Linear Gradient")),
|
||||
(GradientKind::Radial, "dc-grad-radial", tl!("Radial Gradient")),
|
||||
(GradientKind::Freeform, "dc-grad-freeform", tl!("Freeform Gradient")),
|
||||
] {
|
||||
if widgets::icon_button(ui, icon, tip, is_grad && kind == k, 24.0).clicked() {
|
||||
edit(app, json!({"kind": k.label().to_lowercase()}), Live::Released);
|
||||
}
|
||||
}
|
||||
});
|
||||
type_row(app, ui);
|
||||
if widgets::flat_button(ui, tl!("Edit Gradient"), 96.0).clicked() {
|
||||
app.select_tool("gradient");
|
||||
}
|
||||
@@ -297,7 +323,7 @@ fn freeform_section(app: &mut VectorcraftApp, ui: &mut Ui, g: &GradientPaint) {
|
||||
(FreeformMode::Lines, "spline", tl!("Lines: clicks add points joined by a line")),
|
||||
] {
|
||||
if widgets::icon_button(ui, icon, tip, mode == m, 24.0).clicked() && mode != m {
|
||||
edit(app, json!({ "mode": m.label().to_lowercase() }), Live::Released);
|
||||
set_draw_mode(app, m);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -4,16 +4,20 @@
|
||||
//! graphic, fill or stroke colour or text styles. A colour click paints the selection through the
|
||||
//! active Fill/Stroke proxy, a style click applies it to the selected type, and a graphic is
|
||||
//! dragged onto the canvas (or double-clicked) to place a copy. Libraries are kept on this machine.
|
||||
//!
|
||||
//! The search field filters the items by name; items can be moved into user-named groups, shown as
|
||||
//! collapsible sections after the ungrouped items; and the panel menu exports the library to a
|
||||
//! `.vclibrary` file and imports one as a new library (#926).
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use egui::{Rect, Sense, Stroke, StrokeKind, Ui, vec2};
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::Paint;
|
||||
use vectorcraft_engine::cmd::library::Library;
|
||||
use vectorcraft_engine::cmd::library::{ItemKind, LIBRARY_EXT, LIBRARY_EXTS, Library, LibraryGraphic};
|
||||
|
||||
use crate::theme::Tokens;
|
||||
use crate::widgets::{self, PanelDrag, menu_item};
|
||||
use crate::widgets::{self, PanelDrag, menu_item, menu_item_name};
|
||||
use crate::{VectorcraftApp, icons};
|
||||
|
||||
/// The size of a graphic's tile.
|
||||
@@ -21,20 +25,28 @@ const TILE: f32 = 56.0;
|
||||
/// The size of a colour chip.
|
||||
const CHIP: f32 = 22.0;
|
||||
|
||||
/// The current library: its id and a copy of it (the panel acts on it after reading).
|
||||
/// The current library: its id and a copy of it (the panel menu acts on it after reading).
|
||||
fn current(app: &VectorcraftApp) -> Option<(String, Library)> {
|
||||
let libs = &app.session.libraries;
|
||||
let id = libs.current()?;
|
||||
Some((id.to_string(), libs.get(id)?.clone()))
|
||||
}
|
||||
|
||||
/// Run `cmd`, reporting a failure in the status bar.
|
||||
fn run(app: &mut VectorcraftApp, cmd: &str, p: Value) {
|
||||
if let Err(e) = app.run(cmd, p) {
|
||||
/// Report a failure in the status bar (a file dialog closed or still open says nothing).
|
||||
fn report<T>(app: &mut VectorcraftApp, r: Result<T, String>) {
|
||||
if let Err(e) = r
|
||||
&& e != "cancelled"
|
||||
{
|
||||
app.status(e);
|
||||
}
|
||||
}
|
||||
|
||||
/// Run `cmd`, reporting a failure in the status bar.
|
||||
fn run(app: &mut VectorcraftApp, cmd: &str, p: Value) {
|
||||
let r = app.run(cmd, p);
|
||||
report(app, r);
|
||||
}
|
||||
|
||||
/// The name dialog for a new library, or for renaming the current one.
|
||||
fn ask_name(app: &mut VectorcraftApp, rename: Option<&str>) {
|
||||
let (cmd, label, name) = match rename {
|
||||
@@ -44,9 +56,46 @@ fn ask_name(app: &mut VectorcraftApp, rename: Option<&str>) {
|
||||
app.ui.dialog = Some(crate::state::Dialog::new("command", json!({ "__command": cmd, "__label": label, "name": name })));
|
||||
}
|
||||
|
||||
/// The name dialog for a new group of `library` (`items`: `[{kind, item}]` moved into it), or for
|
||||
/// renaming group `rename`.
|
||||
fn ask_group_name(app: &mut VectorcraftApp, library: &str, rename: Option<&str>, items: Value) {
|
||||
let (cmd, label, name, fixed) = match rename {
|
||||
Some(g) => ("library.renameGroup", "Rename Library Group", g, json!({ "library": library, "group": g })),
|
||||
None => ("library.createGroup", "New Library Group", "Group", json!({ "library": library, "items": items })),
|
||||
};
|
||||
let d = json!({ "__command": cmd, "__label": label, "name": name, "__params": fixed });
|
||||
app.ui.dialog = Some(crate::state::Dialog::new("command", d));
|
||||
}
|
||||
|
||||
/// What a click in the panel asks for, done once the list is drawn.
|
||||
enum Act {
|
||||
Run(&'static str, Value),
|
||||
/// The New Group dialog; the items (`[{kind, item}]`) go into the new group.
|
||||
NewGroup(Value),
|
||||
RenameGroup(String),
|
||||
}
|
||||
|
||||
/// What the item list draws from.
|
||||
struct Items<'a> {
|
||||
library: &'a str,
|
||||
lib: &'a Library,
|
||||
/// The group of each grouped item ([`Library::group_index`]).
|
||||
groups: HashMap<(ItemKind, &'a str), usize>,
|
||||
fill_active: bool,
|
||||
}
|
||||
|
||||
impl Items<'_> {
|
||||
fn group_of(&self, kind: ItemKind, key: &str) -> Option<usize> {
|
||||
self.groups.get(&(kind, key)).copied()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let Some((lib_id, lib)) = current(app) else {
|
||||
let fill_active = app.session.fill_active;
|
||||
let has_doc = app.session.active().is_some();
|
||||
let libs = &app.session.libraries;
|
||||
let Some((lib_id, lib)) = libs.current().and_then(|id| Some((id.to_string(), libs.get(id)?))) else {
|
||||
ui.add_space(16.0);
|
||||
ui.vertical_centered(|ui| {
|
||||
icons::icon(ui, "library", 40.0, t.text_dim);
|
||||
@@ -60,18 +109,27 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
});
|
||||
return;
|
||||
};
|
||||
let mut act: Option<Act> = None;
|
||||
// The library picker.
|
||||
let libs: Vec<(String, String)> = app.session.libraries.all().iter().map(|(i, l)| (i.clone(), l.name.clone())).collect();
|
||||
let names: Vec<&str> = libs.iter().map(|(_, n)| n.as_str()).collect();
|
||||
if let Some(i) = widgets::dropdown_names(ui, "lib-picker", &lib.name, &names, ui.available_width())
|
||||
&& let Some((id, _)) = libs.get(i)
|
||||
{
|
||||
run(app, "library.setCurrent", json!({ "library": id }));
|
||||
let names: Vec<&str> = libs.all().iter().map(|(_, l)| l.name.as_str()).collect();
|
||||
if let Some((id, _)) = widgets::dropdown_names(ui, "lib-picker", &lib.name, &names, ui.available_width()).and_then(|i| libs.all().get(i)) {
|
||||
act = Some(Act::Run("library.setCurrent", json!({ "library": id })));
|
||||
}
|
||||
ui.add_space(4.0);
|
||||
let empty = lib.items().next().is_none() && lib.groups.is_empty();
|
||||
let query = if empty { String::new() } else { widgets::search_field(ui, egui::Id::new("library-search"), tl!("Search")) };
|
||||
let query = query.trim().to_lowercase();
|
||||
let searching = !query.is_empty();
|
||||
let shown = |name: &str| !searching || name.to_lowercase().contains(&query);
|
||||
let items = Items { library: &lib_id, lib, groups: lib.group_index(), fill_active };
|
||||
// The items shown in each section: the ungrouped ones first, then each group's.
|
||||
let mut counts = vec![0usize; lib.groups.len() + 1];
|
||||
for (kind, key, _) in lib.items().filter(|(_, _, name)| shown(name)) {
|
||||
if let Some(n) = counts.get_mut(items.group_of(kind, key).map_or(0, |i| i + 1)) {
|
||||
*n += 1;
|
||||
}
|
||||
}
|
||||
ui.add_space(4.0);
|
||||
let empty = lib.colors.is_empty() && lib.char_styles.is_empty() && lib.para_styles.is_empty() && lib.graphics.is_empty();
|
||||
let mut act: Option<(&'static str, Value)> = None;
|
||||
let fill_active = app.session.fill_active;
|
||||
let list_rect = widgets::list_box(ui, |ui| {
|
||||
ui.set_min_height(140.0);
|
||||
ui.set_width(ui.available_width());
|
||||
@@ -84,101 +142,53 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
);
|
||||
return ui.min_rect();
|
||||
}
|
||||
if searching && counts.iter().all(|n| *n == 0) {
|
||||
let body = crate::i18n::fmt(tl!("No items in this library match “{query}”."), &[("query", &query)]);
|
||||
super::empty_state(ui, "search", tl!("No results"), &body);
|
||||
return ui.min_rect();
|
||||
}
|
||||
egui::Frame::NONE.inner_margin(egui::Margin::same(6)).show(ui, |ui| {
|
||||
if !lib.colors.is_empty() {
|
||||
heading(ui, tl!("Colors"));
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.spacing_mut().item_spacing = vec2(4.0, 4.0);
|
||||
for c in &lib.colors {
|
||||
let (r, resp) = ui.allocate_exact_size(vec2(CHIP, CHIP), Sense::click_and_drag());
|
||||
let paint = Paint::solid(c.color);
|
||||
widgets::swatch_tile(ui, r, &paint, false, false);
|
||||
ui.painter().rect_stroke(r, 0.0, Stroke::new(1.0, t.border), StrokeKind::Inside);
|
||||
widgets::drag_source(ui, &resp, || PanelDrag::Paint {
|
||||
paint: paint.clone(),
|
||||
params: json!({ "color": c.color }),
|
||||
rows: None,
|
||||
});
|
||||
let resp = resp.on_hover_text(&c.name);
|
||||
if resp.clicked() {
|
||||
act = Some((
|
||||
"library.use",
|
||||
json!({ "kind": "fillColor", "item": c.name, "to": if fill_active { "fill" } else { "stroke" } }),
|
||||
));
|
||||
}
|
||||
resp.context_menu(|ui| {
|
||||
if menu_item(ui, "Delete", true, false) {
|
||||
act = Some(("library.removeItem", json!({ "kind": "fillColor", "item": c.name })));
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
ui.add_space(6.0);
|
||||
}
|
||||
for (para, list, title) in [(false, &lib.char_styles, tl!("Character Styles")), (true, &lib.para_styles, tl!("Paragraph Styles"))] {
|
||||
if list.is_empty() {
|
||||
items.show(ui, &mut act, |kind, key, name| items.group_of(kind, key).is_none() && shown(name));
|
||||
for (i, g) in lib.groups.iter().enumerate() {
|
||||
let n = counts.get(i + 1).copied().unwrap_or_default();
|
||||
if searching && n == 0 {
|
||||
continue;
|
||||
}
|
||||
heading(ui, title);
|
||||
let kind = if para { "paraStyle" } else { "charStyle" };
|
||||
for st in list {
|
||||
let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click());
|
||||
if resp.hovered() {
|
||||
ui.painter().rect_filled(r, 0.0, t.hover);
|
||||
}
|
||||
icons::paint(
|
||||
ui,
|
||||
if para { "pilcrow" } else { "type" },
|
||||
Rect::from_center_size(r.left_center() + vec2(10.0, 0.0), vec2(14.0, 14.0)),
|
||||
t.icon,
|
||||
);
|
||||
ui.painter().text(
|
||||
r.left_center() + vec2(24.0, 0.0),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
&st.name,
|
||||
egui::FontId::proportional(12.5),
|
||||
t.text,
|
||||
);
|
||||
let resp = resp.on_hover_text(tl!("Click to apply to the selected type"));
|
||||
if resp.clicked() {
|
||||
act = Some(("library.use", json!({ "kind": kind, "item": st.name })));
|
||||
}
|
||||
resp.context_menu(|ui| {
|
||||
if menu_item(ui, "Delete", true, false) {
|
||||
act = Some(("library.removeItem", json!({ "kind": kind, "item": st.name })));
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
// Open unless closed; open while searching, to show what matched.
|
||||
let key = format!("library-group-closed:{lib_id}:{}", g.name);
|
||||
let closed: bool = super::pstate(ui.ctx(), &key);
|
||||
let open = searching || !closed;
|
||||
let header = widgets::section_toggle_name(ui, &g.name, open);
|
||||
ui.painter().text(
|
||||
header.rect.right_center() - vec2(6.0, 0.0),
|
||||
egui::Align2::RIGHT_CENTER,
|
||||
n.to_string(),
|
||||
egui::FontId::proportional(11.5),
|
||||
t.text_dim,
|
||||
);
|
||||
if header.clicked() && !searching {
|
||||
super::set_pstate(ui.ctx(), &key, !closed);
|
||||
}
|
||||
ui.add_space(6.0);
|
||||
}
|
||||
if !lib.graphics.is_empty() {
|
||||
heading(ui, tl!("Graphics"));
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.spacing_mut().item_spacing = vec2(4.0, 4.0);
|
||||
for g in &lib.graphics {
|
||||
let (r, resp) = ui.allocate_exact_size(vec2(TILE, TILE), Sense::click_and_drag());
|
||||
tile(ui, r, &lib_id, g);
|
||||
ui.painter().rect_stroke(r, 0.0, Stroke::new(1.0, if resp.hovered() { t.accent } else { t.border }), StrokeKind::Inside);
|
||||
// Dragged onto the canvas, a copy is placed where it is dropped.
|
||||
widgets::drag_source(ui, &resp, || PanelDrag::LibraryGraphic { library: lib_id.clone(), item: g.id.clone() });
|
||||
let resp = resp.on_hover_text(&g.name);
|
||||
if resp.double_clicked() {
|
||||
act = Some(("library.use", json!({ "kind": "graphic", "item": g.id })));
|
||||
}
|
||||
resp.context_menu(|ui| {
|
||||
if menu_item(ui, "Place", true, false) {
|
||||
act = Some(("library.use", json!({ "kind": "graphic", "item": g.id })));
|
||||
ui.close();
|
||||
}
|
||||
if menu_item(ui, "Delete", true, false) {
|
||||
act = Some(("library.removeItem", json!({ "kind": "graphic", "item": g.id })));
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
header.context_menu(|ui| {
|
||||
if menu_item(ui, "Rename Group…", true, false) {
|
||||
act = Some(Act::RenameGroup(g.name.clone()));
|
||||
ui.close();
|
||||
}
|
||||
if menu_item(ui, "Delete Group", true, false) {
|
||||
act = Some(Act::Run("library.deleteGroup", json!({ "group": g.name })));
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
if !open {
|
||||
continue;
|
||||
}
|
||||
ui.add_space(2.0);
|
||||
if n == 0 {
|
||||
ui.label(egui::RichText::new(tl!("Right-click an item to move it into this group.")).size(11.5).color(t.text_dim));
|
||||
ui.add_space(6.0);
|
||||
} else {
|
||||
items.show(ui, &mut act, |kind, key, name| items.group_of(kind, key) == Some(i) && shown(name));
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.min_rect()
|
||||
@@ -186,7 +196,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
// Art dragged off the canvas, or a swatch, dropped on the list is added to the library.
|
||||
let zone = ui.interact(list_rect, ui.id().with("libraries-drop"), Sense::hover());
|
||||
if let Some(ids) = widgets::art_drop(ui, &zone) {
|
||||
act = Some(("library.add", json!({ "kind": "graphic", "ids": ids })));
|
||||
act = Some(Act::Run("library.add", json!({ "kind": "graphic", "ids": ids })));
|
||||
}
|
||||
if let Some(drag) = zone.dnd_hover_payload::<PanelDrag>()
|
||||
&& let PanelDrag::Paint { paint: Paint::Solid { color, .. }, .. } = &*drag
|
||||
@@ -194,21 +204,13 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
ui.painter().rect_stroke(zone.rect, 0.0, Stroke::new(1.5, t.accent), StrokeKind::Inside);
|
||||
let color = *color;
|
||||
if zone.dnd_release_payload::<PanelDrag>().is_some() {
|
||||
act = Some(("library.add", json!({ "kind": "fillColor", "color": color })));
|
||||
act = Some(Act::Run("library.add", json!({ "kind": "fillColor", "color": color })));
|
||||
}
|
||||
}
|
||||
if let Some((cmd, mut p)) = act {
|
||||
p["library"] = json!(lib_id);
|
||||
if cmd == "library.use" && p["kind"] == "graphic" {
|
||||
// Placed at the centre of the view.
|
||||
if let Some(v) = app.view() {
|
||||
p["center"] = json!([v.center.x, v.center.y]);
|
||||
}
|
||||
}
|
||||
run(app, cmd, p);
|
||||
}
|
||||
let has_doc = app.session.active().is_some();
|
||||
widgets::bottom_bar(ui, |ui| {
|
||||
if widgets::icon_button(ui, "group", tl!("New Group"), false, 24.0).clicked() {
|
||||
act = Some(Act::NewGroup(json!([])));
|
||||
}
|
||||
let add = widgets::icon_button_enabled(ui, "plus", tl!("Add Content"), false, has_doc, 24.0);
|
||||
egui::Popup::menu(&add).show(|ui| {
|
||||
for (label, kind) in [
|
||||
@@ -219,12 +221,154 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
("Paragraph Style", "paraStyle"),
|
||||
] {
|
||||
if menu_item(ui, label, true, false) {
|
||||
run(app, "library.add", json!({ "library": lib_id, "kind": kind }));
|
||||
act = Some(Act::Run("library.add", json!({ "kind": kind })));
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
match act {
|
||||
Some(Act::Run(cmd, mut p)) => {
|
||||
if cmd != "library.setCurrent" {
|
||||
p["library"] = json!(lib_id);
|
||||
}
|
||||
if cmd == "library.use" && p["kind"] == "graphic" {
|
||||
// Placed at the centre of the view.
|
||||
if let Some(v) = app.view() {
|
||||
p["center"] = json!([v.center.x, v.center.y]);
|
||||
}
|
||||
}
|
||||
run(app, cmd, p);
|
||||
}
|
||||
Some(Act::NewGroup(items)) => ask_group_name(app, &lib_id, None, items),
|
||||
Some(Act::RenameGroup(g)) => ask_group_name(app, &lib_id, Some(&g), Value::Null),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
|
||||
impl Items<'_> {
|
||||
/// The colours, character and paragraph styles and graphics `keep` keeps (given the kind, key
|
||||
/// and name of each), each kind under its heading.
|
||||
fn show(&self, ui: &mut Ui, act: &mut Option<Act>, keep: impl Fn(ItemKind, &str, &str) -> bool) {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let lib = self.lib;
|
||||
let colors: Vec<_> = lib.colors.iter().filter(|c| keep(ItemKind::Color, &c.name, &c.name)).collect();
|
||||
if !colors.is_empty() {
|
||||
heading(ui, tl!("Colors"));
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.spacing_mut().item_spacing = vec2(4.0, 4.0);
|
||||
for c in colors {
|
||||
let (r, resp) = ui.allocate_exact_size(vec2(CHIP, CHIP), Sense::click_and_drag());
|
||||
let paint = Paint::solid(c.color);
|
||||
widgets::swatch_tile(ui, r, &paint, false, false);
|
||||
ui.painter().rect_stroke(r, 0.0, Stroke::new(1.0, t.border), StrokeKind::Inside);
|
||||
widgets::drag_source(ui, &resp, || PanelDrag::Paint { paint: paint.clone(), params: json!({ "color": c.color }), rows: None });
|
||||
let resp = resp.on_hover_text(&c.name);
|
||||
if resp.clicked() {
|
||||
let to = if self.fill_active { "fill" } else { "stroke" };
|
||||
*act = Some(Act::Run("library.use", json!({ "kind": "fillColor", "item": c.name, "to": to })));
|
||||
}
|
||||
resp.context_menu(|ui| self.item_menu(ui, act, ItemKind::Color, &c.name));
|
||||
}
|
||||
});
|
||||
ui.add_space(6.0);
|
||||
}
|
||||
for (kind, list, title) in
|
||||
[(ItemKind::CharStyle, &lib.char_styles, tl!("Character Styles")), (ItemKind::ParaStyle, &lib.para_styles, tl!("Paragraph Styles"))]
|
||||
{
|
||||
let list: Vec<_> = list.iter().filter(|s| keep(kind, &s.name, &s.name)).collect();
|
||||
if list.is_empty() {
|
||||
continue;
|
||||
}
|
||||
heading(ui, title);
|
||||
for st in list {
|
||||
let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click());
|
||||
if resp.hovered() {
|
||||
ui.painter().rect_filled(r, 0.0, t.hover);
|
||||
}
|
||||
let icon = if kind == ItemKind::ParaStyle { "pilcrow" } else { "type" };
|
||||
icons::paint(ui, icon, Rect::from_center_size(r.left_center() + vec2(10.0, 0.0), vec2(14.0, 14.0)), t.icon);
|
||||
ui.painter().text(r.left_center() + vec2(24.0, 0.0), egui::Align2::LEFT_CENTER, &st.name, egui::FontId::proportional(12.5), t.text);
|
||||
let resp = resp.on_hover_text(tl!("Click to apply to the selected type"));
|
||||
if resp.clicked() {
|
||||
*act = Some(Act::Run("library.use", json!({ "kind": kind_param(kind), "item": st.name })));
|
||||
}
|
||||
resp.context_menu(|ui| self.item_menu(ui, act, kind, &st.name));
|
||||
}
|
||||
ui.add_space(6.0);
|
||||
}
|
||||
let graphics: Vec<_> = lib.graphics.iter().filter(|g| keep(ItemKind::Graphic, &g.id, &g.name)).collect();
|
||||
if !graphics.is_empty() {
|
||||
heading(ui, tl!("Graphics"));
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.spacing_mut().item_spacing = vec2(4.0, 4.0);
|
||||
for g in graphics {
|
||||
let (r, resp) = ui.allocate_exact_size(vec2(TILE, TILE), Sense::click_and_drag());
|
||||
tile(ui, r, self.library, g);
|
||||
ui.painter().rect_stroke(r, 0.0, Stroke::new(1.0, if resp.hovered() { t.accent } else { t.border }), StrokeKind::Inside);
|
||||
// Dragged onto the canvas, a copy is placed where it is dropped.
|
||||
widgets::drag_source(ui, &resp, || PanelDrag::LibraryGraphic { library: self.library.to_string(), item: g.id.clone() });
|
||||
let resp = resp.on_hover_text(&g.name);
|
||||
let place = || Act::Run("library.use", json!({ "kind": "graphic", "item": g.id }));
|
||||
if resp.double_clicked() {
|
||||
*act = Some(place());
|
||||
}
|
||||
resp.context_menu(|ui| {
|
||||
if menu_item(ui, "Place", true, false) {
|
||||
*act = Some(place());
|
||||
ui.close();
|
||||
}
|
||||
self.item_menu(ui, act, ItemKind::Graphic, &g.id);
|
||||
});
|
||||
}
|
||||
});
|
||||
ui.add_space(6.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// An item's context menu entries: Move to Group (No Group, the library's groups, New
|
||||
/// Group…) and Delete.
|
||||
fn item_menu(&self, ui: &mut Ui, act: &mut Option<Act>, kind: ItemKind, key: &str) {
|
||||
let at = self.group_of(kind, key);
|
||||
let item = json!({ "kind": kind_param(kind), "item": key });
|
||||
ui.menu_button(format!(" {}", tl!("Move to Group")), |ui| {
|
||||
if menu_item(ui, "No Group", true, at.is_none()) {
|
||||
if at.is_some() {
|
||||
*act = Some(Act::Run("library.moveItem", item.clone()));
|
||||
}
|
||||
ui.close();
|
||||
}
|
||||
for (i, g) in self.lib.groups.iter().enumerate() {
|
||||
if menu_item_name(ui, &g.name, true, at == Some(i)) {
|
||||
if at != Some(i) {
|
||||
let mut p = item.clone();
|
||||
p["group"] = json!(g.name);
|
||||
*act = Some(Act::Run("library.moveItem", p));
|
||||
}
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
ui.separator();
|
||||
if menu_item(ui, "New Group…", true, false) {
|
||||
*act = Some(Act::NewGroup(json!([item])));
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
if menu_item(ui, "Delete", true, false) {
|
||||
*act = Some(Act::Run("library.removeItem", item));
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `kind` as the `library.*` commands' `kind` param (a colour as a fill colour).
|
||||
fn kind_param(kind: ItemKind) -> &'static str {
|
||||
match kind {
|
||||
ItemKind::Graphic => "graphic",
|
||||
ItemKind::CharStyle => "charStyle",
|
||||
ItemKind::ParaStyle => "paraStyle",
|
||||
ItemKind::Color | ItemKind::Unknown => "fillColor",
|
||||
}
|
||||
}
|
||||
|
||||
/// A section heading in the list.
|
||||
@@ -235,7 +379,7 @@ fn heading(ui: &mut Ui, text: &str) {
|
||||
}
|
||||
|
||||
/// Graphic `g`'s thumbnail on white in `r`.
|
||||
fn tile(ui: &Ui, r: Rect, library: &str, g: &vectorcraft_engine::cmd::library::LibraryGraphic) {
|
||||
fn tile(ui: &Ui, r: Rect, library: &str, g: &LibraryGraphic) {
|
||||
ui.painter().rect_filled(r, 0.0, egui::Color32::WHITE);
|
||||
if let Some(tex) = thumbnail(ui.ctx(), library, g) {
|
||||
let size = tex.size_vec2();
|
||||
@@ -246,7 +390,7 @@ fn tile(ui: &Ui, r: Rect, library: &str, g: &vectorcraft_engine::cmd::library::L
|
||||
}
|
||||
|
||||
/// The texture of graphic `g`'s PNG thumbnail, decoded once.
|
||||
fn thumbnail(ctx: &egui::Context, library: &str, g: &vectorcraft_engine::cmd::library::LibraryGraphic) -> Option<egui::TextureHandle> {
|
||||
fn thumbnail(ctx: &egui::Context, library: &str, g: &LibraryGraphic) -> Option<egui::TextureHandle> {
|
||||
thread_local! {
|
||||
static CACHE: crate::graphics::TexCache<HashMap<(String, String, usize), Option<egui::TextureHandle>>> = crate::graphics::TexCache::default();
|
||||
}
|
||||
@@ -278,7 +422,37 @@ pub(crate) fn chip(app: &VectorcraftApp, ui: &Ui, r: Rect, library: &str, item:
|
||||
}
|
||||
}
|
||||
|
||||
/// The panel's ≡ menu: Create New Library, Rename Library…, Delete Library.
|
||||
/// Import a library file (`library.import`'s params), saying so in the status bar.
|
||||
pub(crate) fn import(app: &mut VectorcraftApp, p: Value) -> Result<Value, String> {
|
||||
let r = app.run("library.import", p)?;
|
||||
let name = r["name"].as_str().unwrap_or_default().to_string();
|
||||
app.status(format!("Imported library {name}"));
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
/// Import Library…: a picked `.vclibrary` file becomes a new library (on the web the picked file
|
||||
/// arrives later through [`crate::io::open_bytes`]).
|
||||
fn import_picked(app: &mut VectorcraftApp) {
|
||||
if let Some(f) = app.services.open_async.as_mut() {
|
||||
f();
|
||||
return;
|
||||
}
|
||||
let pick = crate::FilePick { filters: vec![("Libraries", LIBRARY_EXTS)], ..Default::default() };
|
||||
if let Some(path) = crate::picks::open(app, &pick) {
|
||||
let r = import(app, json!({ "path": path }));
|
||||
report(app, r);
|
||||
}
|
||||
}
|
||||
|
||||
/// Export Library…: library `id` written to a picked file named after it (the web downloads it).
|
||||
fn export_picked(app: &mut VectorcraftApp, id: &str, name: &str) {
|
||||
let file = format!("{}.{LIBRARY_EXT}", vectorcraft_engine::cmd::library::file_stem_for(name));
|
||||
let r = crate::io::save_command_output_named(app, "library.export", &file, json!({ "library": id }));
|
||||
report(app, r);
|
||||
}
|
||||
|
||||
/// The panel's ≡ menu: Create New Library, Rename Library…, Delete Library, New Group…, Import
|
||||
/// Library…, Export Library….
|
||||
pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let cur = current(app);
|
||||
if menu_item(ui, "Create New Library…", true, false) {
|
||||
@@ -304,6 +478,24 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
);
|
||||
ui.close();
|
||||
}
|
||||
ui.separator();
|
||||
if menu_item(ui, "New Group…", cur.is_some(), false)
|
||||
&& let Some((id, _)) = &cur
|
||||
{
|
||||
ask_group_name(app, id, None, json!([]));
|
||||
ui.close();
|
||||
}
|
||||
ui.separator();
|
||||
if menu_item(ui, "Import Library…", true, false) {
|
||||
crate::picks::button(app, import_picked);
|
||||
ui.close();
|
||||
}
|
||||
if menu_item(ui, "Export Library…", cur.is_some(), false)
|
||||
&& let Some((id, lib)) = cur
|
||||
{
|
||||
crate::picks::button(app, move |app| export_picked(app, &id, &lib.name));
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -315,6 +507,7 @@ mod tests {
|
||||
|
||||
fn frame(app: &mut VectorcraftApp) {
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| {
|
||||
show(app, ui);
|
||||
menu(app, ui);
|
||||
@@ -345,4 +538,94 @@ mod tests {
|
||||
let ctx = egui::Context::default();
|
||||
assert!(thumbnail(&ctx, "Brand", &lib.graphics[0]).is_some());
|
||||
}
|
||||
|
||||
/// The panel's text: every label it shows in one frame (`query` typed in the search field).
|
||||
fn texts(app: &mut VectorcraftApp, query: &str) -> Vec<String> {
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
ctx.data_mut(|d| d.insert_temp(egui::Id::new("library-search"), query.to_string()));
|
||||
let mut shapes = vec![];
|
||||
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| show(app, ui));
|
||||
out.textures_delta.clear();
|
||||
shapes.append(&mut out.shapes);
|
||||
let mut texts = vec![];
|
||||
for s in shapes {
|
||||
if let egui::epaint::Shape::Text(t) = s.shape {
|
||||
texts.push(t.galley.text().to_string());
|
||||
}
|
||||
}
|
||||
texts
|
||||
}
|
||||
|
||||
/// The search field filters items by name, ignoring case; groups show after the ungrouped
|
||||
/// items, and a search nothing matches says so (#926).
|
||||
#[test]
|
||||
fn the_panel_searches_and_shows_groups() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
|
||||
app.run("library.create", json!({"name": "Brand"})).unwrap();
|
||||
for (name, color) in [("Ocean Blue", "#0044aa"), ("Sun Yellow", "#ffcc00")] {
|
||||
app.run("library.add", json!({"kind": "fillColor", "color": color, "name": name})).unwrap();
|
||||
}
|
||||
let t = app.run("text.create", json!({"x": 10, "y": 80, "text": "Type"})).unwrap()["id"].clone();
|
||||
app.run("select.set", json!({"ids": [t]})).unwrap();
|
||||
app.run("library.add", json!({"kind": "charStyle", "name": "Headline"})).unwrap();
|
||||
app.run("library.createGroup", json!({"name": "Warm", "items": [{"kind": "fillColor", "item": "Sun Yellow"}]})).unwrap();
|
||||
let all = texts(&mut app, "");
|
||||
let at = |s: &str| all.iter().position(|t| t == s);
|
||||
assert!(at("Headline").is_some() && at("Warm").is_some(), "{all:?}");
|
||||
assert!(at("Headline") < at("Warm"), "groups come after the ungrouped items: {all:?}");
|
||||
// "BLUE" finds the blue swatch only: the style and the group without a match are hidden.
|
||||
let found = texts(&mut app, "BLUE");
|
||||
assert!(!found.iter().any(|t| t == "Headline" || t == "Warm"), "{found:?}");
|
||||
let found = texts(&mut app, "yellow");
|
||||
assert!(found.iter().any(|t| t == "Warm") && !found.iter().any(|t| t == "Headline"), "{found:?}");
|
||||
let none = texts(&mut app, "zzz");
|
||||
assert!(none.iter().any(|t| t == "No results"), "{none:?}");
|
||||
}
|
||||
|
||||
/// New Group… and Rename Group… ask for a name and act on the library and group they came
|
||||
/// from; the dialog shows only the name.
|
||||
#[test]
|
||||
fn group_dialogs_run_with_their_library_and_group() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
|
||||
let lib = app.run("library.create", json!({"name": "Brand"})).unwrap()["id"].as_str().unwrap().to_string();
|
||||
app.run("library.add", json!({"kind": "fillColor", "color": "#0044aa", "name": "Blue"})).unwrap();
|
||||
ask_group_name(&mut app, &lib, None, json!([{"kind": "fillColor", "item": "Blue"}]));
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("name".into(), json!("Cool"));
|
||||
crate::dialogs::confirm(&mut app).unwrap();
|
||||
ask_group_name(&mut app, &lib, Some("Cool"), Value::Null);
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("name".into(), json!("Cold"));
|
||||
crate::dialogs::confirm(&mut app).unwrap();
|
||||
let got = app.run("library.get", json!({})).unwrap();
|
||||
assert_eq!(got["groups"], json!([{"name": "Cold", "items": [{"kind": "color", "item": "Blue"}]}]));
|
||||
}
|
||||
|
||||
/// Export Library… writes the library's file and Import Library… adds it back as a new library.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn libraries_are_exported_and_imported_from_the_panel_menu() {
|
||||
let dir = vectorcraft_testkit::temp_dir("libraries-panel");
|
||||
let path = dir.join("Brand.vclibrary").to_string_lossy().to_string();
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
|
||||
app.run("library.create", json!({"name": "Brand"})).unwrap();
|
||||
app.run("library.add", json!({"kind": "fillColor", "color": "#0044aa", "name": "Blue"})).unwrap();
|
||||
let picked = path.clone();
|
||||
app.services.pick_save = Some(Box::new(move |pick: &crate::FilePick| {
|
||||
assert_eq!(pick.name, "Brand.vclibrary", "the library's name suggested");
|
||||
Some(picked.clone())
|
||||
}));
|
||||
app.services.write = Some(Box::new(|p: &str, bytes: &[u8]| std::fs::write(p, bytes).map_err(|e| e.to_string())));
|
||||
export_picked(&mut app, "Brand", "Brand");
|
||||
assert!(std::path::Path::new(&path).exists());
|
||||
let picked = path.clone();
|
||||
app.services.pick_open = Some(Box::new(move |_: &crate::FilePick| Some(picked.clone())));
|
||||
import_picked(&mut app);
|
||||
let list = app.run("library.list", json!({})).unwrap();
|
||||
let names: Vec<&str> = list["libraries"].as_array().unwrap().iter().map(|l| l["name"].as_str().unwrap()).collect();
|
||||
assert_eq!(names, ["Brand", "Brand (2)"]);
|
||||
assert_eq!(app.ui.status, "Imported library Brand (2)");
|
||||
}
|
||||
}
|
||||
@@ -40,6 +40,13 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
}
|
||||
transform_section(app, ui);
|
||||
divider(ui);
|
||||
// The Gradient tool: the gradient's type and, for a freeform one, how clicks add points (#921).
|
||||
if app.session.tool_id() == "gradient" {
|
||||
section_header(ui, tl!("Gradient"));
|
||||
super::gradient::type_row(app, ui);
|
||||
super::gradient::draw_radios(app, ui);
|
||||
divider(ui);
|
||||
}
|
||||
let is_image = n_sel == 1 && matches!(first.as_ref().map(|n| &n.kind), Some(NodeKind::Image(_)));
|
||||
if is_image {
|
||||
image_section(app, ui);
|
||||
@@ -563,6 +570,31 @@ mod tests {
|
||||
frame(app, ctx, vec![b(false)]);
|
||||
}
|
||||
|
||||
/// #921: with the Gradient tool, a Gradient section: the type, and for a freeform gradient
|
||||
/// Draw as Points or Lines radio buttons.
|
||||
#[test]
|
||||
fn the_gradient_tool_shows_the_gradient_type_and_draw() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 200, "height": 100})).unwrap();
|
||||
let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap()["id"].as_u64().unwrap();
|
||||
app.run("paint.setFill", json!({"gradient": {}})).unwrap();
|
||||
let ctx = egui::Context::default();
|
||||
let has = |texts: &[(String, Rect)], s: &str| texts.iter().any(|(t, _)| t == s);
|
||||
let texts = frame(&mut app, &ctx, vec![]);
|
||||
assert!(!has(&texts, "Gradient"), "only with the Gradient tool");
|
||||
app.select_tool("gradient");
|
||||
let texts = frame(&mut app, &ctx, vec![]);
|
||||
assert!(has(&texts, "Gradient") && has(&texts, "Type:") && !has(&texts, "Draw:"), "{texts:?}");
|
||||
app.run("paint.editGradient", json!({"kind": "freeform"})).unwrap();
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
let texts = frame(&mut app, &ctx, vec![]);
|
||||
assert!(has(&texts, "Draw:") && has(&texts, "Points") && has(&texts, "Lines"), "{texts:?}");
|
||||
click(&mut app, &ctx, &texts, "Lines");
|
||||
let fill = app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().appearance.fill_paint();
|
||||
let vectorcraft_color::Paint::Gradient(g) = fill else { panic!("{fill:?}") };
|
||||
assert_eq!(super::super::gradient::shown_points(&g).mode, vectorcraft_color::FreeformMode::Lines);
|
||||
}
|
||||
|
||||
/// #696: the number fields are all as wide: the Transform fields, the rotation, the corner
|
||||
/// radius, Opacity and the stroke weight.
|
||||
#[test]
|
||||
|
||||
@@ -141,22 +141,20 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
}
|
||||
ui.end_row();
|
||||
ui.label(egui::RichText::new(tl!("Leader:")).color(t.text));
|
||||
let mut leader = stops.get(sel).map(|s| s.leader.clone()).unwrap_or_default();
|
||||
if ui.add_enabled(stops.get(sel).is_some(), egui::TextEdit::singleline(&mut leader).desired_width(90.0)).lost_focus()
|
||||
&& let Some(s) = stops.get_mut(sel)
|
||||
&& s.leader != leader
|
||||
{
|
||||
// The fields keep what is typed until Enter or a click away commits it (#924).
|
||||
let leader = stops.get(sel).map(|s| s.leader.clone()).unwrap_or_default();
|
||||
let typed = ui.add_enabled_ui(stops.get(sel).is_some(), |ui| widgets::exact_text_field(ui, "tabs-leader", &leader, 90.0)).inner;
|
||||
if let (Some(leader), Some(s)) = (typed, stops.get_mut(sel)) {
|
||||
// Up to eight characters repeat in the leader.
|
||||
s.leader = leader.chars().take(8).collect();
|
||||
apply(app, &stops);
|
||||
}
|
||||
ui.end_row();
|
||||
ui.label(egui::RichText::new(tl!("Align On:")).color(t.text));
|
||||
let decimal = stops.get(sel).is_some_and(|s| s.align == TabAlign::Decimal);
|
||||
let mut on = stops.get(sel).map(|s| s.align_on.to_string()).unwrap_or_else(|| ".".into());
|
||||
if ui.add_enabled(decimal, egui::TextEdit::singleline(&mut on).desired_width(30.0)).lost_focus()
|
||||
&& let (Some(s), Some(c)) = (stops.get_mut(sel), on.chars().next())
|
||||
&& s.align_on != c
|
||||
{
|
||||
let on = stops.get(sel).map(|s| s.align_on.to_string()).unwrap_or_else(|| ".".into());
|
||||
let typed = ui.add_enabled_ui(decimal, |ui| widgets::exact_text_field(ui, "tabs-align-on", &on, 30.0)).inner;
|
||||
if let (Some(c), Some(s)) = (typed.and_then(|t| t.chars().next()), stops.get_mut(sel)) {
|
||||
s.align_on = c;
|
||||
apply(app, &stops);
|
||||
}
|
||||
@@ -305,6 +303,62 @@ mod tests {
|
||||
assert_eq!(back[1]["align"], json!("decimal"));
|
||||
}
|
||||
|
||||
/// #924: Leader and Align On keep what is typed, frame after frame, until Enter applies it
|
||||
/// (spaces kept, eight characters at most).
|
||||
#[test]
|
||||
fn leader_and_align_on_keep_what_is_typed_until_enter() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.session.execute("file.new", &json!({})).unwrap();
|
||||
app.session.execute("text.create", &json!({"x": 10, "y": 20, "text": "a b", "area": {"width": 300, "height": 100}})).unwrap();
|
||||
app.session.execute("text.tabs.set", &json!({"stops": [{"position": 50, "align": "decimal"}]})).unwrap();
|
||||
let ctx = egui::Context::default();
|
||||
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(320.0, 400.0));
|
||||
// One frame with `events` → the texts painted and where.
|
||||
let frame = |app: &mut VectorcraftApp, events: Vec<egui::Event>| {
|
||||
let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }, |ui| show(app, ui));
|
||||
out.textures_delta.clear();
|
||||
out.shapes
|
||||
.iter()
|
||||
.filter_map(|c| match &c.shape {
|
||||
egui::Shape::Text(t) => Some((t.galley.text().to_string(), t.visual_bounding_rect())),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
let key = |key| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() };
|
||||
let click = |at| {
|
||||
[true, false].map(|pressed| egui::Event::PointerButton {
|
||||
pos: at,
|
||||
button: egui::PointerButton::Primary,
|
||||
pressed,
|
||||
modifiers: Default::default(),
|
||||
})
|
||||
};
|
||||
let stop = |app: &VectorcraftApp| current(app).unwrap().1[0].clone();
|
||||
for (label, typed, want) in [("Leader:", [". ", "_", "123456789"], ". _12345"), ("Align On:", [",", "", ""], ",")] {
|
||||
let texts = frame(&mut app, vec![]);
|
||||
let r = texts.iter().find(|(t, _)| t == label).unwrap_or_else(|| panic!("{label} in {texts:?}")).1;
|
||||
let at = egui::pos2(r.right() + 30.0, r.center().y);
|
||||
let [down, up] = click(at);
|
||||
frame(&mut app, vec![egui::Event::PointerMoved(at), down]);
|
||||
frame(&mut app, vec![up]);
|
||||
// Select what is there, then type in pieces over several frames.
|
||||
frame(
|
||||
&mut app,
|
||||
vec![egui::Event::Key { key: egui::Key::A, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND }],
|
||||
);
|
||||
for piece in typed.iter().filter(|p| !p.is_empty()) {
|
||||
frame(&mut app, vec![egui::Event::Text(piece.to_string())]);
|
||||
frame(&mut app, vec![]);
|
||||
}
|
||||
frame(&mut app, vec![key(egui::Key::Enter)]);
|
||||
frame(&mut app, vec![]);
|
||||
let s = stop(&app);
|
||||
let got = if label == "Leader:" { s.leader } else { s.align_on.to_string() };
|
||||
assert_eq!(got, want, "{label}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Position Panel Above Text floats the panel over the text, its ruler's 0 on the frame's left
|
||||
/// edge and a stop's mark over the column it sets, at any zoom (#729).
|
||||
#[test]
|
||||
|
||||
@@ -64,6 +64,20 @@ fn effect_menu_lists_the_pixelate_filters_between_blur_and_sharpen() {
|
||||
assert!(at("Blur") < at("Pixelate") && at("Pixelate") < at("Sharpen"));
|
||||
}
|
||||
|
||||
/// Effect › Video, after Sharpen: De-Interlace opens its dialog, NTSC Colors (no options) applies.
|
||||
#[test]
|
||||
fn effect_menu_lists_the_video_filters_last() {
|
||||
let app = app();
|
||||
let entries = menus::menu_entries(&app);
|
||||
let video: Vec<_> = entries.iter().filter(|e| e.path == ["Effect", "Video"]).collect();
|
||||
let items: Vec<(&str, Option<&str>)> = video.iter().map(|e| (e.label.as_str(), e.command.as_deref())).collect();
|
||||
assert_eq!(items, [("De-Interlace…", Some("effect.dialog")), ("NTSC Colors", Some("effect.apply"))]);
|
||||
let raster: Vec<&str> =
|
||||
entries.iter().filter_map(|e| e.path.get(1).filter(|_| e.path.len() == 2 && e.path[0] == "Effect")).map(String::as_str).collect();
|
||||
let at = |name: &str| raster.iter().position(|s| *s == name).unwrap();
|
||||
assert!(at("Sharpen") < at("Video"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn library_submenus_are_disabled_placeholders() {
|
||||
let app = app();
|
||||
|
||||
@@ -124,6 +124,12 @@ pub fn section_header(ui: &mut Ui, text: &str) {
|
||||
/// A collapsible section's header across the panel: a chevron (down while `open`) and `text`;
|
||||
/// a click anywhere on it toggles the section. Whether it was clicked.
|
||||
pub fn section_toggle(ui: &mut Ui, text: &str, open: bool) -> bool {
|
||||
section_toggle_name(ui, tl!(text), open).clicked()
|
||||
}
|
||||
|
||||
/// [`section_toggle`] for a name that is user data (a library group), shown as it is → its
|
||||
/// response (clicked: toggle; it takes a context menu).
|
||||
pub fn section_toggle_name(ui: &mut Ui, text: &str, open: bool) -> Response {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 24.0), Sense::click());
|
||||
if resp.hovered() {
|
||||
@@ -131,9 +137,9 @@ pub fn section_toggle(ui: &mut Ui, text: &str, open: bool) -> bool {
|
||||
}
|
||||
let chevron = Rect::from_center_size(pos2(rect.left() + 8.0, rect.center().y), vec2(12.0, 12.0));
|
||||
icons::paint(ui, if open { "chevron-down" } else { "chevron-right" }, chevron, if resp.hovered() { t.text_strong } else { t.icon });
|
||||
ui.painter().text(pos2(rect.left() + 18.0, rect.center().y), egui::Align2::LEFT_CENTER, tl!(text), theme::semibold(12.5), t.text);
|
||||
resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::CollapsingHeader, true, open, tl!(text)));
|
||||
resp.on_hover_cursor(egui::CursorIcon::PointingHand).clicked()
|
||||
ui.painter().text(pos2(rect.left() + 18.0, rect.center().y), egui::Align2::LEFT_CENTER, text, theme::semibold(12.5), t.text);
|
||||
resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::CollapsingHeader, true, open, text));
|
||||
resp.on_hover_cursor(egui::CursorIcon::PointingHand)
|
||||
}
|
||||
|
||||
/// Full-width 1 px divider with vertical margins.
|
||||
@@ -364,6 +370,14 @@ pub fn text_field(ui: &mut Ui, id: impl std::hash::Hash + std::fmt::Debug, value
|
||||
(resp.lost_focus() && buf.trim() != shown).then(|| buf.trim().to_string())
|
||||
}
|
||||
|
||||
/// A one-line [`text_field`] that keeps the text exactly as typed, spaces included (a tab
|
||||
/// leader such as ". "). Returns it when a change is committed (Enter or focus loss).
|
||||
pub fn exact_text_field(ui: &mut Ui, id: impl std::hash::Hash + std::fmt::Debug, value: &str, width: f32) -> Option<String> {
|
||||
let id = ui.id().with(id);
|
||||
let (buf, resp, _) = recessed_text(ui, id, value, width, 1);
|
||||
(resp.lost_focus() && buf != value).then_some(buf)
|
||||
}
|
||||
|
||||
/// A form row: `label` in a column `label_width` wide, then what `add` draws.
|
||||
pub fn label_row(ui: &mut Ui, label: &str, label_width: f32, add: impl FnOnce(&mut Ui)) {
|
||||
ui.horizontal(|ui| {
|
||||
|
||||
@@ -404,7 +404,9 @@ Missing linked files: `app.open` of a document whose linked images' files can't
|
||||
folder; `ui.dialog.set {field: "discard", value: true}` then confirm ignores it (the images keep their preview), with
|
||||
`applyToAll` the rest too. The next missing file is asked about after each answer; `ui.dialog.cancel` stops asking.
|
||||
Then, with the preference `updateLinks: "askWhenModified"`, modified linked files are offered for update in a
|
||||
`confirm` dialog whose `ui.dialog.confirm` runs `links.update`.
|
||||
`confirm` dialog whose `ui.dialog.confirm` runs `links.update`. The same happens when the app's window comes back to
|
||||
the front and a linked file of the active document changed meanwhile (asked once per change of a file); with
|
||||
`"automatically"` the files are read again at once, with `"manually"` the Links panel shows them as modified.
|
||||
|
||||
Missing fonts: once the missing linked file questions are answered, or at once when there are none, `app.open` of a
|
||||
document whose type uses fonts that aren't available (`text.missingFonts`) opens the `missingFonts` dialog, one document
|
||||
|
||||
+33
-8
@@ -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`). |
|
||||
@@ -953,9 +953,26 @@ gives another colour merges into the document's), a colour paints the selection'
|
||||
to the document (numbered when its name is taken by other attributes) and applied to the selected text, each as one
|
||||
undo step. `library.removeItem {library?, kind, item}` removes one.
|
||||
|
||||
Items can be put in user-named groups, which the panel shows as collapsible sections after the ungrouped items (its
|
||||
search field filters every item by name; `library.get` lists them all to filter). `library.createGroup {library?,
|
||||
name?, items?: [{kind, item}]}` makes one (a name another group has, ignoring case, gets a number) with those items
|
||||
moved into it; `library.renameGroup {library?, group, name}` renames one; `library.deleteGroup {library?, group}`
|
||||
deletes one, its items staying in the library ungrouped; and `library.moveItem {library?, kind, item, group?}` moves
|
||||
an item into a group (without `group`, out of its group). An item is in one group at most; `library.get` lists the
|
||||
groups as `groups: [{name, items: [{kind: "color"|"charStyle"|"paraStyle"|"graphic", item}]}]` (a graphic by its id).
|
||||
|
||||
`library.export {library?, path?}` writes a library (its colours, styles, graphics with their art and thumbnails, and
|
||||
its groups) as a `.vclibrary` file, the JSON the library folder keeps (without `path`: `{data}`, the file's text).
|
||||
`library.import {path? | data? | dataBase64?, name?}` adds the library of such a file as a new library and makes it
|
||||
the current one; a name another library has gets a number (`Brand (2)`). Imported files are checked: at most 10,000
|
||||
items of each kind and 1,000 groups, names clipped and made unique, thumbnails kept only when they are small PNGs, and
|
||||
groups naming items that aren't there dropped. Files written before groups load as they are.
|
||||
|
||||
```json
|
||||
{"name":"run_command","arguments":{"command":"library.add","params":{"kind":"graphic","name":"Logo"}}}
|
||||
{"name":"run_command","arguments":{"command":"library.use","params":{"kind":"graphic","item":"Logo","center":[300,200]}}}
|
||||
{"name":"run_command","arguments":{"command":"library.createGroup","params":{"name":"Logos","items":[{"kind":"graphic","item":"Logo"}]}}}
|
||||
{"name":"run_command","arguments":{"command":"library.export","params":{"path":"/tmp/Brand.vclibrary"}}}
|
||||
```
|
||||
|
||||
## Strokes on type
|
||||
@@ -1380,7 +1397,7 @@ size. The journal entry of a scaling command records the `strokes` and `corners`
|
||||
|
||||
## Live Corners
|
||||
|
||||
`object.setLiveShape {id?, ids?, radius?, kind?, corners?}` sets the corners of any path (one undo step): a live
|
||||
`object.setLiveShape {id?, ids?, radius?, kind?, corners?, items?}` sets the corners of any path (one undo step): a live
|
||||
rectangle's or polygon's, a star's, a pen path's. A corner is an anchor without handles between two straight sides
|
||||
(not an open path's ends, not a smooth anchor, not one the sides run straight on through). `radius` (pt) and `kind`
|
||||
(`round`, `invertedRound` or `chamfer`) go to the `corners` given, else to the corners holding a Direct-Selected
|
||||
@@ -1396,9 +1413,10 @@ draws no larger than takes the cut halfway along the corner's shorter side (half
|
||||
same limit for its four corners), the corners stay circular through uneven scales (the radius scales by the mean scale,
|
||||
or keeps its size with Scale Corners off), and a rectangle from a file that kept an uneven scale in its transform
|
||||
(elliptical corners) gets circular ones in document units when its corners are next set. Dragging a corner widget
|
||||
rounds the corners whose widgets show (every corner, or the Direct-Selected ones), outlining in red those that reach
|
||||
their limit; the Selection tool shows the widgets of live rectangles and polygons, the Direct Selection tool those of
|
||||
any path. Alt-clicking one cycles their kind and double-clicking one opens Corners (`ui.corners {id?, corners?}`,
|
||||
rounds the corners whose widgets show (every corner, or the Direct-Selected ones) on every selected path at once,
|
||||
outlining in red those that reach their limit; the Selection tool shows the widgets of live rectangles and polygons,
|
||||
the Direct Selection tool those of any path. Several objects each with their own corners are one call:
|
||||
`items: [{id, corners?}]` in place of `ids` and `corners`. Alt-clicking one cycles their kind and double-clicking one opens Corners (`ui.corners {id?, corners?}`,
|
||||
dialog `corners`: `kind`, `radius`; OK runs `object.setLiveShape`).
|
||||
|
||||
```json
|
||||
@@ -1690,7 +1708,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
|
||||
@@ -1809,7 +1827,8 @@ the preview instead of the pixels, plus the path relative to the saved file. `do
|
||||
the linked files again, looking for each at its path, then at its relative path and by name in the document's folder
|
||||
(so a folder moved with its links still opens): the result lists `missingLinks` (their images show the preview),
|
||||
`modifiedLinks` (left as they were; read again only with the preference `updateLinks: "automatically"`, then they are
|
||||
in `updatedLinks`), each as `{name, path, ids}`. `links.check` reports every link's `status` (`ok`, `modified`,
|
||||
in `updatedLinks`), each as `{name, path, ids}`. The desktop app also checks the active document's links when its window
|
||||
comes back to the front, following the same preference. `links.check` reports every link's `status` (`ok`, `modified`,
|
||||
`missing`), `links.update {ids?}` reads modified files again and `links.relink {ids?, path | folder}` points images at
|
||||
another file (or each at the file of its name in a folder); images keep their bounds, one undo step each. Without a
|
||||
file system (the web), linked images show their previews.
|
||||
@@ -2288,7 +2307,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