Merge main into feat/decorative-brush-library

This commit is contained in:
dotCooCoo
2026-11-19 10:59:13 -08:00
96 changed files with 7147 additions and 191 deletions
+84 -3
View File
@@ -175,6 +175,7 @@ pub const BUILTIN: &[BuiltinBrushLibrary] = &[
BuiltinBrushLibrary { id: "calligraphic-nibs", name: "Calligraphic Nibs", make: calligraphic_nibs },
BuiltinBrushLibrary { id: "pressure-sensitive", name: "Pressure Sensitive", make: pressure_sensitive },
BuiltinBrushLibrary { id: "bristle-brushes", name: "Bristle Brushes", make: bristle_brushes },
BuiltinBrushLibrary { id: "paint", name: "Paint", make: paint },
BuiltinBrushLibrary { id: "pattern-borders", name: "Pattern Borders", make: pattern_borders },
BuiltinBrushLibrary { id: "decorative", name: "Decorative", make: decorative },
BuiltinBrushLibrary { id: "scatter-shapes", name: "Scatter Shapes", make: scatter_shapes },
@@ -186,6 +187,7 @@ pub const BUILTIN: &[BuiltinBrushLibrary] = &[
BuiltinBrushLibrary { id: "engraving", name: "Engraving", make: engraving },
BuiltinBrushLibrary { id: "arrows", name: "Arrows", make: arrows },
BuiltinBrushLibrary { id: "image-brush", name: "Image Brush", make: image_brush },
BuiltinBrushLibrary { id: "artistic", name: "Artistic Brushes", make: artistic },
];
/// Built-in library `id`, made once.
@@ -239,6 +241,42 @@ fn art(name: &str, art: Node, colorization: Colorization) -> Brush {
Brush { name: name.into(), kind: BrushKind::Art(ArtBrush { art, colorization, ..Default::default() }) }
}
/// Artistic: four original vector compositions that stretch along a path and take its color.
fn artistic() -> BrushLibrary {
let orbit = group(vec![
black(band(100.0, 1.4, 64, |x| 3.0 * (x * std::f64::consts::TAU / 40.0).sin())),
black(band(100.0, 1.4, 64, |x| -3.0 * (x * std::f64::consts::TAU / 40.0).sin())),
]);
let mut petals = vec![black(band(100.0, 0.8, 4, |_| 0.0))];
for i in 0..6 {
let x = 9.0 + 16.0 * i as f64;
let side = if i % 2 == 0 { 1.0 } else { -1.0 };
petals.push(black(polygon(&[(x - 6.0, 0.0), (x - 2.0, 5.0 * side), (x + 5.0, 7.0 * side), (x + 2.0, 2.0 * side)])));
}
let mut lattice = vec![black(band(100.0, 0.9, 4, |_| 0.0))];
for i in 0..5 {
let x = 20.0 * i as f64;
lattice.push(black(polygon(&[(x, -4.0), (x + 1.0, -4.0), (x + 20.0, 4.0), (x + 19.0, 4.0)])));
lattice.push(black(polygon(&[(x, 4.0), (x + 1.0, 4.0), (x + 20.0, -4.0), (x + 19.0, -4.0)])));
}
let mut facets = Vec::new();
for i in 0..8 {
let x = 12.5 * i as f64;
let high = if i % 2 == 0 { 6.0 } else { 3.5 };
facets.push(black(polygon(&[(x, -high), (x + 11.0, -high / 2.0), (x + 12.5, 0.0), (x + 11.0, high / 2.0), (x, high)])));
}
built(
"Artistic Brushes",
Document::new(100.0, 100.0),
vec![
art("Orbit Lines", orbit, Colorization::Tints),
art("Petal Garland", group(petals), Colorization::Tints),
art("Lattice Braid", group(lattice), Colorization::Tints),
art("Facet Sweep", group(facets), Colorization::Tints),
],
)
}
/// Original fine-line art for an engraving-style brush library.
fn engraving() -> BrushLibrary {
let lines = |count: usize, width: f64, spacing: f64| {
@@ -595,6 +633,45 @@ fn spacer(r: Rect) -> Node {
Node::path(NodeId(0), shapes::rectangle(r), Appearance::default())
}
/// Paint: original filled vector art with broad, broken, loaded, and fanned marks. Each is one
/// stroke stretched along the path, with an intentionally different edge and paint distribution.
fn paint() -> BrushLibrary {
let flat_sweep = group(vec![
black(band(100.0, 5.0, 64, |x| 0.8 * (x / 100.0 * std::f64::consts::TAU).sin())),
black(polygon(&[(0.0, -2.5), (7.0, -3.8), (18.0, -2.5)])),
black(polygon(&[(78.0, 2.5), (94.0, 4.0), (100.0, 2.5)])),
]);
let mut dry_drag = vec![];
for (y, shift) in [(-5.0, 0.0), (-3.2, 4.0), (-1.3, 1.0), (0.8, 6.0), (2.8, 3.0), (4.8, 8.0)] {
dry_drag.push(black(shapes::rectangle(Rect::new(2.0 + shift, y, 35.0 + shift, y + 0.8))));
dry_drag.push(black(shapes::rectangle(Rect::new(40.0 + shift, y, 75.0 - shift / 2.0, y + 0.8))));
dry_drag.push(black(shapes::rectangle(Rect::new(80.0 - shift / 2.0, y, 98.0, y + 0.8))));
}
let mut loaded_stroke = vec![black(band(100.0, 6.0, 64, |x| 1.2 * (x / 100.0 * 2.0 * std::f64::consts::TAU).sin()))];
for (x, r) in [(12.0, 4.2), (39.0, 3.6), (64.0, 4.8), (88.0, 3.9)] {
loaded_stroke.push(black(shapes::ellipse(Rect::new(x - r, -r - 1.5, x + r, r + 1.5))));
}
let mut fan_sweep = vec![];
for i in -2..=2 {
let offset = i as f64;
fan_sweep.push(black(band(100.0, 1.2, 48, |x| offset * (1.4 + x * 0.045) + 0.3 * (x / 100.0 * std::f64::consts::TAU).sin())));
}
let paint_art = |name: &str, art: Node| Brush {
name: name.into(),
kind: BrushKind::Art(ArtBrush { art, width: 150.0, colorization: Colorization::Tints, ..Default::default() }),
};
built(
"Paint",
Document::new(100.0, 100.0),
vec![
paint_art("Flat Sweep", flat_sweep),
paint_art("Dry Drag", group(dry_drag)),
paint_art("Loaded Stroke", group(loaded_stroke)),
paint_art("Fan Sweep", group(fan_sweep)),
],
)
}
/// Pattern Borders: pattern brushes of tiles drawn here; Beads has corner tiles.
fn pattern_borders() -> BrushLibrary {
let zigzag = black(polygon(&[(0.0, 1.4), (5.0, -2.6), (10.0, 1.4), (10.0, 2.6), (5.0, -1.4), (0.0, 2.6)]));
@@ -1078,10 +1155,14 @@ pub fn library(s: &Session, key: &str) -> Option<(LibraryInfo, Arc<BrushLibrary>
return Some(found);
}
if let Some(b) = BUILTIN.iter().find(|b| b.id == key) {
return Some((builtin_info(b), builtin_library(key)?));
return Some((builtin_info(b), builtin_library(b.id)?));
}
let id = libraries(s).into_iter().find(|l| l.name.eq_ignore_ascii_case(key))?.id;
library(s, &id)
if let Some(id) = libraries(s).into_iter().find(|l| l.name.eq_ignore_ascii_case(key)).map(|l| l.id) {
return library(s, &id);
}
// Keep the short built-in alias, but let a user or loaded library own its display name.
let b = key.eq_ignore_ascii_case("Artistic").then(|| BUILTIN.iter().find(|b| b.id == "artistic")).flatten()?;
Some((builtin_info(b), builtin_library(b.id)?))
}
fn library_param(s: &Session, p: &Value, cmd: &str) -> Result<(LibraryInfo, Arc<BrushLibrary>)> {
+10 -5
View File
@@ -84,7 +84,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Convert Color",
[],
None,
"{color (#rrggbbaa and #rgba are refused), to: \"rgb\"|\"cmyk\"|\"gray\"|\"lab\", intent?} → {model, values, hex, lab: [L,a,b], outOfGamut, deltaE}",
"{color (#rrggbbaa and #rgba are refused), to: \"rgb\"|\"cmyk\"|\"gray\"|\"lab\"|\"oklch\", intent?} → {model, values, hex, lab: [L,a,b], outOfGamut, deltaE}; oklch values are [L (0..100 %), C, H (0..360°)] of the color's display sRGB (CSS Color 4 OKLCH: https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch), with H 0 for a gray; a color outside sRGB (a Lab color, a CMYK color or an RGB color in a wider working RGB space) is clipped to sRGB first",
always,
convert_color
),
@@ -1362,10 +1362,15 @@ fn convert_color(_: &mut Session, p: &Value) -> Result<Value> {
let intent = intent_param(p, C)?.unwrap_or(c.settings().intent);
let lab = c.lab(&col);
let (model, vals) = match text_param(p, "to", C)?.unwrap_or("rgb") {
"rgb" => ("rgb", values(&c.convert(&col, Model::Rgb, intent))),
"cmyk" => ("cmyk", values(&c.convert(&col, Model::Cmyk, intent))),
"gray" | "grayscale" => ("gray", values(&c.convert(&col, Model::Gray, intent))),
"lab" => ("lab", vec![lab.l, lab.a, lab.b]),
"rgb" => ("rgb", json!(values(&c.convert(&col, Model::Rgb, intent)))),
"cmyk" => ("cmyk", json!(values(&c.convert(&col, Model::Cmyk, intent)))),
"gray" | "grayscale" => ("gray", json!(values(&c.convert(&col, Model::Gray, intent)))),
"lab" => ("lab", json!([lab.l, lab.a, lab.b])),
"oklch" => {
// RGB numbers past 0..1 ([2, 2, 2]) display clipped, as `hex` reports them.
let [l, ch, h] = vectorcraft_color::oklab::to_oklch(c.display_rgb(&col).map(|v| v.clamp(0.0, 1.0)));
("oklch", json!([l * 100.0, ch, h]))
}
other => return Err(bad(C, format!("unknown model `{other}`"))),
};
let de = c.gamut_error(&col);
+53
View File
@@ -105,6 +105,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
arc
),
cmd!(
"shape.threePointArc",
"Three-Point Arc",
[],
None,
"{start: [x, y], end: [x, y], through?: [x, y], toward?: [x, y], at?: \"start\"|\"end\" (default \"start\"; only with `toward`)} → {id, cx, cy, radius, sweep}: an open circular arc from `start` to `end` in the current stroke (black when it is none) with no fill, its ends exactly at the two points (not pixel-aligned). With `through`, the arc passes through that point, an anchor of the path; with `toward`, it leaves the end `at` names heading toward that point (its tangent there). Give exactly one of `through` and `toward`; `at` with `through` is an error. `sweep` is the arc's turn in degrees, positive clockwise on the page. Two points that are the same, three on one line, or an arc reaching past the canvas are an error, and nothing is drawn",
has_doc,
three_point_arc
),
cmd!(
"shape.rectangularGrid",
"Rectangular Grid",
@@ -680,6 +689,50 @@ fn arc(s: &mut Session, p: &Value) -> Result<Value> {
insert_look_turned(s, "Arc", path_kind(path, None), look, None, true, bbox_angle, true)
}
/// An open circular arc from `start` to `end` ([`shapes::CircularArc`]): through `through`, or
/// leaving the end `at` names toward `toward`. One undo step, named as an Arc tool drag is.
fn three_point_arc(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "shape.threePointArc";
let point = |key: &str| finite_numbers::<2>(&p[key]).map(|[x, y]| Point::new(x, y)).ok_or_else(|| bad(C, format!("`{key}` must be [x, y]")));
let (start, end) = (point("start")?, point("end")?);
let from_end = match p.get("at") {
None => false,
Some(Value::String(v)) if v == "start" || v == "end" => v == "end",
Some(_) => return Err(bad(C, "`at` must be \"start\" or \"end\"")),
};
// The arc, and the point it passes through (an anchor of the path, so the path meets it exactly).
let (arc, via) = match (p.get("through"), p.get("toward")) {
(Some(_), None) if p.get("at").is_some() => return Err(bad(C, "give `at` only with `toward`")),
(Some(_), None) => {
let through = point("through")?;
(shapes::CircularArc::through(start, end, through), Some(through))
}
(None, Some(_)) if from_end => {
let toward = point("toward")?;
(shapes::CircularArc::arriving(start, end, end - toward), None)
}
(None, Some(_)) => {
let toward = point("toward")?;
(shapes::CircularArc::leaving(start, toward - start, end), None)
}
_ => return Err(bad(C, "give exactly one of `through` and `toward`")),
};
let arc = arc.ok_or_else(|| bad(C, "no arc fits these points: two are the same or all three lie on one line"))?;
let path = via.map_or_else(|| arc.to_path(), |v| arc.to_path_via(v));
let look = s.new_art_look(
vectorcraft_color::Paint::None,
if s.paint.stroke.is_none() { vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK) } else { s.paint.stroke.clone() },
s.paint.stroke_width.max(0.1),
);
// Not pixel-aligned: the ends stay on the given points.
let mut out = insert_look_turned(s, "Arc", path_kind(path, None), look, None, true, 0.0, false)?;
out["cx"] = json!(arc.center.x);
out["cy"] = json!(arc.center.y);
out["radius"] = json!(arc.radius);
out["sweep"] = json!(arc.sweep.to_degrees());
Ok(out)
}
/// The grid `paths` (bottom first) as one selected group in the new-art stroke, filled with the
/// current fill when `fill`; a path of several subpaths becomes a compound path of them. The group
/// and its members get the bounding-box angle `bbox_angle` (a grid drawn along a Constrain Angle).
+16
View File
@@ -244,12 +244,22 @@ pub(super) fn spine_move_anchor(s: &mut Session, p: &Value) -> Result<Value> {
Some(_) => return Err(bad(C, "handle must be in or out")),
};
let independent = switch_or(p, "independent", false, C)?;
let symmetric = switch_or(p, "symmetric", false, C)?;
let link = switch_or(p, "link", false, C)?;
let with = spine_points_param(p, C)?;
// Any `with`, even an empty list, asks to move points, which a handle drag doesn't.
if handle.is_some() && p.get("with").is_some_and(|v| !v.is_null()) {
return Err(bad(C, "`with` moves points, not a handle"));
}
if symmetric && independent {
return Err(bad(C, "`independent` and `symmetric` cannot both be true"));
}
if symmetric && handle.is_none() {
return Err(bad(C, "`symmetric` places a handle: give `handle`"));
}
if link && symmetric {
return Err(bad(C, "`link` and `symmetric` cannot both be true"));
}
if link && independent {
return Err(bad(C, "`link` and `independent` cannot both be true"));
}
@@ -264,6 +274,8 @@ pub(super) fn spine_move_anchor(s: &mut Session, p: &Value) -> Result<Value> {
}
edit_spine(s, p, C, "Reshape Spine", |sp, anchors, keys| {
let pull_out = handle.is_some_and(|out| sp.has_segment(index, !out));
// At an open end of the spine the handle moves as it would without `symmetric`.
let symmetric = symmetric && pull_out;
let a = sp.anchors.get_mut(index).ok_or_else(|| bad(C, "no such spine point"))?;
if let Some(out) = handle {
if link {
@@ -271,6 +283,10 @@ pub(super) fn spine_move_anchor(s: &mut Session, p: &Value) -> Result<Value> {
} else {
a.set_handle(out, q, independent);
}
if symmetric {
let opposite = a.p - (q - a.p);
if out { a.h_in = opposite } else { a.h_out = opposite }
}
return Ok(());
}
let delta = q - a.p;
+1 -1
View File
@@ -99,7 +99,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Move Spine Point",
[],
None,
"{id? (default: the selected blend), anchor: index, x, y, with?: [index…], handle?: in|out, independent?: bool, link?: bool} move a point of the blend's spine (its handles along), and the points `with` names by as much, or with `handle` place that handle's end at (x, y) (a smooth point keeps the other handle in line unless `independent`; `link` makes the point smooth with the other handle in line at its own length, a retracted one pulled out to the moved handle's length where a segment leaves the point on its side; `link` needs `handle` and cannot go with `independent`). A key object sitting on a moved point moves with it. The first edit turns the straight spine into a path",
"{id? (default: the selected blend), anchor: index, x, y, with?: [index…], handle?: in|out, independent?: bool, symmetric?: bool, link?: bool} move a point of the blend's spine (its handles along), and the points `with` names by as much, or with `handle` place that handle's end at (x, y) (a smooth point keeps the other handle in line unless `independent`; `symmetric` mirrors the opposite handle about the anchor without changing its kind, except at an open end of the spine; `link` makes the point smooth with the other handle in line at its own length, a retracted one pulled out to the moved handle's length where a segment leaves the point on its side; `symmetric` and `link` need `handle`, `symmetric` cannot go with `independent`, and `link` cannot go with `independent` or `symmetric`; all default false). A key object sitting on a moved point moves with it. The first edit turns the straight spine into a path",
has_doc,
spine_move_anchor
),
+26 -1
View File
@@ -50,7 +50,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Move Direction Handle",
[],
None,
"{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool, link?: bool, at?: [x,y]} move a direction handle; independent moves only that side and makes the anchor a corner; link makes the anchor smooth with the other handle in line at its own length (a retracted one is pulled out to the moved handle's length where a segment leaves the anchor on its side); link and independent cannot both be true; both default false; with link false, at moves the anchor and both handles before placing the chosen handle",
"{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool, symmetric?: bool, link?: bool, at?: [x,y]} move a direction handle; independent moves only that side and makes the anchor a corner; symmetric mirrors the other handle about the anchor without changing its kind (not at an open end, where no segment leaves the anchor on that side); link makes the anchor smooth with the other handle in line at its own length (a retracted one is pulled out to the moved handle's length where a segment leaves the anchor on its side); independent and symmetric cannot both be true, and link cannot go with either; all default false; with link false, at moves the anchor and both handles before placing the chosen handle",
has_doc,
set_handle
),
@@ -461,6 +461,13 @@ fn set_handle(s: &mut Session, p: &Value) -> Result<Value> {
return link_handle(s, p, id, si, ai, out, pos);
}
let independent = switch_or(p, "independent", false, "path.setHandle")?;
let symmetric = switch_or(p, "symmetric", false, "path.setHandle")?;
if symmetric && independent {
return Err(bad("path.setHandle", "`independent` and `symmetric` cannot both be true"));
}
// The other handle is mirrored only where a segment leaves the anchor on its side: at an open
// end the handle moves as it would without `symmetric`.
let symmetric = symmetric && has_segment(s, id, si, ai, !out)?;
let at = match p.get("at").filter(|v| !v.is_null()) {
None => None,
Some(v) => Some(finite_numbers(v).map(|[x, y]| Point::new(x, y)).ok_or_else(|| bad("path.setHandle", "`at` must be [x, y]"))?),
@@ -472,6 +479,7 @@ fn set_handle(s: &mut Session, p: &Value) -> Result<Value> {
&& at.is_none_or(|to| to == a.p)
&& (if out { a.h_out } else { a.h_in }) == pos
&& !(independent && a.kind != AnchorKind::Corner)
&& (!symmetric || (if out { a.h_in } else { a.h_out }) == a.p - (pos - a.p))
{
return ok();
}
@@ -504,6 +512,10 @@ fn set_handle(s: &mut Session, p: &Value) -> Result<Value> {
} else {
a.set_handle(out, pos, independent);
}
if symmetric {
let opposite = a.p - (pos - a.p);
if out { a.h_in = opposite } else { a.h_out = opposite }
}
Ok(())
})?;
ok()
@@ -519,6 +531,9 @@ fn link_handle(s: &mut Session, p: &Value, id: NodeId, si: usize, ai: usize, out
if switch_or(p, "independent", false, C)? {
return Err(bad(C, "`link` and `independent` cannot both be true"));
}
if switch_or(p, "symmetric", false, C)? {
return Err(bad(C, "`link` and `symmetric` cannot both be true"));
}
if !(pos.x.abs() < 1e9 && pos.y.abs() < 1e9) {
return Err(bad(C, "x and y must be finite"));
}
@@ -655,6 +670,16 @@ fn anchor_of(s: &Session, id: NodeId, si: usize, ai: usize) -> Result<Option<Anc
Ok(d.node(id).and_then(|n| n.path_data()).and_then(|path| path.subpaths.get(si)).and_then(|sp| sp.anchors.get(ai)).copied())
}
/// Whether anchor `ai` of subpath `si` of path `id` has a segment on its outgoing (`out`) or
/// incoming side; false when the path, subpath or anchor is not there.
fn has_segment(s: &Session, id: NodeId, si: usize, ai: usize, out: bool) -> Result<bool> {
if s.script_running() {
return Err(EngineError::Busy);
}
let d = &s.doc()?.doc;
Ok(d.node(id).and_then(|n| n.path_data()).and_then(|path| path.subpaths.get(si)).is_some_and(|sp| sp.has_segment(ai, out)))
}
fn set_anchors(s: &mut Session, p: &Value) -> Result<Value> {
let id = object_param(p, "id", "path.setAnchors")?.ok_or_else(|| bad("path.setAnchors", "missing id"))?;
let subs = p.get("subpaths").and_then(Value::as_array).ok_or_else(|| bad("path.setAnchors", "missing subpaths"))?;
@@ -572,6 +572,7 @@ pub(super) const ALLOWED: &[&str] = &[
"shape.rectangularGrid",
"shape.spiral",
"shape.star",
"shape.threePointArc",
"shapeBuilder.merge",
"shapeBuilder.regions",
"shaper.expand",
+7
View File
@@ -752,6 +752,13 @@ impl Session {
t.set_option("cornerRadius", &r);
}
}
// A press of the tool that is dropped keeps the new radius, also when the tool lent a
// selection tool for the press.
if self.press_taken_by("roundedRectangle")
&& let Some((_, saved)) = self.press_options.as_mut()
{
saved.insert("cornerRadius".into(), r);
}
}
if fonts_folder_changed {
let folder = self.prefs.fonts_folder.trim();
+6 -2
View File
@@ -122,7 +122,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Move Type Path Handle",
[],
None,
"{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool} move a direction handle of an anchor of type on a path's path to (x, y), as path.setHandle moves a path's (independent: that side only, the anchor becomes a corner); the start and end brackets keep their fractions of the path and the text reflows along it (what Direct Selection does dragging a handle of the path); no undo step when the handle is already there and the path does not change",
"{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool, symmetric?: bool} move a direction handle of an anchor of type on a path's path to (x, y), as path.setHandle moves a path's (independent: that side only, the anchor becomes a corner; symmetric: mirror the other handle about the anchor without changing its kind, except at an open end of the path; independent and symmetric cannot both be true; both default false); the start and end brackets keep their fractions of the path and the text reflows along it (what Direct Selection does dragging a handle of the path); no undo step when the handle is already there and the path does not change",
has_doc,
set_path_handle
),
@@ -1449,6 +1449,10 @@ fn set_path_handle(s: &mut Session, p: &Value) -> Result<Value> {
let out = super::object::choice(p, C, "which", &["in", "out"])? != Some("in");
let pos = vectorcraft_geom::Point::new(f64_req(p, "x", C)?, f64_req(p, "y", C)?);
let independent = switch_or(p, "independent", false, C)?;
let symmetric = switch_or(p, "symmetric", false, C)?;
if symmetric && independent {
return Err(bad(C, "`independent` and `symmetric` cannot both be true"));
}
let node = s.doc()?.doc.node(id);
let on_path = matches!(node.map(|n| &n.kind), Some(NodeKind::Text(t)) if matches!(t.kind, vectorcraft_doc::TextKind::OnPath { .. }));
if !on_path || node.is_some_and(|n| n.extras().perspective.is_some()) {
@@ -1461,7 +1465,7 @@ fn set_path_handle(s: &mut Session, p: &Value) -> Result<Value> {
let within = |t: &TextObject| {
t.type_path().and_then(|p| p.bounds()).is_some_and(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.abs() <= crate::MAX_COORD))
};
if !(t.set_path_handle((si, ai), out, pos, independent) && within(t)) {
if !(t.set_path_handle_with_symmetry((si, ai), out, pos, independent, symmetric) && within(t)) {
t.kind = before;
return Err(bad(C, "no such path anchor, or the path would reach past the canvas"));
}
+3
View File
@@ -329,6 +329,9 @@ pub struct Session {
/// The id and persistent options of the tool when the press under way began, which a dropped
/// press puts back ([`Session::drop_tool_press`]).
pub(crate) press_options: Option<(String, serde_json::Map<String, serde_json::Value>)>,
/// An option of the active tool was set during the press under way, which stored all of its
/// options, so a dropped press stores the options it puts back.
pub(crate) press_options_stored: bool,
/// The engine saves the selection and active layer before a Type press and restores them if it drops.
pub(crate) press_type_selection: Option<(Selection, Option<NodeId>)>,
/// The freeform gradient point selected once the tool took the press under way, which a
+1
View File
@@ -137,6 +137,7 @@ impl Session {
plane_widget_press: false,
pointer_held: false,
press_options: None,
press_options_stored: false,
press_type_selection: None,
press_point: None,
ruler_guide: None,
+1
View File
@@ -208,6 +208,7 @@ mod targeting;
mod textcombos;
mod textedit;
pub(super) mod textimport;
mod three_point_arc;
mod tileedge;
mod tints;
mod toolsettings;
+96 -1
View File
@@ -112,6 +112,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
"calligraphic-nibs",
"pressure-sensitive",
"bristle-brushes",
"paint",
"pattern-borders",
"decorative",
"scatter-shapes",
@@ -122,7 +123,8 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
"tech-circuit",
"engraving",
"arrows",
"image-brush"
"image-brush",
"artistic"
]
);
assert!(libs.iter().all(|l| l["category"] == "builtIn"));
@@ -191,6 +193,7 @@ fn every_builtin_library_brush_has_its_kind_and_draws() {
("calligraphic-nibs", "calligraphic"),
("pressure-sensitive", "art"),
("bristle-brushes", "bristle"),
("paint", "art"),
("pattern-borders", "pattern"),
("decorative", "pattern"),
("scatter-shapes", "scatter"),
@@ -200,6 +203,7 @@ fn every_builtin_library_brush_has_its_kind_and_draws() {
("dry-media", "art"),
("arrows", "art"),
("image-brush", "scatter"),
("artistic", "art"),
] {
let (_, lib) = cmd::brushlib::library(&s, id).unwrap();
assert!(lib.len() >= 4, "{id}");
@@ -228,6 +232,46 @@ fn builtin_library_brushes_bring_the_resources_their_art_uses() {
assert!(shapes.doc.symbols.iter().any(|x| x.name == "Sparkle"));
}
#[test]
fn artistic_library_strokes_are_editable_and_reopen_from_a_saved_library() {
let mut s = session();
let (_, lib) = cmd::brushlib::library(&s, "artistic").unwrap();
let (_, alias) = cmd::brushlib::library(&s, "Artistic").unwrap();
assert_eq!(alias.brushes, lib.brushes);
assert_eq!(run(&mut s, "brush.library", json!({"library": "Artistic"}))["id"], "artistic");
let names = ["Orbit Lines", "Petal Garland", "Lattice Braid", "Facet Sweep"];
assert_eq!(lib.brushes.iter().map(|b| b.name.as_str()).collect::<Vec<_>>(), names);
let line = run(&mut s, "shape.line", json!({"x1": 10, "y1": 50, "x2": 190, "y2": 50}))["id"].as_u64().unwrap();
let red = vectorcraft_doc::StrokeLayer::new(vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0)), 1.0);
for b in &lib.brushes {
let BrushKind::Art(a) = &b.kind else { panic!("{} is not an art brush", b.name) };
assert!(art_paths(&a.art).len() >= 2, "{} has no editable vector art", b.name);
for path in [line_to(180.0), line_to(1.0)] {
assert!(!vectorcraft_brush::stroke_pieces(&lib.doc, b, &path, &black_stroke()).is_empty(), "{} draws nothing", b.name);
}
// The art is black, so with Tints every path takes the stroke color itself.
let mut fills = vec![];
for piece in vectorcraft_brush::stroke_pieces(&lib.doc, b, &line_to(180.0), &red) {
piece.walk(&mut |n| {
if n.path_data().is_some() {
fills.push(n.appearance.fill_paint().color().map(|c| c.to_rgb()));
}
});
}
let is_red = |c: &Option<[f32; 3]>| c.is_some_and(|[r, g, b]| (r - 1.0).abs() < 1e-5 && g.abs() < 1e-5 && b.abs() < 1e-5);
assert!(!fills.is_empty() && fills.iter().all(is_red), "{} does not take the stroke color: {fills:?}", b.name);
let before = undo_len(&s);
let added = run(&mut s, "brush.addFromLibrary", json!({"library": "artistic", "name": b.name, "apply": true, "ids": [line]}));
assert_eq!(strs(&added["added"]), [b.name.as_str()]);
assert_eq!(added["applied"], json!([line]));
assert_eq!(undo_len(&s), before + 1);
}
let saved = run(&mut s, "brush.saveLibrary", json!({"names": names}));
let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap();
let reopened = vectorcraft_format::load(&bytes).unwrap();
assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes);
}
#[test]
fn image_brush_stamps_draw_and_carry_their_pixels_when_added_and_saved() {
let mut s = session();
@@ -265,6 +309,26 @@ fn image_brush_stamps_draw_and_carry_their_pixels_when_added_and_saved() {
assert_eq!(reopened.images, lib.doc.images);
}
#[test]
fn a_loaded_library_named_artistic_keeps_its_name_ahead_of_the_builtin_alias() {
let mut file = vectorcraft_doc::Document::new(100.0, 100.0);
vectorcraft_brush::store(&mut file, &[vectorcraft_brush::defaults()[0].clone()]);
let b64 = vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&file));
let mut s = session();
let loaded = run(&mut s, "brush.loadLibrary", json!({"dataBase64": b64, "name": "Artistic.vectorcraft"}));
assert_eq!(loaded["name"], "Artistic");
let id = loaded["library"].as_str().unwrap();
assert_eq!(run(&mut s, "brush.library", json!({"library": "Artistic"}))["id"], id);
assert_eq!(run(&mut s, "brush.library", json!({"library": "ARTISTIC"}))["id"], id);
assert_eq!(run(&mut s, "brush.library", json!({"library": "artistic"}))["id"], "artistic", "exact built-in id still works");
// A name a built-in library has selects the built-in, as for every built-in; the loaded one keeps its id.
let full = run(&mut s, "brush.loadLibrary", json!({"dataBase64": b64, "name": "Artistic Brushes.vectorcraft"}));
assert_eq!(full["name"], "Artistic Brushes");
let full_id = full["library"].as_str().unwrap();
assert_eq!(run(&mut s, "brush.library", json!({"library": "Artistic Brushes"}))["id"], "artistic");
assert_eq!(run(&mut s, "brush.library", json!({"library": full_id}))["id"], full_id);
}
/// Every path of brush art `n`: (anchors, opacity).
fn art_paths(n: &vectorcraft_doc::Node) -> Vec<(usize, f32)> {
let mut out = vec![];
@@ -599,6 +663,37 @@ fn pressure_sensitive_brushes_widen_with_pen_pressure_and_survive_a_saved_librar
assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes);
}
#[test]
fn paint_brushes_draw_distinct_marks_and_survive_a_saved_library() {
let mut s = session();
let (_, lib) = cmd::brushlib::library(&s, "Paint").unwrap();
let names = ["Flat Sweep", "Dry Drag", "Loaded Stroke", "Fan Sweep"];
assert_eq!(lib.brushes.iter().map(|b| b.name.as_str()).collect::<Vec<_>>(), names);
let path = run(&mut s, "shape.line", json!({"x1": 10, "y1": 40, "x2": 190, "y2": 40}))["id"].as_u64().unwrap();
let mut curve = line_to(20.0);
curve.curve_to((60.0, -25.0), (140.0, 25.0), (180.0, 0.0));
for b in &lib.brushes {
let BrushKind::Art(art) = &b.kind else { panic!("{} is not an art brush", b.name) };
assert_eq!(art.colorization, vectorcraft_brush::Colorization::Tints);
assert_eq!(art.width, 150.0);
for line in [line_to(2.0), line_to(180.0), curve.clone()] {
let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &line, &black_stroke());
let points = anchors(&pieces.iter().collect::<Vec<_>>());
assert!(!points.is_empty() && points.iter().all(|p| p.x.is_finite() && p.y.is_finite()), "{}", b.name);
}
let before = undo_len(&s);
let added = run(&mut s, "brush.addFromLibrary", json!({"library": "paint", "name": b.name, "apply": true, "ids": [path]}));
assert_eq!(strs(&added["added"]), [b.name.as_str()]);
assert_eq!(added["applied"], json!([path]));
assert_eq!(undo_len(&s), before + 1);
assert_eq!(doc(&s).node(NodeId(path)).unwrap().appearance.stroke().unwrap().brush.as_deref(), Some(b.name.as_str()));
}
let saved = run(&mut s, "brush.saveLibrary", json!({"names": names}));
let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap();
let reopened = vectorcraft_format::load(&bytes).unwrap();
assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes);
}
/// Ink and Wash: a tapered ink art brush, a brush pen whose size follows the pen pressure and two
/// translucent washes, with names of their own and a few paths of art each.
#[test]
+39
View File
@@ -318,6 +318,45 @@ fn convert_query_and_intents() {
assert!(s.execute("color.convert", &json!({"color": "#808080", "intent": "vivid"})).is_err());
}
/// `to: "oklch"` answers the OKLCH of the color's display sRGB, which converts back to the color;
/// a CMYK color's display color, not its naive separation, sets them.
#[test]
fn convert_to_oklch_answers_lightness_chroma_and_hue() {
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
let mut s = session();
let r = s.execute("color.convert", &json!({"color": "#ff0000", "to": "oklch"})).unwrap();
assert_eq!(r["model"], "oklch");
let v: Vec<f64> = r["values"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect();
assert!((v[0] - 62.80).abs() < 0.005 && (v[1] - 0.2577).abs() < 5e-5 && (v[2] - 29.23).abs() < 0.005, "{r}");
let (rgb, lowered) = vectorcraft_color::oklab::from_oklch(v[0] / 100.0, v[1], v[2]);
assert!(!lowered);
assert_eq!(Color::rgb(rgb[0], rgb[1], rgb[2]).to_hex(), "#ff0000");
assert_eq!(r["hex"], "#ff0000");
let gray = s.execute("color.convert", &json!({"color": "#808080", "to": "oklch"})).unwrap();
assert_eq!(gray["values"][2], 0.0, "{gray}");
let ink = json!({"c": 1.0, "m": 0.0, "y": 0.0, "k": 0.0});
let cyan = s.execute("color.convert", &json!({"color": ink, "to": "oklch"})).unwrap();
let shown = vectorcraft_color::oklab::to_oklch(cms::active().display_rgb(&Color::cmyk(1.0, 0.0, 0.0, 0.0)));
let naive = vectorcraft_color::oklab::to_oklch([0.0, 1.0, 1.0]);
let c: Vec<f64> = cyan["values"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect();
let got = [c[0] / 100.0, c[1], c[2]];
assert!((0..3).all(|i| (got[i] - shown[i]).abs() < 1e-9) && shown[1] > 0.05, "{cyan} {shown:?}");
assert!((got[0] - naive[0]).abs() > 0.02, "{cyan} {naive:?}");
// A Lab color outside sRGB answers the OKLCH of its color clipped to sRGB.
let vivid = s.execute("color.convert", &json!({"color": {"l": 50.0, "a": 100.0, "b": 0.0}, "to": "oklch"})).unwrap();
let w: Vec<f64> = vivid["values"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect();
let shown = cms::active().display_rgb(&Color::lab(50.0, 100.0, 0.0)).map(|v| v.clamp(0.0, 1.0));
let clipped = vectorcraft_color::oklab::to_oklch(shown);
assert!((w[0] / 100.0 - clipped[0]).abs() < 1e-9 && (w[1] - clipped[1]).abs() < 1e-9, "{vivid} {clipped:?}");
assert!((w[2] - clipped[2]).abs() < 1e-9 && (0.0..360.0).contains(&w[2]), "{vivid} {clipped:?}");
assert!(vectorcraft_color::oklab::in_srgb(vectorcraft_color::oklab::oklch_to_srgb(w[0] / 100.0, w[1], w[2])), "{vivid}");
// RGB numbers past 0..1 answer the OKLCH of the clipped color `hex` reports: white.
let past = s.execute("color.convert", &json!({"color": [2.0, 2.0, 2.0], "to": "oklch"})).unwrap();
assert_eq!(past["hex"], "#ffffff");
let l = past["values"][0].as_f64().unwrap();
assert!((l - 100.0).abs() < 0.01 && past["values"][1].as_f64().unwrap() < 1e-3, "{past}");
}
#[test]
fn assign_profile_is_stored_and_undoable() {
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
+220
View File
@@ -0,0 +1,220 @@
//! `shape.threePointArc`: an open circular arc between two ends, through a third point or
//! leaving an end toward it, and the Three-Point Arc tool's clicks that run it.
use serde_json::{Value, json};
use vectorcraft_doc::{Node, NodeKind};
use vectorcraft_geom::Point;
use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey};
use crate::*;
const C: &str = "shape.threePointArc";
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
s
}
fn node(s: &Session, id: NodeId) -> Node {
s.doc().unwrap().doc.node(id).unwrap().clone()
}
fn undo_len(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
fn object_count(s: &Session) -> usize {
let mut n = 0;
s.doc().unwrap().doc.walk(|_| n += 1);
n
}
fn id_of(v: &Value) -> NodeId {
NodeId(v["id"].as_u64().unwrap())
}
/// The largest distance of `points` from the path of `id`.
fn farthest_from_path(s: &Session, id: NodeId, points: &[Point]) -> f64 {
let n = node(s, id);
let path = n.path_data().unwrap();
points.iter().map(|p| path.nearest(*p).unwrap().4).fold(0.0, f64::max)
}
/// The arc from (0, 0) to (80, 0) through (40, -40) is the upper half of the circle about
/// (40, 0) with radius 40: an open path from one end to the other, through the third point, with
/// no fill and a stroke, selected, and one undo step.
#[test]
fn the_arc_through_a_third_point_is_an_open_path_and_one_undo_step() {
let mut s = session();
let undo = undo_len(&s);
let out = s.execute(C, &json!({"start": [0, 0], "end": [80, 0], "through": [40, -40]})).unwrap();
assert_eq!((out["cx"].as_f64(), out["cy"].as_f64(), out["radius"].as_f64()), (Some(40.0), Some(0.0), Some(40.0)), "{out}");
// From (0, 0) over the top to (80, 0): clockwise on the page.
assert!((out["sweep"].as_f64().unwrap() - 180.0).abs() < 1e-9, "{out}");
let id = id_of(&out);
let n = node(&s, id);
let NodeKind::Path { path, live: None, .. } = &n.kind else { panic!("not a plain path: {:?}", n.kind) };
let sp = &path.subpaths[0];
assert!(!sp.closed && path.subpaths.len() == 1);
assert_eq!((sp.anchors.first().map(|a| a.p), sp.anchors.last().map(|a| a.p)), (Some(Point::ORIGIN), Some(Point::new(80.0, 0.0))));
assert!(farthest_from_path(&s, id, &[Point::new(40.0, -40.0)]) < 1e-9);
assert!(n.appearance.fill_paint().is_none(), "no fill");
assert!(!n.appearance.stroke_paint().is_none(), "a stroke");
assert_eq!(s.doc().unwrap().selection.objects, [id]);
assert_eq!(undo_len(&s), undo + 1);
s.execute("edit.undo", &json!({})).unwrap();
assert!(s.doc().unwrap().doc.node(id).is_none());
// A third point between the quarter turns is an anchor too, so the path meets it exactly.
let via = Point::new(1000.0 * 20f64.to_radians().cos(), 1000.0 * 20f64.to_radians().sin());
let out = s.execute(C, &json!({"start": [1000, 0], "end": [0, 1000], "through": [via.x, via.y]})).unwrap();
let id = id_of(&out);
assert!(node(&s, id).path_data().unwrap().subpaths[0].anchors.iter().any(|a| a.p == via));
assert!(farthest_from_path(&s, id, &[via]) < 1e-9);
}
/// With `toward`, the arc leaves `start` heading at the point (its first handle points there),
/// or with `at: "end"` arrives at `end` along the line from the point to `end` (run backward, the
/// arc leaves `end` heading at the point).
#[test]
fn the_arc_toward_a_point_has_that_tangent_at_its_end() {
let mut s = session();
let out = s.execute(C, &json!({"start": [0, 0], "end": [80, 0], "toward": [30, -30]})).unwrap();
let n = node(&s, id_of(&out));
let first = n.path_data().unwrap().subpaths[0].anchors[0];
let d = (first.h_out - first.p).normalize();
assert!((d.dot(vectorcraft_geom::Vec2::new(1.0, -1.0).normalize()) - 1.0).abs() < 1e-12, "{d:?}");
// A quarter turn's tangent: the center is at (40, 40) and the radius √3200.
assert!((out["radius"].as_f64().unwrap() - 3200f64.sqrt()).abs() < 1e-9, "{out}");
let out = s.execute(C, &json!({"start": [0, 0], "end": [80, 0], "toward": [50, -30], "at": "end"})).unwrap();
let n = node(&s, id_of(&out));
let last = *n.path_data().unwrap().subpaths[0].anchors.last().unwrap();
let d = (last.p - last.h_in).normalize();
assert!((d.dot(vectorcraft_geom::Vec2::new(1.0, 1.0).normalize()) - 1.0).abs() < 1e-12, "{d:?}");
// The direction from the start and from the end mirror each other.
assert!((out["cx"].as_f64().unwrap() - 40.0).abs() < 1e-9 && (out["cy"].as_f64().unwrap() - 40.0).abs() < 1e-9, "{out}");
}
/// Points that are the same, a third point on the line through the ends, and an arc reaching past
/// the canvas are refused with a message; nothing is drawn and no undo step is added.
#[test]
fn points_with_no_arc_are_refused() {
let mut s = session();
let (undo, count) = (undo_len(&s), object_count(&s));
for p in [
json!({"start": [0, 0], "end": [0, 0], "through": [10, 10]}),
json!({"start": [0, 0], "end": [80, 0], "through": [40, 0]}),
json!({"start": [0, 0], "end": [80, 0], "through": [120, 0]}),
json!({"start": [0, 0], "end": [80, 0], "through": [80, 0]}),
json!({"start": [0, 0], "end": [80, 0], "toward": [0, 0]}),
json!({"start": [0, 0], "end": [80, 0], "toward": [-50, 0]}),
json!({"start": [0, 0], "end": [80, 0], "toward": [40, 0], "at": "end"}),
json!({"start": [0, 0], "end": [0, 0], "toward": [10, 10]}),
] {
let e = s.execute(C, &p).unwrap_err().to_string();
assert!(e.contains("no arc fits these points"), "{p}: {e}");
}
// Nearly in line beyond the end: the circle's center is about 1.2·10⁷ pt down the page, and the
// arc goes round the far side of it.
let far = json!({"start": [0, 0], "end": [80, 0], "through": [200, 0.001]});
let e = s.execute(C, &far).unwrap_err().to_string();
assert!(e.contains("result would exceed the canvas"), "{e}");
assert_eq!((undo_len(&s), object_count(&s)), (undo, count));
}
/// Missing or malformed points, both or neither of `through` and `toward`, an `at` that is not
/// "start" or "end", and an `at` with `through` are errors; nothing is drawn.
#[test]
fn malformed_params_are_refused() {
let mut s = session();
let count = object_count(&s);
for (p, want) in [
(json!({"end": [80, 0], "through": [40, 40]}), "`start` must be [x, y]"),
(json!({"start": [0, 0], "end": [80], "through": [40, 40]}), "`end` must be [x, y]"),
(json!({"start": [0, 0], "end": [80, 0], "through": [40, "a"]}), "`through` must be [x, y]"),
(json!({"start": [0, 0], "end": [80, 0], "through": null}), "`through` must be [x, y]"),
(json!({"start": [0, 0], "end": [80, 0], "toward": [10, 0, 0]}), "`toward` must be [x, y]"),
(json!({"start": [0, 0], "end": [80, 0]}), "give exactly one of `through` and `toward`"),
(json!({"start": [0, 0], "end": [80, 0], "through": [40, 40], "toward": [0, 40]}), "give exactly one of `through` and `toward`"),
(json!({"start": [0, 0], "end": [80, 0], "toward": [0, 40], "at": "middle"}), "`at` must be \"start\" or \"end\""),
(json!({"start": [0, 0], "end": [80, 0], "toward": [0, 40], "at": null}), "`at` must be \"start\" or \"end\""),
(json!({"start": [0, 0], "end": [80, 0], "through": [40, 40], "at": "end"}), "give `at` only with `toward`"),
(json!({"start": [0, 0], "end": [80, 0], "through": [40, 40], "at": "start"}), "give `at` only with `toward`"),
] {
let e = s.execute(C, &p).unwrap_err().to_string();
assert!(e.contains(want), "{p}: {e}");
}
assert_eq!(object_count(&s), count);
}
/// With Align New Objects to Pixel Grid on, the ends stay on the given points.
#[test]
fn the_arc_is_not_moved_onto_the_pixel_grid() {
let mut s = session();
s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": true})).unwrap();
let id = id_of(&s.execute(C, &json!({"start": [0.3, 0.2], "end": [80.6, 0.1], "through": [40.4, -39.7]})).unwrap());
let n = node(&s, id);
let sp = &n.path_data().unwrap().subpaths[0];
assert_eq!(sp.anchors.first().map(|a| a.p), Some(Point::new(0.3, 0.2)));
assert_eq!(sp.anchors.last().map(|a| a.p), Some(Point::new(80.6, 0.1)));
assert!(!n.extras().pixel_aligned);
}
fn view() -> ViewInfo {
ViewInfo { smart_guides: false, ..ViewInfo::default() }
}
fn click(s: &mut Session, x: f64, y: f64) {
for k in [PointerKind::Down, PointerKind::Up] {
s.pointer(&PointerEvent::new(k, x, y).with_mods(Mods::default()), view()).unwrap();
}
}
/// With the Three-Point Arc tool, three clicks draw the arc in one undo step; `]` before the third
/// click makes the third point give the direction instead. Escape drops the ends.
#[test]
fn three_clicks_with_the_tool_draw_the_arc() {
let mut s = session();
s.select_tool("threePointArc", view()).unwrap();
let (undo, count) = (undo_len(&s), object_count(&s));
click(&mut s, 100.0, 200.0);
click(&mut s, 180.0, 200.0);
assert_eq!((undo_len(&s), object_count(&s)), (undo, count), "two ends draw nothing yet");
click(&mut s, 140.0, 160.0);
assert_eq!(undo_len(&s), undo + 1);
let id = *s.doc().unwrap().selection.objects.first().unwrap();
assert!(farthest_from_path(&s, id, &[Point::new(100.0, 200.0), Point::new(140.0, 160.0), Point::new(180.0, 200.0)]) < 1e-9);
// Escape after the ends: the next clicks start afresh.
click(&mut s, 0.0, 0.0);
click(&mut s, 10.0, 300.0);
s.tool_key(ToolKey::Escape, Mods::default(), view()).unwrap();
click(&mut s, 100.0, 300.0);
click(&mut s, 180.0, 300.0);
s.tool_key(ToolKey::BracketRight, Mods::default(), view()).unwrap();
let undo = undo_len(&s);
// Straight up from the first end: the upper half circle about (140, 300).
click(&mut s, 100.0, 250.0);
assert_eq!(undo_len(&s), undo + 1);
let id = *s.doc().unwrap().selection.objects.first().unwrap();
assert!(farthest_from_path(&s, id, &[Point::new(140.0, 260.0)]) < 1e-9);
}
/// `tool.setOption` (the Tool Options dialog's Save) sets the tool's `direction` option, and
/// refuses a value that is not true or false, or an option the tool doesn't have.
#[test]
fn set_option_sets_the_direction_and_refuses_bad_values() {
let mut s = session();
for on in [true, false] {
let set = s.set_tool_option_cmd(&json!({"tool": "threePointArc", "values": {"direction": on}})).unwrap();
assert_eq!(set["direction"], json!(on));
assert_eq!(s.tool_options_of("threePointArc")["direction"], json!(on));
}
let cases = [
(json!({"tool": "threePointArc", "key": "direction", "value": "yes"}), "tool `threePointArc`: `direction` must be true or false"),
(json!({"tool": "threePointArc", "key": "bogus", "value": true}), "tool `threePointArc`: unknown option `bogus`"),
];
for (p, want) in cases {
assert_eq!(s.set_tool_option_cmd(&p).unwrap_err(), want, "{p}");
}
assert_eq!(s.tool_options_of("threePointArc")["direction"], json!(false));
}
+80
View File
@@ -138,6 +138,86 @@ fn a_dropped_press_does_not_keep_what_its_drag_changed() {
assert_eq!(s.prefs.tool_settings["polygon"]["sides"], json!(7), "and stores its sides");
}
/// An option set with `tool.setOption` while a press is held survives the dropped press, in the
/// tool and in the stored options, while what the drag itself changed is put back in both.
#[test]
fn an_option_set_during_a_dropped_press_is_kept() {
let mut s = session();
select(&mut s, "rectangularGrid");
let v = ViewInfo { smart_guides: false, ..Default::default() };
s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 180.0), v).unwrap();
s.tool_key(ToolKey::Up, Mods::default(), v).unwrap();
s.tool_key(ToolKey::Right, Mods::default(), v).unwrap();
assert_eq!((s.tool_options()["rows"].clone(), s.tool_options()["columns"].clone()), (json!(6), json!(6)));
s.set_tool_option_cmd(&json!({"key": "columns", "value": 9})).unwrap();
s.drop_tool_press(v).unwrap();
let o = s.tool_options();
assert_eq!((o["rows"].clone(), o["columns"].clone()), (json!(5), json!(9)), "the drag's rows go back; the set columns stay");
let saved = &s.prefs.tool_settings["rectangularGrid"];
assert_eq!((saved["rows"].clone(), saved["columns"].clone()), (json!(5), json!(9)), "the drag's rows are not stored; the set columns are");
select(&mut s, "selection");
select(&mut s, "rectangularGrid");
let o = s.tool_options();
assert_eq!((o["rows"].clone(), o["columns"].clone()), (json!(5), json!(9)), "a tool switch keeps the set columns");
// The same through the desktop app's setter.
s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 180.0), v).unwrap();
s.tool_key(ToolKey::Up, Mods::default(), v).unwrap();
s.set_tool_option("columns", &json!(3));
s.drop_tool_press(v).unwrap();
let o = s.tool_options();
assert_eq!((o["rows"].clone(), o["columns"].clone()), (json!(5), json!(3)));
let saved = &s.prefs.tool_settings["rectangularGrid"];
assert_eq!((saved["rows"].clone(), saved["columns"].clone()), (json!(5), json!(3)));
}
/// A Corner Radius preference set while a Rounded Rectangle press is held survives the dropped
/// press, in the tool and in the preference.
#[test]
fn a_corner_radius_set_during_a_dropped_press_is_kept() {
let mut s = session();
select(&mut s, "roundedRectangle");
let v = ViewInfo { smart_guides: false, ..Default::default() };
s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 180.0), v).unwrap();
let mut p = s.prefs.clone();
p.corner_radius = 30.0;
s.apply_prefs(p);
s.drop_tool_press(v).unwrap();
assert_eq!(s.tool_options()["cornerRadius"].as_f64(), Some(30.0), "the tool keeps the new radius");
assert_eq!(s.prefs.corner_radius, 30.0, "the preference keeps it");
}
/// An option set with `tool.setOption` on a tool that lent a selection tool for a Cmd-drag
/// survives the dropped press, in the tool and in the stored options. So does a Corner Radius
/// preference set while the Rounded Rectangle lends one.
#[test]
fn an_option_set_on_a_lending_tool_during_a_dropped_press_is_kept() {
let mut s = session();
select(&mut s, "rectangularGrid");
let v = ViewInfo { smart_guides: false, ..Default::default() };
let cmd = Mods { cmd: true, ..Default::default() };
s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0).with_mods(cmd), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 180.0).with_mods(cmd), v).unwrap();
assert_eq!(s.lender.as_ref().map(|t| t.id()), Some("rectangularGrid"), "the press lent a selection tool");
s.set_tool_option_cmd(&json!({"tool": "rectangularGrid", "key": "columns", "value": 9})).unwrap();
s.drop_tool_press(v).unwrap();
assert_eq!(s.tool_id(), "rectangularGrid", "the lending tool is back");
assert_eq!(s.tool_options()["columns"], json!(9), "the tool keeps the set columns");
assert_eq!(s.prefs.tool_settings["rectangularGrid"]["columns"], json!(9), "and stores them");
select(&mut s, "roundedRectangle");
s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0).with_mods(cmd), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 180.0).with_mods(cmd), v).unwrap();
assert_eq!(s.lender.as_ref().map(|t| t.id()), Some("roundedRectangle"), "the press lent a selection tool");
let mut p = s.prefs.clone();
p.corner_radius = 30.0;
s.apply_prefs(p);
s.drop_tool_press(v).unwrap();
assert_eq!(s.tool_options()["cornerRadius"].as_f64(), Some(30.0), "the tool keeps the new radius");
assert_eq!(s.prefs.corner_radius, 30.0, "the preference keeps it");
}
/// A dropped Pen press drops only the anchor it was placing: the path being drawn goes on with
/// the next click.
#[test]
+66 -7
View File
@@ -298,6 +298,10 @@ impl Session {
let points = self.tool.options().get("meshPoints").cloned().unwrap_or_else(|| Value::Array(vec![]));
lent.set_option("meshPoints", &points);
}
// The Cmd/Ctrl held for the loan is not the Cmd/Ctrl that mirrors a dragged handle (#7842).
if id == "directSelection" {
lent.set_option("lentByCmd", &Value::Bool(true));
}
self.selection_at_lend = self.active().map(|d| (d.uid, d.selection.clone()));
self.lender = Some(std::mem::replace(&mut self.tool, lent));
Ok((PointerEvent { mods: Mods { cmd: false, ..ev.mods }, ..*ev }, settled))
@@ -611,13 +615,18 @@ impl Session {
/// Escape, as during a drag, for most tools), and a release returns the tool to rest. Of what
/// the tool asks for along the way, only a cancel and a notify run, so a marquee selects
/// nothing and a click opens no size dialog. The tool gets back the persistent options it had
/// when the press began, and none of the press's changes to them are stored. A dropped Type
/// press restores the prior selection. The freeform gradient point selected once the tool
/// took the press is selected again. A press held while the tool computes an edit on another
/// thread has not reached the tool: it is removed from the held input with the pointer events
/// and tool keys held after it, and the tool is left as it is. A perspective plane key held
/// after it stays held, since the plane it picks outlasts a dropped press. Pointer events held
/// after the last held release belong to the press the tool has, and are removed with it.
/// when the press began, and none of the press's changes to them are stored. An option set
/// during the press with [`Self::set_tool_option`] or [`Self::set_tool_options`], or a General ›
/// Corner Radius change during a Rounded Rectangle press, keeps its new value, also when the
/// tool lent a selection tool for the press (a Cmd-drag). Setting an option stores all of the
/// tool's options, the press's changes included, so the dropped press then stores the options
/// it puts back. A dropped Type press restores the prior selection. The freeform gradient
/// point selected once the tool took the press is selected again. A press held while the tool
/// computes an edit on another thread has not reached the tool: it is removed from the held
/// input with the pointer events and tool keys held after it, and the tool is left as it is.
/// A perspective plane key held after it stays held, since the plane it picks outlasts a
/// dropped press. Pointer events held after the last held release belong to the press the tool
/// has, and are removed with it.
pub fn drop_tool_press(&mut self, view: ViewInfo) -> Result<()> {
let (from, held) = self.held_press();
let keep: Vec<bool> = (self.held_input.iter().enumerate())
@@ -635,6 +644,7 @@ impl Session {
// Nothing to roll back without a document; the tool still drops the press and gets the release.
let _ = self.cancel_interaction();
let before = self.press_options.take();
let stored = std::mem::take(&mut self.press_options_stored);
let type_selection = self.press_type_selection.take();
let point = self.press_point.take();
let mut acts = self.with_tool_cx(view, |t, cx| t.drop_press(cx));
@@ -669,6 +679,11 @@ impl Session {
self.tool.set_option(k, v);
}
}
// An option set during the press stored every option the tool had then, the press's
// changes included: those stored values are put back too.
if stored {
self.keep_tool_settings();
}
}
r.map(drop)
}
@@ -706,6 +721,7 @@ impl Session {
match ev.kind {
PointerKind::Down => {
self.press_options = Some((self.tool.id().to_string(), Self::persistent_options(self.tool.as_ref())));
self.press_options_stored = false;
self.press_type_selection =
if matches!(self.tool.id(), "type" | "areaType" | "typeOnPath" | "verticalType" | "verticalAreaType" | "verticalTypeOnPath") {
self.active().map(|st| (st.selection.clone(), st.active_layer))
@@ -715,6 +731,7 @@ impl Session {
}
PointerKind::Up => {
self.press_options = None;
self.press_options_stored = false;
self.press_type_selection = None;
}
_ => {}
@@ -1309,9 +1326,12 @@ impl Session {
if key == "queue" && self.tool.id() == "place" {
self.note_place_queue_roots();
}
let before_press = self.options_before_press_set();
let sets_pressed = self.press_taken_by(self.tool.id());
self.tool.set_option(key, v);
self.tool_set_since_reset = true;
self.keep_tool_settings();
self.keep_press_set(before_press, |k| sets_pressed && k == key, sets_pressed);
}
/// Keep the automation roots in force now as those the place cursor's queue, being loaded,
@@ -1356,6 +1376,8 @@ impl Session {
self.note_place_queue_roots();
}
let active = id.is_none_or(|id| id == self.tool.id());
let before_press = self.options_before_press_set();
let sets_pressed = self.press_taken_by(id.unwrap_or(self.tool.id()));
// The tool that lent a selection tool for a Cmd-drag is the tool chosen, and active again
// when the drag ends.
let lender = id.is_some_and(|id| self.lender.as_deref().is_some_and(|l| l.id() == id));
@@ -1393,9 +1415,46 @@ impl Session {
let set = other.id();
Self::restore_stores(&self.prefs, self.tool.as_mut(), |store| settings::stores(set).any(|(s, _)| s == store));
}
self.keep_press_set(before_press, |k| sets_pressed && values.contains_key(k), sets_pressed);
out
}
/// The tool that took the press under way: the active tool, or the tool that lent a selection
/// tool for it (a Cmd-drag), which the dropped press gives its options back to.
fn pressed_tool(&self) -> Option<&dyn Tool> {
let (pressed, _) = self.press_options.as_ref()?;
std::iter::once(&self.tool).chain(self.lender.as_ref()).map(|t| t.as_ref()).find(|t| t.id() == pressed)
}
/// Tool `id` took the press under way ([`Self::pressed_tool`]).
pub(crate) fn press_taken_by(&self, id: &str) -> bool {
self.pressed_tool().is_some_and(|t| t.id() == id)
}
/// The persistent options of the tool that took the press under way ([`Self::pressed_tool`])
/// before an option is set: a dropped press puts back the options it began with, except those
/// the set changes ([`Self::keep_press_set`]).
fn options_before_press_set(&self) -> Option<Map<String, Value>> {
self.pressed_tool().map(Self::persistent_options)
}
/// After an option is set during a held press, the press's saved options take the options of
/// the tool that took the press that the set changed from `before` or named (`named`), so a
/// dropped press keeps them. `stored`: the set stored that tool's options, the press's changes
/// included, so a dropped press stores the options it puts back.
fn keep_press_set(&mut self, before: Option<Map<String, Value>>, named: impl Fn(&str) -> bool, stored: bool) {
let Some(before) = before else { return };
let Some(now) = self.pressed_tool().map(Self::persistent_options) else { return };
self.press_options_stored |= stored;
if let Some((_, saved)) = self.press_options.as_mut() {
for (k, v) in now {
if before.get(&k) != Some(&v) || named(&k) {
saved.insert(k, v);
}
}
}
}
/// `tool.setOption {tool?, key?, value?, values?}` (a command of the desktop app and of the
/// headless host): set one option (`key`, `value`) or several (`values`) of `tool` (default:
/// the tool active when the call arrives, named before the edit in progress is finished) → its