Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4a81e549a2 | ||
|
|
11fceda13e | ||
|
|
ea814b3fac | ||
|
|
b5e39048df | ||
|
|
762bd6b927 | ||
|
|
033ceaff41 | ||
|
|
a2e4206155 | ||
|
|
771981e2b1 | ||
|
|
c7aeaa637f | ||
|
|
965fc449e1 | ||
|
|
67af21c6db | ||
|
|
e0b1f55250 |
No files matched your search
+5
-5
@@ -4,7 +4,7 @@ VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adob
|
||||
|
||||
This file tracks **how far we are and what's left**. Time estimates are wall-clock hours of continuous Claude Opus 5.5 agent work (including builds and the CI gate), given both for **one agent** and for **4–6 parallel agents** on disjoint crates. They are counted from the remaining work (see [Parity estimate](#parity-estimate)), calibrated against measured throughput, and updated as work lands.
|
||||
|
||||
_Last updated: 2026-10-09 (after placed documents (File › Place of a `.vectorcraft` file, linked), M4.14–M4.98, M8.1–M8.20, M14.4–M14.7, the MCP prompts, resource templates, completions and logging, the 2026-10-07 issue fixes, the Layers panel rework and the 2026-10-08 community contributions: Pen and shape-tool modifiers, path editing, Layers, Artboards, Swatches/Brushes and dialogs, Japanese composition and PDF text, Hebrew/Arabic type, interface languages (Spanish among them), the font menu, saved selections, MCP and EPS, the missing-font export warning (#319), open paths in the Shape Builder (#374), PDF/`.ai` import keeping strokes live and hidden and nested layers (#372), per-corner Live Corners (#381), SVG type opening at the size it draws at (#396), the Wayland clipboard with copied-file paste (#398), ruler guides that can be selected, moved and deleted (#414), two batches of Preferences options that were stored but unused (#394), skeleton reads with `document.find` for large documents over MCP (#416) and anchors dragged with Direct Selection snapping to points, segments and smart guides, clipped SVG layers opening as clipping layers (#420), PDF/`.ai` layers read on pages of tens of millions of operators (#419), Document Color Mode putting RGB greys on the black plate on request and converting pattern tiles (#421) and movable dialogs with Offset Path's Joins dropdown (#423) and numeric fields scrubbed by dragging their label (#400), stroke weight presets in the stroke unit (#426), the Appearance panel's Opacity popup (#430), type on a path brackets, flip and Type on a Path Options that keep the type in place (#429), Layers rows dragged with a ghost and dropped on the trash or New Layer (#435), tool flyouts opening on a right or corner press (#436), tool flyouts torn off into floating toolbars (#437), the Shape Builder's erase mode deleting edges too (#439), installed fonts registered outside the font folders and fonts installed while the app runs listed in the font menus (#443), alike circular corners on rectangles that aren't square (#442), tool cursors as OS cursors so the pointer no longer trails over the canvas (#444), artboards copied and pasted with their art (#446), guides dragged out of the rulers snapping to the art's side midpoints and the artboards, artboard guides (#451), the toolbar's double arrow and Window › Toolbars › Double Column switching between one and two columns in any window height (#455), the Smart Guides display options and Snapping Tolerance (#394), Font Size and Leading combo boxes with preset lists in the Character and Properties panels and the Control bar (#458), screenshots pasted from the clipboard on macOS, Windows and the web (#457), the Properties panel's Fill and Stroke matching the Control bar's, Illustrator's Window menu panel keys (Shift+F7 for Align…) and Alt-wheel zoom whatever the wheel preference (Discord feedback), the point/area type widget (Discord feedback), groups in legacy Illustrator .ai files (Discord feedback), a rotating desktop log file (#465), image controls in the Control bar and Properties panel: Image Trace with its presets, Mask, Crop Image, Embed/Unembed, and an Image Trace object's preset, Expand and Release (Discord feedback), the Pen working as the Anchor Point tool with Alt held over a selected path's handles and anchors, and anchor buttons that convert, connect and cut paths at the selected anchors (Discord feedback), Japanese hanging punctuation (burasagari, #463), Escape leaving Presentation Mode with no screen mode saved across restarts, documents dropped on the desktop app opening as tabs of their own and a note that an `.ai` file's art off its artboards isn't in the part read (#472), Add/Delete Anchor Point tool icons drawn from the Pen tool's (#479), EPS import running more of PostScript Level 3 (patterns, Type 3 fonts, mesh shadings, masked images, VM and resource probes), and a preview that stands in saying why (Discord feedback, #466, #469, #474), chords with modifiers recorded in Edit › Keyboard Shortcuts (#487), Type Object Selection by Path Only (#394), Anti-aliased Artwork (#394), Show Pixel Grid (#394), pen and touch taps pressed and lifted within one frame clicking where they tapped and the Linux/Wayland pen-tablet workaround (#491), bounding-box resizes landing on the other objects' anchors and centres with labels, and the Rotate, Scale, Shear and Reflect tools snapping their drags (#482), Shift-drag marquees that toggle the objects or anchors they reach and a Lasso whose Alt subtraction keeps the rest of the selection (#483), the mouse wheel stepping the focused numeric field, the dialogs' and preferences' drag values made such fields (#485), Show The Home Screen When No Documents Are Open (#394), Numbers Without Units Are Points (#394), Auto-Collapse Iconic Panels (#394), the Contextual Task Bar moved by its handle and its More Options menu pinning and resetting its position, a designed macOS DMG windoLine truncated
|
||||
_Last updated: 2026-10-09 (after placed documents (File › Place of a `.vectorcraft` file, linked), M4.14–M4.98, M8.1–M8.20, M14.4–M14.7, the MCP prompts, resource templates, completions and logging, the 2026-10-07 issue fixes, the Layers panel rework and the 2026-10-08 community contributions: Pen and shape-tool modifiers, path editing, Layers, Artboards, Swatches/Brushes and dialogs, Japanese composition and PDF text, Hebrew/Arabic type, interface languages (Spanish among them), the font menu, saved selections, MCP and EPS, the missing-font export warning (#319), open paths in the Shape Builder (#374), PDF/`.ai` import keeping strokes live and hidden and nested layers (#372), per-corner Live Corners (#381), SVG type opening at the size it draws at (#396), the Wayland clipboard with copied-file paste (#398), ruler guides that can be selected, moved and deleted (#414), two batches of Preferences options that were stored but unused (#394), skeleton reads with `document.find` for large documents over MCP (#416) and anchors dragged with Direct Selection snapping to points, segments and smart guides, clipped SVG layers opening as clipping layers (#420), PDF/`.ai` layers read on pages of tens of millions of operators (#419), Document Color Mode putting RGB greys on the black plate on request and converting pattern tiles (#421) and movable dialogs with Offset Path's Joins dropdown (#423) and numeric fields scrubbed by dragging their label (#400), stroke weight presets in the stroke unit (#426), the Appearance panel's Opacity popup (#430), type on a path brackets, flip and Type on a Path Options that keep the type in place (#429), Layers rows dragged with a ghost and dropped on the trash or New Layer (#435), tool flyouts opening on a right or corner press (#436), tool flyouts torn off into floating toolbars (#437), the Shape Builder's erase mode deleting edges too (#439), installed fonts registered outside the font folders and fonts installed while the app runs listed in the font menus (#443), alike circular corners on rectangles that aren't square (#442), tool cursors as OS cursors so the pointer no longer trails over the canvas (#444), artboards copied and pasted with their art (#446), guides dragged out of the rulers snapping to the art's side midpoints and the artboards, artboard guides (#451), the toolbar's double arrow and Window › Toolbars › Double Column switching between one and two columns in any window height (#455), the Smart Guides display options and Snapping Tolerance (#394), Font Size and Leading combo boxes with preset lists in the Character and Properties panels and the Control bar (#458), screenshots pasted from the clipboard on macOS, Windows and the web (#457), the Properties panel's Fill and Stroke matching the Control bar's, Illustrator's Window menu panel keys (Shift+F7 for Align…) and Alt-wheel zoom whatever the wheel preference (Discord feedback), the point/area type widget (Discord feedback), groups in legacy Illustrator .ai files (Discord feedback), a rotating desktop log file (#465), image controls in the Control bar and Properties panel: Image Trace with its presets, Mask, Crop Image, Embed/Unembed, and an Image Trace object's preset, Expand and Release (Discord feedback), the Pen working as the Anchor Point tool with Alt held over a selected path's handles and anchors, and anchor buttons that convert, connect and cut paths at the selected anchors (Discord feedback), Japanese hanging punctuation (burasagari, #463), Escape leaving Presentation Mode with no screen mode saved across restarts, documents dropped on the desktop app opening as tabs of their own and a note that an `.ai` file's art off its artboards isn't in the part read (#472), Add/Delete Anchor Point tool icons drawn from the Pen tool's (#479), EPS import running more of PostScript Level 3 (patterns, Type 3 fonts, mesh shadings, masked images, VM and resource probes), and a preview that stands in saying why (Discord feedback, #466, #469, #474), chords with modifiers recorded in Edit › Keyboard Shortcuts (#487), Type Object Selection by Path Only (#394), Anti-aliased Artwork (#394), Show Pixel Grid (#394), pen and touch taps pressed and lifted within one frame clicking where they tapped and the Linux/Wayland pen-tablet workaround (#491), bounding-box resizes landing on the other objects' anchors and centres with labels, and the Rotate, Scale, Shear and Reflect tools snapping their drags (#482), Shift-drag marquees that toggle the objects or anchors they reach and a Lasso whose Alt subtraction keeps the rest of the selection (#483), the mouse wheel stepping the focused numeric field, the dialogs' and preferences' drag values made such fields (#485), Show The Home Screen When No Documents Are Open (#394), Numbers Without Units Are Points (#394), Auto-Collapse Iconic Panels (#394), the Contextual Task Bar moved by its handle and its More Options menu pinning and resetting its position, a designed macOS DMG windoLine truncated
|
||||
|
||||
## Where we are
|
||||
|
||||
@@ -143,9 +143,9 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist
|
||||
- **Type:** Text Wrap, Type on a Path effects (Rainbow/Skew/3D Ribbon/Stair Step/Gravity) and Options (Flip, Align to Path, Spacing; OK keeps the type where it is), type on a path's start, centre and end brackets (Selection and Direct Selection drag them to set where the type runs, slide it along its path and, across the path, flip it: #429), Character and Paragraph Styles (override-preserving redefine), paragraph attributes per paragraph (alignment, indents, spacing, hyphenation, hanging punctuation, tab stops, paragraph style, direction, mojikumi and leading model; the Paragraph, Tabs and Paragraph Styles panels act on the paragraphs the Type tool's selection or caret touches, Return continues the paragraph's style, threads and SVG keep them), Area Type Options (rows/columns/inset/first baseline, vertical Align Top/Center/Bottom/Justify per row/column, reflowing non-rectangular frames and text wrap), threaded text across any closed shapes, Fit Headline, the Every-line Composer for justified and ragged text (paragraph-wide breaks for an even rag, Single-line per object from the Paragraph panel menu or `text.setFormat {composer}`). Area type resizes like Illustrator's type areas: a bounding-box handle drag (Selection tool) or Area Type Options Width/Height size the frame and the text reflows at its size (threads too); Direct Selection drags a frame corner or edge (`text.reshapeArea`). Point type still scales. Auto Size: the frame height follows the text after every edit, in the same undo step (rectangular frames of horizontal type in one row; columns get the least height that holds them; a height set by hand or threading turns it off), and the "Auto Size New Area Type" preference gives it to new area type. Shrink Text to Fit (beyond Illustrator): overflowing area type scales its sizes, leading and baseline shifts down by the largest factor (in 0.1 pt steps of the first run, down to a minimum percentage) that fits, at layout time so every export sees it. `text.areaOptions` and `document.inspect` report overflow and the shrink factor. The Selection tool shows the type widget beside selected type's bounding box (hollow on point type, filled on area type); double-clicking it converts between them (Type › Convert To Area Type / Convert To Point Type), keeping the text and its styles in place. Variable fonts list every named instance as a style of their family (Figtree Light to Black and their italics, Bahnschrift, Segoe UI Variable), and the instance chosen is shaped, drawn, outlined and measured at its axis settings; PDF and SVG embed it as that instance. Variation axis sliders are not done. Beyond Illustrator: inline graphics (`text.insertInline`, Type ▸ Insert Inline Symbol) set a document symbol in a run of type as one character that flows, wraps and justifies like a glyph (InDesign-style inline objects, e.g. mana symbols in card rules text): sized to a multiple of the font size, centred on the cap height, opening up tall lines, following Redefine Symbol; a character of its run's size for Character Alignment and Top-to-Top leading, placed by the bidi reordering in right-to-left text (a neutral U+FFFC); drawn on the canvas, kept as live text plus a `<use>` in SVG and as vector art in PDF; Backspace removes it whole. Hebrew and Arabic are laid out right to left with the Unicode bidirectional algorithm (embedded Latin and numbers keep their direction, lines put in visual order after wrapping) in point, area and path type, with caret, selection and arrow keys in visual order; each paragraph's direction comes from its first strong character unless Paragraph Direction sets it (Paragraph panel with Show Indic Options, `text.setFormat {direction}`), and new type aligns to the start of its direction. SVG export outlines right-to-left text. Font Size and Leading are combo boxes in the Character and Properties panels (Font Size in the Control bar too, beside the Character link, font family and style): type, step with ↑/↓ or the spinner, scrub the label, or pick a preset (6–72 pt, shown in the type unit; Leading also Auto), each pick one undo step; Kerning and Tracking list -100…200; a size, leading, kerning or tracking the selected text doesn't share shows blank (#458).
|
||||
- **Interface languages, vertical type:** VectorCraft ▸ Language (or Preferences ▸ User Interface) picks Automatic (the system locale) or a registered language, persisted as `interfaceLanguage`. Translations come from per-language catalogs (`i18n/*.tsv`): Traditional and Simplified Chinese, Japanese, Spanish (neutral international Spanish, for every `es-*` locale), French (every `fr-*` locale), Italian (every `it-*` locale) and Russian (every `ru-*` locale) cover the whole interface, Czech and Brazilian Portuguese every menu label, Brazilian Portuguese the shell's `tl!` literals too (tested); Spanish, French, Italian and Russian also translate status-bar and error messages as they are shown (`@msg` templates, every message literal tested; the messages themselves stay English for agents); untranslated text stays English. Japanese and Chinese glyphs come from the craft-fonts build input (release builds) or the installed fonts, Czech, Spanish, French, Italian and Russian ones from the bundled UI fonts. The web app follows the browser's languages (or `?lang=`). The Basic toolbar's Type button holds Vertical Type in its flyout. Vertical Type, Vertical Area Type and Vertical Type on a Path create vertical text (columns right to left, upright CJK glyphs and marks with `vert` alternates, Latin and longer numbers on their side, two- and three-digit numbers set as tate-chu-yoko in one em of the column (kept whole when justified), upright glyphs centred on the column (tracked or justified too), point type's anchor on the first column's centre line); kinsoku (the strict set) applies to horizontal and vertical Japanese, and justified Japanese lines spread their room between characters (not inside Latin words); Paragraph panel › Mojikumi Set (shown with Preferences › Type › Show East Asian Options, `text.setFormat {mojikumi}`): None or Line-end Punctuation Half Width (new type's default, as in Illustrator; older documents and imported text keep None) shares one half-em space between consecutive punctuation, sets a closing mark ending a line half width and an opening bracket starting a wrapped line flush with its start, and puts a quarter em between Japanese and Latin letters or digits; Paragraph panel menu › Top-to-Top / Bottom-to-Bottom Leading measures leading from em box top to top (area type's first line touches the frame) or from baseline to baseline (new type in a Japanese interface starts top to top, with em box centre character alignment, #432); Paragraph panel menu › Burasagari None / Regular / Force (`text.setFormat {burasagari: "none"|"standard"|"forced"}`) hangs an East Asian comma or full stop (、。,.、。) ending an area type line outside it, Regular (new type's default) when it doesn't fit and Force always (the rest of the line then fills the measure; closing brackets and Latin punctuation don't hang); Character panel menu › Character Alignment (with the East Asian options; `text.setFormat` or `text.setRangeStyle {charAlign}`) lines characters smaller than the largest on their line up on the Roman baseline, the em box top/right, centre or bottom/left, or the ICF (ideographic character face) top/right or bottom/left, from the font's BASE table or, without one, the average ink box of some ideographs and kana; Type ▸ Type Orientation switches existing text; caret, selection, hit testing and arrow keys follow the writing direction. Vertical text exports to PDF as real text and to SVG as outlines.
|
||||
- **Transparency:** opacity masks (clip/invert/disable/link), exported as SVG `<mask>` and PDF soft masks.
|
||||
- **Advanced art:** live Blends (steps/distance/smooth colour, editable spine, anchor-targeted Blend tool, faithful interpolation, knockout), Envelope Distort (warp/mesh/top object, Reset, full Envelope Options, mesh handles, Edit Contents; type, images, symbols, gradients, patterns and appearance distorted everywhere), Liquify tools with options and pen pressure, Puppet Warp with rotating pins, Perspective Grid with presets, movable planes and projected type (choosing a perspective tool shows the grid; Hide Grid hides it with the tool still chosen), Gradient Mesh, Shape Builder (stroke-only open paths and lines cut the regions they cross and enclose regions of their own; filled open paths count as closed; erase mode while Alt/Option is held: a minus pointer, red highlights of what will go, a click or drag deletes the regions touched, the pieces of open lines and the edges (outline pieces between the points where paths meet, opening their paths there) it passes over, one undo step, `shapeBuilder.merge {erase}` and `shapeBuilder.regions` edges over MCP), Live Paint (every path an edge, open lines included), Image Trace (12 presets, colour layers traced in parallel; a trace past two million anchor points or an image over 64 megapixels is refused with advice rather than running out of memory, and a selection too large to outline shows its bounds (#525); Object › Image Trace › Make and Make and Expand trace at once with the Default preset, #543; with an image selected the Control bar and the Properties panel show Image Trace, whose arrow traces with any preset, Mask (`object.maskImage`: a clipping path on the image's outline, selected so its handles crop), Crop Image and Embed or Unembed in place of Fill and Stroke; with an Image Trace object selected, its Preset (choosing another traces again), the Image Trace panel and Expand, plus Release in Properties; the View modes are not done), pattern swatches with pattern editing mode, live Repeat (radial/grid/mirror).
|
||||
- **Advanced art:** live Blends (steps/distance/smooth colour, editable spine, anchor-targeted Blend tool, faithful interpolation, knockout), Envelope Distort (warp/mesh/top object, Reset, full Envelope Options, mesh handles, Edit Contents; type, images, symbols, gradients, patterns and appearance distorted everywhere), Liquify tools with options and pen pressure, Puppet Warp with rotating pins, Perspective Grid with presets, movable planes and projected type (choosing a perspective tool shows the grid; Hide Grid hides it with the tool still chosen), Gradient Mesh, Shape Builder (stroke-only open paths and lines cut the regions they cross and enclose regions of their own; filled open paths count as closed; erase mode while Alt/Option is held: a minus pointer, red highlights of what will go, a click or drag deletes the regions touched, the pieces of open lines and the edges (outline pieces between the points where paths meet, opening their paths there) it passes over, one undo step, `shapeBuilder.merge {erase}` and `shapeBuilder.regions` edges over MCP), Live Paint (every path an edge, open lines included), Image Trace (12 presets, colour layers traced in parallel; a trace past two million anchor points or an image over 64 megapixels is refused with advice rather than running out of memory, and a selection too large to outline shows its bounds (#525); Object › Image Trace › Make and Make and Expand trace at once with the Default preset, #543; with an image selected the Control bar and the Properties panel show Image Trace, whose arrow traces with any preset, Mask (`object.maskImage`: a clipping path on the image's outline, selected so its handles crop), Crop Image and Embed or Unembed in place of Fill and Stroke; with an Image Trace object selected, its Preset (choosing another traces again), the Image Trace panel and Expand, plus Release in Properties; Color mode's Palette: Limited, Full Tone (as many colours as the tones need, Less … More), Automatic (flat art with its own colours, else Full Tone; a heuristic) and Document Library (the most used colours of the document's swatches or a swatch library, filled with the swatch colours as they are), part of #641; the View modes and Create Strokes are not done), pattern swatches with pattern editing mode, live Repeat (radial/grid/mirror).
|
||||
- **Paint and appearance (M3):**
|
||||
- **Swatches:** names follow the colour model and are unique; Swatch Options (process/spot, Global, Gray/RGB/HSB/CMYK/Web, live preview); editing a global or spot swatch recolours every linked fill, stroke and text run in one undo step; multi-select and delete with confirmation; New Swatch and New Color Group dialogs (a group from the selected artwork's colours); swatches in colour groups convert, separate and count like any other. The Swatches panel selects ranges and whole groups, has a find field, and drags swatches to reorder, regroup or paint art; Add Used Colors, Select All Unused, Merge, Ungroup and Sort by Kind; a CMYK document keeps applied colours in CMYK. Swatch libraries: nine generated colour libraries and five gradient libraries in a library panel, saved and loaded as `.vcswatches`, `.gpl` or CSS. Tints of global and spot colours ("Name 40%") stay linked and separate as a percentage of their plate. Spot colours can be defined in Lab (Spot Colors options). A built-in [Registration] swatch prints on every plate.
|
||||
- **Swatches:** names follow the colour model and are unique; Swatch Options (process/spot, Global, Gray/RGB/HSB/CMYK/Web, live preview); editing a global or spot swatch recolours every linked fill, stroke and text run in one undo step; multi-select and delete with confirmation; New Swatch and New Color Group dialogs (a group from the selected artwork's colours); swatches in colour groups convert, separate and count like any other. The Swatches panel selects ranges and whole groups, has a find field, and drags swatches to reorder, regroup or paint art; Add Used Colors, Select All Unused, Merge, Ungroup and Sort by Kind; a CMYK document keeps applied colours in CMYK. Swatch libraries: nine generated colour libraries and five gradient libraries in a library panel, saved as `.vcswatches`, `.gpl` or CSS, and loaded from `.vcswatches`, `.gpl` and swatch exchange (`.ase`) files (RGB, CMYK, Lab and Gray; global, spot and process; groups). Tints of global and spot colours ("Name 40%") stay linked and separate as a percentage of their plate. Spot colours can be defined in Lab (Spot Colors options). A built-in [Registration] swatch prints on every plate.
|
||||
- **Colour:** a Color Picker (colour field, H/S/B/R/G/B channel slider, HSB/RGB/Lab/CMYK fields, hex, web-only snapping, out-of-gamut correction); the Color panel follows each colour's own model and Alt-click paints the other proxy; proxies look through groups and show "?" for mixed paint; Invert, Complement, Apply Last Color (`,`) and Apply Last Gradient (`.`) keep the colour model; every paint command feeds the recent colours. The Color Guide has 21 harmony rules, Steps and Variation options and Limit to Library. Adjust Color Balance (its Global mode shifts tints) and Saturate preview live; Edit Colors and Recolor also reach meshes, images and patterns. Recolor Artwork has colour reduction, five recolour methods, presets, Limit to Library, a colour-wheel Edit tab and Edit Color Group; a local Color Themes panel saves five-colour themes. Fill/Stroke chips open swatch and mixer popovers (the Properties panel has the Control bar's Fill and Stroke chips, Stroke link and weight spinner, with nothing selected too), panels have Illustrator's Window menu keys (Align Shift+F7, Transform Shift+F8, Pathfinder Cmd+Shift+F9, Layers F7, Character Cmd+T…; every panel can be given one in Edit › Keyboard Shortcuts), and Eyedropper Options pick up and apply chosen attributes (Alt and Shift+Alt, image pixels). Fills and strokes can overprint (Attributes panel, Overprint Black options), and CMYK documents blend in inks on screen, in PDF and when flattening. Document Color Mode converts the art, symbols, pattern tiles and swatches through the colour settings: Gray stays Gray, RGB greys separate into four-colour greys and a rich black as Illustrator does, or go on the black plate only with `grays: "black"` (also for `document.open {colorMode}`).
|
||||
- **Gradients:** lossless, validated gradient params; gradients follow rotate, reflect, shear, non-uniform scale and distortions; the Gradient tool edits the fill or stroke of the active proxy, type included; an interactive on-canvas annotator (move, length/angle, rotate, add/move/delete/duplicate stops, midpoints, a stop popover, Delete and arrow keys). The Gradient panel has the Fill/Stroke proxy, a gradient-swatch dropdown with Save to Swatches, midpoint locations, Alt-drag to copy or swap stops, swatch drops on the ramp and a stop eyedropper; copied appearances and graphic styles place gradients on each target's own bounds; gradient handles snap and honour Constrain Angle. Gradient stops stay linked to global and spot swatches. Freeform gradients (points and lines) are edited on the canvas; radial gradients have an extent ellipse, an aspect handle and an off-centre focal point (SVG `fx`/`fy`, PDF two-point radials). A stroke's gradient runs within, along or across it. Object ▸ Expand turns gradients into N objects or a gradient mesh.
|
||||
- **Strokes:** one stroke-geometry module shared by the canvas, SVG, PDF and Outline Stroke; dotted lines (zero-length dashes draw dots or squares); arrowheads with hollow outlines, tip-on-end or extend-past-end alignment and one opacity for line and head. SVG and PDF export arrowheads, width profiles, brushes and aligned strokes exactly as the canvas draws them; Outline Stroke and the live Outline Stroke effect outline every stroke item as drawn (dashes, heads, profiles, alignment); dashes can be fitted to corners and path ends; width profiles carry through dashes, and their corners take the join. The Stroke panel edits type's character strokes, follows the stroke units (its weight presets are round values in that unit: `0.25 mm`, `0.0625 in`, `1 px`, #426; fields show four decimals in mm, cm and inches, three in points), shows mixed values blank and opens from the Control bar. A width profile library, thirty more arrowheads, and Width Point Edit with multi-select and discontinuous points. Visual bounds and clicks cover the whole painted stroke. Scale Strokes & Effects, Scale Corners and Use Preview Bounds work everywhere, and new art inherits stroke options, a graphic style or the whole last appearance.
|
||||
@@ -158,7 +158,7 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist
|
||||
- **Fonts:** a font is found by any of its names (family and style in every language of its name table, legacy family/style pairs, PostScript name), so documents from other apps open with the font they name; Find Font and `text.fonts` say for each font whether it was found exactly, by another name, substituted or missing, and how many glyphs are missing. PDF and `.ai` import brings Japanese text back as live type: CID fonts without a ToUnicode map read through the standard CMaps, vertical columns (WMode 1) as vertical type, letter spacing as tracking; a glyph is live type only when the installed font (in the closest style of its family) draws the same glyph, and text in a font that isn't installed comes in as live type shown in the fallback font until the font is installed (exports that draw it — PDF, EPS, EMF/WMF, raster, SVG outlines or embedded fonts — warn that they wrote the fallback font; `textAs: outlines` keeps the PDF's embedded glyphs).
|
||||
- **Files (M4):**
|
||||
- `.vectorcraft` (lossless JSON, compressed, atomic saves, save down to v1), Save As with a format chooser, Save a Copy, Revert, templates, Data Recovery after a crash (browser tabs hold their copies with Web Locks too, so a background tab's copies are never taken for a crash's, and a tab repairs copies another removed when it resumes: #367), background save and export. The desktop app writes its warnings and errors (graphics adapter, a lost graphics device, panics the guard recovered from) to standard error and to `logs/vectorcraft.log` next to the preferences, the two previous runs kept and each file capped at 16 MiB, so a launch without a terminal still leaves something to attach to a bug report (#465).
|
||||
- SVG/SVGZ in and out with SVG Options, Preserve Editing, symbols, filters, rich text and physical units (SVG type under a transform or `viewBox` scale opens at the size it draws at, the scale moved into its size, leading, baseline shift and strokes, a stretch, skew or rotation kept as its transform: #396; a top-level group with a clip path, such as a clipped Inkscape layer, opens as a layer with a clipping mask, its name kept: #420; 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; nested groups stay groups, except the sublayers VectorCraft writes, marked `data-vc-layer`, and Inkscape sublayers, which open as sublayers in their layer's colour: #372); PDF and PDF-compatible `.ai` in and out (layers, with hidden ones kept hidden with their art and nested ones as sublayers, on pages of up to 64 million operators, art whose layer can't be told going to a hidden, non-printing layer rather than showing or printing: #419; strokes kept live, a fill and a stroke of one outline as one object; a type object's stroke written as each glyph's outline stroked back on the type, so it stays one editable object; lines wrapped in a frame (each wrapped line ending in a space, one left edge, leading and font) back as one area type object, left aligned or justified with its paragraph spacing, where laying it out breaks the lines where the file does; glyphs set apart by gaps wider than a space (a barcode's digit groups) keeping their places; layers stacked as the pages mark them even when one first paints on a later page, art ending a layer's marked content or a clip closing in a later layer kept in its own layer, and layers with no art kept empty: #508; masks, editable text with type set along a curve coming back as type on a path, each artboard's art on its own page only, an `.ai`'s white page under its layers left out rather than coming in as art, spot colours, presets, security, marks and bleed, ICC output intents, raster effects, subset fonts, PDF/X, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3). CMYK images keep their ink amounts from PDF import (and from placed CMYK TIFFs) to PDF export: a CMYK JPEG passes through unchanged, others stay CMYK (DeviceCMYK, or ICC-based CMYK in PDF/X-3/X-4) unless the Output settings convert them; the canvas shows them through the working CMYK profile (#320).
|
||||
- SVG/SVGZ in and out with SVG Options, Preserve Editing, symbols, filters, rich text and physical units (SVG type under a transform or `viewBox` scale opens at the size it draws at, the scale moved into its size, leading, baseline shift and strokes, a stretch, skew or rotation kept as its transform: #396; a top-level group with a clip path, such as a clipped Inkscape layer, opens as a layer with a clipping mask, its name kept: #420; hidden objects written hidden on Save and `convert`, and `data-*` attributes kept as the objects' own data: #522; top-level groups open as layers named from `data-name`, else the id, also when one more group (a transform on all the art, a `<switch>`) wraps them, hidden ones hidden, and a file whose art sits loose under a root `<svg>` with an id (or `data-name`), as one-layer exports write it, opens with its one layer named from it; nested groups stay groups, except the sublayers VectorCraft writes, marked `data-vc-layer`, and Inkscape sublayers, which open as sublayers in their layer's colour: #372); PDF and PDF-compatible `.ai` in and out (layers, with hidden ones kept hidden with their art and nested ones as sublayers, on pages of up to 64 million operators, art whose layer can't be told going to a hidden, non-printing layer rather than showing or printing: #419; strokes kept live, a fill and a stroke of one outline as one object; a type object's stroke written as each glyph's outline stroked back on the type, so it stays one editable object; lines wrapped in a frame (each wrapped line ending in a space, one left edge, leading and font) back as one area type object, left aligned or justified with its paragraph spacing, where laying it out breaks the lines where the file does; glyphs set apart by gaps wider than a space (a barcode's digit groups) keeping their places; layers stacked as the pages mark them even when one first paints on a later page, art ending a layer's marked content or a clip closing in a later layer kept in its own layer, and layers with no art kept empty: #508; masks, editable text with type set along a curve coming back as type on a path, each artboard's art on its own page only, an `.ai`'s white page under its layers left out rather than coming in as art, spot colours, presets, security, marks and bleed, ICC output intents, raster effects, subset fonts, PDF/X, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3). CMYK images keep their ink amounts from PDF import (and from placed CMYK TIFFs) to PDF export: a CMYK JPEG passes through unchanged, others stay CMYK (DeviceCMYK, or ICC-based CMYK in PDF/X-3/X-4) unless the Output settings convert them; the canvas shows them through the working CMYK profile (#320).
|
||||
- EPS and DXF in and out, EMF/WMF in and out; PNG (with PNG-8), JPEG, WebP, GIF, TIFF, BMP, Targa and layered PSD export. EPS import runs a PostScript Level 3 interpreter written from the PostScript Language Reference: resource categories and `resourceforall`, local and global VM (`currentglobal`/`setglobal`/`gcheck`), `clipsave`/`cliprestore`, subarrays and substrings that share storage, the standard dictionaries in `systemdict`, `dictstack`, `internaldict`, executable filters and strings, `load` by any key, `//name` immediate names, `token`, `execform`, user paths, `cshow`, `rootfont`, `cachestatus`, colour rendering and halftone queries, file `status` and data read with `flushfile`, and `pdfmark` marks dropped (Discord feedback, #466, #469, #474). Masked images (`ImageType 3` in its three interleavings) and reusable streams are read, and an image's several data sources are read in turn, as the reference defines (procedures that read one file get their own rows: such images came in banded, #498). `restore` puts dictionaries back as they were at the `save`, so programs that count their saves in a dictionary read to their end (part of #505). Tiling patterns come in as pattern swatches, uncoloured ones too; Type 3 fonts' glyphs as their outlines, spaced by `ashow`/`widthshow`/`xshow`/`kshow`; mesh and function-based shadings (types 1, 4–7) as gradient meshes; sampled functions (type 0) and Flate/LZW predictors are read. It is tested with programs written from the specification in the ways common generators use these features; Inkscape/cairo EPS files open as vectors. When a file's PostScript still can't be read, it opens as its TIFF preview, its Windows metafile preview (as vectors) or its EPSI preview, and the warning (in the status bar, `document.open`/`app.open`/MCP `open_file` replies and `vectorcraft-cli info`) names the error, the operator that raised it and the procedures it ran in. Legacy PostScript `.ai` files (Illustrator 3–8, written with the prolog that defines their operators) keep their groups and nested groups (`u` … `U`), between and inside clipping groups; EPS and EMF/WMF import nest clips (and groups) at most 128 deep, so a hostile file can't exhaust the stack. DXF TEXT justified Fit or Aligned spans its two points (stretched, or scaled as a whole).
|
||||
- Placed documents: File › Place of a `.vectorcraft` file links to it by default (`file.place`'s `link`): one locked object showing an artboard of the document (or its art's bounds), read the way placing it without Link reads it, its symbols, patterns and images kept apart from the document's; without Link (or from bytes, not a file) it is an editable copy as before. It stays vectors in every output (SVG, PDF, EPS, EMF, DXF), and so do placed documents inside it, read from their own files up to 8 levels deep (documents that place each other stop there). On screen they draw from bitmaps cached per file and zoom step, shared by every copy and made in the background (a placeholder until ready), so a sheet of them redraws in about a millisecond; exports and prints draw them exactly. Like linked images, a save keeps only a preview of each (JPEG when opaque) unless Include Linked Files; output, and zooming past the preview, read the file again, falling back to the preview with a warning when it is gone or changed. Saves for older versions write them as plain art. Links check, update, relink, Update Links on open, Link Info (the artboard's size), Placement Options, Break Link (also Embed, Object › Expand: the editable copy placing without Link gives, its resources joining the document), Edit Original (the document in a new tab) and the Links panel cover them; saving a document updates the open documents that place it. The native format (v4) keeps data of 8 KB or more after the JSON instead of base64 in it.
|
||||
- Place and the Links panel, Package, File Info, Print with print presets, PostScript output and print tiling, slices and Save for Web, Export for Screens and Asset Export, CSS Properties, PNG/PDF/SVG/text clipboard flavours; files copied in a file manager paste as art (SVG, PDF, EMF/WMF, bitmaps) on every desktop platform, and Linux/Wayland reads the compositor's clipboard (#398); on Linux the Paste menu checks the clipboard off the UI thread, so an X11 owner that never answers can't freeze the window (#510); screenshots and other copied pictures paste as embedded images at the view centre everywhere, the web included (#457).
|
||||
@@ -215,7 +215,7 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale)
|
||||
| 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), kinsoku sets 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 |
|
||||
| Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | symbol libraries (original), dynamic symbols, envelope Anti-Alias/Preserve Shape output and warp point editing, brush interpolation in blends (M8 fidelity pass done) | 5–8 |
|
||||
| Image Trace, graphs, image tools | 3 | 70% | graph Design/Column/Marker, Create Object Mosaic, Crop Image polish (an on-canvas crop box), Image Trace View modes (Outlines, Source Image) (Vector Halftone is done) | 6–10 |
|
||||
| Image Trace, graphs, image tools | 3 | 70% | graph Design/Column/Marker, Create Object Mosaic, Crop Image polish (an on-canvas crop box), Image Trace View modes (Outlines, Source Image) and Create Strokes (Vector Halftone and the Image Trace Palette are done) | 6–10 |
|
||||
| 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 presets/rearrange polish (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 | 84% | global/video rulers, Spacing Guides, 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) | 2–4 |
|
||||
|
||||
@@ -31,3 +31,7 @@ sync_github_name = true
|
||||
|
||||
[people.omd0]
|
||||
sync_github_name = true
|
||||
|
||||
[people.dotCooCoo]
|
||||
real_name = "Robert Lee"
|
||||
sync_github_name = true
|
||||
@@ -1,6 +1,9 @@
|
||||
//! Swatch library files: the native `.vcswatches` JSON (colour models, global, spot, gradients
|
||||
//! and colour groups exactly), `.gpl` palettes (8-bit RGB; colour groups as `# Group:` comment
|
||||
//! headers) and CSS custom properties (written only).
|
||||
//! headers) and CSS custom properties (written only). Swatch exchange files (`.ase`) are read
|
||||
//! only ([`read_bytes`]).
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
@@ -58,6 +61,15 @@ struct NativeFile {
|
||||
const NATIVE_FORMAT: &str = "vcswatches";
|
||||
const GPL_HEADER: &str = "GIMP Palette";
|
||||
const GPL_GROUP: &str = "# Group:";
|
||||
const ASE_SIGNATURE: &[u8] = b"ASEF";
|
||||
const ASE_GROUP_START: u16 = 0xC001;
|
||||
const ASE_GROUP_END: u16 = 0xC002;
|
||||
const ASE_COLOR: u16 = 0x0001;
|
||||
/// The most colors and groups read from one `.ase` file.
|
||||
const ASE_MAX_ENTRIES: usize = 100_000;
|
||||
/// The most UTF-16 code units of a name that are kept.
|
||||
const ASE_MAX_NAME: usize = 1024;
|
||||
const ASE_CUT_SHORT: &str = "the swatch exchange file is cut short";
|
||||
|
||||
/// Write `lib` in `format`. Pattern swatches (their tiles live in a document) and None are left
|
||||
/// out; `.gpl` keeps solid colours only, as 8-bit RGB.
|
||||
@@ -199,16 +211,34 @@ pub fn sniff(text: &str) -> bool {
|
||||
t.starts_with(GPL_HEADER) || (t.starts_with('{') && t.contains(NATIVE_FORMAT))
|
||||
}
|
||||
|
||||
/// Read the bytes of a library file: a swatch exchange `.ase` file, else a `.vcswatches` or
|
||||
/// `.gpl` library ([`read`]). `name` names it when the file doesn't.
|
||||
pub fn read_bytes(bytes: &[u8], name: &str) -> Result<SwatchLibrary, String> {
|
||||
if bytes.starts_with(ASE_SIGNATURE) {
|
||||
return read_ase(bytes, name);
|
||||
}
|
||||
read(&String::from_utf8_lossy(bytes), name)
|
||||
}
|
||||
|
||||
/// Are `bytes` a library [`read_bytes`] understands? Text that isn't valid UTF-8 is checked as
|
||||
/// [`read_bytes`] reads it, with the invalid bytes replaced (its first KiB is enough).
|
||||
pub fn sniff_bytes(bytes: &[u8]) -> bool {
|
||||
bytes.starts_with(ASE_SIGNATURE)
|
||||
|| std::str::from_utf8(bytes).is_ok_and(sniff)
|
||||
|| sniff(&String::from_utf8_lossy(bytes.get(..1024).unwrap_or(bytes)))
|
||||
}
|
||||
|
||||
/// `.gpl`: `Name:` names the library, `# Group: name` starts a colour group, other `#` lines and
|
||||
/// headers (`Columns:`) are skipped, as are lines that aren't `r g b [name]`. Unnamed colours are
|
||||
/// named by their values; repeated names get a number.
|
||||
/// headers (`Columns:`) are skipped, as are lines that aren't `r g b [name]`. Unnamed colors are
|
||||
/// named by their values and unnamed groups "Color Group"; a name a color or group already has gets
|
||||
/// a number ([`UniqueNames`]).
|
||||
fn read_gpl(text: &str, fallback: &str) -> SwatchLibrary {
|
||||
let mut lib = SwatchLibrary { name: fallback.into(), ..Default::default() };
|
||||
let mut names: Vec<String> = vec![];
|
||||
let mut names = UniqueNames::default();
|
||||
for line in text.lines().skip(1) {
|
||||
let line = line.trim();
|
||||
if let Some(g) = line.strip_prefix(GPL_GROUP) {
|
||||
lib.groups.push(SwatchGroup { name: g.trim().to_string(), swatches: vec![] });
|
||||
lib.groups.push(SwatchGroup { name: names.unique(group_name(g)), swatches: vec![] });
|
||||
continue;
|
||||
}
|
||||
if let Some(n) = line.strip_prefix("Name:") {
|
||||
@@ -221,9 +251,7 @@ fn read_gpl(text: &str, fallback: &str) -> SwatchLibrary {
|
||||
let [r, g, b] = rgb[..] else { continue };
|
||||
let rest = words[3..].join(" ");
|
||||
let base = if rest.is_empty() { format!("R={r} G={g} B={b}") } else { rest };
|
||||
let name = (1..).map(|i| if i == 1 { base.clone() } else { format!("{base} {i}") }).find(|n| !names.contains(n)).unwrap_or(base);
|
||||
names.push(name.clone());
|
||||
let w = Swatch { name, paint: Paint::solid(Color::rgb8(r, g, b)), global: false, spot: false };
|
||||
let w = Swatch { name: names.unique(base), paint: Paint::solid(Color::rgb8(r, g, b)), global: false, spot: false };
|
||||
match lib.groups.last_mut() {
|
||||
Some(grp) => grp.swatches.push(w),
|
||||
None => lib.swatches.push(w),
|
||||
@@ -232,6 +260,184 @@ fn read_gpl(text: &str, fallback: &str) -> SwatchLibrary {
|
||||
lib
|
||||
}
|
||||
|
||||
/// `.ase`, from public descriptions of the format: the layout from
|
||||
/// <https://www.selapa.net/swatches/colors/fileformats.php>, the component ranges from
|
||||
/// <https://github.com/nsfmc/swatch>. After the signature come, big-endian, a `u16` major (1) and
|
||||
/// minor version, a `u32` block count and the blocks, each a `u16` type, a `u32` body length and
|
||||
/// the body. A group start's body is a name. A color's body is a name, a four-character model
|
||||
/// (`RGB `, `CMYK`, `LAB `, `Gray`), its components as `f32` (3, 4, 3 and 1 of them) and a `u16`
|
||||
/// color type (0 global, 1 spot, 2 process). RGB, CMYK and gray components run from 0 to 1 (a
|
||||
/// gray level of 1 is white), Lab lightness from 0 to 1 and a and b from −128 to 127. A lightness
|
||||
/// above 1 is read as L* itself. A name is a `u16` count of UTF-16 code units, the terminating zero
|
||||
/// included, then the units.
|
||||
///
|
||||
/// Color groups become groups: a group start inside an open group ends that group, and a group
|
||||
/// left open ends with the file. Blocks of other types and colors in other models are skipped.
|
||||
/// Unnamed colors are named by their values and unnamed groups "Color Group"; a name a color or
|
||||
/// group already has gets a number ([`UniqueNames`]). A truncated file, a major version other than
|
||||
/// 1 or more than [`ASE_MAX_ENTRIES`] colors and groups is an error.
|
||||
fn read_ase(bytes: &[u8], fallback: &str) -> Result<SwatchLibrary, String> {
|
||||
let mut data = AseData(bytes);
|
||||
data.bytes(ASE_SIGNATURE.len())?;
|
||||
let (major, minor) = (data.u16()?, data.u16()?);
|
||||
if major != 1 {
|
||||
return Err(format!("swatch exchange version {major}.{minor} isn't supported (only 1.x)"));
|
||||
}
|
||||
let blocks = data.u32()?;
|
||||
let mut lib = SwatchLibrary { name: fallback.into(), ..Default::default() };
|
||||
let mut names = UniqueNames::default();
|
||||
let (mut in_group, mut entries) = (false, 0usize);
|
||||
for _ in 0..blocks {
|
||||
let kind = data.u16()?;
|
||||
let len = usize::try_from(data.u32()?).unwrap_or(usize::MAX);
|
||||
let mut body = AseData(data.bytes(len)?);
|
||||
if matches!(kind, ASE_GROUP_START | ASE_COLOR) {
|
||||
entries += 1;
|
||||
if entries > ASE_MAX_ENTRIES {
|
||||
return Err(format!("the swatch exchange file holds more than {ASE_MAX_ENTRIES} colors and groups"));
|
||||
}
|
||||
}
|
||||
match kind {
|
||||
ASE_GROUP_START => {
|
||||
lib.groups.push(SwatchGroup { name: names.unique(group_name(&body.name()?)), swatches: vec![] });
|
||||
in_group = true;
|
||||
}
|
||||
ASE_GROUP_END => in_group = false,
|
||||
ASE_COLOR => {
|
||||
let Some(mut w) = ase_swatch(&mut body)? else { continue };
|
||||
w.name = names.unique(std::mem::take(&mut w.name));
|
||||
match lib.groups.last_mut().filter(|_| in_group) {
|
||||
Some(g) => g.swatches.push(w),
|
||||
None => lib.swatches.push(w),
|
||||
}
|
||||
}
|
||||
// Other blocks are skipped.
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(lib)
|
||||
}
|
||||
|
||||
/// The swatch of an `.ase` color block, `None` for a model other than RGB, CMYK, Lab and Gray.
|
||||
/// Components are clamped to their ranges.
|
||||
fn ase_swatch(body: &mut AseData) -> Result<Option<Swatch>, String> {
|
||||
let name = body.name()?;
|
||||
let unit = |v: f32| v.clamp(0.0, 1.0);
|
||||
let color = match &body.array::<4>()? {
|
||||
b"RGB " => {
|
||||
let [r, g, b] = [body.f32()?, body.f32()?, body.f32()?];
|
||||
Color::rgb(unit(r), unit(g), unit(b))
|
||||
}
|
||||
b"CMYK" => {
|
||||
let [c, m, y, k] = [body.f32()?, body.f32()?, body.f32()?, body.f32()?];
|
||||
Color::cmyk(unit(c), unit(m), unit(y), unit(k))
|
||||
}
|
||||
// Lightness is stored as a fraction of 100. Some writers store L* itself, which shows as a
|
||||
// value above 1.
|
||||
b"LAB " => {
|
||||
let [l, a, b] = [body.f32()?, body.f32()?, body.f32()?];
|
||||
let l = if l > 1.0 { l.min(100.0) } else { unit(l) * 100.0 };
|
||||
Color::lab(l, a.clamp(-128.0, 127.0), b.clamp(-128.0, 127.0))
|
||||
}
|
||||
// A gray level (1 is white); a gray color holds its ink.
|
||||
b"Gray" => Color::gray(1.0 - unit(body.f32()?)),
|
||||
_ => return Ok(None),
|
||||
};
|
||||
// Some writers leave the color type out, which makes a process color.
|
||||
let kind = if body.0.len() >= 2 { body.u16()? } else { 2 };
|
||||
// Spot colors are global.
|
||||
let (global, spot) = match kind {
|
||||
0 => (true, false),
|
||||
1 => (true, true),
|
||||
_ => (false, false),
|
||||
};
|
||||
let name = if name.is_empty() { value_name(color) } else { name };
|
||||
Ok(Some(Swatch { name, paint: Paint::solid(color), global, spot }))
|
||||
}
|
||||
|
||||
/// A color's values in its own model, as new swatches are named ("C=10 M=20 Y=30 K=0",
|
||||
/// "R=255 G=128 B=0", "Gray K=40", "L=52 a=70 b=-30").
|
||||
fn value_name(c: Color) -> String {
|
||||
let pct = |v: f32| (v * 100.0).round();
|
||||
let byte = |v: f32| (v * 255.0).round();
|
||||
match c {
|
||||
Color::Cmyk { c, m, y, k } => format!("C={} M={} Y={} K={}", pct(c), pct(m), pct(y), pct(k)),
|
||||
Color::Rgb { r, g, b } => format!("R={} G={} B={}", byte(r), byte(g), byte(b)),
|
||||
Color::Gray { k } => format!("Gray K={}", pct(k)),
|
||||
// `+ 0.0` turns a rounded -0 into 0.
|
||||
Color::Lab { l, a, b } => format!("L={} a={} b={}", l.round() + 0.0, a.round() + 0.0, b.round() + 0.0),
|
||||
}
|
||||
}
|
||||
|
||||
/// `.ase` data, read field by field; reading past its end is an error.
|
||||
struct AseData<'a>(&'a [u8]);
|
||||
|
||||
impl<'a> AseData<'a> {
|
||||
fn bytes(&mut self, n: usize) -> Result<&'a [u8], String> {
|
||||
let (head, rest) = self.0.split_at_checked(n).ok_or(ASE_CUT_SHORT)?;
|
||||
self.0 = rest;
|
||||
Ok(head)
|
||||
}
|
||||
fn array<const N: usize>(&mut self) -> Result<[u8; N], String> {
|
||||
let (head, rest) = self.0.split_first_chunk::<N>().ok_or(ASE_CUT_SHORT)?;
|
||||
self.0 = rest;
|
||||
Ok(*head)
|
||||
}
|
||||
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 component; one that isn't a finite number reads as 0.
|
||||
fn f32(&mut self) -> Result<f32, String> {
|
||||
let v = f32::from_be_bytes(self.array()?);
|
||||
Ok(if v.is_finite() { v } else { 0.0 })
|
||||
}
|
||||
/// A name up to its terminating zero, trimmed. A block that ends before it has no name.
|
||||
fn name(&mut self) -> Result<String, String> {
|
||||
if self.0.is_empty() {
|
||||
return Ok(String::new());
|
||||
}
|
||||
let n = usize::from(self.u16()?);
|
||||
let (units, _) = self.bytes(n * 2)?.as_chunks::<2>();
|
||||
let units: Vec<u16> = units.iter().take(ASE_MAX_NAME).map(|u| u16::from_be_bytes(*u)).take_while(|&u| u != 0).collect();
|
||||
Ok(String::from_utf16_lossy(&units).trim().to_string())
|
||||
}
|
||||
}
|
||||
|
||||
/// A group's name as a file gives it, trimmed; "Color Group" when it has none.
|
||||
fn group_name(name: &str) -> String {
|
||||
let name = name.trim();
|
||||
if name.is_empty() { "Color Group".into() } else { name.to_string() }
|
||||
}
|
||||
|
||||
/// The swatch and group names a reader has handed out. Swatches and color groups share one set of
|
||||
/// names, as in a document, and a name already taken gets the first free number ("Black 2").
|
||||
#[derive(Default)]
|
||||
struct UniqueNames {
|
||||
taken: HashSet<String>,
|
||||
/// The last number tried for each repeated name.
|
||||
last: HashMap<String, usize>,
|
||||
}
|
||||
|
||||
impl UniqueNames {
|
||||
fn unique(&mut self, base: String) -> String {
|
||||
if self.taken.insert(base.clone()) {
|
||||
return base;
|
||||
}
|
||||
// Each pass tries the next number, and only finitely many names are taken.
|
||||
let n = self.last.entry(base.clone()).or_insert(1);
|
||||
loop {
|
||||
*n += 1;
|
||||
let name = format!("{base} {n}");
|
||||
if self.taken.insert(name.clone()) {
|
||||
return name;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -294,6 +500,11 @@ mod tests {
|
||||
assert_eq!(names, ["Sky Blue", "R=10 G=20 B=30", "Black", "Black 2"]);
|
||||
assert_eq!(lib.swatches[0].paint.color(), Some(Color::rgb8(0, 128, 255)));
|
||||
assert_eq!(read("GIMP Palette\n1 2 3 x\n", "Fallback").unwrap().name, "Fallback");
|
||||
// Colors and groups share names; an unnamed group is "Color Group".
|
||||
let lib = read("GIMP Palette\n0 0 0 Black\n# Group: Black\n1 1 1 Black\n# Group:\n", "x").unwrap();
|
||||
let groups: Vec<(&str, Vec<&str>)> =
|
||||
lib.groups.iter().map(|g| (g.name.as_str(), g.swatches.iter().map(|w| w.name.as_str()).collect())).collect();
|
||||
assert_eq!(groups, [("Black 2", vec!["Black 3"]), ("Color Group", vec![])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -321,4 +532,117 @@ mod tests {
|
||||
assert!(text.contains("--red: #000000;") && text.contains("--red-2: #000000;"));
|
||||
assert!(read(&text, "x").is_err(), "CSS is written only");
|
||||
}
|
||||
|
||||
/// A swatch exchange file of `blocks` (type, body).
|
||||
fn ase(blocks: &[(u16, Vec<u8>)]) -> Vec<u8> {
|
||||
let mut out = b"ASEF\0\x01\0\0".to_vec();
|
||||
out.extend((blocks.len() as u32).to_be_bytes());
|
||||
for (kind, body) in blocks {
|
||||
out.extend(kind.to_be_bytes());
|
||||
out.extend((body.len() as u32).to_be_bytes());
|
||||
out.extend(body);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A name as `.ase` stores it.
|
||||
fn ase_name(name: &str) -> Vec<u8> {
|
||||
let units: Vec<u16> = name.encode_utf16().chain([0]).collect();
|
||||
let mut out = (units.len() as u16).to_be_bytes().to_vec();
|
||||
out.extend(units.iter().flat_map(|u| u.to_be_bytes()));
|
||||
out
|
||||
}
|
||||
|
||||
/// A color block: name, model, components and color type.
|
||||
fn ase_color(name: &str, model: &[u8; 4], values: &[f32], kind: u16) -> (u16, Vec<u8>) {
|
||||
let mut body = ase_name(name);
|
||||
body.extend(model);
|
||||
body.extend(values.iter().flat_map(|v| v.to_be_bytes()));
|
||||
body.extend(kind.to_be_bytes());
|
||||
(ASE_COLOR, body)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ase_reads_color_models_kinds_and_groups() {
|
||||
let bytes = ase(&[
|
||||
ase_color("Sky", b"RGB ", &[0.0, 0.5, 1.0], 0),
|
||||
ase_color("Ink", b"CMYK", &[1.0, 0.5, 0.0, 0.2], 1),
|
||||
(ASE_GROUP_START, ase_name("Neutrals")),
|
||||
ase_color("Mist", b"Gray", &[0.75], 2),
|
||||
ase_color("Clay", b"LAB ", &[0.5, 20.0, -30.0], 2),
|
||||
(ASE_GROUP_END, vec![]),
|
||||
ase_color("Paper", b"RGB ", &[1.0, 1.0, 1.0], 2),
|
||||
]);
|
||||
assert!(sniff_bytes(&bytes));
|
||||
let sw = |name: &str, color, global, spot| Swatch { name: name.into(), paint: Paint::solid(color), global, spot };
|
||||
let expected = SwatchLibrary {
|
||||
name: "Brand".into(),
|
||||
swatches: vec![
|
||||
sw("Sky", Color::rgb(0.0, 0.5, 1.0), true, false),
|
||||
sw("Ink", Color::cmyk(1.0, 0.5, 0.0, 0.2), true, true),
|
||||
sw("Paper", Color::WHITE, false, false),
|
||||
],
|
||||
groups: vec![SwatchGroup {
|
||||
name: "Neutrals".into(),
|
||||
swatches: vec![sw("Mist", Color::gray(0.25), false, false), sw("Clay", Color::lab(50.0, 20.0, -30.0), false, false)],
|
||||
}],
|
||||
};
|
||||
assert_eq!(read_bytes(&bytes, "Brand").unwrap(), expected, "named after the file; 0 global, 1 spot, 2 process");
|
||||
// A lightness above 1 is L* itself.
|
||||
let deep = read_bytes(&ase(&[ase_color("Deep", b"LAB ", &[53.0, 20.0, -30.0], 2)]), "x").unwrap();
|
||||
assert_eq!(deep.swatches[0].paint.color(), Some(Color::lab(53.0, 20.0, -30.0)));
|
||||
// Text libraries read through the same call, also when they aren't valid UTF-8.
|
||||
assert!(sniff_bytes(b"GIMP Palette\n1 2 3 x\n") && !sniff_bytes(b"ASE") && !sniff_bytes(&[0xff, 0xfe, 0]));
|
||||
assert_eq!(read_bytes(b"GIMP Palette\n1 2 3 x\n", "F").unwrap().swatches.len(), 1);
|
||||
let latin1 = b"GIMP Palette\n1 2 3 Caf\xe9\n";
|
||||
assert!(sniff_bytes(latin1));
|
||||
assert_eq!(read_bytes(latin1, "F").unwrap().swatches.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ase_names_unnamed_and_repeated_entries_and_skips_other_blocks() {
|
||||
let mut untyped = ase_color("Plain", b"RGB ", &[0.2, 0.4, 0.6], 2);
|
||||
untyped.1.truncate(untyped.1.len() - 2);
|
||||
let bytes = ase(&[
|
||||
ase_color("Café 🎨", b"RGB ", &[1.0, 0.0, 0.0], 2),
|
||||
ase_color("", b"CMYK", &[0.1, 0.2, 0.3, 0.0], 2),
|
||||
ase_color(" Red ", b"RGB ", &[2.0, -1.0, f32::NAN], 0),
|
||||
ase_color("Red", b"Gray", &[0.0], 2),
|
||||
untyped,
|
||||
ase_color("Hue", b"HSB ", &[0.1, 0.2, 0.3], 2),
|
||||
(0x0042, vec![1, 2, 3]),
|
||||
(ASE_GROUP_END, vec![]),
|
||||
(ASE_GROUP_START, ase_name("")),
|
||||
(ASE_GROUP_START, ase_name("Red")),
|
||||
ase_color("Red", b"Gray", &[1.0], 2),
|
||||
]);
|
||||
let lib = read_bytes(&bytes, "x").unwrap();
|
||||
let names: Vec<&str> = lib.swatches.iter().map(|w| w.name.as_str()).collect();
|
||||
assert_eq!(names, ["Café 🎨", "C=10 M=20 Y=30 K=0", "Red", "Red 2", "Plain"], "an HSB color and an unknown block are skipped");
|
||||
assert_eq!(lib.swatches[2].paint.color(), Some(Color::rgb(1.0, 0.0, 0.0)), "clamped, NaN read as 0");
|
||||
assert!(lib.swatches[2].global && !lib.swatches[4].global, "without a color type: process");
|
||||
// A group start ends the open group, and groups and colors share names.
|
||||
let groups: Vec<(&str, Vec<&str>)> =
|
||||
lib.groups.iter().map(|g| (g.name.as_str(), g.swatches.iter().map(|w| w.name.as_str()).collect())).collect();
|
||||
assert_eq!(groups, [("Color Group", vec![]), ("Red 3", vec!["Red 4"])]);
|
||||
assert_eq!(lib.groups[1].swatches[0].paint.color(), Some(Color::gray(0.0)), "gray level 1 is white");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn damaged_ase_files_are_errors() {
|
||||
let good = ase(&[(ASE_GROUP_START, ase_name("G")), ase_color("Sky", b"RGB ", &[0.0, 0.5, 1.0], 0)]);
|
||||
assert_eq!(read_bytes(&good, "x").unwrap().len(), 1);
|
||||
for n in ASE_SIGNATURE.len()..good.len() {
|
||||
assert!(read_bytes(&good[..n], "x").is_err(), "cut at {n}");
|
||||
}
|
||||
let mut v2 = good.clone();
|
||||
v2[5] = 2;
|
||||
assert!(read_bytes(&v2, "x").unwrap_err().contains("2.0"), "version 2.0");
|
||||
// Too many colors, or too many groups (empty group starts take 6 bytes each).
|
||||
let colors: Vec<(u16, Vec<u8>)> = (0..=ASE_MAX_ENTRIES).map(|_| ase_color("Gray", b"Gray", &[0.5], 2)).collect();
|
||||
assert!(read_bytes(&ase(&colors), "x").unwrap_err().contains("more than"));
|
||||
let groups: Vec<(u16, Vec<u8>)> = (0..=ASE_MAX_ENTRIES).map(|_| (ASE_GROUP_START, vec![])).collect();
|
||||
assert!(read_bytes(&ase(&groups), "x").unwrap_err().contains("more than"));
|
||||
assert_eq!(read_bytes(&ase(&groups[1..]), "x").unwrap().groups.len(), ASE_MAX_ENTRIES, "up to the limit");
|
||||
}
|
||||
}
|
||||
@@ -120,7 +120,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Make",
|
||||
["Object", "Image Trace"],
|
||||
None,
|
||||
"{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\", threshold: 0-255, colors: 2-256, paths: 0-100, corners: 0-100, noise: px, method: \"abutting\"|\"overlapping\", ignoreWhite, snapCurvesToLines}} → {id, paths, anchors, colors}",
|
||||
"{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, automatic: flat art with its own colours, else fullTone, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), paths: 0-100, corners: 0-100, noise: px, method: \"abutting\"|\"overlapping\", ignoreWhite, snapCurvesToLines}} → {id, paths, anchors, colors}",
|
||||
has_selection_or_ids,
|
||||
|s, p| trace_make(s, p, false)
|
||||
),
|
||||
@@ -651,6 +651,30 @@ fn trace_params(p: &Value) -> Result<tr::TraceParams> {
|
||||
serde_json::from_value(v).map_err(|e| bad("imageTrace.make", e.to_string()))
|
||||
}
|
||||
|
||||
/// Document Library in Color mode: look the library's colours up into `params.swatches` → each
|
||||
/// one as traced (sRGB) with the colour to fill with.
|
||||
fn trace_library(s: &Session, params: &mut tr::TraceParams) -> Result<Vec<([u8; 3], Color)>> {
|
||||
const C: &str = "imageTrace.make";
|
||||
if params.mode != tr::Mode::Color || params.palette != tr::Palette::DocumentLibrary {
|
||||
return Ok(vec![]);
|
||||
}
|
||||
let key = params.library.as_str();
|
||||
let colors = super::swatchlib::library_colors(s, key)
|
||||
.ok_or_else(|| bad(C, format!("no swatch library `{key}` (see swatch.library.list; \"document\": the document's swatches)")))?;
|
||||
if colors.is_empty() {
|
||||
return Err(bad(C, format!("`{key}` has no colours")));
|
||||
}
|
||||
let library: Vec<([u8; 3], Color)> = colors
|
||||
.into_iter()
|
||||
.map(|c| {
|
||||
let [r, g, b, _] = c.to_rgba8(1.0);
|
||||
([r, g, b], c)
|
||||
})
|
||||
.collect();
|
||||
params.swatches = library.iter().map(|l| l.0).collect();
|
||||
Ok(library)
|
||||
}
|
||||
|
||||
/// The most anchor points an Image Trace may make: a photo traced at high fidelity can make
|
||||
/// millions, more than the canvas draws smoothly or a laptop has memory for, so the trace is
|
||||
/// refused with advice instead (#525).
|
||||
@@ -658,7 +682,7 @@ pub const MAX_TRACE_ANCHORS: usize = 2_000_000;
|
||||
|
||||
fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Value> {
|
||||
const C: &str = "imageTrace.make";
|
||||
let params = trace_params(p)?;
|
||||
let mut params = trace_params(p)?;
|
||||
let params_json = serde_json::to_value(¶ms).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
// The preset's name if the parameters are exactly that preset's, else "Custom".
|
||||
let named = str_param(p, "preset").unwrap_or("Default");
|
||||
@@ -687,6 +711,7 @@ fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Value> {
|
||||
};
|
||||
let blob = s.doc()?.doc.images.get(&img.key).ok_or_else(|| EngineError::Other(format!("image data `{}` is missing", img.key)))?;
|
||||
let raster = tr::Raster::decode(&blob.bytes).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
let library = trace_library(s, &mut params)?;
|
||||
let res = tr::trace_within(&raster, ¶ms, MAX_TRACE_ANCHORS).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
// Pixel space of the decoded raster → the image object's pixel space → document.
|
||||
let sx = img.width.max(1) as f64 / raster.width.max(1) as f64;
|
||||
@@ -714,7 +739,9 @@ fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Value> {
|
||||
for tp in res.paths {
|
||||
let path = tp.path.transformed(xf);
|
||||
let mut n = shape_node(d, path, None);
|
||||
n.appearance = fill_only(Paint::solid(Color::rgb8(tp.color[0], tp.color[1], tp.color[2])));
|
||||
// A library colour fills with the swatch's own colour (its model kept).
|
||||
let color = library.iter().find(|(rgb, _)| *rgb == tp.color).map_or_else(|| Color::rgb8(tp.color[0], tp.color[1], tp.color[2]), |l| l.1);
|
||||
n.appearance = fill_only(Paint::solid(color));
|
||||
children.push(Arc::new(n));
|
||||
}
|
||||
let gid = d.alloc_id();
|
||||
|
||||
@@ -70,8 +70,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
|
||||
impl LibraryFile for StyleLibrary {
|
||||
const EXTS: &'static [&'static str] = &[STYLES_EXT];
|
||||
fn read(text: &str, stem: &str) -> std::result::Result<Self, String> {
|
||||
style_libs::read(text, stem)
|
||||
fn read(bytes: &[u8], stem: &str) -> std::result::Result<Self, String> {
|
||||
style_libs::read(&String::from_utf8_lossy(bytes), stem)
|
||||
}
|
||||
fn name(&self) -> &str {
|
||||
&self.name
|
||||
|
||||
@@ -69,7 +69,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Other Library…",
|
||||
["Window", "Swatch Libraries"],
|
||||
None,
|
||||
"{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} load a .vcswatches or .gpl library, or the swatches of any document VectorCraft opens (see document.formats), for the library panel (Window → Swatch Libraries lists it until the app quits) → {library: id, name, count}",
|
||||
"{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} load a .vcswatches, .gpl or .ase (swatch exchange) library, or the swatches of any document VectorCraft opens (see document.formats), for the library panel (Window → Swatch Libraries lists it until the app quits) → {library: id, name, count}",
|
||||
always,
|
||||
load
|
||||
),
|
||||
@@ -98,23 +98,24 @@ struct Extra<L> {
|
||||
pub trait LibraryFile: Sized {
|
||||
/// The extensions of its files (lower case).
|
||||
const EXTS: &'static [&'static str];
|
||||
/// Read a library file whose name without the extension is `stem` (an unnamed library's name).
|
||||
fn read(text: &str, stem: &str) -> std::result::Result<Self, String>;
|
||||
/// Read the bytes of a library file whose name without the extension is `stem` (an unnamed
|
||||
/// library's name).
|
||||
fn read(bytes: &[u8], stem: &str) -> std::result::Result<Self, String>;
|
||||
fn name(&self) -> &str;
|
||||
}
|
||||
|
||||
impl LibraryFile for SwatchLibrary {
|
||||
const EXTS: &'static [&'static str] = LIBRARY_EXTS;
|
||||
fn read(text: &str, stem: &str) -> std::result::Result<Self, String> {
|
||||
palette_io::read(text, stem)
|
||||
fn read(bytes: &[u8], stem: &str) -> std::result::Result<Self, String> {
|
||||
palette_io::read_bytes(bytes, stem)
|
||||
}
|
||||
fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
}
|
||||
|
||||
/// The extensions of library files [`palette_io::read`] reads.
|
||||
pub const LIBRARY_EXTS: &[&str] = &["vcswatches", "gpl"];
|
||||
/// The extensions of library files [`palette_io::read_bytes`] reads.
|
||||
pub const LIBRARY_EXTS: &[&str] = &["vcswatches", "gpl", "ase"];
|
||||
|
||||
impl<L: LibraryFile> Libraries<L> {
|
||||
pub fn user_dir(&self) -> Option<&str> {
|
||||
@@ -133,7 +134,7 @@ impl<L: LibraryFile> Libraries<L> {
|
||||
let Some(dir) = self.user_dir.clone() else { return };
|
||||
for path in library_files(&dir, L::EXTS) {
|
||||
let file = file_name(&path);
|
||||
let Some(lib) = read_file(&path).ok().and_then(|b| L::read(&String::from_utf8_lossy(&b), stem(&file)).ok()) else { continue };
|
||||
let Some(lib) = read_file(&path).ok().and_then(|b| L::read(&b, stem(&file)).ok()) else { continue };
|
||||
let info = LibraryInfo { id: format!("user/{file}"), name: lib.name().to_string(), category: "user" };
|
||||
self.extra.push(Extra { info, path: Some(path), lib: Arc::new(lib) });
|
||||
}
|
||||
@@ -275,11 +276,18 @@ pub const DOCUMENT_SWATCHES: &str = "document";
|
||||
/// [`DOCUMENT_SWATCHES`], of the active document's swatches and colour groups. `None` when there is
|
||||
/// no such library (or document).
|
||||
pub fn limit_palette(s: &Session, key: &str) -> Option<Palette> {
|
||||
Some(Palette::new(library_colors(s, key)?))
|
||||
}
|
||||
|
||||
/// The solid colours of library `key` (an id or name) or, for [`DOCUMENT_SWATCHES`], of the
|
||||
/// active document's swatches and colour groups. `None` when there is no such library (or
|
||||
/// document).
|
||||
pub fn library_colors(s: &Session, key: &str) -> Option<Vec<Color>> {
|
||||
let colors = |sw: &Swatch| sw.paint.color();
|
||||
if key == DOCUMENT_SWATCHES {
|
||||
return Some(Palette::new(s.active()?.doc.swatches_iter().filter_map(colors)));
|
||||
return Some(s.active()?.doc.swatches_iter().filter_map(colors).collect());
|
||||
}
|
||||
Some(Palette::new(library(s, key)?.1.iter().filter_map(colors)))
|
||||
Some(library(s, key)?.1.iter().filter_map(colors).collect())
|
||||
}
|
||||
|
||||
/// The `limitTo` parameter's palette ([`limit_palette`]); `None` without one (or for "").
|
||||
@@ -351,12 +359,11 @@ fn load(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "swatch.library.load";
|
||||
let (info, lib) = s.swatch_libraries.load(p, C, |bytes, file| {
|
||||
// A library file, or a document whose swatches become the library.
|
||||
match std::str::from_utf8(bytes).ok().filter(|t| palette_io::sniff(t)) {
|
||||
Some(t) => palette_io::read(t, stem(file)).map_err(|e| bad(C, e)),
|
||||
None => {
|
||||
let doc = super::fileio::load(file, bytes).map_err(|e| bad(C, e.to_string()))?.doc;
|
||||
document_library(&doc, &[], stem(file).to_string(), C)
|
||||
}
|
||||
if palette_io::sniff_bytes(bytes) {
|
||||
palette_io::read_bytes(bytes, stem(file)).map_err(|e| bad(C, e))
|
||||
} else {
|
||||
let doc = super::fileio::load(file, bytes).map_err(|e| bad(C, e.to_string()))?.doc;
|
||||
document_library(&doc, &[], stem(file).to_string(), C)
|
||||
}
|
||||
})?;
|
||||
Ok(json!({"library": info.id, "name": info.name, "count": lib.len()}))
|
||||
@@ -417,12 +424,17 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
} else {
|
||||
s.edit("Add to Swatches", |d, _| {
|
||||
let mut out = vec![];
|
||||
// Each library group goes into one document group: the group of that name the document
|
||||
// already had, or one made here.
|
||||
let before = d.swatch_groups.len();
|
||||
let mut placed: Vec<(&str, usize)> = vec![];
|
||||
for (group, w) in fresh {
|
||||
let name = d.free_swatch_name(&w.name);
|
||||
let sw = Swatch { name: name.clone(), ..(*w).clone() };
|
||||
match group {
|
||||
Some(g) => {
|
||||
let i = match d.swatch_groups.iter().position(|x| x.name == *g) {
|
||||
let found = placed.iter().find(|(n, _)| *n == g).map(|&(_, i)| i);
|
||||
let i = match found.or_else(|| d.swatch_groups.iter().take(before).position(|x| x.name == *g)) {
|
||||
Some(i) => i,
|
||||
None => {
|
||||
let name = d.free_swatch_name(g);
|
||||
@@ -430,6 +442,9 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
d.swatch_groups.len() - 1
|
||||
}
|
||||
};
|
||||
if found.is_none() {
|
||||
placed.push((g, i));
|
||||
}
|
||||
d.swatch_groups[i].swatches.push(sw);
|
||||
}
|
||||
None => d.swatches.push(sw),
|
||||
|
||||
@@ -669,6 +669,49 @@ fn image_trace_make_and_expand_and_color_presets() {
|
||||
assert!(s.execute("imageTrace.make", &json!({"params": {"mode": "rainbow"}})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_trace_palettes_and_swatch_libraries() {
|
||||
let mut s = session();
|
||||
let quads = vectorcraft_trace::Raster::from_fn(60, 60, |x, y| match (x < 30, y < 30) {
|
||||
(true, true) => [230, 20, 20, 255],
|
||||
(false, true) => [20, 200, 30, 255],
|
||||
(true, false) => [20, 30, 220, 255],
|
||||
(false, false) => [250, 230, 10, 255],
|
||||
});
|
||||
add_image(&mut s, &quads, Affine::IDENTITY);
|
||||
let fills = |s: &Session, id: &Value| -> Vec<Color> {
|
||||
traced_paths(&node(s, NodeId(id.as_u64().unwrap()))).iter().filter_map(|n| n.appearance.fill_paint().color()).collect()
|
||||
};
|
||||
// Document Library: every fill is one of the document's swatch colours, as it is.
|
||||
let r = s.execute("imageTrace.make", &json!({"preset": "6 Colors", "params": {"palette": "documentLibrary"}})).unwrap();
|
||||
let doc = crate::cmd::swatchlib::library_colors(&s, "document").unwrap();
|
||||
let got = fills(&s, &r["id"]);
|
||||
assert!(!got.is_empty() && got.iter().all(|c| doc.contains(c)), "{got:?}");
|
||||
let t = node(&s, NodeId(r["id"].as_u64().unwrap())).trace.unwrap();
|
||||
assert_eq!((t["params"]["palette"].as_str(), t["params"]["library"].as_str()), (Some("documentLibrary"), Some("document")));
|
||||
assert!(t["params"].get("swatches").is_none(), "looked up again at every trace");
|
||||
// A swatch library by id: the web-safe colours.
|
||||
let r = s
|
||||
.execute(
|
||||
"imageTrace.make",
|
||||
&json!({"id": r["id"], "preset": "6 Colors", "params": {"palette": "documentLibrary", "library": "web-safe-216", "colors": 3}}),
|
||||
)
|
||||
.unwrap();
|
||||
let got = fills(&s, &r["id"]);
|
||||
assert!((1..=3).contains(&got.len()), "{got:?}");
|
||||
assert!(got.iter().all(|c| c.to_rgba8(1.0)[..3].iter().all(|v| v % 51 == 0)), "{got:?}");
|
||||
// Full Tone and Automatic keep the four flat colours.
|
||||
let mut id = r["id"].clone();
|
||||
for palette in ["fullTone", "automatic"] {
|
||||
let r = s.execute("imageTrace.make", &json!({"id": id, "preset": "6 Colors", "params": {"palette": palette, "colorDetail": 50}})).unwrap();
|
||||
assert_eq!(r["colors"], 4, "{palette}");
|
||||
id = r["id"].clone();
|
||||
}
|
||||
let mut bad = |p: Value| s.execute("imageTrace.make", &json!({"preset": "6 Colors", "params": p})).is_err();
|
||||
assert!(bad(json!({"palette": "documentLibrary", "library": "No Such Library"})));
|
||||
assert!(bad(json!({"palette": "rainbow"})));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_trace_presets_query_and_errors() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -197,6 +197,74 @@ fn another_documents_swatches_load_as_a_library() {
|
||||
assert!(s.execute("swatch.library.load", &json!({"data": "hello", "name": "x.txt"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn swatch_exchange_files_load_add_and_list_as_user_libraries() {
|
||||
let bytes = vectorcraft_testkit::ase::sample();
|
||||
let mut s = session();
|
||||
let r = run(&mut s, "swatch.library.load", json!({"dataBase64": vectorcraft_format::base64_encode(&bytes), "name": "Brand.ase"}));
|
||||
assert_eq!((r["library"].as_str(), r["name"].as_str(), r["count"].as_u64()), (Some("loaded/Brand.ase"), Some("Brand"), Some(4)));
|
||||
let g = run(&mut s, "swatch.library.get", json!({"library": r["library"]}));
|
||||
let swatches = g["swatches"].as_array().unwrap();
|
||||
let kinds: Vec<(&str, bool, bool)> =
|
||||
swatches.iter().map(|w| (w["name"].as_str().unwrap(), w["global"].as_bool().unwrap(), w["spot"].as_bool().unwrap())).collect();
|
||||
assert_eq!(kinds, [("Sky", true, false), ("Ink", true, true), ("Mist", false, false), ("Clay", false, false)]);
|
||||
assert_eq!(swatches[3]["color"], json!({"model": "lab", "l": 50.0, "a": 20.0, "b": -30.0}));
|
||||
// Added to the document, the spot color stays a spot color and the group stays a color group.
|
||||
run(&mut s, "swatch.library.add", json!({"library": r["library"]}));
|
||||
let d = doc(&s);
|
||||
assert!(d.swatch("Ink").is_some_and(|w| w.spot && w.global));
|
||||
assert_eq!(d.swatch_groups.iter().find(|g| g.name == "Neutrals").map(|g| g.swatches.len()), Some(2));
|
||||
// A damaged file is an error from the swatch exchange reader, not from the document loader.
|
||||
let cut = vectorcraft_format::base64_encode(&bytes[..bytes.len() - 1]);
|
||||
let e = s.execute("swatch.library.load", &json!({"dataBase64": cut, "name": "Cut.ase"})).unwrap_err().to_string();
|
||||
assert!(e.contains("cut short"), "{e}");
|
||||
// `.ase` files in the user library folder are User Defined libraries.
|
||||
let dir = temp_dir("ase");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("Brand.ase"), &bytes).unwrap();
|
||||
s.swatch_libraries.set_user_dir(Some(dir.to_string_lossy().to_string()));
|
||||
let list = run(&mut s, "swatch.library.list", json!({}));
|
||||
let user: Vec<(&str, u64)> = list["libraries"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter(|l| l["category"] == "user")
|
||||
.map(|l| (l["id"].as_str().unwrap(), l["count"].as_u64().unwrap()))
|
||||
.collect();
|
||||
assert_eq!(user, [("user/Brand.ase", 4)]);
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_library_group_stays_one_group_when_a_swatch_has_its_name() {
|
||||
use vectorcraft_testkit::ase::{Block, ase};
|
||||
let mut s = session();
|
||||
assert!(doc(&s).swatch("Blue").is_some(), "a new document has a swatch named Blue");
|
||||
let bytes = ase(&[
|
||||
Block::GroupStart("Blue"),
|
||||
Block::Color("Deep", b"RGB ", &[0.0, 0.0, 0.4], 2),
|
||||
Block::Color("Pale", b"RGB ", &[0.6, 0.7, 1.0], 2),
|
||||
Block::GroupEnd,
|
||||
Block::GroupStart("Blue 2"),
|
||||
Block::Color("Frost", b"RGB ", &[0.9, 0.95, 1.0], 2),
|
||||
Block::GroupEnd,
|
||||
]);
|
||||
let r = run(&mut s, "swatch.library.load", json!({"dataBase64": vectorcraft_format::base64_encode(&bytes), "name": "Blues.ase"}));
|
||||
run(&mut s, "swatch.library.add", json!({"library": r["library"]}));
|
||||
let groups: Vec<(&str, Vec<&str>)> =
|
||||
doc(&s).swatch_groups.iter().map(|g| (g.name.as_str(), g.swatches.iter().map(|w| w.name.as_str()).collect())).collect();
|
||||
assert!(groups.contains(&("Blue 2", vec!["Deep", "Pale"])), "{groups:?}");
|
||||
assert!(groups.contains(&("Blue 2 2", vec!["Frost"])), "the library's own Blue 2 stays apart: {groups:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_libraries_sent_as_bytes_load_when_they_are_not_valid_utf8() {
|
||||
let mut s = session();
|
||||
let latin1 = vectorcraft_format::base64_encode(b"GIMP Palette\n237 28 36 Rouge fonc\xe9\n");
|
||||
let r = run(&mut s, "swatch.library.load", json!({"dataBase64": latin1, "name": "Rouge.gpl"}));
|
||||
assert_eq!(r["count"], 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradient_libraries_are_listed_and_gradient_swatches_rename_and_take_new_gradients() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -247,10 +247,13 @@ fn artboard_tool_moves_with_art_creates_and_deletes() {
|
||||
assert_eq!(s.doc().unwrap().doc.artboards.len(), 2);
|
||||
assert_eq!(s.tool_options()["active"], 1);
|
||||
assert_eq!(s.doc().unwrap().doc.artboards[1].rect, Rect::new(1000.0, 0.0, 1200.0, 100.0));
|
||||
// Delete it.
|
||||
// Delete it: the tool takes the key ahead of the Clear shortcut (the UI only hands Delete to a
|
||||
// tool that claims it).
|
||||
assert!(s.tool_claims_key(ToolKey::Delete, ViewInfo::default()));
|
||||
s.tool_key(ToolKey::Delete, Mods::default(), ViewInfo::default()).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.artboards.len(), 1);
|
||||
// The last artboard can't be deleted.
|
||||
// The last artboard can't be deleted, so Delete stays the shortcut's.
|
||||
assert!(!s.tool_claims_key(ToolKey::Delete, ViewInfo::default()));
|
||||
s.tool_key(ToolKey::Delete, Mods::default(), ViewInfo::default()).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.artboards.len(), 1);
|
||||
}
|
||||
|
||||
@@ -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`), graphic style (`.vcstyles`) and flattener preset
|
||||
//! mutated raster images 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
|
||||
@@ -529,12 +529,21 @@ fn saved(cmd: &str, params: Value) -> String {
|
||||
rich_session().execute(cmd, ¶ms).unwrap()["data"].as_str().unwrap().to_string()
|
||||
}
|
||||
|
||||
/// `r`, after failing the case if the command panicked. The engine's guard reports a panic as
|
||||
/// `EngineError::Internal`.
|
||||
fn no_panic(r: Result<Value, vectorcraft_engine::EngineError>) -> Result<Value, vectorcraft_engine::EngineError> {
|
||||
if let Err(vectorcraft_engine::EngineError::Internal { cmd, msg }) = &r {
|
||||
panic!("{cmd} panicked: {msg}");
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
/// Library file `data` loaded with `load`; what it holds is then used on the rich document
|
||||
/// (`then`, given the load's result), which renders and exports.
|
||||
fn survive_library(what: &str, load: &str, data: &str, then: impl FnOnce(&mut vectorcraft_engine::Session, &Value)) -> Result<(), TestCaseError> {
|
||||
survive(what, || {
|
||||
let mut s = rich_session();
|
||||
let r = s.execute(load, &json!({"data": data, "name": "fuzz"})).ok()?;
|
||||
let r = no_panic(s.execute(load, &json!({"data": data, "name": "fuzz"}))).ok()?;
|
||||
then(&mut s, &r);
|
||||
Some((*s.doc().ok()?.doc).clone())
|
||||
})
|
||||
@@ -542,27 +551,55 @@ fn survive_library(what: &str, load: &str, data: &str, then: impl FnOnce(&mut ve
|
||||
|
||||
fn swatches(what: &str, data: &str) -> Result<(), TestCaseError> {
|
||||
survive_library(what, "swatch.library.load", data, |s, r| {
|
||||
let _ = s.execute("swatch.library.add", &json!({"library": r["library"], "apply": "fill"}));
|
||||
let _ = no_panic(s.execute("swatch.library.add", &json!({"library": r["library"], "apply": "fill"})));
|
||||
})
|
||||
}
|
||||
|
||||
fn styles(what: &str, data: &str) -> Result<(), TestCaseError> {
|
||||
survive_library(what, "graphicStyle.loadLibrary", data, |s, r| {
|
||||
let _ = s.execute("select.all", &json!({}));
|
||||
let _ = s.execute("graphicStyle.addFromLibrary", &json!({"library": r["library"], "apply": true}));
|
||||
let _ = no_panic(s.execute("select.all", &json!({})));
|
||||
let _ = no_panic(s.execute("graphicStyle.addFromLibrary", &json!({"library": r["library"], "apply": true})));
|
||||
})
|
||||
}
|
||||
|
||||
fn flattener_presets(what: &str, data: &str) -> Result<(), TestCaseError> {
|
||||
survive_library(what, "flattener.presets.import", data, |s, r| {
|
||||
let _ = s.execute("select.all", &json!({}));
|
||||
let _ = no_panic(s.execute("select.all", &json!({})));
|
||||
if let Some(name) = r["imported"].get(0) {
|
||||
let _ = s.execute("flattener.preview", &json!({"preset": name, "highlight": "allAffected"}));
|
||||
let _ = s.execute("object.flattenTransparency", &json!({"preset": name, "lineArtPpi": 36, "gradientPpi": 36}));
|
||||
let _ = no_panic(s.execute("flattener.preview", &json!({"preset": name, "highlight": "allAffected"})));
|
||||
let _ = no_panic(s.execute("object.flattenTransparency", &json!({"preset": name, "lineArtPpi": 36, "gradientPpi": 36})));
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Swatch exchange (`.ase`) bytes loaded as a swatch library, then added to the rich document.
|
||||
fn swatch_exchange(what: &str, bytes: &[u8]) -> Result<(), TestCaseError> {
|
||||
survive(what, || {
|
||||
let mut s = rich_session();
|
||||
let load = json!({"dataBase64": vectorcraft_format::base64_encode(bytes), "name": "fuzz.ase"});
|
||||
let r = no_panic(s.execute("swatch.library.load", &load)).ok()?;
|
||||
let _ = no_panic(s.execute("swatch.library.add", &json!({"library": r["library"], "apply": "fill"})));
|
||||
Some((*s.doc().ok()?.doc).clone())
|
||||
})
|
||||
}
|
||||
|
||||
/// A random swatch exchange block (type, body). The body holds a name, a color model when the block
|
||||
/// is a color, and random bytes for the rest.
|
||||
fn arb_ase_block() -> impl Strategy<Value = (u16, Vec<u8>)> {
|
||||
let kind = prop::sample::select(vec![0xC001u16, 0xC002, 0x0001, 0x0042]);
|
||||
let model = prop::sample::select(vec![*b"RGB ", *b"CMYK", *b"LAB ", *b"Gray", *b"HSB "]);
|
||||
(kind, "[ -~]{0,8}", model, prop::collection::vec(any::<u8>(), 0..24)).prop_map(|(kind, name, model, rest)| {
|
||||
let units: Vec<u16> = name.encode_utf16().chain([0]).collect();
|
||||
let mut body = (units.len() as u16).to_be_bytes().to_vec();
|
||||
body.extend(units.iter().flat_map(|u| u.to_be_bytes()));
|
||||
if kind == 0x0001 {
|
||||
body.extend(model);
|
||||
}
|
||||
body.extend(rest);
|
||||
(kind, body)
|
||||
})
|
||||
}
|
||||
|
||||
/// Characters that break JSON and GPL palettes.
|
||||
fn arb_edit() -> impl Strategy<Value = (usize, char)> {
|
||||
(0usize..20_000, prop::sample::select(vec!['{', '}', '[', ']', '"', ':', ',', '-', '9', 'e', '.', ' ', '\n', '#', 'n', 'x', '\t']))
|
||||
@@ -596,6 +633,32 @@ proptest! {
|
||||
let text = saved("flattener.presets.export", json!({"names": ["high", "medium", "low"]}));
|
||||
flattener_presets("mutated flattener presets", &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();
|
||||
bytes.extend((blocks.len() as u32).to_be_bytes());
|
||||
for (kind, body) in &blocks {
|
||||
bytes.extend(kind.to_be_bytes());
|
||||
bytes.extend((body.len() as u32).to_be_bytes());
|
||||
bytes.extend(body);
|
||||
}
|
||||
bytes.extend(tail);
|
||||
swatch_exchange("swatch exchange garbage", &bytes)?;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mutated_swatch_exchange_files_never_panic(cut in prop::option::of(0usize..200), edits in prop::collection::vec((0usize..200, any::<u8>()), 0..12)) {
|
||||
let mut bytes = vectorcraft_testkit::ase::sample();
|
||||
for (at, b) in edits {
|
||||
let n = bytes.len();
|
||||
bytes[at % n] = b;
|
||||
}
|
||||
if let Some(cut) = cut {
|
||||
bytes.truncate(cut);
|
||||
}
|
||||
swatch_exchange("mutated swatch exchange file", &bytes)?;
|
||||
}
|
||||
}
|
||||
|
||||
/// A small image of each raster format Place reads, with resolution metadata where it has some.
|
||||
@@ -704,8 +767,8 @@ proptest! {
|
||||
fn pdf_presets(what: &str, data: &str) -> Result<(), TestCaseError> {
|
||||
survive_library(what, "pdf.preset.import", data, |s, r| {
|
||||
for name in r["imported"].as_array().into_iter().flatten() {
|
||||
let _ = s.execute("document.exportPdf", &json!({"preset": name}));
|
||||
let _ = s.execute("document.save", &json!({"format": "ai", "preset": name}));
|
||||
let _ = no_panic(s.execute("document.exportPdf", &json!({"preset": name})));
|
||||
let _ = no_panic(s.execute("document.save", &json!({"format": "ai", "preset": name})));
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -1219,14 +1282,14 @@ proptest! {
|
||||
/// each one imported.
|
||||
fn print_presets(what: &str, data: &str) -> Result<(), TestCaseError> {
|
||||
survive_library(what, "print.presets.import", data, |s, r| {
|
||||
let list = s.execute("print.presets.list", &json!({})).unwrap_or_default();
|
||||
let list = no_panic(s.execute("print.presets.list", &json!({}))).unwrap_or_default();
|
||||
for name in r["imported"].as_array().into_iter().flatten() {
|
||||
let Some(p) = list["presets"].as_array().into_iter().flatten().find(|p| &p["name"] == name) else { continue };
|
||||
let settings = json!({ "settings": p["settings"] });
|
||||
let pages = s.execute("print.preview", &settings).ok().and_then(|v| v["pages"].as_u64());
|
||||
let _ = s.execute("print.setup", &settings);
|
||||
let pages = no_panic(s.execute("print.preview", &settings)).ok().and_then(|v| v["pages"].as_u64());
|
||||
let _ = no_panic(s.execute("print.setup", &settings));
|
||||
if pages.is_some_and(|n| n <= 8) {
|
||||
let _ = s.execute("file.print", &settings);
|
||||
let _ = no_panic(s.execute("file.print", &settings));
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -1256,9 +1319,11 @@ proptest! {
|
||||
fn perspective_presets(what: &str, data: &str) -> Result<(), TestCaseError> {
|
||||
survive_library(what, "perspective.presets.import", data, |s, r| {
|
||||
for name in r["imported"].as_array().into_iter().flatten() {
|
||||
let _ = s.execute("perspective.grid.preset", &json!({"name": name}));
|
||||
let _ = s.execute("perspective.grid.define", &json!({"name": name, "gridline": 3}));
|
||||
let _ = s.execute("perspective.draw", &json!({"command": "shape.rectangle", "params": {"x": 300, "y": 400, "width": 40, "height": 30}}));
|
||||
let _ = no_panic(s.execute("perspective.grid.preset", &json!({"name": name})));
|
||||
let _ = no_panic(s.execute("perspective.grid.define", &json!({"name": name, "gridline": 3})));
|
||||
let _ = no_panic(
|
||||
s.execute("perspective.draw", &json!({"command": "shape.rectangle", "params": {"x": 300, "y": 400, "width": 40, "height": 30}})),
|
||||
);
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -295,7 +295,9 @@ with the {effect} effect.
|
||||
Method:
|
||||
1. open_file the image: it becomes a document of its own pixel size.
|
||||
2. imageTrace.make with the preset name, adjusting `params` — mode blackAndWhite, grayscale or
|
||||
color, then threshold, colors, paths, corners, noise, method abutting or overlapping,
|
||||
color (palette limited, fullTone for photos, automatic, or documentLibrary to trace with
|
||||
the document's swatches or a swatch `library`), then threshold, colors (colorDetail for
|
||||
fullTone and automatic), paths, corners, noise, method abutting or overlapping,
|
||||
ignoreWhite, snapCurvesToLines. Run imageTrace.presets to see every preset with its numbers.
|
||||
Lower paths and higher corners give the clean, logo-like result; high fidelity needs paths
|
||||
near 90.
|
||||
|
||||
@@ -33,6 +33,7 @@ pub(crate) fn import(svg: &str, opts: &ImportOptions) -> Result<(Document, Vec<S
|
||||
let xml = roxmltree::Document::parse_with_options(svg, roxmltree::ParsingOptions { allow_dtd: true, ..Default::default() })
|
||||
.map_err(|e| SvgError::Parse(e.to_string()))?;
|
||||
let units = RootUnits::of(xml.root_element());
|
||||
let root_name = root_layer_name(xml.root_element());
|
||||
let mut warnings = found.warnings;
|
||||
let (src, slots) = text::prepare(svg, &xml, units.dpi, &mut warnings);
|
||||
let files = found.files;
|
||||
@@ -141,11 +142,17 @@ pub(crate) fn import(svg: &str, opts: &ImportOptions) -> Result<(Document, Vec<S
|
||||
im.doc.layers.push(Arc::new(l));
|
||||
}
|
||||
} else {
|
||||
// An export of a one-layer document names the layer on the root element, its art (groups
|
||||
// among it) loose inside: the one layer takes that name.
|
||||
let children = im.children(top, base);
|
||||
if let Some(l) = im.doc.layers.first_mut()
|
||||
&& let Some(ch) = Arc::make_mut(l).children_mut()
|
||||
{
|
||||
*ch = children;
|
||||
if let Some(l) = im.doc.layers.first_mut() {
|
||||
let l = Arc::make_mut(l);
|
||||
if let Some(ch) = l.children_mut() {
|
||||
*ch = children;
|
||||
}
|
||||
if root_name.is_some() {
|
||||
l.name = root_name;
|
||||
}
|
||||
}
|
||||
}
|
||||
if !im.sublayer_groups.is_empty() {
|
||||
@@ -163,6 +170,13 @@ pub(crate) const SUBLAYER: &str = "data-vc-layer";
|
||||
/// The Inkscape namespace (its layers and their labels).
|
||||
const INKSCAPE: &str = "http://www.inkscape.org/namespaces/inkscape";
|
||||
|
||||
/// The layer name on root element `root` (`<svg id="Main">`, or its `data-name`), as exports of
|
||||
/// one-layer documents write it. An Inkscape root's id (`svg8`) is one Inkscape made up, not a name.
|
||||
fn root_layer_name(root: XNode) -> Option<String> {
|
||||
let id = root.attribute("id").filter(|_| root.attribute((INKSCAPE, "version")).is_none());
|
||||
root.attribute("data-name").or(id).map(str::trim).filter(|n| !n.is_empty()).map(str::to_string)
|
||||
}
|
||||
|
||||
/// Is element `g` a `<g>` marked as a layer ([`SUBLAYER`])? Only one with an id counts: the id (or
|
||||
/// the label beside it) is its name.
|
||||
fn marked_layer(g: XNode) -> bool {
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
//! Symbols export as one `<symbol>` def and a `<use>` per instance (instances the def can't stand
|
||||
//! for get their own art), hidden layers and objects are kept hidden when asked and come back
|
||||
//! hidden with their `data-*` attributes, clipped layers come in as clipping layers, layers and
|
||||
//! sublayers keep their names and nesting, and the editing data notices edits made elsewhere.
|
||||
//! sublayers keep their names and nesting (a one-layer file's from its root element), and the
|
||||
//! editing data notices edits made elsewhere.
|
||||
// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness).
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
@@ -482,6 +483,25 @@ fn sublayers_round_trip() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_root_element_names_the_one_layer() {
|
||||
// A one-layer document exported with its art loose under the root, which carries the name.
|
||||
let svg = r##"<svg version="1.1" id="Main" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 300">
|
||||
<rect x="20" y="50" width="120" height="60" style="fill:none;stroke:#000;stroke-width:4"/>
|
||||
<g id="HiddenSub" style="display:none;"><circle cx="45" cy="175" r="25"/></g>
|
||||
</svg>"##;
|
||||
assert_eq!(outline(&import(svg).unwrap()), ["Layer Main", " Path", " Group HiddenSub (hidden)", " Path"]);
|
||||
// `data-name` when the id can't hold the name.
|
||||
let named = svg.replace("id=\"Main\"", "id=\"Main_Art\" data-name=\"Main Art\"");
|
||||
assert_eq!(import(&named).unwrap().layers[0].name.as_deref(), Some("Main Art"));
|
||||
let names = |svg: &str| import(svg).unwrap().layers.iter().map(|l| l.name.clone().unwrap()).collect::<Vec<_>>();
|
||||
// Not when the groups at the top are the layers.
|
||||
assert_eq!(names(&svg.replace("<rect", "<g id=\"Art\"><rect").replace("stroke-width:4\"/>", "stroke-width:4\"/></g>")), ["Art", "HiddenSub"]);
|
||||
// Nor from the id Inkscape gives its root.
|
||||
let inkscape = svg.replace("id=\"Main\"", "id=\"svg8\" xmlns:inkscape=\"http://www.inkscape.org/namespaces/inkscape\" inkscape:version=\"1.3\"");
|
||||
assert_eq!(names(&inkscape), ["Layer 1"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marked_groups_are_sublayers_only_in_layers() {
|
||||
// Inkscape marks its layers and sublayers; one marked group in a plain group stays a group.
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
//! Hand-written swatch exchange (`.ase`) files for swatch library tests: version 1.0, big-endian,
|
||||
//! with colors in each model and color type, and color groups.
|
||||
|
||||
/// One block of a swatch exchange file.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum Block<'a> {
|
||||
/// A color group starts (its name).
|
||||
GroupStart(&'a str),
|
||||
/// The open color group ends.
|
||||
GroupEnd,
|
||||
/// A color: its name, model (`b"RGB "`, `b"CMYK"`, `b"LAB "` or `b"Gray"`), components and
|
||||
/// color type (0 global, 1 spot, 2 process).
|
||||
Color(&'a str, &'a [u8; 4], &'a [f32], u16),
|
||||
}
|
||||
|
||||
/// A name: a `u16` count of UTF-16 code units, the terminating zero included, then the units.
|
||||
fn name(out: &mut Vec<u8>, name: &str) {
|
||||
let units: Vec<u16> = name.encode_utf16().chain([0]).collect();
|
||||
out.extend(u16::try_from(units.len()).unwrap().to_be_bytes());
|
||||
out.extend(units.iter().flat_map(|u| u.to_be_bytes()));
|
||||
}
|
||||
|
||||
/// A swatch exchange file of `blocks`.
|
||||
pub fn ase(blocks: &[Block]) -> Vec<u8> {
|
||||
let mut out = b"ASEF\0\x01\0\0".to_vec();
|
||||
out.extend(u32::try_from(blocks.len()).unwrap().to_be_bytes());
|
||||
for b in blocks {
|
||||
let mut body = vec![];
|
||||
let kind: u16 = match b {
|
||||
Block::GroupStart(n) => {
|
||||
name(&mut body, n);
|
||||
0xC001
|
||||
}
|
||||
Block::GroupEnd => 0xC002,
|
||||
Block::Color(n, model, values, kind) => {
|
||||
name(&mut body, n);
|
||||
body.extend(*model);
|
||||
body.extend(values.iter().flat_map(|v| v.to_be_bytes()));
|
||||
body.extend(kind.to_be_bytes());
|
||||
0x0001
|
||||
}
|
||||
};
|
||||
out.extend(kind.to_be_bytes());
|
||||
out.extend(u32::try_from(body.len()).unwrap().to_be_bytes());
|
||||
out.extend(body);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A library of four colors: "Sky" (global RGB) and "Ink" (spot CMYK), then the group "Neutrals"
|
||||
/// of the process colors "Mist" (Gray, 25% ink) and "Clay" (Lab 50, 20, −30).
|
||||
pub fn sample() -> Vec<u8> {
|
||||
ase(&[
|
||||
Block::Color("Sky", b"RGB ", &[0.0, 0.5, 1.0], 0),
|
||||
Block::Color("Ink", b"CMYK", &[1.0, 0.5, 0.0, 0.2], 1),
|
||||
Block::GroupStart("Neutrals"),
|
||||
Block::Color("Mist", b"Gray", &[0.75], 2),
|
||||
Block::Color("Clay", b"LAB ", &[0.5, 20.0, -30.0], 2),
|
||||
Block::GroupEnd,
|
||||
])
|
||||
}
|
||||
@@ -10,6 +10,7 @@
|
||||
//! - [`raster`]: rendering helpers and image comparison with a perceptual tolerance.
|
||||
//! - [`geom`]: geometry assertions (approximate equality, curve sampling, Hausdorff distance).
|
||||
//! - [`pdf`]: hand-written PDF files (page boxes, colour spaces, encryption) for import tests.
|
||||
//! - [`ase`]: hand-written swatch exchange (`.ase`) files for swatch library tests.
|
||||
//!
|
||||
//! This crate may only be used as a dev-dependency (enforced by `cargo xtask layers`).
|
||||
// Test support only (a dev-dependency of every crate that uses it): a failed setup or assertion
|
||||
@@ -18,6 +19,7 @@
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
pub mod ase;
|
||||
pub mod fixtures;
|
||||
pub mod geom;
|
||||
pub mod invariants;
|
||||
|
||||
@@ -259,10 +259,19 @@ impl Tool for ArtboardTool {
|
||||
}
|
||||
}
|
||||
|
||||
/// Delete/Backspace remove the active artboard ahead of the Clear shortcut, which would only
|
||||
/// delete selected art; with one artboard left (it can't be deleted) they stay the shortcut's.
|
||||
fn claims_key(&self, cx: &ToolContext, key: ToolKey) -> bool {
|
||||
matches!(key, ToolKey::Delete | ToolKey::Backspace)
|
||||
&& self.drag.is_none()
|
||||
&& cx.doc.artboards.len() > 1
|
||||
&& self.active < cx.doc.artboards.len()
|
||||
}
|
||||
|
||||
fn key(&mut self, cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec<Action> {
|
||||
match key {
|
||||
ToolKey::Delete | ToolKey::Backspace if self.drag.is_none() => {
|
||||
if cx.doc.artboards.len() <= 1 || self.active >= cx.doc.artboards.len() {
|
||||
ToolKey::Delete | ToolKey::Backspace => {
|
||||
if !self.claims_key(cx, key) {
|
||||
return vec![];
|
||||
}
|
||||
let i = self.active;
|
||||
@@ -522,7 +531,8 @@ mod tests {
|
||||
let a = t.pointer(&cx, &ev(PointerKind::Up, 1100.0, 1050.0));
|
||||
assert_eq!(a[0], Action::Exec("artboard.new".into(), json!({"x": 1000.0, "y": 1000.0, "width": 100.0, "height": 50.0})));
|
||||
assert_eq!(a[1], Action::Notify("created".into()));
|
||||
// Delete removes the active artboard.
|
||||
// Delete removes the active artboard, ahead of the Clear shortcut.
|
||||
assert!(t.claims_key(&cx, ToolKey::Delete) && t.claims_key(&cx, ToolKey::Backspace));
|
||||
assert_eq!(t.key(&cx, ToolKey::Delete, Mods::default()), vec![Action::Exec("artboard.delete".into(), json!({"index": 1}))]);
|
||||
assert_eq!(t.key(&cx, ToolKey::Escape, Mods::default()), vec![Action::SwitchTool("selection".into())]);
|
||||
}
|
||||
|
||||
+45
-4
@@ -4,8 +4,11 @@
|
||||
//! and classic colour quantisation), not from any existing implementation:
|
||||
//!
|
||||
//! 1. **Quantise** the image into a small palette: a luminance threshold (Black and White), 1-D
|
||||
//! k-means over the luminance histogram (Grayscale), or median cut followed by weighted
|
||||
//! k-means over a 15-bit colour histogram (Color). Transparent pixels are left out.
|
||||
//! k-means over the luminance histogram (Grayscale), or, in Color, over a 15-bit colour
|
||||
//! histogram as the [`Palette`] asks: median cut to a colour count followed by weighted k-means
|
||||
//! (Limited), median cut until every colour box is tight (Full Tone), one of those two by
|
||||
//! whether the image is flat art (Automatic), or the most used colours of a swatch library
|
||||
//! (Document Library). Transparent pixels are left out.
|
||||
//! 2. **Remove noise**: 4-connected same-colour components smaller than `noise` pixels are merged
|
||||
//! into their most common neighbouring colour.
|
||||
//! 3. **Follow boundaries**: for each colour layer, the pixel-crack edges between inside and
|
||||
@@ -34,7 +37,7 @@ use vectorcraft_geom::PathData;
|
||||
|
||||
pub use contour::{Component, Loop, trace_mask};
|
||||
pub use mosaic::mosaic;
|
||||
pub use quantize::{Quantized, TRANSPARENT, denoise, quantize};
|
||||
pub use quantize::{FULL_TONE_MAX, Quantized, TRANSPARENT, denoise, quantize};
|
||||
|
||||
/// Errors decoding a raster.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
@@ -132,6 +135,28 @@ pub enum Method {
|
||||
Overlapping,
|
||||
}
|
||||
|
||||
/// Where Color mode's colours come from (the Palette popup).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Palette {
|
||||
/// The `colors` colours that best represent the image.
|
||||
#[default]
|
||||
#[serde(alias = "Limited")]
|
||||
Limited,
|
||||
/// As many colours as the image's tones need, up to [`FULL_TONE_MAX`] (photos, gradients):
|
||||
/// `color_detail` sets how close two colours may be and stay apart.
|
||||
#[serde(alias = "Full Tone")]
|
||||
FullTone,
|
||||
/// Flat art (a few colours cover nearly all of it) traces with exactly those colours, anything
|
||||
/// else as Full Tone.
|
||||
#[serde(alias = "Automatic")]
|
||||
Automatic,
|
||||
/// The most used colours of a swatch library ([`TraceParams::swatches`]), at most `colors` of
|
||||
/// them, exactly as they are.
|
||||
#[serde(alias = "library", alias = "Document Library")]
|
||||
DocumentLibrary,
|
||||
}
|
||||
|
||||
/// Image Trace parameters (the Image Trace panel).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
@@ -139,8 +164,20 @@ pub struct TraceParams {
|
||||
pub mode: Mode,
|
||||
/// Black and White: pixels darker than this (luminance 0–255) are black.
|
||||
pub threshold: u8,
|
||||
/// Palette size for Color, number of grays for Grayscale (2–256).
|
||||
/// Color: where the colours come from.
|
||||
pub palette: Palette,
|
||||
/// Palette size for Color (Limited; at most this many for Document Library), number of grays
|
||||
/// for Grayscale (2–256).
|
||||
pub colors: u32,
|
||||
/// Full Tone and Automatic: how many colours, 0 (few) – 100 (many).
|
||||
pub color_detail: f64,
|
||||
/// Document Library: the swatch library, `"document"` (the document's swatches) or a library id
|
||||
/// or name. The caller looks its colours up into `swatches`.
|
||||
pub library: String,
|
||||
/// Document Library: the library's colours (sRGB). Not saved: they are looked up from
|
||||
/// `library` at every trace.
|
||||
#[serde(skip)]
|
||||
pub swatches: Vec<[u8; 3]>,
|
||||
/// Paths (fidelity) 0–100: higher follows the pixels more tightly.
|
||||
pub paths: f64,
|
||||
/// Corners 0–100: higher keeps more corners.
|
||||
@@ -160,7 +197,11 @@ impl Default for TraceParams {
|
||||
Self {
|
||||
mode: Mode::BlackAndWhite,
|
||||
threshold: 128,
|
||||
palette: Palette::Limited,
|
||||
colors: 6,
|
||||
color_detail: 50.0,
|
||||
library: "document".into(),
|
||||
swatches: vec![],
|
||||
paths: 50.0,
|
||||
corners: 75.0,
|
||||
noise: 25,
|
||||
|
||||
+113
-15
@@ -1,6 +1,6 @@
|
||||
//! Colour reduction and noise removal.
|
||||
|
||||
use crate::{Mode, Raster, TraceParams};
|
||||
use crate::{Mode, Palette, Raster, TraceParams};
|
||||
|
||||
/// Label of a transparent (untraced) pixel.
|
||||
pub const TRANSPARENT: u16 = u16::MAX;
|
||||
@@ -67,10 +67,8 @@ pub fn quantize(img: &Raster, params: &TraceParams) -> Quantized {
|
||||
b.sum[2] += p[2] as u64;
|
||||
}
|
||||
}
|
||||
let used: Vec<(usize, [f64; 3], f64)> =
|
||||
bins.iter().enumerate().filter(|(_, b)| b.n > 0).map(|(i, b)| (i, b.mean(), b.n as f64)).collect();
|
||||
let k = params.colors.clamp(2, 256) as usize;
|
||||
let centers = kmeans_rgb(&used, k);
|
||||
let used: Vec<Used> = bins.iter().enumerate().filter(|(_, b)| b.n > 0).map(|(i, b)| (i, b.mean(), b.n as f64)).collect();
|
||||
let centers = color_palette(&used, params);
|
||||
let mut lut = vec![0u16; 1 << 15];
|
||||
for (i, c, _) in &used {
|
||||
lut[*i] = nearest_rgb(¢ers, *c) as u16;
|
||||
@@ -187,12 +185,108 @@ fn nearest_rgb(centers: &[[f64; 3]], c: [f64; 3]) -> usize {
|
||||
best.1
|
||||
}
|
||||
|
||||
/// Median cut for the initial palette, then weighted k-means refinement over histogram bins.
|
||||
fn kmeans_rgb(used: &[(usize, [f64; 3], f64)], k: usize) -> Vec<[f64; 3]> {
|
||||
/// The most colours Full Tone (and Automatic on continuous-tone images) makes.
|
||||
pub const FULL_TONE_MAX: usize = 256;
|
||||
|
||||
/// A histogram bin in use: its index, mean colour and pixel count.
|
||||
type Used = (usize, [f64; 3], f64);
|
||||
|
||||
/// Color mode's palette for the histogram bins `used`, as `params.palette` asks.
|
||||
fn color_palette(used: &[Used], params: &TraceParams) -> Vec<[f64; 3]> {
|
||||
let k = params.colors.clamp(2, 256) as usize;
|
||||
let detail = (params.color_detail / 100.0).clamp(0.0, 1.0);
|
||||
// Full Tone: split until no colour box is wider than 96 (few colours) … 8 (many) levels per
|
||||
// channel, which is one histogram bin.
|
||||
let full_tone = || refine(used, centers(&median_cut(used, FULL_TONE_MAX, 96.0 - 88.0 * detail)));
|
||||
match params.palette {
|
||||
Palette::Limited => kmeans_rgb(used, k),
|
||||
Palette::FullTone => full_tone(),
|
||||
Palette::Automatic => match flat_colors(used, detail) {
|
||||
Some(n) => kmeans_rgb(used, n),
|
||||
None => full_tone(),
|
||||
},
|
||||
Palette::DocumentLibrary if !params.swatches.is_empty() => library_colors(used, ¶ms.swatches, k),
|
||||
// No library colours to use: as Limited.
|
||||
Palette::DocumentLibrary => kmeans_rgb(used, k),
|
||||
}
|
||||
}
|
||||
|
||||
/// Automatic: how many colours flat art is made of, or `None` for continuous tone (photos,
|
||||
/// gradients). Flat art has most of its pixels in a few tight colours (anti-aliased edges and
|
||||
/// noise aside): the bins holding 90% of the pixels are few, and each colour's pixels sit mostly
|
||||
/// in one bin. `detail` (0–1) lets smaller colour areas count as colours of their own.
|
||||
fn flat_colors(used: &[Used], detail: f64) -> Option<usize> {
|
||||
let total: f64 = used.iter().map(|u| u.2).sum();
|
||||
if total <= 0.0 {
|
||||
return Some(2);
|
||||
}
|
||||
let mut by_count: Vec<&Used> = used.iter().collect();
|
||||
by_count.sort_by(|a, b| b.2.total_cmp(&a.2));
|
||||
let mut covered = 0.0;
|
||||
let main = by_count
|
||||
.iter()
|
||||
.take_while(|u| {
|
||||
let before = covered;
|
||||
covered += u.2;
|
||||
before < 0.9 * total
|
||||
})
|
||||
.count();
|
||||
if main > FLAT_BINS {
|
||||
return None;
|
||||
}
|
||||
let boxes = median_cut(used, 64, 24.0);
|
||||
let min_share = (0.04 - 0.035 * detail) * total;
|
||||
let colours: Vec<&ColorBox> = boxes.iter().filter(|b| b.weight >= min_share).collect();
|
||||
let weight: f64 = colours.iter().map(|b| b.weight).sum();
|
||||
let peaks: f64 = colours.iter().map(|b| b.peak).sum();
|
||||
(weight >= 0.9 * total && peaks >= 0.5 * weight && colours.len() <= 32).then_some(colours.len().max(2))
|
||||
}
|
||||
|
||||
/// The most histogram bins flat art's main colours spread over (a few bins per colour).
|
||||
const FLAT_BINS: usize = 96;
|
||||
|
||||
/// Document Library: the `k` swatches (at most) that the most pixels are nearest to.
|
||||
fn library_colors(used: &[Used], swatches: &[[u8; 3]], k: usize) -> Vec<[f64; 3]> {
|
||||
let mut all: Vec<[f64; 3]> = vec![];
|
||||
for s in swatches {
|
||||
let c = s.map(f64::from);
|
||||
if !all.contains(&c) {
|
||||
all.push(c);
|
||||
}
|
||||
}
|
||||
let mut weight = vec![0.0; all.len()];
|
||||
for (_, c, n) in used {
|
||||
if let Some(w) = weight.get_mut(nearest_rgb(&all, *c)) {
|
||||
*w += n;
|
||||
}
|
||||
}
|
||||
let mut order: Vec<usize> = (0..all.len()).collect();
|
||||
order.sort_by(|a, b| weight[*b].total_cmp(&weight[*a]).then(a.cmp(b)));
|
||||
order.into_iter().take(k.max(1)).filter_map(|i| all.get(i).copied()).collect()
|
||||
}
|
||||
|
||||
/// A median-cut box: its weighted mean colour, pixel count and the pixel count of its heaviest bin.
|
||||
struct ColorBox {
|
||||
mean: [f64; 3],
|
||||
weight: f64,
|
||||
peak: f64,
|
||||
}
|
||||
|
||||
fn centers(boxes: &[ColorBox]) -> Vec<[f64; 3]> {
|
||||
boxes.iter().map(|b| b.mean).collect()
|
||||
}
|
||||
|
||||
/// Median cut to `k` colours, then weighted k-means refinement over histogram bins.
|
||||
fn kmeans_rgb(used: &[Used], k: usize) -> Vec<[f64; 3]> {
|
||||
refine(used, centers(&median_cut(used, k, 0.0)))
|
||||
}
|
||||
|
||||
/// Median cut: repeatedly split the box with the largest weighted extent, while there are fewer
|
||||
/// than `k` boxes and some box spans more than `spread` levels of a channel.
|
||||
fn median_cut(used: &[Used], k: usize, spread: f64) -> Vec<ColorBox> {
|
||||
if used.is_empty() {
|
||||
return vec![[255.0; 3]];
|
||||
return vec![ColorBox { mean: [255.0; 3], weight: 0.0, peak: 0.0 }];
|
||||
}
|
||||
// Median cut: repeatedly split the box with the largest weighted extent.
|
||||
let mut boxes: Vec<Vec<usize>> = vec![(0..used.len()).collect()];
|
||||
while boxes.len() < k {
|
||||
let mut best: Option<(f64, usize, usize)> = None;
|
||||
@@ -210,7 +304,7 @@ fn kmeans_rgb(used: &[(usize, [f64; 3], f64)], k: usize) -> Vec<[f64; 3]> {
|
||||
wsum += used[i].2;
|
||||
}
|
||||
let (ch, range) = (0..3).map(|c| (c, hi[c] - lo[c])).fold((0, -1.0), |a, b| if b.1 > a.1 { b } else { a });
|
||||
if range <= 0.0 {
|
||||
if range <= spread.max(0.0) {
|
||||
continue;
|
||||
}
|
||||
let score = range * wsum.sqrt();
|
||||
@@ -235,21 +329,25 @@ fn kmeans_rgb(used: &[(usize, [f64; 3], f64)], k: usize) -> Vec<[f64; 3]> {
|
||||
boxes.push(b);
|
||||
boxes.push(tail);
|
||||
}
|
||||
let mut centers: Vec<[f64; 3]> = boxes
|
||||
boxes
|
||||
.iter()
|
||||
.map(|b| {
|
||||
let mut s = [0.0; 3];
|
||||
let mut w = 0.0;
|
||||
let (mut w, mut peak) = (0.0, 0.0f64);
|
||||
for &i in b {
|
||||
for (acc, v) in s.iter_mut().zip(used[i].1) {
|
||||
*acc += v * used[i].2;
|
||||
}
|
||||
w += used[i].2;
|
||||
peak = peak.max(used[i].2);
|
||||
}
|
||||
[s[0] / w, s[1] / w, s[2] / w]
|
||||
ColorBox { mean: [s[0] / w, s[1] / w, s[2] / w], weight: w, peak }
|
||||
})
|
||||
.collect();
|
||||
// Lloyd refinement.
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Lloyd refinement of `centers` over the bins `used`.
|
||||
fn refine(used: &[Used], mut centers: Vec<[f64; 3]>) -> Vec<[f64; 3]> {
|
||||
for _ in 0..12 {
|
||||
let mut sum = vec![[0.0; 3]; centers.len()];
|
||||
let mut cnt = vec![0.0; centers.len()];
|
||||
|
||||
@@ -348,3 +348,93 @@ fn an_image_too_large_to_trace_is_refused_before_decoding() {
|
||||
assert!(matches!(err, TraceError::TooLarge { width: 30_000, height: 30_000, .. }), "{err}");
|
||||
assert!(matches!(Raster::decode(&png_header(64, 64)), Err(TraceError::Decode(_))), "a small header goes on to decoding");
|
||||
}
|
||||
|
||||
/// Four flat colours with anti-aliased (blended) edges between the quadrants.
|
||||
fn flat_quads() -> Raster {
|
||||
const C: [[u8; 3]; 4] = [[220, 30, 30], [30, 200, 40], [30, 40, 210], [240, 220, 20]];
|
||||
Raster::from_fn(100, 100, |x, y| {
|
||||
let at = |x: u32, y: u32| C[usize::from(x >= 50) + 2 * usize::from(y >= 50)];
|
||||
let (a, b) = (at(x, y), at(x.saturating_sub(1), y.saturating_sub(1)));
|
||||
// Blend the pixels along the quadrant edges, as an anti-aliased picture has them.
|
||||
let c: Vec<u8> = a.iter().zip(b).map(|(p, q)| ((u16::from(*p) + u16::from(q)) / 2) as u8).collect();
|
||||
[c[0], c[1], c[2], 255]
|
||||
})
|
||||
}
|
||||
|
||||
/// A smooth two-dimensional colour gradient (continuous tone).
|
||||
fn gradient() -> Raster {
|
||||
Raster::from_fn(128, 128, |x, y| [(x * 2) as u8, (y * 2) as u8, (255 - x - y / 2) as u8, 255])
|
||||
}
|
||||
|
||||
fn palette(img: &Raster, palette: Palette, colors: u32, color_detail: f64) -> Vec<[u8; 3]> {
|
||||
let p = TraceParams { mode: Mode::Color, palette, colors, color_detail, noise: 4, ..TraceParams::default() };
|
||||
trace(img, &p).palette
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn palettes_parse_from_their_ids_and_names() {
|
||||
for (id, want) in [
|
||||
("limited", Palette::Limited),
|
||||
("fullTone", Palette::FullTone),
|
||||
("Automatic", Palette::Automatic),
|
||||
("documentLibrary", Palette::DocumentLibrary),
|
||||
("library", Palette::DocumentLibrary),
|
||||
] {
|
||||
let p: TraceParams = serde_json::from_value(serde_json::json!({ "palette": id })).unwrap();
|
||||
assert_eq!(p.palette, want, "{id}");
|
||||
}
|
||||
assert_eq!(TraceParams::default().palette, Palette::Limited);
|
||||
// The library's colours are looked up at every trace, not saved with the settings.
|
||||
let v = serde_json::to_value(TraceParams { swatches: vec![[1, 2, 3]], ..TraceParams::default() }).unwrap();
|
||||
assert!(v.get("swatches").is_none() && v["library"] == "document" && v["colorDetail"] == 50.0, "{v}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_tone_follows_the_tones_the_image_has() {
|
||||
// Flat art keeps its few colours (and the tones of its blended edges); a gradient gets many,
|
||||
// more with more detail.
|
||||
let flat = palette(&flat_quads(), Palette::FullTone, 6, 50.0);
|
||||
assert!((4..=10).contains(&flat.len()), "flat art: {flat:?}");
|
||||
let few = palette(&gradient(), Palette::FullTone, 6, 10.0).len();
|
||||
let many = palette(&gradient(), Palette::FullTone, 6, 90.0).len();
|
||||
assert!(few > 6 && many > few && many <= FULL_TONE_MAX, "{few} then {many} colours");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn automatic_traces_flat_art_with_its_colours_and_photos_in_full_tone() {
|
||||
let flat = palette(&flat_quads(), Palette::Automatic, 2, 50.0);
|
||||
assert_eq!(flat.len(), 4, "the four flat colours, whatever `colors` says: {flat:?}");
|
||||
assert!(flat.iter().any(|c| c[0] > 200 && c[1] < 60 && c[2] < 60), "red is one of them: {flat:?}");
|
||||
let tone = palette(&gradient(), Palette::Automatic, 2, 50.0);
|
||||
assert_eq!(tone.len(), palette(&gradient(), Palette::FullTone, 2, 50.0).len(), "continuous tone: as Full Tone");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn document_library_uses_the_most_used_swatches_exactly() {
|
||||
let swatches = vec![[255, 0, 0], [0, 255, 0], [0, 0, 255], [255, 255, 0], [0, 0, 0], [255, 255, 255]];
|
||||
let p = |colors| TraceParams {
|
||||
mode: Mode::Color,
|
||||
palette: Palette::DocumentLibrary,
|
||||
colors,
|
||||
swatches: swatches.clone(),
|
||||
noise: 4,
|
||||
..TraceParams::default()
|
||||
};
|
||||
let hard = Raster::from_fn(100, 100, |x, y| match (x < 50, y < 50) {
|
||||
(true, true) => [220, 30, 30, 255],
|
||||
(false, true) => [30, 200, 40, 255],
|
||||
(true, false) => [30, 40, 210, 255],
|
||||
(false, false) => [240, 220, 20, 255],
|
||||
});
|
||||
let res = trace(&hard, &p(6));
|
||||
let mut got = res.palette.clone();
|
||||
got.sort_unstable();
|
||||
assert_eq!(got, [[0, 0, 255], [0, 255, 0], [255, 0, 0], [255, 255, 0]], "the nearest swatch of each colour, as it is");
|
||||
assert!(res.paths.iter().all(|t| swatches.contains(&t.color)));
|
||||
// At most `colors` of them: the ones the most pixels are nearest to.
|
||||
let two = trace(&hard, &p(2)).palette;
|
||||
assert!(two.len() <= 2 && two.iter().all(|c| swatches.contains(c)), "{two:?}");
|
||||
// Without library colours, it traces as Limited.
|
||||
let none = TraceParams { swatches: vec![], ..p(4) };
|
||||
assert_eq!(trace(&hard, &none).palette.len(), 4);
|
||||
}
|
||||
@@ -151,6 +151,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
ui.ctx().data_mut(|d| {
|
||||
d.insert_temp(column_left_id(), column.left());
|
||||
d.insert_temp(floating::dock_rect_id(), dock);
|
||||
d.insert_temp(floating::icons_rect_id(), column);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -70,6 +70,12 @@ pub(crate) fn dock_rect_id() -> Id {
|
||||
}
|
||||
|
||||
/// The strip along the window's left edge where the Tools panel docks, as last laid out.
|
||||
/// The icon column's bounds (egui temp memory, one frame old), where panels without a tab in the
|
||||
/// tabbed group go back to when docked.
|
||||
pub(crate) fn icons_rect_id() -> Id {
|
||||
Id::new("floating-icons-rect")
|
||||
}
|
||||
|
||||
pub(crate) fn tools_zone_id() -> Id {
|
||||
Id::new("floating-tools-zone")
|
||||
}
|
||||
@@ -216,7 +222,13 @@ fn drop_target(app: &VectorcraftApp, ctx: &egui::Context, what: Moving, at: Pos2
|
||||
return Some((Drop::Stack(first), head));
|
||||
}
|
||||
}
|
||||
zone(dock_rect_id()).filter(|_| app.ui.dock && app.ui.screen_mode < 3).map(|r| (Drop::Dock, r))
|
||||
let dock = zone(dock_rect_id()).filter(|_| app.ui.dock && app.ui.screen_mode < 3)?;
|
||||
// Panels that aren't tabs of the tabbed group (or all of them, with it collapsed) go back to
|
||||
// their icons: light up the icon column, where they land, rather than the tabs.
|
||||
let tabbed = !app.ui.dock_collapsed
|
||||
&& own.and_then(|i| app.ui.floating_panels.get(i)).is_some_and(|g| ids_of(g).into_iter().any(|p| DockTab::from_id(p).is_some()));
|
||||
let lit = if tabbed { dock } else { ctx.data(|d| d.get_temp::<Rect>(icons_rect_id())).unwrap_or(dock) };
|
||||
Some((Drop::Dock, lit))
|
||||
}
|
||||
|
||||
/// Light up a drop zone: over the docked panels, under the floating ones (the moved one too).
|
||||
@@ -262,7 +274,13 @@ pub fn track(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
let ids = ids_of(g);
|
||||
let active = ids.get(g.active).copied().unwrap_or(id);
|
||||
match drop {
|
||||
Drop::Dock => dock(&mut app.ui, &ids, active),
|
||||
Drop::Dock => {
|
||||
dock(&mut app.ui, &ids, active);
|
||||
// One that went back to its icon pops out of it, so it doesn't seem to vanish.
|
||||
if app.ui.dock_collapsed || DockTab::from_id(active).is_none() {
|
||||
app.ui.open_panel = Some(active.to_string());
|
||||
}
|
||||
}
|
||||
Drop::Stack(onto) => stack(&mut app.ui, &ids, active, onto),
|
||||
}
|
||||
}
|
||||
@@ -607,7 +625,7 @@ mod tests {
|
||||
h.hold(h.title("layers"), over);
|
||||
assert!(h.group("layers").contains(over), "the group follows the pointer");
|
||||
let target = drop_target(&h.app, &h.ctx, Moving::Panel("layers"), over);
|
||||
assert_eq!(target.map(|t| t.0), Some(Drop::Dock), "the dock is the drop zone");
|
||||
assert_eq!(target, Some((Drop::Dock, dock)), "the dock is the drop zone, lit whole: its tab comes back");
|
||||
h.release(over);
|
||||
assert!(h.groups().is_empty(), "docked: {:?}", h.groups());
|
||||
assert_eq!((h.dock_tabs().len(), h.app.ui.dock_tab), (3, DockTab::Layers), "back in the dock, shown");
|
||||
@@ -666,6 +684,24 @@ mod tests {
|
||||
assert_eq!(h.icons().len(), count - 1, "Color is back in the column");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_panel_dropped_on_the_dock_lights_up_and_pops_out_of_its_icon() {
|
||||
let mut h = Harness::new();
|
||||
let count = h.icons().len();
|
||||
h.drag(h.icons()[0].center(), pos2(500.0, 400.0));
|
||||
assert_eq!(h.groups(), [["color"]]);
|
||||
// Over the tabbed group: Color has no tab there, so the icon column lights up, not the tabs.
|
||||
let (dock, column) = (h.temp_rect(dock_rect_id()), h.temp_rect(icons_rect_id()));
|
||||
let over = h.dock_tabs()[1].center();
|
||||
h.hold(h.title("color"), over);
|
||||
assert_eq!(drop_target(&h.app, &h.ctx, Moving::Panel("color"), over), Some((Drop::Dock, column)));
|
||||
assert!(column.width() < dock.width(), "the column, not the whole dock: {column:?} {dock:?}");
|
||||
// Dropped, it's back in the column and pops out of its icon rather than vanishing.
|
||||
h.release(over);
|
||||
assert!(h.groups().is_empty());
|
||||
assert_eq!((h.icons().len(), h.app.ui.open_panel.as_deref()), (count, Some("color")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_popped_out_panel_dragged_by_its_title_floats() {
|
||||
let mut h = Harness::new();
|
||||
|
||||
@@ -1152,6 +1152,11 @@
|
||||
Ignore Ignorar
|
||||
Ignore Artboards (all the art as one page) Ignorar mesas de trabajo (toda la ilustración como una página)
|
||||
Ignore White Ignorar blanco
|
||||
Palette: Paleta:
|
||||
Limited Limitada
|
||||
Full Tone Tono completo
|
||||
Document Library Biblioteca del documento
|
||||
Library: Biblioteca:
|
||||
Image Imagen
|
||||
Image Info Información de imagen
|
||||
Image Map: Mapa de imagen:
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -1151,6 +1151,11 @@
|
||||
Ignore Ignorer
|
||||
Ignore Artboards (all the art as one page) Ignorer les plans de travail (toute l’illustration sur une page)
|
||||
Ignore White Ignorer le blanc
|
||||
Palette: Palette :
|
||||
Limited Limitée
|
||||
Full Tone Tons continus
|
||||
Document Library Bibliothèque du document
|
||||
Library: Bibliothèque :
|
||||
Image Image
|
||||
Image Info Informations sur l’image
|
||||
Image Map: Image cliquable :
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -1151,6 +1151,11 @@
|
||||
Ignore Ignora
|
||||
Ignore Artboards (all the art as one page) Ignora tavole da disegno (tutta la grafica come una sola pagina)
|
||||
Ignore White Ignora bianco
|
||||
Palette: Palette:
|
||||
Limited Limitata
|
||||
Full Tone Tono continuo
|
||||
Document Library Libreria del documento
|
||||
Library: Libreria:
|
||||
Image Immagine
|
||||
Image Info Informazioni immagine
|
||||
Image Map: Mappa immagine:
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -1410,6 +1410,11 @@
|
||||
Ignore 無視
|
||||
Ignore Artboards (all the art as one page) アートボードを無視 (すべてのアートを 1 ページとして扱う)
|
||||
Ignore White 白を無視
|
||||
Palette: パレット:
|
||||
Limited 限定
|
||||
Full Tone フルトーン
|
||||
Document Library ドキュメントライブラリ
|
||||
Library: ライブラリ:
|
||||
Image Info 画像情報
|
||||
Image Map: イメージマップ:
|
||||
Image Size イメージサイズ
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -1149,6 +1149,11 @@
|
||||
Ignore Игнорировать
|
||||
Ignore Artboards (all the art as one page) Игнорировать монтажные области (весь рисунок как одна страница)
|
||||
Ignore White Игнорировать белый
|
||||
Palette: Палитра:
|
||||
Limited Ограниченная
|
||||
Full Tone Полутоновая
|
||||
Document Library Библиотека документа
|
||||
Library: Библиотека:
|
||||
Image Изображение
|
||||
Image Info Сведения об изображении
|
||||
Image Map: Карта изображения:
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -1140,6 +1140,11 @@
|
||||
Ignore 忽略
|
||||
Ignore Artboards (all the art as one page) 忽略画板 (所有图稿作为一页)
|
||||
Ignore White 忽略白色
|
||||
Palette: 调板:
|
||||
Limited 有限
|
||||
Full Tone 全色调
|
||||
Document Library 文档库
|
||||
Library: 库:
|
||||
Image 图像
|
||||
Image Info 图像信息
|
||||
Image Map: 图像映射:
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -1169,6 +1169,11 @@
|
||||
Ignore 略過
|
||||
Ignore Artboards (all the art as one page) 忽略工作區域 (所有圖稿視為單一頁面)
|
||||
Ignore White 忽略白色
|
||||
Palette: 調色盤:
|
||||
Limited 有限
|
||||
Full Tone 全色調
|
||||
Document Library 文件資料庫
|
||||
Library: 資料庫:
|
||||
Image 影像
|
||||
Image Info 影像資訊
|
||||
Image Map: 影像地圖:
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -43,6 +43,8 @@ pub fn open_bytes(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Opti
|
||||
if swatches || ext == vectorcraft_doc::style_libs::STYLES_EXT {
|
||||
let p = match path {
|
||||
Some(path) => serde_json::json!({ "path": path }),
|
||||
// `.ase` swatch libraries are binary.
|
||||
None if swatches => serde_json::json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(bytes)}),
|
||||
None => serde_json::json!({"name": name, "data": String::from_utf8_lossy(bytes)}),
|
||||
};
|
||||
let load = if swatches { crate::panels::swatches::load_library } else { crate::panels::graphic_styles::load_library };
|
||||
|
||||
@@ -346,7 +346,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"window.swatchLibrary.other",
|
||||
"Other Library…",
|
||||
"",
|
||||
"{path?} (default: pick a file) load a .vcswatches or .gpl library, or another document's swatches (engine: swatch.library.load), and open it in the library panel",
|
||||
"{path?} (default: pick a file) load a .vcswatches, .gpl or .ase library, or another document's swatches (engine: swatch.library.load), and open it in the library panel",
|
||||
),
|
||||
(
|
||||
"ui.saveSwatchLibrary",
|
||||
|
||||
@@ -1,17 +1,50 @@
|
||||
//! Image Trace panel: preset, mode, threshold or colour count, and the advanced fidelity options.
|
||||
//! Image Trace panel: preset, mode, palette (Color), threshold or colour count, and the advanced
|
||||
//! fidelity options.
|
||||
//! With an Image Trace object selected, changing a setting re-traces it (one undo step per change;
|
||||
//! sliders apply when released). With an image selected, Trace makes a new Image Trace object.
|
||||
|
||||
use egui::Ui;
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Node, NodeKind};
|
||||
use vectorcraft_engine::cmd::swatchlib::DOCUMENT_SWATCHES;
|
||||
|
||||
use super::{first_selected, pstate, set_pstate};
|
||||
use super::{first_selected, library_panel, pstate, set_pstate, swatches};
|
||||
use crate::VectorcraftApp;
|
||||
use crate::widgets::{self, menu_item};
|
||||
|
||||
const MODES: [(&str, &str); 3] = [("blackAndWhite", "Black and White"), ("grayscale", "Grayscale"), ("color", "Color")];
|
||||
|
||||
/// Color mode's palettes (`palette` param ids), in panel order.
|
||||
const PALETTES: [&str; 4] = ["limited", "fullTone", "automatic", "documentLibrary"];
|
||||
|
||||
/// Palette `id`, in the UI language.
|
||||
fn palette_label(id: &str) -> &'static str {
|
||||
match id {
|
||||
"fullTone" => tl!("Full Tone"),
|
||||
"automatic" => tl!("Automatic"),
|
||||
"documentLibrary" => tl!("Document Library"),
|
||||
_ => tl!("Limited"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The name of Document Library's library `key` (the document's swatches or a swatch library); a
|
||||
/// library that is gone shows its key.
|
||||
fn library_label(app: &VectorcraftApp, key: &str) -> String {
|
||||
match swatches::limit_name(app, key) {
|
||||
Some(_) if key == DOCUMENT_SWATCHES => tl!(swatches::DOCUMENT_SWATCHES).to_string(),
|
||||
Some(name) => library_panel::library_name(key, &name).to_string(),
|
||||
None => key.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Document Library's choices: the document's swatches, then the colour libraries (`current`
|
||||
/// checked) → the key chosen.
|
||||
fn library_list(app: &VectorcraftApp, ui: &mut Ui, current: &str) -> Option<String> {
|
||||
let document = menu_item(ui, swatches::DOCUMENT_SWATCHES, true, current == DOCUMENT_SWATCHES).then(|| DOCUMENT_SWATCHES.to_string());
|
||||
ui.separator();
|
||||
library_panel::library_items(ui, &swatches::colour_libraries(app), Some(current)).or(document)
|
||||
}
|
||||
|
||||
/// Panel state: the preset name, the current parameters and the last result's counts.
|
||||
#[derive(Clone, Default)]
|
||||
struct TraceUi {
|
||||
@@ -167,16 +200,41 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
retrace = true;
|
||||
}
|
||||
});
|
||||
let bw = st.params["mode"].as_str() == Some("blackAndWhite");
|
||||
let (key, label, range) = if bw {
|
||||
("threshold", tl!("Threshold"), 0.0..=255.0)
|
||||
} else {
|
||||
("colors", if st.params["mode"] == "grayscale" { tl!("Grays") } else { tl!("Colors") }, 2.0..=256.0)
|
||||
let mode = st.params["mode"].as_str().unwrap_or("blackAndWhite").to_string();
|
||||
let palette = st.params["palette"].as_str().unwrap_or("limited").to_string();
|
||||
if mode == "color" {
|
||||
ui.horizontal(|ui| {
|
||||
widgets::dim_label(ui, tl!("Palette:"));
|
||||
let labels = PALETTES.map(palette_label);
|
||||
if let Some(p) = widgets::dropdown_names(ui, "it-palette", palette_label(&palette), &labels, 170.0).and_then(|i| PALETTES.get(i)) {
|
||||
st.params["palette"] = json!(p);
|
||||
st.preset = "Custom".into();
|
||||
retrace = true;
|
||||
}
|
||||
});
|
||||
if palette == "documentLibrary" {
|
||||
ui.horizontal(|ui| {
|
||||
widgets::dim_label(ui, tl!("Library:"));
|
||||
let key = st.params["library"].as_str().unwrap_or(DOCUMENT_SWATCHES).to_string();
|
||||
if let Some(k) = widgets::combo(ui, "it-library", &library_label(app, &key), 170.0, false, |ui| library_list(app, ui, &key)) {
|
||||
st.params["library"] = json!(k);
|
||||
st.preset = "Custom".into();
|
||||
retrace = true;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
// Full Tone and Automatic: how many colours (Less … More); else a count or the threshold.
|
||||
let (key, label, range, suffix) = match mode.as_str() {
|
||||
"blackAndWhite" => ("threshold", tl!("Threshold"), 0.0..=255.0, ""),
|
||||
"grayscale" => ("colors", tl!("Grays"), 2.0..=256.0, ""),
|
||||
_ if matches!(palette.as_str(), "fullTone" | "automatic") => ("colorDetail", tl!("Colors"), 0.0..=100.0, "%"),
|
||||
_ => ("colors", tl!("Colors"), 2.0..=256.0, ""),
|
||||
};
|
||||
let mut v = st.params[key].as_f64().unwrap_or(0.0);
|
||||
let (changed, release) = slider(ui, label, &mut v, range, "");
|
||||
let (changed, release) = slider(ui, label, &mut v, range, suffix);
|
||||
if changed {
|
||||
st.params[key] = json!(v.round() as u64);
|
||||
st.params[key] = if key == "colorDetail" { json!(v.round()) } else { json!(v.round() as u64) };
|
||||
st.preset = "Custom".into();
|
||||
}
|
||||
retrace |= release;
|
||||
@@ -258,6 +316,61 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use egui::{Event, PointerButton, Pos2, Rect, vec2};
|
||||
|
||||
/// One headless frame of the panel (and its menu) with `events`: the texts drawn, with where.
|
||||
fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec<Event>) -> Vec<(String, Rect)> {
|
||||
let screen = Rect::from_min_size(Pos2::ZERO, vec2(280.0, 700.0));
|
||||
let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }, |ui| show(app, ui));
|
||||
out.textures_delta.clear();
|
||||
crate::tests_removeanchors::shapes_text(&out.shapes.iter().map(|c| c.shape.clone()).collect::<Vec<_>>())
|
||||
}
|
||||
|
||||
/// Click the panel's `label` (the first one drawn).
|
||||
fn click(app: &mut VectorcraftApp, ctx: &egui::Context, label: &str) {
|
||||
let texts = frame(app, ctx, vec![]);
|
||||
let at = texts.iter().find(|(t, _)| t == label).map(|(_, r)| r.center()).unwrap_or_else(|| panic!("no `{label}` in {texts:?}"));
|
||||
let press = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() };
|
||||
frame(app, ctx, vec![Event::PointerMoved(at), press(true)]);
|
||||
frame(app, ctx, vec![press(false)]);
|
||||
}
|
||||
|
||||
fn traced_app() -> VectorcraftApp {
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
let img = image::RgbaImage::from_fn(20, 20, |x, _| image::Rgba(if x < 10 { [0, 0, 0, 255] } else { [255, 255, 255, 255] }));
|
||||
let mut png = vec![];
|
||||
img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
|
||||
let data = vectorcraft_format::base64_encode(&png);
|
||||
app.run("file.place", json!({"name": "half.png", "dataBase64": data, "link": false})).unwrap();
|
||||
app.run("imageTrace.make", json!({"preset": "Default"})).unwrap();
|
||||
app
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_palette_shows_in_color_mode_and_traces_again() {
|
||||
let mut app = traced_app();
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
let has = |texts: &[(String, Rect)], s: &str| texts.iter().any(|(t, _)| t == s);
|
||||
let palette = |app: &VectorcraftApp| target(app).2.map(|t| t["params"]["palette"].clone());
|
||||
assert!(!has(&frame(&mut app, &ctx, vec![]), "Palette:"), "Black and White has no palette");
|
||||
app.run("imageTrace.make", json!({"preset": "6 Colors"})).unwrap();
|
||||
let texts = frame(&mut app, &ctx, vec![]);
|
||||
assert!(has(&texts, "Palette:") && has(&texts, "Limited") && !has(&texts, "Library:"), "{texts:?}");
|
||||
// Document Library traces again with the document's swatches, and names them.
|
||||
click(&mut app, &ctx, "Limited");
|
||||
click(&mut app, &ctx, "Document Library");
|
||||
assert_eq!(palette(&app), Some(json!("documentLibrary")));
|
||||
let texts = frame(&mut app, &ctx, vec![]);
|
||||
assert!(has(&texts, "Library:") && has(&texts, "Document Swatches"), "{texts:?}");
|
||||
// Full Tone's Colors is how many, Less (0%) … More (100%).
|
||||
click(&mut app, &ctx, "Document Library");
|
||||
click(&mut app, &ctx, "Full Tone");
|
||||
assert_eq!(palette(&app), Some(json!("fullTone")));
|
||||
let texts = frame(&mut app, &ctx, vec![]);
|
||||
assert!(has(&texts, "50") && !has(&texts, "Library:"), "{texts:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn panel_and_menu_draw_headless() {
|
||||
@@ -266,6 +379,7 @@ mod tests {
|
||||
app.session.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap();
|
||||
for _ in 0..2 {
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| {
|
||||
show(&mut app, ui);
|
||||
menu(&mut app, ui);
|
||||
|
||||
@@ -616,4 +616,16 @@ mod tests {
|
||||
}
|
||||
assert!(!builtin_library(&open.id) && builtin_library(vectorcraft_engine::cmd::swatchlib::DOCUMENT_SWATCHES));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn swatch_exchange_files_without_a_path_open_in_the_library_panel() {
|
||||
// A file opened on the web has no path; open_bytes passes its bytes as dataBase64.
|
||||
let mut app = app();
|
||||
crate::io::open_bytes(&mut app, "Brand.ase", &vectorcraft_testkit::ase::sample(), None).unwrap();
|
||||
let open = app.ui.library_panel.clone().unwrap();
|
||||
assert_eq!(open.id, "loaded/Brand.ase");
|
||||
let (_, lib) = SwatchLibraries::get(&app, &open.id).unwrap();
|
||||
assert_eq!((lib.len(), lib.groups.len()), (4, 1));
|
||||
assert_eq!(app.session.documents().len(), 1, "not opened as a document");
|
||||
}
|
||||
}
|
||||
@@ -37,7 +37,7 @@ fn labels(items: &[Item]) -> Vec<&'static str> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn shapes_text(shapes: &[Shape]) -> Vec<(String, Rect)> {
|
||||
pub(crate) fn shapes_text(shapes: &[Shape]) -> Vec<(String, Rect)> {
|
||||
fn walk(s: &Shape, v: &mut Vec<(String, Rect)>) {
|
||||
match s {
|
||||
Shape::Text(t) => v.push((t.galley.text().to_string(), Rect::from_min_size(t.pos, t.galley.size()))),
|
||||
|
||||
@@ -154,7 +154,7 @@ Clicking a swatch there runs `swatch.library.add {library, names: [name], apply}
|
||||
one with Alt), so one undo step adds and applies it; Shift/Cmd-clicks select swatches and colour groups for
|
||||
Add to Swatches.
|
||||
`window.swatchLibrary.other {path?}` loads a library file (or another document's swatches) and opens it there;
|
||||
opening a `.vcswatches` or `.gpl` file with `app.open` does the same. `ui.saveSwatchLibrary {names?}` opens the
|
||||
opening a `.vcswatches`, `.gpl` or `.ase` file with `app.open` does the same. `ui.saveSwatchLibrary {names?}` opens the
|
||||
`saveSwatchLibrary` dialog (fields `name`, `format`: `vcswatches`/`gpl`/`css`, `user`: save to the user library
|
||||
folder, `selectedOnly` with `names`); `ui.dialog.confirm` runs `swatch.library.save` (to a file it asks for a path).
|
||||
|
||||
|
||||
+1
-1
@@ -239,7 +239,7 @@ web build has no net at all.
|
||||
Untrusted input has property tests that must never panic:
|
||||
|
||||
- `crates/engine/tests/import_fuzz.rs`: garbage, hostile and mutated SVG and PDF, and swatch
|
||||
(`.vcswatches`, `.gpl`), graphic style (`.vcstyles`) and flattener preset (`.vcflattener`)
|
||||
(`.vcswatches`, `.gpl`, `.ase`), graphic style (`.vcstyles`) and flattener preset (`.vcflattener`)
|
||||
libraries, loaded and used, then rendered and exported.
|
||||
- `crates/engine/tests/command_sweep.rs`: every command with junk parameters.
|
||||
- `crates/format/tests/prop_format.rs`: garbage and mutated `.vectorcraft` files.
|
||||
|
||||
+3
-1
@@ -740,7 +740,9 @@ swatch in the library panel does). `swatch.resetDefaults {replace?}` brings back
|
||||
as a library (`.vcswatches` keeps colour models, global, spot, gradients and colour groups; `.gpl` is 8-bit RGB;
|
||||
CSS writes custom properties); without `path` it returns `{data}`, and `user: true` saves into the user library
|
||||
folder of the desktop app (listed as category `user`, User Defined). `swatch.library.load {path? | data? |
|
||||
dataBase64?, name?}` loads a `.vcswatches` or `.gpl` file, or another document's swatches, as a library to add from.
|
||||
dataBase64?, name?}` loads a `.vcswatches`, `.gpl` or swatch exchange (`.ase`) file, or another document's swatches,
|
||||
as a library to add from. From an `.ase` file it reads RGB, CMYK, Lab and Gray colors as global, spot or process
|
||||
swatches and keeps their color groups.
|
||||
|
||||
## Graphic style libraries
|
||||
|
||||
|
||||
Reference in new issue
Block a user