Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
965fc449e1 | ||
|
|
977e5d1967 | ||
|
|
b73e19eef2 | ||
|
|
4792bd82a2 | ||
|
|
d5e6be1565 | ||
|
|
a469568c7d | ||
|
|
53b4845f6f | ||
|
|
5f92f5eb7f |
No files matched your search
+4
-4
@@ -4,7 +4,7 @@ VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adob
|
||||
|
||||
This file tracks **how far we are and what's left**. Time estimates are wall-clock hours of continuous Claude Opus 5.5 agent work (including builds and the CI gate), given both for **one agent** and for **4–6 parallel agents** on disjoint crates. They are counted from the remaining work (see [Parity estimate](#parity-estimate)), calibrated against measured throughput, and updated as work lands.
|
||||
|
||||
_Last updated: 2026-10-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
|
||||
|
||||
@@ -134,9 +134,9 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist
|
||||
- **Temporary tools:** Cmd with any other tool drags with the selection tool used last (Selection, Direct Selection or Group Selection). Held Space pans and Cmd+Space zooms (Cmd+Alt+Space out) whatever the tool.
|
||||
- **Panel drag and drop:** art dragged off the canvas onto the Symbols panel becomes a symbol, onto the Swatches panel a pattern swatch and onto the Brushes panel an Art brush; a symbol dragged onto the canvas places an instance where it is dropped, and a brush dragged onto a path is applied to it.
|
||||
- **Tool double-clicks:** double-clicking a tool's button opens its options: Hand fits the artboard in the window, Zoom shows 100 %, Rotate, Scale, Reflect and Shear open their Object › Transform dialogs, the Selection, Direct Selection and Group Selection tools the Move dialog (Enter opens these seven tools' dialogs too), Gradient, Eyedropper, Blend and the Liquify tools their panels or options, and the Pencil, Paintbrush, Smooth, Blob Brush and Eraser tools their Tool Options (Fidelity, fill, the tolerances, the brush size).
|
||||
- **Layers panel:** every layer, sublayer, group and object is a clickable row at any depth: a click highlights it and makes its layer current (new art goes there), Shift-click a range, Ctrl/Cmd-click toggles. Sublayers are no longer treated as objects: clicks, marquees, Select All and the Select menu take the art inside them, and each sublayer selects in its own colour. Selection squares on rows with selected art (click selects a row's art, Shift adds or removes; dragging the square moves the selection to another row, Alt copies), the eye and lock on every row with drag-down-the-column (one undo step), Ctrl/Cmd-click an eye for per-layer Outline, Alt-click an eye or lock to hide or lock the other layers (again: show or unlock them all), triangles with Alt to open or close everything inside, drag and drop rows above, below or into layers and groups with a drop line (Alt copies) and a dimmed copy of the row under the pointer (dropped on the trash rows are deleted, on New Layer duplicated, as in Illustrator), inline rename, Delete key on highlighted rows. Buttons and the full panel menu: New Layer/Sublayer (Alt: options, Ctrl: on top), Duplicate, Delete, Options for Selection, clipping mask, isolation, Locate Object, Merge Selected, Flatten Artwork, Collect in New Layer, Release to Layers (Sequence and Build), Reverse Order, Template, Hide/Outline/Lock Others and Show/Preview/Unlock All, Paste Remembers Layers, Panel Options (row size, thumbnails per kind, Show Layers Only). Layer Options: name, colour (presets, each with a chip of its colour, or custom), Template, Lock, Show, Print, Preview (outline drawing and clicking) and Dim Images to %. Every operation is a command (`layer.move`, `layer.highlight`, `layer.merge`…) with validation against cycles and invalid nesting.
|
||||
- **Layers panel:** every layer, sublayer, group and object is a clickable row at any depth: a click highlights it and makes its layer current (new art goes there), Shift-click a range, Ctrl/Cmd-click toggles. Sublayers are no longer treated as objects: clicks, marquees, Select All and the Select menu take the art inside them, and each sublayer selects in its own colour. Selection squares on rows with selected art (click selects a row's art, Shift adds or removes; dragging the square moves the selection to another row, Alt copies), the eye and lock on every row with drag-down-the-column (one undo step), Ctrl/Cmd-click an eye for per-layer Outline, Alt-click an eye or lock to hide or lock the other layers (again: show or unlock them all), triangles with Alt to open or close everything inside, drag and drop rows above, below or into layers and groups with a drop line (Alt copies) and a dimmed copy of the row under the pointer (dropped on the trash rows are deleted, on New Layer duplicated, as in Illustrator), inline rename, Delete key on highlighted rows. Buttons and the full panel menu: New Layer/Sublayer (Alt: options, Ctrl: on top), Duplicate, Delete, Options for Selection, clipping mask, isolation, Locate Object, Merge Selected, Flatten Artwork, Collect in New Layer, Release to Layers (Sequence and Build), Reverse Order, Template, Hide/Outline/Lock Others and Show/Preview/Unlock All, Paste Remembers Layers, Panel Options (row size, thumbnails per kind, Show Layers Only). Layer Options: name, colour (presets, each with a chip of its colour, or custom), Template, Lock, Show, Print, Preview (outline drawing and clicking) and Dim Images to %. Every operation is a command (`layer.move`, `layer.highlight`, `layer.merge`…) with validation against cycles and invalid nesting. A document opens with only its top-level layers open; the rows left open are saved in the native file (nothing is written for the default) and reopen that way. Only the rows scrolled into view are laid out, from a row list made once per change: a layer of 5,000 groups of 10 paths, all open, draws the panel in 0.4 ms a frame instead of about 29 s (#638).
|
||||
- **Drawing aids:** Smart Guides and snapping (moving, with the Selection, Group Selection or Direct Selection tool, and resizing by the bounding-box handles with the Selection or Free Transform tool, Shift and Alt too: the dragged corner or side lands on the other objects' anchors and centres ("anchor", "center") or lines up with their edges and centres (a line and "align"); the Rotate, Scale, Shear and Reflect tools drag from the anchor they grab and snap the pointer the same way, so a corner dragged onto another object's anchor scales exactly onto it, #482; anchors dragged with Direct Selection: the one pressed on lands on other anchors, its own path's that stay put among them, on path segments or in line with them, the others following, Shift keeps 45° steps, and with Smart Guides off Snap to Point pulls it onto anchors; the Artboard tool snaps artboards, and their bleed, to other artboards, bleeds and art, the grid or whole pixels while moving, copying and resizing them, and the Transform panel shows and edits the active artboard's X/Y/W/H; drawn points, #506: hovering shows where the press goes, the point lands on the other objects' anchors, centres and paths ("anchor", "center", "path") or lines up with their anchors, edges and centres ("align"), the Pen's on the path being drawn too, near a construction guide through the anchor before it on that guide (Preferences › Smart Guides › Construction Guides and Angles), and with Shift kept to its 45° step or a square's diagonal it slides along that way into line; the targets are gathered once per document state, from the art in the window, and the anchors, centres and lines near the pointer are found by bisection, so hovering never rescans the document), guides dragged out of the rulers (#451: they snap as moved guides do, Shift to the ruler's ticks; with the Artboard tool they are artboard guides, which run across their artboard only and move, copy and delete with it, `guide.add {artboard}`) that the Selection, Direct Selection and Group Selection tools then pick and drag (#414: the selected guides highlight and move together, Alt copies them, Shift snaps the dragged one to the ticks, otherwise it snaps to pixels, the grid or the edges, centres (so the sides' midpoints) and anchors of the art and the artboards, or with Smart Guides off Snap to Point pulls it onto anchors; the arrow keys nudge them, Delete deletes them, dragging one back onto its ruler deletes it, Lock Guides and Hide Guides leave them alone; `guide.list`, `guide.select`, `guide.move` and `guide.remove` reach agents), a right-click on either ruler or the origin box to pick the document's units (the current one checked; `document.setUnits`, one undo step, #528), and Draw Normal / Behind / Inside modes.
|
||||
- **Views:** the status bar's artboard navigator (first, previous, next, last; `view.goToArtboard`) goes to an artboard and fits it, and Fit Artboard in Window and Actual Size show the navigator's artboard. The Artboards panel highlights that active artboard: clicking a row makes it active (the Artboard tool's too, while it is chosen) as does clicking an artboard with the Artboard tool, double-clicking its number also fits it in the window and double-clicking its name renames it. Duplicate Artboards, or a row dragged onto New Artboard, copies the artboard with its art (#446). Escape leaves Presentation Mode, F from it goes back to Normal Screen Mode, and the screen mode isn't saved with the preferences: the app always starts in Normal Screen Mode with its menus and panels (#472).
|
||||
- **Views:** the status bar's artboard navigator (first, previous, next, last; `view.goToArtboard`) goes to an artboard and fits it, and Fit Artboard in Window and Actual Size show the navigator's artboard. The Artboards panel highlights that active artboard: clicking a row makes it active (the Artboard tool's too, while it is chosen) as does clicking an artboard with the Artboard tool, double-clicking its number also fits it in the window and double-clicking its name renames it. Duplicate Artboards, or a row dragged onto New Artboard, copies the artboard with its art (#446). Escape leaves Presentation Mode, F from it goes back to Normal Screen Mode, and the screen mode isn't saved with the preferences: the app always starts in Normal Screen Mode with its menus and panels (#472). View › Pixel Preview shows the art as the document pixels it rasterizes to, one per point and hard-edged when magnified, turning with a rotated view (it used to draw the smooth vectors, with only the pixel grid over them).
|
||||
- **Geometry and effects:**
|
||||
- Pathfinder (10 exact curve booleans), Offset, Outline Stroke, Simplify, Clean Up, Split Into Grid, Divide Objects Below. Object › Path › Remove Anchor Points (`path.removeAnchors`) removes the direct-selected anchors without opening their paths (the Delete key still deletes them with their segments): the neighbours keep their handle directions and their facing handles are refitted so one cubic follows the two old segments, and straight sides stay straight. The Delete Anchor Point tool uses the same refit. The Control bar, the contextual task bar, the Properties quick actions and the canvas context menu offer it when anchors are selected. With anchors selected, the Control bar and the Properties panel also convert them to corner or smooth (`path.convertAnchors`), connect end points (Join) and cut the path at them (`path.cutAtAnchors`, also on the task bar and the context menu): a closed path opens there and an open one becomes one path per piece, each cut leaving one of its two coincident anchors selected so a drag pulls the path apart.
|
||||
- Live effects with previewing dialogs: Distort & Transform, Path, Convert to Shape, 15 Warp styles, Round Corners, Scribble, Effect → Pathfinder (all 10 operations, live on groups; several loose objects are grouped first, in one undo step), Color Adjustments (Brightness/Contrast, Curves, Levels, Hue/Saturation, Shift to Color, Temperature/Tint, on vectors, live type and embedded images), and raster drop shadow, glows and feather. SVG and PDF export keep live effects (geometry baked; SVG raster effects as filters).
|
||||
@@ -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); 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; 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).
|
||||
|
||||
@@ -610,6 +610,11 @@ pub struct Document {
|
||||
/// save time only, so changing the view never marks the document modified.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub last_view: Option<SavedView>,
|
||||
/// The layers, sublayers and groups open in the Layers panel when the document was saved; they
|
||||
/// reopen that way. `None`: the default, only the top-level layers open. Written at save time
|
||||
/// only, like [`Document::last_view`].
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub layers_open: Option<Vec<NodeId>>,
|
||||
/// Edit → Assign Profile: the profiles the document is tagged with (files before format v3
|
||||
/// kept them in `unknown`, see [`Document::migrate_color_profiles`]).
|
||||
#[serde(default, skip_serializing_if = "ColorProfiles::is_empty")]
|
||||
@@ -702,6 +707,7 @@ impl Document {
|
||||
metadata: DocMetadata::default(),
|
||||
raster_effects: RasterEffectsSettings::default(),
|
||||
last_view: None,
|
||||
layers_open: None,
|
||||
color_profiles: ColorProfiles::default(),
|
||||
export_settings: Default::default(),
|
||||
extra: Default::default(),
|
||||
|
||||
@@ -216,15 +216,20 @@ fn is_svg(f: &Format) -> bool {
|
||||
matches!(f.id, "svg" | "svgz")
|
||||
}
|
||||
|
||||
/// The document as written: native files carry the view to reopen at.
|
||||
/// The document as written: native files carry the view to reopen at and the Layers panel's open
|
||||
/// rows.
|
||||
fn doc_to_save(st: &DocState, f: &Format) -> Arc<Document> {
|
||||
if is_native(f) && st.doc.last_view != st.view {
|
||||
let mut d = (*st.doc).clone();
|
||||
d.last_view = st.view.clone();
|
||||
Arc::new(d)
|
||||
} else {
|
||||
st.doc.clone()
|
||||
if !is_native(f) {
|
||||
return st.doc.clone();
|
||||
}
|
||||
let open = st.layers_open.saved(&st.doc);
|
||||
if st.doc.last_view == st.view && st.doc.layers_open == open {
|
||||
return st.doc.clone();
|
||||
}
|
||||
let mut d = (*st.doc).clone();
|
||||
d.last_view = st.view.clone();
|
||||
d.layers_open = open;
|
||||
Arc::new(d)
|
||||
}
|
||||
|
||||
/// What a format loses against a native file (reported whenever a save writes it).
|
||||
@@ -274,6 +279,7 @@ fn artboard_doc(doc: &Document, i: usize) -> Document {
|
||||
d.artboards = vec![a.clone()];
|
||||
// It opens fitted to its artboard, not at the master file's view.
|
||||
d.last_view = None;
|
||||
d.layers_open = None;
|
||||
for layer in &mut d.layers {
|
||||
keep_on(layer, r);
|
||||
}
|
||||
|
||||
@@ -153,6 +153,8 @@ pub struct DocState {
|
||||
pub recovery: Option<cmd::recovery::RecoveryCopy>,
|
||||
/// View → Show Print Tiling, per document (view state: not saved, not undoable).
|
||||
pub print_tiling: bool,
|
||||
/// The rows open in the Layers panel (view state: not undoable; native files keep it).
|
||||
pub layers_open: OpenRows,
|
||||
/// Transform Again after a perspective move or scale (Perspective Selection tool): the
|
||||
/// `perspective.transform` params it repeats. `None` once an ordinary transform follows.
|
||||
pub last_perspective: Option<Value>,
|
||||
@@ -160,11 +162,61 @@ pub struct DocState {
|
||||
|
||||
static NEXT_DOC_UID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
|
||||
|
||||
/// The rows open in the Layers panel: the layers, sublayers and groups that show what they hold.
|
||||
/// A document opens with the ones it was saved with ([`Document::layers_open`]), else with only
|
||||
/// its top-level layers open.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct OpenRows {
|
||||
ids: std::collections::HashSet<NodeId>,
|
||||
/// Counts the changes, so views can keep what they work out from the open rows.
|
||||
generation: u64,
|
||||
}
|
||||
|
||||
impl OpenRows {
|
||||
/// The rows `saved` in a file, else `doc`'s top-level layers.
|
||||
fn new(doc: &Document, saved: Option<Vec<NodeId>>) -> Self {
|
||||
let ids = match saved {
|
||||
Some(ids) => ids.into_iter().collect(),
|
||||
None => doc.layers.iter().map(|l| l.id).collect(),
|
||||
};
|
||||
Self { ids, generation: 0 }
|
||||
}
|
||||
pub fn contains(&self, id: NodeId) -> bool {
|
||||
self.ids.contains(&id)
|
||||
}
|
||||
/// Open or close row `id`.
|
||||
pub fn set(&mut self, id: NodeId, open: bool) {
|
||||
let changed = if open { self.ids.insert(id) } else { self.ids.remove(&id) };
|
||||
self.generation += u64::from(changed);
|
||||
}
|
||||
/// Changes so far: the same number means the same open rows.
|
||||
pub fn generation(&self) -> u64 {
|
||||
self.generation
|
||||
}
|
||||
/// What a native file keeps of the open rows: those of `doc` that hold others, in id order;
|
||||
/// `None` when they are the default (only the top-level layers).
|
||||
pub fn saved(&self, doc: &Document) -> Option<Vec<NodeId>> {
|
||||
let mut ids = vec![];
|
||||
doc.walk(|n| {
|
||||
if n.children().is_some() && self.ids.contains(&n.id) {
|
||||
ids.push(n.id);
|
||||
}
|
||||
});
|
||||
ids.sort_unstable();
|
||||
let mut layers: Vec<NodeId> = doc.layers.iter().map(|l| l.id).collect();
|
||||
layers.sort_unstable();
|
||||
(ids != layers).then_some(ids)
|
||||
}
|
||||
}
|
||||
|
||||
impl DocState {
|
||||
pub fn new(mut doc: Document, path: Option<String>) -> Self {
|
||||
let active_layer = doc.default_layer();
|
||||
// The saved view lives here while the document is open (saves write it back).
|
||||
// The saved view and open Layers rows live here while the document is open (saves write
|
||||
// them back).
|
||||
let view = doc.last_view.take();
|
||||
let saved_open = doc.layers_open.take();
|
||||
let layers_open = OpenRows::new(&doc, saved_open);
|
||||
let doc = Arc::new(doc);
|
||||
Self {
|
||||
saved_doc: doc.clone(),
|
||||
@@ -190,6 +242,7 @@ impl DocState {
|
||||
recovered: false,
|
||||
recovery: None,
|
||||
print_tiling: false,
|
||||
layers_open,
|
||||
last_perspective: None,
|
||||
}
|
||||
}
|
||||
@@ -956,6 +1009,7 @@ impl Session {
|
||||
st.save_options = old.save_options.clone();
|
||||
st.converted = old.converted;
|
||||
st.view = old.view.clone();
|
||||
st.layers_open = old.layers_open.clone();
|
||||
let old = std::mem::replace(&mut self.docs[index], st);
|
||||
if let Some(stash) = &mut self.batch_stash {
|
||||
stash.push(old);
|
||||
|
||||
@@ -260,6 +260,37 @@ fn the_saved_view_round_trips_without_dirtying() {
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_layers_rows_round_trip_without_dirtying() {
|
||||
let d = dir("open-rows");
|
||||
let mut s = session();
|
||||
let layer = s.doc().unwrap().doc.layers[0].id;
|
||||
let a = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a]})).unwrap();
|
||||
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
// A document starts with its top-level layers open, and a file keeps nothing for that.
|
||||
assert!(s.doc().unwrap().layers_open.contains(layer) && !s.doc().unwrap().layers_open.contains(g));
|
||||
let native = path(&d, "rows.vectorcraft");
|
||||
s.execute("document.save", &json!({"path": native})).unwrap();
|
||||
let bytes = std::fs::read(&native).unwrap();
|
||||
assert_eq!(vectorcraft_format::load(&bytes).unwrap().layers_open, None);
|
||||
// Opening the group and closing the layer is view state: not an edit, kept by the file.
|
||||
let st = s.doc_mut().unwrap();
|
||||
st.layers_open.set(g, true);
|
||||
st.layers_open.set(layer, false);
|
||||
assert!(!s.doc().unwrap().is_dirty());
|
||||
s.execute("document.save", &json!({"path": native})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.layers_open, None, "only the written file carries it");
|
||||
let mut again = session();
|
||||
again.execute("document.open", &json!({"path": native})).unwrap();
|
||||
let open = &again.doc().unwrap().layers_open;
|
||||
assert!(open.contains(g) && !open.contains(layer));
|
||||
// Older files (none saved) open with the top-level layers open.
|
||||
let doc = vectorcraft_format::load(&vectorcraft_format::save(&vectorcraft_doc::Document::new(5.0, 5.0), false)).unwrap();
|
||||
assert_eq!(doc.layers_open, None);
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_plans_suggest_names_and_folders() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -68,6 +68,7 @@ fn write(doc: &Document, opts: &ExportOptions, native: Option<&[u8]>, id_prefix:
|
||||
symbol_nest: 0,
|
||||
fonts: Vec::new(),
|
||||
shared_images: HashMap::new(),
|
||||
layer_nest: 0,
|
||||
};
|
||||
w.assign_name_ids();
|
||||
// Page Isolated Blending / Page Knockout Group: the page content is one isolated group.
|
||||
@@ -266,6 +267,8 @@ struct Writer<'a> {
|
||||
/// Images written once in the defs and drawn with `<use>`, by key and size: the pieces an
|
||||
/// envelope cuts a distorted image into share its pixels.
|
||||
shared_images: HashMap<(String, u32, u32), String>,
|
||||
/// Layers being written inside one another (more than one: a sublayer).
|
||||
layer_nest: usize,
|
||||
}
|
||||
|
||||
/// The characters type uses from one face, under one `@font-face` description: the family the
|
||||
@@ -545,8 +548,8 @@ impl Writer<'_> {
|
||||
}
|
||||
/// ` id="…"` for a named object, plus ` data-name="…"` with the name itself when the id had to
|
||||
/// differ from it (spaces, punctuation, duplicates, the unique prefix).
|
||||
/// The id of `n`'s element (with its name when the id isn't it), then the object's own data
|
||||
/// as `data-*` attributes.
|
||||
/// The id of `n`'s element (with its name when the id isn't it), a sublayer's mark
|
||||
/// ([`crate::import::SUBLAYER`]), then the object's own data as `data-*` attributes.
|
||||
fn id_attr(&self, n: &Node) -> String {
|
||||
if self.anonymous {
|
||||
return String::new();
|
||||
@@ -556,6 +559,10 @@ impl Writer<'_> {
|
||||
(Some(id), _) => format!(" id=\"{}\"", xml_escape(id)),
|
||||
(None, _) => String::new(),
|
||||
};
|
||||
// A sublayer is marked as one, so import makes it a sublayer again, not a group.
|
||||
if !out.is_empty() && n.is_layer() && self.layer_nest > 1 {
|
||||
out.push_str(&format!(" {}=\"sublayer\"", crate::import::SUBLAYER));
|
||||
}
|
||||
for (k, v) in n.attrs.as_deref().map_or(&[][..], |a| a.data.as_slice()) {
|
||||
// Names as XML takes them; ours (`name`, `vc-…`) are written by the export itself.
|
||||
let valid = k.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.')) && k != "name" && !k.starts_with("vc-");
|
||||
@@ -1215,6 +1222,8 @@ impl Writer<'_> {
|
||||
|
||||
/// An object, inside `<a>` when it links to a URL (Attributes panel).
|
||||
fn node(&mut self, n: &Node) {
|
||||
let layer = usize::from(n.is_layer());
|
||||
self.layer_nest += layer;
|
||||
match n.url().filter(|_| n.visible && !self.anonymous) {
|
||||
Some(url) => {
|
||||
self.line(&format!("<a xlink:href=\"{}\">", xml_escape(url)));
|
||||
@@ -1225,6 +1234,7 @@ impl Writer<'_> {
|
||||
}
|
||||
None => self.node_body(n),
|
||||
}
|
||||
self.layer_nest -= layer;
|
||||
}
|
||||
|
||||
fn node_body(&mut self, n: &Node) {
|
||||
|
||||
+87
-17
@@ -8,7 +8,7 @@ use std::sync::Arc;
|
||||
use usvg::roxmltree;
|
||||
use vectorcraft_color::{BlendMode, Color, Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop, Paint};
|
||||
use vectorcraft_doc::{
|
||||
Appearance, AppearanceItem, Dash, Document, FillLayer, ImageBlob, ImageObject, LayerColor, LineCap, LineJoin, Node, NodeKind, PatternDef,
|
||||
Appearance, AppearanceItem, Dash, Document, FillLayer, ImageBlob, ImageObject, LayerColor, LineCap, LineJoin, Node, NodeId, NodeKind, PatternDef,
|
||||
StrokeLayer, Unit,
|
||||
};
|
||||
use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, Vec2, shapes};
|
||||
@@ -65,6 +65,8 @@ pub(crate) fn import(svg: &str, opts: &ImportOptions) -> Result<(Document, Vec<S
|
||||
files,
|
||||
non_scaling: found.non_scaling,
|
||||
data: found.data,
|
||||
sublayers: found.sublayers,
|
||||
sublayer_groups: HashSet::new(),
|
||||
screen: (kx * ky).sqrt(),
|
||||
};
|
||||
if im.files.nested_text() {
|
||||
@@ -74,22 +76,32 @@ pub(crate) fn import(svg: &str, opts: &ImportOptions) -> Result<(Document, Vec<S
|
||||
// usvg wraps everything in an id-less group carrying the viewBox transform when needed.
|
||||
let mut top = tree.root();
|
||||
let mut base = Affine::scale_non_uniform(kx, ky) * aff(top.transform());
|
||||
if let [usvg::Node::Group(g)] = top.children()
|
||||
&& g.id().is_empty()
|
||||
&& is_plain(g)
|
||||
&& im.text_slot(g).is_none()
|
||||
{
|
||||
if let Some(g) = im.wrapper(top) {
|
||||
base *= aff(g.transform());
|
||||
top = g;
|
||||
}
|
||||
|
||||
// Top-level `<g id>` elements become layers (as in the reference app); otherwise all art goes
|
||||
// into "Layer 1". A clip path on one (as on an Inkscape layer, or our clipping layers) makes it
|
||||
// a clipping layer. Top-level text joins the layer below it (the first layer if none is).
|
||||
// Top-level `<g id>` elements become layers (as in the reference app), named from their
|
||||
// labels (`data-name`…) else their ids; otherwise all art goes into "Layer 1". A clip path on
|
||||
// one (as on an Inkscape layer, or our clipping layers) makes it a clipping layer. Top-level
|
||||
// text joins the layer below it (the first layer if none is).
|
||||
let is_layer = |im: &Importer, c: &usvg::Node| matches!(c, usvg::Node::Group(g) if !g.id().is_empty() && !made_up(g.id()) && !im.links.contains_key(g.id()) && !im.uses.contains_key(g.id()) && only_clips(g) && im.text_slot(g).is_none());
|
||||
let is_text = |im: &Importer, c: &usvg::Node| matches!(c, usvg::Node::Group(g) if im.text_slot(g).is_some());
|
||||
let layer_mode = top.children().iter().any(|c| is_layer(&im, c)) && top.children().iter().all(|c| is_layer(&im, c) || is_text(&im, c));
|
||||
if layer_mode {
|
||||
let layer_mode = |im: &Importer, top: &usvg::Group| {
|
||||
top.children().iter().any(|c| is_layer(im, c)) && top.children().iter().all(|c| is_layer(im, c) || is_text(im, c))
|
||||
};
|
||||
// The layers may sit in more wrappers (a transform on all the art, a `<switch>`'s group).
|
||||
if !layer_mode(&im, top) {
|
||||
let (mut inner, mut ts) = (top, base);
|
||||
while let Some(g) = im.wrapper(inner) {
|
||||
ts *= aff(g.transform());
|
||||
inner = g;
|
||||
}
|
||||
if layer_mode(&im, inner) {
|
||||
(top, base) = (inner, ts);
|
||||
}
|
||||
}
|
||||
if layer_mode(&im, top) {
|
||||
im.doc.layers.clear();
|
||||
let mut loose = vec![];
|
||||
for c in top.children() {
|
||||
@@ -136,9 +148,48 @@ pub(crate) fn import(svg: &str, opts: &ImportOptions) -> Result<(Document, Vec<S
|
||||
*ch = children;
|
||||
}
|
||||
}
|
||||
if !im.sublayer_groups.is_empty() {
|
||||
for l in &mut im.doc.layers {
|
||||
promote_sublayers(Arc::make_mut(l), &im.sublayer_groups);
|
||||
}
|
||||
}
|
||||
Ok((im.doc, im.warnings))
|
||||
}
|
||||
|
||||
/// What marks a nested `<g>` as a sublayer rather than a group: our export writes it on the layers
|
||||
/// it writes inside layers. (Inkscape's `inkscape:groupmode="layer"` counts too.)
|
||||
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";
|
||||
|
||||
/// 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 {
|
||||
g.tag_name().name() == "g"
|
||||
&& g.attribute("id").is_some_and(|id| !id.is_empty())
|
||||
&& (g.has_attribute(SUBLAYER) || g.attribute((INKSCAPE, "groupmode")) == Some("layer"))
|
||||
}
|
||||
|
||||
/// Turn the groups made of elements marked as layers (`marked`, see [`marked_layer`]) right inside
|
||||
/// layer `l` into its sublayers, in its colour, and theirs in turn. A marked group anywhere else
|
||||
/// (in a group, a mask, a symbol) stays a group: only layers hold layers.
|
||||
fn promote_sublayers(l: &mut Node, marked: &HashSet<NodeId>) {
|
||||
let NodeKind::Layer { color, children, .. } = &mut l.kind else { return };
|
||||
let color = *color;
|
||||
for c in children.iter_mut().filter(|c| marked.contains(&c.id)) {
|
||||
let c = Arc::make_mut(c);
|
||||
let NodeKind::Group { children, clip } = &mut c.kind else { continue };
|
||||
let mut sub = Node::layer(c.id, "", color);
|
||||
sub.set_clips(*clip);
|
||||
if let Some(ch) = sub.children_mut() {
|
||||
*ch = std::mem::take(children);
|
||||
}
|
||||
c.kind = sub.kind;
|
||||
promote_sublayers(c, marked);
|
||||
}
|
||||
}
|
||||
|
||||
/// SVG's initial `font-size` (`medium`) in user units.
|
||||
pub(super) const DEFAULT_FONT_SIZE: f64 = 12.0;
|
||||
|
||||
@@ -214,6 +265,10 @@ struct Importer {
|
||||
non_scaling: HashSet<String>,
|
||||
/// The `data-*` attributes of elements, by id ([`user_data`]).
|
||||
data: HashMap<String, Vec<(String, String)>>,
|
||||
/// Ids of the `<g>` elements marked as layers ([`marked_layer`]).
|
||||
sublayers: HashSet<String>,
|
||||
/// The groups made of them, made sublayers where they sit in a layer ([`promote_sublayers`]).
|
||||
sublayer_groups: HashSet<NodeId>,
|
||||
/// Points per screen pixel (the root's user unit before its `viewBox`): what a non-scaling
|
||||
/// stroke's width is measured in.
|
||||
screen: f64,
|
||||
@@ -326,6 +381,8 @@ struct Found {
|
||||
non_scaling: HashSet<String>,
|
||||
/// The `data-*` attributes of elements, by id ([`user_data`]).
|
||||
data: HashMap<String, Vec<(String, String)>>,
|
||||
/// Ids of the `<g>` elements marked as layers ([`marked_layer`]).
|
||||
sublayers: HashSet<String>,
|
||||
warnings: Vec<String>,
|
||||
}
|
||||
|
||||
@@ -396,7 +453,7 @@ impl Edits {
|
||||
fn prepass<'s>(svg: &'s str, opts: &ImportOptions) -> (Cow<'s, str>, Found) {
|
||||
let mut found = Found::default();
|
||||
// (`:` for prefixed elements such as `<svg:image>`.)
|
||||
if !["<a", "display", "<use", ":use", "<image", ":image", vector_effect::NON_SCALING, "data-"].iter().any(|t| svg.contains(t)) {
|
||||
if !["<a", "display", "<use", ":use", "<image", ":image", vector_effect::NON_SCALING, "data-", "groupmode"].iter().any(|t| svg.contains(t)) {
|
||||
return (svg.into(), found);
|
||||
}
|
||||
let Ok(xml) = roxmltree::Document::parse_with_options(svg, roxmltree::ParsingOptions { allow_dtd: true, ..Default::default() }) else {
|
||||
@@ -417,6 +474,7 @@ fn prepass<'s>(svg: &'s str, opts: &ImportOptions) -> (Cow<'s, str>, Found) {
|
||||
}
|
||||
}
|
||||
}
|
||||
found.sublayers = elements().filter(|g| marked_layer(*g)).filter_map(|g| g.attribute("id")).map(str::to_string).collect();
|
||||
let symbols: HashSet<&str> = elements().filter(|n| n.tag_name().name() == "symbol").filter_map(|n| n.attribute("id")).collect();
|
||||
for u in elements().filter(|n| n.tag_name().name() == "use") {
|
||||
if let Some(sym) = href(u).and_then(|h| h.strip_prefix('#')).filter(|s| symbols.contains(s)) {
|
||||
@@ -440,19 +498,20 @@ fn prepass<'s>(svg: &'s str, opts: &ImportOptions) -> (Cow<'s, str>, Found) {
|
||||
/// The elements that are objects (what [`hidden_objects`] shows).
|
||||
const OBJECTS: &[&str] = &["g", "a", "path", "rect", "circle", "ellipse", "line", "polyline", "polygon", "image", "text", "use"];
|
||||
|
||||
/// Show the undisplayed objects outside `<defs>` (and the like) for usvg, recording their ids.
|
||||
/// Show the undisplayed objects outside `<defs>` (and the like) for usvg, recording their ids. The
|
||||
/// objects in a `<switch>` count too (some apps wrap all their layers in one).
|
||||
fn hidden_objects(svg: &str, xml: &roxmltree::Document, css: &css::Styles, edits: &mut Edits, ids: &mut HashSet<String>) {
|
||||
let linked: HashSet<&str> = xml.descendants().filter_map(href).filter_map(|h| h.strip_prefix('#')).collect();
|
||||
let mut todo: Vec<XNode> = xml.root_element().children().filter(XNode::is_element).collect();
|
||||
while let Some(n) = todo.pop() {
|
||||
let tag = n.tag_name().name();
|
||||
if !OBJECTS.contains(&tag) || n.attribute("id").is_some_and(|id| linked.contains(id)) {
|
||||
if n.attribute("id").is_some_and(|id| linked.contains(id)) {
|
||||
continue;
|
||||
}
|
||||
if matches!(tag, "g" | "a") {
|
||||
if matches!(tag, "g" | "a" | "switch") {
|
||||
todo.extend(n.children().filter(XNode::is_element));
|
||||
}
|
||||
if css.own(n, "display").as_deref() != Some("none") {
|
||||
if !OBJECTS.contains(&tag) || css.own(n, "display").as_deref() != Some("none") {
|
||||
continue;
|
||||
}
|
||||
ids.insert(edits.id(svg, n));
|
||||
@@ -498,7 +557,6 @@ fn link(n: &mut Node, url: &str) {
|
||||
/// The names apps keep beside element ids, by id: `data-name`, `inkscape:label`, `serif:id` or
|
||||
/// `aria-label` (the first one present).
|
||||
fn labels(xml: &roxmltree::Document) -> HashMap<String, String> {
|
||||
const INKSCAPE: &str = "http://www.inkscape.org/namespaces/inkscape";
|
||||
const SERIF: &str = "http://www.serif.com/";
|
||||
xml.descendants()
|
||||
.filter_map(|n| {
|
||||
@@ -609,6 +667,15 @@ impl Importer {
|
||||
}
|
||||
}
|
||||
|
||||
/// The child of `g` when it's all `g` holds and only wraps art: an id-less group that leaves
|
||||
/// it as it is (but for a transform) and isn't a text.
|
||||
fn wrapper<'g>(&self, g: &'g usvg::Group) -> Option<&'g usvg::Group> {
|
||||
match g.children() {
|
||||
[usvg::Node::Group(w)] if w.id().is_empty() && is_plain(w) && self.text_slot(w).is_none() => Some(w),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn children(&mut self, g: &usvg::Group, acc: Affine) -> Vec<Arc<Node>> {
|
||||
g.children().iter().filter_map(|c| self.node(c, acc)).map(Arc::new).collect()
|
||||
}
|
||||
@@ -853,6 +920,9 @@ impl Importer {
|
||||
n.blend = blend(g.blend_mode());
|
||||
n.isolate = g.isolate();
|
||||
n.mask = mask;
|
||||
if !is_text && self.sublayers.contains(g.id()) {
|
||||
self.sublayer_groups.insert(n.id);
|
||||
}
|
||||
Some(n)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! 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, and the
|
||||
//! editing data notices edits made elsewhere.
|
||||
//! 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.
|
||||
// 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)]
|
||||
|
||||
@@ -350,6 +350,173 @@ fn hidden_groups_others_use_stay_hidden() {
|
||||
assert_eq!((paths, hidden), (0, 0), "{:?}", d.layers);
|
||||
}
|
||||
|
||||
/// The layer tree: each object by kind (layers and groups with their names), `(hidden)` when
|
||||
/// hidden, its contents indented below it.
|
||||
fn outline(d: &Document) -> Vec<String> {
|
||||
fn walk(n: &Node, depth: usize, out: &mut Vec<String>) {
|
||||
let name = n.children().map(|_| format!(" {}", n.name.as_deref().unwrap_or("-"))).unwrap_or_default();
|
||||
let hidden = if n.visible { "" } else { " (hidden)" };
|
||||
out.push(format!("{}{}{name}{hidden}", " ".repeat(depth), n.kind_label()));
|
||||
for c in n.children().into_iter().flatten() {
|
||||
walk(c, depth + 1, out);
|
||||
}
|
||||
}
|
||||
let mut out = vec![];
|
||||
for l in &d.layers {
|
||||
walk(l, 0, &mut out);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Layers as other apps export them (#372): named top-level groups, one hidden; a hidden named
|
||||
/// group and a hidden object inside a layer.
|
||||
const EXPORTED_LAYERS: &str = r##"<svg xmlns="http://www.w3.org/2000/svg" width="400" height="300" viewBox="0 0 400 300">
|
||||
<g id="Main">
|
||||
<rect id="plainStroke" x="20" y="50" width="120" height="60" style="fill:none;stroke:#000;stroke-width:4"/>
|
||||
<rect id="hiddenObject" x="200" y="50" width="60" height="60" style="display:none;fill:#fff;stroke:#000"/>
|
||||
<g id="HiddenSub" style="display:none"><circle cx="45" cy="175" r="25" style="fill:#fff;stroke:#000"/></g>
|
||||
</g>
|
||||
<g id="Second" display="none"><rect x="10" y="10" width="5" height="5"/></g>
|
||||
</svg>"##;
|
||||
|
||||
#[test]
|
||||
fn top_level_groups_become_named_layers() {
|
||||
let expected = ["Layer Main", " Path", " Path (hidden)", " Group HiddenSub (hidden)", " Path", "Layer Second (hidden)", " Path"];
|
||||
let d = import(EXPORTED_LAYERS).unwrap();
|
||||
assert_eq!(outline(&d), expected);
|
||||
// A nested group stays a group: nothing in the file says it's a sublayer.
|
||||
// `data-name` names the layer when the id can't (spaces, punctuation).
|
||||
let named = EXPORTED_LAYERS.replace("<g id=\"Main\">", "<g id=\"Main_Art\" data-name=\"Main Art\">");
|
||||
assert_eq!(import(&named).unwrap().layers[0].name.as_deref(), Some("Main Art"));
|
||||
// Layers wrapped in more groups: a transform on all the art, or a `<switch>` choosing them.
|
||||
let moved = EXPORTED_LAYERS.replace("<g id=\"Main\">", "<g transform=\"translate(5 5)\"><g id=\"Main\">").replace("</svg>", "</g></svg>");
|
||||
let d = import(&moved).unwrap();
|
||||
assert_eq!(outline(&d), expected, "{moved}");
|
||||
let stroke = &d.layers[0].children().unwrap()[0];
|
||||
assert_eq!(stroke.geometric_bounds().unwrap(), Rect::new(25.0, 55.0, 145.0, 115.0));
|
||||
let switched = EXPORTED_LAYERS
|
||||
.replace("<g id=\"Main\">", "<switch><foreignObject requiredExtensions=\"urn:example:none\" width=\"1\" height=\"1\"/><g><g id=\"Main\">")
|
||||
.replace("</svg>", "</g></switch></svg>");
|
||||
assert_eq!(outline(&import(&switched).unwrap()), expected, "{switched}");
|
||||
// Art beside the groups puts everything in one layer, as before.
|
||||
let loose = EXPORTED_LAYERS.replace("</svg>", "<rect x=\"1\" y=\"1\" width=\"2\" height=\"2\"/></svg>");
|
||||
assert_eq!(import(&loose).unwrap().layers.iter().map(|l| l.name.as_deref()).collect::<Vec<_>>(), [Some("Layer 1")]);
|
||||
}
|
||||
|
||||
/// Layer "Base" holding a path, a named group, a clipping sublayer and a hidden sublayer "Notes"
|
||||
/// with a sublayer of its own; layer "Top" above it.
|
||||
fn sublayered() -> Document {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
let square = |d: &mut Document, x: f64| {
|
||||
let ap = Appearance::basic(Paint::solid(Color::rgb8(200, 30, 30)), Paint::None, 0.0);
|
||||
Arc::new(Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, x, x + 10.0, x + 10.0)), ap))
|
||||
};
|
||||
let layer = |children: Vec<Arc<Node>>, d: &mut Document, name: &str| {
|
||||
let mut l = Node::layer(d.alloc_id(), name, vectorcraft_doc::LayerColor::Preset(3));
|
||||
*l.children_mut().unwrap() = children;
|
||||
l
|
||||
};
|
||||
let deep = layer(vec![square(&mut d, 60.0)], &mut d, "Deep");
|
||||
let mut notes = layer(vec![square(&mut d, 50.0), Arc::new(deep)], &mut d, "Notes");
|
||||
notes.visible = false;
|
||||
let mut clip = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(20.0, 20.0, 30.0, 30.0)), Appearance::default());
|
||||
if let NodeKind::Path { clipping, .. } = &mut clip.kind {
|
||||
*clipping = true;
|
||||
}
|
||||
let mut window = layer(vec![Arc::new(clip), square(&mut d, 25.0)], &mut d, "Window");
|
||||
window.set_clips(true);
|
||||
let mut group = Node::group(d.alloc_id(), vec![square(&mut d, 30.0), square(&mut d, 40.0)]);
|
||||
group.name = Some("Pair".into());
|
||||
let art = vec![square(&mut d, 10.0), Arc::new(group), Arc::new(window), Arc::new(notes)];
|
||||
let base = Arc::make_mut(&mut d.layers[0]);
|
||||
base.name = Some("Base".into());
|
||||
*base.children_mut().unwrap() = art;
|
||||
let top = layer(vec![square(&mut d, 80.0)], &mut d, "Top");
|
||||
d.layers.push(Arc::new(top));
|
||||
d
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sublayers_round_trip() {
|
||||
let d = sublayered();
|
||||
let expected = [
|
||||
"Layer Base",
|
||||
" Path",
|
||||
" Group Pair",
|
||||
" Path",
|
||||
" Path",
|
||||
" Layer Window",
|
||||
" Path",
|
||||
" Path",
|
||||
" Layer Notes (hidden)",
|
||||
" Path",
|
||||
" Layer Deep",
|
||||
" Path",
|
||||
"Layer Top",
|
||||
" Path",
|
||||
];
|
||||
assert_eq!(outline(&d), expected);
|
||||
let styles = [vectorcraft_svg::Styling::PresentationAttributes, vectorcraft_svg::Styling::InlineStyle, vectorcraft_svg::Styling::InternalCss];
|
||||
for styling in styles {
|
||||
// Saved with the hidden sublayer: the same tree comes back.
|
||||
let kept = export(&d, &ExportOptions { hidden_layers: true, styling, ..Default::default() });
|
||||
assert_eq!(kept.matches("data-vc-layer").count(), 3, "sublayers only: {kept}");
|
||||
let back = import(&kept).unwrap();
|
||||
assert_eq!(outline(&back), expected, "{kept}");
|
||||
// A sublayer takes its layer's colour.
|
||||
back.walk(|n| {
|
||||
if let NodeKind::Layer { color, .. } = &n.kind
|
||||
&& n.name.as_deref() != Some("Top")
|
||||
{
|
||||
assert_eq!(*color, vectorcraft_doc::LayerColor::Preset(0), "{:?}", n.name);
|
||||
}
|
||||
});
|
||||
assert!(back.layers[0].children().unwrap()[2].clips());
|
||||
assert_similar(&render_artboard(&back), &render_artboard(&d), 24.0, 0.002);
|
||||
}
|
||||
// Exported without hidden art, the visible sublayer still comes back as one.
|
||||
let plain = import(&export(&d, &ExportOptions::default())).unwrap();
|
||||
assert_eq!(
|
||||
outline(&plain),
|
||||
["Layer Base", " Path", " Group Pair", " Path", " Path", " Layer Window", " Path", " Path", "Layer Top", " Path"]
|
||||
);
|
||||
}
|
||||
|
||||
#[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.
|
||||
let svg = r##"<svg xmlns="http://www.w3.org/2000/svg" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" width="100" height="100">
|
||||
<g id="layer1" inkscape:groupmode="layer" inkscape:label="Base">
|
||||
<rect x="1" y="1" width="5" height="5"/>
|
||||
<g id="layer2" inkscape:groupmode="layer" inkscape:label="Sub" style="display:none">
|
||||
<rect x="10" y="10" width="5" height="5"/>
|
||||
<g id="layer3" inkscape:groupmode="layer" inkscape:label="Deeper"><rect x="20" y="10" width="5" height="5"/></g>
|
||||
</g>
|
||||
<g id="g1"><rect x="30" y="1" width="5" height="5"/><g id="layer4" data-vc-layer="sublayer"><rect x="40" y="1" width="5" height="5"/></g></g>
|
||||
</g>
|
||||
</svg>"##;
|
||||
let d = import(svg).unwrap();
|
||||
assert_eq!(
|
||||
outline(&d),
|
||||
[
|
||||
"Layer Base",
|
||||
" Path",
|
||||
" Layer Sub (hidden)",
|
||||
" Path",
|
||||
" Layer Deeper",
|
||||
" Path",
|
||||
" Group g1",
|
||||
" Path",
|
||||
" Group layer4",
|
||||
" Path",
|
||||
]
|
||||
);
|
||||
// Art outside layers ("Layer 1" holds it): a marked group there is a sublayer of it.
|
||||
let loose = svg.replace("</svg>", "<rect x=\"1\" y=\"1\" width=\"2\" height=\"2\"/></svg>");
|
||||
let d = import(&loose).unwrap();
|
||||
assert_eq!(outline(&d)[..4], ["Layer Layer 1", " Layer Base", " Path", " Layer Sub (hidden)"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn editing_data_notices_edits_made_elsewhere() {
|
||||
let d = symbol_doc(2.0, &[Affine::translate((50.0, 50.0))]);
|
||||
|
||||
+108
-16
@@ -218,6 +218,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
// Artwork raster.
|
||||
let ppp = ui.ctx().pixels_per_point();
|
||||
let (w, h) = ((rect.width() * ppp).round().max(1.0) as u32, (rect.height() * ppp).round().max(1.0) as u32);
|
||||
// View › Pixel Preview: the art as it rasterizes, one pixel per point, while a document pixel
|
||||
// is bigger than a screen pixel (below that the screen render already shows it).
|
||||
let pixel = (app.ui.view.pixel_preview && v.zoom * ppp as f64 > 1.0).then(|| pixel_region(&xf)).flatten();
|
||||
let key = CacheKey {
|
||||
doc: st.uid as usize,
|
||||
revision: st.revision,
|
||||
@@ -233,6 +236,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
rot: v.rotation,
|
||||
anti_alias: app.session.prefs.anti_aliased_artwork,
|
||||
placed: vectorcraft_render::placed_document::generation(),
|
||||
pixel,
|
||||
};
|
||||
// Placed documents' bitmaps are being made: draw again when they are ready.
|
||||
if vectorcraft_render::placed_document::busy() {
|
||||
@@ -248,16 +252,23 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
if let Some(done) = app.canvas.worker.as_mut().and_then(|w| w.poll())
|
||||
&& done.key.doc == key.doc
|
||||
{
|
||||
upload(app, ui.ctx(), &done.img);
|
||||
upload(app, ui.ctx(), &done.img, done.key.pixel.is_some());
|
||||
app.canvas.key = Some(done.key);
|
||||
app.perf.render_ms = done.ms;
|
||||
app.canvas.last_ms = done.ms;
|
||||
}
|
||||
if app.canvas.key.as_ref() != Some(&key) || app.canvas.texture.is_none() {
|
||||
let view = Affine::translate((w as f64 / 2.0, h as f64 / 2.0))
|
||||
* Affine::rotate(v.rotation.to_radians())
|
||||
* Affine::scale(v.zoom * ppp as f64)
|
||||
* Affine::translate(-v.center.to_vec2());
|
||||
let (w, h, view) = match pixel {
|
||||
Some([x0, y0, x1, y1]) => ((x1 - x0) as u32, (y1 - y0) as u32, Affine::translate((-x0 as f64, -y0 as f64))),
|
||||
None => (
|
||||
w,
|
||||
h,
|
||||
Affine::translate((w as f64 / 2.0, h as f64 / 2.0))
|
||||
* Affine::rotate(v.rotation.to_radians())
|
||||
* Affine::scale(v.zoom * ppp as f64)
|
||||
* Affine::translate(-v.center.to_vec2()),
|
||||
),
|
||||
};
|
||||
let opts = vectorcraft_render::RenderOptions { outline: app.ui.view.outline, background: None, artboards: false, ..Default::default() };
|
||||
let opts = vectorcraft_render::RenderOptions {
|
||||
proof: vectorcraft_render::proof::active_proof(),
|
||||
@@ -284,7 +295,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
_ => {
|
||||
let t0 = now_ms();
|
||||
let img = app.canvas.renderer.render(&doc, w, h, view, &opts);
|
||||
upload(app, ui.ctx(), &img);
|
||||
upload(app, ui.ctx(), &img, pixel.is_some());
|
||||
app.canvas.key = Some(key.clone());
|
||||
app.perf.render_ms = now_ms() - t0;
|
||||
app.canvas.last_ms = app.perf.render_ms;
|
||||
@@ -293,14 +304,28 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
}
|
||||
if let (Some(tex), Some(k)) = (&app.canvas.texture, &app.canvas.key)
|
||||
&& k.doc == key.doc
|
||||
&& (k.rot - v.rotation).abs() < 1e-9
|
||||
{
|
||||
// Reproject the last frame if it was rendered for a different view.
|
||||
let old = Xf { rect, zoom: k.zoom, center: Point::new(k.cx, k.cy), rot: xf.rot };
|
||||
let _ = k.rot;
|
||||
let a = xf.to_screen(old.to_doc(rect.min));
|
||||
let b = xf.to_screen(old.to_doc(rect.max));
|
||||
painter.image(tex.id(), egui::Rect::from_min_max(a, b), egui::Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);
|
||||
match k.pixel {
|
||||
// Document pixels: placed over the document rect they cover, turning with the view.
|
||||
Some([x0, y0, x1, y1]) => {
|
||||
let q = xf.quad(Rect::new(x0 as f64, y0 as f64, x1 as f64, y1 as f64));
|
||||
let mut mesh = egui::Mesh::with_texture(tex.id());
|
||||
for (pos, uv) in q.into_iter().zip([pos2(0.0, 0.0), pos2(1.0, 0.0), pos2(1.0, 1.0), pos2(0.0, 1.0)]) {
|
||||
mesh.vertices.push(egui::epaint::Vertex { pos, uv, color: Color32::WHITE });
|
||||
}
|
||||
mesh.add_triangle(0, 1, 2);
|
||||
mesh.add_triangle(0, 2, 3);
|
||||
painter.add(Shape::mesh(mesh));
|
||||
}
|
||||
None if (k.rot - v.rotation).abs() < 1e-9 => {
|
||||
// Reproject the last frame if it was rendered for a different view.
|
||||
let old = Xf { rect, zoom: k.zoom, center: Point::new(k.cx, k.cy), rot: xf.rot };
|
||||
let a = xf.to_screen(old.to_doc(rect.min));
|
||||
let b = xf.to_screen(old.to_doc(rect.max));
|
||||
painter.image(tex.id(), egui::Rect::from_min_max(a, b), egui::Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
if let Some(look) = grid_look.filter(|_| !grids_in_back) {
|
||||
grid(&painter, &xf, doc.grid.spacing, doc.grid.subdivisions, look);
|
||||
@@ -1717,14 +1742,31 @@ fn kurbo_flatten(p: &BezPath, tol: f64, f: &mut impl FnMut(PathEl)) {
|
||||
vectorcraft_geom::kurbo::flatten(p.elements().iter().copied(), tol, f);
|
||||
}
|
||||
|
||||
fn upload(app: &mut VectorcraftApp, ctx: &egui::Context, img: &vectorcraft_render::Rendered) {
|
||||
/// Upload the art's raster; Pixel Preview's document pixels keep hard edges when magnified.
|
||||
fn upload(app: &mut VectorcraftApp, ctx: &egui::Context, img: &vectorcraft_render::Rendered, pixel: bool) {
|
||||
let color = egui::ColorImage::from_rgba_premultiplied([img.width as usize, img.height as usize], &img.pixels);
|
||||
let options = if pixel { egui::TextureOptions::NEAREST } else { egui::TextureOptions::LINEAR };
|
||||
match &mut app.canvas.texture {
|
||||
Some(tex) => tex.set(color, egui::TextureOptions::LINEAR),
|
||||
None => app.canvas.texture = Some(ctx.load_texture("canvas", color, egui::TextureOptions::LINEAR)),
|
||||
Some(tex) => tex.set(color, options),
|
||||
None => app.canvas.texture = Some(ctx.load_texture("canvas", color, options)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Pixel Preview: the whole document pixels (x0, y0, x1, y1) under the canvas, rotated view
|
||||
/// included. None when the view is degenerate.
|
||||
fn pixel_region(xf: &Xf) -> Option<[i64; 4]> {
|
||||
let r = xf.rect;
|
||||
let corners = [r.left_top(), r.right_top(), r.right_bottom(), r.left_bottom()].map(|p| xf.to_doc(p));
|
||||
let (mut x0, mut y0, mut x1, mut y1) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
|
||||
for p in corners {
|
||||
(x0, y0, x1, y1) = (x0.min(p.x), y0.min(p.y), x1.max(p.x), y1.max(p.y));
|
||||
}
|
||||
let (x0, y0, x1, y1) = (x0.floor(), y0.floor(), x1.ceil(), y1.ceil());
|
||||
// A document pixel is bigger than a screen pixel here, so the region is about canvas-sized.
|
||||
let ok = [x0, y0, x1, y1].iter().all(|c| c.is_finite() && c.abs() < 1e9) && x1 > x0 && y1 > y0 && x1 - x0 <= 16384.0 && y1 - y0 <= 16384.0;
|
||||
ok.then_some([x0 as i64, y0 as i64, x1 as i64, y1 as i64])
|
||||
}
|
||||
|
||||
/// The Contextual Task Bar's area.
|
||||
fn task_bar_id() -> egui::Id {
|
||||
egui::Id::new("task-bar")
|
||||
@@ -2249,6 +2291,56 @@ mod tests {
|
||||
(v, out.textures_delta)
|
||||
}
|
||||
|
||||
/// View › Pixel Preview: magnified, the art shows as the document pixels it rasterizes to (one
|
||||
/// per point, hard-edged), not as smooth vectors; zoomed out or out of Pixel Preview the canvas
|
||||
/// renders for the screen again.
|
||||
#[test]
|
||||
fn pixel_preview_shows_the_document_pixels() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
// Its 1 pt stroke covers a quarter of document pixel 99 and most of pixel 100.
|
||||
app.session.execute("shape.rectangle", &json!({"x": 100.25, "y": 50, "width": 200, "height": 200})).unwrap();
|
||||
app.canvas.worker_started = true; // render on this thread
|
||||
let ctx = egui::Context::default();
|
||||
// The art's raster uploaded by one frame: (width, height, hard-edged, pixels).
|
||||
let upload = |app: &mut VectorcraftApp| {
|
||||
let (_, mut delta) = frame_output(app, &ctx);
|
||||
let art = app.canvas.texture.as_ref().unwrap().id();
|
||||
let up = delta.set.iter().find(|e| e.0.eq(&art)).and_then(|e| e.1.last()).map(|d| {
|
||||
let egui::ImageData::Color(img) = &d.image;
|
||||
(img.width(), img.height(), d.options.magnification == egui::TextureFilter::Nearest, img.pixels.clone())
|
||||
});
|
||||
delta.clear();
|
||||
up.expect("the art re-rendered")
|
||||
};
|
||||
let screen = upload(&mut app); // the first frame fits the view to the artboard
|
||||
assert!(screen.0 > 600 && !screen.2, "out of Pixel Preview: the screen's pixels, smoothed");
|
||||
app.ui.view.pixel_preview = true;
|
||||
let view = app.view_mut().unwrap();
|
||||
(view.zoom, view.center) = (8.0, Point::new(100.0, 150.0));
|
||||
let (w, h, hard, px) = upload(&mut app);
|
||||
assert!(hard, "hard-edged pixels");
|
||||
assert!(w <= screen.0 / 8 + 2 && h <= screen.1 / 8 + 2, "one pixel per point: {w} × {h}");
|
||||
let [x0, y0, x1, y1] = app.canvas.key.as_ref().and_then(|k| k.pixel).expect("the pixels rendered");
|
||||
assert_eq!(((x1 - x0) as usize, (y1 - y0) as usize), (w, h));
|
||||
// Each document pixel is one texel, anti-aliased by how much of it the art covers.
|
||||
let alpha = |x: i64| px[((150 - y0) * w as i64 + x - x0) as usize].a();
|
||||
assert!((40..=90).contains(&alpha(99)), "a quarter of pixel 99: {}", alpha(99));
|
||||
assert!(alpha(100) > 200, "most of pixel 100: {}", alpha(100));
|
||||
assert_eq!((alpha(98), alpha(101)), (0, 255));
|
||||
// The pixels are placed over the document rect they cover.
|
||||
let s = shapes(&mut app, &ctx);
|
||||
let art = app.canvas.texture.as_ref().unwrap().id();
|
||||
let Some(Shape::Mesh(mesh)) = s.iter().find(|s| matches!(s, Shape::Mesh(m) if m.texture_id == art)) else { panic!("the art") };
|
||||
let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap());
|
||||
let at = xf.to_screen(Point::new(x0 as f64, y0 as f64));
|
||||
assert!((mesh.vertices[0].pos - at).length() < 0.01, "{:?} at {at:?}", mesh.vertices[0].pos);
|
||||
// Zoomed out, a document pixel is no bigger than a screen pixel: rendered for the screen.
|
||||
app.view_mut().unwrap().zoom = 0.5;
|
||||
let (w, _, hard, _) = upload(&mut app);
|
||||
assert!(w > 600 && !hard, "zoomed out: the screen's pixels");
|
||||
}
|
||||
|
||||
/// General › Anti-aliased Artwork (#394): on (the default), the art's edges are smoothed on
|
||||
/// screen; off, every pixel is either painted or not, and turning it either way re-renders.
|
||||
#[test]
|
||||
|
||||
@@ -288,6 +288,9 @@ pub struct CacheKey {
|
||||
pub anti_alias: bool,
|
||||
/// [`vectorcraft_render::placed_document::generation`]: placed documents' bitmaps made since.
|
||||
pub placed: u64,
|
||||
/// View › Pixel Preview: the document pixels rendered (x0, y0, x1, y1), one per point, shown
|
||||
/// with hard edges. None: the art is rendered for the screen.
|
||||
pub pixel: Option<[i64; 4]>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
|
||||
@@ -24,13 +24,20 @@
|
||||
//! on the trash clears it.
|
||||
//!
|
||||
//! While an opacity mask is edited the panel lists only its art, under an `<Opacity Mask>` entry.
|
||||
//!
|
||||
//! The rows open are the document's ([`OpenRows`], saved in native files): a document opens with
|
||||
//! only its top-level layers open. The rows shown are listed once per document change, and only
|
||||
//! those scrolled into view are laid out, so a document of many thousand objects costs no more
|
||||
//! per frame than a small one.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::sync::Arc;
|
||||
|
||||
use egui::{Color32, Sense, Stroke, StrokeKind, Ui, vec2};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
|
||||
use vectorcraft_engine::OpenRows;
|
||||
|
||||
use crate::theme::Tokens;
|
||||
use crate::widgets::{Live, PanelDrag};
|
||||
@@ -198,9 +205,97 @@ fn opens(n: &Node, opts: &PanelOptions) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `n` or anything in it has a name containing `q` (lowercase).
|
||||
fn matches(n: &Node, q: &str) -> bool {
|
||||
n.display_name().to_lowercase().contains(q) || n.children().is_some_and(|c| c.iter().any(|c| matches(c, q)))
|
||||
/// One row of the panel.
|
||||
#[derive(Clone)]
|
||||
struct Row {
|
||||
node: Arc<Node>,
|
||||
/// Nesting level (0: a top-level layer).
|
||||
depth: usize,
|
||||
/// A clipping path: its group or layer clips.
|
||||
clip_path: bool,
|
||||
/// It holds rows ([`opens`]), and shows them.
|
||||
opens: bool,
|
||||
open: bool,
|
||||
/// The colour of its layer (its own, for a layer).
|
||||
colour: Color32,
|
||||
/// Drawn dimmed: hidden itself or in a hidden layer or group, or a template layer.
|
||||
dim: bool,
|
||||
}
|
||||
|
||||
/// What the rows were listed from: listed again when any of it changes.
|
||||
#[derive(Clone, PartialEq)]
|
||||
struct RowsKey {
|
||||
uid: u64,
|
||||
revision: u64,
|
||||
open: u64,
|
||||
layers_only: bool,
|
||||
query: String,
|
||||
}
|
||||
|
||||
/// The rows the panel shows, top down: the layers (only the opacity mask's while one is edited)
|
||||
/// with the rows of the open ones inside them. A search shows every row whose name, or the name of
|
||||
/// anything inside it, contains `query` (lowercase).
|
||||
fn list_rows(doc: &Document, open: &OpenRows, opts: &PanelOptions, query: &str) -> Vec<Row> {
|
||||
let mask_layer = doc.mask_edit.map(|m| m.layer);
|
||||
let mut out = vec![];
|
||||
for l in doc.layers.iter().rev().filter(|l| mask_layer.is_none_or(|m| m == l.id)) {
|
||||
push_rows(l, 0, false, (Color32::PLACEHOLDER, true), (open, opts, query), &mut out);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Add the rows of `n` and those open inside it to `out`; `(colour, shown)` are those of what holds
|
||||
/// it (the layer's colour, and whether it is visible).
|
||||
fn push_rows(
|
||||
n: &Arc<Node>,
|
||||
depth: usize,
|
||||
clip_path: bool,
|
||||
(colour, shown): (Color32, bool),
|
||||
cx: (&OpenRows, &PanelOptions, &str),
|
||||
out: &mut Vec<Row>,
|
||||
) {
|
||||
let (open_rows, opts, query) = cx;
|
||||
if opts.layers_only && !n.is_layer() {
|
||||
return;
|
||||
}
|
||||
let colour = match &n.kind {
|
||||
NodeKind::Layer { color, .. } => {
|
||||
let [r, g, b] = color.rgb();
|
||||
Color32::from_rgb(r, g, b)
|
||||
}
|
||||
_ => colour,
|
||||
};
|
||||
let shown = shown && n.visible;
|
||||
let opens = opens(n, opts);
|
||||
let searching = !query.is_empty();
|
||||
let open = opens && (searching || open_rows.contains(n.id));
|
||||
let at = out.len();
|
||||
out.push(Row { node: n.clone(), depth, clip_path, opens, open, colour, dim: !shown || n.is_template() });
|
||||
if open && let Some(children) = n.children() {
|
||||
for (i, c) in children.iter().enumerate().rev() {
|
||||
push_rows(c, depth + 1, i == 0 && n.clips(), (colour, shown), cx, out);
|
||||
}
|
||||
}
|
||||
// Searching, a row stays for its own name or for a row it keeps inside it.
|
||||
if searching && out.len() == at + 1 && !n.display_name().to_lowercase().contains(query) {
|
||||
out.truncate(at);
|
||||
}
|
||||
}
|
||||
|
||||
/// The rows of the active document as [`list_rows`] lists them, listed again only when the
|
||||
/// document, its open rows, the search or Show Layers Only changed.
|
||||
fn rows_of_doc(ui: &Ui, st: &vectorcraft_engine::DocState, opts: &PanelOptions, query: &str) -> Arc<Vec<Row>> {
|
||||
let now =
|
||||
RowsKey { uid: st.uid, revision: st.revision, open: st.layers_open.generation(), layers_only: opts.layers_only, query: query.to_string() };
|
||||
let id = key("rows");
|
||||
if let Some((was, rows)) = ui.data(|d| d.get_temp::<(RowsKey, Arc<Vec<Row>>)>(id))
|
||||
&& was == now
|
||||
{
|
||||
return rows;
|
||||
}
|
||||
let rows = Arc::new(list_rows(&st.doc, &st.layers_open, opts, query));
|
||||
ui.data_mut(|d| d.insert_temp(id, (now, rows.clone())));
|
||||
rows
|
||||
}
|
||||
|
||||
/// Everything one frame of the panel reads.
|
||||
@@ -213,8 +308,6 @@ struct View<'a> {
|
||||
opts: PanelOptions,
|
||||
t: Tokens,
|
||||
h: f32,
|
||||
/// The search field's text, lowercase (empty: every row).
|
||||
query: String,
|
||||
column: Option<ColumnDrag>,
|
||||
/// The row to scroll into view.
|
||||
reveal: Option<NodeId>,
|
||||
@@ -224,8 +317,6 @@ struct View<'a> {
|
||||
#[derive(Default)]
|
||||
struct Out {
|
||||
actions: Vec<(String, Value)>,
|
||||
/// The rows shown, top down.
|
||||
order: Vec<NodeId>,
|
||||
/// A row clicked with these modifiers (resolved once every row is listed).
|
||||
click: Option<(NodeId, egui::Modifiers)>,
|
||||
/// The column drag after this frame (`Some(None)`: it ended).
|
||||
@@ -249,23 +340,25 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
d.insert_temp(shown_doc, st.uid);
|
||||
});
|
||||
}
|
||||
let uid = st.uid;
|
||||
let doc = st.doc.clone();
|
||||
let rows = st.highlighted_rows();
|
||||
// Rows highlighted anew (a click, Locate Object, a new layer): open the layers around them.
|
||||
let seen: Vec<NodeId> = ui.data(|d| d.get_temp(key("seen"))).unwrap_or_default();
|
||||
let mut reveal = None;
|
||||
let expanded = app.ui.layers_expanded.entry(uid).or_insert_with(|| doc.layers.iter().map(|l| l.id.0).collect());
|
||||
if rows != seen {
|
||||
for r in &rows {
|
||||
for a in doc.ancestry(*r).unwrap_or_default().split_last().map(|(_, a)| a.to_vec()).unwrap_or_default() {
|
||||
expanded.insert(a.0);
|
||||
let around: Vec<NodeId> =
|
||||
rows.iter().flat_map(|r| doc.ancestry(*r).unwrap_or_default().split_last().map(|(_, a)| a.to_vec()).unwrap_or_default()).collect();
|
||||
if let Some(st) = app.session.active_mut() {
|
||||
for a in around {
|
||||
st.layers_open.set(a, true);
|
||||
}
|
||||
}
|
||||
reveal = rows.first().copied();
|
||||
ui.data_mut(|d| d.insert_temp(key("seen"), rows.clone()));
|
||||
}
|
||||
let query = crate::widgets::search_field(ui, egui::Id::new("layers-search"), tl!("Search All")).trim().to_lowercase();
|
||||
let Some(st) = app.session.active() else { return };
|
||||
let list = rows_of_doc(ui, st, &app.ui.layers_panel, &query);
|
||||
let view = View {
|
||||
doc: &doc,
|
||||
sel: st.selection.objects.iter().copied().collect(),
|
||||
@@ -275,30 +368,31 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
opts: app.ui.layers_panel.clone(),
|
||||
t,
|
||||
h: app.ui.layers_panel.row(),
|
||||
query,
|
||||
column: ui.data(|d| d.get_temp(key("column"))),
|
||||
reveal,
|
||||
};
|
||||
// While an opacity mask is edited only its art is listed.
|
||||
let mask_layer = doc.mask_edit.map(|m| m.layer);
|
||||
let mut out = Out::default();
|
||||
ui.add_space(6.0);
|
||||
let list_h = ui.available_height() - 34.0;
|
||||
let list = egui::ScrollArea::vertical().max_height(list_h).auto_shrink([false, false]).show(ui, |ui| {
|
||||
// Only the rows in view are laid out; one revealed out of view is scrolled to.
|
||||
let revealed = reveal.and_then(|id| list.iter().position(|r| r.node.id == id));
|
||||
let scrolled = ui.scope(|ui| {
|
||||
ui.spacing_mut().item_spacing.y = 0.0;
|
||||
let expanded = app.ui.layers_expanded.entry(uid).or_default();
|
||||
for l in doc.layers.iter().rev().filter(|l| mask_layer.is_none_or(|m| m == l.id)) {
|
||||
row(ui, &view, l, 0, false, expanded, &mut out);
|
||||
}
|
||||
egui::ScrollArea::vertical().max_height(list_h).auto_shrink([false, false]).show_rows(ui, view.h, list.len(), |ui, range| {
|
||||
if let Some(i) = revealed.filter(|i| !range.contains(i)) {
|
||||
let top = ui.max_rect().top() + (i as f32 - range.start as f32) * view.h;
|
||||
ui.scroll_to_rect(egui::Rect::from_min_size(egui::pos2(ui.max_rect().left(), top), vec2(ui.max_rect().width(), view.h)), None);
|
||||
}
|
||||
for r in list.get(range).unwrap_or_default() {
|
||||
row(ui, &view, r, &mut out);
|
||||
}
|
||||
})
|
||||
});
|
||||
let list_rect = list.inner_rect;
|
||||
resolve_click(ui, &view, &mut out);
|
||||
let expanded = app.ui.layers_expanded.entry(uid).or_default();
|
||||
for (id, open) in out.toggle.drain(..) {
|
||||
if open {
|
||||
expanded.insert(id.0);
|
||||
} else {
|
||||
expanded.remove(&id.0);
|
||||
let list_rect = scrolled.inner.inner_rect;
|
||||
resolve_click(ui, &view, &list, &mut out);
|
||||
if let Some(st) = app.session.active_mut() {
|
||||
for (id, open) in out.toggle.drain(..) {
|
||||
st.layers_open.set(id, open);
|
||||
}
|
||||
}
|
||||
// The column drag: live while it lasts, one undo step when the button is released.
|
||||
@@ -415,15 +509,16 @@ fn bottom_bar(app: &mut VectorcraftApp, ui: &mut Ui, view: &View, doc: &Document
|
||||
|
||||
/// Resolve the row clicked this frame: plain (highlight it), Ctrl/Cmd (toggle it) or Shift
|
||||
/// (highlight the rows from the last one clicked down to it).
|
||||
fn resolve_click(ui: &Ui, view: &View, out: &mut Out) {
|
||||
fn resolve_click(ui: &Ui, view: &View, list: &[Row], out: &mut Out) {
|
||||
let Some((id, m)) = out.click.take() else { return };
|
||||
let anchor: Option<NodeId> = ui.data(|d| d.get_temp(key("anchor")));
|
||||
ui.data_mut(|d| d.insert_temp(key("focus"), true));
|
||||
let at = |id: NodeId| list.iter().position(|r| r.node.id == id);
|
||||
if m.shift
|
||||
&& let Some(a) = anchor.or(view.rows.last().copied())
|
||||
&& let (Some(i), Some(j)) = (out.order.iter().position(|r| *r == a), out.order.iter().position(|r| *r == id))
|
||||
&& let (Some(i), Some(j)) = (at(a), at(id))
|
||||
{
|
||||
let range: Vec<u64> = out.order.get(i.min(j)..=i.max(j)).unwrap_or_default().iter().map(|r| r.0).collect();
|
||||
let range: Vec<u64> = list.get(i.min(j)..=i.max(j)).unwrap_or_default().iter().map(|r| r.node.id.0).collect();
|
||||
out.actions.push(("layer.highlight".into(), json!({"ids": range, "mode": if m.command { "add" } else { "set" }})));
|
||||
return;
|
||||
}
|
||||
@@ -447,19 +542,14 @@ fn takes(n: &Node, drag: &LayersDrag, doc: &Document) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn row(ui: &mut Ui, view: &View, n: &Node, depth: usize, clip_path: bool, expanded: &mut HashSet<u64>, out: &mut Out) {
|
||||
/// The widgets of row `item`.
|
||||
fn row(ui: &mut Ui, view: &View, item: &Row, out: &mut Out) {
|
||||
let n = &*item.node;
|
||||
let (depth, clip_path, has_children, open, color) = (item.depth, item.clip_path, item.opens, item.open, item.colour);
|
||||
let doc = view.doc;
|
||||
let t = &view.t;
|
||||
if !view.query.is_empty() && !matches(n, &view.query) {
|
||||
return;
|
||||
}
|
||||
if view.opts.layers_only && !n.is_layer() {
|
||||
return;
|
||||
}
|
||||
let h = view.h;
|
||||
let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), h), Sense::click_and_drag());
|
||||
out.order.push(n.id);
|
||||
if view.reveal == Some(n.id) {
|
||||
ui.scroll_to_rect(r, None);
|
||||
}
|
||||
@@ -470,7 +560,6 @@ fn row(ui: &mut Ui, view: &View, n: &Node, depth: usize, clip_path: bool, expand
|
||||
n.walk(&mut |c| any |= c.id != n.id && view.sel.contains(&c.id));
|
||||
any
|
||||
});
|
||||
let color = layer_colour(doc, n.id);
|
||||
// Highlighted rows (else the current layer's).
|
||||
let highlighted = if view.rows.is_empty() { n.is_layer() && Some(n.id) == view.current } else { view.rows.contains(&n.id) };
|
||||
if highlighted {
|
||||
@@ -490,9 +579,6 @@ fn row(ui: &mut Ui, view: &View, n: &Node, depth: usize, clip_path: bool, expand
|
||||
colour_bar(ui, n, r, x, color);
|
||||
x += 6.0 + depth as f32 * INDENT;
|
||||
// Disclosure triangle; Alt opens or closes everything inside too.
|
||||
let searching = !view.query.is_empty();
|
||||
let has_children = opens(n, &view.opts);
|
||||
let open = has_children && (searching || expanded.contains(&n.id.0));
|
||||
if has_children {
|
||||
let dr = egui::Rect::from_min_size(egui::pos2(x, r.center().y - 8.0), vec2(14.0, 16.0));
|
||||
let dresp = ui.interact(dr, ui.id().with(("disc", n.id.0)), Sense::click());
|
||||
@@ -548,8 +634,7 @@ fn row(ui: &mut Ui, view: &View, n: &Node, depth: usize, clip_path: bool, expand
|
||||
} else {
|
||||
painted_name(n, &name, crate::i18n::current())
|
||||
};
|
||||
let dim = !doc.is_visible(n.id) || n.is_template();
|
||||
let text = painter.text(egui::pos2(x, r.center().y), egui::Align2::LEFT_CENTER, shown, font, if dim { t.text_dim } else { t.text });
|
||||
let text = painter.text(egui::pos2(x, r.center().y), egui::Align2::LEFT_CENTER, shown, font, if item.dim { t.text_dim } else { t.text });
|
||||
name_end = text.right();
|
||||
// A clipping path's name is underlined, a masked object's with a dashed line.
|
||||
if clip_path {
|
||||
@@ -605,11 +690,6 @@ fn row(ui: &mut Ui, view: &View, n: &Node, depth: usize, clip_path: bool, expand
|
||||
ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing);
|
||||
}
|
||||
drop_target(ui, view, n, r, x - 16.0, open, &resp, out);
|
||||
if open && let Some(children) = n.children() {
|
||||
for (i, c) in children.iter().enumerate().rev() {
|
||||
row(ui, view, c, depth + 1, i == 0 && n.clips(), expanded, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Alt-clicking row `n`'s eye (`eye`) or lock: Hide Others or Lock Others, every top-level layer
|
||||
@@ -951,15 +1031,9 @@ pub fn expand(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
|
||||
v
|
||||
}
|
||||
};
|
||||
let uid = st.uid;
|
||||
let layers: Vec<u64> = st.doc.layers.iter().map(|l| l.id.0).collect();
|
||||
let set = app.ui.layers_expanded.entry(uid).or_insert_with(|| layers.into_iter().collect());
|
||||
let st = app.session.active_mut().ok_or("no document open")?;
|
||||
for i in &ids {
|
||||
if open {
|
||||
set.insert(*i);
|
||||
} else {
|
||||
set.remove(i);
|
||||
}
|
||||
st.layers_open.set(NodeId(*i), open);
|
||||
}
|
||||
Ok(json!({ "count": ids.len() }))
|
||||
}
|
||||
@@ -1623,4 +1697,53 @@ mod tests {
|
||||
assert_eq!(rows_of(&app), vec![sub]);
|
||||
assert_eq!(app.session.active().unwrap().current_layer(), Some(sub));
|
||||
}
|
||||
|
||||
/// A layer of 2,000 groups of 10 paths with every row open: one frame lays out only the rows
|
||||
/// in view, and a row highlighted far below them is scrolled to.
|
||||
#[test]
|
||||
fn only_the_rows_in_view_are_laid_out() {
|
||||
use vectorcraft_doc::Appearance;
|
||||
use vectorcraft_geom::{Rect, shapes};
|
||||
let mut d = Document::new(1000.0, 1000.0);
|
||||
let mut groups = vec![];
|
||||
let mut needle = None;
|
||||
for g in 0..2000 {
|
||||
let kids = (0..10)
|
||||
.map(|k| {
|
||||
let r = Rect::new(k as f64, g as f64 * 0.1, k as f64 + 1.0, g as f64 * 0.1 + 1.0);
|
||||
let mut n = Node::path(d.alloc_id(), shapes::rectangle(r), Appearance::default());
|
||||
if g == 0 && k == 0 {
|
||||
n.name = Some("Needle".into());
|
||||
needle = Some(n.id);
|
||||
}
|
||||
Arc::new(n)
|
||||
})
|
||||
.collect();
|
||||
groups.push(Arc::new(Node::group(d.alloc_id(), kids)));
|
||||
}
|
||||
*Arc::make_mut(&mut d.layers[0]).children_mut().unwrap() = groups;
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.session.add_document(d, None);
|
||||
expand(&mut app, &json!({})).unwrap();
|
||||
let ctx = egui::Context::default();
|
||||
// (shapes drawn, whether the needle's name is among them); a second passes per frame, so
|
||||
// scrolling ends.
|
||||
let mut time = 0.0;
|
||||
let mut frame = |app: &mut VectorcraftApp| {
|
||||
time += 1.0;
|
||||
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(300.0, 800.0));
|
||||
let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), time: Some(time), ..Default::default() }, |ui| show(app, ui));
|
||||
out.textures_delta.clear();
|
||||
let found = out.shapes.iter().any(|c| matches!(&c.shape, egui::Shape::Text(t) if t.galley.text() == "Needle"));
|
||||
(out.shapes.len(), found)
|
||||
};
|
||||
let (shapes, found) = frame(&mut app);
|
||||
// 22,001 rows; about 30 fit.
|
||||
assert!(shapes < 1000 && !found, "{shapes} shapes");
|
||||
let needle = needle.unwrap();
|
||||
app.session.execute("layer.highlight", &json!({"ids": [needle.0], "mode": "set"})).unwrap();
|
||||
let found = (0..4).any(|_| frame(&mut app).1);
|
||||
assert_eq!(app.session.active().unwrap().highlighted_rows(), [needle]);
|
||||
assert!(found, "the highlighted row is scrolled into view");
|
||||
}
|
||||
}
|
||||
@@ -365,9 +365,6 @@ pub struct UiState {
|
||||
/// Layers panel › Panel Options… (row size, thumbnails, Show Layers Only).
|
||||
#[serde(default)]
|
||||
pub layers_panel: crate::panels::layers::PanelOptions,
|
||||
/// The Layers panel's open rows, per open document (`DocState::uid` → node ids).
|
||||
#[serde(skip)]
|
||||
pub layers_expanded: std::collections::HashMap<u64, std::collections::HashSet<u64>>,
|
||||
/// The desktop window's size, position and maximized state, saved when the app quits and
|
||||
/// restored at the next launch (the desktop host reads and writes it; none on the web).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
@@ -521,7 +518,6 @@ impl Default for UiState {
|
||||
dxf_import: Value::Null,
|
||||
home: None,
|
||||
layers_panel: Default::default(),
|
||||
layers_expanded: Default::default(),
|
||||
window: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -882,6 +882,7 @@ and `layerRows`, the rows highlighted in the panel.
|
||||
dimImages, dimPercent; OK is one undo step), `ui.layersPanelOptions` opens Panel Options (`layersPanelOptions`:
|
||||
layersOnly, rowSize small|medium|large|other, otherSize, thumbLayers, thumbGroups, thumbObjects), and
|
||||
`ui.layersExpand {ids?, open?}` opens or closes rows as their triangles do (Alt-click: everything inside).
|
||||
A document opens with only its top-level layers open; the open rows are saved in the native file and reopen that way.
|
||||
|
||||
```json
|
||||
{"name":"run_command","arguments":{"command":"layer.newSublayer","params":{"name":"Shadows"}}}
|
||||
|
||||
Reference in new issue
Block a user