mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-30 02:07:10 +01:00
Scripts: keep new-art defaults and direct selections through path edits
- PathPoint.remove() renumbers the direct-selected anchors and segments after the removed point, and drops the removed anchor and the selected segments it ended, through selection commands after the points are written. A removed anchor no longer stays selected, and the same index no longer selects a different point. - pathItems.add() reads new art's paint after the target document is active, so a path added to a document in the back keeps the stroke that document's selection gives new art. - Paths a script draws put new art's paint back afterwards, so a defaultStrokeWidth the script set applies to every path it draws, not only the first. - appearance.setNewArt refuses a fill or stroke paint with a setting a paint does not take, such as opacity, instead of applying the rest.
This commit is contained in:
1 parent
dd93247cbf
commit
7a71837dea
4 files changed
+157
-24
No files matched your search
@@ -72,6 +72,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
|
||||
/// The most dash and gap lengths `appearance.setNewArt` takes.
|
||||
const MAX_DASHES: usize = 64;
|
||||
/// The settings a `fill` or `stroke` paint of `appearance.setNewArt` takes.
|
||||
const PAINT_KEYS: [&str; 6] = ["color", "none", "swatch", "tint", "gradient", "keepModel"];
|
||||
/// The largest dash, gap or dash offset `appearance.setNewArt` takes, in points.
|
||||
const MAX_DASH_LENGTH: f64 = 1_000_000.0;
|
||||
|
||||
@@ -116,6 +118,9 @@ fn set_new_art(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if !v.is_object() {
|
||||
return Err(bad(C, format!("{key} must be a paint object (color, none, swatch or gradient), got {v}")));
|
||||
}
|
||||
if let Some(k) = v.as_object().and_then(|o| o.keys().find(|k| !PAINT_KEYS.contains(&k.as_str()))) {
|
||||
return Err(bad(C, format!("{key}: unknown setting `{k}` (a paint takes {})", PAINT_KEYS.join(", "))));
|
||||
}
|
||||
if v.get("swatch").is_some_and(|w| !w.is_string()) {
|
||||
return Err(bad(C, format!("{key}: `swatch` must be a swatch name")));
|
||||
}
|
||||
|
||||
@@ -459,14 +459,18 @@ fn made_id(r: &Value) -> std::result::Result<NodeId, HostError> {
|
||||
}
|
||||
|
||||
/// Runs the command `id` that makes a path in `doc` on top of the active layer, the selection kept,
|
||||
/// and reverses the new path's direction when `reversed`. → the new path.
|
||||
/// and reverses the new path's direction when `reversed`. → the new path. Selecting the new path
|
||||
/// and putting the selection back load the selected objects' paint and stroke width into new art,
|
||||
/// so new art's paint from before, the defaults a script set included, is put back.
|
||||
fn make(h: &super::Host, doc: Doc, id: &str, params: &Value, reversed: bool) -> Answer {
|
||||
let made = on_doc(h, doc.uid, true, |h| {
|
||||
let id = made_id(&drawing_normally(h, || command_value(h, id, params))?.1)?;
|
||||
if reversed {
|
||||
command(h, "path.reverse", &json!({"ids": [id.0]}))?;
|
||||
}
|
||||
Ok(id)
|
||||
let made = keeping_paint(h, || {
|
||||
on_doc(h, doc.uid, true, |h| {
|
||||
let id = made_id(&drawing_normally(h, || command_value(h, id, params))?.1)?;
|
||||
if reversed {
|
||||
command(h, "path.reverse", &json!({"ids": [id.0]}))?;
|
||||
}
|
||||
Ok(id)
|
||||
})
|
||||
})?;
|
||||
let s = h.session.borrow();
|
||||
let st = s.documents().iter().find(|d| d.uid == doc.uid).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?;
|
||||
@@ -616,22 +620,23 @@ fn items_star(h: &super::Host, a: &[Data]) -> Answer {
|
||||
/// path is set back to none in the same step, and new art keeps the paint it had before.
|
||||
fn items_add(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let doc = items_doc(h, a)?;
|
||||
let add = |h: &super::Host, unpainted: bool| {
|
||||
// New art's paint is read with the document active, since activating a document can load its
|
||||
// selection's appearance into new art. Selecting the new path loads its temporary stroke into
|
||||
// new art, and putting the selection back does not undo that, so new art's paint from before
|
||||
// the path is put back.
|
||||
let made = keeping_paint(h, || {
|
||||
on_doc(h, doc.uid, true, |h| {
|
||||
let unpainted = {
|
||||
let ap = h.session.borrow().new_art();
|
||||
ap.fill_paint().is_none() && ap.stroke_paint().is_none()
|
||||
};
|
||||
let id = made_id(&drawing_normally(h, || command_value(h, "path.create", &json!({"d": ""})))?.1)?;
|
||||
if unpainted {
|
||||
command(h, "paint.setStroke", &json!({"none": true, "ids": [id.0]}))?;
|
||||
}
|
||||
Ok(id)
|
||||
})
|
||||
};
|
||||
let unpainted = {
|
||||
let ap = h.session.borrow().new_art();
|
||||
ap.fill_paint().is_none() && ap.stroke_paint().is_none()
|
||||
};
|
||||
// Selecting the new path loads its temporary stroke into new art, and putting the selection
|
||||
// back does not undo that, so new art's paint from before the path is put back.
|
||||
let made = if unpainted { keeping_paint(h, || add(h, true))? } else { add(h, false)? };
|
||||
})?;
|
||||
let s = h.session.borrow();
|
||||
let st = s.documents().iter().find(|d| d.uid == doc.uid).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?;
|
||||
Ok(super::item_ref(h, st, made))
|
||||
@@ -1652,20 +1657,84 @@ fn path_selected_points(h: &super::Host, a: &[Data]) -> Answer {
|
||||
/// `remove()`: deletes the point; a subpath left with no points goes too.
|
||||
fn pt_remove(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let (item, i) = this_point(h, a)?;
|
||||
edit_points(h, item, |subs| {
|
||||
if let Some((s, j)) = locate(subs, i)
|
||||
&& let Some(sp) = subs.get_mut(s)
|
||||
{
|
||||
sp.anchors.remove(j);
|
||||
if sp.anchors.is_empty() {
|
||||
subs.remove(s);
|
||||
}
|
||||
// A direct selection of the path's points is renumbered after the removal.
|
||||
let selected = {
|
||||
let s = h.session.borrow();
|
||||
let st = s.documents().iter().find(|d| d.uid == item.doc.uid).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?;
|
||||
let sel = &st.selection;
|
||||
(sel.anchors.contains_key(&item.id) || sel.segments.contains_key(&item.id)).then(|| sel.clone())
|
||||
};
|
||||
let removed = edit_points(h, item, |subs| {
|
||||
let (s, j) = locate(subs, i)?;
|
||||
let sp = subs.get_mut(s)?;
|
||||
// The segment that closes a closed subpath ends at its first anchor.
|
||||
let closing = (sp.closed && j == 0).then(|| sp.anchors.len() - 1);
|
||||
sp.anchors.remove(j);
|
||||
let gone = sp.anchors.is_empty();
|
||||
if gone {
|
||||
subs.remove(s);
|
||||
}
|
||||
Some((s, j, gone, closing))
|
||||
})?;
|
||||
if let (Some((s, j, gone, closing)), Some(mut sel)) = (removed, selected) {
|
||||
// The points are written first, and the selection is then set with selection commands,
|
||||
// which the journal records with the edit.
|
||||
flush(h)?;
|
||||
renumber_selected(&mut sel, item.id, s, j, gone, closing);
|
||||
on_doc(h, item.doc.uid, false, |h| {
|
||||
let doc = h.session.borrow().active().map(|st| st.doc.clone()).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?;
|
||||
super::restore_selection(h, &doc, &sel)
|
||||
})?;
|
||||
}
|
||||
cut_points(h, item);
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// Updates the direct selection `sel` of the path `id` after the anchor `j` of its subpath `s` was
|
||||
/// removed, and the subpath with it when `gone`: the anchor, the segments it ended and their other
|
||||
/// ends leave the selection, unless a segment still selected ends there, and the anchors, segments
|
||||
/// and subpaths after it keep the points they selected. `closing` is the segment that closed the
|
||||
/// subpath at the removed anchor, when it did.
|
||||
fn renumber_selected(sel: &mut crate::doc::Selection, id: NodeId, s: usize, j: usize, gone: bool, closing: Option<usize>) {
|
||||
// An anchor (or a segment, by its first anchor) after the removed one moves down one place.
|
||||
let shift = |(p, k): (usize, usize), segment: bool| -> Option<(usize, usize)> {
|
||||
match p.cmp(&s) {
|
||||
std::cmp::Ordering::Less => Some((p, k)),
|
||||
std::cmp::Ordering::Greater => Some((if gone { p - 1 } else { p }, k)),
|
||||
std::cmp::Ordering::Equal if gone => None,
|
||||
std::cmp::Ordering::Equal if k == j || (segment && (k + 1 == j || closing == Some(k))) => None,
|
||||
std::cmp::Ordering::Equal => Some((p, if k > j { k - 1 } else { k })),
|
||||
}
|
||||
};
|
||||
// The other ends of the selected segments that the removal joins, in the new numbering: the
|
||||
// anchor before the removed one and the one after it.
|
||||
let mut ends: Vec<(usize, usize)> = Vec::new();
|
||||
if let Some(segments) = sel.segments.get_mut(&id) {
|
||||
let cut: Vec<(usize, usize)> = segments.iter().copied().filter(|g| shift(*g, true).is_none() && g.0 == s && !gone).collect();
|
||||
for (p, k) in cut {
|
||||
// Segment k runs from anchor k to anchor k + 1; one of the two is the removed one.
|
||||
let other = if k == j { k + 1 } else { k };
|
||||
// The closing segment's other end is its first anchor, the old last one.
|
||||
let other = if closing == Some(k) { k } else { other };
|
||||
ends.extend(shift((p, other), false));
|
||||
}
|
||||
*segments = segments.iter().filter_map(|g| shift(*g, true)).collect();
|
||||
if segments.is_empty() {
|
||||
sel.segments.remove(&id);
|
||||
}
|
||||
}
|
||||
let kept_ends: Vec<(usize, usize)> =
|
||||
sel.segments.get(&id).map(|g| g.iter().flat_map(|(p, k)| [(*p, *k), (*p, k + 1)]).collect()).unwrap_or_default();
|
||||
if let Some(anchors) = sel.anchors.get_mut(&id) {
|
||||
*anchors = anchors.iter().filter_map(|a| shift(*a, false)).filter(|a| !ends.contains(a) || kept_ends.contains(a)).collect();
|
||||
}
|
||||
if let Some((key, a)) = sel.key_anchor
|
||||
&& key == id
|
||||
{
|
||||
sel.key_anchor = shift(a, false).filter(|a| sel.anchors.get(&id).is_some_and(|set| set.contains(a))).map(|a| (key, a));
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Registration ----
|
||||
|
||||
/// The members `PathItem` adds to `PageItem`'s.
|
||||
|
||||
@@ -429,6 +429,9 @@ fn set_new_art_refuses_bad_values_with_nothing_changed() {
|
||||
json!({"stroke": {"tint": 50, "color": "#000000"}}),
|
||||
json!({"fillOverprint": "yes"}),
|
||||
json!({"widht": 3}),
|
||||
// A setting a paint does not take, here or nested in it, is refused too.
|
||||
json!({"fill": {"color": "#ff0000", "opacity": 25}}),
|
||||
json!({"stroke": {"none": true, "weight": 2}}),
|
||||
] {
|
||||
assert!(s.execute("appearance.setNewArt", ¶ms).is_err(), "accepted {params}");
|
||||
assert_eq!(s.paint, before, "changed new art for {params}");
|
||||
|
||||
@@ -753,6 +753,62 @@ fn an_added_path_leaves_new_art_unpainted_with_basic_appearance_off() {
|
||||
assert_eq!(s.paint, paint, "new art keeps no fill and no stroke");
|
||||
}
|
||||
|
||||
/// With Basic Appearance off, a path added to a document in the back takes the appearance of that
|
||||
/// document's selection, which its activation loads into new art, even when new art in the
|
||||
/// document in front has no paint.
|
||||
#[test]
|
||||
fn a_path_added_to_a_document_in_the_back_keeps_that_documents_stroke() {
|
||||
let (mut s, a, _) = doc();
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
s.prefs.new_art_basic = false;
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.prefs.new_art_basic = true;
|
||||
s.execute("paint.setFill", &json!({"none": true})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
s.prefs.new_art_basic = false;
|
||||
assert!(s.new_art().stroke_paint().is_none());
|
||||
let out = log(&mut s, "var d = app.documents[1]; var n = d.pathItems.add(); vc.log(n.stroked); vc.log(app.activeDocument == d);");
|
||||
assert_eq!(out, [json!(true), json!(false)]);
|
||||
}
|
||||
|
||||
/// Drawing a path and putting the selection back keep the defaults a script set, so a second
|
||||
/// path gets them too.
|
||||
#[test]
|
||||
fn every_path_a_script_draws_gets_its_default_stroke_width() {
|
||||
let (mut s, a, _) = doc();
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument; d.defaultStrokeWidth = 7;\
|
||||
var r1 = d.pathItems.rectangle(10, 10, 5, 5), r2 = d.pathItems.rectangle(20, 20, 5, 5);\
|
||||
vc.log([r1.strokeWidth, r2.strokeWidth, d.defaultStrokeWidth]);",
|
||||
);
|
||||
assert_eq!(out, [json!([7, 7, 7])]);
|
||||
}
|
||||
|
||||
/// Removing a point renumbers the direct-selected anchors after it, and a removed selected anchor
|
||||
/// leaves the selection.
|
||||
#[test]
|
||||
fn removing_a_point_keeps_the_direct_selection_on_the_same_anchors() {
|
||||
let (mut s, a, _) = doc();
|
||||
s.execute("select.anchorsMany", &json!({"items": [{"id": a.0, "anchors": [[0, 3]]}], "mode": "set"})).unwrap();
|
||||
log(&mut s, "app.activeDocument.pathItems[0].pathPoints[3].remove();");
|
||||
// A path left with no selected anchor leaves the selection, as `select.anchorsMany` leaves it.
|
||||
assert_eq!(selected_anchors(&s, a), None, "the removed anchor is not selected");
|
||||
assert!(!s.active().unwrap().selection.objects.contains(&a));
|
||||
s.execute("select.anchorsMany", &json!({"items": [{"id": a.0, "anchors": [[0, 2]]}], "mode": "set"})).unwrap();
|
||||
let at = node(&s, a).path_data().unwrap().subpaths[0].anchors[2].p;
|
||||
log(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].remove();");
|
||||
assert_eq!(selected_anchors(&s, a), Some(vec![(0, 1)]), "the selected anchor moved down one place");
|
||||
assert_eq!(node(&s, a).path_data().unwrap().subpaths[0].anchors[1].p, at);
|
||||
// A selected segment that the removal joins leaves the selection with its other end.
|
||||
s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 0]], "mode": "set"})).unwrap();
|
||||
log(&mut s, "app.activeDocument.pathItems[0].pathPoints[1].remove();");
|
||||
assert_eq!(selected_anchors(&s, a), None, "the segment's other end is not selected");
|
||||
assert!(!s.active().unwrap().selection.objects.contains(&a));
|
||||
}
|
||||
|
||||
/// [`doc`] with pattern `Dots` and spot swatch `Ink`, and path `a` with no fill or stroke.
|
||||
fn doc_with_paints() -> (Session, NodeId) {
|
||||
let (mut s, a, _) = doc();
|
||||
|
||||
Reference in new issue
Block a user