From bb56fd7d23fdcd16501a5aca80c6d9ce1a100b6e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 10:30:36 -0800 Subject: [PATCH 01/10] Fill Area: a click adds a path of the enclosed area and keeps the paths around it A new Fill Area tool in the Live Paint Bucket's group adds a closed path of the area under a click, with the current fill, stroke and stroke weight. The paths that bound the area are not changed, and nothing needs to be selected: visible, unlocked paths on every layer bound areas, open paths and the overlap of filled shapes included. The area under the pointer is outlined in red while the pointer is over it, and a click outside every area does nothing and records no undo step. The path appears on the press and is kept on the release; Escape or a canceled touch before the release takes it back. The new path goes directly above the front-most object along the area. When a group, Live Paint group or clipping group holds that object, the path goes above the outermost group in its layer, not inside it. The tool sends the new shapeBuilder.copyRegion command (point, ids, gap, openFilledAsClosed, fill, stroke). It uses the Shape Builder's Gap Detection and Consider Open Filled Paths as Closed, and a double-click opens the Shape Builder Tool Options. The area search maps the paths near the point first and widens the window a few times before it maps every path. When a window's paths have more segments than one Shape Builder map takes, the paths with the most segments are left out, and an area is taken only when none of them reaches it. When all the paths together have more segments than that, only an area the nearby paths enclose is found. In a document of more than 128 segments the hover search runs on another thread, and the outline of an area goes when the document changes under a still pointer. Docs: docs/mcp.md, docs/target-app-parity.md, cursors.toml and the regenerated UI command catalog. Catalog rows for the tool, its undo step and its message. --- ASSETS.md | 1 + assets/icons/dc-fill-area.svg | 1 + crates/engine/src/cmd/buildcmds.rs | 20 +- .../engine/src/cmd/buildcmds/shape_builder.rs | 43 +- crates/engine/src/cmd/plugin_call/reviewed.rs | 1 + crates/engine/src/tests.rs | 1 + crates/engine/src/tests/fill_area.rs | 571 ++++++++++++++++++ crates/mcp/src/ui_catalog.rs | 2 +- crates/tools/src/builder.rs | 22 +- crates/tools/src/builder/fill_area.rs | 523 ++++++++++++++++ crates/tools/src/catalog.rs | 1 + crates/tools/src/cursors.toml | 2 + crates/tools/src/settings.rs | 2 + .../src/dialogs/shape_builder_options.rs | 16 + crates/ui-egui/src/i18n/bg.tsv | 3 + crates/ui-egui/src/i18n/bs.tsv | 3 + crates/ui-egui/src/i18n/ca.tsv | 3 + crates/ui-egui/src/i18n/cs.tsv | 3 + crates/ui-egui/src/i18n/da.tsv | 3 + crates/ui-egui/src/i18n/de.tsv | 3 + crates/ui-egui/src/i18n/el.tsv | 3 + crates/ui-egui/src/i18n/es.tsv | 3 + crates/ui-egui/src/i18n/fi.tsv | 3 + crates/ui-egui/src/i18n/fr.tsv | 3 + crates/ui-egui/src/i18n/gu.tsv | 2 + crates/ui-egui/src/i18n/hi.tsv | 3 + crates/ui-egui/src/i18n/hu.tsv | 3 + crates/ui-egui/src/i18n/id.tsv | 3 + crates/ui-egui/src/i18n/it.tsv | 3 + crates/ui-egui/src/i18n/ja.tsv | 3 + crates/ui-egui/src/i18n/ka.tsv | 3 + crates/ui-egui/src/i18n/ko.tsv | 3 + crates/ui-egui/src/i18n/nl.tsv | 3 + crates/ui-egui/src/i18n/pl.tsv | 3 + crates/ui-egui/src/i18n/pt-br.tsv | 3 + crates/ui-egui/src/i18n/ru.tsv | 3 + crates/ui-egui/src/i18n/sv.tsv | 3 + crates/ui-egui/src/i18n/tr.tsv | 3 + crates/ui-egui/src/i18n/uk.tsv | 3 + crates/ui-egui/src/i18n/vi.tsv | 3 + crates/ui-egui/src/i18n/zh-hans.tsv | 3 + crates/ui-egui/src/i18n/zh-hant.tsv | 3 + crates/ui-egui/src/icon_data.rs | 1 + crates/ui-egui/src/icons.rs | 1 + crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/toolbar.rs | 5 +- docs/mcp.md | 27 +- docs/target-app-parity.md | 1 + 48 files changed, 1308 insertions(+), 18 deletions(-) create mode 100644 assets/icons/dc-fill-area.svg create mode 100644 crates/engine/src/tests/fill_area.rs create mode 100644 crates/tools/src/builder/fill_area.rs diff --git a/ASSETS.md b/ASSETS.md index dbdd8b84d8..768dab55e0 100644 --- a/ASSETS.md +++ b/ASSETS.md @@ -152,6 +152,7 @@ Generated-in-code art is original and has no file to list. This covers the defau | `assets/icons/dc-draw-inside.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-draw-normal.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-ellipse.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-fill-area.svg` | VectorCraft contributors | Original work, drawn for VectorCraft: three crossing lines with the triangle they enclose filled | MIT OR Apache-2.0 | | | `assets/icons/dc-fill-none.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-filter.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-flare.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | diff --git a/assets/icons/dc-fill-area.svg b/assets/icons/dc-fill-area.svg new file mode 100644 index 0000000000..50631a7750 --- /dev/null +++ b/assets/icons/dc-fill-area.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs index a605652612..3e5de3f95a 100644 --- a/crates/engine/src/cmd/buildcmds.rs +++ b/crates/engine/src/cmd/buildcmds.rs @@ -39,7 +39,7 @@ mod trace; pub use live_paint::live_paint_gaps; use live_paint::{lp_expand, lp_fill, lp_gap_options, lp_info, lp_make, lp_merge, lp_release, lp_stroke_edge}; -use shape_builder::{sb_merge, sb_regions}; +use shape_builder::{sb_copy_region, sb_merge, sb_regions}; pub(crate) use trace::TracePresetChanges; pub use trace::{TracePreset, TracePresetChange, TraceRun, Traced}; use trace::{trace_expand, trace_make, trace_presets_delete, trace_presets_save, trace_release, trace_set_view}; @@ -67,6 +67,15 @@ pub fn specs() -> Vec { has_selection_or_ids, sb_regions ), + cmd!( + "shapeBuilder.copyRegion", + "Fill Area", + [], + None, + "{point: [x,y], ids?|id?: [id…] (the objects or layers whose paths bound areas; default: every layer, nothing needs to be selected), gap?: pt (0–72; 0: Gap Detection off; out of range is an error), openFilledAsClosed?: true (as shapeBuilder.merge), fill?, stroke?: \"#rrggbb\" | {color|swatch|gradient|none} (default: the current fill and stroke, with the current stroke weight)} add a new closed path of the area under point that the visible, unlocked paths enclose (the region of shapeBuilder.regions holding it: areas a shape already fills and areas open paths bound count too), directly above the front-most object along the area (its outline touches the area's outline, or it covers the area; when a group, Live Paint group, Shaper group or clipping group holds that path, above the outermost group in its layer, never inside it), and select it; the paths around the area are not changed; a point in no enclosed area is an error and changes nothing (no undo step); when the paths together have more than 65,536 segments, only an area the paths near the point enclose is found → {id, above (the object the new path went above)}", + has_doc, + sb_copy_region + ), cmd!( "livePaint.make", "Make", @@ -262,12 +271,17 @@ fn stroke_only(paint: Paint, width: f64) -> Appearance { // ---------- Shape Builder ---------- fn fill_param(s: &Session, p: &Value, cmd: &str) -> Result> { - match p.get("fill") { + paint_param(s, p, "fill", cmd) +} + +/// The paint `p` gives for `key` (`"#rrggbb"` or `{color|swatch|gradient|none}`), as `fill` is read. +fn paint_param(s: &Session, p: &Value, key: &str, cmd: &str) -> Result> { + match p.get(key) { None | Some(Value::Null) => Ok(None), Some(v @ Value::Object(o)) if o.contains_key("color") || o.contains_key("swatch") || o.contains_key("gradient") || o.contains_key("none") => { paint_from(s, v) } - Some(v) => color_value(v).map(|c| Some(Paint::solid(super::paint::new_color(s, p, c)))).ok_or_else(|| bad(cmd, format!("bad fill {v}"))), + Some(v) => color_value(v).map(|c| Some(Paint::solid(super::paint::new_color(s, p, c)))).ok_or_else(|| bad(cmd, format!("bad {key} {v}"))), } } diff --git a/crates/engine/src/cmd/buildcmds/shape_builder.rs b/crates/engine/src/cmd/buildcmds/shape_builder.rs index 472ba2208b..a24d04bcda 100644 --- a/crates/engine/src/cmd/buildcmds/shape_builder.rs +++ b/crates/engine/src/cmd/buildcmds/shape_builder.rs @@ -1,7 +1,7 @@ use super::{ Arc, Beside, BuilderMap, EngineError, FillRule, Node, NodeId, PathData, Point, Rect, Result, Session, Touched, Value, b, bad, check_numbers, - f64_or, fill_param, finite, gap_param, ids_json, json, marquee_param, po, points_param, remnant, replace_leaves, replace_with_pieces, root_ids, - shape_node, switch_or, + f64_or, fill_param, finite, gap_param, ids_json, json, marquee_param, named_ids, number_or, outermost, paint_param, po, point_param, + points_param, remnant, replace_leaves, replace_with_pieces, root_ids, shape_node, switch_or, }; pub(super) fn sb_merge(s: &mut Session, p: &Value) -> Result { @@ -183,6 +183,45 @@ pub(super) fn sb_merge(s: &mut Session, p: &Value) -> Result { Ok(out) } +pub(super) fn sb_copy_region(s: &mut Session, p: &Value) -> Result { + const C: &str = "shapeBuilder.copyRegion"; + let pt = point_param(p, "point").filter(|q| finite(*q)).ok_or_else(|| bad(C, "missing point [x,y]"))?; + let open_filled_as_closed = switch_or(p, "openFilledAsClosed", true, C)?; + let gap = number_or(p, "gap", 0.0, C)?; + if !(0.0..=po::SHAPE_BUILDER_MAX_GAP).contains(&gap) { + return Err(bad(C, format!("gap must be 0 to {} pt, not {gap}", po::SHAPE_BUILDER_MAX_GAP))); + } + let fill = paint_param(s, p, "fill", C)?.unwrap_or_else(|| s.paint.fill.clone()); + let stroke = paint_param(s, p, "stroke", C)?.unwrap_or_else(|| s.paint.stroke.clone()); + let look = s.new_art_look(fill, stroke, s.paint.stroke_width); + let area = { + let d = &s.doc()?.doc; + let roots = match named_ids(p)? { + Some(ids) => { + if let Some(bad_id) = ids.iter().find(|i| d.node(**i).is_none()) { + return Err(EngineError::NoNode(*bad_id)); + } + // An object listed with a layer or group that holds it counts once. + outermost(d, ids) + } + None => b::every_layer(d), + }; + b::AreaFinder::new(d, &roots, gap, open_filled_as_closed).find(pt) + }; + let Some(area) = area else { return Err(EngineError::Other("Fill Area: no enclosed area under the pointer".into())) }; + let id = s.edit("Fill Area", |d, sel| { + let mut n = shape_node(d, area.path.clone(), None); + look.apply(d, &mut n); + let id = n.id; + let mut above = Beside::above(d, &[area.above]); + above.put(d, area.above, vec![n])?; + above.finish(d)?; + sel.set([id]); + Ok(id) + })?; + Ok(json!({ "id": id.0, "above": area.above.0 })) +} + pub(super) fn sb_regions(s: &mut Session, p: &Value) -> Result { let open_filled_as_closed = switch_or(p, "openFilledAsClosed", true, "shapeBuilder.regions")?; check_numbers(p, &["gap"], "shapeBuilder.regions")?; diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index f445237d83..4c1ee6fab9 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -554,6 +554,7 @@ pub(super) const ALLOWED: &[&str] = &[ "shape.rectangularGrid", "shape.spiral", "shape.star", + "shapeBuilder.copyRegion", "shapeBuilder.merge", "shapeBuilder.regions", "shaper.expand", diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 1b420d7805..fd3ee09415 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -64,6 +64,7 @@ mod expand_symbols; mod eyedropper; mod file; mod fileinfo; +mod fill_area; mod flatpresets; mod flatpreview; mod flatten; diff --git a/crates/engine/src/tests/fill_area.rs b/crates/engine/src/tests/fill_area.rs new file mode 100644 index 0000000000..98c5dc34db --- /dev/null +++ b/crates/engine/src/tests/fill_area.rs @@ -0,0 +1,571 @@ +//! Tests for Fill Area (`shapeBuilder.copyRegion` and the `fillArea` tool). + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::Node; +use vectorcraft_geom::{FillRule, PathData, Point}; +use vectorcraft_tools::{Cursor, Mods, Overlay, PointerEvent, PointerKind}; + +use crate::*; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + s +} + +fn id_of(v: &Value) -> NodeId { + NodeId(v["id"].as_u64().unwrap()) +} + +fn node(s: &Session, id: NodeId) -> Node { + s.doc().unwrap().doc.node(id).cloned().unwrap() +} + +fn outline(s: &Session, id: NodeId) -> (PathData, FillRule) { + vectorcraft_tools::builder::node_outline(&node(s, id)).expect("path") +} + +fn area(s: &Session, id: NodeId) -> f64 { + let (p, r) = outline(s, id); + vectorcraft_pathops::area(&p, r) +} + +fn line(s: &mut Session, a: (f64, f64), b: (f64, f64)) -> NodeId { + id_of(&s.execute("shape.line", &json!({"x1": a.0, "y1": a.1, "x2": b.0, "y2": b.1})).unwrap()) +} + +fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId { + id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()) +} + +/// Two diagonals and a crossbar: they enclose a triangle of 900 pt² above the crossbar. +fn triangle(s: &mut Session) -> [NodeId; 3] { + [line(s, (0.0, 0.0), (100.0, 100.0)), line(s, (100.0, 0.0), (0.0, 100.0)), line(s, (-10.0, 80.0), (110.0, 80.0))] +} + +/// The ids of the default layer's children, back to front. +fn stack(s: &Session) -> Vec { + let d = &s.doc().unwrap().doc; + d.children(d.default_layer()).map(|c| c.iter().map(|n| n.id).collect()).unwrap_or_default() +} + +fn undo_len(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn deselect(s: &mut Session) { + s.execute("select.set", &json!({"ids": []})).unwrap(); +} + +/// Four circles in a 2×2 grid, each touching its neighbors, enclose a diamond nothing fills. With +/// nothing selected, a click in it adds the diamond and leaves the circles as they were. +#[test] +fn fill_area_adds_the_diamond_four_circles_enclose_and_keeps_them() { + let mut s = session(); + let mut circles = vec![]; + for (x, y) in [(0.0, 0.0), (100.0, 0.0), (0.0, 100.0), (100.0, 100.0)] { + circles.push(id_of(&s.execute("shape.ellipse", &json!({"x": x, "y": y, "width": 100, "height": 100})).unwrap())); + } + deselect(&mut s); + let before: Vec<_> = circles.iter().map(|c| outline(&s, *c)).collect(); + let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [100, 100]})).unwrap(); + let new = id_of(&r); + assert!((area(&s, new) - 2146.0).abs() < 10.0, "{}", area(&s, new)); + assert_eq!(stack(&s).len(), 5, "the four circles and the diamond"); + let after: Vec<_> = circles.iter().map(|c| outline(&s, *c)).collect(); + assert_eq!(after, before, "the circles keep their geometry"); + assert_eq!(s.doc().unwrap().selection.objects, vec![new], "the new path is selected"); +} + +/// The overlap of two filled squares is an area too: the new path covers it, and both squares stay +/// whole (a Shape Builder merge there cuts it out of them). +#[test] +fn fill_area_copies_the_overlap_of_two_filled_squares() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let b = rect(&mut s, 50.0, 0.0, 100.0, 100.0); + deselect(&mut s); + let (oa, ob) = (outline(&s, a), outline(&s, b)); + let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [75, 50]})).unwrap(); + let new = id_of(&r); + assert!((area(&s, new) - 5000.0).abs() < 1.0, "{}", area(&s, new)); + assert_eq!((outline(&s, a), outline(&s, b)), (oa, ob)); + assert_eq!(stack(&s), vec![a, b, new], "above the front-most square"); + assert_eq!(r["above"], json!(b.0)); +} + +/// Three lines bound a triangle; the new path has the current fill and stroke. +#[test] +fn fill_area_fills_the_triangle_three_lines_bound_with_the_current_paint() { + let mut s = session(); + let lines = triangle(&mut s); + deselect(&mut s); + s.execute("paint.setFill", &json!({"color": "#336699"})).unwrap(); + s.execute("paint.setStroke", &json!({"color": "#993300"})).unwrap(); + let (fill, stroke) = (s.paint.fill.clone(), s.paint.stroke.clone()); + let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 70]})).unwrap(); + let new = id_of(&r); + assert!((area(&s, new) - 900.0).abs() < 1e-6, "{}", area(&s, new)); + let n = node(&s, new); + assert_eq!(n.appearance.fill_paint(), fill); + assert_eq!(n.appearance.stroke_paint(), stroke); + assert_eq!(stack(&s), vec![lines[0], lines[1], lines[2], new]); + // `fill` and `stroke` override the current paint. + let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 70], "fill": "#00ff00", "stroke": {"none": true}})).unwrap(); + let n = node(&s, id_of(&r)); + assert_eq!(n.appearance.fill_paint(), Paint::solid(Color::rgb(0.0, 1.0, 0.0))); + assert_eq!(n.appearance.stroke_paint(), Paint::None); +} + +/// The new path takes the current stroke weight. +#[test] +fn fill_area_takes_the_current_stroke_weight() { + let mut s = session(); + triangle(&mut s); + deselect(&mut s); + s.execute("paint.setStroke", &json!({"color": "#993300"})).unwrap(); + s.paint.stroke_width = 4.0; + let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 70]})).unwrap(); + assert_eq!(node(&s, id_of(&r)).appearance.stroke_width(), 4.0); +} + +/// `ids` names the objects or layers whose paths bound areas: without the crossbar the triangle is +/// open, and naming the layer takes every path in it. +#[test] +fn fill_area_ids_limit_the_paths_that_bound_areas() { + let mut s = session(); + let lines = triangle(&mut s); + deselect(&mut s); + let two = json!({"point": [50, 70], "ids": [lines[0].0, lines[1].0]}); + assert!(s.execute("shapeBuilder.copyRegion", &two).is_err()); + let all = json!({"point": [50, 70], "ids": [lines[0].0, lines[1].0, lines[2].0]}); + let r = s.execute("shapeBuilder.copyRegion", &all).unwrap(); + assert!((area(&s, id_of(&r)) - 900.0).abs() < 1e-6); + let layer = s.doc().unwrap().doc.default_layer().unwrap(); + let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 70], "ids": [layer.0]})).unwrap(); + assert!((area(&s, id_of(&r)) - 900.0).abs() < 1e-6); +} + +/// The new path goes above the group, Live Paint group or clipping group that holds the paths +/// along the area, never inside it, and the group keeps its members. +#[test] +fn fill_area_stacks_above_the_group_that_holds_the_paths() { + let mut s = session(); + let lines = triangle(&mut s); + let ids: Vec = lines.iter().map(|l| l.0).collect(); + s.execute("select.set", &json!({"ids": ids})).unwrap(); + let g = id_of(&s.execute("object.group", &json!({})).unwrap()); + deselect(&mut s); + let members = |s: &Session, g: NodeId| -> Vec { node(s, g).children().unwrap().iter().map(|n| n.id).collect() }; + let before = members(&s, g); + let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 70]})).unwrap(); + assert_eq!(stack(&s), vec![g, id_of(&r)]); + assert_eq!(r["above"], json!(g.0)); + assert_eq!(members(&s, g), before); + + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let b = rect(&mut s, 50.0, 0.0, 100.0, 100.0); + let lp = id_of(&s.execute("livePaint.make", &json!({"ids": [a.0, b.0]})).unwrap()); + deselect(&mut s); + let before = members(&s, lp); + let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [75, 50]})).unwrap(); + assert!((area(&s, id_of(&r)) - 5000.0).abs() < 1.0, "{}", area(&s, id_of(&r))); + assert_eq!(stack(&s), vec![lp, id_of(&r)]); + assert_eq!(members(&s, lp), before); + + let mut s = session(); + let lines = triangle(&mut s); + let mask = rect(&mut s, -20.0, -20.0, 140.0, 140.0); + let ids: Vec = lines.iter().map(|l| l.0).chain([mask.0]).collect(); + s.execute("select.set", &json!({"ids": ids})).unwrap(); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + let clip = s.doc().unwrap().selection.objects[0]; + deselect(&mut s); + let before = members(&s, clip); + let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 70]})).unwrap(); + assert_eq!(stack(&s), vec![clip, id_of(&r)]); + assert_eq!(members(&s, clip), before); +} + +/// The new path goes directly above the front-most object along the area, not above art that +/// lies elsewhere, and paths on other layers bound areas too. +#[test] +fn fill_area_takes_paths_on_every_layer_and_stacks_above_the_area() { + let mut s = session(); + let first = s.doc().unwrap().doc.default_layer(); + 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 far = rect(&mut s, 400.0, 400.0, 50.0, 50.0); + let other = id_of(&s.execute("layer.new", &json!({"name": "Other"})).unwrap()); + let l3 = line(&mut s, (-10.0, 80.0), (110.0, 80.0)); + let top = rect(&mut s, 500.0, 400.0, 50.0, 50.0); + deselect(&mut s); + let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 70]})).unwrap(); + let new = id_of(&r); + let d = &s.doc().unwrap().doc; + assert_eq!(d.parent_of(new), Some(other)); + let kids: Vec = d.children(Some(other)).unwrap().iter().map(|n| n.id).collect(); + assert_eq!(kids, vec![l3, new, top]); + let kids: Vec = d.children(first).unwrap().iter().map(|n| n.id).collect(); + assert_eq!(kids, vec![l1, l2, far]); +} + +/// An area far larger than the paths near the point: four long lines bound a 400 pt square whose +/// middle no path's bounds hold, and a small triangle inside it is a hole in the area. +#[test] +fn fill_area_finds_an_area_that_reaches_far_from_the_point() { + let mut s = session(); + line(&mut s, (-20.0, 0.0), (420.0, 0.0)); + line(&mut s, (-20.0, 400.0), (420.0, 400.0)); + line(&mut s, (0.0, -20.0), (0.0, 420.0)); + line(&mut s, (400.0, -20.0), (400.0, 420.0)); + let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [200, 200]})).unwrap(); + assert!((area(&s, id_of(&r)) - 160_000.0).abs() < 1.0, "{}", area(&s, id_of(&r))); + for (a, b) in [((150.0, 250.0), (250.0, 350.0)), ((250.0, 250.0), (150.0, 350.0)), ((140.0, 330.0), (260.0, 330.0))] { + line(&mut s, a, b); + } + deselect(&mut s); + let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 50]})).unwrap(); + assert!((area(&s, id_of(&r)) - (160_000.0 - 900.0)).abs() < 1.0, "the square less the triangle: {}", area(&s, id_of(&r))); +} + +/// Distant art with more segments than one Shape Builder map takes does not stop four lines from +/// bounding the square between them: the search maps the lines near the point first, and a window +/// that reaches the distant art leaves it out. +#[test] +fn fill_area_finds_a_nearby_area_beside_a_huge_distant_path() { + for (at, huge_x) in [(0.0, 20_000.0), (100.0, 1_300.0)] { + let mut s = session(); + let (lo, hi) = (at, at + 800.0); + line(&mut s, (lo - 20.0, lo), (hi + 20.0, lo)); + line(&mut s, (lo - 20.0, hi), (hi + 20.0, hi)); + line(&mut s, (lo, lo - 20.0), (lo, hi + 20.0)); + line(&mut s, (hi, lo - 20.0), (hi, hi + 20.0)); + let n = vectorcraft_pathops::SHAPE_BUILDER_MAX_SEGMENTS; + let pts: Vec = (0..=n).map(|k| Point::new(huge_x + 400.0 * k as f64 / n as f64, 500.0 + (k % 2) as f64)).collect(); + let look = vectorcraft_doc::Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0); + s.edit("t", |d, _| { + let id = d.alloc_id(); + let top = d.children(d.default_layer()).map_or(0, |c| c.len()); + d.insert(d.default_layer(), top, Node::path(id, PathData::single(vectorcraft_geom::SubPath::polyline(&pts, false)), look))?; + Ok(id) + }) + .unwrap(); + deselect(&mut s); + let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [at + 400.0, at + 400.0]})).unwrap(); + assert!((area(&s, id_of(&r)) - 640_000.0).abs() < 1.0, "{huge_x}: {}", area(&s, id_of(&r))); + } +} + +/// A path with too many segments near a long, flat area stays out of the map, and the area's far +/// ends still bound it. +#[test] +fn fill_area_finds_a_long_area_beside_a_huge_path() { + let mut s = session(); + line(&mut s, (-10.0, -20.0), (810.0, -20.0)); + line(&mut s, (-10.0, 20.0), (810.0, 20.0)); + line(&mut s, (0.0, -30.0), (0.0, 30.0)); + line(&mut s, (800.0, -30.0), (800.0, 30.0)); + line(&mut s, (-10.0, 0.0), (810.0, 0.0)); + let n = vectorcraft_pathops::SHAPE_BUILDER_MAX_SEGMENTS; + let pts: Vec = (0..=n).map(|k| Point::new(300.0 + 200.0 * k as f64 / n as f64, 60.0 + (k % 2) as f64 * 0.5)).collect(); + let look = vectorcraft_doc::Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0); + s.edit("t", |d, _| { + let id = d.alloc_id(); + let top = d.children(d.default_layer()).map_or(0, |c| c.len()); + d.insert(d.default_layer(), top, Node::path(id, PathData::single(vectorcraft_geom::SubPath::polyline(&pts, false)), look))?; + Ok(id) + }) + .unwrap(); + deselect(&mut s); + let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [400, 0.5]})).unwrap(); + assert!((area(&s, id_of(&r)) - 16_000.0).abs() < 1.0, "{}", area(&s, id_of(&r))); +} + +/// A path with too many segments that crosses the area cannot be left out, and the paths together +/// are past the segment limit: the square it cuts is not filled across it, whether four lines or one +/// filled rectangle bound the square. +#[test] +fn fill_area_does_not_fill_across_a_huge_path_it_left_out() { + for closed in [false, true] { + let mut s = session(); + if closed { + rect(&mut s, 0.0, 0.0, 400.0, 400.0); + } else { + line(&mut s, (-20.0, 0.0), (420.0, 0.0)); + line(&mut s, (-20.0, 400.0), (420.0, 400.0)); + line(&mut s, (0.0, -20.0), (0.0, 420.0)); + line(&mut s, (400.0, -20.0), (400.0, 420.0)); + } + let n = vectorcraft_pathops::SHAPE_BUILDER_MAX_SEGMENTS; + let pts: Vec = (0..=n).map(|k| Point::new(-20.0 + 440.0 * k as f64 / n as f64, 300.0)).collect(); + let look = vectorcraft_doc::Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0); + s.edit("t", |d, _| { + let id = d.alloc_id(); + let top = d.children(d.default_layer()).map_or(0, |c| c.len()); + d.insert(d.default_layer(), top, Node::path(id, PathData::single(vectorcraft_geom::SubPath::polyline(&pts, false)), look))?; + Ok(id) + }) + .unwrap(); + deselect(&mut s); + let (undo, kids) = (undo_len(&s), stack(&s)); + assert!(s.execute("shapeBuilder.copyRegion", &json!({"point": [200, 100]})).is_err(), "closed: {closed}"); + assert_eq!((undo_len(&s), stack(&s)), (undo, kids)); + } +} + +/// With Gap Detection on, a square on a higher layer within the gap of the area's corners does not +/// bound the area, so the new path stays above the square that does. +#[test] +fn fill_area_gap_does_not_stack_above_a_nearby_path() { + let mut s = session(); + let first = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let layer = s.doc().unwrap().doc.default_layer(); + let other = id_of(&s.execute("layer.new", &json!({"name": "Other"})).unwrap()); + rect(&mut s, 102.0, 0.0, 100.0, 100.0); + deselect(&mut s); + let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 50], "gap": 3})).unwrap(); + let d = &s.doc().unwrap().doc; + assert_eq!(d.parent_of(id_of(&r)), layer); + assert_ne!(d.parent_of(id_of(&r)), Some(other)); + assert_eq!(r["above"], json!(first.0)); +} + +/// An object listed in `ids` with the layer that holds it counts once, so the new path still goes +/// above the front-most of two overlapping squares. +#[test] +fn fill_area_ids_count_an_object_and_its_layer_once() { + let mut s = session(); + let back = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let front = rect(&mut s, 50.0, 0.0, 100.0, 100.0); + deselect(&mut s); + let layer = s.doc().unwrap().doc.default_layer().unwrap(); + let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [75, 50], "ids": [layer.0, back.0]})).unwrap(); + assert_eq!(stack(&s), vec![back, front, id_of(&r)]); +} + +/// A flat window that reaches a path with too many segments leaves that path out and grows to the +/// paths it had not picked: a crossbar that no path near the point leads to still splits the area. +#[test] +fn fill_area_keeps_paths_a_capped_window_had_not_picked() { + let mut s = session(); + // Four lines bound a box; a line through the point and a crossbar higher up cut it. + line(&mut s, (50.0, -60.0), (50.0, 410.0)); + line(&mut s, (350.0, -60.0), (350.0, 410.0)); + line(&mut s, (40.0, -50.0), (360.0, -50.0)); + line(&mut s, (40.0, 400.0), (360.0, 400.0)); + line(&mut s, (0.0, 100.0), (400.0, 100.0)); + line(&mut s, (40.0, 30.0), (360.0, 30.0)); + let n = vectorcraft_pathops::SHAPE_BUILDER_MAX_SEGMENTS; + let pts: Vec = (0..=n).map(|k| Point::new(380.0 + 20.0 * k as f64 / n as f64, 100.0 + (k % 2) as f64 * 0.5)).collect(); + let look = vectorcraft_doc::Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0); + s.edit("t", |d, _| { + let id = d.alloc_id(); + let top = d.children(d.default_layer()).map_or(0, |c| c.len()); + d.insert(d.default_layer(), top, Node::path(id, PathData::single(vectorcraft_geom::SubPath::polyline(&pts, false)), look))?; + Ok(id) + }) + .unwrap(); + deselect(&mut s); + let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [200, 99.5]})).unwrap(); + assert!((area(&s, id_of(&r)) - 21_000.0).abs() < 1.0, "between the crossbar and the line: {}", area(&s, id_of(&r))); +} + +/// Two diagonals and a crossbar about 3 pt short of each: the area closes only with a gap of 3 pt +/// or more, and a gap out of 0 to 72 pt is an error. +#[test] +fn fill_area_gap_closes_small_gaps() { + let mut s = session(); + line(&mut s, (0.0, 0.0), (100.0, 100.0)); + line(&mut s, (100.0, 0.0), (0.0, 100.0)); + line(&mut s, (24.0, 80.0), (76.0, 80.0)); + deselect(&mut s); + assert!(s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 70]})).is_err()); + assert!(s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 70], "gap": 2})).is_err()); + let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 70], "gap": 3})).unwrap(); + let a = area(&s, id_of(&r)); + assert!(a > 850.0 && a < 900.0, "the triangle and its two bridges: {a}"); + for gap in [json!(-1), json!(73), json!("3")] { + assert!(s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 70], "gap": gap})).is_err(), "{gap}"); + } +} + +/// Locked and hidden paths do not bound an area: the triangle fills while its crossbar is unlocked +/// and visible, and not once the crossbar is locked or hidden. +#[test] +fn fill_area_skips_locked_and_hidden_paths() { + for how in ["object.lock", "object.hide"] { + let mut s = session(); + let lines = triangle(&mut s); + deselect(&mut s); + let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 70]})).unwrap(); + assert!((area(&s, id_of(&r)) - 900.0).abs() < 1e-6, "{how}"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute(how, &json!({"ids": [lines[2].0]})).unwrap(); + deselect(&mut s); + let (undo, kids) = (undo_len(&s), stack(&s)); + assert!(s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 70]})).is_err(), "{how}"); + assert_eq!((undo_len(&s), stack(&s)), (undo, kids), "{how}"); + } +} + +/// A point in no enclosed area changes nothing and records no undo step; bad params are errors. A +/// point inside the triangle fills it. +#[test] +fn fill_area_outside_every_area_changes_nothing() { + let mut s = session(); + triangle(&mut s); + deselect(&mut s); + assert!(s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 70]})).is_ok()); + s.execute("edit.undo", &json!({})).unwrap(); + let (undo, kids) = (undo_len(&s), stack(&s)); + for p in [json!({"point": [500, 500]}), json!({"point": [50, 90]}), json!({"point": [-500, -500]})] { + assert!(s.execute("shapeBuilder.copyRegion", &p).is_err(), "{p}"); + } + for p in [json!({}), json!({"point": [50]}), json!({"point": [50, 70], "fill": "nope"}), json!({"point": [50, 70], "stroke": 3})] { + assert!(s.execute("shapeBuilder.copyRegion", &p).is_err(), "{p}"); + } + assert!(s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 70], "ids": [999_999]})).is_err()); + assert_eq!((undo_len(&s), stack(&s)), (undo, kids)); +} + +/// The tool outlines the area under the pointer, shows the bucket over it, and a click adds the +/// path; a click outside every area records nothing. It uses the Shape Builder's Gap Detection. +#[test] +fn fill_area_tool_drives_the_command() { + let mut s = session(); + line(&mut s, (0.0, 0.0), (100.0, 100.0)); + line(&mut s, (100.0, 0.0), (0.0, 100.0)); + line(&mut s, (24.0, 80.0), (76.0, 80.0)); + deselect(&mut s); + let v = ViewInfo::default(); + s.select_tool("fillArea", v).unwrap(); + assert_eq!(s.tool_id(), "fillArea"); + s.pointer(&PointerEvent::new(PointerKind::Move, 50.0, 70.0), v).unwrap(); + assert!(s.overlays(v).is_empty(), "the gap leaves the triangle open"); + assert_eq!(s.cursor(Point::new(50.0, 70.0), Mods::default(), v), Cursor::LivePaintBucket); + let (undo, kids) = (undo_len(&s), stack(&s)); + s.pointer(&PointerEvent::new(PointerKind::Down, 50.0, 70.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 50.0, 70.0), v).unwrap(); + assert_eq!((undo_len(&s), stack(&s)), (undo, kids), "nothing to fill"); + // The Shape Builder's options reach the active Fill Area tool. + s.set_tool_option_cmd(&json!({"tool": "shapeBuilder", "values": {"gapDetection": true, "gapLength": 3}})).unwrap(); + assert_eq!(s.tool_options_of("fillArea")["gapLength"], json!(3.0)); + s.pointer(&PointerEvent::new(PointerKind::Move, 50.0, 70.0), v).unwrap(); + let red: Vec<_> = s.overlays(v).into_iter().filter(|o| matches!(o, Overlay::Path { color: [0xff, 0x2a, 0x2a], .. })).collect(); + assert_eq!(red.len(), 1, "the area is outlined in red"); + assert_eq!(s.cursor(Point::new(50.0, 70.0), Mods::default(), v), Cursor::LivePaintBucketFace); + s.pointer(&PointerEvent::new(PointerKind::Down, 50.0, 70.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 50.0, 70.0), v).unwrap(); + assert_eq!(s.journal.last().unwrap().0, "shapeBuilder.copyRegion"); + assert_eq!(stack(&s).len(), 4); + assert_eq!(undo_len(&s), undo + 1); + assert_eq!(s.tool_id(), "fillArea"); + assert!(s.set_tool_option_cmd(&json!({"tool": "fillArea", "values": {"highlightColor": "#ff0000"}})).is_err()); + assert!(s.set_tool_option_cmd(&json!({"tool": "fillArea", "values": {"gapLength": "wide"}})).is_err()); + // Setting them on Fill Area sets them for the Shape Builder too. + s.set_tool_option_cmd(&json!({"tool": "fillArea", "values": {"gapLength": 5, "openFilledAsClosed": false}})).unwrap(); + let opts = s.tool_options_of("shapeBuilder"); + assert_eq!((opts["gapLength"].clone(), opts["openFilledAsClosed"].clone()), (json!(5.0), json!(false))); +} + +/// The hover search for a document of more than 128 segments runs on another thread: nothing is +/// outlined until the tool is polled, and a click finds the area at once. +#[test] +fn fill_area_tool_hovers_a_large_document_on_another_thread() { + let mut s = session(); + s.execute("shape.polygon", &json!({"cx": 300, "cy": 300, "radius": 100, "sides": 200})).unwrap(); + deselect(&mut s); + let v = ViewInfo::default(); + s.select_tool("fillArea", v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Move, 300.0, 300.0), v).unwrap(); + assert!(s.tool_waiting()); + assert!(s.overlays(v).is_empty()); + // The pointer moves on inside the area before the search is done: its result still serves. + s.pointer(&PointerEvent::new(PointerKind::Move, 305.0, 300.0), v).unwrap(); + s.tool_poll(v, false).unwrap(); + s.tool_poll(v, true).unwrap(); + assert!(!s.tool_waiting()); + assert_eq!(s.overlays(v).len(), 1, "the polygon is outlined"); + // Leaving the area takes the outline away at once, while the next search runs. + s.pointer(&PointerEvent::new(PointerKind::Move, 500.0, 500.0), v).unwrap(); + assert!(s.overlays(v).is_empty()); + s.tool_poll(v, true).unwrap(); + assert!(s.overlays(v).is_empty()); + s.pointer(&PointerEvent::new(PointerKind::Move, 300.0, 300.0), v).unwrap(); + s.tool_poll(v, true).unwrap(); + assert_eq!(s.overlays(v).len(), 1); + // A click while a search runs waits for it. + s.pointer(&PointerEvent::new(PointerKind::Move, 310.0, 300.0), v).unwrap(); + let undo = undo_len(&s); + s.pointer(&PointerEvent::new(PointerKind::Down, 310.0, 300.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 310.0, 300.0), v).unwrap(); + assert_eq!(undo_len(&s), undo + 1); +} + +/// A press that is dropped before the release (a long or canceled touch) takes the new path back +/// and records no undo step. +#[test] +fn fill_area_tool_dropped_press_adds_nothing() { + let mut s = session(); + triangle(&mut s); + deselect(&mut s); + let v = ViewInfo::default(); + s.select_tool("fillArea", v).unwrap(); + let (undo, kids) = (undo_len(&s), stack(&s)); + s.pointer(&PointerEvent::new(PointerKind::Down, 50.0, 70.0), v).unwrap(); + assert_eq!(stack(&s).len(), kids.len() + 1, "the path shows during the press"); + s.drop_tool_press(v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 50.0, 70.0), v).unwrap(); + assert_eq!((undo_len(&s), stack(&s)), (undo, kids)); +} + +/// The outline under a still pointer goes when the document changes, and the canvas hovers the +/// tool again then. +#[test] +fn fill_area_tool_drops_a_hover_the_document_no_longer_has() { + let mut s = session(); + rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let v = ViewInfo::default(); + s.select_tool("fillArea", v).unwrap(); + assert!(s.tool_wants_rehover()); + s.pointer(&PointerEvent::new(PointerKind::Move, 50.0, 50.0), v).unwrap(); + assert_eq!(s.overlays(v).len(), 1); + s.execute("edit.clear", &json!({})).unwrap(); + assert!(s.overlays(v).is_empty()); + assert_eq!(s.cursor(Point::new(50.0, 50.0), Mods::default(), v), Cursor::LivePaintBucket); +} + +/// Moving the pointer from an area with a hole into the area that fills the hole outlines the +/// inner area instead. +#[test] +fn fill_area_tool_hover_moves_from_an_area_into_its_hole() { + let mut s = session(); + line(&mut s, (-20.0, 0.0), (420.0, 0.0)); + line(&mut s, (-20.0, 400.0), (420.0, 400.0)); + line(&mut s, (0.0, -20.0), (0.0, 420.0)); + line(&mut s, (400.0, -20.0), (400.0, 420.0)); + for (a, b) in [((150.0, 250.0), (250.0, 350.0)), ((250.0, 250.0), (150.0, 350.0)), ((140.0, 330.0), (260.0, 330.0))] { + line(&mut s, a, b); + } + deselect(&mut s); + let v = ViewInfo::default(); + s.select_tool("fillArea", v).unwrap(); + let outlined = |s: &mut Session| -> Vec { + s.overlays(v) + .into_iter() + .filter_map(|o| match o { + Overlay::Path { path, .. } => Some(kurbo::Shape::bounding_box(&path).width()), + _ => None, + }) + .collect() + }; + s.pointer(&PointerEvent::new(PointerKind::Move, 50.0, 50.0), v).unwrap(); + let w = outlined(&mut s); + assert!(w.len() == 1 && (w[0] - 400.0).abs() < 1e-6, "the square: {w:?}"); + s.pointer(&PointerEvent::new(PointerKind::Move, 200.0, 320.0), v).unwrap(); + let w = outlined(&mut s); + assert!(w.len() == 1 && (w[0] - 60.0).abs() < 1e-6, "the triangle in its hole: {w:?}"); +} diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 6e8626666a..158c34f0b7 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -979,7 +979,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.options", "Tool Options…", "", - "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront and filledLines held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool, diameter (pt), intensity and density (1–10), shared by the eight tools; OK runs tool.setOption {tool, values}), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", + "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront and filledLines held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool, diameter (pt), intensity and density (1–10), shared by the eight tools; OK runs tool.setOption {tool, values}), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), fillArea → the same Shape Builder Tool Options (Fill Area uses their gapDetection, gapLength and openFilledAsClosed), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", ), ( "ui.colorGuideOptions", diff --git a/crates/tools/src/builder.rs b/crates/tools/src/builder.rs index 51617935f5..4cb0a813f9 100644 --- a/crates/tools/src/builder.rs +++ b/crates/tools/src/builder.rs @@ -1,7 +1,7 @@ -//! Shape Builder (Shift+M), Live Paint Bucket (K) and Live Paint Selection (Shift+L). +//! Shape Builder (Shift+M), Live Paint Bucket (K), Fill Area 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::shape_builder` (Shape +//! The tools only emit commands (`shapeBuilder.merge`, `shapeBuilder.copyRegion`, `livePaint.fill`, +//! `livePaint.strokeEdge`, `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 @@ -28,11 +28,13 @@ use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, Tool pub use po::SHAPE_BUILDER_MAX_GAP; mod cache; +mod fill_area; mod live_paint; mod lookup; mod map; use cache::{BACKGROUND_SEGMENTS, CacheKey, RegionCache}; +pub use fill_area::{AreaFinder, EnclosedArea, FillAreaTool, every_layer}; #[cfg(test)] use live_paint::LpHover; pub use live_paint::{ @@ -815,11 +817,16 @@ impl Tool for ShapeBuilderTool { /// is not true or false, a `pickColorFrom` other than `artwork` or `swatches`, a `selection` other /// than `freeform` or `straightLine`, a `highlightColor` that is not an RGB color without an alpha /// part and a `gapLength` that is not a finite number are errors. A finite gap length out of 0 to -/// [`SHAPE_BUILDER_MAX_GAP`] is not an error: the tool clamps it. The Live Paint tools are checked -/// by [`check_live_paint_options`]; Ok for every other tool. Saved settings go to the tools' -/// `set_option` instead, which skips a value it cannot read. +/// [`SHAPE_BUILDER_MAX_GAP`] is not an error: the tool clamps it. `fillArea` takes only +/// `gapDetection`, `gapLength` and `openFilledAsClosed`, checked the same way. The Live Paint tools +/// are checked by [`check_live_paint_options`]; Ok for every other tool. Saved settings go to the +/// tools' `set_option` instead, which skips a value it cannot read. pub fn check_builder_options(tool: &str, values: &serde_json::Map) -> Result<(), String> { - if tool != "shapeBuilder" { + if tool == "fillArea" { + if let Some(key) = values.keys().find(|k| !matches!(k.as_str(), "gapDetection" | "gapLength" | "openFilledAsClosed")) { + return Err(format!("unknown Fill Area option `{key}`")); + } + } else if tool != "shapeBuilder" { return check_live_paint_options(tool, values); } let one_of = |key: &str, v: &Value, names: &[&str]| { @@ -849,6 +856,7 @@ pub fn create(id: &str) -> Option> { "shapeBuilder" => Box::new(ShapeBuilderTool::default()), "livePaintBucket" => Box::new(LivePaintBucketTool::default()), "livePaintSelection" => Box::new(LivePaintSelectionTool::default()), + "fillArea" => Box::new(FillAreaTool::new()), _ => return None, }) } diff --git a/crates/tools/src/builder/fill_area.rs b/crates/tools/src/builder/fill_area.rs new file mode 100644 index 0000000000..d4b841b9ca --- /dev/null +++ b/crates/tools/src/builder/fill_area.rs @@ -0,0 +1,523 @@ +//! The Fill Area tool: a click inside an area that visible, unlocked paths enclose adds a new +//! closed path of that area with the current fill and stroke (`shapeBuilder.copyRegion`). The +//! paths around the area stay as they are, and nothing needs to be selected. + +use super::lookup::path_contains; +use super::*; + +/// The area [`AreaFinder::find`] finds under a point. +#[derive(Clone, Debug, PartialEq)] +pub struct EnclosedArea { + /// The area's outline, as a Shape Builder merge of that one region makes it. + pub path: PathData, + /// The object directly in a layer that holds the front-most path along the area (its outline + /// touches the area's outline, or it covers the area): the new path goes directly above it, so + /// it never goes inside a group, a Live Paint group, a Shaper group or a clipping group. + pub above: NodeId, +} + +/// How many times [`AreaFinder::find`] widens the part of the document it maps before it maps +/// every path. +const WINDOW_ROUNDS: usize = 24; + +/// The side (pt) of the first window [`AreaFinder::find`] maps around a point that no path's bounds +/// hold. +const FIRST_WINDOW: f64 = 32.0; + +/// How many times [`AreaFinder::find`] makes the window four times larger when the paths in it hold +/// no area under the point, before it maps every path: a 32 pt window reaches 8,192 pt. +const NEAR_ROUNDS: usize = 4; + +/// Finds the area under a point among the paths of some objects, mapping only the paths near the +/// point first: an area that lies inside a window is bounded by the paths whose bounds reach the +/// window, so the paths outside it cannot change it. When the maps of [`NEAR_ROUNDS`] larger windows +/// have no area under the point, or the area does not fit after [`WINDOW_ROUNDS`] widenings, the +/// finder maps every path. When a window's paths have more segments than one Shape Builder map +/// takes, the paths with the most segments are left out until the rest fit, and an area is taken +/// only when no path left out reaches it. When every path together has more segments than that, +/// an area no window finds is not found. The map of every path, once a search has needed it, is +/// kept for the next search. +pub struct AreaFinder { + /// The inputs back → front, as [`shape_builder_shapes`] gives them, with their bounds and the + /// object directly in a layer that holds each one ([`outermost`]). + inputs: Vec<(po::Shape, Rect, NodeId)>, + /// The bounds of every input. + total: Option, + gap: f64, + /// The segments of all the inputs. + segments: usize, + /// Whether all the inputs fit the segment limit of one Shape Builder map. Past it a map keeps + /// only the filled areas and loses the lines between them, so no map of every input is made. + fits: bool, + /// The map of every input, with the index of each of its shapes in `inputs`. + full: Option<(BuilderMap, Vec)>, +} + +/// Does `r` hold `p`, edges included? +fn holds(r: &Rect, p: Point) -> bool { + p.x >= r.x0 && p.x <= r.x1 && p.y >= r.y0 && p.y <= r.y1 +} + +/// Do `a` and `b` overlap or touch? +fn meet(a: &Rect, b: &Rect) -> bool { + a.x0 <= b.x1 && b.x0 <= a.x1 && a.y0 <= b.y1 && b.y0 <= a.y1 +} + +/// Does `outer` hold all of `inner`? +fn within(inner: &Rect, outer: &Rect) -> bool { + inner.x0 >= outer.x0 && inner.x1 <= outer.x1 && inner.y0 >= outer.y0 && inner.y1 <= outer.y1 +} + +/// The object directly in a layer (or sublayer) that holds `id`: `id` itself when a layer holds it. +fn outermost(doc: &Document, id: NodeId) -> NodeId { + let Some(line) = doc.ancestry(id) else { return id }; + let layer = line.iter().rposition(|a| doc.node(*a).is_some_and(|n| n.is_layer())); + layer.and_then(|k| line.get(k + 1)).copied().unwrap_or(id) +} + +impl AreaFinder { + /// The finder over the paths of `roots` (layers or objects) that the Shape Builder takes: + /// visible, unlocked paths, compound paths and Live Paint faces and edges that draw, not on a + /// locked artboard. Gaps up to `gap` close, and with `open_filled_as_closed` a filled open path + /// bounds an area as if an invisible edge closed it. + pub fn new(doc: &Document, roots: &[NodeId], gap: f64, open_filled_as_closed: bool) -> Self { + let roots = sorted_roots(doc, roots); + let (shapes, leaves) = shape_builder_shapes(doc, &roots, open_filled_as_closed); + let editable = doc.editable(); + let inputs: Vec<(po::Shape, Rect, NodeId)> = shapes + .into_iter() + .zip(leaves) + .filter(|(_, l)| editable(l.id)) + .filter_map(|(s, l)| { + let b = s.path.bounds()?; + Some((s, b, outermost(doc, l.id))) + }) + .collect(); + let total = inputs.iter().map(|(_, b, _)| *b).reduce(|a, b| a.union(b)); + let gap = if gap.is_finite() { gap.clamp(0.0, SHAPE_BUILDER_MAX_GAP) } else { 0.0 }; + let segments: usize = inputs.iter().flat_map(|(s, ..)| &s.path.subpaths).map(|sp| sp.segment_count()).sum(); + Self { inputs, total, gap, segments, fits: segments <= po::SHAPE_BUILDER_MAX_SEGMENTS, full: None } + } + + /// The area under `p`: the smallest region of the map of the paths that holds `p`. None when + /// `p` is in no enclosed area. + pub fn find(&mut self, p: Point) -> Option { + if let Some((map, picked)) = &self.full { + return self.area_in(map, picked, p); + } + let total = self.total?; + // A gap bridge reaches at most `gap` past a path, so a window takes in every path within + // that of it. + let reach = self.gap + 1.0; + if !holds(&total.inflate(reach, reach), p) { + return None; + } + let mut window = self + .inputs + .iter() + .filter(|(_, b, _)| holds(&b.inflate(reach, reach), p)) + .map(|(_, b, _)| *b) + .reduce(|a, b| a.union(b)) + .unwrap_or_else(|| Rect::from_center_size(p, (FIRST_WINDOW, FIRST_WINDOW))); + let mut near = 0; + let mut every_path = false; + // The paths left out of the windows' maps to keep them within the segment limit, by index. + let mut left_out = vec![false; self.inputs.len()]; + let mut any_left_out = false; + for round in 0..=WINDOW_ROUNDS { + let last = every_path || round == WINDOW_ROUNDS; + if last && !self.fits { + return None; + } + let zone = window.inflate(reach, reach); + let mut picked: Vec = (0..self.inputs.len()) + .filter(|&i| last || (!left_out.get(i).is_some_and(|o| *o) && self.inputs.get(i).is_some_and(|(_, b, _)| meet(b, &zone)))) + .collect(); + // Past the segment limit a map keeps only the filled areas, so the paths with the most + // segments stay out of the window's map. + if !last { + for i in self.over_limit(&picked) { + if let Some(o) = left_out.get_mut(i) { + *o = true; + any_left_out = true; + } + } + picked.retain(|&i| !left_out.get(i).is_some_and(|o| *o)); + } + let every = picked.len() == self.inputs.len(); + let shapes: Vec = picked.iter().filter_map(|&i| self.inputs.get(i).map(|(s, ..)| s.clone())).collect(); + let map = BuilderMap::of_shapes(shapes, false, self.gap); + let bounds = map.region_at(p).and_then(|k| map.regions.get(k)).map(|(.., rb)| *rb); + if every { + let area = self.area_in(&map, &picked, p); + self.full = Some((map, picked)); + return area; + } + let before = window; + match bounds { + // A path left out that reaches the area could cut it, and only the map of every + // path holds both. + Some(rb) if within(&rb, &window) => { + let reached = rb.inflate(reach, reach); + let cut = any_left_out && self.inputs.iter().zip(&left_out).any(|((_, b, _), out)| *out && meet(b, &reached)); + if !cut { + return self.area_in(&map, &picked, p); + } + every_path = true; + } + Some(rb) => window = window.union(rb), + // No area of the paths near the point holds it: an area that does is bounded by + // paths farther away. The window grows four times over a few rounds, and then the + // next round maps every path. + None if near < NEAR_ROUNDS => { + near += 1; + let (w, h) = (window.width().max(FIRST_WINDOW) * 4.0, window.height().max(FIRST_WINDOW) * 4.0); + window = window.union(Rect::from_center_size(window.center(), (w, h))); + } + None => window = total, + } + // A window that did not grow would give the same map again. + if window == before { + every_path = true; + } + } + None + } + + /// The inputs among `picked` to leave out of a map so that the rest fit the segment limit of + /// one Shape Builder map: the ones with the most segments first. Empty when all of `picked` fit. + fn over_limit(&self, picked: &[usize]) -> Vec { + let segments = |i: usize| self.inputs.get(i).map_or(0, |(s, ..)| s.path.subpaths.iter().map(|sp| sp.segment_count()).sum::()); + let mut sum: usize = picked.iter().map(|&i| segments(i)).sum(); + let mut by_size: Vec<(usize, usize)> = picked.iter().map(|&i| (segments(i), i)).collect(); + by_size.sort_by_key(|(n, _)| std::cmp::Reverse(*n)); + let mut out = vec![]; + for (n, i) in by_size { + if sum <= po::SHAPE_BUILDER_MAX_SEGMENTS { + break; + } + sum -= n; + out.push(i); + } + out + } + + /// The area under `p` in `map`, made of the inputs `picked` (in its order). + fn area_in(&self, map: &BuilderMap, picked: &[usize], p: Point) -> Option { + let (region, ..) = map.region_at(p).and_then(|k| map.regions.get(k))?; + let path = po::FaceMerger::with_gap(&map.shapes, self.gap).merge(&[region]); + if path.is_empty() { + return None; + } + let anchors: Vec = region.path.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p)).collect(); + // The front-most shape that covers the area or that an anchor of its outline lies on. A + // shape within the gap of an anchor counts only when no shape is along the area itself, + // so a path near the area that bounds none of it does not decide where the new path goes. + let along = |gap: f64| { + map.shapes.iter().enumerate().rev().find(|(i, s)| { + let tol = outline_snap(&s.path) + gap; + region.sources.contains(i) + || s.path.bounds().is_some_and(|b| { + let b = b.inflate(tol, tol); + anchors.iter().any(|q| holds(&b, *q) && s.path.nearest(*q).is_some_and(|(.., d)| d <= tol)) + }) + }) + }; + let k = along(0.0).or_else(|| along(self.gap)).map_or(map.shapes.len().checked_sub(1)?, |(i, _)| i); + let above = picked.get(k).and_then(|&i| self.inputs.get(i)).map(|(.., id)| *id)?; + Some(EnclosedArea { path, above }) + } +} + +/// The paths the Fill Area tool finds areas among: every layer's. +pub fn every_layer(doc: &Document) -> Vec { + doc.layers.iter().map(|l| l.id).collect() +} + +/// Fill Area (in the Live Paint Bucket's group): a click inside an area that visible, unlocked +/// paths on any layer enclose adds a new closed path of that area with the current fill and stroke +/// (`shapeBuilder.copyRegion`), directly above the front-most object along it. The paths stay as +/// they are and nothing needs to be selected. The area under the pointer is outlined while it +/// hovers. Gap Detection and Consider Open Filled Paths as Closed are the Shape Builder's options. +#[derive(Default)] +pub struct FillAreaTool { + gap_detection: bool, + gap_length: f64, + /// Consider Open Filled Paths as Closed turned off: a filled open path cuts areas as a line + /// does. + open_filled_cuts: bool, + /// The finder for the document as it is, with the key it was made for. Away while a search + /// runs on another thread. + finder: Option<(FinderKey, AreaFinder)>, + /// The area under the pointer, with the document revision it was found in. + hover: Option<((u64, u64), EnclosedArea)>, + /// Where the pointer last moved over the canvas. + at: Option, + /// A hover search running on another thread. + job: Option, + /// The key whose search on another thread failed: hovering does not search it again. + failed: Option, + /// A press added the path as a preview, which the release keeps. + pressing: bool, +} + +/// The document revision, the gap and the open-filled rule an [`AreaFinder`] was made with. +type FinderKey = ((u64, u64), f64, bool); + +/// A search for the area under `p` on another thread, which hands back the finder it took. +struct HoverJob { + key: FinderKey, + p: Point, + done: std::sync::mpsc::Receiver<(AreaFinder, Option)>, +} + +/// Runs `finder.find(p)` on another thread; gives the finder back when no thread starts. +#[cfg(not(target_arch = "wasm32"))] +fn spawn_find(finder: AreaFinder, p: Point) -> Result)>, Box> { + let (tx, done) = std::sync::mpsc::channel(); + let (back_tx, back) = std::sync::mpsc::channel(); + let spawned = std::thread::Builder::new().name("vectorcraft-fill-area".into()).spawn(move || { + // The finder comes in through a channel, so a thread that does not start leaves it here. + if let Ok(mut f) = back.recv() { + let area = AreaFinder::find(&mut f, p); + // The tool may have dropped the receiver meanwhile (another tool, a new revision). + let _ = tx.send((f, area)); + } + }); + match spawned { + Ok(_) => match back_tx.send(finder) { + Ok(()) => Ok(done), + Err(e) => Err(Box::new(e.0)), + }, + Err(_) => Err(Box::new(finder)), + } +} + +/// The web build has no threads. +#[cfg(target_arch = "wasm32")] +fn spawn_find(finder: AreaFinder, _p: Point) -> Result)>, Box> { + Err(Box::new(finder)) +} + +impl FillAreaTool { + /// A tool with the Shape Builder's default options. + pub fn new() -> Self { + Self { gap_length: GAP_LENGTHS[0], ..Self::default() } + } + + fn gap(&self) -> f64 { + if self.gap_detection { self.gap_length } else { 0.0 } + } + + fn open_filled_as_closed(&self) -> bool { + !self.open_filled_cuts + } + + fn finder_key(&self, cx: &ToolContext) -> FinderKey { + (cx.revision, self.gap(), self.open_filled_as_closed()) + } + + /// The finder for the document as `cx` has it, made again when the key changed. + fn take_finder(&mut self, cx: &ToolContext) -> AreaFinder { + let key = self.finder_key(cx); + match self.finder.take() { + Some((k, f)) if k == key => f, + _ => AreaFinder::new(cx.doc, &every_layer(cx.doc), key.1, key.2), + } + } + + /// The hover area when it is current and holds `p`. + fn hover_holding(&self, cx: &ToolContext, p: Point) -> Option<&EnclosedArea> { + self.hover.as_ref().filter(|(rev, a)| *rev == cx.revision && path_contains(&a.path, FillRule::NonZero, p)).map(|(_, a)| a) + } + + /// The area under `p`, found here and now (a click). A search running on another thread is + /// waited for first, so its finder is not made again. + fn area_at(&mut self, cx: &ToolContext, p: Point) -> Option { + if let Some(a) = self.hover_holding(cx, p) { + return Some(a.clone()); + } + while self.job.is_some() { + self.settle(cx, true); + } + let key = self.finder_key(cx); + let mut finder = self.take_finder(cx); + let area = finder.find(p); + self.finder = Some((key, finder)); + area + } + + /// Looks for the area under `p` for the hover. A search of more than [`BACKGROUND_SEGMENTS`] + /// segments runs on another thread, and [`Tool::poll`] takes its result; while one runs, a new + /// position waits for it. + fn hover_at(&mut self, cx: &ToolContext, p: Point) { + self.at = Some(p); + if self.hover_holding(cx, p).is_some() { + return; + } + // The outline of an area the pointer left goes at once, while the next search runs. + self.hover = None; + if self.job.is_some() { + return; + } + let key = self.finder_key(cx); + if self.failed == Some(key) { + self.hover = None; + return; + } + let mut finder = self.take_finder(cx); + if finder.segments > BACKGROUND_SEGMENTS { + match spawn_find(finder, p) { + Ok(done) => { + self.job = Some(HoverJob { key, p, done }); + return; + } + Err(f) => finder = *f, + } + } + self.hover = finder.find(p).map(|a| (key.0, a)); + self.finder = Some((key, finder)); + } + + /// Takes the result of the hover search on another thread when it is done (`wait`: waits for + /// it), and starts the search for where the pointer moved meanwhile. + fn settle(&mut self, cx: &ToolContext, wait: bool) { + let Some(job) = self.job.take() else { return }; + let got = if wait { + job.done.recv().ok() + } else { + match job.done.try_recv() { + Ok(v) => Some(v), + Err(std::sync::mpsc::TryRecvError::Empty) => { + self.job = Some(job); + return; + } + Err(std::sync::mpsc::TryRecvError::Disconnected) => None, + } + }; + let Some((finder, area)) = got else { + // The search failed (a bug in the planar map): hovering does not search it again, and + // a click searches here, which reports the failure. + self.failed = Some(job.key); + self.hover = None; + return; + }; + let current = job.key == self.finder_key(cx); + if current { + self.finder = Some((job.key, finder)); + } + // The area found serves wherever the pointer moved meanwhile, as long as it holds it. + let at = self.at; + self.hover = area.filter(|a| current && at.is_some_and(|p| path_contains(&a.path, FillRule::NonZero, p))).map(|a| (job.key.0, a)); + if let Some(p) = at + && self.hover.is_none() + && (p != job.p || !current) + { + self.hover_at(cx, p); + } + } +} + +impl Tool for FillAreaTool { + fn id(&self) -> &'static str { + "fillArea" + } + + fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { + match ev.kind { + PointerKind::Move => { + self.hover_at(cx, ev.pos); + vec![] + } + PointerKind::Down => { + // A click in no enclosed area does nothing. + let found = self.area_at(cx, ev.pos).is_some(); + self.hover = None; + if !found { + return vec![]; + } + let mut params = json!({ "point": [ev.pos.x, ev.pos.y], "gap": self.gap() }); + if !self.open_filled_as_closed() { + params["openFilledAsClosed"] = json!(false); + } + // The path shows at once and is kept on the release; a press that is dropped (a + // long or canceled touch, a second finger) or Escape before the release takes it + // back. + self.pressing = true; + vec![Action::Begin("Fill Area".into()), Action::Preview("shapeBuilder.copyRegion".into(), params)] + } + PointerKind::Up if std::mem::take(&mut self.pressing) => vec![Action::Commit], + _ => vec![], + } + } + + fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { + if key == ToolKey::Escape && std::mem::take(&mut self.pressing) { vec![Action::Cancel] } else { vec![] } + } + + fn busy(&self) -> bool { + self.pressing + } + + fn overlays(&self, cx: &ToolContext) -> Vec { + self.hover + .iter() + .filter(|(rev, _)| *rev == cx.revision) + .map(|(_, a)| Overlay::Path { path: a.path.to_bezpath(), color: HIGHLIGHT_RED, width: 3.0, dashed: false }) + .collect() + } + + fn cursor(&self, cx: &ToolContext, p: Point, _m: Mods) -> Cursor { + if self.hover_holding(cx, p).is_some() { Cursor::LivePaintBucketFace } else { Cursor::LivePaintBucket } + } + + fn hover_ended(&mut self, _cx: &ToolContext) { + self.hover = None; + self.at = None; + } + + /// The area under a still pointer changes with the document and the view. + fn wants_rehover(&self) -> bool { + true + } + + fn waiting(&self) -> bool { + self.job.is_some() + } + + fn poll(&mut self, cx: &ToolContext, wait: bool) -> Vec { + self.settle(cx, wait); + while wait && self.job.is_some() { + self.settle(cx, true); + } + vec![] + } + + /// The Shape Builder's Gap Detection, Gap Length and Consider Open Filled Paths as Closed, + /// which the tool shares. + fn options(&self) -> Value { + json!({ + "gapDetection": self.gap_detection, + "gapLength": self.gap_length, + "openFilledAsClosed": self.open_filled_as_closed(), + }) + } + + fn set_option(&mut self, key: &str, v: &Value) { + match key { + "gapDetection" => self.gap_detection = v.as_bool().unwrap_or(self.gap_detection), + "gapLength" => { + if let Some(n) = v.as_f64().filter(|n| n.is_finite()) { + self.gap_length = n.clamp(0.0, SHAPE_BUILDER_MAX_GAP); + } + } + "openFilledAsClosed" => { + if let Some(b) = v.as_bool() { + self.open_filled_cuts = !b; + } + } + _ => {} + } + self.hover = None; + } +} diff --git a/crates/tools/src/catalog.rs b/crates/tools/src/catalog.rs index 9bbd7cbdfb..b9263c39a9 100644 --- a/crates/tools/src/catalog.rs +++ b/crates/tools/src/catalog.rs @@ -92,6 +92,7 @@ pub const TOOL_GROUPS: &[&[ToolInfo]] = &[ &[ t("shapeBuilder", "Shape Builder Tool", Some("Shift+M"), "tool-shape-builder"), t("livePaintBucket", "Live Paint Bucket", Some("K"), "tool-bucket"), + t("fillArea", "Fill Area Tool", None, "tool-fill-area"), t("livePaintSelection", "Live Paint Selection Tool", Some("Shift+L"), "tool-live-select"), ], &[ diff --git a/crates/tools/src/cursors.toml b/crates/tools/src/cursors.toml index 51756bf0fd..3a850c72f9 100644 --- a/crates/tools/src/cursors.toml +++ b/crates/tools/src/cursors.toml @@ -514,6 +514,7 @@ id = "LivePaintBucket" group = "Colour and gradient" shown_when = [ "The Live Paint Bucket where a click paints nothing: away from Live Paint groups and the selected paths' regions, or over a part the Paint Fills and Paint Strokes options (and Shift) leave unpainted.", + "The Fill Area tool outside every area that visible, unlocked paths enclose, where a click adds nothing.", "With Use Precise Cursors on, the crosshair shows instead.", ] hotspot = "The drop the paint pours onto." @@ -524,6 +525,7 @@ id = "LivePaintBucketFace" group = "Colour and gradient" shown_when = [ "The Live Paint Bucket over a face of a Live Paint group, or a region of the selected paths, that a click fills.", + "The Fill Area tool over an enclosed area, where a click adds a path of that area.", "With Use Precise Cursors on, the crosshair shows instead.", ] hotspot = "The drop the paint pours onto." diff --git a/crates/tools/src/settings.rs b/crates/tools/src/settings.rs index a5c92b00b0..2c6c5a75e5 100644 --- a/crates/tools/src/settings.rs +++ b/crates/tools/src/settings.rs @@ -69,6 +69,8 @@ const ROWS: &[Row] = &[ "highlightColor", ], ), + // Fill Area uses the Shape Builder's Gap Detection and open-filled-path options. + (&["fillArea"], Some("shapeBuilder"), &["openFilledAsClosed", "gapDetection", "gapLength"]), // Objects on Path Tool Options: the Pivot and Rotate of the objects attached next. (&["objectsOnPath"], None, &["pivot", "rotate"]), (&["artboard"], None, &["moveArt", "scaleArt"]), diff --git a/crates/ui-egui/src/dialogs/shape_builder_options.rs b/crates/ui-egui/src/dialogs/shape_builder_options.rs index 9393e0707e..b49d9f7e17 100644 --- a/crates/ui-egui/src/dialogs/shape_builder_options.rs +++ b/crates/ui-egui/src/dialogs/shape_builder_options.rs @@ -159,6 +159,22 @@ mod tests { assert_eq!(opts["openFilledAsClosed"], true); } + /// Double-clicking the Fill Area tool opens the Shape Builder Tool Options, whose Gap + /// Detection the active Fill Area tool takes on OK. + #[test] + fn the_fill_area_tool_opens_the_shape_builder_options() { + let mut a = app(); + a.select_tool("fillArea"); + let r = a.run("tool.options", json!({"tool": "fillArea"})).unwrap(); + assert_eq!(r["dialog"], json!(KIND)); + let d = a.ui.dialog.as_mut().unwrap(); + d.fields.insert("gapDetection".into(), json!(true)); + d.fields.insert("gapLength".into(), json!(6)); + super::super::confirm(&mut a).unwrap(); + let opts = a.session.tool_options_of("fillArea"); + assert_eq!((opts["gapDetection"].clone(), opts["gapLength"].clone()), (json!(true), json!(6.0))); + } + #[test] fn double_clicking_the_tool_opens_its_options_and_ok_keeps_them() { let mut app = app(); diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 61e90c789d..1d2633fe99 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -1906,6 +1906,8 @@ font-technology Variable Променливи List Workspaces Извеждане на работни пространства Live Paint Динамично оцветяване Live Paint Bucket Кофа за динамично оцветяване + Fill Area Запълване на област + Fill Area Tool Инструмент „Запълване на област“ Live Paint Bucket (Stroke) Кофа за динамично оцветяване (Щрих) Live Paint Info Информация за динамично оцветяване Live Paint Selection Tool Инструмент за селекция на динамично оцветяване @@ -4311,6 +4313,7 @@ axis Both И двете @msg Saved {path} Записано: {path} @msg Select text or click into text with the Type tool to insert glyphs Изберете текст или щракнете в текста с инструмента „Текст“, за да вмъкнете глифи @msg Shape Builder: no region under the pointer Инструмент за създаване на форми: няма област под показалеца +@msg Fill Area: no enclosed area under the pointer Запълване на област: няма затворена област под показалеца @msg Shape Builder: select paths or compound paths Инструмент за създаване на форми: изберете пътища или съставни пътища @msg Show All Hidden Attributes: nothing is hidden Показване на всички скрити атрибути: нищо не е скрито @msg Split Into Grid: select paths large enough for the grid Разделяне на мрежа: изберете пътища, достатъчно големи за мрежата diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index b3a4eefc2f..d84b3e6128 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -3451,6 +3451,8 @@ theme Appearance Izgled Symbolism Tool Alat simbolizam Image Trace Presets Predlošci praćenja slike Live Paint Bucket Kanta za živo bojenje + Fill Area Popuni područje + Fill Area Tool Alat za popunjavanje područja Live Paint Bucket (Stroke) Kanta za živo bojenje (potez) Live Paint Info Informacije o živom bojenju Shape Builder Graditelj oblika @@ -4685,6 +4687,7 @@ imageTrace Outline Obris @msg Saved {path} Sačuvano: {path} @msg Select text or click into text with the Type tool to insert glyphs Odaberite tekst ili kliknite u tekst alatom za tekst da umetnete glifove @msg Shape Builder: no region under the pointer Graditelj oblika: nema regije ispod pokazivača +@msg Fill Area: no enclosed area under the pointer Popuni područje: nema zatvorenog područja ispod pokazivača @msg Shape Builder: select paths or compound paths Graditelj oblika: odaberite putanje ili složene putanje @msg Show All Hidden Attributes: nothing is hidden Prikaži sve skrivene atribute: ništa nije skriveno @msg Split Into Grid: select paths large enough for the grid Podijeli u mrežu: odaberite putanje dovoljno velike za mrežu diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 2f9f1d8fdc..26dea6bf21 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -2479,6 +2479,8 @@ digits Malayalam Malaiàlam Live curve fitting Ajustament de corbes en directe Live Paint Pintura interactiva Live Paint Bucket Galleda de pintura interactiva + Fill Area Emplena l'àrea + Fill Area Tool Eina Emplena l'àrea Live Paint Bucket (Stroke) Galleda de pintura interactiva (traç) Live Paint Info Informació de pintura interactiva Live Paint Selection Tool Eina de selecció de pintura interactiva @@ -6298,6 +6300,7 @@ digits Malayalam Malaiàlam @msg shadings of more than 4096 patches or triangles were left out els ombrejats de més de 4096 pedaços o triangles s’han omès @msg shadings whose functions are of an unknown type are filled with their middle colour els ombrejats les funcions dels quals són d’un tipus desconegut s’omplen amb el seu color central @msg Shape Builder: no region under the pointer Constructor de formes: no hi ha cap regió sota el punter +@msg Fill Area: no enclosed area under the pointer Emplena l'àrea: no hi ha cap àrea tancada sota el punter @msg Shape Builder: select paths or compound paths Constructor de formes: selecciona traçats o traçats compostos @msg shortcut for `{k}` must be a string la drecera de `{k}` ha de ser una cadena @msg Show All Hidden Attributes: nothing is hidden Mostra tots els atributs ocults: no hi ha res d’ocult diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 4628b89a1d..a519d436fc 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -3543,6 +3543,8 @@ theme Appearance Motiv Symbolism Tool Nástroj symbolů Image Trace Presets Přednastavení vektorizace obrazu Live Paint Bucket Kbelík živé malby + Fill Area Vyplnit oblast + Fill Area Tool Nástroj Vyplnit oblast Live Paint Bucket (Stroke) Kbelík živé malby (tah) Live Paint Info Informace o živé malbě Shape Builder Tvorba tvarů @@ -4888,6 +4890,7 @@ imageTrace Outline Obrys @msg Saved {path} Uloženo: {path} @msg Select text or click into text with the Type tool to insert glyphs Glyfy vložíte, když vyberete text nebo do něj kliknete nástrojem Text @msg Shape Builder: no region under the pointer Tvorba tvarů: pod ukazatelem není žádná oblast +@msg Fill Area: no enclosed area under the pointer Vyplnit oblast: pod ukazatelem není žádná uzavřená oblast @msg Shape Builder: select paths or compound paths Tvorba tvarů: vyberte cesty nebo složené cesty @msg Show All Hidden Attributes: nothing is hidden Zobrazit všechny skryté atributy: nic není skryto @msg Split Into Grid: select paths large enough for the grid Rozdělit do mřížky: vyberte cesty dost velké pro mřížku diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 8b822be042..62fc5496e9 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -3892,6 +3892,8 @@ theme Appearance Udseende Symbolism Tool Symbolværktøj Image Trace Presets Forudindstillinger til billedsporing Live Paint Bucket Live Paint-spand + Fill Area Udfyld område + Fill Area Tool Værktøjet Udfyld område Live Paint Bucket (Stroke) Live Paint-spand (kontur) Live Paint Info Live Paint-info Shape Builder Formbygger @@ -5093,6 +5095,7 @@ imageTrace Outline Kontur @msg Saved {path} Gemte {path} @msg Select text or click into text with the Type tool to insert glyphs Markér tekst, eller klik i tekst med tekstværktøjet, for at indsætte glyffer @msg Shape Builder: no region under the pointer Figurbygger: intet område under markøren +@msg Fill Area: no enclosed area under the pointer Udfyld område: intet lukket område under markøren @msg Shape Builder: select paths or compound paths Figurbygger: markér kurver eller sammensatte kurver @msg Show All Hidden Attributes: nothing is hidden Vis alle skjulte attributter: intet er skjult @msg Split Into Grid: select paths large enough for the grid Opdel i gitter: markér kurver, der er store nok til gitteret diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 752a60accd..27d2b641d3 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1979,6 +1979,8 @@ file-filter Templates Vorlagen List Workspaces Arbeitsbereiche auflisten Live Paint Interaktiv malen Live Paint Bucket Interaktiv-malen-Werkzeug + Fill Area Fläche füllen + Fill Area Tool Fläche-füllen-Werkzeug Live Paint Bucket (Stroke) Interaktiv-malen-Werkzeug (Kontur) Live Paint Info Informationen zu „Interaktiv malen“ Live Paint Selection Tool Interaktiv-malen-Auswahlwerkzeug @@ -4490,6 +4492,7 @@ theme Appearance Erscheinungsbild @msg Saved {path} {path} gespeichert @msg Select text or click into text with the Type tool to insert glyphs Wählen Sie Text aus oder klicken Sie mit dem Text-Werkzeug in einen Text, um Glyphen einzufügen @msg Shape Builder: no region under the pointer Formerstellung: kein Bereich unter dem Zeiger +@msg Fill Area: no enclosed area under the pointer Fläche füllen: kein geschlossener Bereich unter dem Zeiger @msg Shape Builder: select paths or compound paths Formerstellung: Wählen Sie Pfade oder zusammengesetzte Pfade aus @msg Show All Hidden Attributes: nothing is hidden Alle ausgeblendeten Attribute einblenden: Es ist nichts ausgeblendet @msg Split Into Grid: select paths large enough for the grid In Raster teilen: Wählen Sie Pfade aus, die groß genug für das Raster sind diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 9b32ea177c..fa15a3f764 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2582,6 +2582,7 @@ axis Both Και τα δύο @msg Saved {path} Αποθηκεύτηκε το {path} @msg Select text or click into text with the Type tool to insert glyphs Επιλέξτε κείμενο ή κάντε κλικ μέσα σε κείμενο με το εργαλείο κειμένου για εισαγωγή γλύφων @msg Shape Builder: no region under the pointer Δημιουργία σχημάτων: δεν υπάρχει περιοχή κάτω από τον δείκτη +@msg Fill Area: no enclosed area under the pointer Γέμισμα περιοχής: δεν υπάρχει κλειστή περιοχή κάτω από τον δείκτη @msg Shape Builder: select paths or compound paths Δημιουργία σχημάτων: επιλέξτε διαδρομές ή σύνθετες διαδρομές @msg Show All Hidden Attributes: nothing is hidden Εμφάνιση όλων των κρυφών χαρακτηριστικών: δεν υπάρχουν κρυφά χαρακτηριστικά @msg Split Into Grid: select paths large enough for the grid Διαίρεση σε πλέγμα: επιλέξτε αρκετά μεγάλες διαδρομές για το πλέγμα @@ -2991,6 +2992,8 @@ theme Appearance Εμφάνιση List View Προβολή λίστας List Workspaces Λίστα χώρων εργασίας Live Paint Bucket Κουβάς δυναμικής βαφής + Fill Area Γέμισμα περιοχής + Fill Area Tool Εργαλείο γεμίσματος περιοχής Live Paint Bucket (Stroke) Κουβάς δυναμικής βαφής (περίγραμμα) Live Paint Info Πληροφορίες δυναμικής βαφής Live Paint Selection Tool Επιλογή δυναμικής βαφής (Live Paint Selection Tool) diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 9c81265e9d..8b64b99e89 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1976,6 +1976,8 @@ font-technology Variable Variables List Workspaces Enumerar espacios de trabajo Live Paint Pintura interactiva Live Paint Bucket Bote de pintura interactiva + Fill Area Rellenar área + Fill Area Tool Herramienta Rellenar área Live Paint Bucket (Stroke) Bote de pintura interactiva (trazo) Live Paint Info Información de pintura interactiva Live Paint Selection Tool Herramienta Selección de pintura interactiva @@ -4579,6 +4581,7 @@ axis Both Ambos @msg Saved {path} Se guardó {path} @msg Select text or click into text with the Type tool to insert glyphs Selecciona texto o haz clic dentro del texto con la herramienta Texto para insertar glifos @msg Shape Builder: no region under the pointer Generador de formas: no hay ninguna región bajo el puntero +@msg Fill Area: no enclosed area under the pointer Rellenar área: no hay ninguna área cerrada bajo el puntero @msg Shape Builder: select paths or compound paths Generador de formas: selecciona trazados o trazados compuestos @msg Show All Hidden Attributes: nothing is hidden Mostrar todos los atributos ocultos: no hay nada oculto @msg Split Into Grid: select paths large enough for the grid Dividir en cuadrícula: selecciona trazados lo bastante grandes para la cuadrícula diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 67897bbe68..7bd151914d 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -3482,6 +3482,8 @@ theme Appearance Ulkoasu Symbolism Tool Symbolityökalu Image Trace Presets Kuvan jäljityksen esiasetukset Live Paint Bucket Elävän maalauksen ämpäri + Fill Area Täytä alue + Fill Area Tool Alueen täyttötyökalu Live Paint Bucket (Stroke) Elävän maalauksen ämpäri (viiva) Live Paint Info Elävän maalauksen tiedot Shape Builder Muodonmuodostin @@ -4812,6 +4814,7 @@ imageTrace Outline Ääriviiva @msg Saved {path} Tallennettiin {path} @msg Select text or click into text with the Type tool to insert glyphs Valitse tekstiä tai napsauta tekstiin tekstityökalulla, niin voit lisätä merkkejä @msg Shape Builder: no region under the pointer Muodonmuodostin: osoittimen alla ei ole aluetta +@msg Fill Area: no enclosed area under the pointer Täytä alue: osoittimen alla ei ole suljettua aluetta @msg Shape Builder: select paths or compound paths Muodonmuodostin: valitse polkuja tai yhdistelmäpolkuja @msg Show All Hidden Attributes: nothing is hidden Näytä kaikki piilotetut attribuutit: mitään ei ole piilotettu @msg Split Into Grid: select paths large enough for the grid Jaa ruudukoksi: valitse ruudukolle riittävän suuret polut diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 9c04f43b1b..00a12a3f59 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1970,6 +1970,8 @@ font-technology Variable Variables List Workspaces Lister les espaces de travail Live Paint Peinture dynamique Live Paint Bucket Pot de peinture dynamique + Fill Area Remplir la zone + Fill Area Tool Outil Remplir la zone Live Paint Bucket (Stroke) Pot de peinture dynamique (contour) Live Paint Info Informations sur la peinture dynamique Live Paint Selection Tool Outil Sélection de peinture dynamique @@ -4557,6 +4559,7 @@ axis Both Les deux @msg Saved to User Defined: {_1} Enregistré dans Défini par l’utilisateur : {_1} @msg Saved {path} {path} enregistré @msg Select text or click into text with the Type tool to insert glyphs Sélectionnez du texte ou cliquez dans un texte avec l’outil Texte pour insérer des glyphes +@msg Fill Area: no enclosed area under the pointer Remplir la zone : aucune zone fermée sous le pointeur @msg Shape Builder: no region under the pointer Concepteur de forme : aucune zone sous le pointeur @msg Shape Builder: select paths or compound paths Concepteur de forme : sélectionnez des tracés ou des tracés transparents @msg Show All Hidden Attributes: nothing is hidden Afficher tous les attributs masqués : rien n’est masqué diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 4807c7ec25..9705fe9b1a 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -2029,6 +2029,8 @@ List Workspaces વર્કસ્પેસની યાદી Live Paint લાઇવ પેઇન્ટ Live Paint Bucket લાઇવ પેઇન્ટ બકેટ + Fill Area વિસ્તાર ભરો + Fill Area Tool વિસ્તાર ભરો ટૂલ Live Paint Bucket (Stroke) લાઇવ પેઇન્ટ બકેટ (સ્ટ્રોક) Live Paint Info લાઇવ પેઇન્ટ માહિતી Live Paint Selection Tool લાઇવ પેઇન્ટ પસંદગી ટૂલ diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 15582a2dbd..4bd2dde82b 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -2728,6 +2728,8 @@ antiAlias Sharp शार्प Live curve fitting लाइव वक्र फिटिंग Live Paint लाइव पेंट Live Paint Bucket लाइव पेंट बकेट + Fill Area क्षेत्र भरें + Fill Area Tool क्षेत्र भरें टूल Live Paint Bucket (Stroke) लाइव पेंट बाल्टी (स्ट्रोक) Live Paint Info लाइव पेंट जानकारी Live Paint Selection Tool लाइव पेंट सिलेक्शन टूल @@ -8089,6 +8091,7 @@ antiAlias Sharp शार्प @msg shadings of more than 4096 patches or triangles were left out 4096 से अधिक पैच या त्रिकोणों के छायांकन को छोड़ दिया गया था @msg shadings whose functions are of an unknown type are filled with their middle colour छायांकन जिसका कार्य अज्ञात प्रकार के होते हैं, उनके मध्य रंग से भरे होते हैं @msg Shape Builder: no region under the pointer आकृति बिल्डर: सूचक के तहत कोई क्षेत्र नहीं +@msg Fill Area: no enclosed area under the pointer क्षेत्र भरें: सूचक के तहत कोई बंद क्षेत्र नहीं @msg Shape Builder: select paths or compound paths आकृति बिल्डर: पाथ या मिश्रित पाथ सिलेक्ट करें @msg Shaper needs 1–64 source paths शेपर के लिए 1–64 स्रोत पाथ चाहिए @msg shortcut for `{k}` must be a string `{k}` के लिए शॉर्टकट एक स्ट्रिंग होना चाहिए diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 8ddb1d34ca..8e8bae5fb7 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -2474,6 +2474,8 @@ file-filter Templates Sablonok List Workspaces Munkaterületek listázása Live Paint Élő festés Live Paint Bucket Élő festékesvödör + Fill Area Terület kitöltése + Fill Area Tool Területkitöltő eszköz Live Paint Bucket (Stroke) Élő festékesvödör (körvonal) Live Paint Info Élő festés adatai Live Paint Selection Tool Élőfestés-kijelölés @@ -5820,6 +5822,7 @@ imageTrace Outline Körvonal @msg shadings of more than 4096 patches or triangles were left out kimaradtak a 4096-nál több foltból vagy háromszögből álló árnyalások @msg shadings whose functions are of an unknown type are filled with their middle colour az ismeretlen típusú függvényt használó árnyalások a középső színükkel kitöltve jelennek meg @msg Shape Builder: no region under the pointer Alakzatépítő: a mutató alatt nincs terület +@msg Fill Area: no enclosed area under the pointer Terület kitöltése: a mutató alatt nincs zárt terület @msg Shape Builder: select paths or compound paths Alakzatépítő: jelölj ki útvonalakat vagy összetett útvonalakat @msg shortcut for `{k}` must be a string `{k}` billentyűparancsa csak szöveg lehet @msg Show All Hidden Attributes: nothing is hidden Összes rejtett attribútum megjelenítése: nincs rejtett elem diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 8d7639c430..33aa3dca40 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -3226,6 +3226,8 @@ theme Appearance Tampilan Symbolism Tool Alat simbolisme Image Trace Presets Preset telusur gambar Live Paint Bucket Ember Live Paint + Fill Area Isi Area + Fill Area Tool Alat Isi Area Live Paint Bucket (Stroke) Ember Live Paint (guratan) Live Paint Info Info Live Paint Shape Builder Pembangun bentuk @@ -4427,6 +4429,7 @@ imageTrace Outline Kontur @msg Saved {path} Berhasil menyimpan {path} @msg Select text or click into text with the Type tool to insert glyphs Pilih teks atau klik di dalam teks dengan alat Teks untuk menyisipkan glif @msg Shape Builder: no region under the pointer Pembangun Bentuk: tidak ada area di bawah penunjuk +@msg Fill Area: no enclosed area under the pointer Isi Area: tidak ada area tertutup di bawah penunjuk @msg Shape Builder: select paths or compound paths Pembangun Bentuk: pilih jalur atau jalur majemuk @msg Show All Hidden Attributes: nothing is hidden Tampilkan semua atribut tersembunyi: tidak ada yang tersembunyi @msg Split Into Grid: select paths large enough for the grid Bagi menjadi kisi: pilih jalur yang cukup besar untuk kisi diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 1c0590ff98..dd640f71e6 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -2012,6 +2012,8 @@ file-filter Templates Modelli List Workspaces Elenca aree di lavoro Live Paint Pittura dinamica Live Paint Bucket Secchiello pittura dinamica + Fill Area Riempi area + Fill Area Tool Strumento Riempi area Live Paint Bucket (Stroke) Secchiello pittura dinamica (traccia) Live Paint Info Informazioni pittura dinamica Live Paint Selection Tool Strumento Selezione pittura dinamica @@ -4620,6 +4622,7 @@ axis Both Entrambi @msg Saved {path} Salvato {path} @msg Select text or click into text with the Type tool to insert glyphs Seleziona del testo o fai clic nel testo con lo strumento Testo per inserire glifi @msg Shape Builder: no region under the pointer Generatore forme: nessuna regione sotto il puntatore +@msg Fill Area: no enclosed area under the pointer Riempi area: nessuna area chiusa sotto il puntatore @msg Shape Builder: select paths or compound paths Generatore forme: seleziona tracciati o tracciati composti @msg Show All Hidden Attributes: nothing is hidden Mostra tutti gli attributi nascosti: non c'è nulla di nascosto @msg Split Into Grid: select paths large enough for the grid Dividi in griglia: seleziona tracciati abbastanza grandi per la griglia diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index dedcdb328e..bc4ceb16bf 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -2277,6 +2277,8 @@ antiAlias Sharp シャープ List View リスト表示 List Workspaces ワークスペースの一覧 Live Paint Bucket ライブペイントツール + Fill Area 領域を塗りつぶし + Fill Area Tool 領域塗りつぶしツール Live Paint Bucket (Stroke) ライブペイントツール (線) Live Paint Info ライブペイント情報 Live Paint Selection Tool ライブペイント選択ツール @@ -4533,6 +4535,7 @@ swatch Bright Violet ビビッドバイオレット @msg Live Paint: select paths or compound paths ライブペイント: パスまたは複合パスを選択してください @msg Live Paint: these paths are too degenerate to paint ライブペイント: これらのパスは形状がつぶれすぎていてペイントできません @msg Shape Builder: no region under the pointer シェイプ形成ツール: ポインターの下に領域がありません +@msg Fill Area: no enclosed area under the pointer 領域を塗りつぶし: ポインターの下に閉じた領域がありません @msg Shape Builder: select paths or compound paths シェイプ形成ツール: パスまたは複合パスを選択してください @msg image data `{_1}` is missing 画像データ `{_1}` が見つかりません @msg no Live Paint edge near that point その位置の近くにライブペイントのエッジがありません diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index d9d75dd737..45f0616852 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5196,6 +5196,8 @@ theme Appearance იერსახე Symbolism Tool სიმბოლოების ხელსაწყო Image Trace Presets გამოსახულების ვექტორიზაციის პრესეტები Live Paint Bucket ცოცხალი შეღებვის სათლი + Fill Area არის შევსება + Fill Area Tool არის შევსების ხელსაწყო Live Paint Bucket (Stroke) ცოცხალი შეღებვის სათლი (კონტური) Live Paint Info ცოცხალი შეღებვის ინფორმაცია Shape Builder ფიგურების კონსტრუქტორი @@ -6354,6 +6356,7 @@ font-technology Variable ცვლადი @msg Saved {path} შენახულია: {path} @msg Select text or click into text with the Type tool to insert glyphs გლიფების ჩასასმელად მონიშნეთ ტექსტი ან ტექსტის ხელსაწყოთი დაწკაპეთ ტექსტში @msg Shape Builder: no region under the pointer ფიგურების კონსტრუქტორი: მაჩვენებლის ქვეშ არე არ არის +@msg Fill Area: no enclosed area under the pointer არის შევსება: მაჩვენებლის ქვეშ დახურული არე არ არის @msg Shape Builder: select paths or compound paths ფიგურების კონსტრუქტორი: მონიშნეთ ტრაექტორიები ან შედგენილი ტრაექტორიები @msg Show All Hidden Attributes: nothing is hidden ყველა დამალული ატრიბუტის ჩვენება: დამალული არაფერია @msg Split Into Grid: select paths large enough for the grid ბადედ გაყოფა: მონიშნეთ ბადისთვის საკმარისად დიდი ტრაექტორიები diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 90f4e1f3fd..6ebaaa67bc 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -2267,6 +2267,8 @@ antiAlias Sharp 날카롭게 List View 목록 보기 List Workspaces 작업 영역 목록 Live Paint Bucket 라이브 페인트 통 + Fill Area 영역 채우기 + Fill Area Tool 영역 채우기 도구 Live Paint Bucket (Stroke) 라이브 페인트 통 (선) Live Paint Info 라이브 페인트 정보 Live Paint Selection Tool 라이브 페인트 선택 도구 @@ -4460,6 +4462,7 @@ theme Appearance 외관 @msg Live Paint: select paths or compound paths 라이브 페인트: 패스 또는 컴파운드 패스를 선택하세요 @msg Live Paint: these paths are too degenerate to paint 라이브 페인트: 이 패스는 퇴화되어 칠할 수 없습니다 @msg Shape Builder: no region under the pointer 모양 빌더: 포인터 아래에 영역이 없습니다 +@msg Fill Area: no enclosed area under the pointer 영역 채우기: 포인터 아래에 닫힌 영역이 없습니다 @msg Shape Builder: select paths or compound paths 모양 빌더: 패스 또는 컴파운드 패스를 선택하세요 @msg image data `{_1}` is missing 이미지 데이터 `{_1}`이(가) 없습니다 @msg no Live Paint edge near that point 그 지점 근처에 라이브 페인트 가장자리가 없습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 990e369f0f..f118f22f15 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -3788,6 +3788,8 @@ theme Appearance Vormgeving Symbolism Tool Symbolisatiegereedschap Image Trace Presets Voorinstellingen voor afbeeldingtracering Live Paint Bucket Live Paint-emmer + Fill Area Gebied vullen + Fill Area Tool Gereedschap Gebied vullen Live Paint Bucket (Stroke) Live Paint-emmer (streek) Live Paint Info Live Paint-info Shape Builder Vormopbouw @@ -4990,6 +4992,7 @@ imageTrace Outline Contour @msg Saved {path} {path} opgeslagen @msg Select text or click into text with the Type tool to insert glyphs Selecteer tekst of klik met het tekstgereedschap in tekst om glyphs in te voegen @msg Shape Builder: no region under the pointer Vormbouwer: geen gebied onder de aanwijzer +@msg Fill Area: no enclosed area under the pointer Gebied vullen: geen gesloten gebied onder de aanwijzer @msg Shape Builder: select paths or compound paths Vormbouwer: selecteer paden of samengestelde paden @msg Show All Hidden Attributes: nothing is hidden Alle verborgen kenmerken tonen: er is niets verborgen @msg Split Into Grid: select paths large enough for the grid In raster verdelen: selecteer paden die groot genoeg zijn voor het raster diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 647a0c62bd..f7900b61c5 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -3422,6 +3422,8 @@ theme Appearance Wygląd Symbolism Tool Narzędzie symboli Image Trace Presets Ustawienia obrysu obrazu Live Paint Bucket Wiadro aktywnego malowania + Fill Area Wypełnij obszar + Fill Area Tool Narzędzie Wypełnij obszar Live Paint Bucket (Stroke) Wiadro aktywnego malowania (obrys) Live Paint Info Informacje o aktywnym malowaniu Shape Builder Kreator kształtów @@ -4711,6 +4713,7 @@ imageTrace Outline Kontur @msg Saved {path} Zapisano {path} @msg Select text or click into text with the Type tool to insert glyphs Zaznacz tekst lub kliknij w tekst narzędziem Tekst, aby wstawić glify @msg Shape Builder: no region under the pointer Kreator kształtów: brak obszaru pod wskaźnikiem +@msg Fill Area: no enclosed area under the pointer Wypełnij obszar: brak zamkniętego obszaru pod wskaźnikiem @msg Shape Builder: select paths or compound paths Kreator kształtów: zaznacz ścieżki lub ścieżki złożone @msg Show All Hidden Attributes: nothing is hidden Pokaż wszystkie ukryte atrybuty: nic nie jest ukryte @msg Split Into Grid: select paths large enough for the grid Podziel na siatkę: zaznacz ścieżki wystarczająco duże dla siatki diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 2c0817772d..bc38bc7477 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -1658,6 +1658,8 @@ antiAlias Sharp Nítido List Workspaces Listar Espaços de Trabalho Live Paint Pintura ao Vivo Live Paint Bucket Balde de Pintura ao Vivo + Fill Area Preencher área + Fill Area Tool Ferramenta Preencher Área Live Paint Bucket (Stroke) Balde de Pintura ao Vivo (Traçado) Live Paint Info Informações da Pintura ao Vivo Live Paint Selection Tool Ferramenta Seleção de Pintura ao Vivo @@ -3954,6 +3956,7 @@ axis Both Ambos @msg Saved {path} {path} salvo @msg Select text or click into text with the Type tool to insert glyphs Selecione texto ou clique em um texto com a ferramenta Texto para inserir glifos @msg Shape Builder: no region under the pointer Criador de formas: nenhuma região sob o ponteiro +@msg Fill Area: no enclosed area under the pointer Preencher área: nenhuma área fechada sob o ponteiro @msg Shape Builder: select paths or compound paths Criador de formas: selecione traçados ou traçados compostos @msg Show All Hidden Attributes: nothing is hidden Mostrar todos os atributos ocultos: nada está oculto @msg Split Into Grid: select paths large enough for the grid Dividir em grade: selecione traçados grandes o bastante para a grade diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 28db02bb34..ddaf229a94 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -2003,6 +2003,8 @@ file-filter Templates Шаблоны List Workspaces Перечислить рабочие среды Live Paint Быстрая заливка Live Paint Bucket Быстрая заливка (ведро) + Fill Area Заливка области + Fill Area Tool Инструмент «Заливка области» Live Paint Bucket (Stroke) Быстрая заливка (обводка) Live Paint Info Сведения о быстрой заливке Live Paint Selection Tool Инструмент «Выделение быстрой заливки» @@ -4616,6 +4618,7 @@ axis Both Оба @msg Saved {path} Сохранено: {path} @msg Select text or click into text with the Type tool to insert glyphs Выделите текст или щёлкните внутри текста инструментом «Текст», чтобы вставить глифы @msg Shape Builder: no region under the pointer Создание фигур: под указателем нет области +@msg Fill Area: no enclosed area under the pointer Заливка области: под указателем нет замкнутой области @msg Shape Builder: select paths or compound paths Создание фигур: выделите контуры или составные контуры @msg Show All Hidden Attributes: nothing is hidden Показать все скрытые атрибуты: ничего не скрыто @msg Split Into Grid: select paths large enough for the grid Разделение на сетку: выделите контуры, достаточно большие для сетки diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 2f19e59397..ef3259a8bb 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1915,6 +1915,8 @@ font-technology Variable Variabla List Workspaces Lista arbetslayouter Live Paint Direktmålning Live Paint Bucket Direktmålningshink + Fill Area Fyll område + Fill Area Tool Verktyget Fyll område Live Paint Bucket (Stroke) Direktmålningshink (kontur) Live Paint Info Direktmålningsinfo Live Paint Selection Tool Markeringsverktyg för direktmålning @@ -4489,6 +4491,7 @@ axis Both Båda @msg Saved {path} Sparade {path} @msg Select text or click into text with the Type tool to insert glyphs Markera text eller klicka i text med textverktyget för att infoga glyfer @msg Shape Builder: no region under the pointer Formbyggare: inget område under pekaren +@msg Fill Area: no enclosed area under the pointer Fyll område: inget slutet område under pekaren @msg Shape Builder: select paths or compound paths Formbyggare: markera banor eller sammansatta banor @msg Show All Hidden Attributes: nothing is hidden Visa alla dolda attribut: ingenting är dolt @msg Split Into Grid: select paths large enough for the grid Dela upp i rutnät: markera banor som är tillräckligt stora för rutnätet diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 7639c326cb..41b181cbe5 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1802,6 +1802,8 @@ font-technology Variable Değişken List Workspaces Çalışma Alanlarını Listeleme Live Paint Canlı Boyama Live Paint Bucket Canlı Boyama Kovası + Fill Area Alanı Doldur + Fill Area Tool Alan Doldurma Aracı Live Paint Bucket (Stroke) Canlı Boya Kovası (Strok) Live Paint Info Canlı Boyama Bilgisi Live Paint Selection Tool Canlı Boyama Seçim Aracı @@ -4332,6 +4334,7 @@ axis Both Her İkisi @msg Saved {path} {path} kaydedildi @msg Select text or click into text with the Type tool to insert glyphs Glif eklemek için metni seçin veya Yazım aracıyla metne tıklayın @msg Shape Builder: no region under the pointer Şekil Oluşturucu: işaretçinin altında bölge yok +@msg Fill Area: no enclosed area under the pointer Alanı Doldur: işaretçinin altında kapalı alan yok @msg Shape Builder: select paths or compound paths Şekil Oluşturucu: yolları veya bileşik yolları seçin @msg Show All Hidden Attributes: nothing is hidden Tüm Gizli Özellikleri Göster: hiçbir şey gizli değildir @msg Split Into Grid: select paths large enough for the grid Izgaraya Böl: ızgara için yeterince büyük yollar seçin diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index b95631a14b..0d6ca7aabb 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -2006,6 +2006,8 @@ file-filter Templates Шаблони List Workspaces Перелічити робочі середовища Live Paint Швидка заливка Live Paint Bucket Швидка заливка (відро) + Fill Area Заливка області + Fill Area Tool Інструмент «Заливка області» Live Paint Bucket (Stroke) Швидка заливка (обведення) Live Paint Info Відомості про швидку заливку Live Paint Selection Tool Інструмент «Виділення швидкої заливки» @@ -4604,6 +4606,7 @@ axis Both Обидві @msg Saved {path} Збережено: {path} @msg Select text or click into text with the Type tool to insert glyphs Виділіть текст або клацніть всередині тексту інструментом «Текст», щоб вставити гліфи @msg Shape Builder: no region under the pointer Створення фігур: під вказівником немає області +@msg Fill Area: no enclosed area under the pointer Заливка області: під вказівником немає замкненої області @msg Shape Builder: select paths or compound paths Створення фігур: виділіть контури або складені контури @msg Show All Hidden Attributes: nothing is hidden Показати всі приховані атрибути: нічого не приховано @msg Split Into Grid: select paths large enough for the grid Поділ на сітку: виділіть контури, досить великі для сітки diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 3cc07d98cc..ab56736406 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -2308,6 +2308,8 @@ digits Hindi Hindi List Workspaces Liệt kê không gian làm việc Live Paint Tô trực tiếp Live Paint Bucket Xô Tô trực tiếp + Fill Area Tô vùng + Fill Area Tool Công cụ Tô vùng Live Paint Bucket (Stroke) Xô Tô trực tiếp (Nét) Live Paint Info Thông tin Tô trực tiếp Live Paint Selection Tool Công cụ Chọn Tô trực tiếp @@ -5495,6 +5497,7 @@ theme Appearance Giao diện @msg shadings of more than 4096 patches or triangles were left out các vùng tô có hơn 4096 mảnh hoặc tam giác đã bị bỏ qua @msg shadings whose functions are of an unknown type are filled with their middle colour các vùng tô có hàm loại không xác định được tô bằng màu giữa @msg Shape Builder: no region under the pointer Xây dựng hình dạng: không có vùng nào dưới con trỏ +@msg Fill Area: no enclosed area under the pointer Tô vùng: không có vùng kín nào dưới con trỏ @msg Shape Builder: select paths or compound paths Xây dựng hình dạng: chọn đường dẫn hoặc đường dẫn phức @msg shortcut for `{k}` must be a string phím tắt cho `{k}` phải là chuỗi @msg Show All Hidden Attributes: nothing is hidden Hiện tất cả thuộc tính ẩn: không có gì bị ẩn diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index f96d93d9ea..0583b22448 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1883,6 +1883,8 @@ file-filter Templates 模板 List Workspaces 列出工作区 Live Paint 实时上色 Live Paint Bucket 实时上色工具 + Fill Area 填充区域 + Fill Area Tool 填充区域工具 Live Paint Bucket (Stroke) 实时上色工具 (描边) Live Paint Info 实时上色信息 Live Paint Selection Tool 实时上色选择工具 @@ -4247,6 +4249,7 @@ imageTrace Outline 轮廓 @msg Live Paint: select paths or compound paths 实时上色:请选择路径或复合路径 @msg Live Paint: these paths are too degenerate to paint 实时上色:这些路径过于退化,无法上色 @msg Shape Builder: no region under the pointer 形状生成器:指针下方没有区域 +@msg Fill Area: no enclosed area under the pointer 填充区域:指针下方没有封闭区域 @msg Shape Builder: select paths or compound paths 形状生成器:请选择路径或复合路径 @msg image data `{_1}` is missing 缺少图像数据 `{_1}` @msg no Live Paint edge near that point 该点附近没有实时上色边缘 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 6a962013ca..5847a39151 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1892,6 +1892,7 @@ file-filter Templates 範本 @msg Live Paint: select paths or compound paths 即時上色:請選取路徑或複合路徑 @msg Live Paint: these paths are too degenerate to paint 即時上色:這些路徑過度退化,無法上色 @msg Shape Builder: no region under the pointer 形狀建立:指標下方沒有區域 +@msg Fill Area: no enclosed area under the pointer 填滿區域:指標下方沒有封閉區域 @msg Shape Builder: select paths or compound paths 形狀建立:請選取路徑或複合路徑 @msg image data `{_1}` is missing 找不到影像資料 `{_1}` @msg no Live Paint edge near that point 該點附近沒有即時上色邊緣 @@ -3073,6 +3074,8 @@ file-filter Templates 範本 List Workspaces 列出工作區 Live Paint 即時上色 Live Paint Bucket 即時上色油漆桶 + Fill Area 填滿區域 + Fill Area Tool 填滿區域工具 Live Paint Bucket (Stroke) 即時上色油漆桶 (筆畫) Live Paint Info 即時上色資訊 Live Paint Selection Tool 即時上色選取工具 diff --git a/crates/ui-egui/src/icon_data.rs b/crates/ui-egui/src/icon_data.rs index f521e45c22..5239fc05c0 100644 --- a/crates/ui-egui/src/icon_data.rs +++ b/crates/ui-egui/src/icon_data.rs @@ -82,6 +82,7 @@ pub static ICONS: &[(&str, &[u8])] = &[ ("dc-draw-inside", include_bytes!("../../../assets/icons/dc-draw-inside.svg")), ("dc-draw-normal", include_bytes!("../../../assets/icons/dc-draw-normal.svg")), ("dc-ellipse", include_bytes!("../../../assets/icons/dc-ellipse.svg")), + ("dc-fill-area", include_bytes!("../../../assets/icons/dc-fill-area.svg")), ("dc-fill-none", include_bytes!("../../../assets/icons/dc-fill-none.svg")), ("dc-filter", include_bytes!("../../../assets/icons/dc-filter.svg")), ("dc-flare", include_bytes!("../../../assets/icons/dc-flare.svg")), diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index e352653279..c795aeb7ee 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -77,6 +77,7 @@ pub fn tool_icon(name: &str) -> &'static str { "tool-puppet" => "dc-puppet", "tool-shape-builder" => "dc-shape-builder", "tool-bucket" => "dc-live-bucket", + "tool-fill-area" => "dc-fill-area", "tool-live-select" => "dc-live-select", "tool-perspective" => "dc-perspective", "tool-perspective-select" => "dc-perspective", diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 5b73f36ab6..2a8771f37c 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -980,7 +980,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.options", "Tool Options…", "", - "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront and filledLines held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool, diameter (pt), intensity and density (1–10), shared by the eight tools; OK runs tool.setOption {tool, values}), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", + "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront and filledLines held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool, diameter (pt), intensity and density (1–10), shared by the eight tools; OK runs tool.setOption {tool, values}), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), fillArea → the same Shape Builder Tool Options (Fill Area uses their gapDetection, gapLength and openFilledAsClosed), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", ), ( "ui.colorGuideOptions", diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index c4da70d84f..ae8f74abc4 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -58,7 +58,7 @@ pub const BASIC: &[(&str, &[&[&str]])] = &[ &[ &["width", "warp", "twirl", "pucker", "bloat", "scallop", "crystallize", "wrinkle"], &["rotate", "reflect", "scale", "shear", "reshape", "freeTransform", "puppetWarp"], - &["shapeBuilder", "livePaintBucket", "livePaintSelection", "blend"], + &["shapeBuilder", "livePaintBucket", "fillArea", "livePaintSelection", "blend"], &["dimension"], ], ), @@ -454,7 +454,8 @@ pub fn open_options(app: &mut VectorcraftApp, tool: &str) -> Result Ok(crate::dialogs::shape_builder_options::open(app)), + // Fill Area uses the Shape Builder's Gap Detection and open-filled-path options. + "shapeBuilder" | "fillArea" => Ok(crate::dialogs::shape_builder_options::open(app)), // The Objects on Path tool: the Pivot and Rotate of the objects it attaches next. "objectsOnPath" => Ok(crate::dialogs::objects_on_path_options::open(app)), // The Line Segment, Arc and grid tools: their Tool Options, the options of their next diff --git a/docs/mcp.md b/docs/mcp.md index 7bbc2f4cb7..340479d26f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2024,7 +2024,7 @@ and `type.fractionalWidths`; `flip` in `type.dynamicTextPreset`; `remove` and `o `swatch.addUsedColors`; `visible` in `appearance.setItem`; `copy` in `appearance.transfer`; `reverse` and `append` in `appearance.copyFrom`; `reverse` and `stroke` in `paint.editGradient`; `stroke` in `paint.setGradientGeom` and in `paint.freeform.addPoint`, `setPoint`, `deletePoint`, `addLine`, `splitLine` and `get`; `erase`, -`openFilledAsClosed` and `splitStroke` in `shapeBuilder.merge`; `openFilledAsClosed` in `shapeBuilder.regions`; `closeGaps` in `livePaint.gapOptions`; and +`openFilledAsClosed` and `splitStroke` in `shapeBuilder.merge`; `openFilledAsClosed` in `shapeBuilder.regions` and `shapeBuilder.copyRegion`; `closeGaps` in `livePaint.gapOptions`; and `enhanced` in `imageTrace.make` and `imageTrace.makeAndExpand`. A null is read as a key left out. These commands refuse a string or another value that is not a number with `` `radius` must be a number, not "2" ``, @@ -2043,7 +2043,7 @@ and `fitMinPercent` in `text.areaOptions`; `x` and `y` in `symbol.place`; `radiu `symbol.spray`; `radius` and `intensity` in `symbol.adjust`; `to` in `swatch.move`; `weight` and `opacity` in `appearance.setItem`; `r`, `g`, `b`, `c`, `m`, `y`, `k`, `gray` and `tint` in `edit.colors.adjustBalance`; `steps` and `amount` in `color.harmony`; `angle` in `paint.editGradient` and in the `gradient` of a command that takes a paint; `t` in -`paint.freeform.splitLine`; `tolerance` and `gap` in `shapeBuilder.merge`; `gap` in `shapeBuilder.regions`; and +`paint.freeform.splitLine`; `tolerance` and `gap` in `shapeBuilder.merge`; `gap` in `shapeBuilder.regions` and `shapeBuilder.copyRegion`; and `width` and `tolerance` in `livePaint.strokeEdge`. A null is read as a key left out. A gradient stop that names a swatch refuses a `tint` that is not a number with `` stop 0: `tint` must be a number ``. @@ -11032,6 +11032,29 @@ a stroke when it has `rect`. With both `rect` and `points`, the command also tou {"name":"run_command","arguments":{"command":"shapeBuilder.merge","params":{"rect":[50,50,200,200]}}} ``` +The Fill Area tool (`fillArea`, in the Live Paint Bucket's group) adds a new closed path of the area under a click +and leaves the paths around it as they are. Nothing needs to be selected: the visible, unlocked paths on every layer +bound areas, filled or not, open paths included, and the overlap of two filled shapes is an area of its own. While the +pointer hovers an area, the tool outlines it in red and the pointer shows the bucket with paint; elsewhere the pointer +shows the empty bucket, and a click there does nothing. The new path appears on the press and is kept on the release; +Escape or a canceled touch before the release takes it back. In a document of more than 128 path segments the tool looks +for the hovered area on another thread, and the outline appears when that search is done. The tool sends `shapeBuilder.copyRegion` with `point`, the Shape Builder's gap +length (`gap`, 0 with Gap Detection off) and its `openFilledAsClosed`: the two tools share `gapDetection`, `gapLength` +and `openFilledAsClosed`, so `tool.setOption` on either one sets them for both, and `fillArea` has no other options. +Double-clicking the Fill Area tool opens the Shape Builder Tool Options (`tool.options {tool: "fillArea"}`, dialog +`shapeBuilderOptions`). +The new path takes the current fill, stroke and stroke weight (`fill` and `stroke` override the paints), goes directly +above the front-most object along the area (one whose outline touches the area's outline, or that covers it) and is +selected. When a group, Live Paint group, Shaper group or clipping group holds that object, the new path goes above the +outermost group in its layer, not inside it, and the group keeps its members. A point in no enclosed area is the error "Fill Area: no enclosed area under the pointer" and records no undo +step; a `gap` outside 0 to 72 is an error. It returns `{id, above}`. The command looks for the area among the paths +near the point first. When the paths together have more than 65,536 segments and the paths near the point do not +enclose it, the point counts as in no enclosed area. + +```json +{"name":"run_command","arguments":{"command":"shapeBuilder.copyRegion","params":{"point":[50,70],"gap":3}}} +``` + ## Perspective grid The grid is document data (`perspective.grid.set` edits the model directly). `perspective.grid.get` reads it: diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 21b0074bbd..a95061c53c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1267,6 +1267,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur As VectorCraft's own rule, OK in Shape Builder Tool Options gives an error for a highlight Color with an alpha part (`#rrggbbaa` or `#rgba`) and changes nothing. Regression test: `dialogs::shape_builder_options::tests::a_highlight_color_with_an_alpha_part_is_refused`. With Pick Color From Artwork, a merged shape takes the appearance, opacity and blending mode of the object where the drag starts, else of the object where it ends, else of the front-most selected object, as the [Shape Builder combine page](https://web.archive.org/web/20251006211643/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/combine-shapes-with-shape-builder-tool.html) describes. A click in an area that no selected object covers, such as a hole other shapes enclose, takes the front-most selected object's look (`shapeBuilder.merge` `points`: the first point is where the drag starts, and the last point is where it ends). A Shift-drag with the Shape Builder tool draws a rectangular marquee for merging many paths at once, as [Combine shapes with the Shape Builder tool](https://web.archive.org/web/20251006211643/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/combine-shapes-with-shape-builder-tool.html) describes: the regions it reaches are shaded while it is drawn and merge into one shape on release, or with Alt they are deleted. The marquee reaches each region whose outline crosses it or has an anchor inside it, and the region that holds the whole marquee; this rule is VectorCraft's own. For Pick Color From Artwork, the marquee's starting corner is where the drag starts and the opposite corner is where it ends (`shapeBuilder.merge` `rect`). + As VectorCraft's own tool, Fill Area (in the Live Paint Bucket's group) adds a new closed path of the area under a click with the current fill and stroke, directly above the front-most object along it, and leaves the paths around it as they are. It needs no selection: the visible, unlocked paths on every layer bound areas, open paths and the overlap of filled shapes included, and it uses the Shape Builder's Gap Detection (`shapeBuilder.copyRegion`). Regression tests: `tests::fill_area::*`. Shape Builder pieces on dense hatches (lines at exact 0.25 or 0.5 pt steps across another line) come back one per stretch between crossings, with no speck where the sweep cut a line's two passes a rounding error apart: the planar map contracts the stub between such cuts into one vertex, bounded by each cluster's extent so a run of tiny level segments keeps its length (`crates/pathops/src/planar.rs` tests `a_dense_hatch_at_exact_binary_steps_cuts_each_line_once_per_crossing`, `a_run_of_tiny_level_segments_is_not_contracted_as_stubs`, `a_line_crossed_where_its_two_passes_part_is_cut_once`). The planar map's edge-source grid stays linear in memory on any input: a segment is filed once per cell it crosses, and the grid holds at most a budget of cell references (a few dozen per item plus a few rows' worth), past which the remaining items go to a short scanned list and are still found, so thousands of coincident segments cannot make the index quadratic (`crates/pathops/src/planar.rs` test `rect_index_holds_a_bounded_number_of_references`). The Blob Brush Tool Options have Keep selected and Merge only with selection, both off by default: while Keep selected is off, the blob a stroke draws or merges into is not selected afterwards, and while Merge only with selection is on, a stroke merges only with selected blobs of its color that it touches (`path.blob` `keepSelected` and `mergeOnlySelection`). From 6fed8b22f2b4a8047433e295348b4888e06d66be Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 16:48:27 -0800 Subject: [PATCH 02/10] Docs: the M12 milestone row names the Fill Area tool --- docs/roadmap.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/roadmap.md b/docs/roadmap.md index da1645efb2..f869de1e01 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -168,7 +168,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | M9 | Live effects (+ 3D & Materials) | 🟡 2D effects done incl. Effect → Pathfinder, Color Adjustments and Document Raster Effects Settings; PDF export warns when the pixel cap lowers raster-effect resolution; Artistic › Colored Pencil, Cutout, Dry Brush, Film Grain, Fresco, Neon Glow, Paint Daubs, Palette Knife, Poster Edges, Rough Pastels, Smudge Stick, Sponge, Underpainting and Watercolor and Sketch › Halftone Pattern, Bas Relief, Charcoal, Conté Crayon, Photocopy, Stamp, Torn Edges and Water Paper done (57/57 Photoshop filters); Revolve with automatic smooth vector shading, default-on circular caps and continuous rims, Extrude & Bevel, Inflate and Rotate with one to ten colored directional lights and four original lighting presets; SVG Filters, remaining raster effects and 3D materials and shadows pending | 81–130 | | M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, six generated libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, Weather Icons), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, ten generated libraries including Tech Circuit, Ink and Wash, Bristle Brushes and Dry Media, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | | M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View, middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | -| M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color, Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369); Live Paint Bucket fills faces crossed in one drag (#6373) | 6–10 | +| M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color, Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369); Live Paint Bucket fills faces crossed in one drag (#6373); the Fill Area tool in the Live Paint Bucket group adds a path of the area a click encloses and keeps the paths around it | 6–10 | | M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; the script document model and batch work remain | 18–27 | | M14 | 1.0 polish (preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326; a release more than 1 pt from the press keeps the caret, a tap within 1 pt selects all, #6659); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset , UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307); Swatches item context menus tested in all five views and rendered layouts inspected; Linux full CI passed, Windows engine baseline limitations documented (G12) | 18–28 | | — | Interaction fidelity pass (every tool's modifiers, Properties panel per context, isolation, nuance; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed) | ⬜ (new ruler-guide Alt orientation implemented; existing-guide Escape cancellation regression-tested; broader pass remains) | 60–90 | From 94fee63cc15d8dd90b0fb9c0307cd4a39db645e2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 18:32:27 -0800 Subject: [PATCH 03/10] Fill Area: the large-document test presses while a hover search runs The pointer leaves the area to start a search on another thread before the press, so the test covers a click that waits for that search, and it checks that the press settles it. --- crates/engine/src/tests/fill_area.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/tests/fill_area.rs b/crates/engine/src/tests/fill_area.rs index 98c5dc34db..aebf2323a4 100644 --- a/crates/engine/src/tests/fill_area.rs +++ b/crates/engine/src/tests/fill_area.rs @@ -497,10 +497,13 @@ fn fill_area_tool_hovers_a_large_document_on_another_thread() { s.pointer(&PointerEvent::new(PointerKind::Move, 300.0, 300.0), v).unwrap(); s.tool_poll(v, true).unwrap(); assert_eq!(s.overlays(v).len(), 1); - // A click while a search runs waits for it. - s.pointer(&PointerEvent::new(PointerKind::Move, 310.0, 300.0), v).unwrap(); + // A click while a search runs waits for it: the pointer leaves the area, which starts a + // search, and the press inside the area comes before any poll. + s.pointer(&PointerEvent::new(PointerKind::Move, 500.0, 500.0), v).unwrap(); + assert!(s.tool_waiting()); let undo = undo_len(&s); s.pointer(&PointerEvent::new(PointerKind::Down, 310.0, 300.0), v).unwrap(); + assert!(!s.tool_waiting(), "the press waited for the search"); s.pointer(&PointerEvent::new(PointerKind::Up, 310.0, 300.0), v).unwrap(); assert_eq!(undo_len(&s), undo + 1); } From af868f2de6f7c7d27cb9e868c9d2ec76e5d746ce Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 18:53:58 -0800 Subject: [PATCH 04/10] Fill Area: a left-out path cuts an area only when one of its segments reaches it A path with too many segments for a window's map is left out of it. The finder treated such a path as cutting the area whenever its bounding box met the area, so a path made of subpaths far apart on either side of an area made the finder map every path, which fails past the segment limit, and the area could not be filled. The finder now checks the path's segments. --- crates/engine/src/tests/fill_area.rs | 26 ++++++++++++++++++++++++++ crates/tools/src/builder/fill_area.rs | 12 +++++++++++- 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/tests/fill_area.rs b/crates/engine/src/tests/fill_area.rs index aebf2323a4..c0501ea786 100644 --- a/crates/engine/src/tests/fill_area.rs +++ b/crates/engine/src/tests/fill_area.rs @@ -316,6 +316,32 @@ fn fill_area_does_not_fill_across_a_huge_path_it_left_out() { } } +/// A path with too many segments whose subpaths lie far apart on either side of the square has a box +/// that holds the square, but no segment of it comes near: it is left out and the square is filled. +#[test] +fn fill_area_fills_an_area_that_a_left_out_paths_box_holds_but_its_segments_miss() { + let mut s = session(); + line(&mut s, (-20.0, 0.0), (420.0, 0.0)); + line(&mut s, (-20.0, 400.0), (420.0, 400.0)); + line(&mut s, (0.0, -20.0), (0.0, 420.0)); + line(&mut s, (400.0, -20.0), (400.0, 420.0)); + let n = vectorcraft_pathops::SHAPE_BUILDER_MAX_SEGMENTS; + let pts: Vec = (0..=n).map(|k| Point::new(-2000.0 + 400.0 * k as f64 / n as f64, -1000.0 + (k % 2) as f64)).collect(); + let far = [Point::new(2000.0, 1500.0), Point::new(2100.0, 1500.0)]; + let path = PathData::new(vec![vectorcraft_geom::SubPath::polyline(&pts, false), vectorcraft_geom::SubPath::polyline(&far, false)]); + let look = vectorcraft_doc::Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0); + s.edit("t", |d, _| { + let id = d.alloc_id(); + let top = d.children(d.default_layer()).map_or(0, |c| c.len()); + d.insert(d.default_layer(), top, Node::path(id, path, look))?; + Ok(id) + }) + .unwrap(); + deselect(&mut s); + let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [200, 200]})).unwrap(); + assert!((area(&s, id_of(&r)) - 160_000.0).abs() < 1.0, "{}", area(&s, id_of(&r))); +} + /// With Gap Detection on, a square on a higher layer within the gap of the area's corners does not /// bound the area, so the new path stays above the square that does. #[test] diff --git a/crates/tools/src/builder/fill_area.rs b/crates/tools/src/builder/fill_area.rs index d4b841b9ca..cac964bf19 100644 --- a/crates/tools/src/builder/fill_area.rs +++ b/crates/tools/src/builder/fill_area.rs @@ -2,6 +2,8 @@ //! closed path of that area with the current fill and stroke (`shapeBuilder.copyRegion`). The //! paths around the area stay as they are, and nothing needs to be selected. +use vectorcraft_geom::path::segment_bounds; + use super::lookup::path_contains; use super::*; @@ -63,6 +65,13 @@ fn meet(a: &Rect, b: &Rect) -> bool { a.x0 <= b.x1 && b.x0 <= a.x1 && a.y0 <= b.y1 && b.y0 <= a.y1 } +/// Does a segment of `path` (closing segments included) meet `zone`? A path whose box meets the zone +/// may still lie wholly outside it, as a path of subpaths far apart does. +fn reaches(path: &PathData, zone: &Rect) -> bool { + let bez = path.to_bezpath(); + vectorcraft_geom::kurbo::segments(bez.elements().iter().copied()).any(|seg| meet(&segment_bounds(seg), zone)) +} + /// Does `outer` hold all of `inner`? fn within(inner: &Rect, outer: &Rect) -> bool { inner.x0 >= outer.x0 && inner.x1 <= outer.x1 && inner.y0 >= outer.y0 && inner.y1 <= outer.y1 @@ -159,7 +168,8 @@ impl AreaFinder { // path holds both. Some(rb) if within(&rb, &window) => { let reached = rb.inflate(reach, reach); - let cut = any_left_out && self.inputs.iter().zip(&left_out).any(|((_, b, _), out)| *out && meet(b, &reached)); + let cut = any_left_out + && self.inputs.iter().zip(&left_out).any(|((s, b, _), out)| *out && meet(b, &reached) && reaches(&s.path, &reached)); if !cut { return self.area_in(&map, &picked, p); } From a071c38769cc173575a9734d7718e327a0a3d8ba Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 19:12:17 -0800 Subject: [PATCH 05/10] Shape Builder: a fill or stroke object that is not a paint is an error A fill or stroke such as {"swatch": 123} gave no paint, so shapeBuilder.copyRegion and shapeBuilder.merge used the current paint. Both commands now report it as a bad fill or stroke. --- crates/engine/src/cmd/buildcmds.rs | 3 ++- crates/engine/src/tests/fill_area.rs | 6 ++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs index e5d45fdc92..51f44ce479 100644 --- a/crates/engine/src/cmd/buildcmds.rs +++ b/crates/engine/src/cmd/buildcmds.rs @@ -279,7 +279,8 @@ fn paint_param(s: &Session, p: &Value, key: &str, cmd: &str) -> Result Ok(None), Some(v @ Value::Object(o)) if o.contains_key("color") || o.contains_key("swatch") || o.contains_key("gradient") || o.contains_key("none") => { - paint_from(s, v) + // A paint key whose value is not a paint, such as `{"swatch": 123}`, gives no paint. + paint_from(s, v)?.map(Some).ok_or_else(|| bad(cmd, format!("bad {key} {v}"))) } Some(v) => color_value(v).map(|c| Some(Paint::solid(super::paint::new_color(s, p, c)))).ok_or_else(|| bad(cmd, format!("bad {key} {v}"))), } diff --git a/crates/engine/src/tests/fill_area.rs b/crates/engine/src/tests/fill_area.rs index c0501ea786..4de5171bff 100644 --- a/crates/engine/src/tests/fill_area.rs +++ b/crates/engine/src/tests/fill_area.rs @@ -453,6 +453,12 @@ fn fill_area_outside_every_area_changes_nothing() { for p in [json!({}), json!({"point": [50]}), json!({"point": [50, 70], "fill": "nope"}), json!({"point": [50, 70], "stroke": 3})] { assert!(s.execute("shapeBuilder.copyRegion", &p).is_err(), "{p}"); } + for paint in [json!({"swatch": 123}), json!({"color": 5}), json!({"color": "nope"})] { + for key in ["fill", "stroke"] { + let p = json!({"point": [50, 70], key: paint}); + assert!(s.execute("shapeBuilder.copyRegion", &p).is_err(), "{p}"); + } + } assert!(s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 70], "ids": [999_999]})).is_err()); assert_eq!((undo_len(&s), stack(&s)), (undo, kids)); } From c860bf27eff59a70ea15737947c744dc8561d0cc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 19:30:15 -0800 Subject: [PATCH 06/10] Fill Area: a left-out curve cuts an area only where it reaches it A segment's box can meet an area while the segment does not, as with a diagonal line or a curve that arcs around the area. The finder now halves such a segment until a piece has an end in the area, its box misses it, or it is smaller than 0.01 pt. --- crates/engine/src/tests/fill_area.rs | 51 +++++++++++++++------------ crates/tools/src/builder/fill_area.rs | 26 ++++++++++++-- 2 files changed, 53 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/tests/fill_area.rs b/crates/engine/src/tests/fill_area.rs index 4de5171bff..0b00ddf954 100644 --- a/crates/engine/src/tests/fill_area.rs +++ b/crates/engine/src/tests/fill_area.rs @@ -316,30 +316,37 @@ fn fill_area_does_not_fill_across_a_huge_path_it_left_out() { } } -/// A path with too many segments whose subpaths lie far apart on either side of the square has a box -/// that holds the square, but no segment of it comes near: it is left out and the square is filled. +/// A path with too many segments whose box holds the square, but no segment of it comes near: its +/// subpaths lie far apart on either side of the square, or one curve arcs around the square and its +/// box holds the square. It is left out and the square is filled. #[test] fn fill_area_fills_an_area_that_a_left_out_paths_box_holds_but_its_segments_miss() { - let mut s = session(); - line(&mut s, (-20.0, 0.0), (420.0, 0.0)); - line(&mut s, (-20.0, 400.0), (420.0, 400.0)); - line(&mut s, (0.0, -20.0), (0.0, 420.0)); - line(&mut s, (400.0, -20.0), (400.0, 420.0)); - let n = vectorcraft_pathops::SHAPE_BUILDER_MAX_SEGMENTS; - let pts: Vec = (0..=n).map(|k| Point::new(-2000.0 + 400.0 * k as f64 / n as f64, -1000.0 + (k % 2) as f64)).collect(); - let far = [Point::new(2000.0, 1500.0), Point::new(2100.0, 1500.0)]; - let path = PathData::new(vec![vectorcraft_geom::SubPath::polyline(&pts, false), vectorcraft_geom::SubPath::polyline(&far, false)]); - let look = vectorcraft_doc::Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0); - s.edit("t", |d, _| { - let id = d.alloc_id(); - let top = d.children(d.default_layer()).map_or(0, |c| c.len()); - d.insert(d.default_layer(), top, Node::path(id, path, look))?; - Ok(id) - }) - .unwrap(); - deselect(&mut s); - let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [200, 200]})).unwrap(); - assert!((area(&s, id_of(&r)) - 160_000.0).abs() < 1.0, "{}", area(&s, id_of(&r))); + // A cubic from (-1000, 1500) up over the square to (1400, 1500); at its top it is at y -750. + let mut arc = vectorcraft_geom::SubPath::polyline(&[Point::new(-1000.0, 1500.0), Point::new(1400.0, 1500.0)], false); + arc.anchors[0].h_out = Point::new(-1000.0, -1500.0); + arc.anchors[1].h_in = Point::new(1400.0, -1500.0); + let far = vectorcraft_geom::SubPath::polyline(&[Point::new(2000.0, 1500.0), Point::new(2100.0, 1500.0)], false); + for second in [far, arc] { + let mut s = session(); + line(&mut s, (-20.0, 0.0), (420.0, 0.0)); + line(&mut s, (-20.0, 400.0), (420.0, 400.0)); + line(&mut s, (0.0, -20.0), (0.0, 420.0)); + line(&mut s, (400.0, -20.0), (400.0, 420.0)); + let n = vectorcraft_pathops::SHAPE_BUILDER_MAX_SEGMENTS; + let pts: Vec = (0..=n).map(|k| Point::new(-2000.0 + 400.0 * k as f64 / n as f64, -1000.0 + (k % 2) as f64)).collect(); + let path = PathData::new(vec![vectorcraft_geom::SubPath::polyline(&pts, false), second.clone()]); + let look = vectorcraft_doc::Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0); + s.edit("t", |d, _| { + let id = d.alloc_id(); + let top = d.children(d.default_layer()).map_or(0, |c| c.len()); + d.insert(d.default_layer(), top, Node::path(id, path, look))?; + Ok(id) + }) + .unwrap(); + deselect(&mut s); + let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [200, 200]})).unwrap(); + assert!((area(&s, id_of(&r)) - 160_000.0).abs() < 1.0, "{second:?}: {}", area(&s, id_of(&r))); + } } /// With Gap Detection on, a square on a higher layer within the gap of the area's corners does not diff --git a/crates/tools/src/builder/fill_area.rs b/crates/tools/src/builder/fill_area.rs index cac964bf19..a3950fd997 100644 --- a/crates/tools/src/builder/fill_area.rs +++ b/crates/tools/src/builder/fill_area.rs @@ -3,6 +3,7 @@ //! paths around the area stay as they are, and nothing needs to be selected. use vectorcraft_geom::path::segment_bounds; +use vectorcraft_geom::{ParamCurve, PathSeg}; use super::lookup::path_contains; use super::*; @@ -66,10 +67,31 @@ fn meet(a: &Rect, b: &Rect) -> bool { } /// Does a segment of `path` (closing segments included) meet `zone`? A path whose box meets the zone -/// may still lie wholly outside it, as a path of subpaths far apart does. +/// may still lie wholly outside it, as a path of subpaths far apart, a diagonal line or a curve +/// that arcs around the zone does. fn reaches(path: &PathData, zone: &Rect) -> bool { let bez = path.to_bezpath(); - vectorcraft_geom::kurbo::segments(bez.elements().iter().copied()).any(|seg| meet(&segment_bounds(seg), zone)) + vectorcraft_geom::kurbo::segments(bez.elements().iter().copied()).any(|seg| segment_reaches(seg, zone, 0)) +} + +/// How many times [`segment_reaches`] halves a segment: a piece of 1/2^24 of a segment counts as +/// meeting the zone when its box does. +const REACH_SPLITS: u32 = 24; + +/// The side (pt) below which a piece of a segment whose box meets the zone counts as meeting it. +const REACH_TOLERANCE: f64 = 0.01; + +/// Does `seg` meet `zone`? Its halves are checked in turn while their boxes meet the zone and +/// neither end is in it; a piece smaller than [`REACH_TOLERANCE`] whose box meets the zone counts. +fn segment_reaches(seg: PathSeg, zone: &Rect, depth: u32) -> bool { + let b = segment_bounds(seg); + if !meet(&b, zone) { + return false; + } + if holds(zone, seg.start()) || holds(zone, seg.end()) || depth >= REACH_SPLITS || b.width().max(b.height()) < REACH_TOLERANCE { + return true; + } + segment_reaches(seg.subsegment(0.0..0.5), zone, depth + 1) || segment_reaches(seg.subsegment(0.5..1.0), zone, depth + 1) } /// Does `outer` hold all of `inner`? From 735de46552f235a2843c021e1342d898ac79c0e4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 17:54:18 -0800 Subject: [PATCH 07/10] Fill Area: tool.setOption accepts the Shape Builder options it shares main now checks every option tool.setOption gets against the tool before setting any, and a tool without its own check rejects every option. The Fill Area tool now checks its options with check_builder_options, as the Shape Builder does, so gapDetection, gapLength and openFilledAsClosed are accepted again and other keys or bad values are still errors. --- crates/tools/src/builder/fill_area.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/tools/src/builder/fill_area.rs b/crates/tools/src/builder/fill_area.rs index a3950fd997..f38c69b723 100644 --- a/crates/tools/src/builder/fill_area.rs +++ b/crates/tools/src/builder/fill_area.rs @@ -552,4 +552,7 @@ impl Tool for FillAreaTool { } self.hover = None; } + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + check_builder_options(self.id(), &serde_json::Map::from_iter([(key.to_string(), v.clone())])) + } } From efadb7ee0d2edb138cf00078da7513abe1674e6f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 20:52:26 -0800 Subject: [PATCH 08/10] Fill Area: in isolation mode only the isolated group's paths bound areas With a group or layer isolated, the tool's hover and click and shapeBuilder.copyRegion take only the paths inside it, and the new path goes inside it, directly above the object in it that holds the front-most path along the area. Before, a click on art outside the isolated group added a path there. No area is found while the isolated object is a path or compound path, a group that makes, moves or combines its own art (Live Paint, compound shapes, Shaper groups, graphs, Image Trace results, dimensions, flares, Objects on Path), a layer or group with a live effect, a clipping mask, or an object inside one of these or inside an envelope. An isolated object that no longer exists counts as no isolation, for the tool as for the command. --- crates/engine/src/cmd/buildcmds.rs | 2 +- .../engine/src/cmd/buildcmds/shape_builder.rs | 14 +- crates/engine/src/tests/fill_area.rs | 131 ++++++++++++++++++ crates/tools/src/builder.rs | 2 +- crates/tools/src/builder/fill_area.rs | 113 ++++++++++++--- docs/mcp.md | 8 +- docs/target-app-parity.md | 2 +- 7 files changed, 243 insertions(+), 29 deletions(-) diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs index 8f9a828885..3136b52e42 100644 --- a/crates/engine/src/cmd/buildcmds.rs +++ b/crates/engine/src/cmd/buildcmds.rs @@ -73,7 +73,7 @@ pub fn specs() -> Vec { "Fill Area", [], None, - "{point: [x,y], ids?|id?: [id…] (the objects or layers whose paths bound areas; default: every layer, nothing needs to be selected), gap?: pt (0–72; 0: Gap Detection off; out of range is an error), openFilledAsClosed?: true (as shapeBuilder.merge), fill?, stroke?: \"#rrggbb\" | {color|swatch|gradient|none} (default: the current fill and stroke, with the current stroke weight)} add a new closed path of the area under point that the visible, unlocked paths enclose (the region of shapeBuilder.regions holding it: areas a shape already fills and areas open paths bound count too), directly above the front-most object along the area (its outline touches the area's outline, or it covers the area; when a group, Live Paint group, Shaper group or clipping group holds that path, above the outermost group in its layer, never inside it), and select it; the paths around the area are not changed; a point in no enclosed area is an error and changes nothing (no undo step); when the paths together have more than 65,536 segments, only an area the paths near the point enclose is found → {id, above (the object the new path went above)}", + "{point: [x,y], ids?|id?: [id…] (the objects or layers whose paths bound areas; default: every layer, nothing needs to be selected), gap?: pt (0–72; 0: Gap Detection off; out of range is an error), openFilledAsClosed?: true (as shapeBuilder.merge), fill?, stroke?: \"#rrggbb\" | {color|swatch|gradient|none} (default: the current fill and stroke, with the current stroke weight)} add a new closed path of the area under point that the visible, unlocked paths enclose (the region of shapeBuilder.regions holding it: areas a shape already fills and areas open paths bound count too), directly above the front-most object along the area (its outline touches the area's outline, or it covers the area; when a group, Live Paint group, Shaper group or clipping group holds that path, above the outermost group in its layer, never inside it), and select it; in isolation mode only the paths of the isolated layer or group bound areas (with ids, only the paths of the listed objects that are in it), and the new path goes inside it, directly above the object in it that holds that path; no area is found while the isolated object is not a layer or group (a path or compound path), is a Live Paint group, compound shape, Shaper group, graph, Image Trace result, dimension, flare or Objects on Path group, is a layer or group with a live effect or a clipping mask, or lies inside one of these or inside an envelope; the paths around the area are not changed; a point in no enclosed area is an error and changes nothing (no undo step); when the paths together have more than 65,536 segments, only an area the paths near the point enclose is found → {id, above (the object the new path went above)}", has_doc, sb_copy_region ), diff --git a/crates/engine/src/cmd/buildcmds/shape_builder.rs b/crates/engine/src/cmd/buildcmds/shape_builder.rs index a24d04bcda..626efb44b1 100644 --- a/crates/engine/src/cmd/buildcmds/shape_builder.rs +++ b/crates/engine/src/cmd/buildcmds/shape_builder.rs @@ -195,18 +195,22 @@ pub(super) fn sb_copy_region(s: &mut Session, p: &Value) -> Result { let stroke = paint_param(s, p, "stroke", C)?.unwrap_or_else(|| s.paint.stroke.clone()); let look = s.new_art_look(fill, stroke, s.paint.stroke_width); let area = { - let d = &s.doc()?.doc; - let roots = match named_ids(p)? { + let st = s.doc()?; + let d = &st.doc; + let named = match named_ids(p)? { Some(ids) => { if let Some(bad_id) = ids.iter().find(|i| d.node(**i).is_none()) { return Err(EngineError::NoNode(*bad_id)); } // An object listed with a layer or group that holds it counts once. - outermost(d, ids) + Some(outermost(d, ids)) } - None => b::every_layer(d), + None => None, }; - b::AreaFinder::new(d, &roots, gap, open_filled_as_closed).find(pt) + // In isolation mode only the isolated layer or group's paths bound areas, and the new path + // goes inside it. + b::fill_area_roots(d, st.isolation, named.as_deref()) + .and_then(|(roots, scope)| b::AreaFinder::new(d, &roots, scope, gap, open_filled_as_closed).find(pt)) }; let Some(area) = area else { return Err(EngineError::Other("Fill Area: no enclosed area under the pointer".into())) }; let id = s.edit("Fill Area", |d, sel| { diff --git a/crates/engine/src/tests/fill_area.rs b/crates/engine/src/tests/fill_area.rs index 0b00ddf954..7ba4bcc26f 100644 --- a/crates/engine/src/tests/fill_area.rs +++ b/crates/engine/src/tests/fill_area.rs @@ -189,6 +189,137 @@ fn fill_area_stacks_above_the_group_that_holds_the_paths() { assert_eq!(members(&s, clip), before); } +/// In isolation mode only the isolated group's paths bound areas, for the command and the tool: a +/// click in an area that art outside the group encloses adds nothing, and the new path goes inside +/// the group, above the path along the area. +#[test] +fn fill_area_stays_inside_the_isolated_group() { + let mut s = session(); + let outside = + [line(&mut s, (200.0, 0.0), (300.0, 100.0)), line(&mut s, (300.0, 0.0), (200.0, 100.0)), line(&mut s, (190.0, 80.0), (310.0, 80.0))]; + let lines = triangle(&mut s); + let ids: Vec = lines.iter().map(|l| l.0).collect(); + s.execute("select.set", &json!({"ids": ids})).unwrap(); + let g = id_of(&s.execute("object.group", &json!({})).unwrap()); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + deselect(&mut s); + let members = |s: &Session| -> Vec { node(s, g).children().unwrap().iter().map(|n| n.id).collect() }; + let (undo, kids) = (undo_len(&s), stack(&s)); + assert!(s.execute("shapeBuilder.copyRegion", &json!({"point": [250, 70]})).is_err(), "art outside the isolated group"); + let named: Vec = outside.iter().map(|l| l.0).collect(); + assert!(s.execute("shapeBuilder.copyRegion", &json!({"point": [250, 70], "ids": named})).is_err(), "named art outside it"); + assert_eq!((undo_len(&s), stack(&s), members(&s)), (undo, kids.clone(), lines.to_vec())); + + let v = ViewInfo::default(); + s.select_tool("fillArea", v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Move, 250.0, 70.0), v).unwrap(); + assert!( + !s.overlays(v).iter().any(|o| matches!(o, Overlay::Path { color: [0xff, 0x2a, 0x2a], .. })), + "no area outside the isolated group is outlined" + ); + s.pointer(&PointerEvent::new(PointerKind::Down, 250.0, 70.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 250.0, 70.0), v).unwrap(); + assert_eq!((undo_len(&s), stack(&s), members(&s)), (undo, kids.clone(), lines.to_vec())); + + s.pointer(&PointerEvent::new(PointerKind::Move, 50.0, 70.0), v).unwrap(); + let red = s.overlays(v).into_iter().filter(|o| matches!(o, Overlay::Path { color: [0xff, 0x2a, 0x2a], .. })).count(); + assert_eq!(red, 1, "the isolated group's area is outlined"); + s.pointer(&PointerEvent::new(PointerKind::Down, 50.0, 70.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 50.0, 70.0), v).unwrap(); + let new = s.doc().unwrap().selection.objects[0]; + assert_eq!(s.doc().unwrap().doc.parent_of(new), Some(g)); + assert_eq!(members(&s), [lines.as_slice(), &[new]].concat()); + assert_eq!(stack(&s), kids); + assert!((area(&s, new) - 900.0).abs() < 1.0, "{}", area(&s, new)); + + // An isolated object that no longer exists counts as no isolation, for the tool as for the + // command: the area outside the group fills. + s.doc_mut().unwrap().isolation = Some(NodeId(999_999)); + s.pointer(&PointerEvent::new(PointerKind::Move, 250.0, 70.0), v).unwrap(); + let red = s.overlays(v).into_iter().filter(|o| matches!(o, Overlay::Path { color: [0xff, 0x2a, 0x2a], .. })).count(); + assert_eq!(red, 1, "the area outside the group is outlined"); + s.pointer(&PointerEvent::new(PointerKind::Down, 250.0, 70.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 250.0, 70.0), v).unwrap(); + let new = s.doc().unwrap().selection.objects[0]; + assert_eq!(s.doc().unwrap().doc.parent_of(new), s.doc().unwrap().doc.default_layer()); +} + +/// While a compound path is isolated, Fill Area finds no area, for the command and the tool, and +/// changes nothing: the compound path cannot hold the new path. The same goes for an isolated +/// Objects on Path group, a group with a Transform effect and a group that is a clipping mask. +#[test] +fn fill_area_finds_nothing_while_a_compound_path_is_isolated() { + let mut s = session(); + let outer = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let inner = rect(&mut s, 25.0, 25.0, 50.0, 50.0); + s.execute("select.set", &json!({"ids": [outer.0, inner.0]})).unwrap(); + let c = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap()); + deselect(&mut s); + assert!(s.execute("shapeBuilder.copyRegion", &json!({"point": [10, 10]})).is_ok(), "the ring fills outside isolation"); + s.execute("edit.undo", &json!({})).unwrap(); + s.doc_mut().unwrap().isolation = Some(c); + let (undo, kids) = (undo_len(&s), stack(&s)); + assert!(s.execute("shapeBuilder.copyRegion", &json!({"point": [10, 10]})).is_err()); + let v = ViewInfo::default(); + s.select_tool("fillArea", v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Move, 10.0, 10.0), v).unwrap(); + assert!(!s.overlays(v).iter().any(|o| matches!(o, Overlay::Path { color: [0xff, 0x2a, 0x2a], .. }))); + s.pointer(&PointerEvent::new(PointerKind::Down, 10.0, 10.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 10.0, 10.0), v).unwrap(); + assert_eq!((undo_len(&s), stack(&s)), (undo, kids)); + + // An Objects on Path group moves its members along the path, so a new path in it would not + // stay where the area is. + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 40.0, 40.0); + let b = rect(&mut s, 100.0, 0.0, 40.0, 40.0); + let path = line(&mut s, (0.0, 200.0), (300.0, 200.0)); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let g = id_of(&s.execute("object.objectsOnPath.attach", &json!({"path": path.0})).unwrap()); + deselect(&mut s); + let c = s.doc().unwrap().doc.node(a).unwrap().geometric_bounds().unwrap().center(); + assert!(s.execute("shapeBuilder.copyRegion", &json!({"point": [c.x, c.y]})).is_ok(), "the square fills outside isolation"); + s.execute("edit.undo", &json!({})).unwrap(); + s.doc_mut().unwrap().isolation = Some(g); + let (undo, kids) = (undo_len(&s), stack(&s)); + assert!(s.execute("shapeBuilder.copyRegion", &json!({"point": [c.x, c.y]})).is_err()); + assert_eq!((undo_len(&s), stack(&s)), (undo, kids)); + + // A group with a Transform effect moves what is in it, so a new path in it would not be drawn + // where the area is. + let mut s = session(); + let lines = triangle(&mut s); + let ids: Vec = lines.iter().map(|l| l.0).collect(); + s.execute("select.set", &json!({"ids": ids})).unwrap(); + let g = id_of(&s.execute("object.group", &json!({})).unwrap()); + s.execute("effect.apply", &json!({"effect": "distort.transform", "params": {"moveH": 100}, "ids": [g.0], "item": null})).unwrap(); + deselect(&mut s); + s.doc_mut().unwrap().isolation = Some(g); + let (undo, kids) = (undo_len(&s), stack(&s)); + assert!(s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 70]})).is_err()); + assert_eq!((undo_len(&s), stack(&s), node(&s, g).children().unwrap().len()), (undo, kids, 3)); + + // A group that is a clipping mask clips and is not painted, so it takes no new path. + let mut s = session(); + let back = rect(&mut s, -20.0, -20.0, 140.0, 140.0); + let edge = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + s.execute("select.set", &json!({"ids": [back.0, edge.0]})).unwrap(); + let clip = id_of(&s.execute("object.clippingMask.make", &json!({})).unwrap()); + s.execute("select.set", &json!({"ids": [edge.0]})).unwrap(); + let mask = id_of(&s.execute("object.group", &json!({})).unwrap()); + // A filled square drawn in the mask group bounds an area of its own. + s.doc_mut().unwrap().isolation = Some(mask); + let square = rect(&mut s, 10.0, 10.0, 80.0, 80.0); + assert_eq!(s.doc().unwrap().doc.parent_of(square), Some(mask)); + deselect(&mut s); + let first = node(&s, clip).children().unwrap()[0].id; + assert_eq!(first, mask, "the group is the clipping mask"); + let (undo, kids) = (undo_len(&s), stack(&s)); + let members = node(&s, mask).children().unwrap().len(); + assert!(s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 70]})).is_err()); + assert_eq!((undo_len(&s), stack(&s), node(&s, mask).children().unwrap().len()), (undo, kids, members)); +} + /// The new path goes directly above the front-most object along the area, not above art that /// lies elsewhere, and paths on other layers bound areas too. #[test] diff --git a/crates/tools/src/builder.rs b/crates/tools/src/builder.rs index 931c14532e..cec57b2887 100644 --- a/crates/tools/src/builder.rs +++ b/crates/tools/src/builder.rs @@ -34,7 +34,7 @@ mod lookup; mod map; use cache::{BACKGROUND_SEGMENTS, CacheKey, RegionCache}; -pub use fill_area::{AreaFinder, EnclosedArea, FillAreaTool, every_layer}; +pub use fill_area::{AreaFinder, EnclosedArea, FillAreaTool, every_layer, fill_area_roots}; #[cfg(test)] use live_paint::LpHover; pub use live_paint::{ diff --git a/crates/tools/src/builder/fill_area.rs b/crates/tools/src/builder/fill_area.rs index f38c69b723..663068f1b7 100644 --- a/crates/tools/src/builder/fill_area.rs +++ b/crates/tools/src/builder/fill_area.rs @@ -14,8 +14,9 @@ pub struct EnclosedArea { /// The area's outline, as a Shape Builder merge of that one region makes it. pub path: PathData, /// The object directly in a layer that holds the front-most path along the area (its outline - /// touches the area's outline, or it covers the area): the new path goes directly above it, so - /// it never goes inside a group, a Live Paint group, a Shaper group or a clipping group. + /// touches the area's outline, or it covers the area), or in isolation mode the object directly + /// in the isolated object: the new path goes directly above it, so it never goes inside a group, + /// a Live Paint group, a Shaper group or a clipping group other than the isolated one. pub above: NodeId, } @@ -99,19 +100,85 @@ fn within(inner: &Rect, outer: &Rect) -> bool { inner.x0 >= outer.x0 && inner.x1 <= outer.x1 && inner.y0 >= outer.y0 && inner.y1 <= outer.y1 } -/// The object directly in a layer (or sublayer) that holds `id`: `id` itself when a layer holds it. -fn outermost(doc: &Document, id: NodeId) -> NodeId { +/// The object directly in `scope` (the isolated object in isolation mode), or else directly in a +/// layer (or sublayer), that holds `id`: `id` itself when `scope` or a layer holds it, or when `id` +/// is `scope`. +fn outermost(doc: &Document, id: NodeId, scope: Option) -> NodeId { let Some(line) = doc.ancestry(id) else { return id }; - let layer = line.iter().rposition(|a| doc.node(*a).is_some_and(|n| n.is_layer())); - layer.and_then(|k| line.get(k + 1)).copied().unwrap_or(id) + let k = match scope { + Some(s) => line.iter().rposition(|a| *a == s), + None => line.iter().rposition(|a| doc.node(*a).is_some_and(|n| n.is_layer())), + }; + k.and_then(|k| line.get(k + 1)).copied().unwrap_or(id) +} + +/// Does `n` make, move or combine the art in it itself, so that a new path in it would not stay as +/// Fill Area adds it: a Live Paint group, a compound shape, a Shaper group, a graph, an Image Trace +/// result, a dimension, a flare or an Objects on Path group. +fn managed(n: &Node) -> bool { + let e = n.extras(); + super::lookup::is_live_paint(n) + || n.is_compound_shape() + || e.shaper.is_some() + || e.graph.is_some() + || e.trace.is_some() + || e.dimension.is_some() + || e.flare.is_some() + || e.objects_on_path.is_some() +} + +/// The roots the Fill Area tool and `shapeBuilder.copyRegion` find areas among, with the isolated +/// object the new path goes into ([`AreaFinder::new`]'s `scope`), for `isolation` (the document's +/// isolated object) and `named` (the objects or layers named; None: every layer). In isolation mode +/// only the isolated layer or group's paths count: of `named`, the ones inside it, with the +/// isolated object in place of one that holds it. An isolated object that no longer exists counts +/// as no isolation. None while an object that is not a layer or a group is isolated (a compound +/// path or a single path), a layer or group with a live effect, a group that is [`managed`] or a +/// clipping mask, or one inside such an object or inside another object that is not a layer or a +/// group (an envelope): no area is found then. +pub fn fill_area_roots(doc: &Document, isolation: Option, named: Option<&[NodeId]>) -> Option<(Vec, Option)> { + let Some(iso) = isolation.filter(|i| doc.node(*i).is_some()) else { + return Some((named.map_or_else(|| every_layer(doc), <[NodeId]>::to_vec), None)); + }; + let line = doc.ancestry(iso)?; + // Every object from the layer down to the isolated one is a layer or a plain group: an + // envelope, a blend or another object that draws its contents its own way does not hold + // the new path as drawn. + // A layer or group with a live effect (a Transform effect moves what is in it) draws the new + // path elsewhere than the area. + let plain = + |a: &Node| (a.is_layer() || (matches!(a.kind, NodeKind::Group { .. }) && !managed(a))) && !a.appearance.effects.iter().any(|e| e.visible); + if !line.iter().all(|a| doc.node(*a).is_some_and(plain)) { + return None; + } + // A clipping group or clipped layer's first member is its mask, which clips and is not painted. + let in_mask = line.windows(2).any(|w| { + let [p, m] = w else { return false }; + doc.node(*p).is_some_and(|p| p.clips() && p.children().and_then(|c| c.first()).is_some_and(|f| f.id == *m)) + }); + if in_mask { + return None; + } + let Some(named) = named else { return Some((vec![iso], Some(iso))) }; + let mut out = vec![]; + for r in named { + if line.contains(r) { + out.push(iso); + } else if doc.ancestry(*r).is_some_and(|a| a.contains(&iso)) { + out.push(*r); + } + } + Some((out, Some(iso))) } impl AreaFinder { /// The finder over the paths of `roots` (layers or objects) that the Shape Builder takes: /// visible, unlocked paths, compound paths and Live Paint faces and edges that draw, not on a /// locked artboard. Gaps up to `gap` close, and with `open_filled_as_closed` a filled open path - /// bounds an area as if an invisible edge closed it. - pub fn new(doc: &Document, roots: &[NodeId], gap: f64, open_filled_as_closed: bool) -> Self { + /// bounds an area as if an invisible edge closed it. With `scope` (the isolated object in + /// isolation mode), an area's new path goes directly above the object in `scope` that holds the + /// front-most path along it, so it stays inside the isolated object. + pub fn new(doc: &Document, roots: &[NodeId], scope: Option, gap: f64, open_filled_as_closed: bool) -> Self { let roots = sorted_roots(doc, roots); let (shapes, leaves) = shape_builder_shapes(doc, &roots, open_filled_as_closed); let editable = doc.editable(); @@ -121,7 +188,7 @@ impl AreaFinder { .filter(|(_, l)| editable(l.id)) .filter_map(|(s, l)| { let b = s.path.bounds()?; - Some((s, b, outermost(doc, l.id))) + Some((s, b, outermost(doc, l.id, scope))) }) .collect(); let total = inputs.iter().map(|(_, b, _)| *b).reduce(|a, b| a.union(b)); @@ -281,8 +348,8 @@ pub struct FillAreaTool { /// The finder for the document as it is, with the key it was made for. Away while a search /// runs on another thread. finder: Option<(FinderKey, AreaFinder)>, - /// The area under the pointer, with the document revision it was found in. - hover: Option<((u64, u64), EnclosedArea)>, + /// The area under the pointer, with the key of the finder that found it. + hover: Option<(FinderKey, EnclosedArea)>, /// Where the pointer last moved over the canvas. at: Option, /// A hover search running on another thread. @@ -293,8 +360,9 @@ pub struct FillAreaTool { pressing: bool, } -/// The document revision, the gap and the open-filled rule an [`AreaFinder`] was made with. -type FinderKey = ((u64, u64), f64, bool); +/// The document revision, the gap, the open-filled rule and the isolated object an [`AreaFinder`] +/// was made with. +type FinderKey = ((u64, u64), f64, bool, Option); /// A search for the area under `p` on another thread, which hands back the finder it took. struct HoverJob { @@ -346,21 +414,26 @@ impl FillAreaTool { } fn finder_key(&self, cx: &ToolContext) -> FinderKey { - (cx.revision, self.gap(), self.open_filled_as_closed()) + (cx.revision, self.gap(), self.open_filled_as_closed(), cx.isolation) } - /// The finder for the document as `cx` has it, made again when the key changed. + /// The finder for the document as `cx` has it, made again when the key changed. In isolation + /// mode it takes only the isolated object's paths, as the command does. fn take_finder(&mut self, cx: &ToolContext) -> AreaFinder { let key = self.finder_key(cx); match self.finder.take() { Some((k, f)) if k == key => f, - _ => AreaFinder::new(cx.doc, &every_layer(cx.doc), key.1, key.2), + _ => { + // An isolated object Fill Area does not work in gives a finder of no paths. + let (roots, scope) = fill_area_roots(cx.doc, key.3, None).unwrap_or_default(); + AreaFinder::new(cx.doc, &roots, scope, key.1, key.2) + } } } /// The hover area when it is current and holds `p`. fn hover_holding(&self, cx: &ToolContext, p: Point) -> Option<&EnclosedArea> { - self.hover.as_ref().filter(|(rev, a)| *rev == cx.revision && path_contains(&a.path, FillRule::NonZero, p)).map(|(_, a)| a) + self.hover.as_ref().filter(|(k, a)| *k == self.finder_key(cx) && path_contains(&a.path, FillRule::NonZero, p)).map(|(_, a)| a) } /// The area under `p`, found here and now (a click). A search running on another thread is @@ -407,7 +480,7 @@ impl FillAreaTool { Err(f) => finder = *f, } } - self.hover = finder.find(p).map(|a| (key.0, a)); + self.hover = finder.find(p).map(|a| (key, a)); self.finder = Some((key, finder)); } @@ -440,7 +513,7 @@ impl FillAreaTool { } // The area found serves wherever the pointer moved meanwhile, as long as it holds it. let at = self.at; - self.hover = area.filter(|a| current && at.is_some_and(|p| path_contains(&a.path, FillRule::NonZero, p))).map(|a| (job.key.0, a)); + self.hover = area.filter(|a| current && at.is_some_and(|p| path_contains(&a.path, FillRule::NonZero, p))).map(|a| (job.key, a)); if let Some(p) = at && self.hover.is_none() && (p != job.p || !current) @@ -494,7 +567,7 @@ impl Tool for FillAreaTool { fn overlays(&self, cx: &ToolContext) -> Vec { self.hover .iter() - .filter(|(rev, _)| *rev == cx.revision) + .filter(|(k, _)| *k == self.finder_key(cx)) .map(|(_, a)| Overlay::Path { path: a.path.to_bezpath(), color: HIGHLIGHT_RED, width: 3.0, dashed: false }) .collect() } diff --git a/docs/mcp.md b/docs/mcp.md index ba62592f84..569d08f199 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13228,7 +13228,13 @@ Double-clicking the Fill Area tool opens the Shape Builder Tool Options (`tool.o The new path takes the current fill, stroke and stroke weight (`fill` and `stroke` override the paints), goes directly above the front-most object along the area (one whose outline touches the area's outline, or that covers it) and is selected. When a group, Live Paint group, Shaper group or clipping group holds that object, the new path goes above the -outermost group in its layer, not inside it, and the group keeps its members. A point in no enclosed area is the error "Fill Area: no enclosed area under the pointer" and records no undo +outermost group in its layer, not inside it, and the group keeps its members. In isolation mode only the paths in +the isolated layer or group bound areas, for the tool's hover and click and for the command (with `ids`, only the +paths of the listed objects that are in it), and the new path goes inside the isolated layer or group, directly above +the object in it that holds that path. No area is found while the isolated object is not a layer or group (a path +or compound path), is a Live Paint group, compound shape, Shaper group, graph, Image Trace result, dimension, flare or +Objects on Path group, is a layer or group with a live effect or a clipping mask, or lies inside one of these or +inside an envelope. A point in no enclosed area is the error "Fill Area: no enclosed area under the pointer" and records no undo step; a `gap` outside 0 to 72 is an error. It returns `{id, above}`. The command looks for the area among the paths near the point first. When the paths together have more than 65,536 segments and the paths near the point do not enclose it, the point counts as in no enclosed area. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 79ea0f99c7..70be2d54ff 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1526,7 +1526,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With Pick Color From Artwork, a merged shape takes the appearance, opacity and blending mode of the object where the drag starts, else of the object where it ends, else of the front-most selected object, as the [Shape Builder combine page](https://web.archive.org/web/20251006211643/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/combine-shapes-with-shape-builder-tool.html) describes. A click in an area that no selected object covers, such as a hole other shapes enclose, takes the front-most selected object's look (`shapeBuilder.merge` `points`: the first point is where the drag starts, and the last point is where it ends). A Shift-drag with the Shape Builder tool draws a rectangular marquee for merging many paths at once, as [Combine shapes with the Shape Builder tool](https://web.archive.org/web/20251006211643/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/combine-shapes-with-shape-builder-tool.html) describes: the regions it reaches are shaded while it is drawn and merge into one shape on release, or with Alt they are deleted. The marquee reaches each region whose outline crosses it or has an anchor inside it, and the region that holds the whole marquee; this rule is VectorCraft's own. For Pick Color From Artwork, the marquee's starting corner is where the drag starts and the opposite corner is where it ends (`shapeBuilder.merge` `rect`). The Shape Builder works on the selected paths, as [Combine shapes with the Shape Builder tool](https://web.archive.org/web/20251006211643/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/combine-shapes-with-shape-builder-tool.html) describes. As VectorCraft's own rule, a click or drag that builds nothing says why in the status bar when it is released: "Shape Builder: select paths or compound paths" when nothing is selected or the selection holds no unlocked, visible path; "Shape Builder: select all paths you want to merge" when the release is over a path or compound path that is not selected; and "Shape Builder: no region under the pointer" otherwise. The document, the selection and the undo history stay as they were, and the next gesture that builds something clears the message. Regression tests: `shape_builder_with_nothing_selected_says_what_to_select`, `shape_builder_names_the_unselected_path_under_a_release_that_built_nothing` and `shape_builder_replayed_gesture_over_nothing_gives_its_status_once` in `builder/tests.rs`, and `tests::build::shape_builder_click_that_builds_nothing_shows_why`. - As VectorCraft's own tool, Fill Area (in the Live Paint Bucket's group) adds a new closed path of the area under a click with the current fill and stroke, directly above the front-most object along it, and leaves the paths around it as they are. It needs no selection: the visible, unlocked paths on every layer bound areas, open paths and the overlap of filled shapes included, and it uses the Shape Builder's Gap Detection (`shapeBuilder.copyRegion`). Regression tests: `tests::fill_area::*`. + As VectorCraft's own tool, Fill Area (in the Live Paint Bucket's group) adds a new closed path of the area under a click with the current fill and stroke, directly above the front-most object along it, and leaves the paths around it as they are. It needs no selection: the visible, unlocked paths on every layer bound areas, open paths and the overlap of filled shapes included, and it uses the Shape Builder's Gap Detection (`shapeBuilder.copyRegion`). In isolation mode only the isolated layer or group's paths bound areas and the new path goes inside it. It finds no area while the isolated object is not a layer or group, is a group that makes, moves or combines its own art (Live Paint, compound shapes, Shaper groups, graphs, Image Trace results, dimensions, flares, Objects on Path), is a layer or group with a live effect or a clipping mask, or lies inside one of these or inside an envelope. Regression tests: `tests::fill_area::*`. Shape Builder pieces on dense hatches (lines at exact 0.25 or 0.5 pt steps across another line) come back one per stretch between crossings, with no speck where the sweep cut a line's two passes a rounding error apart: the planar map contracts the stub between such cuts into one vertex, bounded by each cluster's extent so a run of tiny level segments keeps its length (`crates/pathops/src/planar.rs` tests `a_dense_hatch_at_exact_binary_steps_cuts_each_line_once_per_crossing`, `a_run_of_tiny_level_segments_is_not_contracted_as_stubs`, `a_line_crossed_where_its_two_passes_part_is_cut_once`). The Shape Builder's gray hatch over the region under the pointer and the regions a drag has touched is drawn by a sweep that tests each hatch line only against the region's edges that span it, instead of every edge on every line. The hatch lines are the same, coordinate for coordinate; on a 2,000-sided region 1,000 hatches take about 83 ms of CPU time instead of 356 ms (release build, median of 7 alternating runs), and on a region of 40 sides the time is about the same, so the gain is on large, complex regions such as traced art (`crates/tools/src/builder/tests.rs` tests `hatch_matches_testing_every_edge`, `hatch_tests_only_the_edges_spanning_each_line` and `hatch_sweep_finds_the_crossings_of_every_edge`; timing: `hatch_perf`). The planar map's edge-source grid stays linear in memory on any input: a segment is filed once per cell it crosses, and the grid holds at most a budget of cell references (a few dozen per item plus a few rows' worth), past which the remaining items go to a short scanned list and are still found, so thousands of coincident segments cannot make the index quadratic (`crates/pathops/src/planar.rs` test `rect_index_holds_a_bounded_number_of_references`). From c10df66a904888d73f46c8efc76e7bb7de9e106f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 12:41:42 -0800 Subject: [PATCH 09/10] Fill Area: left-out paths, stacking and the press follow the area itself When the paths near a click have more segments than one map takes and the largest are left out, a left-out path now stops the search only when it crosses the area or comes within the gap of its outline, not when it merely lies in the area's box: a dense path in the empty corner of a filled L no longer keeps the L from being filled. A left-out closed path in front that covers the area still decides where the new path goes, so the new path is not hidden under it. With Gap Detection off, a path counts as along the area only when an anchor of the area's outline lies within 0.05 pt of it. Before, a long path's own snap distance (1 pt for a 10,000 pt line) let a line that neither touches nor covers the area take the new path onto its layer. A press while a hover search runs on another thread waits for that search only, and no longer starts and waits for a search at the position the pointer passed on the way. --- crates/engine/src/tests/fill_area.rs | 70 +++++++++++++ crates/tools/src/builder/fill_area.rs | 145 +++++++++++++++++++------- crates/tools/src/builder/tests.rs | 29 ++++++ 3 files changed, 208 insertions(+), 36 deletions(-) diff --git a/crates/engine/src/tests/fill_area.rs b/crates/engine/src/tests/fill_area.rs index 7ba4bcc26f..a11f8d2975 100644 --- a/crates/engine/src/tests/fill_area.rs +++ b/crates/engine/src/tests/fill_area.rs @@ -480,6 +480,76 @@ fn fill_area_fills_an_area_that_a_left_out_paths_box_holds_but_its_segments_miss } } +/// Puts `path` with `look` in front on the current layer. +fn insert_path(s: &mut Session, path: PathData, look: vectorcraft_doc::Appearance) -> NodeId { + s.edit("t", |d, _| { + let id = d.alloc_id(); + let top = d.children(d.default_layer()).map_or(0, |c| c.len()); + d.insert(d.default_layer(), top, Node::path(id, path, look))?; + Ok(id) + }) + .unwrap() +} + +/// A path with too many segments in the empty corner of a filled L, well clear of both arms, is +/// left out and does not stop the L from being filled, though the L's box holds it. +#[test] +fn fill_area_fills_an_l_whose_empty_corner_holds_a_left_out_path() { + let mut s = session(); + let l = [(0.0, 0.0), (400.0, 0.0), (400.0, 100.0), (100.0, 100.0), (100.0, 400.0), (0.0, 400.0)].map(|(x, y)| Point::new(x, y)); + let solid = vectorcraft_doc::Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0); + insert_path(&mut s, PathData::single(vectorcraft_geom::SubPath::polyline(&l, true)), solid); + let n = vectorcraft_pathops::SHAPE_BUILDER_MAX_SEGMENTS; + let pts: Vec = (0..=n).map(|k| Point::new(250.0 + 100.0 * k as f64 / n as f64, 250.0 + (k % 2) as f64)).collect(); + let look = vectorcraft_doc::Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0); + insert_path(&mut s, PathData::single(vectorcraft_geom::SubPath::polyline(&pts, false)), look); + deselect(&mut s); + let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 50]})).unwrap(); + assert!((area(&s, id_of(&r)) - 70_000.0).abs() < 1.0, "{}", area(&s, id_of(&r))); +} + +/// A filled contour with too many segments on a higher layer surrounds a small square, its outline +/// far from it: it is left out of the map, and the new path still goes above it, since it covers +/// the area. +#[test] +fn fill_area_stacks_above_a_left_out_path_that_covers_the_area() { + let mut s = session(); + let layer = s.doc().unwrap().doc.default_layer(); + rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let over = id_of(&s.execute("layer.new", &json!({"name": "Over"})).unwrap()); + let n = vectorcraft_pathops::SHAPE_BUILDER_MAX_SEGMENTS + 1; + let pts: Vec = (0..n) + .map(|k| { + let a = k as f64 * std::f64::consts::TAU / n as f64; + Point::new(50.0 + 3000.0 * a.cos(), 50.0 + 3000.0 * a.sin()) + }) + .collect(); + let solid = vectorcraft_doc::Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0); + let contour = insert_path(&mut s, PathData::single(vectorcraft_geom::SubPath::polyline(&pts, true)), solid); + deselect(&mut s); + let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 50]})).unwrap(); + assert!((area(&s, id_of(&r)) - 10_000.0).abs() < 1.0, "{}", area(&s, id_of(&r))); + assert_eq!(r["above"], json!(contour.0)); + let d = &s.doc().unwrap().doc; + assert_eq!(d.parent_of(id_of(&r)), Some(over)); + assert_ne!(d.parent_of(id_of(&r)), layer); +} + +/// With Gap Detection off, a long line on a higher layer 0.75 pt from a square's edge neither +/// touches nor covers the square, so the new path stays above the square. +#[test] +fn fill_area_does_not_stack_above_a_line_that_does_not_touch_the_area() { + let mut s = session(); + let layer = s.doc().unwrap().doc.default_layer(); + let square = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + id_of(&s.execute("layer.new", &json!({"name": "Other"})).unwrap()); + line(&mut s, (-5000.0, -0.75), (5000.0, -0.75)); + deselect(&mut s); + let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 50]})).unwrap(); + assert_eq!(r["above"], json!(square.0)); + assert_eq!(s.doc().unwrap().doc.parent_of(id_of(&r)), layer); +} + /// With Gap Detection on, a square on a higher layer within the gap of the area's corners does not /// bound the area, so the new path stays above the square that does. #[test] diff --git a/crates/tools/src/builder/fill_area.rs b/crates/tools/src/builder/fill_area.rs index 663068f1b7..bd41eeaf24 100644 --- a/crates/tools/src/builder/fill_area.rs +++ b/crates/tools/src/builder/fill_area.rs @@ -38,7 +38,8 @@ const NEAR_ROUNDS: usize = 4; /// have no area under the point, or the area does not fit after [`WINDOW_ROUNDS`] widenings, the /// finder maps every path. When a window's paths have more segments than one Shape Builder map /// takes, the paths with the most segments are left out until the rest fit, and an area is taken -/// only when no path left out reaches it. When every path together has more segments than that, +/// only when no path left out crosses it or comes within the gap of it; a path left out that +/// covers it still counts for where the new path goes. When every path together has more segments than that, /// an area no window finds is not found. The map of every path, once a search has needed it, is /// kept for the next search. pub struct AreaFinder { @@ -67,32 +68,77 @@ fn meet(a: &Rect, b: &Rect) -> bool { a.x0 <= b.x1 && b.x0 <= a.x1 && a.y0 <= b.y1 && b.y0 <= a.y1 } -/// Does a segment of `path` (closing segments included) meet `zone`? A path whose box meets the zone -/// may still lie wholly outside it, as a path of subpaths far apart, a diagonal line or a curve -/// that arcs around the zone does. -fn reaches(path: &PathData, zone: &Rect) -> bool { - let bez = path.to_bezpath(); - vectorcraft_geom::kurbo::segments(bez.elements().iter().copied()).any(|seg| segment_reaches(seg, zone, 0)) +/// The area a path left out of a window's map may cut: its outline, the same as a closed path +/// (`bez`), and the box (`zone`) its outline reaches with the gap. +struct Reach<'a> { + face: &'a PathData, + bez: &'a vectorcraft_geom::kurbo::BezPath, + zone: Rect, + /// How close (pt) to the outline a path may come and still change the area: the gap and 1 pt. + reach: f64, } -/// How many times [`segment_reaches`] halves a segment: a piece of 1/2^24 of a segment counts as -/// meeting the zone when its box does. +/// Does a segment of `path` (closing segments included) lie inside the area or come within its +/// reach of the area's outline? A path in the box of the area may still lie wholly outside the +/// area, in the empty corner of an L or around it, and such a path does not change it. `budget` +/// counts the work (pieces checked times the outline's segments); when it runs out, the path +/// counts as cutting the area. +fn cuts(path: &PathData, area: &Reach, budget: &mut usize) -> bool { + let bez = path.to_bezpath(); + let cost = area.face.subpaths.iter().map(|sp| sp.segment_count()).sum::().max(1); + vectorcraft_geom::kurbo::segments(bez.elements().iter().copied()).any(|seg| segment_cuts(seg, area, cost, budget, 0)) +} + +/// How many times [`segment_cuts`] halves a segment: a piece of 1/2^24 of a segment near the area +/// counts as cutting it. const REACH_SPLITS: u32 = 24; -/// The side (pt) below which a piece of a segment whose box meets the zone counts as meeting it. +/// The side (pt) below which a piece of a segment that may come within reach of the area counts as +/// cutting it. const REACH_TOLERANCE: f64 = 0.01; -/// Does `seg` meet `zone`? Its halves are checked in turn while their boxes meet the zone and -/// neither end is in it; a piece smaller than [`REACH_TOLERANCE`] whose box meets the zone counts. -fn segment_reaches(seg: PathSeg, zone: &Rect, depth: u32) -> bool { +/// How much work [`cuts`] does for one area before it takes a path as cutting it: pieces checked +/// times the segments of the area's outline. +const CUT_BUDGET: usize = 1 << 24; + +/// Does `seg` lie inside the area or come within its reach of the area's outline? A piece whose +/// box misses the area's zone does not; a piece whose middle is inside the area or within reach of +/// its outline does; a piece farther from the outline than its box is wide does not, since every +/// point of it is then out of reach and on the same side. The rest is halved. +fn segment_cuts(seg: PathSeg, area: &Reach, cost: usize, budget: &mut usize, depth: u32) -> bool { let b = segment_bounds(seg); - if !meet(&b, zone) { + if !meet(&b, &area.zone) { return false; } - if holds(zone, seg.start()) || holds(zone, seg.end()) || depth >= REACH_SPLITS || b.width().max(b.height()) < REACH_TOLERANCE { + let Some(left) = budget.checked_sub(cost) else { return true }; + *budget = left; + let mid = seg.eval(0.5); + if area.bez.winding(mid) != 0 { return true; } - segment_reaches(seg.subsegment(0.0..0.5), zone, depth + 1) || segment_reaches(seg.subsegment(0.5..1.0), zone, depth + 1) + let Some((.., d)) = area.face.nearest(mid) else { return true }; + if d <= area.reach { + return true; + } + let wide = b.width().hypot(b.height()); + if d - area.reach > wide { + return false; + } + if depth >= REACH_SPLITS || wide < REACH_TOLERANCE { + return true; + } + segment_cuts(seg.subsegment(0.0..0.5), area, cost, budget, depth + 1) || segment_cuts(seg.subsegment(0.5..1.0), area, cost, budget, depth + 1) +} + +/// How far (pt) an anchor of an area's outline may lie from a path's outline, with Gap Detection +/// off, and still count as on it: the least snap distance [`outline_snap`] gives, five times the +/// 0.01 pt precision the Shape Builder's map works to. +const CONTACT: f64 = 0.05; + +/// Does the filled area of the closed subpaths of `s` hold `p`? +fn covers(s: &po::Shape, p: Point) -> bool { + let closed = PathData::new(s.path.subpaths.iter().filter(|sp| sp.closed).cloned().collect()); + path_contains(&closed, s.rule, p) } /// Does `outer` hold all of `inner`? @@ -201,7 +247,7 @@ impl AreaFinder { /// `p` is in no enclosed area. pub fn find(&mut self, p: Point) -> Option { if let Some((map, picked)) = &self.full { - return self.area_in(map, picked, p); + return self.area_in(map, picked, &[], p); } let total = self.total?; // A gap bridge reaches at most `gap` past a path, so a window takes in every path within @@ -245,22 +291,27 @@ impl AreaFinder { let every = picked.len() == self.inputs.len(); let shapes: Vec = picked.iter().filter_map(|&i| self.inputs.get(i).map(|(s, ..)| s.clone())).collect(); let map = BuilderMap::of_shapes(shapes, false, self.gap); - let bounds = map.region_at(p).and_then(|k| map.regions.get(k)).map(|(.., rb)| *rb); + let face = map.region_at(p).and_then(|k| map.regions.get(k)); + let bounds = face.map(|(.., rb)| *rb); if every { - let area = self.area_in(&map, &picked, p); + let area = self.area_in(&map, &picked, &[], p); self.full = Some((map, picked)); return area; } let before = window; match bounds { - // A path left out that reaches the area could cut it, and only the map of every - // path holds both. + // A path left out that crosses the area or comes within its reach could cut it, and + // only the map of every path holds both. Some(rb) if within(&rb, &window) => { let reached = rb.inflate(reach, reach); + let mut budget = CUT_BUDGET; let cut = any_left_out - && self.inputs.iter().zip(&left_out).any(|((s, b, _), out)| *out && meet(b, &reached) && reaches(&s.path, &reached)); + && face.is_none_or(|(region, bez, _)| { + let area = Reach { face: ®ion.path, bez, zone: reached, reach }; + self.inputs.iter().zip(&left_out).any(|((s, b, _), out)| *out && meet(b, &reached) && cuts(&s.path, &area, &mut budget)) + }); if !cut { - return self.area_in(&map, &picked, p); + return self.area_in(&map, &picked, &left_out, p); } every_path = true; } @@ -301,8 +352,11 @@ impl AreaFinder { out } - /// The area under `p` in `map`, made of the inputs `picked` (in its order). - fn area_in(&self, map: &BuilderMap, picked: &[usize], p: Point) -> Option { + /// The area under `p` in `map`, made of the inputs `picked` (in its order). `left_out` marks + /// the inputs left out of the map, by index, none of which comes near the area: the front-most + /// of them that covers the area decides where the new path goes when it is in front of the + /// shape the map gives. + fn area_in(&self, map: &BuilderMap, picked: &[usize], left_out: &[bool], p: Point) -> Option { let (region, ..) = map.region_at(p).and_then(|k| map.regions.get(k))?; let path = po::FaceMerger::with_gap(&map.shapes, self.gap).merge(&[region]); if path.is_empty() { @@ -312,9 +366,10 @@ impl AreaFinder { // The front-most shape that covers the area or that an anchor of its outline lies on. A // shape within the gap of an anchor counts only when no shape is along the area itself, // so a path near the area that bounds none of it does not decide where the new path goes. + // Without a gap, an anchor is on a shape's outline within [`CONTACT`]. let along = |gap: f64| { map.shapes.iter().enumerate().rev().find(|(i, s)| { - let tol = outline_snap(&s.path) + gap; + let tol = if gap > 0.0 { outline_snap(&s.path) + gap } else { CONTACT }; region.sources.contains(i) || s.path.bounds().is_some_and(|b| { let b = b.inflate(tol, tol); @@ -323,7 +378,12 @@ impl AreaFinder { }) }; let k = along(0.0).or_else(|| along(self.gap)).map_or(map.shapes.len().checked_sub(1)?, |(i, _)| i); - let above = picked.get(k).and_then(|&i| self.inputs.get(i)).map(|(.., id)| *id)?; + let mapped = *picked.get(k)?; + // A path left out comes near no part of the area, so it covers all of it or none of it. + let covering = + left_out.iter().enumerate().rev().find(|(i, out)| **out && *i > mapped && self.inputs.get(*i).is_some_and(|(s, ..)| covers(s, p))); + let front = covering.map_or(mapped, |(i, _)| i); + let above = self.inputs.get(front).map(|(.., id)| *id)?; Some(EnclosedArea { path, above }) } } @@ -371,9 +431,22 @@ struct HoverJob { done: std::sync::mpsc::Receiver<(AreaFinder, Option)>, } +#[cfg(not(target_arch = "wasm32"))] +thread_local! { + /// The hover searches this thread has started on other threads ([`hover_searches_started`]). + static HOVER_SEARCHES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// How many hover searches this thread has started on other threads, for tests that count them. +#[cfg(all(test, not(target_arch = "wasm32")))] +pub(super) fn hover_searches_started() -> usize { + HOVER_SEARCHES.with(std::cell::Cell::get) +} + /// Runs `finder.find(p)` on another thread; gives the finder back when no thread starts. #[cfg(not(target_arch = "wasm32"))] fn spawn_find(finder: AreaFinder, p: Point) -> Result)>, Box> { + HOVER_SEARCHES.with(|n| n.set(n.get() + 1)); let (tx, done) = std::sync::mpsc::channel(); let (back_tx, back) = std::sync::mpsc::channel(); let spawned = std::thread::Builder::new().name("vectorcraft-fill-area".into()).spawn(move || { @@ -437,14 +510,13 @@ impl FillAreaTool { } /// The area under `p`, found here and now (a click). A search running on another thread is - /// waited for first, so its finder is not made again. + /// waited for first, so its finder is not made again; no search starts for where the pointer + /// moved meanwhile. fn area_at(&mut self, cx: &ToolContext, p: Point) -> Option { if let Some(a) = self.hover_holding(cx, p) { return Some(a.clone()); } - while self.job.is_some() { - self.settle(cx, true); - } + self.settle(cx, true, false); let key = self.finder_key(cx); let mut finder = self.take_finder(cx); let area = finder.find(p); @@ -485,8 +557,8 @@ impl FillAreaTool { } /// Takes the result of the hover search on another thread when it is done (`wait`: waits for - /// it), and starts the search for where the pointer moved meanwhile. - fn settle(&mut self, cx: &ToolContext, wait: bool) { + /// it), and with `follow` starts the search for where the pointer moved meanwhile. + fn settle(&mut self, cx: &ToolContext, wait: bool, follow: bool) { let Some(job) = self.job.take() else { return }; let got = if wait { job.done.recv().ok() @@ -514,7 +586,8 @@ impl FillAreaTool { // The area found serves wherever the pointer moved meanwhile, as long as it holds it. let at = self.at; self.hover = area.filter(|a| current && at.is_some_and(|p| path_contains(&a.path, FillRule::NonZero, p))).map(|a| (job.key, a)); - if let Some(p) = at + if follow + && let Some(p) = at && self.hover.is_none() && (p != job.p || !current) { @@ -591,9 +664,9 @@ impl Tool for FillAreaTool { } fn poll(&mut self, cx: &ToolContext, wait: bool) -> Vec { - self.settle(cx, wait); + self.settle(cx, wait, true); while wait && self.job.is_some() { - self.settle(cx, true); + self.settle(cx, true, true); } vec![] } diff --git a/crates/tools/src/builder/tests.rs b/crates/tools/src/builder/tests.rs index dc31c1ba79..0cdaad3434 100644 --- a/crates/tools/src/builder/tests.rs +++ b/crates/tools/src/builder/tests.rs @@ -3767,6 +3767,35 @@ fn live_paint_selection_options_set_the_highlight() { assert_eq!(t.options()["width"], json!(LP_SELECT_WIDTH_RANGE.0)); } +/// A press while a Fill Area hover search runs on another thread waits for that search only: no +/// search starts for where the pointer moved meanwhile, and the press finds its own area. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn fill_area_press_does_not_search_a_hover_position_it_passed() { + let mut d = Document::new(800.0, 600.0); + let l = d.layers[0].id; + let pts: Vec = (0..200) + .map(|k| { + let a = k as f64 * std::f64::consts::TAU / 200.0; + Point::new(300.0 + 100.0 * a.cos(), 300.0 + 100.0 * a.sin()) + }) + .collect(); + let poly = d.alloc_id(); + d.insert(Some(l), 0, Node::path(poly, PathData::single(SubPath::polyline(&pts, true)), Appearance::default_art())).unwrap(); + let s = Selection::default(); + let p = paint(); + let cx = ToolContext { revision: (1, 1), ..cx(&d, &s, &p) }; + let mut t = FillAreaTool::new(); + let started = super::fill_area::hover_searches_started(); + t.pointer(&cx, &ev(PointerKind::Move, 500.0, 500.0)); + assert!(t.waiting()); + t.pointer(&cx, &ev(PointerKind::Move, 510.0, 500.0)); + let acts = t.pointer(&cx, &ev(PointerKind::Down, 300.0, 300.0)); + assert!(matches!(acts.as_slice(), [Action::Begin(_), Action::Preview(id, _)] if id == "shapeBuilder.copyRegion"), "{acts:?}"); + assert!(!t.waiting()); + assert_eq!(super::fill_area::hover_searches_started() - started, 1, "only the search that was running"); +} + #[test] fn create_builds_the_three_tools() { for id in ["shapeBuilder", "livePaintBucket", "livePaintSelection"] { From 6adc5c651c03c813af2b560f9f28257018167b6f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 13:14:42 -0800 Subject: [PATCH 10/10] Fill Area: no area while a clipping group or the art it clips is isolated Before, only a clipping mask itself was refused in isolation mode. A clipping group or clipped layer that was isolated, or that held the isolated group, still took the new path, where its mask could hide or cut it. Now no area is found then, for the tool and for shapeBuilder.copyRegion, as the documentation of the command states. --- crates/engine/src/tests/fill_area.rs | 13 +++++++++++++ crates/tools/src/builder/fill_area.rs | 15 ++++++--------- 2 files changed, 19 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/tests/fill_area.rs b/crates/engine/src/tests/fill_area.rs index a11f8d2975..6625c7e150 100644 --- a/crates/engine/src/tests/fill_area.rs +++ b/crates/engine/src/tests/fill_area.rs @@ -318,6 +318,19 @@ fn fill_area_finds_nothing_while_a_compound_path_is_isolated() { let members = node(&s, mask).children().unwrap().len(); assert!(s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 70]})).is_err()); assert_eq!((undo_len(&s), stack(&s), node(&s, mask).children().unwrap().len()), (undo, kids, members)); + // The clipping group itself, and a group of the art it clips, take no new path either: the + // mask would hide or cut it. + s.doc_mut().unwrap().isolation = None; + s.execute("select.set", &json!({"ids": [back.0]})).unwrap(); + let clipped = id_of(&s.execute("object.group", &json!({})).unwrap()); + assert_eq!(s.doc().unwrap().doc.parent_of(clipped), Some(clip)); + deselect(&mut s); + for iso in [clip, clipped] { + s.doc_mut().unwrap().isolation = Some(iso); + let (undo, kids) = (undo_len(&s), stack(&s)); + assert!(s.execute("shapeBuilder.copyRegion", &json!({"point": [5, 5]})).is_err(), "{iso:?}"); + assert_eq!((undo_len(&s), stack(&s)), (undo, kids), "{iso:?}"); + } } /// The new path goes directly above the front-most object along the area, not above art that diff --git a/crates/tools/src/builder/fill_area.rs b/crates/tools/src/builder/fill_area.rs index bd41eeaf24..f535bd0aa3 100644 --- a/crates/tools/src/builder/fill_area.rs +++ b/crates/tools/src/builder/fill_area.rs @@ -179,9 +179,9 @@ fn managed(n: &Node) -> bool { /// only the isolated layer or group's paths count: of `named`, the ones inside it, with the /// isolated object in place of one that holds it. An isolated object that no longer exists counts /// as no isolation. None while an object that is not a layer or a group is isolated (a compound -/// path or a single path), a layer or group with a live effect, a group that is [`managed`] or a -/// clipping mask, or one inside such an object or inside another object that is not a layer or a -/// group (an envelope): no area is found then. +/// path or a single path), a layer or group with a live effect, a group that is [`managed`], a +/// clipping group or clipped layer, or one inside such an object or inside another object that is +/// not a layer or a group (an envelope): no area is found then. pub fn fill_area_roots(doc: &Document, isolation: Option, named: Option<&[NodeId]>) -> Option<(Vec, Option)> { let Some(iso) = isolation.filter(|i| doc.node(*i).is_some()) else { return Some((named.map_or_else(|| every_layer(doc), <[NodeId]>::to_vec), None)); @@ -197,12 +197,9 @@ pub fn fill_area_roots(doc: &Document, isolation: Option, named: Option< if !line.iter().all(|a| doc.node(*a).is_some_and(plain)) { return None; } - // A clipping group or clipped layer's first member is its mask, which clips and is not painted. - let in_mask = line.windows(2).any(|w| { - let [p, m] = w else { return false }; - doc.node(*p).is_some_and(|p| p.clips() && p.children().and_then(|c| c.first()).is_some_and(|f| f.id == *m)) - }); - if in_mask { + // A clipping group or clipped layer's mask clips and is not painted, and its mask hides or cuts + // a new path among the art it clips. + if line.iter().any(|a| doc.node(*a).is_some_and(Node::clips)) { return None; } let Some(named) = named else { return Some((vec![iso], Some(iso))) };