Merge pull request #8782 from storytold/train/carry8001

Fill Area: a click adds a path of the enclosed area and keeps the paths around it (#8001)
This commit is contained in:
BFlat authored and GitHub committed 2026-11-20 07:00:48 +07:00
commit 5efe19e7c5
49 files changed
+1783 -19

No files matched your search

+1
View File
@@ -155,6 +155,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 | |
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M7 9h10l-5 8.7z" fill="currentColor" stroke="none"/><path d="M3 9h18"/><path d="M5 5.5 14.5 22"/><path d="M19 5.5 9.5 22"/></svg>

After

Width:  |  Height:  |  Size: 321 B

+19 -4
View File
@@ -40,7 +40,7 @@ mod trace;
pub use live_paint::live_paint_gaps;
pub(crate) use live_paint::{LivePaintMove, check_part_name, clear_part_name, isolated_live_paints, merge_drawn_in_isolation};
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::{
TRACE_PRESET_EXTS, TRACE_PRESET_FORMAT, TRACE_PRESET_MAX_BYTES, TracePreset, TracePresetChange, TraceRun, Traced, image_trace_target,
@@ -72,6 +72,15 @@ pub fn specs() -> Vec<CommandSpec> {
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; 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
),
cmd!(
"livePaint.make",
"Make",
@@ -285,12 +294,18 @@ fn stroke_only(paint: Paint, width: f64) -> Appearance {
// ---------- Shape Builder ----------
fn fill_param(s: &Session, p: &Value, cmd: &str) -> Result<Option<Paint>> {
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<Option<Paint>> {
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)
// 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 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}"))),
}
}
@@ -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<Value> {
@@ -183,6 +183,49 @@ pub(super) fn sb_merge(s: &mut Session, p: &Value) -> Result<Value> {
Ok(out)
}
pub(super) fn sb_copy_region(s: &mut Session, p: &Value) -> Result<Value> {
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 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.
Some(outermost(d, ids))
}
None => None,
};
// 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| {
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<Value> {
let open_filled_as_closed = switch_or(p, "openFilledAsClosed", true, "shapeBuilder.regions")?;
check_numbers(p, &["gap"], "shapeBuilder.regions")?;
@@ -574,6 +574,7 @@ pub(super) const ALLOWED: &[&str] = &[
"shape.spiral",
"shape.star",
"shape.threePointArc",
"shapeBuilder.copyRegion",
"shapeBuilder.merge",
"shapeBuilder.regions",
"shaper.expand",
+1
View File
@@ -67,6 +67,7 @@ mod expand_symbols;
mod eyedropper;
mod file;
mod fileinfo;
mod fill_area;
mod flatpresets;
mod flatpreview;
mod flatten;
+827
View File
@@ -0,0 +1,827 @@
//! 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<NodeId> {
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<u64> = 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<NodeId> { 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<u64> = 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);
}
/// 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<u64> = 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<NodeId> { 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<u64> = 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<u64> = 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 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
/// 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<NodeId> = d.children(Some(other)).unwrap().iter().map(|n| n.id).collect();
assert_eq!(kids, vec![l3, new, top]);
let kids: Vec<NodeId> = 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<Point> = (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<Point> = (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<Point> = (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));
}
}
/// 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() {
// 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<Point> = (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)));
}
}
/// 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<Point> = (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<Point> = (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]
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<Point> = (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}");
}
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));
}
/// 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: 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);
}
/// 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<f64> {
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:?}");
}
+1 -1
View File
@@ -1175,7 +1175,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; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), 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), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), 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, filledLines and lineWidth 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 (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), 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 To Line truncated
"{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; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), 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), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), 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, filledLines and lineWidth 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 (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), 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 To Line truncated
),
(
"ui.colorGuideOptions",
+15 -7
View File
@@ -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, fill_area_roots};
#[cfg(test)]
use live_paint::LpHover;
pub use live_paint::{
@@ -868,11 +870,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<String, Value>) -> 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]| {
@@ -902,6 +909,7 @@ pub fn create(id: &str) -> Option<Box<dyn Tool>> {
"shapeBuilder" => Box::new(ShapeBuilderTool::default()),
"livePaintBucket" => Box::new(LivePaintBucketTool::default()),
"livePaintSelection" => Box::new(LivePaintSelectionTool::default()),
"fillArea" => Box::new(FillAreaTool::new()),
_ => return None,
})
}
+701
View File
@@ -0,0 +1,701 @@
//! 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 vectorcraft_geom::path::segment_bounds;
use vectorcraft_geom::{ParamCurve, PathSeg};
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), 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,
}
/// 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 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 {
/// 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<Rect>,
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<usize>)>,
}
/// 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
}
/// 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,
}
/// 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::<usize>().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 that may come within reach of the area counts as
/// cutting it.
const REACH_TOLERANCE: f64 = 0.01;
/// 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, &area.zone) {
return false;
}
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;
}
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`?
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 `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>) -> NodeId {
let Some(line) = doc.ancestry(id) else { return 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`], 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<NodeId>, named: Option<&[NodeId]>) -> Option<(Vec<NodeId>, Option<NodeId>)> {
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 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))) };
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. 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<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, scope)))
})
.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<EnclosedArea> {
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<usize> = (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<po::Shape> = picked.iter().filter_map(|&i| self.inputs.get(i).map(|(s, ..)| s.clone())).collect();
let map = BuilderMap::of_shapes(shapes, false, self.gap);
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);
self.full = Some((map, picked));
return area;
}
let before = window;
match bounds {
// 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
&& face.is_none_or(|(region, bez, _)| {
let area = Reach { face: &region.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, &left_out, 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<usize> {
let segments = |i: usize| self.inputs.get(i).map_or(0, |(s, ..)| s.path.subpaths.iter().map(|sp| sp.segment_count()).sum::<usize>());
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). `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<EnclosedArea> {
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<Point> = 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.
// 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 = 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);
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 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 })
}
}
/// The paths the Fill Area tool finds areas among: every layer's.
pub fn every_layer(doc: &Document) -> Vec<NodeId> {
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 key of the finder that found it.
hover: Option<(FinderKey, EnclosedArea)>,
/// Where the pointer last moved over the canvas.
at: Option<Point>,
/// A hover search running on another thread.
job: Option<HoverJob>,
/// The key whose search on another thread failed: hovering does not search it again.
failed: Option<FinderKey>,
/// A press added the path as a preview, which the release keeps.
pressing: 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<NodeId>);
/// 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<EnclosedArea>)>,
}
#[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<usize> = 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<std::sync::mpsc::Receiver<(AreaFinder, Option<EnclosedArea>)>, Box<AreaFinder>> {
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 || {
// 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<std::sync::mpsc::Receiver<(AreaFinder, Option<EnclosedArea>)>, Box<AreaFinder>> {
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(), cx.isolation)
}
/// 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,
_ => {
// 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(|(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
/// 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<EnclosedArea> {
if let Some(a) = self.hover_holding(cx, p) {
return Some(a.clone());
}
self.settle(cx, true, false);
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, 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 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()
} 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, a));
if follow
&& 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<Action> {
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<Action> {
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<Overlay> {
self.hover
.iter()
.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()
}
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<Action> {
self.settle(cx, wait, true);
while wait && self.job.is_some() {
self.settle(cx, true, 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;
}
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())]))
}
}
+29
View File
@@ -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<Point> = (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"] {
+1
View File
@@ -103,6 +103,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"),
],
&[
+2
View File
@@ -524,6 +524,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."
@@ -534,6 +535,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."
+2
View File
@@ -98,6 +98,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"]),
@@ -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();
+3
View File
@@ -2075,6 +2075,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 Инструмент за селекция на динамично оцветяване
@@ -4785,6 +4787,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 Разделяне на мрежа: изберете пътища, достатъчно големи за мрежата
Can't render this file because it is too large.
+3
View File
@@ -3701,6 +3701,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
@@ -5190,6 +5192,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
Can't render this file because it contains an unexpected character in line 2 and column 73.
+3
View File
@@ -2689,6 +2689,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
@@ -7228,6 +7230,7 @@ liquify-list-end {0}, {1} {0} i {1}
@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 all paths you want to merge Constructor de formes: selecciona tots els traçats que vulguis combinar
@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
Can't render this file because it is too large.
+3
View File
@@ -3802,6 +3802,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ů
@@ -5481,6 +5483,7 @@ liquify-list-end {0}, {1} {0} a {1}
@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 all paths you want to merge Tvorba tvarů: vyberte všechny cesty, které chcete sloučit
@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
Can't render this file because it is too large.
+3
View File
@@ -6282,6 +6282,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
@@ -7735,6 +7737,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 all paths you want to merge Figurbygger: markér alle kurver, du vil flette
@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
Can't render this file because it is too large.
+3
View File
@@ -2169,6 +2169,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
@@ -5057,6 +5059,7 @@ liquify-list-end {0}, {1} {0} und {1}
@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 all paths you want to merge Formerstellung: Wählen Sie alle Pfade aus, die Sie zusammenfügen möchten
@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
Can't render this file because it is too large.
+3
View File
@@ -2896,6 +2896,7 @@ liquify-list-end {0}, {1} {0} και {1}
@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 all paths you want to merge Δημιουργία σχημάτων: επιλέξτε όλες τις διαδρομές που θέλετε να συγχωνεύσετε
@msg Shape Builder: select paths or compound paths Δημιουργία σχημάτων: επιλέξτε διαδρομές ή σύνθετες διαδρομές
@msg Show All Hidden Attributes: nothing is hidden Εμφάνιση όλων των κρυφών χαρακτηριστικών: δεν υπάρχουν κρυφά χαρακτηριστικά
@@ -3306,6 +3307,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)
Can't render this file because it is too large.
+3
View File
@@ -2167,6 +2167,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
@@ -5168,6 +5170,7 @@ liquify-list-end {0}, {1} {0}, {1}
@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 all paths you want to merge Generador de formas: selecciona todos los trazados que quieras combinar
@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
Can't render this file because it is too large.
+3
View File
@@ -3739,6 +3739,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
@@ -5409,6 +5411,7 @@ liquify-list-end {0}, {1} {0} ja {1}
@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 all paths you want to merge Muodonmuodostin: valitse kaikki polut, jotka haluat yhdistää
@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
Can't render this file because it is too large.
+3
View File
@@ -2157,6 +2157,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
@@ -5126,6 +5128,7 @@ liquify-list-end {0}, {1} {0} et {1}
@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 all paths you want to merge Concepteur de forme : sélectionnez tous les tracés à fusionner
@msg Shape Builder: select paths or compound paths Concepteur de forme : sélectionnez des tracés ou des tracés transparents
Can't render this file because it is too large.
+2
View File
@@ -2180,6 +2180,8 @@
List Workspaces વર્કસ્પેસની યાદી
Live Paint લાઇવ પેઇન્ટ
Live Paint Bucket લાઇવ પેઇન્ટ બકેટ
Fill Area વિસ્તાર ભરો
Fill Area Tool વિસ્તાર ભરો ટૂલ
Live Paint Bucket (Stroke) લાઇવ પેઇન્ટ બકેટ (સ્ટ્રોક)
Live Paint Info લાઇવ પેઇન્ટ માહિતી
Live Paint Selection Tool લાઇવ પેઇન્ટ પસંદગી ટૂલ
Can't render this file because it contains an unexpected character in line 72 and column 5.
+3
View File
@@ -3195,6 +3195,8 @@ arrowhead Feather पंख
Live curve fitting लाइव वक्र फिटिंग
Live Paint लाइव पेंट
Live Paint Bucket लाइव पेंट बकेट
Fill Area क्षेत्र भरें
Fill Area Tool क्षेत्र भरें टूल
Live Paint Bucket (Stroke) लाइव पेंट बाल्टी (स्ट्रोक)
Live Paint Info लाइव पेंट जानकारी
Live Paint Selection Tool लाइव पेंट सिलेक्शन टूल
@@ -9090,6 +9092,7 @@ liquify-list-end {0}, {1} {0} और {1}
@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 all paths you want to merge आकृति बिल्डर: वे सभी पाथ सिलेक्ट करें जिन्हें आप मर्ज करना चाहते हैं
@msg Shape Builder: select paths or compound paths आकृति बिल्डर: पाथ या मिश्रित पाथ सिलेक्ट करें
@msg Shaper needs 1–64 source paths शेपर के लिए 1–64 स्रोत पाथ चाहिए
Can't render this file because it is too large.
+3
View File
@@ -2681,6 +2681,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
@@ -6466,6 +6468,7 @@ liquify-list-end {0}, {1} {0} és {1}
@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 all paths you want to merge Alakzatépítő: jelöld ki az összes egyesítendő útvonalat
@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
Can't render this file because it is too large.
+3
View File
@@ -4150,6 +4150,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
@@ -5599,6 +5601,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
Can't render this file because it is too large.
+3
View File
@@ -2209,6 +2209,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
@@ -5195,6 +5197,7 @@ liquify-list-end {0}, {1} {0} e {1}
@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 all paths you want to merge Generatore forme: seleziona tutti i tracciati da unire
@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
Can't render this file because it is too large.
+3
View File
@@ -2479,6 +2479,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 ライブペイント選択ツール
@@ -5026,6 +5028,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 all paths you want to merge シェイプ形成ツール: 結合するパスをすべて選択してください
@msg Shape Builder: select paths or compound paths シェイプ形成ツール: パスまたは複合パスを選択してください
@msg image data `{_1}` is missing 画像データ `{_1}` が見つかりません
Can't render this file because it is too large.
+3
View File
@@ -5560,6 +5560,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 ფიგურების კონსტრუქტორი
@@ -6965,6 +6967,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 all paths you want to merge ფიგურების კონსტრუქტორი: მონიშნეთ ყველა ტრაექტორია, რომლის გაერთიანებაც გსურთ
@msg Shape Builder: select paths or compound paths ფიგურების კონსტრუქტორი: მონიშნეთ ტრაექტორიები ან შედგენილი ტრაექტორიები
@msg Show All Hidden Attributes: nothing is hidden ყველა დამალული ატრიბუტის ჩვენება: დამალული არაფერია
Can't render this file because it is too large.
+3
View File
@@ -2469,6 +2469,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 라이브 페인트 선택 도구
@@ -4955,6 +4957,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 all paths you want to merge 모양 빌더: 병합할 패스를 모두 선택하세요
@msg Shape Builder: select paths or compound paths 모양 빌더: 패스 또는 컴파운드 패스를 선택하세요
@msg image data `{_1}` is missing 이미지 데이터 `{_1}`이(가) 없습니다
Can't render this file because it is too large.
+3
View File
@@ -4148,6 +4148,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
@@ -5602,6 +5604,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 all paths you want to merge Vormbouwer: selecteer alle paden die je wilt samenvoegen
@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
Can't render this file because it is too large.
+3
View File
@@ -3681,6 +3681,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
@@ -5300,6 +5302,7 @@ liquify-list-end {0}, {1} {0} i {1}
@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 all paths you want to merge Kreator kształtów: zaznacz wszystkie ścieżki, które chcesz scalić
@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
Can't render this file because it is too large.
+3
View File
@@ -1829,6 +1829,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
@@ -4450,6 +4452,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 all paths you want to merge Criador de formas: selecione todos os traçados que deseja mesclar
@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
Can't render this file because it is too large.
+3
View File
@@ -2195,6 +2195,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 Инструмент «Выделение быстрой заливки»
@@ -5190,6 +5192,7 @@ liquify-list-end {0}, {1} {0} и {1}
@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 all paths you want to merge Создание фигур: выделите все контуры, которые нужно объединить
@msg Shape Builder: select paths or compound paths Создание фигур: выделите контуры или составные контуры
@msg Show All Hidden Attributes: nothing is hidden Показать все скрытые атрибуты: ничего не скрыто
Can't render this file because it is too large.
+3
View File
@@ -2097,6 +2097,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
@@ -5065,6 +5067,7 @@ liquify-list-end {0}, {1} {0} och {1}
@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 all paths you want to merge Formbyggare: markera alla banor du vill sammanfoga
@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
Can't render this file because it is too large.
+3
View File
@@ -1990,6 +1990,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ı
@@ -4900,6 +4902,7 @@ liquify-list-end {0}, {1} {0} ve {1}
@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 all paths you want to merge Şekil Oluşturucu: birleştirmek istediğiniz tüm yolları seçin
@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
Can't render this file because it is too large.
+3
View File
@@ -2203,6 +2203,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 Інструмент «Виділення швидкої заливки»
@@ -5179,6 +5181,7 @@ liquify-list-end {0}, {1} {0} і {1}
@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 all paths you want to merge Створення фігур: виділіть усі контури, які потрібно об’єднати
@msg Shape Builder: select paths or compound paths Створення фігур: виділіть контури або складені контури
@msg Show All Hidden Attributes: nothing is hidden Показати всі приховані атрибути: нічого не приховано
Can't render this file because it is too large.
+3
View File
@@ -2519,6 +2519,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
@@ -6169,6 +6171,7 @@ liquify-list-end {0}, {1} {0} và {1}
@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 all paths you want to merge Xây dựng hình dạng: chọn tất cả đường dẫn bạn muốn hợp nhất
@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
Can't render this file because it is too large.
+3
View File
@@ -2079,6 +2079,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 实时上色选择工具
@@ -4736,6 +4738,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 all paths you want to merge 形状生成器:请选择要合并的所有路径
@msg Shape Builder: select paths or compound paths 形状生成器:请选择路径或复合路径
@msg image data `{_1}` is missing 缺少图像数据 `{_1}`
Can't render this file because it is too large.
+3
View File
@@ -2083,6 +2083,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 all paths you want to merge 形狀建立:請選取要合併的所有路徑
@msg Shape Builder: select paths or compound paths 形狀建立:請選取路徑或複合路徑
@msg image data `{_1}` is missing 找不到影像資料 `{_1}`
@@ -3477,6 +3478,8 @@ liquify-list-end {0}, {1} {0}和{1}
List Workspaces 列出工作區
Live Paint 即時上色
Live Paint Bucket 即時上色油漆桶
Fill Area 填滿區域
Fill Area Tool 填滿區域工具
Live Paint Bucket (Stroke) 即時上色油漆桶 (筆畫)
Live Paint Info 即時上色資訊
Live Paint Selection Tool 即時上色選取工具
Can't render this file because it is too large.
+1
View File
@@ -85,6 +85,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")),
+1
View File
@@ -81,6 +81,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",
+1 -1
View File
@@ -1176,7 +1176,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; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), 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), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), 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, filledLines and lineWidth 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 (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), 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 To Line truncated
"{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; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), 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), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), 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, filledLines and lineWidth 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 (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), 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 To Line truncated
),
(
"ui.colorGuideOptions",
+3 -2
View File
@@ -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"],
],
),
@@ -469,7 +469,8 @@ pub fn open_options(app: &mut VectorcraftApp, tool: &str) -> Result<serde_json::
crate::dialogs::perspective_options::open(app);
Ok(json!({ "dialog": crate::dialogs::perspective_options::KIND }))
}
"shapeBuilder" => 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
+31 -2
View File
@@ -2388,7 +2388,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" ``,
@@ -2409,7 +2409,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 ``.
@@ -13565,6 +13565,35 @@ 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. 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.
```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:
+1
View File
@@ -1547,6 +1547,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`). 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`).