mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-26 14:50:09 +00:00
Brushes: brush.freehand is one undo step and refuses strokeless paths and unknown keys
brush.freehand drew the path with one edit and set the brush with a second, so one Undo left the path without its brush. The brush is now set in the same edit that draws, continues or redraws the path, and the step is named Paintbrush whatever the style. A brush for a path with no stroke (a continued or redrawn path without one, or a new filled "pencil" path while the stroke is None) was skipped and the call still succeeded. It is now refused with "cannot apply brush `<name>`: path has no stroke" before anything changes. The Paintbrush tool sends brush.freehand when a brush is current, so continuing or redrawing such a path with it now shows this error. This rule is VectorCraft's own. brush.freehand is no longer in UNCHECKED: it takes the path.freehand keys and `brush`, and any other key is refused with "unknown parameter".
This commit is contained in:
@@ -19,8 +19,8 @@ use super::edit::{outermost, selected_roots};
|
||||
use super::pathops::{remove_each, separate};
|
||||
use super::swatch::{anchor, names_param};
|
||||
use super::{
|
||||
CommandSpec, Result, Session, bad, check_numbers, cmd, color_param, find_command, has_doc, has_selection, id_param, named_ids, number_or, ok,
|
||||
str_param, switch_or,
|
||||
CommandSpec, Result, Session, bad, check_numbers, cmd, color_param, find_command, has_doc, has_selection, named_ids, number_or, ok, str_param,
|
||||
switch_or,
|
||||
};
|
||||
use crate::EngineError;
|
||||
|
||||
@@ -180,7 +180,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Paintbrush",
|
||||
[],
|
||||
None,
|
||||
"{…params as path.freehand, brush?: name} paint a freehand stroke with a brush; without `brush` (or with null) the plain path is drawn; a `brush` that names no brush in the document, or a `style` other than \"pencil\" or \"brush\", is an error and nothing is drawn → {id}",
|
||||
"{…params as path.freehand, brush?: name} paint a freehand stroke with a brush; without `brush` (or with null) the plain path is drawn; a `brush` that names no brush in the document, a `style` other than \"pencil\" or \"brush\", a `brush` for a path with no stroke (a continued or redrawn path without one, or a new filled \"pencil\" path while the stroke is None) and an unknown key are errors and nothing is drawn; the path and its brush are one undo step → {id}",
|
||||
has_doc,
|
||||
brush_freehand
|
||||
),
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
use super::{
|
||||
AppearanceItem, Arc, BTreeSet, Bristle, Brush, BrushKind, Color, Document, EngineError, Node, NodeId, NodeKind, Paint, Result, Session, Value,
|
||||
anchor, bad, brush, check_numbers, find_command, id_param, ids_json, json, name_param, names_param, ok, roots, selection_art, set_unknown,
|
||||
str_param,
|
||||
anchor, bad, brush, check_numbers, find_command, ids_json, json, name_param, names_param, ok, roots, selection_art, set_unknown, str_param,
|
||||
};
|
||||
|
||||
// ---------- brushes ----------
|
||||
@@ -729,9 +728,10 @@ pub(super) fn expand_brush(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "ids": ids_json(&out) }))
|
||||
}
|
||||
|
||||
/// Paints a `path.freehand` stroke with the brush `brush` names. A `brush` left out or null draws
|
||||
/// the plain path; a `brush` that is not a string or names no brush in the document, and a `style`
|
||||
/// other than "pencil" or "brush", is an error before anything is drawn.
|
||||
/// Paints a `path.freehand` stroke with the brush `brush` names, in one undo step with the path.
|
||||
/// A `brush` left out or null draws the plain path; a `brush` that is not a string or names no
|
||||
/// brush in the document, a `style` other than "pencil" or "brush", and a `brush` for a path with
|
||||
/// no stroke are errors before anything is drawn.
|
||||
pub(super) fn brush_freehand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "brush.freehand";
|
||||
let name = match crate::cmd::text_param(p, "brush", C)? {
|
||||
@@ -745,13 +745,6 @@ pub(super) fn brush_freehand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(v) => return Err(bad(C, format!("`style` must be \"pencil\" or \"brush\", not {v}"))),
|
||||
}
|
||||
let spec = find_command("path.freehand").ok_or_else(|| EngineError::UnknownCommand("path.freehand".into()))?;
|
||||
let r = crate::cmd::run_checked(s, spec, p)?;
|
||||
let (Some(name), Some(id)) = (name, id_param(&r, "id")) else { return Ok(r) };
|
||||
s.edit("Paintbrush", |d, _| {
|
||||
if let Some(st) = d.node_mut(id).and_then(|n| n.appearance.stroke_mut()) {
|
||||
st.brush = Some(name.clone());
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(r)
|
||||
let checked = crate::schemas::check(spec, p, s.replaying())?;
|
||||
crate::cmd::draw2::freehand_brushed(s, checked.as_ref().unwrap_or(p), name.as_deref())
|
||||
}
|
||||
|
||||
@@ -33,3 +33,4 @@ mod smooth;
|
||||
pub use commands::specs;
|
||||
pub(super) use common::{ids_json, replace_with_pieces, usize_opt};
|
||||
pub(super) use cut::{components, erase_outline};
|
||||
pub(super) use freehand::freehand_brushed;
|
||||
|
||||
@@ -157,6 +157,34 @@ fn redraw_section(pd: &PathData, pts: &[Point], tol: Option<f64>, within: f64) -
|
||||
}
|
||||
|
||||
pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
freehand_brushed(s, p, None)
|
||||
}
|
||||
|
||||
/// The object a brush on path `id` paints: the compound path a member path is in, else the path.
|
||||
fn brush_target(d: &Document, id: NodeId) -> NodeId {
|
||||
d.parent_of(id).filter(|p| d.node(*p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }))).unwrap_or(id)
|
||||
}
|
||||
|
||||
/// Whether `ap` has a stroke a brush can paint: a stroke whose paint is not None.
|
||||
fn can_brush(ap: &Appearance) -> bool {
|
||||
ap.stroke().is_some_and(|st| !st.paint.is_none())
|
||||
}
|
||||
|
||||
fn no_stroke(name: &str) -> EngineError {
|
||||
bad("brush.freehand", format!("cannot apply brush `{name}`: path has no stroke"))
|
||||
}
|
||||
|
||||
/// Sets brush `name` on the stroke of object `id` of `d`.
|
||||
fn set_brush(d: &mut Document, id: NodeId, name: &str) {
|
||||
if let Some(st) = d.node_mut(id).and_then(|n| n.appearance.stroke_mut()) {
|
||||
st.brush = Some(name.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
/// `path.freehand`, with the stroke painted with brush `brush_name` (one `brush.freehand` has
|
||||
/// checked) in the same undo step as the path. A path without a stroke is an error before
|
||||
/// anything changes.
|
||||
pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&str>) -> Result<Value> {
|
||||
const C: &str = "path.freehand";
|
||||
let samples = samples_param(p, "points", C)?;
|
||||
if samples.iter().any(|q| !within_input_bound(q.pt)) {
|
||||
@@ -173,6 +201,8 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let fit_tol = switch_or(p, "fit", true, C)?.then_some(tol);
|
||||
let closed = switch_or(p, "closed", false, C)?;
|
||||
let brush = str_param(p, "style") == Some("brush");
|
||||
// The undo step's name: a stroke painted with a brush is a Paintbrush stroke, whatever its style.
|
||||
let label = if brush || brush_name.is_some() { "Paintbrush" } else { "Pencil" };
|
||||
let keep_selected = switch_or(p, "keepSelected", true, C)?;
|
||||
let filled = switch_or(p, "fill", false, C)?;
|
||||
if let Some(ext) = p.get("extend").filter(|v| !v.is_null()) {
|
||||
@@ -180,6 +210,12 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let at_start = str_param(ext, "end") == Some("start");
|
||||
let (pd, _) = path_of(&s.doc()?.doc, id)?;
|
||||
let si = pd.subpaths.iter().rposition(|s| !s.closed && !s.anchors.is_empty()).ok_or_else(|| bad(C, "path has no open end"))?;
|
||||
let target = brush_target(&s.doc()?.doc, id);
|
||||
if let Some(name) = brush_name
|
||||
&& !s.doc()?.doc.node(target).is_some_and(|n| can_brush(&n.appearance))
|
||||
{
|
||||
return Err(no_stroke(name));
|
||||
}
|
||||
let mut sp = pd.subpaths[si].clone();
|
||||
let old_len = subpath_len(&sp);
|
||||
if at_start {
|
||||
@@ -191,6 +227,15 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let Some(p0) = pts.first_mut() else { return Err(bad(C, "needs points")) };
|
||||
*p0 = end;
|
||||
if pts.len() < 2 {
|
||||
// No stroke to add: the brush alone changes, when it is not the path's already.
|
||||
if let Some(name) = brush_name
|
||||
&& s.doc()?.doc.node(target).and_then(|n| n.appearance.stroke()).is_some_and(|st| st.brush.as_deref() != Some(name))
|
||||
{
|
||||
s.edit("Paintbrush", |d, _| {
|
||||
set_brush(d, target, name);
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
return Ok(json!({ "id": id.0 }));
|
||||
}
|
||||
// A stroke that ends on an open end of another path connects the two: (that path, its last
|
||||
@@ -290,7 +335,7 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let drawn = old.extended(old_len, &pen, drawn_len - old_len);
|
||||
if connect.is_some() { drawn.extended(drawn_len, &other, other_len) } else { drawn }
|
||||
});
|
||||
s.edit(if brush { "Paintbrush" } else { "Pencil" }, |d, sel| {
|
||||
s.edit(label, |d, sel| {
|
||||
let reverse = at_start && !sp.closed;
|
||||
if reverse {
|
||||
sp.reverse();
|
||||
@@ -326,6 +371,9 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
{
|
||||
if reverse { joined.reversed() } else { joined }.write(st);
|
||||
}
|
||||
if let Some(name) = brush_name {
|
||||
set_brush(d, target, name);
|
||||
}
|
||||
if keep_selected {
|
||||
sel.set([id]);
|
||||
} else {
|
||||
@@ -346,11 +394,19 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// were, measured along the old path; fit them to the new length if strokes drawn with a
|
||||
// pen get redrawn.
|
||||
if let Some((si, sp)) = redraw_section(&pd, &pts, fit_tol, within) {
|
||||
s.edit(if brush { "Paintbrush" } else { "Pencil" }, |d, sel| {
|
||||
// A member path of a compound path is redrawn in it: the compound path is what is
|
||||
// selected, and what a brush paints.
|
||||
let whole = brush_target(&s.doc()?.doc, id);
|
||||
if let Some(name) = brush_name
|
||||
&& !s.doc()?.doc.node(whole).is_some_and(|n| can_brush(&n.appearance))
|
||||
{
|
||||
return Err(no_stroke(name));
|
||||
}
|
||||
s.edit(label, |d, sel| {
|
||||
*path_mut(d, id)?.subpaths.get_mut(si).ok_or_else(|| bad(C, "no such subpath"))? = sp;
|
||||
// A member path of a compound path is redrawn in it: the compound path is what is
|
||||
// selected.
|
||||
let whole = d.parent_of(id).filter(|p| d.node(*p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }))).unwrap_or(id);
|
||||
if let Some(name) = brush_name {
|
||||
set_brush(d, whole, name);
|
||||
}
|
||||
if keep_selected {
|
||||
sel.set([whole]);
|
||||
} else {
|
||||
@@ -373,7 +429,15 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(st) = look.appearance.stroke_mut() {
|
||||
pen.write(st);
|
||||
}
|
||||
let out = insert_look(s, if brush { "Paintbrush" } else { "Pencil" }, path_kind(PathData::single(sp)), look, None, keep_selected)?;
|
||||
if let Some(name) = brush_name {
|
||||
if !can_brush(&look.appearance) {
|
||||
return Err(no_stroke(name));
|
||||
}
|
||||
if let Some(st) = look.appearance.stroke_mut() {
|
||||
st.brush = Some(name.to_string());
|
||||
}
|
||||
}
|
||||
let out = insert_look(s, label, path_kind(PathData::single(sp)), look, None, keep_selected)?;
|
||||
if !keep_selected {
|
||||
// A new stroke with Keep selected off leaves nothing selected: Illustrator starts the stroke
|
||||
// by dropping the earlier selection, it does not keep it (#5752).
|
||||
|
||||
@@ -512,7 +512,6 @@ pub const UNCHECKED: &[&str] = &[
|
||||
"assets.settings.set",
|
||||
"attributes.info",
|
||||
"attributes.set",
|
||||
"brush.freehand",
|
||||
"css.export",
|
||||
"css.generate",
|
||||
"css.selection",
|
||||
|
||||
@@ -1002,6 +1002,105 @@ fn brush_freehand_refuses_a_brush_or_style_it_cannot_use() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A `brush.freehand` call outside an interaction draws the path and paints it with the brush in
|
||||
/// one undo step: one Undo removes the path and gives back the earlier selection, and one Redo
|
||||
/// brings back the brushed path. Continuing a path with a brush is one step too.
|
||||
#[test]
|
||||
fn brush_freehand_direct_call_has_one_undo_step() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
select(&mut s, &[a]);
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let r = s.execute("brush.freehand", &json!({"points": [[10, 10], [60, 40], [120, 10]], "style": "brush", "brush": "Charcoal"})).unwrap();
|
||||
let id = NodeId(r["id"].as_u64().unwrap());
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step");
|
||||
assert_eq!(brush_of(&s, id).as_deref(), Some("Charcoal"));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(*s.doc().unwrap().doc == *before, "one Undo removes the brushed path");
|
||||
assert_eq!(selected(&s), [a], "Undo gives back the earlier selection");
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(brush_of(&s, id).as_deref(), Some("Charcoal"), "Redo brings back the brush");
|
||||
assert_eq!(selected(&s), [id]);
|
||||
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let p = json!({"points": [[120, 10], [160, 60], [200, 10]], "extend": {"id": id.0, "end": "end"}, "brush": "Dots"});
|
||||
assert_eq!(s.execute("brush.freehand", &p).unwrap()["id"], json!(id.0));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "continuing is one undo step");
|
||||
assert_eq!(brush_of(&s, id).as_deref(), Some("Dots"));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(brush_of(&s, id).as_deref(), Some("Charcoal"), "one Undo takes back the stroke and its brush");
|
||||
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
s.execute("brush.freehand", &json!({"points": [[10, 100], [60, 140], [120, 100]], "style": "pencil", "brush": "Charcoal"})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
|
||||
assert_eq!(s.doc().unwrap().history.undo.last().map(|e| e.label.as_str()), Some("Paintbrush"), "a stroke with a brush is a Paintbrush step");
|
||||
}
|
||||
|
||||
/// `brush.freehand` refuses a brush for a path with no stroke (a continued path, a redrawn one
|
||||
/// and a new filled pencil path while the stroke is None) instead of reporting it painted: the
|
||||
/// document, the selection and the undo history stay as they were. Without a brush the path is
|
||||
/// drawn as `path.freehand` draws it.
|
||||
#[test]
|
||||
fn brush_freehand_refuses_a_brush_on_a_path_without_a_stroke() {
|
||||
let mut s = session();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
let drawn = json!([[10, 10], [60, 20], [90, 80], [20, 90]]);
|
||||
let p = NodeId(s.execute("path.freehand", &json!({"points": drawn, "fill": true})).unwrap()["id"].as_u64().unwrap());
|
||||
assert!(node(&s, p).appearance.stroke_paint().is_none(), "the path has no stroke");
|
||||
// The redraw below replaces a section of the path rather than drawing a new one.
|
||||
let redraw = json!({"points": [[10, 10], [40, 30], [60, 20]], "redraw": {"id": p.0}});
|
||||
assert_eq!(s.execute("path.freehand", &redraw).unwrap()["id"], json!(p.0));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
select(&mut s, &[p]);
|
||||
let extend = json!({"id": p.0, "end": "end"});
|
||||
for (what, mut params) in [
|
||||
("continued", json!({"points": [[20, 90], [0, 120], [-10, 150]], "extend": extend})),
|
||||
("continued by one point", json!({"points": [[20, 90]], "extend": extend})),
|
||||
("redrawn", redraw.clone()),
|
||||
("new filled pencil", json!({"points": [[100, 100], [150, 120], [180, 180]], "style": "pencil", "fill": true})),
|
||||
] {
|
||||
params["brush"] = json!("Charcoal");
|
||||
let (before, undo) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len());
|
||||
let e = s.execute("brush.freehand", ¶ms).expect_err(&format!("{what}: refused"));
|
||||
assert_eq!(e.to_string(), "invalid parameters for `brush.freehand`: cannot apply brush `Charcoal`: path has no stroke", "{what}");
|
||||
assert!(*s.doc().unwrap().doc == *before, "{what}: the document stays");
|
||||
assert_eq!(selected(&s), [p], "{what}: the selection stays");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "{what}: no undo step");
|
||||
}
|
||||
let r = s.execute("brush.freehand", &json!({"points": [[20, 90], [0, 120], [-10, 150]], "extend": extend, "brush": null})).unwrap();
|
||||
assert_eq!(r["id"], json!(p.0));
|
||||
assert_eq!(brush_of(&s, p), None, "without a brush the path is continued as it is");
|
||||
}
|
||||
|
||||
/// `brush.freehand` takes the keys of `path.freehand` and `brush`, and refuses any other key with
|
||||
/// the nearest key it takes, before it draws.
|
||||
#[test]
|
||||
fn brush_freehand_refuses_unknown_keys() {
|
||||
let spec = crate::cmd::find_command("brush.freehand").unwrap();
|
||||
let mut keys = crate::cmd::params::accepted_keys(spec.params).expect("the description names every key");
|
||||
keys.sort_unstable();
|
||||
assert_eq!(keys, ["brush", "closed", "connect", "extend", "fidelity", "fill", "fit", "keepSelected", "points", "redraw", "style"]);
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
select(&mut s, &[a]);
|
||||
let points = json!([[10, 10], [60, 40], [120, 10]]);
|
||||
let (before, undo) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len());
|
||||
let e = s.execute("brush.freehand", &json!({"points": points, "brsuh": "Charcoal"})).expect_err("a misspelled key is refused");
|
||||
assert!(e.to_string().contains("unknown parameter `brsuh`; did you mean `brush`?"), "{e}");
|
||||
assert!(*s.doc().unwrap().doc == *before, "the document stays");
|
||||
assert_eq!(selected(&s), [a], "the selection stays");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step");
|
||||
let every = json!({
|
||||
"points": points, "fidelity": 2.0, "fit": true, "closed": false, "style": "brush", "fill": false, "keepSelected": true,
|
||||
"extend": null, "connect": null, "redraw": null, "brush": "Charcoal"
|
||||
});
|
||||
let id = NodeId(s.execute("brush.freehand", &every).unwrap()["id"].as_u64().unwrap());
|
||||
assert_eq!(brush_of(&s, id).as_deref(), Some("Charcoal"));
|
||||
}
|
||||
|
||||
/// The Paintbrush skips a brush deleted after it was chosen: a deleted tool brush gives way to
|
||||
/// the document's current brush, and with neither the stroke is drawn without a brush.
|
||||
#[test]
|
||||
|
||||
Reference in New Issue
Block a user