Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3585ef654c | ||
|
|
28fc79d57a | ||
|
|
1d04ee0e84 | ||
|
|
72fc1ac0e1 | ||
|
|
d8a2d4cd81 | ||
|
|
c70f69253b |
No files matched your search
+8
-7
@@ -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-08 (after 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, and the missing-font export warning (#319); see [Honest assessment](#honest-assessment-2026-10-05))._
|
||||
_Last updated: 2026-10-08 (after 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) and PDF/`.ai` import keeping strokes live and hidden and nested layers (#372); see [Honest assessment](#honest-assessment-2026-10-05))._
|
||||
|
||||
## Where we are
|
||||
|
||||
@@ -63,7 +63,8 @@ Ordered by how much each gap blocks someone from switching. Sizes are one-agent
|
||||
spell-check dictionary (open licence), Touch Type and Snap to Glyph. Vertical point, area and path type have
|
||||
initial support. 35–48 h across type core and advanced.
|
||||
5. **Brushes, symbols and libraries:** brush options depth; original brush, symbol and graphic-style libraries
|
||||
generated in code (never Adobe's); dynamic symbols; Start Global Edit. 14–22 h.
|
||||
generated in code (never Adobe's); dynamic symbols; Start Global Edit; brushes driven by pen tilt, bearing and
|
||||
barrel rotation (6D art pens, #372), which needs tablet input beyond pressure on every platform. 20–32 h.
|
||||
6. **Automation:** Variables (data merge), a scripting surface over the command registry, batch. 8–12 h.
|
||||
7. **Views and windows:** multiple windows and arrange, Consolidate All Windows, video
|
||||
rulers. 15–25 h.
|
||||
@@ -129,7 +130,7 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist
|
||||
- **Type:** Text Wrap, Type on a Path effects (Rainbow/Skew/3D Ribbon/Stair Step/Gravity), Character and Paragraph Styles (override-preserving redefine), Area Type Options (rows/columns/inset/first baseline), threaded text across any closed shapes, Fit Headline. Area type resizes like Illustrator's type areas: a bounding-box handle drag (Selection tool) or Area Type Options Width/Height size the frame and the text reflows at its size (threads too); Direct Selection drags a frame corner or edge (`text.reshapeArea`). Point type still scales. Variable fonts list every named instance as a style of their family (Figtree Light to Black and their italics, Bahnschrift, Segoe UI Variable), and the instance chosen is shaped, drawn, outlined and measured at its axis settings; PDF and SVG embed it as that instance. Variation axis sliders are not done. Hebrew and Arabic are laid out right to left with the Unicode bidirectional algorithm (embedded Latin and numbers keep their direction, lines put in visual order after wrapping) in point, area and path type, with caret, selection and arrow keys in visual order; each paragraph's direction comes from its first strong character unless Paragraph Direction sets it (Paragraph panel with Show Indic Options, `text.setFormat {direction}`), and new type aligns to the start of its direction. SVG export outlines right-to-left text.
|
||||
- **Interface languages, vertical type:** VectorCraft ▸ Language (or Preferences ▸ User Interface) picks Automatic (the system locale) or a registered language, persisted as `interfaceLanguage`. Translations come from per-language catalogs (`i18n/*.tsv`): Traditional and Simplified Chinese, Japanese and Spanish (neutral international Spanish, for every `es-*` locale) cover the whole interface, Czech and Brazilian Portuguese every menu label, Brazilian Portuguese the shell's `tl!` literals too (tested); untranslated text stays English. Japanese and Chinese glyphs come from the craft-fonts build input (release builds) or the installed fonts, Czech and Spanish ones from the bundled UI fonts. The Basic toolbar's Type button holds Vertical Type in its flyout. Vertical Type, Vertical Area Type and Vertical Type on a Path create vertical text (columns right to left, upright CJK glyphs and marks with `vert` alternates, Latin and longer numbers on their side, two- and three-digit numbers set as tate-chu-yoko in one em of the column (kept whole when justified), upright glyphs centred on the column (tracked or justified too), point type's anchor on the first column's centre line); kinsoku (the strict set) applies to horizontal and vertical Japanese, and justified Japanese lines spread their room between characters (not inside Latin words); Paragraph panel › Mojikumi Set (shown with Preferences › Type › Show East Asian Options, `text.setFormat {mojikumi}`): None or Line-end Punctuation Half Width (new type's default, as in Illustrator; older documents and imported text keep None) shares one half-em space between consecutive punctuation, sets a closing mark ending a line half width, and puts a quarter em between Japanese and Latin letters or digits; Paragraph panel menu › Top-to-Top / Bottom-to-Bottom Leading measures leading from em box top to top (area type's first line touches the frame) or from baseline to baseline; Type ▸ Type Orientation switches existing text; caret, selection, hit testing and arrow keys follow the writing direction. Vertical text exports to PDF as real text and to SVG as outlines.
|
||||
- **Transparency:** opacity masks (clip/invert/disable/link), exported as SVG `<mask>` and PDF soft masks.
|
||||
- **Advanced art:** live Blends (steps/distance/smooth colour, editable spine, anchor-targeted Blend tool, faithful interpolation, knockout), Envelope Distort (warp/mesh/top object, Reset, full Envelope Options, mesh handles, Edit Contents; type, images, symbols, gradients, patterns and appearance distorted everywhere), Liquify tools with options and pen pressure, Puppet Warp with rotating pins, Perspective Grid with presets, movable planes and projected type (choosing a perspective tool shows the grid; Hide Grid hides it with the tool still chosen), Gradient Mesh, Shape Builder, Live Paint (every path an edge, open lines included), Image Trace (12 presets), pattern swatches with pattern editing mode, live Repeat (radial/grid/mirror).
|
||||
- **Advanced art:** live Blends (steps/distance/smooth colour, editable spine, anchor-targeted Blend tool, faithful interpolation, knockout), Envelope Distort (warp/mesh/top object, Reset, full Envelope Options, mesh handles, Edit Contents; type, images, symbols, gradients, patterns and appearance distorted everywhere), Liquify tools with options and pen pressure, Puppet Warp with rotating pins, Perspective Grid with presets, movable planes and projected type (choosing a perspective tool shows the grid; Hide Grid hides it with the tool still chosen), Gradient Mesh, Shape Builder (stroke-only open paths and lines cut the regions they cross and enclose regions of their own; Alt deletes their pieces; filled open paths count as closed), Live Paint (every path an edge, open lines included), Image Trace (12 presets), pattern swatches with pattern editing mode, live Repeat (radial/grid/mirror).
|
||||
- **Paint and appearance (M3):**
|
||||
- **Swatches:** names follow the colour model and are unique; Swatch Options (process/spot, Global, Gray/RGB/HSB/CMYK/Web, live preview); editing a global or spot swatch recolours every linked fill, stroke and text run in one undo step; multi-select and delete with confirmation; New Swatch and New Color Group dialogs (a group from the selected artwork's colours); swatches in colour groups convert, separate and count like any other. The Swatches panel selects ranges and whole groups, has a find field, and drags swatches to reorder, regroup or paint art; Add Used Colors, Select All Unused, Merge, Ungroup and Sort by Kind; a CMYK document keeps applied colours in CMYK. Swatch libraries: nine generated colour libraries and five gradient libraries in a library panel, saved and loaded as `.vcswatches`, `.gpl` or CSS. Tints of global and spot colours ("Name 40%") stay linked and separate as a percentage of their plate. Spot colours can be defined in Lab (Spot Colors options). A built-in [Registration] swatch prints on every plate.
|
||||
- **Colour:** a Color Picker (colour field, H/S/B/R/G/B channel slider, HSB/RGB/Lab/CMYK fields, hex, web-only snapping, out-of-gamut correction); the Color panel follows each colour's own model and Alt-click paints the other proxy; proxies look through groups and show "?" for mixed paint; Invert, Complement, Apply Last Color (`,`) and Apply Last Gradient (`.`) keep the colour model; every paint command feeds the recent colours. The Color Guide has 21 harmony rules, Steps and Variation options and Limit to Library. Adjust Color Balance (its Global mode shifts tints) and Saturate preview live; Edit Colors and Recolor also reach meshes, images and patterns. Recolor Artwork has colour reduction, five recolour methods, presets, Limit to Library, a colour-wheel Edit tab and Edit Color Group; a local Color Themes panel saves five-colour themes. Fill/Stroke chips open swatch and mixer popovers, panels have their shortcuts, and Eyedropper Options pick up and apply chosen attributes (Alt and Shift+Alt, image pixels). Fills and strokes can overprint (Attributes panel, Overprint Black options), and CMYK documents blend in inks on screen, in PDF and when flattening.
|
||||
@@ -144,7 +145,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.
|
||||
- SVG/SVGZ in and out with SVG Options, Preserve Editing, symbols, filters, rich text and physical units; PDF and PDF-compatible `.ai` in and out (layers, 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; PDF and PDF-compatible `.ai` in and out (layers, with hidden ones kept hidden with their art and nested ones as sublayers; strokes kept live, a fill and a stroke of one outline as one object; 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 Illustrator's AGM/CoolType prologs (resource categories, `resourceforall`, `clipsave`/`cliprestore`, subarrays and substrings that share storage, the standard dictionaries in `systemdict`, `dictstack`, `internaldict`, executable filters, `cshow`, metadata skipped with `flushfile`), so Illustrator 30 EPS files open as vectors, and falls back to its palette TIFF preview. DXF TEXT justified Fit or Aligned spans its two points (stretched, or scaled as a whole).
|
||||
- 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.
|
||||
- **Performance:** 20k shapes + 1k texts render in 27 ms per full-retina frame (7.8 ms zoomed), 7× faster than the first version. The UI thread never blocks. The web build is 7.1 MB gzipped.
|
||||
@@ -161,7 +162,7 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist
|
||||
| M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Color Picker, Color panel, Color Guide, Color Themes, Edit Colors and Recolor Artwork; gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool, Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries. Left: freeform and mixed spot/process gradients export as stops or process colours to SVG/PDF; confirm the Scale Strokes & Effects default | 4–8 |
|
||||
| M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out, EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, Asset Export, clipboard flavours, File Info. Left: DWG (use DXF), PSD placement as layers, overprint read back from PDF, polish | 3–6 |
|
||||
| M5 | Performance | 🟡 background render + caches + MT done; `vectorcraft-cli bench` and `vectorcraft-cli perf` (budget suite); file format v2 opens 3× faster (50k paths: 722 → 244 ms); raster effects (glows, shadows, blur, feather) no longer force the whole frame single-threaded (filtered offscreen per effect, verified equal to the single-threaded reference); effect-heavy demos need a clean-machine benchmark; dirty-region rendering, GPU backend spike pending | 15–25 |
|
||||
| M6 | Path operations (Pathfinder, Shape Builder, offset…) | ✅ mostly done (Boolean precision on almost-horizontal edges fixed and the property tests made deterministic; Shape Builder edge erase, large-offset bug open) | 3–6 |
|
||||
| M6 | Path operations (Pathfinder, Shape Builder, offset…) | ✅ mostly done (Boolean precision on almost-horizontal edges fixed and the property tests made deterministic; Shape Builder gap detection, large-offset bug open) | 3–6 |
|
||||
| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | 🟡 Character/Paragraph Styles, Area Type Options (with Width/Height), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs, OpenType panel, Find Font, installed system fonts in every font menu (searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, filter by script and kind, list a family's styles, and star favourites) and found by name on open/import, variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects, tab stops + Tabs panel, Hebrew/Arabic bidirectional text and Paragraph Direction done; tab leaders, spell check, vertical type pending | 45–60 |
|
||||
| M8 | Transform & distort (Puppet Warp, Liquify tools, Envelopes, Blends, Perspective Grid) | ✅ done (M8.1–M8.20 on 2026-10-06, fidelity pass): Liquify Tool Options with one shared brush, pen pressure, hold-to-apply, a safe scope and incremental strokes; tool options that last; Puppet Warp rotation, multi-select, Control bar and a rest-shape session that follows Undo; Width tool on compound paths; Envelope dialogs with preview, Reset with Warp/Mesh, full Envelope Options, type/images/symbols/appearance/gradients/patterns distorted on canvas and in every export, warps that keep their frame, Edit Contents, mesh handles and Control bar; Blend Options, anchor-targeted Blend tool, editable spine, keys picked on the canvas, faithful interpolation and knockout; Perspective Grid with Define Grid, presets, lock/snap/rulers, widgets, the 1–4 plane switch, movable planes, Perspective Selection scale/copy/perpendicular/Transform Again, and type and symbols truly projected with Edit Text. Left: Anti-Alias and Preserve Shape output, warp-envelope point editing, brush interpolation in blends, Free Transform/Scale/Reflect along a rotated box | 2–4 |
|
||||
| M9 | Live effects (+ 3D & Materials) | 🟡 2D effects done incl. Effect → Pathfinder and Color Adjustments; SVG Filters, Document Raster Effects Settings, 3D pending | 86–135 |
|
||||
@@ -190,9 +191,9 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale)
|
||||
|---|---:|---:|---|---:|
|
||||
| Selection, transform & align tools | 6 | 85% | Free Transform/Scale/Reflect along a rotated box, Start Global Edit, transform nuances (the rotated persistent bounding box is done) | 4–6 |
|
||||
| Drawing tools | 7 | 85% | Shaper Groups (merge/punch overlapping shapes), pencil and the remaining pen modifier nuances, Touch Type | 10–15 |
|
||||
| Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 86% | Live Paint gap options, Shape Builder edge cases | 3–6 |
|
||||
| Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 86% | Live Paint gap options, Shape Builder gap detection and options | 3–6 |
|
||||
| Colour, swatches, gradients, patterns, mesh, recolor | 7 | 96% | freeform and mixed spot/process gradients in SVG/PDF (exported as stops or process colours), pattern fills in Expand | 2–4 |
|
||||
| Strokes, brushes, width profiles | 5 | 88% | brush options depth, brush libraries (generated in code) | 6–10 |
|
||||
| Strokes, brushes, width profiles | 5 | 88% | brush options depth, brush libraries (generated in code), brushes driven by pen tilt, bearing and barrel rotation (6D art pens) | 12–20 |
|
||||
| Appearance, transparency, graphic styles, masks | 5 | 98% | raster effect reach in preview bounds (flattener presets apply in PDF, EPS and print) | 1–2 |
|
||||
| Live vector effects | 5 | 85% | Outline Object, Pathfinder Hard/Soft Mix and Trap, SVG Filters | 6–10 |
|
||||
| Raster effects (Effect Gallery, Document Raster Effects Settings) | 4 | 20% | ~55 Photoshop-style filters (Artistic, Brush Strokes, Distort, Pixelate, Sketch, Stylize, Texture, Video) and the Effect Gallery; Document Raster Effects Settings and raster effects in PDF are done | 28–42 |
|
||||
|
||||
@@ -16,10 +16,11 @@ use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::appearance::{AppearanceItem, FillLayer, StrokeLayer};
|
||||
use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, Selection};
|
||||
use vectorcraft_geom::{FillRule, Point, Rect, Shape as _};
|
||||
use vectorcraft_geom::{FillRule, PathData, Point, Rect};
|
||||
use vectorcraft_pathops as po;
|
||||
use vectorcraft_tools::builder::{
|
||||
self as b, EDGE_NAME, FACE_NAME, LIVE_PAINT_NAME, SOURCES_NAME, edge_near, face_at, is_live_paint, sample_polyline, shapes_for, sorted_roots,
|
||||
self as b, BuilderMap, EDGE_NAME, FACE_NAME, LIVE_PAINT_NAME, SOURCES_NAME, Touched, edge_near, face_at, is_live_paint, sample_polyline,
|
||||
sorted_roots,
|
||||
};
|
||||
use vectorcraft_trace as tr;
|
||||
|
||||
@@ -38,7 +39,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Shape Builder",
|
||||
[],
|
||||
None,
|
||||
"{ids?: [id…] (default: selection), points: [[x,y]…] (drag path; one point = click), erase?: bool (Alt-drag deletes the regions), fill?: \"#rrggbb\" | {color|swatch|gradient|none} (default: the fill of the object under the first point)} → {ids, merged, regions}",
|
||||
"{ids?: [id…] (default: selection), points: [[x,y]…] (drag path; one point = click), erase?: bool (Alt-drag deletes the regions, and the pieces of unfilled open paths within tolerance), tolerance?: pt (2, erase only), fill?: \"#rrggbb\" | {color|swatch|gradient|none} (default: the fill of the object under the first point; the current fill for an area only lines enclose)} → {ids, merged, regions, lines}",
|
||||
has_selection_or_ids,
|
||||
sb_merge
|
||||
),
|
||||
@@ -47,7 +48,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Shape Builder Regions",
|
||||
[],
|
||||
None,
|
||||
"{ids?} → {regions: [{bounds: [x0,y0,x1,y1], area, sources: [id…]}]} faces of the planar arrangement",
|
||||
"{ids?} → {regions: [{bounds: [x0,y0,x1,y1], area, sources: [id…]}], lines: [{bounds, source: id}]} faces of the planar arrangement (unfilled open paths cut them; sources is empty for an area only they enclose) and the pieces of those open paths",
|
||||
has_selection_or_ids,
|
||||
sb_regions
|
||||
),
|
||||
@@ -224,37 +225,51 @@ fn sb_merge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(C, "points must be a non-empty list of finite [x,y]"));
|
||||
}
|
||||
let erase = bool_or(p, "erase", false);
|
||||
// Line pieces are only deleted (Alt), never merged.
|
||||
let line_tol = erase.then(|| f64_or(p, "tolerance", 2.0).clamp(0.0, 1000.0));
|
||||
let fill = fill_param(s, p, C)?;
|
||||
let current_fill = s.paint.fill.clone();
|
||||
let roots = root_ids(s, p)?;
|
||||
let label = if erase { "Shape Builder Delete" } else { "Shape Builder" };
|
||||
let (ids, merged, count) = s.edit(label, |d, sel| {
|
||||
let (shapes, leaves) = shapes_for(d, &roots);
|
||||
let (ids, merged, regions, lines) = s.edit(label, |d, sel| {
|
||||
let (map, leaves) = BuilderMap::new(d, &roots);
|
||||
let leaves: Vec<Node> = leaves.into_iter().cloned().collect();
|
||||
if shapes.is_empty() {
|
||||
if map.shapes.is_empty() {
|
||||
return Err(EngineError::Other("Shape Builder: select paths or compound paths".into()));
|
||||
}
|
||||
let regs = po::regions(&shapes);
|
||||
let shapes_r: Vec<(kurbo::BezPath, Rect)> = regs.iter().map(|r| (r.path.to_bezpath(), r.path.bounds().unwrap_or(Rect::ZERO))).collect();
|
||||
let step = (d.bounds_of(&roots, false).map(|r| r.width().max(r.height())).unwrap_or(100.0) / 2000.0).max(0.25);
|
||||
let mut touched: Vec<usize> = vec![];
|
||||
let mut touched = Touched::default();
|
||||
for q in sample_polyline(&pts, step) {
|
||||
if let Some(i) = shapes_r.iter().position(|(bp, bb)| bb.contains(q) && bp.winding(q) != 0)
|
||||
&& !touched.contains(&i)
|
||||
{
|
||||
touched.push(i);
|
||||
}
|
||||
touched.add(map.hit(q, line_tol));
|
||||
}
|
||||
if touched.is_empty() {
|
||||
return Err(EngineError::Other("Shape Builder: no region under the pointer".into()));
|
||||
}
|
||||
let picked: Vec<&po::Region> = touched.iter().map(|&i| ®s[i]).collect();
|
||||
let union = po::merge_regions(&picked);
|
||||
let affected: Vec<bool> = (0..shapes.len()).map(|i| picked.iter().any(|r| r.sources.contains(&i))).collect();
|
||||
let style_src = regs[touched[0]].top();
|
||||
let picked: Vec<&po::Region> = touched.regions.iter().filter_map(|&i| map.regions.get(i).map(|r| &r.0)).collect();
|
||||
let union = if picked.is_empty() { PathData::default() } else { po::merge_regions(&picked) };
|
||||
// The merged shape takes the look of the front-most object over the first region, or (for an
|
||||
// area only lines enclose) of the front-most object and the current fill.
|
||||
let covered = picked.iter().find_map(|r| r.top());
|
||||
let style_src = covered.or(map.shapes.len().checked_sub(1));
|
||||
let merged_fill = fill.or_else(|| covered.is_none().then_some(current_fill));
|
||||
let mut new_nodes: Vec<Node> = vec![];
|
||||
let mut merged_id = None;
|
||||
for (i, (sh, leaf)) in shapes.iter().zip(&leaves).enumerate() {
|
||||
if !affected[i] {
|
||||
for (i, (sh, leaf)) in map.shapes.iter().zip(&leaves).enumerate() {
|
||||
let pieces: Vec<usize> = map.lines.iter().enumerate().filter(|(_, (l, _))| l.key == i as u64).map(|(k, _)| k).collect();
|
||||
if !pieces.is_empty() {
|
||||
// An open path loses the pieces deleted and those between merged (or deleted) regions.
|
||||
let keep: Vec<usize> =
|
||||
pieces.iter().copied().filter(|k| !touched.lines.contains(k) && !map.line_between(*k, &touched.regions)).collect();
|
||||
if keep.len() == pieces.len() {
|
||||
new_nodes.push(d.reid(leaf));
|
||||
} else {
|
||||
for k in keep {
|
||||
if let Some((l, _)) = map.lines.get(k) {
|
||||
new_nodes.push(shape_node(d, l.path.clone(), Some(leaf)));
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if !picked.iter().any(|r| r.sources.contains(&i)) {
|
||||
new_nodes.push(d.reid(leaf));
|
||||
} else {
|
||||
let rest = po::boolean(&sh.path, sh.rule, &union, FillRule::NonZero, po::BoolOp::Difference);
|
||||
@@ -262,9 +277,9 @@ fn sb_merge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
new_nodes.push(shape_node(d, rest, Some(leaf)));
|
||||
}
|
||||
}
|
||||
if !erase && Some(i) == style_src {
|
||||
if !erase && !union.is_empty() && Some(i) == style_src {
|
||||
let mut m = shape_node(d, union.clone(), Some(leaf));
|
||||
if let Some(f) = &fill {
|
||||
if let Some(f) = &merged_fill {
|
||||
m.appearance.set_fill(f.clone());
|
||||
}
|
||||
merged_id = Some(m.id);
|
||||
@@ -273,9 +288,9 @@ fn sb_merge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let new_ids = replace_roots(d, &roots, new_nodes)?;
|
||||
sel.set(new_ids.iter().copied());
|
||||
Ok((new_ids, merged_id, touched.len()))
|
||||
Ok((new_ids, merged_id, touched.regions.len(), touched.lines.len()))
|
||||
})?;
|
||||
Ok(json!({ "ids": ids_json(&ids), "merged": merged.map(|m| m.0), "regions": count }))
|
||||
Ok(json!({ "ids": ids_json(&ids), "merged": merged.map(|m| m.0), "regions": regions, "lines": lines }))
|
||||
}
|
||||
|
||||
/// Remove the roots and insert `nodes` where the front-most root was. Returns the new ids.
|
||||
@@ -300,20 +315,22 @@ fn replace_roots(d: &mut Document, roots: &[NodeId], nodes: Vec<Node>) -> Result
|
||||
fn sb_regions(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let roots = root_ids(s, p)?;
|
||||
let d = &s.doc()?.doc;
|
||||
let (shapes, leaves) = shapes_for(d, &roots);
|
||||
let regs = po::regions(&shapes);
|
||||
let out: Vec<Value> = regs
|
||||
let (map, leaves) = BuilderMap::new(d, &roots);
|
||||
let id_of = |i: usize| leaves.get(i).map(|n| n.id.0);
|
||||
let regions: Vec<Value> = map
|
||||
.regions
|
||||
.iter()
|
||||
.filter_map(|r| {
|
||||
let bb = r.path.bounds()?;
|
||||
Some(json!({
|
||||
.map(|(r, _, bb)| {
|
||||
json!({
|
||||
"bounds": [bb.x0, bb.y0, bb.x1, bb.y1],
|
||||
"area": po::area(&r.path, FillRule::NonZero),
|
||||
"sources": r.sources.iter().map(|&i| leaves[i].id.0).collect::<Vec<_>>(),
|
||||
}))
|
||||
"sources": r.sources.iter().filter_map(|&i| id_of(i)).collect::<Vec<_>>(),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
Ok(json!({ "regions": out }))
|
||||
let lines: Vec<Value> =
|
||||
map.lines.iter().map(|(l, bb)| json!({ "bounds": [bb.x0, bb.y0, bb.x1, bb.y1], "source": id_of(l.key as usize) })).collect();
|
||||
Ok(json!({ "regions": regions, "lines": lines }))
|
||||
}
|
||||
|
||||
// ---------- Live Paint ----------
|
||||
|
||||
@@ -79,8 +79,10 @@ pub struct Interaction {
|
||||
pub doc: Arc<Document>,
|
||||
pub selection: Selection,
|
||||
pub preview: Option<(String, Value)>,
|
||||
/// Per-document state restored on cancel (current layer, isolation).
|
||||
/// Per-document state restored on cancel (current layer, highlighted Layers panel rows,
|
||||
/// isolation).
|
||||
pub active_layer: Option<NodeId>,
|
||||
pub layer_rows: Vec<NodeId>,
|
||||
pub isolation: Option<NodeId>,
|
||||
/// The perspective transform the previews make (`perspective.transform` params): Transform
|
||||
/// Again repeats it once the drag is committed.
|
||||
@@ -206,6 +208,7 @@ impl DocState {
|
||||
self.doc = it.doc;
|
||||
self.selection = it.selection;
|
||||
self.active_layer = it.active_layer;
|
||||
self.layer_rows = it.layer_rows;
|
||||
self.isolation = it.isolation;
|
||||
self.revision += 1;
|
||||
}
|
||||
@@ -1114,6 +1117,7 @@ impl Session {
|
||||
selection: st.selection.clone(),
|
||||
preview: None,
|
||||
active_layer: st.active_layer,
|
||||
layer_rows: st.layer_rows.clone(),
|
||||
isolation: st.isolation,
|
||||
perspective_again: None,
|
||||
});
|
||||
|
||||
@@ -172,6 +172,154 @@ fn shape_builder_tool_drives_the_command() {
|
||||
assert_eq!(layer_children(&s), 1);
|
||||
}
|
||||
|
||||
/// A red 100 × 100 square crossed by a stroke-only vertical line at x = 50, both selected.
|
||||
fn square_and_line(s: &mut Session) -> (NodeId, NodeId) {
|
||||
let a = rect(s, 0.0, 0.0, 100.0, 100.0);
|
||||
set_fill(s, a, Color::rgb(1.0, 0.0, 0.0));
|
||||
let l = line(s, (50.0, -20.0), (50.0, 120.0));
|
||||
s.execute("select.set", &json!({"ids": [a.0, l.0]})).unwrap();
|
||||
(a, l)
|
||||
}
|
||||
|
||||
/// The open paths among `ids`, as (anchors, bounds).
|
||||
fn open_paths(s: &Session, ids: &[NodeId]) -> Vec<(usize, Rect)> {
|
||||
ids.iter()
|
||||
.map(|i| node(s, *i))
|
||||
.filter(|n| !outline(n).0.is_closed())
|
||||
.map(|n| (outline(&n).0.anchor_count(), n.geometric_bounds().unwrap()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shape_builder_line_splits_a_shape_into_regions() {
|
||||
let mut s = session();
|
||||
let (a, l) = square_and_line(&mut s);
|
||||
let r = s.execute("shapeBuilder.regions", &json!({})).unwrap();
|
||||
let regs = r["regions"].as_array().unwrap();
|
||||
assert_eq!(regs.len(), 2, "{r}");
|
||||
for x in regs {
|
||||
assert!((x["area"].as_f64().unwrap() - 5000.0).abs() < 1e-6);
|
||||
assert_eq!(x["sources"], json!([a.0]));
|
||||
}
|
||||
let lines = r["lines"].as_array().unwrap();
|
||||
assert_eq!(lines.len(), 3, "the line cut at both sides of the square");
|
||||
assert!(lines.iter().all(|x| x["source"] == l.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shape_builder_click_on_a_side_of_a_line_splits_the_shape() {
|
||||
let mut s = session();
|
||||
square_and_line(&mut s);
|
||||
let r = s.execute("shapeBuilder.merge", &json!({"points": [[25, 50]]})).unwrap();
|
||||
assert_eq!(r["regions"], 1);
|
||||
let out = ids(&r);
|
||||
let merged = NodeId(r["merged"].as_u64().unwrap());
|
||||
assert_eq!(node(&s, merged).geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 50.0, 100.0));
|
||||
assert_eq!(node(&s, merged).appearance.fill_paint(), Paint::solid(Color::rgb(1.0, 0.0, 0.0)));
|
||||
let closed: Vec<f64> = out.iter().filter(|i| outline(&node(&s, **i)).0.is_closed()).map(|i| area(&s, *i)).collect();
|
||||
assert_eq!(closed.len(), 2, "both halves");
|
||||
assert!(closed.iter().all(|a| (a - 5000.0).abs() < 1.0), "{closed:?}");
|
||||
// The line only bounds the region: it stays whole.
|
||||
assert_eq!(open_paths(&s, &out), vec![(2, Rect::new(50.0, -20.0, 50.0, 120.0))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shape_builder_merge_across_a_line_removes_the_piece_between() {
|
||||
let mut s = session();
|
||||
square_and_line(&mut s);
|
||||
let r = s.execute("shapeBuilder.merge", &json!({"points": [[25, 50], [75, 50]]})).unwrap();
|
||||
assert_eq!(r["regions"], 2);
|
||||
let out = ids(&r);
|
||||
let merged = NodeId(r["merged"].as_u64().unwrap());
|
||||
assert!((area(&s, merged) - 10000.0).abs() < 1.0);
|
||||
assert_eq!(out.len(), 3, "merged square + the line's two loose ends");
|
||||
let mut ends = open_paths(&s, &out);
|
||||
ends.sort_by(|a, b| a.1.y0.total_cmp(&b.1.y0));
|
||||
assert_eq!(ends, vec![(2, Rect::new(50.0, -20.0, 50.0, 0.0)), (2, Rect::new(50.0, 100.0, 50.0, 120.0))]);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(layer_children(&s), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shape_builder_alt_deletes_a_region_or_a_line_piece() {
|
||||
let mut s = session();
|
||||
square_and_line(&mut s);
|
||||
let r = s.execute("shapeBuilder.merge", &json!({"points": [[75, 50]], "erase": true})).unwrap();
|
||||
assert!(r["merged"].is_null());
|
||||
let out = ids(&r);
|
||||
let left: Vec<NodeId> = out.iter().copied().filter(|i| outline(&node(&s, *i)).0.is_closed()).collect();
|
||||
assert_eq!(left.len(), 1);
|
||||
assert_eq!(node(&s, left[0]).geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 50.0, 100.0));
|
||||
assert_eq!(open_paths(&s, &out).len(), 1, "the line stays whole");
|
||||
|
||||
// Alt on the line inside the square deletes that piece only.
|
||||
let mut s = session();
|
||||
square_and_line(&mut s);
|
||||
let r = s.execute("shapeBuilder.merge", &json!({"points": [[51, 50]], "erase": true, "tolerance": 2})).unwrap();
|
||||
assert_eq!((r["regions"].as_u64(), r["lines"].as_u64()), (Some(0), Some(1)));
|
||||
let out = ids(&r);
|
||||
assert_eq!(out.len(), 3);
|
||||
let sq: Vec<NodeId> = out.iter().copied().filter(|i| outline(&node(&s, *i)).0.is_closed()).collect();
|
||||
assert_eq!(sq.len(), 1);
|
||||
assert!((area(&s, sq[0]) - 10000.0).abs() < 1.0, "the square is untouched");
|
||||
assert_eq!(open_paths(&s, &out).len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shape_builder_fills_an_area_lines_enclose() {
|
||||
let mut s = session();
|
||||
let l1 = line(&mut s, (0.0, 0.0), (100.0, 100.0));
|
||||
let l2 = line(&mut s, (100.0, 0.0), (0.0, 100.0));
|
||||
let l3 = line(&mut s, (-10.0, 80.0), (110.0, 80.0));
|
||||
s.execute("select.set", &json!({"ids": [l1.0, l2.0, l3.0]})).unwrap();
|
||||
let r = s.execute("shapeBuilder.regions", &json!({})).unwrap();
|
||||
assert_eq!(r["regions"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(r["regions"][0]["sources"], json!([]));
|
||||
let r = s.execute("shapeBuilder.merge", &json!({"points": [[50, 70]]})).unwrap();
|
||||
let merged = NodeId(r["merged"].as_u64().unwrap());
|
||||
assert!((area(&s, merged) - 900.0).abs() < 1e-6, "{}", area(&s, merged));
|
||||
assert_eq!(node(&s, merged).appearance.fill_paint(), s.paint.fill, "the current fill");
|
||||
assert!(!node(&s, merged).appearance.stroke_paint().is_none(), "the lines' stroke");
|
||||
assert_eq!(ids(&r).len(), 4, "the triangle + the three lines, which only bound it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shape_builder_closes_filled_open_paths() {
|
||||
let mut s = session();
|
||||
let r = s.execute("path.create", &json!({"anchors": [{"x": 0, "y": 0}, {"x": 100, "y": 0}, {"x": 100, "y": 100}]})).unwrap();
|
||||
let p = NodeId(r["id"].as_u64().unwrap());
|
||||
set_fill(&mut s, p, Color::rgb(0.0, 1.0, 0.0));
|
||||
s.execute("select.set", &json!({"ids": [p.0]})).unwrap();
|
||||
let r = s.execute("shapeBuilder.regions", &json!({})).unwrap();
|
||||
assert_eq!(r["regions"].as_array().unwrap().len(), 1, "the fill's area, closed by an invisible edge");
|
||||
assert!((r["regions"][0]["area"].as_f64().unwrap() - 5000.0).abs() < 1e-6);
|
||||
assert_eq!(r["lines"], json!([]));
|
||||
// Unfilled, it is only an edge.
|
||||
s.edit("t", |d, _| {
|
||||
d.node_mut(p).unwrap().appearance.set_fill(Paint::None);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let r = s.execute("shapeBuilder.regions", &json!({})).unwrap();
|
||||
assert_eq!(r["regions"], json!([]));
|
||||
assert_eq!(r["lines"].as_array().unwrap().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shape_builder_tool_alt_deletes_line_pieces() {
|
||||
let mut s = session();
|
||||
square_and_line(&mut s);
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool("shapeBuilder", v).unwrap();
|
||||
let alt = Mods { alt: true, ..Default::default() };
|
||||
s.pointer(&PointerEvent::new(PointerKind::Move, 51.0, 50.0).with_mods(alt), v).unwrap();
|
||||
assert_eq!(s.overlays(v).len(), 1, "the line piece is highlighted");
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 51.0, 50.0).with_mods(alt), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 51.0, 50.0).with_mods(alt), v).unwrap();
|
||||
assert_eq!(s.journal.last().unwrap().0, "shapeBuilder.merge");
|
||||
assert_eq!(layer_children(&s), 3, "square + the line's two loose ends");
|
||||
}
|
||||
|
||||
// ---------- Live Paint ----------
|
||||
|
||||
fn live(s: &mut Session) -> NodeId {
|
||||
|
||||
@@ -231,3 +231,21 @@ fn a_failed_batch_brings_back_a_document_it_reverted() {
|
||||
assert!(st.is_dirty() && st.interaction.is_none());
|
||||
assert!(st.revision > revision, "the restored document redraws");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_batch_gives_back_the_highlighted_rows_and_the_current_layer() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"created": null})).unwrap();
|
||||
let layer = s.doc().unwrap().doc.layers[0].id;
|
||||
// A step that highlights the layer's row, then one that fails: the highlight goes back too.
|
||||
let steps = json!([{"command": "layer.setCurrent", "params": {"id": layer.0}}, {"command": "no.such.command"}]);
|
||||
assert!(s.execute("command.batch", &json!({ "commands": steps })).is_err());
|
||||
assert!(s.doc().unwrap().layer_rows.is_empty(), "no row stays highlighted");
|
||||
assert_eq!(s.doc().unwrap().active_layer, Some(layer));
|
||||
// So Collect in New Layer acts on the drawn rectangle, as it does when the journal is replayed
|
||||
// (a failed batch isn't journaled).
|
||||
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 1, "height": 1})).unwrap();
|
||||
s.execute("layer.collectInNew", &json!({})).unwrap();
|
||||
let r = replayed(&s);
|
||||
assert_eq!(documents(&r), documents(&s));
|
||||
}
|
||||
@@ -35,6 +35,7 @@ pub struct Region { pub path: PathData, pub sources: Vec<usize> }
|
||||
pub fn regions(shapes: &[Shape]) -> Vec<Region>; // all faces of the arrangement
|
||||
pub fn region_at(shapes: &[Shape], p: Point) -> Option<Region>;
|
||||
pub fn merge_regions(regions: &[&Region]) -> PathData; // Shape Builder merge = union
|
||||
pub fn shape_builder(shapes: &[Shape]) -> (Vec<Region>, Vec<Shape>); // (regions, open-path pieces)
|
||||
```
|
||||
|
||||
Each result takes its key as follows:
|
||||
@@ -58,6 +59,8 @@ pub fn interior_point(path: &PathData) -> Option<Point>;
|
||||
|
||||
Unlike `regions`, which splits the filled areas of closed shapes, `live_paint` treats every path as an edge, open paths included. Three crossing lines enclose a triangle, a line across a rectangle splits it in two, and an area enclosed by paths becomes a face even when nothing fills it. Each face lists the inputs whose fill covers it; the list is empty for an area that is only enclosed by paths. Each edge is a piece of a path, split wherever another path meets it, and keeps the key of the front-most input it lies on.
|
||||
|
||||
`shape_builder` gives the Shape Builder's regions. With closed paths only, they are the `regions`. Once an open path is among them, they are the `live_paint` faces, so a stroke-only line across a shape splits it and lines can enclose a region of their own. The second list holds the pieces of each path that has no closed subpath, keyed by its index, so the Shape Builder can delete them one by one. The caller closes any open path whose fill should count. Inputs with more than `SHAPE_BUILDER_MAX_SEGMENTS` segments fall back to the filled areas.
|
||||
|
||||
## Offset / stroke
|
||||
|
||||
```rust
|
||||
|
||||
@@ -20,7 +20,7 @@ pub use edit::{
|
||||
};
|
||||
pub use offset::{Cap, Join, offset_path, outline_stroke, stroke_region};
|
||||
pub use pathfinder::{PathfinderOp, Region, Shape, merge_regions, pathfinder, region_at, regions};
|
||||
pub use planar::{interior_point, live_paint};
|
||||
pub use planar::{SHAPE_BUILDER_MAX_SEGMENTS, interior_point, live_paint, shape_builder};
|
||||
|
||||
/// Errors from fallible operations.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
|
||||
|
||||
@@ -288,6 +288,32 @@ pub fn live_paint(shapes: &[Shape]) -> (Vec<Region>, Vec<Shape>) {
|
||||
build(shapes).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Most segments the Shape Builder sweeps with open paths as edges: the planar map costs far more
|
||||
/// than the filled areas' arrangement, so past this only the filled areas count.
|
||||
pub const SHAPE_BUILDER_MAX_SEGMENTS: usize = 4096;
|
||||
|
||||
/// Shape Builder regions of `shapes` (back → front), and the pieces of their open paths.
|
||||
///
|
||||
/// Closed paths bound regions with their filled areas, as in [`regions`](crate::regions). Open
|
||||
/// paths (the caller closes the ones whose fill should count) are cutting edges: a line across a
|
||||
/// shape splits it, lines around an area enclose a region nothing fills (empty `sources`), and each
|
||||
/// path with no closed subpath comes back cut wherever another path meets it, as pieces keyed by
|
||||
/// its index in `shapes`. With no open path, more than [`SHAPE_BUILDER_MAX_SEGMENTS`] segments or
|
||||
/// a map that can't be built, only the filled areas count and there are no pieces.
|
||||
pub fn shape_builder(shapes: &[Shape]) -> (Vec<Region>, Vec<Shape>) {
|
||||
let has_open = shapes.iter().flat_map(|s| &s.path.subpaths).any(|sp| !sp.closed && sp.anchors.len() >= 2);
|
||||
let segments: usize = shapes.iter().flat_map(|s| &s.path.subpaths).map(|sp| sp.segment_count()).sum();
|
||||
if has_open && segments <= SHAPE_BUILDER_MAX_SEGMENTS {
|
||||
let keyed: Vec<Shape> = shapes.iter().enumerate().map(|(i, s)| Shape::new(s.path.clone(), s.rule, i as u64)).collect();
|
||||
let (faces, edges) = live_paint(&keyed);
|
||||
if !faces.is_empty() || !edges.is_empty() {
|
||||
let is_line = |i: u64| shapes.get(i as usize).is_some_and(|s| !s.path.subpaths.iter().any(|sp| sp.closed));
|
||||
return (faces, edges.into_iter().filter(|e| is_line(e.key)).collect());
|
||||
}
|
||||
}
|
||||
(crate::regions(shapes), Vec::new())
|
||||
}
|
||||
|
||||
fn build(shapes: &[Shape]) -> Option<(Vec<Region>, Vec<Shape>)> {
|
||||
let mut inputs: Vec<(BezPath, usize)> = Vec::new();
|
||||
for (i, s) in shapes.iter().enumerate() {
|
||||
@@ -736,6 +762,69 @@ mod tests {
|
||||
assert_eq!(edges.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shape_builder_lines_cut_regions() {
|
||||
// A line across a rectangle: two regions, the line in three pieces keyed by its index.
|
||||
let s = [rect(0.0, 0.0, 100.0, 50.0, 7), line((40.0, -20.0), (60.0, 70.0), 8)];
|
||||
let (regions, lines) = shape_builder(&s);
|
||||
assert_eq!(regions.len(), 2);
|
||||
assert!(regions.iter().all(|r| r.sources == [0]));
|
||||
assert_eq!(lines.len(), 3);
|
||||
assert!(lines.iter().all(|l| l.key == 1 && !l.path.is_closed()));
|
||||
// Lines alone enclose a region nothing fills.
|
||||
let s = [line((0.0, 0.0), (100.0, 100.0), 0), line((100.0, 0.0), (0.0, 100.0), 0), line((-10.0, 80.0), (110.0, 80.0), 0)];
|
||||
let (regions, lines) = shape_builder(&s);
|
||||
assert_eq!(regions.len(), 1);
|
||||
assert!(regions[0].sources.is_empty() && regions[0].top().is_none());
|
||||
assert_eq!(lines.len(), 9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shape_builder_closed_only_or_degenerate_is_the_filled_arrangement() {
|
||||
let s = [rect(0.0, 0.0, 100.0, 100.0, 0), rect(50.0, 0.0, 150.0, 100.0, 1)];
|
||||
assert_eq!(shape_builder(&s), (crate::regions(&s), vec![]));
|
||||
// A broken line can't be swept: what the filled areas give (nothing here, without a panic).
|
||||
let s = [rect(0.0, 0.0, 100.0, 100.0, 0), line((0.0, 0.0), (f64::NAN, 1.0), 1)];
|
||||
assert_eq!(shape_builder(&s), (crate::regions(&s), vec![]));
|
||||
// Zero-length and doubled-back lines don't break it either.
|
||||
let s = [
|
||||
rect(0.0, 0.0, 100.0, 100.0, 0),
|
||||
line((50.0, 50.0), (50.0, 50.0), 1),
|
||||
line((0.0, 0.0), (100.0, 0.0), 2),
|
||||
line((50.0, 0.0), (50.0, 100.0), 3),
|
||||
];
|
||||
let (regions, _) = shape_builder(&s);
|
||||
assert_eq!(regions.len(), 2);
|
||||
assert!((regions.iter().map(area).sum::<f64>() - 10000.0).abs() < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shape_builder_stays_quick_up_to_its_cap() {
|
||||
// A wavy ring of nearly the most segments the map takes, crossed by a few lines.
|
||||
let n = SHAPE_BUILDER_MAX_SEGMENTS - 8;
|
||||
let ring: Vec<Point> = (0..n)
|
||||
.map(|k| {
|
||||
let t = k as f64 / n as f64 * std::f64::consts::TAU;
|
||||
let r = 100.0 + 5.0 * (t * 200.0).sin();
|
||||
Point::new(r * t.cos(), r * t.sin())
|
||||
})
|
||||
.collect();
|
||||
let mut s = vec![Shape::new(PathData::single(SubPath::polyline(&ring, true)), FillRule::NonZero, 0)];
|
||||
for k in 0..4 {
|
||||
let y = -60.0 + 40.0 * f64::from(k);
|
||||
s.push(line((-150.0, y), (150.0, y + 7.0), 1));
|
||||
}
|
||||
let started = std::time::Instant::now();
|
||||
let (regions, lines) = shape_builder(&s);
|
||||
assert!(regions.len() >= 5, "the ring cut in five bands at least (the waves make pockets)");
|
||||
assert!(lines.len() >= 12, "{}", lines.len());
|
||||
assert!(started.elapsed().as_secs_f64() < 5.0, "{:?}", started.elapsed());
|
||||
// Past the cap, only the filled areas count.
|
||||
s.push(line((0.0, 0.0), (1.0, 1.0), 2));
|
||||
s[0].path.subpaths[0].anchors.extend((0..16).map(|k| vectorcraft_geom::Anchor::corner(Point::new(100.0, f64::from(k)))));
|
||||
assert!(shape_builder(&s).1.is_empty());
|
||||
}
|
||||
|
||||
fn arb_segment() -> impl Strategy<Value = Shape> {
|
||||
let c = || (0..10i32).prop_map(|v| f64::from(v) * 10.0);
|
||||
prop_oneof![
|
||||
|
||||
+112
-20
@@ -11,7 +11,7 @@ use hayro_interpret::{
|
||||
MaskType, PathDrawMode, SoftMask, StrokeProps, interpret_page,
|
||||
};
|
||||
use hayro_syntax::object::Name;
|
||||
use kurbo::{Affine, BezPath, Rect, Shape};
|
||||
use kurbo::{Affine, BezPath, PathEl, Rect, Shape};
|
||||
use vectorcraft_color::{BlendMode, Color, Paint, Swatch};
|
||||
use vectorcraft_doc::{
|
||||
Appearance, AppearanceItem, Artboard, ColorMode, Dash, Document, FillLayer, ImageBlob, ImageObject, Knockout, LayerColor, LineCap, LineJoin,
|
||||
@@ -21,7 +21,7 @@ use vectorcraft_geom::{FillRule, PathData};
|
||||
|
||||
use crate::import_color::{Colors, Native};
|
||||
use crate::import_mask::{MaskSpec, contains, is_rectangle, luminance, mask_spec, white_cover};
|
||||
use crate::import_scan::{Ocgs, Scan, all_on, hides_forms, scan_page};
|
||||
use crate::import_scan::{MAX_NESTING, Ocgs, Scan, all_on, hides_forms, scan_page};
|
||||
use crate::import_shading::{clipped, extend_clip, fold_stop_opacity, mesh_shading, shading_gradient};
|
||||
use crate::import_text::{Families, Look, Placement, TextLine, Upright};
|
||||
use crate::{CropTo, ImportOptions, ImportReport, PdfError, TextAs};
|
||||
@@ -46,6 +46,60 @@ enum Slot {
|
||||
Group(usize),
|
||||
}
|
||||
|
||||
/// What each group's layer holds, in paint order: its sublayers (their groups) and, where its
|
||||
/// own group is listed, its art.
|
||||
type Nesting = HashMap<usize, Vec<usize>>;
|
||||
|
||||
/// Group `g` paints (its first art): note where its art goes in its layer, and where that layer
|
||||
/// goes when it is new: in its parent's layer (placed the same way) or, for a top-level group, in
|
||||
/// `slots`.
|
||||
fn place_group(g: usize, ocgs: &Ocgs, slots: &mut Vec<Slot>, nesting: &mut Nesting) {
|
||||
let placed = nesting.contains_key(&g);
|
||||
nesting.entry(g).or_default().push(g);
|
||||
if placed {
|
||||
return;
|
||||
}
|
||||
let mut child = g;
|
||||
// Each parent is placed before its sublayers, so the chain ends (within the nesting depth).
|
||||
for _ in 0..=MAX_NESTING {
|
||||
let Some(parent) = ocgs.list.get(child).and_then(|o| o.parent) else { break };
|
||||
let placed = nesting.contains_key(&parent);
|
||||
nesting.entry(parent).or_default().push(child);
|
||||
if placed {
|
||||
return;
|
||||
}
|
||||
child = parent;
|
||||
}
|
||||
slots.push(Slot::Group(child));
|
||||
}
|
||||
|
||||
/// The layer of group `g`, in `color`: its art and sublayers. `None` for a group that isn't read.
|
||||
fn group_layer(
|
||||
b: &mut Builder<'_>,
|
||||
g: usize,
|
||||
ocgs: &Ocgs,
|
||||
nesting: &Nesting,
|
||||
art: &mut HashMap<usize, Vec<Arc<Node>>>,
|
||||
color: LayerColor,
|
||||
) -> Option<Node> {
|
||||
let ocg = ocgs.list.get(g)?;
|
||||
let mut l = Node::layer(b.id(), &ocg.name, color);
|
||||
(l.visible, l.locked) = (ocg.on, ocg.locked);
|
||||
let mut children = vec![];
|
||||
for &c in nesting.get(&g).into_iter().flatten() {
|
||||
if c == g {
|
||||
children.extend(art.remove(&g).unwrap_or_default());
|
||||
} else if let Some(sub) = group_layer(b, c, ocgs, nesting, art, color) {
|
||||
children.push(Arc::new(sub));
|
||||
}
|
||||
}
|
||||
if let NodeKind::Layer { children: c, printable, .. } = &mut l.kind {
|
||||
*c = children;
|
||||
*printable = ocg.print;
|
||||
}
|
||||
Some(l)
|
||||
}
|
||||
|
||||
/// Import a PDF, returning the document plus warnings about content that was approximated or skipped.
|
||||
pub fn import_with_report(bytes: &[u8], opts: &ImportOptions) -> Result<ImportReport, PdfError> {
|
||||
let original = crate::pages::open(bytes, opts.password.as_deref())?;
|
||||
@@ -54,7 +108,7 @@ pub fn import_with_report(bytes: &[u8], opts: &ImportOptions) -> Result<ImportRe
|
||||
let route = opts.layers && !ocgs.list.is_empty();
|
||||
// Content that is off imports as hidden layers: an update of the file turns every group on
|
||||
// (unless a form is hidden by its own group: its art couldn't be told apart).
|
||||
let hide = route && ocgs.any_off();
|
||||
let hide = route && ocgs.skips_any();
|
||||
let turned_on = (hide && !picked.iter().filter_map(|&n| original.pages().get(n)).any(|p| hides_forms(p, &mut ocgs)))
|
||||
.then(|| all_on(bytes, &original))
|
||||
.flatten()
|
||||
@@ -100,6 +154,7 @@ pub fn import_with_report(bytes: &[u8], opts: &ImportOptions) -> Result<ImportRe
|
||||
let mut placeholder = true;
|
||||
let mut slots: Vec<Slot> = vec![];
|
||||
let mut group_art: HashMap<usize, Vec<Arc<Node>>> = HashMap::new();
|
||||
let mut nesting = Nesting::new();
|
||||
for (i, &number) in picked.iter().enumerate() {
|
||||
let Some(page) = pages.get(number) else { continue };
|
||||
// The chosen box sits at (x, 0); the page draws round it.
|
||||
@@ -158,7 +213,7 @@ pub fn import_with_report(bytes: &[u8], opts: &ImportOptions) -> Result<ImportRe
|
||||
None => slots.push(page_layer(&mut b, art)),
|
||||
Some(g) => {
|
||||
let into = group_art.entry(g).or_insert_with(|| {
|
||||
slots.push(Slot::Group(g));
|
||||
place_group(g, &ocgs, &mut slots, &mut nesting);
|
||||
vec![]
|
||||
});
|
||||
into.extend(art);
|
||||
@@ -172,16 +227,11 @@ pub fn import_with_report(bytes: &[u8], opts: &ImportOptions) -> Result<ImportRe
|
||||
for (n, slot) in slots.into_iter().enumerate() {
|
||||
let layer = match slot {
|
||||
Slot::Page(l) => *l,
|
||||
Slot::Group(g) => {
|
||||
let Some(ocg) = ocgs.list.get(g) else { continue };
|
||||
let mut l = Node::layer(b.id(), &ocg.name, LayerColor::Preset((n % 27) as u8));
|
||||
(l.visible, l.locked) = (ocg.on, ocg.locked);
|
||||
if let NodeKind::Layer { children, printable, .. } = &mut l.kind {
|
||||
*children = group_art.remove(&g).unwrap_or_default();
|
||||
*printable = ocg.print;
|
||||
}
|
||||
l
|
||||
}
|
||||
// Sublayers take their top-level layer's colour.
|
||||
Slot::Group(g) => match group_layer(&mut b, g, &ocgs, &nesting, &mut group_art, LayerColor::Preset((n % 27) as u8)) {
|
||||
Some(l) => l,
|
||||
None => continue,
|
||||
},
|
||||
};
|
||||
doc.layers.push(Arc::new(layer));
|
||||
}
|
||||
@@ -497,6 +547,8 @@ struct Builder<'p> {
|
||||
/// A transparency group was just pushed: a form's (whose flags come next) or an image's.
|
||||
pending: bool,
|
||||
nested: u32,
|
||||
/// The last filled path: its node and its outline (a stroke of the same outline joins it).
|
||||
last_fill: Option<(NodeId, BezPath)>,
|
||||
}
|
||||
|
||||
fn blend(b: hayro_interpret::BlendMode) -> BlendMode {
|
||||
@@ -528,6 +580,29 @@ fn fill_rule(r: hayro_interpret::FillRule) -> FillRule {
|
||||
}
|
||||
}
|
||||
|
||||
/// `p` with every subpath closed: how a fill reads it.
|
||||
fn closed_subpaths(p: &BezPath) -> BezPath {
|
||||
let mut out = BezPath::new();
|
||||
let mut open = false;
|
||||
for el in p.elements() {
|
||||
if open && matches!(el, PathEl::MoveTo(_)) {
|
||||
out.push(PathEl::ClosePath);
|
||||
}
|
||||
out.push(*el);
|
||||
open = !matches!(el, PathEl::ClosePath);
|
||||
}
|
||||
if open {
|
||||
out.push(PathEl::ClosePath);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Do a fill of `fill` and a stroke of `stroke` paint one object's outline? Applications write the
|
||||
/// fill without closing the path (filling closes it) and the stroke closed.
|
||||
fn same_outline(fill: &BezPath, stroke: &BezPath) -> bool {
|
||||
fill.elements() == stroke.elements() || closed_subpaths(fill).elements() == closed_subpaths(stroke).elements()
|
||||
}
|
||||
|
||||
fn mean_scale(a: Affine) -> f64 {
|
||||
a.determinant().abs().sqrt()
|
||||
}
|
||||
@@ -606,6 +681,7 @@ impl<'p> Builder<'p> {
|
||||
marked: vec![],
|
||||
pending: false,
|
||||
nested: 0,
|
||||
last_fill: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -656,10 +732,15 @@ impl<'p> Builder<'p> {
|
||||
let children = self.close_frames();
|
||||
let groups = std::mem::take(&mut self.root_groups);
|
||||
let mut parts: Vec<(Option<usize>, Vec<Arc<Node>>)> = vec![];
|
||||
// Thousands of groups: find each one's part by index.
|
||||
let mut at: HashMap<Option<usize>, usize> = HashMap::new();
|
||||
for (n, g) in children.into_iter().zip(groups.into_iter().chain(std::iter::repeat(None))) {
|
||||
match parts.iter_mut().find(|(k, _)| *k == g) {
|
||||
Some((_, v)) => v.push(n),
|
||||
None => parts.push((g, vec![n])),
|
||||
let i = *at.entry(g).or_insert_with(|| {
|
||||
parts.push((g, vec![]));
|
||||
parts.len() - 1
|
||||
});
|
||||
if let Some((_, v)) = parts.get_mut(i) {
|
||||
v.push(n);
|
||||
}
|
||||
}
|
||||
parts
|
||||
@@ -1219,24 +1300,35 @@ impl<'a> Device<'a> for Builder<'_> {
|
||||
if let NodeKind::Path { rule: r, .. } = &mut n.kind {
|
||||
*r = fill_rule(*rule);
|
||||
}
|
||||
self.last_fill = Some((n.id, bp));
|
||||
let n = wrap(self, n);
|
||||
self.push_node(n);
|
||||
}
|
||||
PathDrawMode::Stroke(props) => {
|
||||
let st = stroke_layer(paint, opacity, props, mean_scale(transform));
|
||||
// Fill-then-stroke of the same path (the `B` operator) becomes one object.
|
||||
// Fill-then-stroke of the same path (the `B` operator, or a fill and a stroke of
|
||||
// the outline as Illustrator writes an object) becomes one object: a path with a
|
||||
// fill and a live stroke.
|
||||
let blend = self.blend;
|
||||
let fill = self.last_fill.take();
|
||||
let last = match self.mask {
|
||||
Some(_) => self.masked.last_mut(),
|
||||
None => self.stack.last_mut().and_then(|f| f.children.last_mut()),
|
||||
};
|
||||
if band.is_none()
|
||||
&& let Some(last) = last
|
||||
&& let Some((id, outline)) = fill
|
||||
&& last.id == id
|
||||
&& last.blend == blend
|
||||
&& last.path_data() == Some(&pd)
|
||||
&& last.appearance.stroke().is_none()
|
||||
&& same_outline(&outline, &bp)
|
||||
{
|
||||
Arc::make_mut(last).appearance.items.push(AppearanceItem::Stroke(st));
|
||||
let last = Arc::make_mut(last);
|
||||
// The stroke's outline: closing it changes the stroke, not the fill.
|
||||
if let Some(p) = last.path_data_mut() {
|
||||
*p = pd;
|
||||
}
|
||||
last.appearance.items.push(AppearanceItem::Stroke(st));
|
||||
return;
|
||||
}
|
||||
let n = Node::path(self.id(), pd, Appearance { items: vec![AppearanceItem::Stroke(st)], ..Default::default() });
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! What the interpreter doesn't tell the import, read from the file itself: the optional content
|
||||
//! groups (layers) with their states, which group each marked-content sequence belongs to, the
|
||||
//! isolate and knockout flags of transparency groups, and the names of the fonts.
|
||||
//! groups (layers) with their states and nesting, which group each marked-content sequence belongs
|
||||
//! to, the isolate and knockout flags of transparency groups, and the names of the fonts.
|
||||
//!
|
||||
//! hayro-interpret reports a marked-content sequence by its tag alone and a transparency group
|
||||
//! without its flags, and skips the content of groups that are off. So each page's content is
|
||||
@@ -16,7 +16,7 @@ use hayro_interpret::CacheKey;
|
||||
use hayro_syntax::Pdf;
|
||||
use hayro_syntax::content::TypedIter;
|
||||
use hayro_syntax::content::ops::TypedInstruction;
|
||||
use hayro_syntax::object::{Array, Dict, FromBytes, Name, Object, ObjectIdentifier, dict_or_stream};
|
||||
use hayro_syntax::object::{Array, Dict, FromBytes, MaybeRef, Name, Object, ObjectIdentifier, dict_or_stream};
|
||||
use hayro_syntax::page::{Page, Resources};
|
||||
|
||||
/// The interpreter's limit on nested form XObjects.
|
||||
@@ -25,6 +25,8 @@ const MAX_DEPTH: u32 = 50;
|
||||
const MAX_OPS: usize = 2_000_000;
|
||||
/// The most groups read.
|
||||
const MAX_GROUPS: usize = 10_000;
|
||||
/// The deepest layers nest in the configuration's `/Order`.
|
||||
pub(crate) const MAX_NESTING: usize = 32;
|
||||
|
||||
/// An optional content group: a layer.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
@@ -35,6 +37,8 @@ pub(crate) struct Ocg {
|
||||
/// Printed (its print usage isn't off).
|
||||
pub print: bool,
|
||||
pub locked: bool,
|
||||
/// The group it is listed under in the layer order (a sublayer of it).
|
||||
pub parent: Option<usize>,
|
||||
}
|
||||
|
||||
/// The file's optional content groups.
|
||||
@@ -44,6 +48,10 @@ pub(crate) struct Ocgs {
|
||||
index: HashMap<ObjectIdentifier, usize>,
|
||||
/// The groups that are off (as the interpreter decides it).
|
||||
off: HashSet<ObjectIdentifier>,
|
||||
/// The groups whose view state applies when the file opens (an `/AS` entry for viewing).
|
||||
view_auto: HashSet<ObjectIdentifier>,
|
||||
/// The groups placed in the layer order.
|
||||
placed: HashSet<usize>,
|
||||
}
|
||||
|
||||
impl Ocgs {
|
||||
@@ -68,35 +76,88 @@ impl Ocgs {
|
||||
o.off.remove(&id);
|
||||
}
|
||||
o.off.extend(refs(&config, b"OFF"));
|
||||
let auto = config.get::<Array<'_>>(b"AS").map(|a| a.iter::<Dict<'_>>().take(MAX_GROUPS).collect::<Vec<_>>()).unwrap_or_default();
|
||||
for d in auto.iter().filter(|d| d.get::<Name<'_>>(b"Event").is_some_and(|e| e.as_ref() == b"View")) {
|
||||
o.view_auto.extend(refs(d, b"OCGs"));
|
||||
}
|
||||
let locked: HashSet<_> = refs(&config, b"Locked").into_iter().collect();
|
||||
for id in all {
|
||||
if let Some(d) = xref.get::<Dict<'_>>(id) {
|
||||
o.add(id, &d, locked.contains(&id));
|
||||
}
|
||||
}
|
||||
if let Some(order) = config.get::<Array<'_>>(b"Order") {
|
||||
o.nest(&order, None, 0, xref, &mut 0);
|
||||
}
|
||||
o
|
||||
}
|
||||
|
||||
/// Read the layer order `order` (listed under group `parent`): a group followed by an array
|
||||
/// lists that array's groups as its sublayers; an array starting with a label lists its
|
||||
/// groups under the label, which isn't a group (they go under `parent`). A group listed twice
|
||||
/// stays where it is first listed. `seen`: the entries read so far.
|
||||
fn nest(&mut self, order: &Array<'_>, parent: Option<usize>, depth: usize, xref: &hayro_syntax::xref::XRef, seen: &mut usize) {
|
||||
let mut prev = None;
|
||||
for item in order.raw_iter() {
|
||||
*seen += 1;
|
||||
if *seen > 4 * MAX_GROUPS {
|
||||
return;
|
||||
}
|
||||
let sub = match item {
|
||||
MaybeRef::Ref(r) => {
|
||||
let id = ObjectIdentifier::from(r);
|
||||
let sub = xref.get::<Array<'_>>(id);
|
||||
if sub.is_none() {
|
||||
prev = self.place(id, parent);
|
||||
}
|
||||
sub
|
||||
}
|
||||
MaybeRef::NotRef(o) => o.into_array(),
|
||||
};
|
||||
if let Some(sub) = sub
|
||||
&& depth < MAX_NESTING
|
||||
{
|
||||
let label = matches!(sub.raw_iter().next(), Some(MaybeRef::NotRef(Object::String(_))));
|
||||
let under = prev.take().filter(|_| !label).or(parent);
|
||||
self.nest(&sub, under, depth + 1, xref, seen);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Put group `id` under `parent` in the layer order → its index, unless it isn't a group or
|
||||
/// is already placed. Each group is placed after its parent, so the nesting has no cycles.
|
||||
fn place(&mut self, id: ObjectIdentifier, parent: Option<usize>) -> Option<usize> {
|
||||
let i = *self.index.get(&id)?;
|
||||
let placed = self.placed.insert(i);
|
||||
let g = self.list.get_mut(i).filter(|_| placed)?;
|
||||
g.parent = parent;
|
||||
Some(i)
|
||||
}
|
||||
|
||||
/// Note group `id` (its dictionary `d`) → its index.
|
||||
fn add(&mut self, id: ObjectIdentifier, d: &Dict<'_>, locked: bool) -> usize {
|
||||
if let Some(i) = self.index.get(&id) {
|
||||
return *i;
|
||||
}
|
||||
let name = d.get::<hayro_syntax::object::String<'_>>(b"Name").map(|s| text_string(s.as_bytes())).unwrap_or_default();
|
||||
let print = d
|
||||
.get::<Dict<'_>>(b"Usage")
|
||||
.and_then(|u| u.get::<Dict<'_>>(b"Print"))
|
||||
.and_then(|p| p.get::<Name<'_>>(b"PrintState"))
|
||||
.is_none_or(|s| s.as_ref() != b"OFF");
|
||||
let on = !self.off.contains(&id);
|
||||
self.list.push(Ocg { name: if name.is_empty() { format!("Layer {}", self.list.len() + 1) } else { name }, on, print, locked });
|
||||
let print = usage(d, b"Print", b"PrintState") != Some(false);
|
||||
// A view state applies when the configuration says so on opening; an off one hides the
|
||||
// group all the same (it says how the group is meant to be seen).
|
||||
let view = usage(d, b"View", b"ViewState");
|
||||
let on = match view {
|
||||
Some(v) if self.view_auto.contains(&id) => v,
|
||||
Some(false) => false,
|
||||
_ => !self.off.contains(&id),
|
||||
};
|
||||
let name = if name.is_empty() { format!("Layer {}", self.list.len() + 1) } else { name };
|
||||
self.list.push(Ocg { name, on, print, locked, parent: None });
|
||||
self.index.insert(id, self.list.len() - 1);
|
||||
self.list.len() - 1
|
||||
}
|
||||
|
||||
/// Is any group off?
|
||||
pub fn any_off(&self) -> bool {
|
||||
self.list.iter().any(|g| !g.on)
|
||||
/// Does the interpreter leave out the art of some group (off in the default configuration)?
|
||||
pub fn skips_any(&self) -> bool {
|
||||
self.index.keys().any(|id| self.off.contains(id))
|
||||
}
|
||||
|
||||
/// The group content marked with `/OC` (`d`: the group or membership dictionary, `id` its
|
||||
@@ -119,6 +180,16 @@ impl Ocgs {
|
||||
}
|
||||
}
|
||||
|
||||
/// The state (`ON` → true, `OFF` → false) group `d`'s usage `category` gives in `key`.
|
||||
fn usage(d: &Dict<'_>, category: &[u8], key: &[u8]) -> Option<bool> {
|
||||
let state = d.get::<Dict<'_>>(b"Usage")?.get::<Dict<'_>>(category)?.get::<Name<'_>>(key)?;
|
||||
match state.as_ref() {
|
||||
b"ON" => Some(true),
|
||||
b"OFF" => Some(false),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A PDF text string: UTF-16 (with its byte order mark), UTF-8 (with one) or PDFDocEncoding
|
||||
/// (read as Latin-1, which it matches for letters).
|
||||
pub(crate) fn text_string(b: &[u8]) -> String {
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
//! Import fidelity: soft masks → opacity masks, isolated and knockout groups, tiling patterns →
|
||||
//! pattern swatches, text → point type, mesh shadings → gradient meshes, gradient stop opacity
|
||||
//! and shading Extend flags.
|
||||
//! and shading Extend flags; strokes stay live strokes.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_color::{BlendMode, Color, Gradient, GradientKind, GradientPaint, GradientStop, Paint};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Knockout, Node, NodeId, NodeKind, OpacityMask};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Knockout, LineCap, LineJoin, Node, NodeId, NodeKind, OpacityMask};
|
||||
use vectorcraft_geom::{Rect, shapes};
|
||||
use vectorcraft_testkit::pdf::{PdfPage, first_extra, pdf_with};
|
||||
|
||||
@@ -390,3 +390,57 @@ fn glyphs_turned_along_a_curve_become_type_on_a_path() {
|
||||
assert_eq!(straight.len(), 1);
|
||||
assert!(matches!(straight[0].kind, vectorcraft_doc::TextKind::Point), "{:?}", straight[0].kind);
|
||||
}
|
||||
|
||||
/// The leaves (objects that aren't groups or clipping paths) of a document.
|
||||
fn objects(d: &Document) -> Vec<Node> {
|
||||
all(d).into_iter().filter(|n| !n.is_container() && !matches!(n.kind, NodeKind::Path { clipping: true, .. })).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_object_written_as_a_fill_and_a_closed_stroke_stays_one_path_with_a_live_stroke() {
|
||||
// As Illustrator writes an object: the fill of the outline left open, then the stroke of it
|
||||
// closed, each in its own transform. Two subpaths: one ending on its start, one not.
|
||||
let outline = "0 0 m -20 1 l -30 -12 l -30 30 l 0 0 l 5 5 m 10 5 l 10 10 l";
|
||||
let content = format!(
|
||||
"0.2 0.2 0.2 rg q 1 0 0 1 50 50 cm {outline} f Q 1 1 1 RG 1.5 w 1 J 1 j 4 M [3 2] 1 d q 1 0 0 1 50 50 cm {} S Q",
|
||||
outline.replace(" 5 5 m", " h 5 5 m") + " h"
|
||||
);
|
||||
let d = open(&one_page(&content, "", &[]));
|
||||
let objs = objects(&d);
|
||||
assert_eq!(objs.len(), 1, "one object, not a fill and a separate stroke: {objs:#?}");
|
||||
let n = &objs[0];
|
||||
assert_eq!(fill_color(n), Some(Color::rgb(0.2, 0.2, 0.2)));
|
||||
let st = n.appearance.stroke().expect("a live stroke");
|
||||
assert_eq!(st.paint.color(), Some(Color::WHITE));
|
||||
assert!((st.width - 1.5).abs() < 1e-6);
|
||||
assert_eq!((st.cap, st.join), (LineCap::Round, LineJoin::Round));
|
||||
assert!((st.miter_limit - 4.0).abs() < 1e-6);
|
||||
let dash = st.dash.as_ref().expect("dashed");
|
||||
assert_eq!((dash.pattern.as_slice(), dash.offset), (&[3.0, 2.0][..], 1.0));
|
||||
// The stroke's outline: both subpaths closed, as they were stroked.
|
||||
let p = n.path_data().unwrap();
|
||||
assert_eq!(p.subpaths.len(), 2);
|
||||
assert!(p.is_closed());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn different_outlines_filled_and_stroked_stay_apart() {
|
||||
let d = open(&one_page("1 0 0 rg 10 10 m 40 10 l 40 40 l f 0 0 1 RG 10 10 m 40 10 l 40 40 l 10 40 l h S 0 g 50 50 m 60 60 l S", "", &[]));
|
||||
let objs = objects(&d);
|
||||
assert_eq!(objs.len(), 3);
|
||||
assert!(objs[0].appearance.stroke().is_none() && objs[1].appearance.fill().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stroke_under_a_stretched_transform_stays_a_stroke() {
|
||||
// Stretched twice as wide: the stroke keeps its average width (√2 × 2 pt) rather than
|
||||
// becoming a filled outline.
|
||||
let d = open(&one_page("0 0 1 RG 2 w q 2 0 0 1 0 0 cm 10 10 m 40 10 l 40 40 l S Q", "", &[]));
|
||||
let objs = objects(&d);
|
||||
assert_eq!(objs.len(), 1);
|
||||
assert!(objs[0].appearance.fill().is_none());
|
||||
let st = objs[0].appearance.stroke().expect("a stroke");
|
||||
assert!((st.width - 2.0 * 2f64.sqrt()).abs() < 1e-6, "{}", st.width);
|
||||
let b = objs[0].geometric_bounds().unwrap();
|
||||
assert!((b.x0 - 20.0).abs() < 1e-6 && (b.x1 - 80.0).abs() < 1e-6, "{b:?}");
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Optional content groups become layers: name, visibility, print state and lock; art that is
|
||||
//! off comes in as a hidden layer.
|
||||
//! Optional content groups become layers: name, visibility (the default configuration's or the
|
||||
//! view state's), print state, lock and nesting; art that is off comes in as a hidden layer.
|
||||
|
||||
use vectorcraft_color::Color;
|
||||
use vectorcraft_doc::{Document, Node, NodeKind};
|
||||
@@ -192,3 +192,109 @@ fn a_page_fill_that_is_art_stays() {
|
||||
assert_eq!(names(&d), ["Shapes", "Page 1"]);
|
||||
assert_eq!(path_count(&d), 3);
|
||||
}
|
||||
|
||||
/// A page drawing a red, a blue and a green square in groups `defs` (as `/MC0`–`/MC2`), the
|
||||
/// catalog listing them with default configuration `config`, plus `more` objects; in `config` and
|
||||
/// `more`, `{0}`–`{2}` stand for the groups.
|
||||
fn three_groups(defs: [&str; 3], more: &[&str], config: &str) -> Vec<u8> {
|
||||
let refs = [0, 1, 2].map(|i| format!("{} 0 R", first_extra(1) + i));
|
||||
let fill = |s: &str| (0..3).fold(s.to_string(), |s, i| s.replace(&format!("{{{i}}}"), &refs[i]));
|
||||
let content = "/OC /MC0 BDC 1 0 0 rg 10 10 20 20 re f EMC /OC /MC1 BDC 0 0 1 rg 40 40 20 20 re f EMC /OC /MC2 BDC 0 1 0 rg 70 70 20 20 re f EMC";
|
||||
let page = PdfPage { resources: fill("/Properties << /MC0 {0} /MC1 {1} /MC2 {2} >>"), ..PdfPage::new(100.0, 100.0, content) };
|
||||
let catalog = format!("/OCProperties << /OCGs [{}] /D << {} >> >> ", refs.join(" "), fill(config));
|
||||
let more: Vec<String> = more.iter().map(|m| fill(m)).collect();
|
||||
let objs: Vec<&str> = defs.iter().copied().chain(more.iter().map(String::as_str)).collect();
|
||||
pdf_with_catalog(&[page], &objs, &catalog, None)
|
||||
}
|
||||
|
||||
fn ocg(name: &str, usage: &str) -> String {
|
||||
format!("<< /Type /OCG /Name ({name}) {usage} >>")
|
||||
}
|
||||
|
||||
fn visibility(layers: &[std::sync::Arc<Node>]) -> Vec<bool> {
|
||||
layers.iter().map(|l| l.visible).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_view_state_that_is_off_hides_the_layer_with_its_art() {
|
||||
let off = ocg("Off", "/Usage << /View << /ViewState /OFF >> >>");
|
||||
// With an /AS entry for viewing, the view state wins over the default configuration.
|
||||
let on = ocg("On", "/Usage << /View << /ViewState /ON >> >>");
|
||||
let bytes = three_groups([&ocg("Plain", ""), &off, &on], &[], "/OFF [{2}] /AS [<< /Event /View /Category [/View] /OCGs [{1} {2}] >>]");
|
||||
let d = import(&bytes).unwrap();
|
||||
assert_eq!(names(&d), ["Plain", "Off", "On"]);
|
||||
assert_eq!(visibility(&d.layers), [true, false, true]);
|
||||
assert_eq!(colors(&d.layers[1]), [Color::rgb(0.0, 0.0, 1.0)]);
|
||||
assert_eq!(colors(&d.layers[2]), [Color::rgb(0.0, 1.0, 0.0)], "the art the default configuration hides is read");
|
||||
// Without one, a view state that is off still hides the layer.
|
||||
let d = import(&three_groups([&ocg("Plain", ""), &off, &ocg("Other", "")], &[], "")).unwrap();
|
||||
assert_eq!(visibility(&d.layers), [true, false, true]);
|
||||
assert_eq!(colors(&d.layers[1]), [Color::rgb(0.0, 0.0, 1.0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_groups_become_sublayers_and_hidden_ones_keep_their_art() {
|
||||
// The order as an object of its own (as Illustrator writes it): "Top" holds "Sub", which is
|
||||
// off; a label's groups stay at the level of the label.
|
||||
let order = first_extra(1) + 3;
|
||||
let bytes = three_groups(
|
||||
[&ocg("Top", ""), &ocg("Sub", ""), &ocg("Other", "")],
|
||||
&["[{0} [{1}] [(Label) {2}]]"],
|
||||
&format!("/OFF [{{1}}] /Order {order} 0 R"),
|
||||
);
|
||||
let d = import(&bytes).unwrap();
|
||||
assert_eq!(names(&d), ["Top", "Other"]);
|
||||
assert_eq!(visibility(&d.layers), [true, true]);
|
||||
let top = d.layers[0].children().unwrap();
|
||||
assert_eq!(top.len(), 2, "its art, then its sublayer");
|
||||
assert_eq!(top[0].appearance.fill().and_then(|f| f.paint.color()), Some(Color::rgb(1.0, 0.0, 0.0)));
|
||||
let sub = &top[1];
|
||||
assert!(matches!(sub.kind, NodeKind::Layer { .. }) && sub.name.as_deref() == Some("Sub"));
|
||||
assert!(!sub.visible, "the sublayer that is off is hidden");
|
||||
assert_eq!(colors(sub), [Color::rgb(0.0, 0.0, 1.0)], "with its art");
|
||||
assert_eq!(d.layer_color(sub.id), d.layer_color(d.layers[0].id), "a sublayer takes its layer's colour");
|
||||
assert_eq!(colors(&d.layers[1]), [Color::rgb(0.0, 1.0, 0.0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sublayer_that_paints_first_brings_its_parent_layer() {
|
||||
// "Sub" paints first; "Top", its parent, paints its own art last.
|
||||
let bytes = three_groups([&ocg("Sub", ""), &ocg("Other", ""), &ocg("Top", "")], &[], "/Order [{2} [{0}] {1}]");
|
||||
let d = import(&bytes).unwrap();
|
||||
assert_eq!(names(&d), ["Top", "Other"]);
|
||||
let top = d.layers[0].children().unwrap();
|
||||
assert_eq!(top.len(), 2);
|
||||
assert_eq!(top[0].name.as_deref(), Some("Sub"));
|
||||
assert_eq!(colors(&top[0]), [Color::rgb(1.0, 0.0, 0.0)]);
|
||||
assert_eq!(top[1].appearance.fill().and_then(|f| f.paint.color()), Some(Color::rgb(0.0, 1.0, 0.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_layer_orders_stay_bounded() {
|
||||
// A group listed twice, under itself, and an order nested far deeper than layers go.
|
||||
let deep = format!("{}{{2}}{}", "[".repeat(100), "]".repeat(100));
|
||||
let order = format!("[{{0}} [{{0}} {{1}}] {{1}} [{{0}}] {deep}]");
|
||||
let d = import(&three_groups([&ocg("A", ""), &ocg("B", ""), &ocg("C", "")], &[], &format!("/Order {order}"))).unwrap();
|
||||
assert_eq!(names(&d), ["A", "C"], "C, listed too deep, stays a top-level layer");
|
||||
assert_eq!(d.layers[0].children().unwrap()[1].name.as_deref(), Some("B"));
|
||||
let mut count = 0;
|
||||
d.walk(|n| count += usize::from(matches!(n.kind, NodeKind::Layer { .. })));
|
||||
assert_eq!(count, 3, "each group is one layer");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thousands_of_layers_hidden_ones_included_all_come_in() {
|
||||
const N: usize = 3000;
|
||||
let first = first_extra(1);
|
||||
let objs: Vec<String> = (0..N).map(|i| ocg(&format!("L{i}"), "")).collect();
|
||||
let refs: Vec<String> = (0..N).map(|i| format!("{} 0 R", first + i)).collect();
|
||||
let props: String = refs.iter().enumerate().map(|(i, r)| format!("/M{i} {r} ")).collect();
|
||||
let content: String = (0..N).map(|i| format!("/OC /M{i} BDC {} {} 1 1 re f EMC ", i % 100, i / 100)).collect();
|
||||
let off: Vec<&str> = refs.iter().step_by(2).map(String::as_str).collect();
|
||||
let catalog = format!("/OCProperties << /OCGs [{}] /D << /OFF [{}] >> >> ", refs.join(" "), off.join(" "));
|
||||
let page = PdfPage { resources: format!("/Properties << {props}>>"), ..PdfPage::new(100.0, 100.0, &content) };
|
||||
let objs: Vec<&str> = objs.iter().map(String::as_str).collect();
|
||||
let d = import(&pdf_with_catalog(&[page], &objs, &catalog, None)).unwrap();
|
||||
assert_eq!(d.layers.len(), N);
|
||||
assert!(d.layers.iter().enumerate().all(|(i, l)| l.visible == (i % 2 == 1) && l.children().is_some_and(|c| c.len() == 1)));
|
||||
}
|
||||
+191
-38
@@ -1,7 +1,8 @@
|
||||
//! Shape Builder (Shift+M), Live Paint Bucket (K) and Live Paint Selection (Shift+L).
|
||||
//!
|
||||
//! The tools only emit commands (`shapeBuilder.merge`, `livePaint.fill`, `livePaint.strokeEdge`,
|
||||
//! `select.*`); the planar arrangement comes from `vectorcraft_pathops::regions`.
|
||||
//! `select.*`); the planar arrangement comes from `vectorcraft_pathops::shape_builder` (Shape
|
||||
//! Builder) and `vectorcraft_pathops::live_paint` (Live Paint).
|
||||
//!
|
||||
//! **Live Paint groups** are ordinary groups (no special node kind): the group's name starts with
|
||||
//! [`LIVE_PAINT_PREFIX`]; its first child is a hidden group named [`SOURCES_NAME`] holding the
|
||||
@@ -151,6 +152,141 @@ pub fn shapes_for<'a>(doc: &'a Document, roots: &[NodeId]) -> (Vec<po::Shape>, V
|
||||
(shapes, used)
|
||||
}
|
||||
|
||||
/// Shape Builder inputs: [`shapes_for`], with the open subpaths of filled paths closed where that
|
||||
/// encloses an area (the fill bounds a region, as if an invisible edge closed it). Unfilled open
|
||||
/// paths and straight lines stay open and cut the regions they cross.
|
||||
fn shape_builder_shapes<'a>(doc: &'a Document, roots: &[NodeId]) -> (Vec<po::Shape>, Vec<&'a Node>) {
|
||||
let (mut shapes, leaves) = shapes_for(doc, roots);
|
||||
for (s, l) in shapes.iter_mut().zip(&leaves) {
|
||||
if l.appearance.fill_paint().is_none() {
|
||||
continue;
|
||||
}
|
||||
for sp in s.path.subpaths.iter_mut().filter(|sp| !sp.closed) {
|
||||
let mut closed = sp.clone();
|
||||
closed.closed = true;
|
||||
let mut bp = BezPath::new();
|
||||
closed.to_bezpath_into(&mut bp);
|
||||
let size = bp.bounding_box().size();
|
||||
sp.closed = bp.area().abs() > 1e-9 * (size.width * size.width + size.height * size.height);
|
||||
}
|
||||
}
|
||||
(shapes, leaves)
|
||||
}
|
||||
|
||||
/// A planar-map face with its outline and bounds, ready for hit tests.
|
||||
pub type Face = (po::Region, BezPath, Rect);
|
||||
|
||||
fn faces_of(regions: Vec<po::Region>) -> Vec<Face> {
|
||||
regions
|
||||
.into_iter()
|
||||
.filter_map(|r| {
|
||||
let bp = r.path.to_bezpath();
|
||||
let b = r.path.bounds()?;
|
||||
Some((r, bp, b))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The Shape Builder's planar map of a selection.
|
||||
#[derive(Default)]
|
||||
pub struct BuilderMap {
|
||||
/// The inputs, back → front (see [`po::shape_builder`]).
|
||||
pub shapes: Vec<po::Shape>,
|
||||
pub regions: Vec<Face>,
|
||||
/// Pieces of the unfilled open paths, keyed by input index, with their bounds.
|
||||
pub lines: Vec<(po::Shape, Rect)>,
|
||||
}
|
||||
|
||||
/// What a Shape Builder gesture touches at a point.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Hit {
|
||||
Region(usize),
|
||||
Line(usize),
|
||||
}
|
||||
|
||||
impl BuilderMap {
|
||||
/// The map of `roots` (sorted back → front), with the leaves the inputs came from.
|
||||
pub fn new<'a>(doc: &'a Document, roots: &[NodeId]) -> (Self, Vec<&'a Node>) {
|
||||
let (shapes, leaves) = shape_builder_shapes(doc, roots);
|
||||
if shapes.is_empty() {
|
||||
return (Self::default(), leaves);
|
||||
}
|
||||
let (regions, lines) = po::shape_builder(&shapes);
|
||||
let lines = lines.into_iter().filter_map(|l| Some((l.path.bounds()?, l))).map(|(b, l)| (l, b)).collect();
|
||||
(Self { shapes, regions: faces_of(regions), lines }, leaves)
|
||||
}
|
||||
|
||||
/// The region containing `p`.
|
||||
pub fn region_at(&self, p: Point) -> Option<usize> {
|
||||
self.regions.iter().position(|(_, bp, b)| b.contains(p) && bp.winding(p) != 0)
|
||||
}
|
||||
|
||||
/// The line piece nearest `p`, within `tol`.
|
||||
pub fn line_near(&self, p: Point, tol: f64) -> Option<usize> {
|
||||
let mut best: Option<(f64, usize)> = None;
|
||||
for (i, (l, b)) in self.lines.iter().enumerate() {
|
||||
if b.inflate(tol, tol).contains(p)
|
||||
&& let Some((.., d)) = l.path.nearest(p)
|
||||
&& d <= tol
|
||||
&& best.is_none_or(|b| d < b.0)
|
||||
{
|
||||
best = Some((d, i));
|
||||
}
|
||||
}
|
||||
best.map(|b| b.1)
|
||||
}
|
||||
|
||||
/// What a gesture at `p` touches: with `line_tol` (erasing), a line piece that close, else the
|
||||
/// region under it.
|
||||
pub fn hit(&self, p: Point, line_tol: Option<f64>) -> Option<Hit> {
|
||||
line_tol.and_then(|t| self.line_near(p, t)).map(Hit::Line).or_else(|| self.region_at(p).map(Hit::Region))
|
||||
}
|
||||
|
||||
/// Does line piece `i` run between two of `regions` (an edge that merging or deleting them
|
||||
/// removes)?
|
||||
pub fn line_between(&self, i: usize, regions: &[usize]) -> bool {
|
||||
let Some(sp) = self.lines.get(i).and_then(|(l, _)| l.path.subpaths.first()) else { return false };
|
||||
let n = sp.segment_count();
|
||||
if n == 0 {
|
||||
return false;
|
||||
}
|
||||
let c = sp.segment(n / 2);
|
||||
use kurbo::{ParamCurve as _, ParamCurveDeriv as _};
|
||||
let (m, d) = (c.eval(0.5), c.deriv().eval(0.5).to_vec2());
|
||||
let len = d.hypot();
|
||||
if !(len.is_finite() && len > 0.0) {
|
||||
return false;
|
||||
}
|
||||
// A little to each side: inside the faces next to it, which share it exactly.
|
||||
let off = d.turn_90() * (0.05f64.min(0.05 * c.p0.distance(c.p3)).max(1e-6) / len);
|
||||
[m + off, m - off].into_iter().all(|q| self.region_at(q).is_some_and(|r| regions.contains(&r)))
|
||||
}
|
||||
}
|
||||
|
||||
/// The regions and line pieces a Shape Builder gesture has touched, in the order touched.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct Touched {
|
||||
pub regions: Vec<usize>,
|
||||
pub lines: Vec<usize>,
|
||||
}
|
||||
|
||||
impl Touched {
|
||||
pub fn add(&mut self, hit: Option<Hit>) {
|
||||
let (list, i) = match hit {
|
||||
Some(Hit::Region(i)) => (&mut self.regions, i),
|
||||
Some(Hit::Line(i)) => (&mut self.lines, i),
|
||||
None => return,
|
||||
};
|
||||
if !list.contains(&i) {
|
||||
list.push(i);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.regions.is_empty() && self.lines.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
/// Selected roots sorted back → front in document order.
|
||||
pub fn sorted_roots(doc: &Document, ids: &[NodeId]) -> Vec<NodeId> {
|
||||
let mut v: Vec<(Vec<usize>, NodeId)> = ids.iter().filter_map(|id| doc.index_path(*id).map(|p| (p, *id))).collect();
|
||||
@@ -238,13 +374,12 @@ pub fn hatch(path: &BezPath, gap: f64) -> BezPath {
|
||||
out
|
||||
}
|
||||
|
||||
/// Regions of the current selection, cached by document identity and selection.
|
||||
/// The planar map of the current selection, cached by document identity and selection.
|
||||
#[derive(Default)]
|
||||
struct RegionCache {
|
||||
key: Option<(usize, Vec<NodeId>)>,
|
||||
regions: Vec<(po::Region, BezPath, Rect)>,
|
||||
/// Live Paint faces (every path an edge, open ones included) rather than Shape Builder
|
||||
/// regions (the filled areas of the shapes).
|
||||
map: BuilderMap,
|
||||
/// Live Paint faces (every path an edge, filled or not) rather than Shape Builder regions.
|
||||
live: bool,
|
||||
}
|
||||
|
||||
@@ -252,58 +387,57 @@ impl RegionCache {
|
||||
fn live_paint() -> Self {
|
||||
Self { live: true, ..Default::default() }
|
||||
}
|
||||
fn get(&mut self, cx: &ToolContext) -> &[(po::Region, BezPath, Rect)] {
|
||||
fn get(&mut self, cx: &ToolContext) -> &BuilderMap {
|
||||
let key = (cx.doc as *const Document as usize, cx.selection.objects.clone());
|
||||
if self.key.as_ref() != Some(&key) {
|
||||
let roots = sorted_roots(cx.doc, &cx.selection.objects);
|
||||
let (shapes, _) = shapes_for(cx.doc, &roots);
|
||||
self.regions = if shapes.is_empty() {
|
||||
vec![]
|
||||
self.map = if self.live {
|
||||
let (shapes, _) = shapes_for(cx.doc, &roots);
|
||||
let regions = if shapes.is_empty() { vec![] } else { faces_of(po::live_paint(&shapes).0) };
|
||||
BuilderMap { regions, ..Default::default() }
|
||||
} else {
|
||||
let regions = if self.live { po::live_paint(&shapes).0 } else { po::regions(&shapes) };
|
||||
regions
|
||||
.into_iter()
|
||||
.filter_map(|r| {
|
||||
let bp = r.path.to_bezpath();
|
||||
let b = r.path.bounds()?;
|
||||
Some((r, bp, b))
|
||||
})
|
||||
.collect()
|
||||
BuilderMap::new(cx.doc, &roots).0
|
||||
};
|
||||
self.key = Some(key);
|
||||
}
|
||||
&self.regions
|
||||
&self.map
|
||||
}
|
||||
fn at(&mut self, cx: &ToolContext, p: Point) -> Option<usize> {
|
||||
self.get(cx).iter().position(|(_, bp, b)| b.contains(p) && bp.winding(p) != 0)
|
||||
self.get(cx).region_at(p)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- Shape Builder ----------
|
||||
|
||||
/// Shape Builder tool: drag across regions to merge them, Alt-drag to delete them.
|
||||
/// Shape Builder tool: drag across regions to merge them, Alt-drag to delete them (and the pieces
|
||||
/// of open paths it passes over).
|
||||
#[derive(Default)]
|
||||
pub struct ShapeBuilderTool {
|
||||
cache: RegionCache,
|
||||
hover: Option<usize>,
|
||||
hover: Option<Hit>,
|
||||
points: Vec<Point>,
|
||||
touched: Vec<usize>,
|
||||
touched: Touched,
|
||||
dragging: bool,
|
||||
alt: bool,
|
||||
}
|
||||
|
||||
/// How close (screen px) the pointer must come to a line piece to delete it.
|
||||
const LINE_TOL_PX: f64 = 4.0;
|
||||
|
||||
impl ShapeBuilderTool {
|
||||
fn line_tol(cx: &ToolContext, alt: bool) -> Option<f64> {
|
||||
alt.then(|| cx.tol(LINE_TOL_PX))
|
||||
}
|
||||
|
||||
fn touch(&mut self, cx: &ToolContext, from: Option<Point>, to: Point) {
|
||||
let pts = match from {
|
||||
Some(a) => sample_polyline(&[a, to], cx.tol(2.0)),
|
||||
None => vec![to],
|
||||
};
|
||||
let tol = Self::line_tol(cx, self.alt);
|
||||
for p in pts {
|
||||
if let Some(i) = self.cache.at(cx, p)
|
||||
&& !self.touched.contains(&i)
|
||||
{
|
||||
self.touched.push(i);
|
||||
}
|
||||
let hit = self.cache.get(cx).hit(p, tol);
|
||||
self.touched.add(hit);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -317,7 +451,7 @@ impl Tool for ShapeBuilderTool {
|
||||
let p = ev.pos;
|
||||
match ev.kind {
|
||||
PointerKind::Move => {
|
||||
self.hover = self.cache.at(cx, p);
|
||||
self.hover = self.cache.get(cx).hit(p, Self::line_tol(cx, ev.mods.alt));
|
||||
vec![]
|
||||
}
|
||||
PointerKind::Down => {
|
||||
@@ -327,7 +461,7 @@ impl Tool for ShapeBuilderTool {
|
||||
self.dragging = true;
|
||||
self.alt = ev.mods.alt;
|
||||
self.points = vec![p];
|
||||
self.touched.clear();
|
||||
self.touched = Touched::default();
|
||||
self.touch(cx, None, p);
|
||||
vec![]
|
||||
}
|
||||
@@ -353,7 +487,12 @@ impl Tool for ShapeBuilderTool {
|
||||
self.cache.key = None;
|
||||
let roots = sorted_roots(cx.doc, &cx.selection.objects);
|
||||
let pts: Vec<Value> = points.iter().map(|q| json!([q.x, q.y])).collect();
|
||||
vec![Action::Exec("shapeBuilder.merge".into(), json!({ "ids": json_ids(&roots), "points": pts, "erase": self.alt || ev.mods.alt }))]
|
||||
let erase = self.alt || ev.mods.alt;
|
||||
let mut params = json!({ "ids": json_ids(&roots), "points": pts, "erase": erase });
|
||||
if let Some(t) = Self::line_tol(cx, erase) {
|
||||
params["tolerance"] = json!(t);
|
||||
}
|
||||
vec![Action::Exec("shapeBuilder.merge".into(), params)]
|
||||
}
|
||||
_ => vec![],
|
||||
}
|
||||
@@ -361,13 +500,26 @@ impl Tool for ShapeBuilderTool {
|
||||
|
||||
fn overlays(&self, cx: &ToolContext) -> Vec<Overlay> {
|
||||
let mut out = vec![];
|
||||
let regions = &self.cache.regions;
|
||||
let map = &self.cache.map;
|
||||
let color = if self.dragging && self.alt { HIGHLIGHT_RED } else { HATCH };
|
||||
let show: Vec<usize> = if self.dragging { self.touched.clone() } else { self.hover.into_iter().collect() };
|
||||
for i in show {
|
||||
if let Some((_, bp, _)) = regions.get(i) {
|
||||
out.push(Overlay::Path { path: hatch(bp, cx.tol(4.0)), color, width: 1.0, dashed: false });
|
||||
out.push(Overlay::Path { path: bp.clone(), color, width: 1.0, dashed: false });
|
||||
let show: Vec<Hit> = if self.dragging {
|
||||
self.touched.regions.iter().map(|&i| Hit::Region(i)).chain(self.touched.lines.iter().map(|&i| Hit::Line(i))).collect()
|
||||
} else {
|
||||
self.hover.into_iter().collect()
|
||||
};
|
||||
for hit in show {
|
||||
match hit {
|
||||
Hit::Region(i) => {
|
||||
if let Some((_, bp, _)) = map.regions.get(i) {
|
||||
out.push(Overlay::Path { path: hatch(bp, cx.tol(4.0)), color, width: 1.0, dashed: false });
|
||||
out.push(Overlay::Path { path: bp.clone(), color, width: 1.0, dashed: false });
|
||||
}
|
||||
}
|
||||
Hit::Line(i) => {
|
||||
if let Some((l, _)) = map.lines.get(i) {
|
||||
out.push(Overlay::Path { path: l.path.to_bezpath(), color: HIGHLIGHT_RED, width: 3.0, dashed: false });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if self.dragging && self.points.len() > 1 {
|
||||
@@ -434,6 +586,7 @@ fn lp_overlays(h: &LpHover, cache: &RegionCache) -> Vec<Overlay> {
|
||||
LpHover::None => vec![],
|
||||
LpHover::Part(bp) => vec![Overlay::Path { path: bp.clone(), color: HIGHLIGHT_RED, width: 4.0, dashed: false }],
|
||||
LpHover::Region(i) => cache
|
||||
.map
|
||||
.regions
|
||||
.get(*i)
|
||||
.map(|(_, bp, _)| vec![Overlay::Path { path: bp.clone(), color: HIGHLIGHT_RED, width: 4.0, dashed: false }])
|
||||
@@ -623,7 +776,7 @@ mod tests {
|
||||
let mut t = ShapeBuilderTool::default();
|
||||
t.pointer(&cx, &ev(PointerKind::Down, 25.0, 50.0));
|
||||
t.pointer(&cx, &ev(PointerKind::Drag, 75.0, 50.0));
|
||||
assert_eq!(t.touched.len(), 2);
|
||||
assert_eq!(t.touched.regions.len(), 2);
|
||||
assert!(t.busy());
|
||||
let acts = t.pointer(&cx, &ev(PointerKind::Up, 75.0, 50.0));
|
||||
let Action::Exec(id, v) = &acts[0] else { panic!("{acts:?}") };
|
||||
|
||||
+6
-3
@@ -373,9 +373,12 @@ their stop opacity and stop where the shading doesn't extend. Text becomes point
|
||||
the file's font (by name; fonts that aren't available are listed in `warnings` and show in the fallback font, and
|
||||
every export that draws that type — PDF, EPS, EMF/WMF, raster images, SVG with outlined or embedded fonts — says in
|
||||
its `warnings` that it wrote the fallback font) — `textAs: "outlines"` keeps the glyph outlines the file draws instead
|
||||
(its embedded fonts, installed or not). Optional content groups (the layers of PDF and PDF-compatible `.ai`
|
||||
files) become layers with their name, visibility, print state and lock, art that is off coming in as a hidden layer;
|
||||
art outside them goes to a layer per page (except the opaque white page a `.ai` paints under its layers, which isn't art). `layers: false` gives one layer per page of only what shows:
|
||||
(its embedded fonts, installed or not). Strokes stay live strokes (width, cap, join, miter limit, dash and paint), and
|
||||
an object written as a fill and then a stroke of the same outline is one path with both. Optional content groups (the
|
||||
layers of PDF and PDF-compatible `.ai` files) become layers with their name, visibility (the default configuration's,
|
||||
or a view state that is off), print state and lock, nested as sublayers the way the file's layer order nests them; art
|
||||
that is off comes in as a hidden layer. Art outside them goes to a layer per page (except the opaque white page a `.ai`
|
||||
paints under its layers, which isn't art). `layers: false` gives one layer per page of only what shows:
|
||||
|
||||
```json
|
||||
{"name":"run_command","arguments":{"command":"document.open","params":{"path":"/tmp/map.pdf","textAs":"outlines","layers":false}}}
|
||||
|
||||
Reference in new issue
Block a user