Merge main into blend redraw bounds fix

This commit is contained in:
yoriswind
2026-11-13 19:10:12 -08:00
804 changed files with 100912 additions and 7425 deletions
+34 -7
View File
@@ -46,7 +46,7 @@ pub mod importmatches;
pub(crate) mod inline;
mod interactivity;
mod intertwine;
mod layer;
pub(crate) mod layer;
mod layerpanel;
pub mod library;
pub mod linkfiles;
@@ -82,7 +82,7 @@ pub mod rasterfx;
mod recolor;
pub mod recovery;
pub mod scripts;
mod select;
pub(crate) mod select;
pub(crate) mod shaper;
pub mod shortcutset;
pub(crate) mod slices;
@@ -245,6 +245,12 @@ pub fn has_selected_member(s: &Session) -> std::result::Result<(), String> {
let Some(root) = ordinary_isolation(st) else { return has_selection(s) };
if st.selection.objects.iter().any(|id| inside_isolation(&st.doc, root, *id)) { Ok(()) } else { Err("nothing selected".into()) }
}
/// [`has_selected_member`], or a ruler guide is selected outside isolation mode: Object › Lock ›
/// Selection and Object › Hide › Selection.
pub fn has_selected_member_or_guide(s: &Session) -> std::result::Result<(), String> {
let st = s.active().ok_or("no document open")?;
if ordinary_isolation(st).is_none() && !st.selection.guides.is_empty() { Ok(()) } else { has_selected_member(s) }
}
/// Whether `id` lies inside the isolated object `root` (the root itself does not).
pub(crate) fn inside_isolation(d: &vectorcraft_doc::Document, root: vectorcraft_doc::NodeId, id: vectorcraft_doc::NodeId) -> bool {
id != root && d.ancestry(id).is_some_and(|a| a.contains(&root))
@@ -506,8 +512,13 @@ fn id_entry(value: &Value, key: &str, index: usize, cmd: &str) -> Result<NodeId>
/// them), each checked ([`checked_id`]): a malformed one, or one naming no object, is an error,
/// never the selection. `None` when it gives neither (or gives them as `null`).
pub(crate) fn given_objects(s: &Session, p: &Value, command: &str) -> Result<Option<Vec<NodeId>>> {
given_nodes(s, p, command, false)
}
/// The nodes `p` gives `command`, as [`given_objects`] reads them; ruler guide nodes are taken
/// too when `guides`, else refused.
pub(crate) fn given_nodes(s: &Session, p: &Value, command: &str, guides: bool) -> Result<Option<Vec<NodeId>>> {
if p.get("ids").is_some_and(|v| !v.is_null()) {
return checked_ids_param(s, p, "ids", command).map(Some);
return checked_nodes_param(s, p, "ids", command, guides).map(Some);
}
match p.get("id").filter(|v| !v.is_null()) {
None => Ok(None),
@@ -515,7 +526,7 @@ pub(crate) fn given_objects(s: &Session, p: &Value, command: &str) -> Result<Opt
Some(Value::String(r)) if r.starts_with('$') => {
Err(bad(command, format!("`id` is the step reference {r:?}, which only `run` and `command_batch` resolve")))
}
Some(v) => Ok(Some(vec![checked_id(s, v, command)?])),
Some(v) => Ok(Some(vec![checked_node(s, v, command, guides)?])),
}
}
/// The objects `p` gives `command`, as [`given_objects`] reads them, checked only for their form:
@@ -541,9 +552,18 @@ pub(crate) fn index(v: u64) -> usize {
}
/// Validate all explicit targets before a command changes the document or selection.
pub(crate) fn checked_ids_param(s: &Session, p: &Value, key: &str, command: &str) -> Result<Vec<NodeId>> {
checked_nodes_param(s, p, key, command, false)
}
/// The `key` list as [`checked_ids_param`] checks it; ruler guide nodes are taken too when
/// `guides`, else refused.
pub(crate) fn checked_nodes_param(s: &Session, p: &Value, key: &str, command: &str, guides: bool) -> Result<Vec<NodeId>> {
let values =
p.get(key).and_then(Value::as_array).ok_or_else(|| bad(command, format!("{key} must be an array of non-negative integer object ids")))?;
values.iter().enumerate().map(|(index, value)| id_entry(value, key, index, command).and_then(|_| checked_id(s, value, command))).collect()
values
.iter()
.enumerate()
.map(|(index, value)| id_entry(value, key, index, command).and_then(|_| checked_node(s, value, command, guides)))
.collect()
}
/// The objects a command acts on: `ids` when given (every one checked, and those inside another
@@ -557,11 +577,16 @@ pub(crate) fn checked_ids_or_selection(s: &Session, p: &Value, command: &str) ->
}
pub(crate) fn checked_id(s: &Session, value: &Value, command: &str) -> Result<NodeId> {
checked_node(s, value, command, false)
}
/// `value` as the id of a node of the active document; a ruler guide's is taken only when
/// `guides`.
pub(crate) fn checked_node(s: &Session, value: &Value, command: &str, guides: bool) -> Result<NodeId> {
let id = value.as_u64().map(NodeId).ok_or_else(|| bad(command, format!("invalid object id {value}: expected a non-negative integer")))?;
match s.doc()?.doc.node(id) {
None => Err(bad(command, format!("no such object id {value}"))),
// The guide commands take ruler guides by index.
Some(n) if n.is_ruler_guide() => Err(bad(command, format!("id {value} is a ruler guide, not an object"))),
Some(n) if n.is_ruler_guide() && !guides => Err(bad(command, format!("id {value} is a ruler guide, not an object"))),
Some(_) => Ok(id),
}
}
@@ -777,7 +802,9 @@ pub(crate) fn unique_name_from(base: &str, next: &mut std::collections::HashMap<
/// The most presets one presets file imports: each is looked up among the saved ones.
pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000;
pub(crate) use addons::DecodedImages;
pub(crate) use addons::{DecodedImages, refresh_color_masks};
/// Document Info's category titles and the Objects category's count labels.
pub use docinfo::{CATEGORIES, OBJECT_LABELS};
pub use docmenu::guide_indexes;
pub(crate) use edit::{settle_interaction, typing_in_progress};
pub(crate) use object::bounds_rewrite;
+1 -1
View File
@@ -14,7 +14,7 @@ mod select;
mod shapes;
mod typetools;
pub(crate) use image::DecodedImages;
pub(crate) use image::{DecodedImages, refresh_color_masks};
use super::CommandSpec;
+20 -3
View File
@@ -20,7 +20,9 @@ use vectorcraft_doc::{Node, NodeId, OrientedBox};
use vectorcraft_geom::{Affine, Point, Rect};
use vectorcraft_render::effects;
use super::super::appearance::series_children_in_paint_order;
use super::super::edit::selected_roots;
use super::super::graph::capture_series_object_opacity;
use super::super::menucmds::whole_or;
use super::super::object::{choice, object_bounds_transform, scaling, transform_node, transform_patterns};
use super::super::typecmd::refresh_bounds_of;
@@ -90,7 +92,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Randomize Opacity",
["Object", "Plug-ins", "Arrange Tools"],
None,
"{min?: % 0..100 (30), max?: % 0..100 (100; not less than min), seed?: whole number (0; the same seed, objects and range give the same opacities), ids?: [id…] (default: the selection)} give each selected object (the top-level ones) its own opacity, picked at random and evenly from min to max, as one undo step; it is the object's opacity, as the Transparency panel sets it → {count}",
"{min?: % 0..100 (30), max?: % 0..100 (100; not less than min), seed?: whole number (0; the same seed, objects and range give the same opacities), ids?: [id…] (default: the selection)} give each selected object (the top-level ones) its own opacity, picked at random and evenly from min to max, as one undo step; it is the object's opacity, as the Transparency panel sets it. On paths directly in a graph series whose opacity changes, the graph stores the opacity and blend mode of the frontmost of them for its next redraw (docs/mcp.md) → {count}",
has_selection,
randomize_opacity
),
@@ -99,7 +101,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Sort Objects",
["Object", "Plug-ins", "Arrange Tools"],
None,
"{by?: \"width\" | \"height\" | \"area\" (width × height) | \"x\" (left edge) | \"y\" (top edge) | \"opacity\" (%) | \"stacking\" (stacking order, from the back) (\"area\"), apply?: one of the same (\"stacking\"), order?: \"ascending\" (small to large) | \"descending\" (large to small) | \"random\" (\"ascending\"), distribute?: false (true: the values step evenly from the smallest to the largest; false: the objects trade the values they have), seed?: whole number (0; the order \"random\" picks), scaleStrokes?: the Scale Strokes & Effects preference (width, height and area), ids?: [id…] (default: the selection)} sort the selected objects (the top-level ones, at most 20000) by the attribute `by` and give them the values of `apply` in that order, as one undo step: the first in order gets the smallest value. Sizes and places are measured and set as object.setBounds measures them (Use Preview Bounds), a width, height or area about each object's centre (an area in proportion); stacking order always trades places, and only among the objects in the same layer or group. A run that changes nothing makes no step → {count}",
"{by?: \"width\" | \"height\" | \"area\" (width × height) | \"x\" (left edge) | \"y\" (top edge) | \"opacity\" (%) | \"stacking\" (stacking order, from the back) (\"area\"), apply?: one of the same (\"stacking\"), order?: \"ascending\" (small to large) | \"descending\" (large to small) | \"random\" (\"ascending\"), distribute?: false (true: the values step evenly from the smallest to the largest; false: the objects trade the values they have), seed?: whole number (0; the order \"random\" picks), scaleStrokes?: the Scale Strokes & Effects preference (width, height and area), ids?: [id…] (default: the selection)} sort the selected objects (the top-level ones, at most 20000) by the attribute `by` and give them the values of `apply` in that order, as one undo step: the first in order gets the smallest value. Sizes and places are measured and set as object.setBounds measures them (Use Preview Bounds), a width, height or area about each object's centre (an area in proportion); stacking order always trades places, and only among the objects in the same layer or group. With apply \"opacity\", on paths directly in a graph series whose opacity changes, the graph stores the opacity and blend mode of the frontmost of them for its next redraw (docs/mcp.md). A run that changes nothing makes no step → {count}",
has_multi,
sort
),
@@ -396,17 +398,30 @@ fn randomize_opacity(s: &mut Session, p: &Value) -> Result<Value> {
}
let (lo, hi) = ((min / 100.0) as f32, (max / 100.0) as f32);
s.edit("Randomize Opacity", |d, _| {
let mut changed = vec![];
for id in &ids {
let o = rng.range(lo, hi);
if let Some(n) = d.node_mut(*id) {
if let Some(n) = d.node_mut(*id)
&& n.opacity != o
{
n.opacity = o;
changed.push(*id);
}
}
keep_series_opacity(d, &changed);
Ok(())
})?;
Ok(json!({ "count": ids.len() }))
}
/// Store on their graphs the opacity just given to the paths among `changed` (objects whose opacity changed) that are
/// directly in a graph series, with their blend mode, so that every path of the series has them when the graph is drawn
/// again; the frontmost of them in a series sets them.
fn keep_series_opacity(d: &mut vectorcraft_doc::Document, changed: &[NodeId]) {
let marks = series_children_in_paint_order(d, changed);
capture_series_object_opacity(d, &marks);
}
/// An object Sort Objects sorts: its layer or group, its place in it, its box as
/// `object.setBounds` measures it and its opacity (%).
struct Sorted {
@@ -510,6 +525,8 @@ fn sort(s: &mut Session, p: &Value) -> Result<Value> {
n.opacity = (v / 100.0) as f32;
}
}
let changed: Vec<NodeId> = wanted.iter().filter(|(o, v)| (o.opacity - v).abs() >= 1e-6).map(|(o, _)| o.id).collect();
keep_series_opacity(d, &changed);
Ok(())
})?;
return Ok(count);
+35 -13
View File
@@ -10,7 +10,7 @@ use vectorcraft_geom::{PathData, Point, Rect};
use vectorcraft_pathops::addons as po;
use super::super::super::edit::outermost;
use super::super::super::layer::empty_artboards;
use super::super::super::layer::{empty_artboards, remove_artboards};
use crate::Result;
/// Sine of the turn below which an anchor on a straight run is collinear.
@@ -369,11 +369,7 @@ fn restructure(d: &mut Document, scope: &mut Scope, kind: Kind) -> Result<Outcom
break;
}
if let Scope::Objects(roots) = scope {
for (id, nodes) in &found {
if let Some(at) = roots.iter().position(|r| r == id) {
roots.splice(at..=at, nodes.iter().map(|n| n.id));
}
}
*roots = replace_roots(roots, &found);
}
out.ids.extend(found.iter().map(|(id, _)| *id));
d.insert_beside(found, true)?;
@@ -382,6 +378,36 @@ fn restructure(d: &mut Document, scope: &mut Scope, kind: Kind) -> Result<Outcom
Ok(out)
}
#[cfg(test)]
thread_local! {
/// Tests: how many scope roots [`replace_roots`] looked at on this thread.
pub(super) static ROOTS_SEEN: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// The scope's objects after a pass replaced `found`: each found object gives way to the ids of
/// what replaces it, in its place, and the others keep their order. An id that `roots` lists more
/// than once is replaced at its first places, once for each time `found` lists it. One walk of
/// `roots`.
pub(super) fn replace_roots(roots: &[NodeId], found: &[(NodeId, Vec<Node>)]) -> Vec<NodeId> {
let mut with: HashMap<NodeId, (&[Node], usize)> = HashMap::with_capacity(found.len());
for (id, nodes) in found {
with.entry(*id).or_insert((nodes.as_slice(), 0)).1 += 1;
}
let mut out = Vec::with_capacity(roots.len());
for r in roots {
#[cfg(test)]
ROOTS_SEEN.set(ROOTS_SEEN.get() + 1);
match with.get_mut(r) {
Some((nodes, left)) if *left > 0 => {
*left -= 1;
out.extend(nodes.iter().map(|n| n.id));
}
_ => out.push(*r),
}
}
out
}
/// Run `f` on a copy of each path in scope (not guides), and keep the copies it changed: `f`
/// returns how many issues it fixed.
fn reshape(d: &mut Document, scope: &Scope, f: impl Fn(&Node, &mut PathData) -> usize) -> Result<Outcome> {
@@ -479,13 +505,9 @@ fn near_points(d: &mut Document, scope: &Scope) -> Result<Outcome> {
fn artboards(d: &mut Document, sel: &mut Selection, scope: &Scope) -> Result<Outcome> {
let Scope::Document = scope else { return Ok(Outcome::default()) };
let empty = empty_artboards(d);
// The last first, so the others keep their places.
for &i in empty.iter().rev() {
if i < d.artboards.len() {
let id = d.artboards.remove(i).id;
d.retire_artboard_id(id);
d.retain_guides(sel, |g| g.artboard != Some(id));
}
if empty.is_empty() {
return Ok(Outcome::default());
}
remove_artboards(d, sel, &empty)?;
Ok(Outcome { count: empty.len(), ids: vec![], artboards: empty })
}
@@ -341,6 +341,33 @@ fn fix_all_is_one_undo_step() {
assert_eq!(s.doc().unwrap().doc.artboards.len(), doc.artboards.len());
}
#[test]
fn a_long_straight_run_loses_its_inner_anchors_in_one_step() {
let mut s = session();
let n: u32 = 5_000;
let mut pts: Vec<(f64, f64)> = (0..n).map(|i| (10.0 + f64::from(i) * 0.05, 150.0)).collect();
pts.push((260.0, 190.0));
let id = line(&mut s, &pts);
let other = rect(&mut s, 300.0, 20.0, 40.0, 40.0);
select(&mut s, &[other]);
let check = s.execute("addon.cleanup.check", &json!({"kinds": ["collinearAnchors"], "scope": "document"})).unwrap();
assert_eq!(check["total"], n - 2, "{check}");
assert_eq!(check["findings"][0]["ids"], json!([id.0]));
let shown = s.execute("addon.cleanup.show", &json!({"kind": "collinearAnchors", "scope": "document"})).unwrap();
assert_eq!(shown["count"], n - 2);
assert_eq!(s.doc().unwrap().selection.objects, [id], "Show selects the path");
select(&mut s, &[other]);
let (steps, before) = (undo_steps(&s), node(&s, id).unwrap());
let r = s.execute("addon.cleanup.fix", &json!({"kinds": ["collinearAnchors"], "scope": "document"})).unwrap();
assert_eq!((r["total"].as_u64(), r["fixed"]["collinearAnchors"].as_u64()), (Some(u64::from(n) - 2), Some(u64::from(n) - 2)));
assert_eq!(undo_steps(&s), steps + 1);
assert_eq!(s.doc().unwrap().selection.objects, [other], "Fix keeps the selection");
let ends: Vec<(f64, f64)> = node(&s, id).unwrap().path_data().unwrap().subpaths[0].anchors.iter().map(|a| (a.p.x, a.p.y)).collect();
assert_eq!(ends, [(10.0, 150.0), (10.0 + f64::from(n - 1) * 0.05, 150.0), (260.0, 190.0)]);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(node(&s, id).unwrap(), before);
}
#[test]
fn the_scope_is_the_selection_or_the_document() {
let mut s = session();
@@ -362,6 +389,150 @@ fn the_scope_is_the_selection_or_the_document() {
}
}
/// The ids of the first layer's objects, bottom to top.
fn layer_ids(s: &Session) -> Vec<NodeId> {
match &s.doc().unwrap().doc.layers[0].kind {
NodeKind::Layer { children, .. } => children.iter().map(|c| c.id).collect(),
other => panic!("not a layer: {other:?}"),
}
}
/// A plain group of the one object `id`.
fn group(s: &mut Session, id: NodeId) -> NodeId {
wrap(s, id, |children| NodeKind::Group { children, clip: false })
}
#[test]
fn unwrapping_selected_groups_keeps_their_places_and_order() {
let mut s = session();
let c1 = rect(&mut s, 10.0, 10.0, 20.0, 20.0);
let a = rect(&mut s, 40.0, 10.0, 20.0, 20.0);
let g1 = group(&mut s, a);
let c2 = rect(&mut s, 70.0, 10.0, 20.0, 20.0);
let empty = s
.edit("t", |d, _| {
let (parent, i, _) = d.position(c2).unwrap();
let g = d.alloc_id();
Ok(d.insert(parent, i + 1, Node::new(g, NodeKind::Group { children: vec![], clip: false }))?)
})
.unwrap();
let c3 = rect(&mut s, 100.0, 10.0, 20.0, 20.0);
let b = rect(&mut s, 130.0, 10.0, 20.0, 20.0);
let inner = group(&mut s, b);
let outer = group(&mut s, inner);
let c4 = rect(&mut s, 160.0, 10.0, 20.0, 20.0);
let x = rect(&mut s, 190.0, 10.0, 20.0, 20.0);
let unselected = group(&mut s, x);
assert_eq!(layer_ids(&s), [c1, g1, c2, empty, c3, outer, c4, unselected]);
select(&mut s, &[c1, g1, c2, empty, c3, outer, c4]);
let check = s.execute("addon.cleanup.check", &json!({"kinds": ["needlessGroups"], "scope": "selection"})).unwrap();
let r = s.execute("addon.cleanup.fix", &json!({"kinds": ["needlessGroups"], "scope": "selection"})).unwrap();
// The inner group is found only once its outer group is gone: on a later pass, as a root.
assert_eq!(r["fixed"]["needlessGroups"], 4, "{r}");
assert_eq!(check["total"], 4, "the check finds what Fix fixes: {check}");
let mut listed: Vec<u64> = check["findings"][0]["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();
listed.sort_unstable();
let mut gone: Vec<u64> = [g1, empty, outer, inner].iter().map(|i| i.0).collect();
gone.sort_unstable();
assert_eq!(listed, gone);
assert_eq!(layer_ids(&s), [c1, a, c2, c3, b, c4, unselected], "each member takes its group's place");
for id in [g1, empty, outer, inner] {
assert!(node(&s, id).is_none(), "{id:?} unwrapped");
}
}
#[test]
fn fix_all_reaches_the_members_of_unwrapped_selected_groups() {
let mut s = session();
rect(&mut s, 200.0, 20.0, 80.0, 60.0);
let below = rect(&mut s, 20.0, 150.0, 30.0, 30.0);
let copy = s
.edit("t", |d, _| {
let mut copy = d.node(below).unwrap().clone();
copy.id = d.alloc_id();
let (parent, i, _) = d.position(below).unwrap();
Ok(d.insert(parent, i + 1, copy)?)
})
.unwrap();
let g = group(&mut s, copy);
select(&mut s, &[below, g]);
// The copy sits apart from the object it doubles until its group is unwrapped.
assert_eq!(found(&mut s, "duplicateObjects", "selection"), 0);
assert_eq!(found(&mut s, "needlessGroups", "selection"), 1);
let r = s.execute("addon.cleanup.fix", &json!({"scope": "selection"})).unwrap();
assert_eq!((r["fixed"]["needlessGroups"].as_u64(), r["fixed"]["duplicateObjects"].as_u64()), (Some(1), Some(1)), "{r}");
assert!(node(&s, g).is_none() && node(&s, copy).is_none());
assert!(node(&s, below).is_some());
}
#[test]
fn replacing_roots_takes_each_found_object_at_its_first_place() {
use super::checks::replace_roots;
let n = |id: u64| Node::new(NodeId(id), NodeKind::Group { children: vec![], clip: false });
let ids = |v: &[u64]| v.iter().map(|i| NodeId(*i)).collect::<Vec<_>>();
let roots = ids(&[1, 2, 1, 3]);
assert_eq!(replace_roots(&roots, &[(NodeId(1), vec![n(10), n(11)])]), ids(&[10, 11, 2, 1, 3]));
assert_eq!(replace_roots(&roots, &[(NodeId(1), vec![]), (NodeId(1), vec![])]), ids(&[2, 3]), "listed twice: both places");
assert_eq!(replace_roots(&roots, &[(NodeId(3), vec![]), (NodeId(2), vec![n(20)])]), ids(&[1, 20, 1]));
// A found object inside a root leaves the roots as they are.
assert_eq!(replace_roots(&roots, &[(NodeId(7), vec![n(70)])]), roots);
assert_eq!(replace_roots(&[], &[(NodeId(7), vec![])]), ids(&[]));
}
/// How many scope roots fixing `n` selected stray points above `n` selected clean objects looks at.
fn roots_seen_removing(n: usize) -> usize {
use super::checks::ROOTS_SEEN;
let mut s = session();
let mut ids: Vec<NodeId> = (0..n).map(|i| rect(&mut s, (i % 20) as f64 * 15.0, (i / 20) as f64 * 15.0, 10.0, 10.0)).collect();
ids.extend((0..n).map(|i| path(&mut s, json!([{"x": i % 300, "y": i / 300}]), false)));
select(&mut s, &ids);
ROOTS_SEEN.set(0);
let r = s.execute("addon.cleanup.fix", &json!({"kinds": ["strayPoints"], "scope": "selection"})).unwrap();
assert_eq!(r["total"].as_u64(), Some(n as u64));
assert_eq!(layer_ids(&s), ids[..n]);
ROOTS_SEEN.get()
}
#[test]
fn removing_many_selected_objects_looks_at_each_root_once_a_pass() {
let (small, large) = (roots_seen_removing(150), roots_seen_removing(300));
assert_eq!(small, 300, "one pass over the 300 roots");
assert!(large <= 2 * small, "{small} roots looked at for 150 removals, {large} for 300");
}
#[test]
fn deleting_many_empty_artboards_walks_the_artboards_and_guides_once() {
use crate::cmd::layer::ARTBOARD_PASSES;
let mut s = session();
rect(&mut s, 200.0, 20.0, 80.0, 60.0);
let (keep, gone) = s
.edit("t", |d, _| {
let first = d.artboards[0].id;
let keep = d.add_ruler_guide(&vectorcraft_doc::Guide { artboard: Some(first), ..vectorcraft_doc::Guide::new(true, 100.0) });
let mut gone = vec![];
for i in 0..40 {
let mut a = d.artboards[0].clone();
a.id = d.next_artboard_id();
let x = 1000.0 + i as f64 * 200.0;
a.rect = Rect::new(x, 1000.0, x + 100.0, 1100.0);
gone.push(d.add_ruler_guide(&vectorcraft_doc::Guide { artboard: Some(a.id), ..vectorcraft_doc::Guide::new(true, x + 50.0) }));
d.artboards.push(a);
}
Ok((keep, gone))
})
.unwrap();
let first = s.doc().unwrap().doc.artboards[0].clone();
ARTBOARD_PASSES.set(0);
let r = s.execute("addon.cleanup.fix", &json!({"kinds": ["emptyArtboards"], "scope": "document"})).unwrap();
assert_eq!(r["total"].as_u64(), Some(40), "{r}");
assert_eq!(ARTBOARD_PASSES.get(), 2, "one walk over the artboards and one over the guides");
let d = &s.doc().unwrap().doc;
assert_eq!(d.artboards, vec![first]);
let left: Vec<Option<NodeId>> = d.ruler_guides().into_iter().map(|g| g.id).collect();
assert_eq!(left, vec![Some(keep)]);
assert!(gone.iter().all(|id| !left.contains(&Some(*id))));
}
#[test]
fn show_selects_the_objects_with_the_issue() {
let mut s = session();
+34 -7
View File
@@ -206,11 +206,31 @@ struct Source {
text: String,
}
#[cfg(test)]
thread_local! {
/// Tests: how many times [`thread_index`] went through the document's threads on this thread.
static THREAD_SCANS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// Each object the document's text threads list, with the index of the first thread that lists it.
fn thread_index(d: &Document) -> std::collections::HashMap<NodeId, usize> {
#[cfg(test)]
THREAD_SCANS.with(|c| c.set(c.get() + 1));
let mut out = std::collections::HashMap::new();
for (i, thread) in d.text_threads.iter().enumerate() {
for id in thread {
out.entry(*id).or_insert(i);
}
}
out
}
impl Source {
/// Horizontal point or area type that isn't threaded and whose text all fits; None otherwise.
fn of(d: &Document, id: NodeId) -> Option<Self> {
/// Horizontal point or area type that isn't threaded (`threaded` false) and whose text all
/// fits; None otherwise.
fn of(d: &Document, id: NodeId, threaded: bool) -> Option<Self> {
let t = text_of(d, id)?;
if t.vertical || matches!(t.kind, TextKind::OnPath { .. }) || d.text_threads.iter().any(|th| th.contains(&id)) {
if t.vertical || matches!(t.kind, TextKind::OnPath { .. }) || threaded {
return None;
}
let lay = layout(t);
@@ -376,8 +396,10 @@ fn break_text(s: &mut Session, p: &Value) -> Result<Value> {
};
let d = &s.doc()?.doc;
let (mut items, mut skipped, mut count) = (vec![], vec![], 0);
for id in texts_under(d, &checked_ids_or_selection(s, p, C)?)? {
let (Some(src), Some(node)) = (Source::of(d, id), d.node(id)) else {
let ids = texts_under(d, &checked_ids_or_selection(s, p, C)?)?;
let threads = thread_index(d);
for id in ids {
let (Some(src), Some(node)) = (Source::of(d, id, threads.contains_key(&id)), d.node(id)) else {
skipped.push(id);
continue;
};
@@ -405,7 +427,8 @@ fn split_text(s: &mut Session, _: &Value) -> Result<Value> {
return Err(EngineError::Other("Click in type with a Type tool to split it".into()));
};
let d = &s.doc()?.doc;
let (Some(src), Some(node)) = (Source::of(d, id), d.node(id).filter(|_| d.is_editable(id))) else {
let threaded = d.text_threads.iter().any(|th| th.contains(&id));
let (Some(src), Some(node)) = (Source::of(d, id, threaded), d.node(id).filter(|_| d.is_editable(id))) else {
return Err(EngineError::Other("Select horizontal point or area type whose text fits".into()));
};
let text = &src.text;
@@ -821,13 +844,17 @@ fn remove_breaks(s: &mut Session, p: &Value) -> Result<Value> {
let ids = texts_under(d, &checked_ids_or_selection(s, p, C)?)?;
// A threaded story whose frames are all among them is read as one text, once.
let named: std::collections::HashSet<NodeId> = ids.iter().copied().collect();
let threads = thread_index(d);
let mut done = std::collections::HashSet::new();
let mut out: Vec<(NodeId, Vec<(usize, bool)>)> = vec![];
for &id in &ids {
if !done.insert(id) {
continue;
}
let story = crate::cmd::threads::story_of(d, id);
let story = match threads.get(&id).and_then(|&i| d.text_threads.get(i)) {
Some(thread) => crate::cmd::threads::story_in(d, thread, id),
None => vec![],
};
if !story.is_empty() && story.iter().all(|f| named.contains(f)) {
done.extend(story.iter().copied());
out.extend(story_cuts(d, &story, brk));
@@ -158,6 +158,62 @@ fn break_text_refuses_what_it_cannot_break() {
assert!(matches!(r, Err(EngineError::BadParams { .. })), "{r:?}");
}
/// Two area frames threaded together, with `story` flowing through them → (first, second).
fn threaded(s: &mut Session, story: &str) -> (NodeId, NodeId) {
let a = text(s, json!({"x": 10, "y": 300, "text": story, "size": 12, "area": {"width": 150, "height": 60}}));
let b = NodeId(s.execute("shape.rectangle", &json!({"x": 200, "y": 300, "width": 150, "height": 60})).unwrap()["id"].as_u64().unwrap());
select(s, &[a, b]);
s.execute("text.thread.create", &json!({})).unwrap();
(a, b)
}
fn thread_scans() -> usize {
super::THREAD_SCANS.with(|c| c.get())
}
/// Threaded frames in the selection stay as they are and are reported as skipped; the other type
/// is broken. The document's threads are gone through once for the whole selection, not once
/// per object.
#[test]
fn break_text_skips_threaded_frames_and_reads_the_threads_once() {
let mut s = session();
let (a, b) = threaded(&mut s, "Threaded story text");
let mut plain = vec![];
for i in 0..6 {
plain.push(text(&mut s, json!({"x": 20, "y": 30 + 30 * i, "text": "Two words", "size": 14})));
}
let was = glyphs(&s, &plain);
let frames = (obj(&s, a), obj(&s, b));
let before = doc_json(&s);
let steps = undo_steps(&s);
let mut all = vec![a, b];
all.extend(&plain);
select(&mut s, &all);
let scans = thread_scans();
let r = s.execute("addon.cleanup.breakText", &json!({"by": "words"})).unwrap();
assert_eq!(thread_scans() - scans, 1, "the threads are gone through once");
assert_eq!(ids(&json!({"ids": r["skipped"]})), [a, b]);
assert_eq!((obj(&s, a), obj(&s, b)), frames, "the threaded frames stay as they are");
let pieces = ids(&r);
assert_eq!(pieces.len(), 12);
assert_eq!(s.doc().unwrap().selection.objects.len(), 12, "the pieces are selected");
assert_same_places(&was, &glyphs(&s, &pieces));
assert_eq!(undo_steps(&s), steps + 1);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(doc_json(&s), before);
}
#[test]
fn split_text_refuses_a_threaded_frame() {
let mut s = session();
let (a, _) = threaded(&mut s, "Threaded story text");
select(&mut s, &[a]);
edit_text(&mut s, a, 9, 9);
let before = doc_json(&s);
assert!(other(s.execute("addon.cleanup.splitText", &json!({}))).contains("point or area type"));
assert_eq!(doc_json(&s), before);
}
#[test]
fn combine_puts_glyph_pieces_back_together_where_they_were() {
let mut s = session();
@@ -300,6 +356,29 @@ fn remove_breaks_with_ids_null_in_the_characters_a_type_tool_selected() {
assert_eq!(obj(&s, id).plain_text(), "a b\nc");
}
/// Remove Breaks reads a threaded story whose frames are all selected as one text and each other
/// object on its own, going through the document's threads once for the whole selection.
#[test]
fn remove_breaks_reads_the_threads_once() {
let mut s = session();
let (a, b) = threaded(&mut s, "one\ntwo");
let mut plain = vec![];
for i in 0..6 {
plain.push(text(&mut s, json!({"x": 20, "y": 30 + 30 * i, "text": "a\nb", "size": 12})));
}
let mut all = vec![a, b];
all.extend(&plain);
select(&mut s, &all);
let scans = thread_scans();
let r = s.execute("addon.cleanup.removeBreaks", &json!({"kind": "paragraph"})).unwrap();
assert_eq!(thread_scans() - scans, 1, "the threads are gone through once");
assert_eq!(r["removed"], 7);
assert_eq!(obj(&s, a).plain_text(), "one two");
for id in plain {
assert_eq!(obj(&s, id).plain_text(), "a b");
}
}
#[test]
fn split_at_the_cursor_and_around_a_selection() {
for (anchor, caret, want) in [(6, 6, &["Split", "here please"][..]), (6, 10, &["Split", "here", "please"][..])] {
+17 -11
View File
@@ -43,7 +43,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Apply as Filter",
["Object", "Plug-ins", "Color Effects"],
None,
"{effect: a colour adjustment's effect id (adjust.brightnessContrast, adjust.curves, adjust.hueSaturation, adjust.levels, adjust.shiftToColor, adjust.temperatureTint, addon.color.exposure, addon.color.desaturate, addon.color.duotone or addon.color.invert), params?: {…} (as effect.apply; missing keys take the dialog defaults), fill?: true, stroke?: true, includeImages?: true, includePatterns?: true, ids?: [id…] (default: the selection)} recolour the objects and everything inside them as the live effect would draw them, but in their colours, as edit.colors.invert does (fills, strokes, type, gradient meshes, embedded images and pattern tiles), as one undo step; their effects stay. Duotone links a colour to its one tone's swatch as the live effect does → {changed}",
"{effect: a colour adjustment's effect id (adjust.brightnessContrast, adjust.curves, adjust.hueSaturation, adjust.levels, adjust.shiftToColor, adjust.temperatureTint, addon.color.exposure, addon.color.desaturate, addon.color.duotone or addon.color.invert), params?: {…} (as effect.apply; missing keys take the dialog defaults), fill?: true, stroke?: true, includeImages?: true, includePatterns?: true, ids?: [id…] (default: the selection)} recolour the objects and everything inside them as the live effect would draw them, but in their colours, as edit.colors.invert does (fills, strokes, type, gradient meshes, embedded images and pattern tiles), as one undo step (none when nothing changes); their effects stay. Duotone links a colour to its one tone's swatch as the live effect does. On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke (docs/mcp.md) → {changed}",
has_selection,
filter
),
@@ -52,7 +52,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Print Ink Fixes",
["Object", "Plug-ins", "Color Effects"],
None,
"{scope?: \"selection\" (the selection, or `ids`; by default, the document while nothing is selected) | \"document\" (every layer), inkLimit?: total ink % 1..400 (0 or left out: off), excludePureBlack?: true (black-only and grey colours keep their ink), removeWhiteOverprint?: false (white fills and strokes stop overprinting), overprintBlack?: black % 1..100 (black-only and grey fills and strokes this dark or darker overprint, as edit.colors.overprintBlack; 0 or left out: off), textOnly?: false (Overprint Black on type only), fill?: true, stroke?: true, ids?: [id…]} prepare a CMYK document's inks for print as one undo step: CMYK colours (solid, gradient stops, gradient meshes) with more total ink than inkLimit are scaled down to it (colours of spot swatches and Registration stay), white overprint is removed and black overprint set. Refused in RGB documents (File › Document Color Mode › CMYK Color first) → {changed, inkLimited: paints and meshes scaled, whiteOverprintRemoved: objects, blackOverprinted: objects}",
"{scope?: \"selection\" (the selection, or `ids`; by default, the document while nothing is selected) | \"document\" (every layer), inkLimit?: total ink % 1..400 (0 or left out: off), excludePureBlack?: true (black-only and grey colours keep their ink), removeWhiteOverprint?: false (white fills and strokes stop overprinting), overprintBlack?: black % 1..100 (black-only and grey fills and strokes this dark or darker overprint, as edit.colors.overprintBlack; 0 or left out: off), textOnly?: false (Overprint Black on type only), fill?: true, stroke?: true, ids?: [id…]} prepare a CMYK document's inks for print as one undo step: CMYK colours (solid, gradient stops, gradient meshes) with more total ink than inkLimit are scaled down to it (colours of spot swatches and Registration stay), white overprint is removed and black overprint set. Refused in RGB documents (File › Document Color Mode › CMYK Color first). On a path directly in a graph series, the graph also stores a paint the ink limit changes on the topmost visible fill or stroke (docs/mcp.md) → {changed, inkLimited: paints and meshes scaled, whiteOverprintRemoved: objects, blackOverprinted: objects}",
has_doc,
print_fixes::run
),
@@ -70,7 +70,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Apply Nearest Swatch",
["Object", "Plug-ins", "Color Effects"],
None,
"{library?: as addon.color.nearestSwatch (default: \"document\"), fill?: true, stroke?: true, ids?: [id…] (default: the selection)} give each solid colour and gradient stop of the selected objects' fills and strokes (their type's and those of the objects inside them; gradient meshes too) the colour of its nearest swatch in the library, as addon.color.nearestSwatch finds it, as one undo step: a global or spot swatch's colour links to it. A library's swatches the colours take are added to the document's first, as swatch.library.add adds them (a spot colour stays spot); images and patterns keep their colours → {changed: paints changed, swatches: [the document swatches the colours took], added: [swatches added to the document]}",
"{library?: as addon.color.nearestSwatch (default: \"document\"), fill?: true, stroke?: true, ids?: [id…] (default: the selection)} give each solid colour and gradient stop of the selected objects' fills and strokes (their type's and those of the objects inside them; gradient meshes too) the colour of its nearest swatch in the library, as addon.color.nearestSwatch finds it, as one undo step (none when nothing changes): a global or spot swatch's colour links to it. A library's swatches the colours take are added to the document's first, as swatch.library.add adds them (a spot colour stays spot); images and patterns keep their colours. On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke (docs/mcp.md) → {changed: paints changed, swatches: [the document swatches the colours took], added: [swatches added to the document]}",
has_selection,
nearest::apply
),
@@ -79,7 +79,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Apply Fill to Stroke",
["Object", "Plug-ins", "Color Effects"],
None,
"{ids?|id?, skipNone?: bool} each target's top stroke takes its own top fill, as it is (a colour in its model, a global or spot colour linked at its tint, a gradient or pattern with its placement, None); a stroke given paint at width 0 gets 1 pt, as Swap Fill and Stroke does. Type: each run's stroke takes its own fill, and while the Type tool has characters selected (no ids), only those. A graph's series marks and labels keep the paint when the graph is drawn again. skipNone: leave alone a target whose fill is None. A target whose stroke already has that paint is left as it is, and when nothing changes no undo step is recorded. The default stroke takes the default fill the same way → {objects}",
"{ids?|id?, skipNone?: bool} each target's top stroke takes its own top fill, as it is (a colour in its model, a global or spot colour linked at its tint, a gradient or pattern with its placement, None); a stroke given paint at width 0 gets 1 pt, as Swap Fill and Stroke does. Type: each run's stroke takes its own fill, and while the Type tool has characters selected (no ids), only those. A graph's labels keep the paint when the graph is drawn again. On a path directly in a graph series, the graph also stores the paint and weight of the topmost visible stroke when the command wrote that row (exceptions: docs/mcp.md). skipNone: leave alone a target whose fill is None. A target whose stroke already has that paint is left as it is, and when nothing changes no undo step is recorded. The default stroke takes the default fill the same way → {objects}",
has_doc,
|s, p| copy_paint(s, p, true)
),
@@ -226,6 +226,8 @@ fn copy_paint(s: &mut Session, p: &Value, to_stroke: bool) -> Result<Value> {
if !ids.is_empty() {
let before = s.doc()?.doc.clone();
super::super::overprint::edit_counted(s, label, |d| {
// Each object with the row the paint went to, for the paint a graph stores for its series.
let mut written = Vec::new();
for id in &ids {
let Some(node) = d.node_mut(*id) else { continue };
if let NodeKind::Text(t) = &mut node.kind {
@@ -239,19 +241,23 @@ fn copy_paint(s: &mut Session, p: &Value, to_stroke: bool) -> Result<Value> {
let (from, to) = if to_stroke { (ap.fill_paint(), ap.stroke_paint()) } else { (ap.stroke_paint(), ap.fill_paint()) };
// A missing item reads as None: copying None onto it would add an item that
// changes nothing.
if (skip_none && from.is_none()) || from == to {
if skip_none && from.is_none() {
continue;
}
if to_stroke {
restore_unpainted_stroke(ap, None, &from);
ap.set_stroke(from);
} else {
ap.set_fill(from);
if from != to {
if to_stroke {
restore_unpainted_stroke(ap, None, &from);
ap.set_stroke(from);
} else {
ap.set_fill(from);
}
}
// A row that already had the paint counts as written with it, as for `paint.setFill`.
written.extend(ap.items.iter().rposition(|it| it.is_fill() != to_stroke).map(|at| (*id, at)));
}
objects = super::super::appearance::count_changed(d, &before, &ids);
// The graph keeps the paint its series marks and labels now have.
let series = super::super::graph::capture_series_paints(d, &ids, !to_stroke);
let series = super::super::appearance::capture_series_paint_writes(&before, d, &ids, &written);
let labels = super::super::graph::capture_label_styles(d, &ids, &copy_run);
Ok(objects + usize::from(series || labels))
})?;
@@ -11,7 +11,7 @@ use vectorcraft_color::swatch::REGISTRATION;
use vectorcraft_doc::overprint::{OverprintBlack, is_white};
use vectorcraft_doc::{ColorMode, Node, NodeKind};
use super::super::super::colorcmds::{Recolor, Scope};
use super::super::super::colorcmds::{Recolor, Scope, keeping_series_paint};
use super::super::super::overprint::edit_counted;
use super::super::super::{bad, checked_ids_or_selection, number_or, switch_or, text_param};
use crate::{Result, Session};
@@ -149,7 +149,7 @@ pub(super) fn run(s: &mut Session, p: &Value) -> Result<Value> {
true
};
let scope = Scope { fill: fixes.fill, stroke: fixes.stroke, images: false, patterns: false };
ink = Recolor::with_links(scope, &|c| fixes.limit(c), &links).run(d, &ids);
ink = keeping_series_paint(d, &ids, |d| Ok(Recolor::with_links(scope, &|c| fixes.limit(c), &links).run(d, &ids)))?;
}
if !fixes.remove_white_overprint && fixes.overprint_black <= 0.0 {
return Ok(ink);
+4 -2
View File
@@ -1,9 +1,10 @@
//! Cutting Tools (`addon.cutting.*`), a built-in add-on that prepares art for cutting. Stencil
//! Bridges cuts bridges out of the selected art so that a stencil cut from it holds together
//! ([`stencil`]), and Weed Box and Lines adds a weed box and weeding lines around the selected art
//! for vinyl cutting ([`weed`]). Its submenu (Object › Plug-ins › Cutting Tools) and dialogs are
//! the UI's.
//! for vinyl cutting ([`weed`]). Banner Hems and Grommets marks the hems and grommets of a banner
//! ([`banner`]). Its submenu (Object › Plug-ins › Cutting Tools) and dialogs are the UI's.
mod banner;
mod stencil;
mod weed;
@@ -12,5 +13,6 @@ use super::super::CommandSpec;
pub fn specs() -> Vec<CommandSpec> {
let mut v = stencil::specs();
v.extend(weed::specs());
v.extend(banner::specs());
v
}
@@ -0,0 +1,228 @@
//! Banner Hems and Grommets (`addon.cutting.banner`), a command of the built-in Cutting Tools
//! add-on for finishing a printed banner: on each chosen side of the banner it adds a hem line,
//! where the edge is folded back and sewn (<https://en.wikipedia.org/wiki/Hem>), and grommet
//! marks, where rings are set into the material to hang it
//! (<https://en.wikipedia.org/wiki/Grommet>), spread evenly at most a set spacing apart. The
//! banner is the selected art's bounds, or each artboard.
#[cfg(test)]
mod tests;
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_color::Paint;
use vectorcraft_color::swatch::REGISTRATION;
use vectorcraft_doc::{Appearance, Node};
use vectorcraft_geom::{Point, Rect, shapes};
use super::super::super::edit::selected_roots;
use super::super::super::paint::swatch_solid;
use super::super::super::pathops::length_given;
use super::super::super::{CommandSpec, bad, cmd, has_doc, switch_or, text_param};
use super::weed::outside_clips;
use crate::{Result, Session};
/// Banner Hems and Grommets' command.
pub const BANNER: &str = "addon.cutting.banner";
/// The sides of a banner, in the order the grommets go round it.
const SIDES: [&str; 4] = ["top", "right", "bottom", "left"];
/// The largest hem, inset or spacing, in points.
const MAX_DISTANCE: f64 = 100_000.0;
/// The most grommets one run adds.
const MAX_GROMMETS: usize = 100_000;
/// Two grommet centers closer than this are one grommet (the corner that two sides share).
const SAME: f64 = 1e-6;
pub fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"addon.cutting.banner",
"Banner Hems and Grommets…",
["Object", "Plug-ins", "Cutting Tools"],
None,
"{hem?: pt 0..100000 (72: from each edge to its hem line; 0: no hem lines), grommets?: bool (true), spacing?: pt more than 0 and at most 100000 (1728: the most the grommets on a side are apart), grommetInset?: pt 0..100000 (36: from each edge to the grommets' centers), diameter?: pt 0.01..1000 (27: each grommet mark's circle), top?, right?, bottom?, left?: bool (true: the sides that get a hem and grommets), weight?: pt 0.01..1000 (0.3), swatch?: a color swatch the marks are stroked in (\"[Registration]\"), allArtboards?: bool (default: true when nothing is selected)} mark the hems and grommets of a banner, the selected art's bounds or each artboard: a hem line `hem` inside each chosen edge, running the edge's whole length, and grommet marks (a circle with a cross at its center) `grommetInset` inside each chosen edge, one at each end of the side and the rest spread evenly between them, as few as keep them at most `spacing` apart. One group named Banner Marks per banner, stroked with no fill, on top of the current layer, selected, as one undo step → {id: the first group, ids, hems (hem lines), grommets (grommet marks)}",
has_doc,
banner
)]
}
/// The distance `p` gives for `key` (0..[`MAX_DISTANCE`]), or `default`.
fn distance(p: &Value, key: &str, default: f64) -> Result<f64> {
match length_given(p, key, BANNER)? {
None => Ok(default),
Some(v) if (0.0..=MAX_DISTANCE).contains(&v) => Ok(v),
Some(_) => Err(bad(BANNER, format!("`{key}` must be from 0 to {MAX_DISTANCE} pt"))),
}
}
/// The length `p` gives for `key` (0.01..1000), or `default`.
fn size(p: &Value, key: &str, default: f64) -> Result<f64> {
match length_given(p, key, BANNER)? {
None => Ok(default),
Some(v) if (0.01..=1000.0).contains(&v) => Ok(v),
Some(_) => Err(bad(BANNER, format!("`{key}` must be from 0.01 to 1000 pt"))),
}
}
/// Which sides are on, in [`SIDES`] order.
type Sides = [bool; 4];
/// Whether marks `depth` inside a banner's near and far edges, `len` apart, fit: they stay inside
/// the banner, and when both edges are chosen the two sets stay apart.
fn fits(depth: f64, len: f64, near: bool, far: bool) -> bool {
match (near, far) {
(true, true) => 2.0 * depth < len,
(true, false) | (false, true) => depth < len,
(false, false) => true,
}
}
/// The hem lines of banner `r`: one `hem` inside each chosen edge, from one end of the edge to the
/// other.
fn hem_lines(r: Rect, hem: f64, sides: Sides) -> Vec<(Point, Point)> {
if hem <= 0.0 {
return vec![];
}
let lines = [
(Point::new(r.x0, r.y0 + hem), Point::new(r.x1, r.y0 + hem)),
(Point::new(r.x1 - hem, r.y0), Point::new(r.x1 - hem, r.y1)),
(Point::new(r.x0, r.y1 - hem), Point::new(r.x1, r.y1 - hem)),
(Point::new(r.x0 + hem, r.y0), Point::new(r.x0 + hem, r.y1)),
];
lines.into_iter().zip(sides).filter(|(_, on)| *on).map(|(l, _)| l).collect()
}
/// The grommet centers of banner `r`: on each chosen side, `inset` inside the edge, one at each end
/// (`inset` from the edges across it) and the rest spread evenly between them, as few as keep them
/// at most `spacing` apart. They go round the banner clockwise from the top left; a corner that two
/// chosen sides share has one grommet. `None` when there would be more than `limit`.
fn grommet_centers(r: Rect, inset: f64, spacing: f64, sides: Sides, limit: usize) -> Option<Vec<Point>> {
let (l, t, rt, b) = (r.x0 + inset, r.y0 + inset, r.x1 - inset, r.y1 - inset);
// Each side from its start to its end, clockwise.
let runs = [
(Point::new(l, t), Point::new(rt, t)),
(Point::new(rt, t), Point::new(rt, b)),
(Point::new(rt, b), Point::new(l, b)),
(Point::new(l, b), Point::new(l, t)),
];
let mut out: Vec<Point> = vec![];
for ((a, z), on) in runs.into_iter().zip(sides) {
if !on {
continue;
}
let gaps = ((z - a).hypot() / spacing - 1e-9).ceil().max(1.0);
if !gaps.is_finite() || gaps > limit as f64 {
return None;
}
let gaps = gaps as usize;
for i in 0..=gaps {
let p = a.lerp(z, i as f64 / gaps as f64);
// A side starts where the one before it ends, and the last one ends where the first
// starts.
let shared = |q: Option<&Point>| q.is_some_and(|q| (*q - p).hypot() < SAME);
if !shared(out.last()) && !shared(out.first()) {
out.push(p);
}
if out.len() > limit {
return None;
}
}
}
Some(out)
}
fn banner(s: &mut Session, p: &Value) -> Result<Value> {
let hem = distance(p, "hem", 72.0)?;
let inset = distance(p, "grommetInset", 36.0)?;
let spacing = match length_given(p, "spacing", BANNER)? {
None => 1728.0,
Some(v) if v > 0.0 && v <= MAX_DISTANCE => v,
Some(_) => return Err(bad(BANNER, format!("`spacing` must be more than 0 and at most {MAX_DISTANCE} pt"))),
};
let diameter = size(p, "diameter", 27.0)?;
let weight = size(p, "weight", 0.3)?;
let with_grommets = switch_or(p, "grommets", true, BANNER)?;
let mut sides = [true; 4];
for (on, key) in sides.iter_mut().zip(SIDES) {
*on = switch_or(p, key, true, BANNER)?;
}
if !sides.contains(&true) {
return Err(bad(BANNER, "turn on at least one side"));
}
if hem == 0.0 && !with_grommets {
return Err(bad(BANNER, "with no hem and no grommets there is nothing to mark"));
}
let swatch = text_param(p, "swatch", BANNER)?.unwrap_or(REGISTRATION);
let stroke = swatch_solid(&s.doc()?.doc, swatch, None).map_err(|e| bad(BANNER, e))?;
let all = switch_or(p, "allArtboards", s.doc()?.selection.is_empty(), BANNER)?;
let banners: Vec<Rect> = if all {
s.doc()?.doc.artboards.iter().map(|a| a.rect).collect()
} else {
let roots = selected_roots(s)?;
if roots.is_empty() {
return Err(bad(BANNER, "select the banner, or mark every artboard"));
}
s.doc()?.doc.bounds_of(&roots, false).into_iter().collect()
};
if banners.is_empty() {
return Err(bad(BANNER, "there is no banner to mark"));
}
let [top, right, bottom, left] = sides;
let mut marks = vec![];
let mut total = 0;
for r in &banners {
let (w, h) = (r.width(), r.height());
if !(w.is_finite() && h.is_finite()) || w <= 0.0 || h <= 0.0 {
return Err(bad(BANNER, "the banner has no width or height"));
}
// A hem line must stay inside the banner and apart from the hem line on the far side.
if hem > 0.0 && !(fits(hem, h, top, bottom) && fits(hem, w, left, right)) {
return Err(bad(BANNER, "the hem is too deep for the banner"));
}
let centers = if with_grommets {
// The grommets on a side run from `inset` past one end to `inset` before the other,
// stay inside the banner and stay apart from the grommets on the far side.
let runs_fit = (!(top || bottom) || 2.0 * inset <= w) && (!(left || right) || 2.0 * inset <= h);
if !(runs_fit && fits(inset, h, top, bottom) && fits(inset, w, left, right)) {
return Err(bad(BANNER, "the grommet inset is too large for the banner"));
}
grommet_centers(*r, inset, spacing, sides, MAX_GROMMETS - total)
.ok_or_else(|| bad(BANNER, format!("the spacing makes more than {MAX_GROMMETS} grommets")))?
} else {
vec![]
};
total += centers.len();
marks.push((hem_lines(*r, hem, sides), centers));
}
let parent = outside_clips(&s.doc()?.doc, s.doc()?.target_parent()?);
let ap = Appearance::basic(Paint::None, stroke, weight);
let half = diameter / 2.0;
let (ids, hems) = s.edit("Banner Hems and Grommets", |d, sel| {
let (mut ids, mut hems) = (vec![], 0);
for (lines, centers) in &marks {
let mut children = vec![];
for (a, b) in lines {
let mut n = Node::path(d.alloc_id(), shapes::line(*a, *b), ap.clone());
n.name = Some("Hem".into());
children.push(Arc::new(n));
}
hems += lines.len();
for c in centers {
let ring = Node::path(d.alloc_id(), shapes::ellipse(Rect::new(c.x - half, c.y - half, c.x + half, c.y + half)), ap.clone());
let across = Node::path(d.alloc_id(), shapes::line(Point::new(c.x - half, c.y), Point::new(c.x + half, c.y)), ap.clone());
let down = Node::path(d.alloc_id(), shapes::line(Point::new(c.x, c.y - half), Point::new(c.x, c.y + half)), ap.clone());
let mut g = Node::group(d.alloc_id(), vec![Arc::new(ring), Arc::new(across), Arc::new(down)]);
g.name = Some("Grommet".into());
children.push(Arc::new(g));
}
let mut g = Node::group(d.alloc_id(), children);
g.name = Some("Banner Marks".into());
ids.push(g.id);
d.insert(parent, usize::MAX, g)?;
}
sel.set(ids.iter().copied());
Ok((ids, hems))
})?;
let first = ids.first().map(|i| i.0);
Ok(json!({ "id": first, "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "hems": hems, "grommets": total }))
}
@@ -0,0 +1,263 @@
//! Tests for `addon.cutting.banner`: hem lines and grommet marks on the sides of a banner.
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_color::Paint;
use vectorcraft_doc::{Appearance, Node, NodeKind};
use vectorcraft_geom::{Point, Rect, shapes};
use super::{grommet_centers, hem_lines};
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 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())
}
fn node(s: &Session, id: NodeId) -> Node {
s.doc().unwrap().doc.node(id).cloned().unwrap()
}
/// Runs Banner Hems and Grommets with `p` and gives the first group it made.
fn banner(s: &mut Session, p: Value) -> (Value, Node) {
let r = s.execute("addon.cutting.banner", &p).unwrap();
let g = node(s, id_of(&r));
(r, g)
}
fn round(p: Point) -> (f64, f64) {
let r = |v: f64| (v * 1000.0).round() / 1000.0;
(r(p.x), r(p.y))
}
/// The hem lines in group `g` as their two ends.
fn hems(g: &Node) -> Vec<((f64, f64), (f64, f64))> {
g.children()
.unwrap()
.iter()
.filter(|c| c.name.as_deref() == Some("Hem"))
.map(|c| match &c.kind {
NodeKind::Path { path, .. } => {
let a: Vec<Point> = path.anchors().map(|(_, _, a)| a.p).collect();
assert_eq!(a.len(), 2, "a hem line is one straight segment");
(round(a[0]), round(a[1]))
}
other => panic!("not a path: {other:?}"),
})
.collect()
}
/// The grommet marks in group `g` as their centers.
fn grommets(g: &Node) -> Vec<(f64, f64)> {
g.children().unwrap().iter().filter(|c| c.name.as_deref() == Some("Grommet")).map(|c| round(c.geometric_bounds().unwrap().center())).collect()
}
#[test]
fn hems_and_grommets_go_round_a_selected_banner() {
let mut s = session();
rect(&mut s, 0.0, 0.0, 400.0, 200.0);
let undo = s.doc().unwrap().history.undo.len();
let (r, g) = banner(&mut s, json!({"hem": 20, "grommetInset": 10, "spacing": 150, "diameter": 8}));
assert_eq!(g.name.as_deref(), Some("Banner Marks"));
assert_eq!(
hems(&g),
vec![((0.0, 20.0), (400.0, 20.0)), ((380.0, 0.0), (380.0, 200.0)), ((0.0, 180.0), (400.0, 180.0)), ((20.0, 0.0), (20.0, 200.0))]
);
// 380 pt along the top and bottom need 3 gaps at most 150 apart, 180 down the sides 2; the
// corners are shared.
assert_eq!(
grommets(&g),
vec![
(10.0, 10.0),
(136.667, 10.0),
(263.333, 10.0),
(390.0, 10.0),
(390.0, 100.0),
(390.0, 190.0),
(263.333, 190.0),
(136.667, 190.0),
(10.0, 190.0),
(10.0, 100.0)
]
);
assert_eq!(r["hems"], 4);
assert_eq!(r["grommets"], 10);
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step");
assert_eq!(s.doc().unwrap().selection.objects, [g.id]);
}
#[test]
fn a_grommet_is_a_circle_with_a_cross_stroked_in_registration() {
let mut s = session();
rect(&mut s, 0.0, 0.0, 100.0, 100.0);
let (_, g) = banner(&mut s, json!({"hem": 0, "grommetInset": 10, "diameter": 6, "weight": 0.5}));
let first = g.children().unwrap().iter().find(|c| c.name.as_deref() == Some("Grommet")).cloned().unwrap();
assert_eq!(first.geometric_bounds(), Some(Rect::new(7.0, 7.0, 13.0, 13.0)));
let parts = first.children().unwrap();
assert_eq!(parts.len(), 3, "a circle and two lines");
for c in parts.iter() {
assert!(matches!(c.kind, NodeKind::Path { .. }), "a path");
assert_eq!(c.appearance.fill_paint(), Paint::None);
assert!(c.appearance.stroke_paint().is_registration());
assert_eq!(c.appearance.stroke_width(), 0.5);
}
}
#[test]
fn every_artboard_is_marked_when_nothing_is_selected() {
let mut s = session();
s.execute("artboard.new", &json!({"x": 900, "y": 0, "width": 200, "height": 150})).unwrap();
s.execute("select.none", &json!({})).unwrap();
let r = s.execute("addon.cutting.banner", &json!({"grommets": false})).unwrap();
let ids: Vec<NodeId> = r["ids"].as_array().unwrap().iter().map(|v| NodeId(v.as_u64().unwrap())).collect();
assert_eq!(ids.len(), 2);
let second = node(&s, ids[1]);
assert_eq!(hems(&second)[0], ((900.0, 72.0), (1100.0, 72.0)), "the default hem is 72 pt");
assert!(grommets(&second).is_empty());
assert_eq!(r["grommets"], 0);
}
#[test]
fn only_the_chosen_sides_are_marked() {
let mut s = session();
rect(&mut s, 0.0, 0.0, 300.0, 100.0);
let (_, g) = banner(&mut s, json!({"hem": 10, "grommetInset": 5, "spacing": 1000, "right": false, "bottom": false, "left": false}));
assert_eq!(hems(&g), vec![((0.0, 10.0), (300.0, 10.0))]);
assert_eq!(grommets(&g), vec![(5.0, 5.0), (295.0, 5.0)]);
}
#[test]
fn units_are_read_and_bad_params_are_refused() {
let mut s = session();
rect(&mut s, 0.0, 0.0, 400.0, 400.0);
let (_, g) = banner(&mut s, json!({"hem": "1 in", "grommetInset": "0.5 in", "spacing": "10 in"}));
assert_eq!(hems(&g)[0], ((0.0, 72.0), (400.0, 72.0)));
assert_eq!(grommets(&g)[0], (36.0, 36.0));
let before = s.doc().unwrap().history.undo.len();
for p in [
json!({"hem": -1}),
json!({"hem": "x"}),
json!({"spacing": 0}),
json!({"diameter": 0}),
json!({"weight": 1e9}),
json!({"top": "yes"}),
json!({"top": false, "right": false, "bottom": false, "left": false}),
json!({"hem": 0, "grommets": false}),
json!({"hem": 250}),
json!({"grommetInset": 250}),
json!({"spacing": 0.001}),
json!({"swatch": "no such swatch"}),
] {
assert!(s.execute("addon.cutting.banner", &p).is_err(), "{p} is refused");
}
assert_eq!(s.doc().unwrap().history.undo.len(), before, "a refused run changes nothing");
}
#[test]
fn hems_and_grommets_on_one_side_may_go_past_the_middle() {
let mut s = session();
rect(&mut s, 0.0, 0.0, 300.0, 100.0);
let one = json!({"right": false, "bottom": false, "left": false, "spacing": 1000});
let with = |extra: Value| {
let mut p = one.clone();
p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
p
};
let (_, g) = banner(&mut s, with(json!({"hem": 60, "grommetInset": 70})));
assert_eq!(hems(&g), vec![((0.0, 60.0), (300.0, 60.0))]);
assert_eq!(grommets(&g), vec![(70.0, 70.0), (230.0, 70.0)]);
for p in [with(json!({"hem": 100})), with(json!({"hem": 0, "grommetInset": 100})), with(json!({"grommetInset": 151}))] {
assert!(s.execute("addon.cutting.banner", &p).is_err(), "{p} reaches the far edge or past the ends");
}
// A grommet inset of half the width puts the grommets of a side on one point: one grommet.
let mut s = session();
rect(&mut s, 0.0, 0.0, 100.0, 300.0);
let (_, g) = banner(&mut s, with(json!({"hem": 0, "grommetInset": 50, "spacing": 10})));
assert_eq!(grommets(&g), vec![(50.0, 50.0)]);
}
#[test]
fn hems_and_grommets_on_opposite_sides_stay_apart() {
let mut s = session();
rect(&mut s, 0.0, 0.0, 300.0, 100.0);
let pair = |p: Value| {
let mut q = json!({"right": false, "left": false, "spacing": 1000});
q.as_object_mut().unwrap().extend(p.as_object().unwrap().clone());
q
};
// Half the height would put the top and bottom marks on the same line.
let refused = [
pair(json!({"hem": 50})),
pair(json!({"hem": 0, "grommetInset": 50})),
json!({"hem": 0, "grommetInset": 150, "top": false, "bottom": false}),
];
for p in refused {
assert!(s.execute("addon.cutting.banner", &p).is_err(), "{p} is refused");
}
let (_, g) = banner(&mut s, pair(json!({"hem": 49.5, "grommetInset": 49.5})));
assert_eq!(hems(&g), vec![((0.0, 49.5), (300.0, 49.5)), ((0.0, 50.5), (300.0, 50.5))]);
assert_eq!(grommets(&g), vec![(49.5, 49.5), (250.5, 49.5), (250.5, 50.5), (49.5, 50.5)]);
}
#[test]
fn the_marks_go_outside_a_clip_group_edited_in_isolation() {
let mut s = session();
let parent = s.doc().unwrap().target_parent().unwrap();
let (g, art) = s
.edit("clip group", |d, _| {
let clip = Arc::new(Node::path(d.alloc_id(), shapes::rectangle(Rect::new(100.0, 100.0, 150.0, 140.0)), Appearance::default()));
let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 400.0, 200.0)), Appearance::default());
let art_id = art.id;
let mut g = Node::group(d.alloc_id(), vec![clip, Arc::new(art)]);
if let NodeKind::Group { clip, .. } = &mut g.kind {
*clip = true;
}
let id = g.id;
d.insert(parent, usize::MAX, g)?;
Ok((id, art_id))
})
.unwrap();
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
s.execute("select.set", &json!({"ids": [art.0]})).unwrap();
let (_, marks) = banner(&mut s, json!({"hem": 20, "grommets": false}));
// The clipping path would hide marks inside the clip group.
assert_eq!(s.doc().unwrap().doc.parent_of(marks.id), parent);
assert_eq!(hems(&marks)[0], ((0.0, 20.0), (400.0, 20.0)), "the selected art is the banner");
}
#[test]
fn all_artboards_marks_the_artboards_even_with_a_selection() {
let mut s = session();
rect(&mut s, 10.0, 10.0, 100.0, 100.0);
let (_, g) = banner(&mut s, json!({"allArtboards": true, "grommets": false}));
assert_eq!(hems(&g)[0], ((0.0, 72.0), (800.0, 72.0)));
}
#[test]
fn an_empty_document_has_no_banner_to_mark_when_artboards_are_off() {
let mut s = session();
assert!(s.execute("addon.cutting.banner", &json!({"allArtboards": false})).is_err());
}
#[test]
fn a_side_shorter_than_the_spacing_has_a_grommet_at_each_end() {
let r = Rect::new(0.0, 0.0, 100.0, 50.0);
let c = grommet_centers(r, 0.0, 1000.0, [true, false, false, false], 10).unwrap();
assert_eq!(c, vec![Point::new(0.0, 0.0), Point::new(100.0, 0.0)]);
// Spacing that divides the side exactly does not add a grommet, even when the division
// rounds up (2.1 / 0.3 is 7.000000000000001).
let c = grommet_centers(Rect::new(0.0, 0.0, 2.1, 1.0), 0.0, 0.3, [true, false, false, false], 100).unwrap();
assert_eq!(c.len(), 8);
assert!(grommet_centers(r, 0.0, 1.0, [true; 4], 10).is_none(), "over the limit");
assert!(hem_lines(r, 0.0, [true; 4]).is_empty());
}
+1 -1
View File
@@ -72,7 +72,7 @@ fn lines_across(length: f64, count: Option<usize>, spacing: Option<f64>) -> Resu
/// Where the Weeding group goes: `parent`, or, when `parent` is inside a clip group or clipping
/// sublayer (a group edited in isolation), the container around the outermost of them. A clipping
/// path would hide the lines and the box, which lie outside the art.
fn outside_clips(d: &Document, parent: Option<NodeId>) -> Option<NodeId> {
pub(super) fn outside_clips(d: &Document, parent: Option<NodeId>) -> Option<NodeId> {
let clips = |id: NodeId| d.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Group { clip: true, .. } | NodeKind::Layer { clip: true, .. }));
let (mut at, mut out) = (parent, parent);
while let Some(p) = at {
+4 -1
View File
@@ -132,8 +132,10 @@ fn export_all_open(s: &mut Session, p: &Value) -> Result<Value> {
let active = s.active;
for i in 0..s.docs.len() {
// Each document in turn is the one Save a Copy writes; switching tabs this way leaves every
// document's tool and interaction alone, and the active one comes back below.
// document's tool and interaction alone, and the active one comes back below. Its colors
// are written through its own profiles.
s.active = Some(i);
s.sync_front_profiles();
let Ok(st) = s.doc() else { continue };
let title = st.doc.title.clone();
let stem = fileio::file_stem(st.path.as_deref().unwrap_or(&title));
@@ -160,6 +162,7 @@ fn export_all_open(s: &mut Session, p: &Value) -> Result<Value> {
}
}
s.active = active;
s.sync_front_profiles();
Ok(json!({ "files": files, "failed": failed, "format": format.id }))
}
+112 -74
View File
@@ -2,12 +2,16 @@
//! selected images transparent in their own pixels, as one undo step. The background is the most
//! common color along an image's edges, the average of its four corners, or colors the caller
//! picks. It is cleared where it reaches in from an edge, or wherever it is. The work is done here,
//! on the pixels; nothing is sent anywhere. It is a VectorCraft addition. Its submenu (Object ›
//! Plug-ins › Image Tools) and dialog are the UI's.
//! on the pixels; nothing is sent anywhere. Color Mask ([`mask`]) hides colors matched the same
//! way while the image keeps its pixels. They are VectorCraft additions. Its submenu (Object ›
//! Plug-ins › Image Tools) and dialogs are the UI's.
mod mask;
#[cfg(test)]
mod tests;
pub(crate) use mask::refresh as refresh_color_masks;
use std::collections::{HashMap, HashSet};
use std::io::Cursor;
use std::sync::{Arc, Weak};
@@ -15,12 +19,12 @@ use std::sync::{Arc, Weak};
use image::{DynamicImage, ImageBuffer, LumaA, Rgba};
use serde_json::{Value, json};
use vectorcraft_color::Color;
use vectorcraft_doc::{ImageBlob, NodeId, NodeKind};
use vectorcraft_doc::{ImageBlob, ImageObject, NodeId, NodeKind};
use vectorcraft_geom::Affine;
use super::super::fileio::{MAX_RASTER_ALLOC, ppi};
use super::super::menucmds::has_image;
use super::super::paint::{PROCESS_ON_TRANSPARENCY, gray_colorized_with_process};
use super::super::paint::{PROCESS_ON_TRANSPARENCY, colorized_with_process};
use super::super::{CommandSpec, Result, Session, bad, checked_ids_param, cmd, hex_with_alpha, number_or, switch_or, text_param};
/// Remove Background's command.
@@ -35,7 +39,7 @@ const MAX_COLORS: usize = 16;
const WORK_BYTES: u64 = 10;
pub fn specs() -> Vec<CommandSpec> {
vec![cmd!(
let mut v = vec![cmd!(
"addon.image.removeBackground",
"Remove Background…",
["Object", "Plug-ins", "Image Tools"],
@@ -43,7 +47,9 @@ pub fn specs() -> Vec<CommandSpec> {
"{background?: \"edges\" (default: the most common color along the image's edges; nothing is cleared when the edges hold at least as many clear pixels as pixels of that color) | \"corners\" (the average of the image's four corner pixels that are not clear; nothing is cleared when all four are clear) | \"colors\" (the colors in `colors`), colors?: [color…] or one string of them split by commas or spaces (1 to 16 colors, each a hex color \"#rrggbb\" or \"#rgb\" with or without the # or one of black, white, red, green and blue; needed with background: colors, and checked but not used with edges or corners), contiguous?: bool (true: only background pixels that reach in from an edge are cleared; false: they are cleared wherever they are; true), match?: \"distance\" (default: a color's RGB distance from a background color) | \"channels\" (its largest difference on one of red, green and blue), tolerance?: 0..100 (with distance, % of the largest RGB distance; with channels, % of 255 steps on one channel; a pixel this near a background color is cleared; 10), softness?: 0..100 (% past the tolerance over which pixels fade from cleared to kept; 10), ids?: [id…] (default: the selected images)} make the background of each image transparent in its own pixels, as one undo step: the image stays an image, embedded as a PNG with an alpha channel at the depth of its pixels (16-bit images keep 16 bits and grayscale images stay gray) with the source's color profile and resolution, and a linked image is embedded; a CMYK image, a linked image that shows its preview (embed or relink it first), an image too large to change, a result with no pixel left, and a grayscale image colorized with a process color (which can't colorize gray pixels with transparency) are refused, and an image whose pixels do not change is left as it is (no undo step when none changes) → {changed: the images changed, ids, cleared: the pixels made fully clear in them}",
has_image,
remove_background
)]
)];
v.extend(mask::specs());
v
}
/// Where the background's colors come from.
@@ -79,50 +85,50 @@ pub(crate) struct Settings {
}
impl Settings {
/// The settings `p` gives, each checked.
fn read(p: &Value) -> Result<Self> {
/// The settings `p` gives to command `cmd`, each checked.
fn read(p: &Value, cmd: &str) -> Result<Self> {
let percent = |key: &str| -> Result<f64> {
let v = number_or(p, key, 10.0, C)?;
if v.is_finite() && (0.0..=100.0).contains(&v) { Ok(v) } else { Err(bad(C, format!("`{key}` must be from 0 to 100"))) }
let v = number_or(p, key, 10.0, cmd)?;
if v.is_finite() && (0.0..=100.0).contains(&v) { Ok(v) } else { Err(bad(cmd, format!("`{key}` must be from 0 to 100"))) }
};
let (tolerance, softness) = (percent("tolerance")?, percent("softness")?);
let colors = match p.get("colors") {
None | Some(Value::Null) => None,
Some(v) => Some(colors(v)?),
Some(v) => Some(colors(v, cmd)?),
};
let background = match text_param(p, "background", C)? {
let background = match text_param(p, "background", cmd)? {
None | Some("edges") => Background::Edges,
Some("corners") => Background::Corners,
Some("colors") => Background::Colors(colors.ok_or_else(colors_error)?),
Some(_) => return Err(bad(C, "`background` must be edges, corners or colors")),
Some("colors") => Background::Colors(colors.ok_or_else(|| colors_error(cmd))?),
Some(_) => return Err(bad(cmd, "`background` must be edges, corners or colors")),
};
let measure = match text_param(p, "match", C)? {
let measure = match text_param(p, "match", cmd)? {
None | Some("distance") => Match::Distance,
Some("channels") => Match::Channels,
Some(_) => return Err(bad(C, "`match` must be distance or channels")),
Some(_) => return Err(bad(cmd, "`match` must be distance or channels")),
};
let contiguous = switch_or(p, "contiguous", true, C)?;
let contiguous = switch_or(p, "contiguous", true, cmd)?;
Ok(Self { background, contiguous, measure, tolerance, softness })
}
}
fn colors_error() -> crate::EngineError {
bad(C, "`colors` must list 1 to 16 colors, each hex (#rrggbb or #rgb) or black, white, red, green or blue")
fn colors_error(cmd: &str) -> crate::EngineError {
bad(cmd, "`colors` must list 1 to 16 colors, each hex (#rrggbb or #rgb) or black, white, red, green or blue")
}
/// The colors `v` lists: an array of strings, or one string of them split by commas or spaces.
/// Each is read as [`Color::from_hex`] reads it; one with an alpha part is refused.
fn colors(v: &Value) -> Result<Vec<[u8; 3]>> {
/// The colors `v` lists to command `cmd`: an array of strings, or one string of them split by
/// commas or spaces. Each is read as [`Color::from_hex`] reads it; one with an alpha part is refused.
fn colors(v: &Value, cmd: &str) -> Result<Vec<[u8; 3]>> {
// One past the most is enough to tell a list that is too long.
let texts: Vec<&str> = match v {
Value::String(s) => s.split([',', ' ', '\t', '\n']).filter(|t| !t.is_empty()).take(MAX_COLORS + 1).collect(),
Value::Array(a) => a.iter().take(MAX_COLORS + 1).map(Value::as_str).collect::<Option<_>>().ok_or_else(colors_error)?,
_ => return Err(colors_error()),
Value::Array(a) => a.iter().take(MAX_COLORS + 1).map(Value::as_str).collect::<Option<_>>().ok_or_else(|| colors_error(cmd))?,
_ => return Err(colors_error(cmd)),
};
if texts.is_empty() || texts.len() > MAX_COLORS {
return Err(colors_error());
return Err(colors_error(cmd));
}
texts.into_iter().map(|t| rgb8(t).ok_or_else(colors_error)).collect()
texts.into_iter().map(|t| rgb8(t).ok_or_else(|| colors_error(cmd))).collect()
}
/// The 8-bit RGB of the color `t` writes.
@@ -135,7 +141,7 @@ fn rgb8(t: &str) -> Option<[u8; 3]> {
}
fn remove_background(s: &mut Session, p: &Value) -> Result<Value> {
let settings = Settings::read(p)?;
let settings = Settings::read(p, C)?;
// A preview step keeps the pixels it decodes for the next step; other runs keep none.
let mut kept = std::mem::take(&mut s.decoded_images);
let previewing = s.previewing;
@@ -165,40 +171,15 @@ fn remove_background(s: &mut Session, p: &Value) -> Result<Value> {
/// cleared as `settings` say and the transform that keeps its place and size. Decoded pixels are
/// taken from and kept in `kept` when it is given.
fn changes(s: &Session, p: &Value, settings: &Settings, mut kept: Option<&mut DecodedImages>) -> Result<Vec<(NodeId, Cleared, Affine)>> {
let images = images(s, p, C)?;
// The result has an alpha channel, which a grayscale image colorized with a process color
// can't take. The pixels that are cleared are checked, the image's own, not the ones a color
// mask shows.
let st = s.doc()?;
let ids: Vec<NodeId> = if p.get("ids").is_some_and(|v| !v.is_null()) {
// Each image once, however often `ids` names it.
let mut given = HashSet::new();
let ids: Vec<NodeId> = checked_ids_param(s, p, "ids", C)?.into_iter().filter(|id| given.insert(*id)).collect();
if let Some(id) = ids.iter().find(|id| !matches!(st.doc.node(**id).map(|n| &n.kind), Some(NodeKind::Image(_)))) {
return Err(bad(C, format!("object {} is not an image", id.0)));
}
ids
} else {
st.selection.objects.iter().copied().filter(|id| matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::Image(_)))).collect()
};
if ids.is_empty() {
return Err(bad(C, "select an image"));
}
// Every image is checked before any is decoded.
let mut images = vec![];
for id in ids {
let Some(n) = st.doc.node(id) else { continue };
let NodeKind::Image(im) = &n.kind else { continue };
let blob = st.doc.images.get(&im.key).ok_or_else(|| bad(C, "the image's pixels are missing"))?;
// The result has an alpha channel, which a grayscale image colorized with a process color
// can't take.
if gray_colorized_with_process(&st.doc, n).is_some() {
for (id, _, blob) in &images {
if blob.gray_source().is_some() && st.doc.node(*id).is_some_and(|n| colorized_with_process(&st.doc, n)) {
return Err(bad(C, PROCESS_ON_TRANSPARENCY));
}
// The preview stands in for a file that hasn't been read, or that is kept at its preview.
if im.link.is_some() && blob.is_proxy() {
return Err(bad(C, "the linked image shows its preview: embed or relink it first"));
}
if blob.is_cmyk() {
return Err(bad(C, "a CMYK image has no transparency to set"));
}
images.push((id, im, blob));
}
// Each image's pixels once, however many objects show them.
let mut cleared: HashMap<&str, Option<Cleared>> = HashMap::new();
@@ -207,7 +188,7 @@ fn changes(s: &Session, p: &Value, settings: &Settings, mut kept: Option<&mut De
let out = match cleared.get(im.key.as_str()) {
Some(out) => out.clone(),
None => {
let out = clear(blob, settings, kept.as_deref_mut())?;
let out = clear(blob, settings, kept.as_deref_mut(), C)?;
cleared.insert(&im.key, out.clone());
out
}
@@ -225,6 +206,58 @@ fn changes(s: &Session, p: &Value, settings: &Settings, mut kept: Option<&mut De
Ok(changes)
}
/// The image objects command `cmd` acts on (`ids`, each once, or the selected images), each with
/// its pixels, all checked before any is decoded: an object that is not an image, missing pixels,
/// a linked image that shows its preview and a CMYK image are errors, as is no image at all.
fn images<'a>(s: &'a Session, p: &Value, cmd: &str) -> Result<Vec<(NodeId, &'a ImageObject, &'a ImageBlob)>> {
let st = s.doc()?;
let mut images = vec![];
for id in targets(s, p, cmd)? {
let Some(NodeKind::Image(im)) = st.doc.node(id).map(|n| &n.kind) else { continue };
let blob = st.doc.images.get(&im.key).ok_or_else(|| bad(cmd, "the image's pixels are missing"))?;
// The preview stands in for a file that hasn't been read, or that is kept at its preview.
if im.link.is_some() && blob.is_proxy() {
return Err(bad(cmd, "the linked image shows its preview: embed or relink it first"));
}
if blob.is_cmyk() {
return Err(cmyk_refusal(cmd));
}
images.push((id, &**im, blob));
}
Ok(images)
}
/// The image objects command `cmd` acts on: `ids`, each once, or the selected images. An object in
/// `ids` that is not an image is an error, as is no image at all.
fn targets(s: &Session, p: &Value, cmd: &str) -> Result<Vec<NodeId>> {
let st = s.doc()?;
let ids: Vec<NodeId> = if p.get("ids").is_some_and(|v| !v.is_null()) {
// Each image once, however often `ids` names it.
let mut given = HashSet::new();
let ids: Vec<NodeId> = checked_ids_param(s, p, "ids", cmd)?.into_iter().filter(|id| given.insert(*id)).collect();
if let Some(id) = ids.iter().find(|id| !matches!(st.doc.node(**id).map(|n| &n.kind), Some(NodeKind::Image(_)))) {
return Err(bad(cmd, format!("object {} is not an image", id.0)));
}
ids
} else {
st.selection.objects.iter().copied().filter(|id| matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::Image(_)))).collect()
};
if ids.is_empty() {
return Err(bad(cmd, "select an image"));
}
Ok(ids)
}
/// Whether `cmd` is one of Color Mask's commands, which hide pixels instead of clearing them.
fn masks(cmd: &str) -> bool {
matches!(cmd, mask::COLOR_MASK | mask::REMOVE_COLOR_MASK | mask::APPLY_COLOR_MASK)
}
/// Command `cmd`'s refusal of a CMYK image.
fn cmyk_refusal(cmd: &str) -> crate::EngineError {
if masks(cmd) { bad(cmd, "a CMYK image can't take a color mask") } else { bad(cmd, "a CMYK image has no transparency to set") }
}
/// An image with its background cleared: its PNG, its size in pixels, and how many of its pixels
/// were made fully clear.
#[derive(Clone, Debug)]
@@ -352,16 +385,16 @@ impl Pixels {
/// `blob` with its background cleared as `settings` say, or `None` when no pixel changes. A CMYK
/// image, one that can't be decoded or is too large to change, and a result with no pixel left are
/// errors. The PNG keeps the source's ICC profile and resolution. The decoded pixels are taken
/// from and kept in `kept` when it is given.
pub(crate) fn clear(blob: &ImageBlob, settings: &Settings, mut kept: Option<&mut DecodedImages>) -> Result<Option<Cleared>> {
/// errors of command `cmd`. The PNG keeps the source's ICC profile and resolution. The decoded
/// pixels are taken from and kept in `kept` when it is given.
pub(crate) fn clear(blob: &ImageBlob, settings: &Settings, mut kept: Option<&mut DecodedImages>, cmd: &str) -> Result<Option<Cleared>> {
if blob.is_cmyk() {
return Err(bad(C, "a CMYK image has no transparency to set"));
return Err(cmyk_refusal(cmd));
}
let found = kept.as_deref_mut().and_then(|k| k.get(&blob.bytes));
let (source, gray, icc) = match found {
Some(found) => found,
None => decode(blob, kept)?,
None => decode(blob, kept, cmd)?,
};
// The pixels kept for the next run stay as they are; ones not kept are worked on in place.
let mut px = Arc::try_unwrap(source).unwrap_or_else(|kept| Pixels::clone(&kept));
@@ -373,7 +406,11 @@ pub(crate) fn clear(blob: &ImageBlob, settings: &Settings, mut kept: Option<&mut
Pixels::Sixteen(img) => img.pixels().any(|p| p.0[3] > 0),
};
if !left {
return Err(bad(C, "every pixel matches the background: no image would be left"));
return Err(if masks(cmd) {
bad(cmd, "the mask would hide every pixel")
} else {
bad(cmd, "every pixel matches the background: no image would be left")
});
}
let out = match (px, gray) {
(Pixels::Eight(img), false) => DynamicImage::ImageRgba8(img),
@@ -389,9 +426,9 @@ pub(crate) fn clear(blob: &ImageBlob, settings: &Settings, mut kept: Option<&mut
let mut encoder = image::codecs::png::PngEncoder::new(&mut png);
if let Some(icc) = icc {
use image::ImageEncoder as _;
encoder.set_icc_profile(icc).map_err(|e| bad(C, e.to_string()))?;
encoder.set_icc_profile(icc).map_err(|e| bad(cmd, e.to_string()))?;
}
out.write_with_encoder(encoder).map_err(|e| bad(C, e.to_string()))?;
out.write_with_encoder(encoder).map_err(|e| bad(cmd, e.to_string()))?;
// The resolution the file declares, which sizes the image at 100% when it is replaced or relinked.
if let Some(r) = ppi::resolution(&blob.bytes) {
png = ppi::with_png_resolution(&png, r);
@@ -401,11 +438,12 @@ pub(crate) fn clear(blob: &ImageBlob, settings: &Settings, mut kept: Option<&mut
/// `blob`'s pixels as straight RGBA, whether they were gray, and its ICC profile. An image that
/// can't be decoded or is too large to change is an error. The pixels are kept in `kept`, when it
/// is given, if a copy of them fits the decode allowance beside the work.
fn decode(blob: &ImageBlob, kept: Option<&mut DecodedImages>) -> Result<(Arc<Pixels>, bool, Option<Vec<u8>>)> {
let reader =
|| image::ImageReader::new(Cursor::new(blob.bytes.as_slice())).with_guessed_format().map_err(|_| bad(C, "the image's pixels can't be read"));
let mut decoder = reader()?.into_decoder().map_err(|e| bad(C, format!("the image's pixels can't be read: {e}")))?;
/// is given, if a copy of them fits the decode allowance beside the work. Errors are command `cmd`'s.
fn decode(blob: &ImageBlob, kept: Option<&mut DecodedImages>, cmd: &str) -> Result<(Arc<Pixels>, bool, Option<Vec<u8>>)> {
let reader = || {
image::ImageReader::new(Cursor::new(blob.bytes.as_slice())).with_guessed_format().map_err(|_| bad(cmd, "the image's pixels can't be read"))
};
let mut decoder = reader()?.into_decoder().map_err(|e| bad(cmd, format!("the image's pixels can't be read: {e}")))?;
// The ICC profile the colors are in goes with them into the PNG.
let (w, h, kind, icc) = {
use image::ImageDecoder as _;
@@ -418,13 +456,13 @@ fn decode(blob: &ImageBlob, kept: Option<&mut DecodedImages>) -> Result<(Arc<Pix
let deep = kind.bytes_per_pixel() > kind.channel_count();
let per_pixel = u64::from(kind.bytes_per_pixel()) + 2 * if deep { 8 } else { 4 } + WORK_BYTES;
if u64::from(w).checked_mul(u64::from(h)).and_then(|n| n.checked_mul(per_pixel)).is_none_or(|n| n > MAX_RASTER_ALLOC) {
return Err(bad(C, format!("an image of {w} × {h} pixels is too large to change")));
return Err(bad(cmd, format!("an image of {w} × {h} pixels is too large to change")));
}
let mut reader = reader()?;
let mut limits = image::Limits::default();
limits.max_alloc = Some(MAX_RASTER_ALLOC);
reader.limits(limits);
let img = reader.decode().map_err(|e| bad(C, format!("the image's pixels can't be read: {e}")))?;
let img = reader.decode().map_err(|e| bad(cmd, format!("the image's pixels can't be read: {e}")))?;
#[cfg(test)]
DECODES.with(|c| c.set(c.get() + 1));
let gray = matches!(img.color(), image::ColorType::L8 | image::ColorType::La8 | image::ColorType::L16 | image::ColorType::La16);
+443
View File
@@ -0,0 +1,443 @@
//! Image Tools › Color Mask (`addon.image.colorMask`, `addon.image.removeColorMask`,
//! `addon.image.applyColorMask`): colors of the selected images are hidden while their pixels
//! stay as they are. The colors are matched as Remove Background matches them ([`super::clear`]);
//! the image keeps its own pixels, and the mask's settings and the masked pixels are kept with it
//! ([`vectorcraft_doc::color_mask`]), so the mask can be changed, removed, or applied to the
//! pixels later. When an image's own pixels are replaced (a link updated or relinked, the image
//! cropped or recolored), its mask is applied to the new pixels ([`refresh`]).
#[cfg(test)]
mod tests;
use std::collections::HashMap;
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_doc::color_mask::{ColorMask, MaskBackground, MaskMatch};
use vectorcraft_doc::{Document, ImageBlob, Node, NodeId, NodeKind};
use vectorcraft_geom::Affine;
use super::super::super::paint::{PROCESS_ON_TRANSPARENCY, colorized_with_process};
use super::super::super::{CommandSpec, Result, Session, bad, cmd};
use super::{Background, DecodedImages, MAX_COLORS, Match, Settings, clear, images, targets};
/// Color Mask's command.
pub const COLOR_MASK: &str = "addon.image.colorMask";
/// Remove Color Mask's command.
pub const REMOVE_COLOR_MASK: &str = "addon.image.removeColorMask";
/// Apply Color Mask's command.
pub const APPLY_COLOR_MASK: &str = "addon.image.applyColorMask";
/// The params that set a mask; with none of them, Color Mask only reports.
const SETTINGS: [&str; 6] = ["background", "colors", "contiguous", "match", "tolerance", "softness"];
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
"addon.image.colorMask",
"Color Mask…",
["Object", "Plug-ins", "Image Tools"],
None,
"{background?: \"edges\" (default: the most common color along the image's edges) | \"corners\" (the average of the image's four corner pixels that are not clear) | \"colors\" (the colors in `colors`), colors?: [color…] or one string of them split by commas or spaces (1 to 16 hex colors or black, white, red, green and blue, as addon.image.removeBackground takes them; needed with background: colors), contiguous?: bool (true: only matching pixels that reach in from an edge are hidden; false: wherever they are; true), match?: \"distance\" (default: a color's RGB distance from a hidden color) | \"channels\" (its largest difference on one of red, green and blue), tolerance?: 0..100 (% as addon.image.removeBackground measures it; a pixel this near a hidden color is hidden; 10), softness?: 0..100 (% past the tolerance over which pixels fade from hidden to shown; 10), ids?: [id…] (default: the selected images)} hide colors of each image without changing its pixels, as one undo step: the image keeps its own pixels, and the mask (these settings, and the image's pixels with the hidden colors made clear, made as Remove Background makes them) is kept with the image and saved with the document; the canvas, printing and separations, PDF, SVG, EPS, raster formats, DXF, EMF, WMF, the legacy .ai and the .ai editing data, copy and paste, and placing a document show the masked pixels, and a click on any part of the image's frame selects it (the Eyedropper, Object Mosaic, Create Gradient Mesh, Crop Image's trim and Image Trace read the image's own pixels); setting the mask again replaces it, and an image whose mask does not change is left as it is (no undo step when none changes); when the image's own pixels are replaced later (Update Link, Relink, Crop Image, a recolor, a linked file read again on open), the mask is made again for the new pixels; an object in `ids` that is not an image, a CMYK image, a linked image that shows its preview (embed or relink it first), an image too large to change, a mask that would hide every pixel, and a mask that would hide pixels of a grayscale image colorized with a process color (masked gray pixels have transparency, which only a spot color, black or white colorizes; each image is checked on the pixels its new mask shows) are refused. With none of background, colors, contiguous, match, tolerance and softness given, nothing changes and the mask settings of the first image (or the defaults when it has no mask) are returned → {changed: the images changed, ids, hidden: the pixels made fully clear in them} or {background, colors, contiguous, match, tolerance, softness, masked}",
super::has_image,
color_mask
),
cmd!(
"addon.image.removeColorMask",
"Remove Color Mask",
["Object", "Plug-ins", "Image Tools"],
None,
"{ids?: [id…] (default: the selected images)} take the color mask off each image, as one undo step: the image shows its own pixels again; images without a mask are left as they are (no undo step when none has one), and an object in `ids` that is not an image is refused → {changed, ids}",
has_color_mask,
remove_color_mask
),
cmd!(
"addon.image.applyColorMask",
"Apply Color Mask",
["Object", "Plug-ins", "Image Tools"],
None,
"{ids?: [id…] (default: the selected images)} make each image's color mask part of its pixels, as one undo step: the masked pixels become the image's own, embedded as a PNG with an alpha channel (a linked image is embedded), and the mask is taken off; a mask that hides nothing is only taken off (the image keeps its pixels and its link); images without a mask are left as they are (no undo step when none has one), and an object in `ids` that is not an image, and a mask made again for new pixels that would give a grayscale image colorized with a process color an alpha channel, are refused → {changed, ids}",
has_color_mask,
apply_color_mask
),
]
}
/// Enabled when a selected image has a color mask.
fn has_color_mask(s: &Session) -> std::result::Result<(), String> {
let st = s.active().ok_or("no document open")?;
if st.selection.objects.iter().any(|id| st.doc.node(*id).and_then(Document::color_mask_of).is_some()) {
Ok(())
} else {
Err("select an image with a color mask".into())
}
}
impl Settings {
/// The settings a mask was made with, `None` when a file gave ones out of range.
fn of(m: &ColorMask) -> Option<Self> {
let percent = |v: f64| v.is_finite() && (0.0..=100.0).contains(&v);
if !percent(m.tolerance) || !percent(m.softness) {
return None;
}
let background = match m.background {
MaskBackground::Edges => Background::Edges,
MaskBackground::Corners => Background::Corners,
MaskBackground::Colors if (1..=MAX_COLORS).contains(&m.colors.len()) => Background::Colors(m.colors.clone()),
MaskBackground::Colors => return None,
};
let measure = match m.measure {
MaskMatch::Distance => Match::Distance,
MaskMatch::Channels => Match::Channels,
};
Some(Self { background, contiguous: m.contiguous, measure, tolerance: m.tolerance, softness: m.softness })
}
/// A mask with these settings whose masked pixels are `key`, made from the pixels `from`.
fn mask(&self, key: String, from: String) -> ColorMask {
let (background, colors) = match &self.background {
Background::Edges => (MaskBackground::Edges, vec![]),
Background::Corners => (MaskBackground::Corners, vec![]),
Background::Colors(c) => (MaskBackground::Colors, c.clone()),
};
let measure = match self.measure {
Match::Distance => MaskMatch::Distance,
Match::Channels => MaskMatch::Channels,
};
ColorMask { key, from, background, colors, contiguous: self.contiguous, measure, tolerance: self.tolerance, softness: self.softness }
}
}
/// The masked pixels of `blob` (`None`: no pixel is hidden, the image's own pixels show) as
/// `settings` say, with errors of command `cmd`.
fn masked(blob: &ImageBlob, settings: &Settings, kept: Option<&mut DecodedImages>, cmd: &str) -> Result<Option<(String, ImageBlob, u64)>> {
Ok(clear(blob, settings, kept, cmd)?.map(|out| (out.blob.content_key(), out.blob, out.cleared)))
}
fn color_mask(s: &mut Session, p: &Value) -> Result<Value> {
if !SETTINGS.iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) {
return report(s, p);
}
let settings = Settings::read(p, COLOR_MASK)?;
// A preview step keeps the pixels it decodes for the next step; other runs keep none.
let mut kept = std::mem::take(&mut s.decoded_images);
let previewing = s.previewing;
let found = mask_changes(s, p, &settings, previewing.then_some(&mut kept));
s.decoded_images = kept;
let changes = found?;
let ids: Vec<u64> = changes.iter().map(|c| c.0.0).collect();
let hidden: u64 = changes.iter().map(|c| c.3).sum();
if !changes.is_empty() {
s.edit("Color Mask", |d, _| {
for (id, mask, blob, _) in changes {
if let Some(blob) = blob {
d.images.entry(mask.key.clone()).or_insert(blob);
}
if let Some(n) = d.node_mut(id) {
n.extras_mut().color_mask = Some(Box::new(mask));
}
}
Ok(())
})?;
}
Ok(json!({ "changed": ids.len(), "ids": ids, "hidden": hidden }))
}
/// The images `p` names whose mask changes, each with its new mask, the masked pixels to add (when
/// the document doesn't have them) and how many pixels they hide.
type MaskChange = (NodeId, ColorMask, Option<ImageBlob>, u64);
fn mask_changes(s: &Session, p: &Value, settings: &Settings, mut kept: Option<&mut DecodedImages>) -> Result<Vec<MaskChange>> {
let st = s.doc()?;
// Each image's pixels once, however many objects show them.
let mut made: HashMap<&str, (String, Option<ImageBlob>, u64)> = HashMap::new();
let mut out = vec![];
for (id, im, blob) in images(s, p, COLOR_MASK)? {
let (key, pixels, hidden) = match made.get(im.key.as_str()) {
Some(m) => m.clone(),
None => {
let m = match masked(blob, settings, kept.as_deref_mut(), COLOR_MASK)? {
Some((key, blob, hidden)) => (key, Some(blob), hidden),
None => (im.key.clone(), None, 0),
};
made.insert(&im.key, m.clone());
m
}
};
let mask = settings.mask(key, im.key.clone());
if st.doc.node(id).and_then(Document::color_mask_of) == Some(&mask) {
continue;
}
// Masked pixels that hide something have an alpha channel, which a grayscale image
// colorized with a process color can't take. The pixels the new mask shows are checked,
// made from the image's own pixels, not the ones an earlier mask shows.
let shown = pixels.as_ref().or_else(|| st.doc.images.get(&mask.key));
if st.doc.node(id).is_some_and(|n| refused_colorize(&st.doc, n, shown)) {
return Err(bad(COLOR_MASK, PROCESS_ON_TRANSPARENCY));
}
let pixels = pixels.filter(|_| !st.doc.images.contains_key(&mask.key));
out.push((id, mask, pixels, hidden));
}
Ok(out)
}
/// Whether masked pixels `shown`, made for image node `n`, have transparency that `n`'s colorize
/// color can't take: gray pixels with an alpha channel and a process color
/// ([`colorized_with_process`]).
fn refused_colorize(doc: &Document, n: &Node, shown: Option<&ImageBlob>) -> bool {
shown.and_then(ImageBlob::gray_source).is_some_and(|g| g.alpha) && colorized_with_process(doc, n)
}
/// Color Mask without settings: the first image's mask settings, or the defaults. It reads them
/// for images a change would refuse too (CMYK, a linked image at its preview), so the dialog opens.
fn report(s: &Session, p: &Value) -> Result<Value> {
let st = s.doc()?;
let first = targets(s, p, COLOR_MASK)?.first().and_then(|id| st.doc.node(*id)).and_then(Document::color_mask_of).cloned();
let m = first.as_ref();
let hex = |c: &[u8; 3]| format!("#{:02x}{:02x}{:02x}", c[0], c[1], c[2]);
let colors =
m.filter(|m| !m.colors.is_empty()).map_or_else(|| "#ffffff".to_string(), |m| m.colors.iter().map(hex).collect::<Vec<_>>().join(", "));
let name = |v: Value| v.as_str().map(str::to_string).unwrap_or_default();
Ok(json!({
"background": name(serde_json::to_value(m.map_or(MaskBackground::Edges, |m| m.background)).unwrap_or_default()),
"colors": colors,
"contiguous": m.is_none_or(|m| m.contiguous),
"match": name(serde_json::to_value(m.map_or(MaskMatch::Distance, |m| m.measure)).unwrap_or_default()),
"tolerance": m.map_or(10.0, |m| m.tolerance),
"softness": m.map_or(10.0, |m| m.softness),
"masked": m.is_some(),
}))
}
/// The image objects `p` names ([`targets`]: `ids`, or the selected images) that have a color mask.
fn masked_images(s: &Session, p: &Value, cmd: &str) -> Result<Vec<NodeId>> {
let st = s.doc()?;
Ok(targets(s, p, cmd)?.into_iter().filter(|id| st.doc.node(*id).and_then(Document::color_mask_of).is_some()).collect())
}
fn remove_color_mask(s: &mut Session, p: &Value) -> Result<Value> {
let ids = masked_images(s, p, REMOVE_COLOR_MASK)?;
if !ids.is_empty() {
s.edit("Remove Color Mask", |d, _| {
for id in &ids {
if let Some(n) = d.node_mut(*id) {
n.extras_mut().color_mask = None;
}
}
Ok(())
})?;
}
Ok(json!({ "changed": ids.len(), "ids": ids.iter().map(|id| id.0).collect::<Vec<_>>() }))
}
fn apply_color_mask(s: &mut Session, p: &Value) -> Result<Value> {
let ids = masked_images(s, p, APPLY_COLOR_MASK)?;
// Each image's masked pixels, made again first when its own pixels changed since. A mask that
// hides nothing (its masked pixels are the image's own) is only taken off: the image keeps its
// pixels and its link.
let mut made = vec![];
{
let st = s.doc()?;
for id in &ids {
let Some(n) = st.doc.node(*id) else { continue };
let (NodeKind::Image(im), Some(m)) = (&n.kind, Document::color_mask_of(n)) else { continue };
let mask = match fresh(&st.doc, n, APPLY_COLOR_MASK) {
Some(Ok(fresh)) => fresh,
Some(Err(e)) => return Err(e),
None => (m.clone(), None),
};
if mask.0.key == im.key {
made.push((*id, None));
continue;
}
let shown = st.doc.images.get(&mask.0.key).or(mask.1.as_ref());
if refused_colorize(&st.doc, n, shown) {
return Err(bad(APPLY_COLOR_MASK, PROCESS_ON_TRANSPARENCY));
}
let size = mask_size(shown, im.width, im.height);
made.push((*id, Some((mask, size))));
}
}
if !made.is_empty() {
s.edit("Apply Color Mask", |d, _| {
for (id, applied) in made {
let Some(n) = d.node_mut(id) else { continue };
n.extras_mut().color_mask = None;
let Some(((mask, blob), (w, h))) = applied else { continue };
if let Some(blob) = blob {
d.images.entry(mask.key.clone()).or_insert(blob);
}
let Some(n) = d.node_mut(id) else { continue };
if let NodeKind::Image(im) = &mut n.kind {
// Masked pixels of another size than the object's keep its place and size.
if (w, h) != (im.width, im.height) {
im.xf *= Affine::scale_non_uniform(f64::from(im.width) / f64::from(w), f64::from(im.height) / f64::from(h));
(im.width, im.height) = (w, h);
}
im.key = mask.key;
im.link = None;
}
}
Ok(())
})?;
}
Ok(json!({ "changed": ids.len(), "ids": ids.iter().map(|id| id.0).collect::<Vec<_>>() }))
}
/// The size in pixels of masked pixels `blob` (from its header), or the object's when it can't be
/// read.
fn mask_size(blob: Option<&ImageBlob>, width: u32, height: u32) -> (u32, u32) {
blob.and_then(|b| image::ImageReader::new(std::io::Cursor::new(b.bytes.as_slice())).with_guessed_format().ok()?.into_dimensions().ok())
.filter(|(w, h)| *w > 0 && *h > 0)
.unwrap_or((width, height))
}
/// The mask of image node `n` made again for the image's own pixels, with the masked pixels when
/// `doc` doesn't have them: `None` when the mask is up to date (or `n` has none), an error when the
/// pixels can't be masked (missing, CMYK, a linked preview, too large, every pixel hidden, or
/// settings a file gave out of range).
fn fresh(doc: &Document, n: &Node, cmd: &str) -> Option<Result<(ColorMask, Option<ImageBlob>)>> {
let (NodeKind::Image(im), Some(m)) = (&n.kind, Document::color_mask_of(n)) else { return None };
if !stale_mask(doc, n) {
return None;
}
let made = || -> Result<(ColorMask, Option<ImageBlob>)> {
let settings = Settings::of(m).ok_or_else(|| bad(cmd, "the color mask's settings are out of range"))?;
let blob = doc.images.get(&im.key).ok_or_else(|| bad(cmd, "the image's pixels are missing"))?;
if im.link.is_some() && blob.is_proxy() {
return Err(bad(cmd, "the linked image shows its preview: embed or relink it first"));
}
Ok(match masked(blob, &settings, None, cmd)? {
Some((key, blob, _)) => {
let blob = (!doc.images.contains_key(&key)).then_some(blob);
(settings.mask(key, im.key.clone()), blob)
}
None => (settings.mask(im.key.clone(), im.key.clone()), None),
})
};
Some(made())
}
/// After an edit from `before` (`None`: everything is new, as after a document's links are read):
/// the color masks of images in `doc`'s art ([`Document::art_roots`]: layers, symbols, graph
/// designs, patterns and the original of the pattern being edited, opacity mask art included)
/// whose own pixels were replaced are made again for the new pixels ([`Refresh::made`]). Only the
/// art that changed since `before` is looked at.
pub(crate) fn refresh(before: Option<&Document>, doc: &mut Document) {
let old: Vec<&Arc<Node>> = before.map(|b| b.art_roots().collect()).unwrap_or_default();
let mut pass = Refresh { doc: &*doc, made: HashMap::new(), blobs: vec![] };
let mut fixed = vec![];
for (i, root) in doc.art_roots().enumerate() {
let counterpart = old.get(i).copied().filter(|o| o.id == root.id);
if stale_in(doc, root, counterpart) {
let mut root = root.clone();
pass.fix(Arc::make_mut(&mut root));
fixed.push((i, root));
}
}
let blobs = pass.blobs;
if fixed.is_empty() {
return;
}
for (key, blob) in blobs {
doc.images.entry(key).or_insert(blob);
}
let mut fixed = fixed.into_iter().peekable();
for (i, root) in doc.art_roots_mut().enumerate() {
if fixed.peek().is_some_and(|(at, _)| *at == i)
&& let Some((_, new)) = fixed.next()
{
*root = new;
}
}
}
/// Whether `n`, or anything in it (opacity-mask art included), is an image whose mask is out of
/// date ([`stale_mask`]). What is the same as in `old`, `n`'s counterpart before an edit, is not
/// looked at.
fn stale_in(doc: &Document, n: &Arc<Node>, old: Option<&Arc<Node>>) -> bool {
if old.is_some_and(|o| Arc::ptr_eq(o, n)) {
return false;
}
if stale_mask(doc, n) {
return true;
}
let old_mask = old.and_then(|o| o.extras().mask.as_ref()).map(|m| &m.art);
if n.extras().mask.as_ref().is_some_and(|m| stale_in(doc, &m.art, old_mask)) {
return true;
}
let Some(children) = n.children() else { return false };
let before = old.and_then(|o| o.children()).map_or(&[][..], Vec::as_slice);
let mut by_id: Option<HashMap<NodeId, &Arc<Node>>> = None;
children.iter().enumerate().any(|(i, c)| {
let b = match before.get(i) {
Some(b) if b.id == c.id => Some(b),
_ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&c.id).copied(),
};
stale_in(doc, c, b)
})
}
/// Whether `n` is an image whose color mask was not made from its own pixels (or whose masked
/// pixels `doc` doesn't have). A mask that hides nothing (its masked pixels are the image's own)
/// is up to date while the image's key stays the same, even when its pixels are missing.
fn stale_mask(doc: &Document, n: &Node) -> bool {
matches!((&n.kind, Document::color_mask_of(n)), (NodeKind::Image(im), Some(m))
if im.pixels.is_none() && !(m.made_for(im) && (m.key == im.key || doc.images.contains_key(&m.key))))
}
/// One [`refresh`] pass: the masks made so far, by the image's pixels, the mask's settings and
/// whether a process color colorizes the image (an image shown by many objects is decoded once),
/// and the masked pixels to add to the document.
struct Refresh<'a> {
doc: &'a Document,
made: HashMap<(String, String, bool), ColorMask>,
blobs: Vec<(String, ImageBlob)>,
}
impl Refresh<'_> {
/// Make the masks out of date in `n` (a copy of the document's art) again.
fn fix(&mut self, n: &mut Node) {
if let Some(mask) = self.made(n) {
n.extras_mut().color_mask = Some(Box::new(mask));
}
if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut())
&& stale_in(self.doc, &m.art, None)
{
self.fix(Arc::make_mut(&mut m.art));
}
for c in n.children_mut().into_iter().flatten() {
if stale_in(self.doc, c, None) {
self.fix(Arc::make_mut(c));
}
}
}
/// The mask of image node `n` made again for the image's own pixels ([`fresh`]), `None` when
/// it is up to date. A mask that can't be made for them (every pixel hidden, CMYK pixels, a
/// linked preview, too large, gray pixels with transparency under a process color) keeps its
/// settings and hides nothing: the image shows its own pixels, and setting the mask again
/// reports why.
fn made(&mut self, n: &Node) -> Option<ColorMask> {
let (NodeKind::Image(im), Some(m)) = (&n.kind, Document::color_mask_of(n)) else { return None };
if !stale_mask(self.doc, n) {
return None;
}
let settings = ColorMask { key: String::new(), from: String::new(), ..m.clone() };
let at = (im.key.clone(), format!("{settings:?}"), colorized_with_process(self.doc, n));
if let Some(made) = self.made.get(&at) {
return Some(made.clone());
}
let hides_nothing = || ColorMask { key: im.key.clone(), from: im.key.clone(), ..m.clone() };
let mask = match fresh(self.doc, n, COLOR_MASK)? {
Ok((mask, blob)) if refused_colorize(self.doc, n, blob.as_ref().or_else(|| self.doc.images.get(&mask.key))) => hides_nothing(),
Ok((mask, blob)) => {
self.blobs.extend(blob.map(|b| (mask.key.clone(), b)));
mask
}
Err(_) => hides_nothing(),
};
self.made.insert(at, mask.clone());
Some(mask)
}
}
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -392,7 +392,7 @@ fn the_color_profile_is_kept() {
encoder.set_icc_profile(icc.clone()).unwrap();
DynamicImage::ImageRgba8(framed()).write_with_encoder(encoder).unwrap();
let blob = ImageBlob::png(bytes);
let out = super::clear(&blob, &settings(Background::Edges), None).unwrap().unwrap();
let out = super::clear(&blob, &settings(Background::Edges), None, super::C).unwrap().unwrap();
let mut decoder = image::codecs::png::PngDecoder::new(Cursor::new(out.blob.bytes.as_slice())).unwrap();
assert_eq!(decoder.icc_profile().unwrap(), Some(icc));
}
+19 -6
View File
@@ -2,8 +2,8 @@
//! the Extend Path tool's extension, the Measure & Inspect tool's readouts, the Anchor Inspector's
//! anchor edits, Split / Add Points at Crossings, Slide Anchor Along Path, the Corner Tool's corners
//! ([`corners`]), the Parametric Shape Tool's shapes ([`shape`]), the Shared Edge Merge Tool's
//! merges with Keep Shared Points Together ([`shared_edge`]), Divide into Dashes and Expand Dashes
//! into Paths.
//! merges with Keep Shared Points Together ([`shared_edge`]), Divide into Dashes, Expand Dashes
//! into Paths and Trim at Crossings ([`trim`]).
//! Its tools, panels and submenu (Object › Plug-ins › Path Precision Tools) are the tools crate's
//! and the UI's.
@@ -14,6 +14,7 @@ mod shape;
mod shared_edge;
#[cfg(test)]
mod tests;
mod trim;
use std::collections::{BTreeMap, BTreeSet};
@@ -143,7 +144,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add Points at Crossings",
["Object", "Plug-ins", "Path Precision Tools"],
None,
"{cut?: bool (false: add anchors where the paths cross; true: also cut them there), selfCrossings?: bool (false: where a path crosses itself too), ids?: [id…] (default: the selection)} where the paths under the objects cross one another, as one undo step; at most 10000 segments → {ids, crossings (anchors placed)}",
"{cut?: bool (false: add anchors where the paths cross; true: also cut them there), selfCrossings?: bool (false: where a path crosses itself too, a curved segment that loops over itself included), ids?: [id…] (default: the selection)} where the paths under the objects cross one another, as one undo step; at most 10000 segments → {ids, crossings (anchors placed)}",
has_selection,
crossings
),
@@ -178,6 +179,7 @@ pub fn specs() -> Vec<CommandSpec> {
v.extend(shape::specs());
v.extend(corners::specs());
v.extend(shared_edge::specs());
v.extend(trim::specs());
v
}
@@ -609,7 +611,7 @@ fn remove_keep_shape(s: &mut Session, _: &Value) -> Result<Value> {
fn picked_segments(segments: Option<&BTreeSet<(usize, usize)>>, si: usize, sp: &SubPath, anchors: &BTreeSet<usize>) -> BTreeSet<usize> {
let n = sp.anchors.len().max(1);
match segments.filter(|set| !set.is_empty()) {
Some(set) => set.iter().filter(|(s, _)| *s == si).map(|(_, k)| *k).collect(),
Some(set) => super::super::path::subpath_refs(set, si).collect(),
None => (0..sp.segment_count()).filter(|k| anchors.contains(k) && anchors.contains(&((k + 1) % n))).collect(),
}
}
@@ -681,6 +683,18 @@ pub(super) fn close(s: &mut Session, p: &Value) -> Result<Value> {
// ---------- Split / Add Points at Crossings ----------
/// The crossing places `on` of one path, as `(segment, t)` for each of its `subpaths` subpaths in
/// the order they come in `on`. A place on a subpath past the last is left out.
fn places_by_subpath(on: &[(usize, usize, f64)], subpaths: usize) -> Vec<Vec<(usize, f64)>> {
let mut by_sub = vec![vec![]; subpaths];
for &(si, seg, t) in on {
if let Some(here) = by_sub.get_mut(si) {
here.push((seg, t));
}
}
by_sub
}
fn crossings(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "addon.pathtools.crossings";
let (cut, self_crossings) = (switch_or(p, "cut", false, C)?, switch_or(p, "selfCrossings", false, C)?);
@@ -702,8 +716,7 @@ fn crossings(s: &mut Session, p: &Value) -> Result<Value> {
}
let mut subs = vec![];
let mut marks = vec![];
for (si, sp) in path.subpaths.iter().enumerate() {
let here: Vec<(usize, f64)> = on.iter().filter(|(s, ..)| *s == si).map(|&(_, seg, t)| (seg, t)).collect();
for (sp, here) in path.subpaths.iter().zip(places_by_subpath(&on, path.subpaths.len())) {
let (out, m) = pt::insert_at(sp, &here);
count += m.len();
subs.push(out);
+241 -1
View File
@@ -6,7 +6,7 @@ use std::collections::BTreeSet;
use serde_json::{Value, json};
use vectorcraft_doc::{LiveCorners, LiveShape, NodeId};
use vectorcraft_geom::shapes::CornerKind;
use vectorcraft_geom::{AnchorKind, PathData, Point};
use vectorcraft_geom::{AnchorKind, PathData, Point, SubPath};
use vectorcraft_tools::{PointerEvent, PointerKind};
use crate::{Session, ViewInfo};
@@ -275,6 +275,152 @@ fn crossings_add_anchors_or_cut_in_one_step() {
refuses(&mut s, "addon.pathtools.crossings", &[json!({"cut": "yes"}), json!({"ids": [123456]})]);
}
/// A selected path with an open polyline subpath through each of `subs`; an empty list makes an
/// empty subpath.
fn compound(s: &mut Session, subs: &[&[(f64, f64)]]) -> NodeId {
let id = line(s, &[(0.0, 0.0), (1.0, 0.0)], false);
let pd =
PathData::new(subs.iter().map(|pts| SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::<Vec<_>>(), false)).collect());
s.edit("Test", |d, _| {
super::set_path(d, id, pd);
Ok(())
})
.unwrap();
select(s, &[id]);
id
}
/// The anchor points of each subpath of `pd`, rounded to a millionth.
fn points(pd: &PathData) -> Vec<Vec<(f64, f64)>> {
let r = |v: f64| (v * 1e6).round() / 1e6;
pd.subpaths.iter().map(|sp| sp.anchors.iter().map(|a| (r(a.p.x), r(a.p.y))).collect()).collect()
}
/// A path's subpaths: A (0), an empty one (1), C (2) and D (3, the last).
const SUBS: [&[(f64, f64)]; 4] =
[&[(0.0, 0.0), (100.0, 0.0), (200.0, 0.0)], &[], &[(0.0, 50.0), (100.0, 50.0)], &[(0.0, 100.0), (100.0, 100.0), (200.0, 100.0)]];
/// Direct-select `segments` of `id` and the anchors `anchors`.
fn select_segments(s: &mut Session, id: NodeId, anchors: &[(usize, usize)], segments: &[(usize, usize)]) {
s.select(|_, sel| {
sel.set([id]);
sel.anchors.insert(id, anchors.iter().copied().collect());
sel.segments.insert(id, segments.iter().copied().collect());
})
.unwrap();
}
#[test]
fn picked_segments_reads_only_its_own_subpath() {
let set: BTreeSet<(usize, usize)> = [(0, 0), (0, 2), (1, 1), (3, 0), (3, 1)].into();
let sp = SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(1.0, 0.0), Point::new(2.0, 0.0), Point::new(3.0, 0.0)], false);
let all: BTreeSet<usize> = (0..4).collect();
let picked = |si| super::picked_segments(Some(&set), si, &sp, &all).into_iter().collect::<Vec<_>>();
assert_eq!([picked(0), picked(1), picked(2), picked(3), picked(4)], [vec![0, 2], vec![1], vec![], vec![0, 1], vec![]]);
// Without direct-selected segments, the segments between two selected anchors.
let anchors: BTreeSet<usize> = [0, 1, 3].into();
for none in [None, Some(&BTreeSet::new())] {
assert_eq!(super::picked_segments(none, 0, &sp, &anchors).into_iter().collect::<Vec<_>>(), [0]);
}
}
#[test]
fn places_by_subpath_keeps_the_order_and_leaves_out_missing_subpaths() {
let on = [(3, 1, 0.75), (0, 0, 0.5), (3, 1, 0.25), (7, 0, 0.5), (0, 1, 0.1), (3, 0, 0.5), (0, 0, 0.2)];
let by_sub = super::places_by_subpath(&on, 4);
assert_eq!(by_sub, [vec![(0, 0.5), (1, 0.1), (0, 0.2)], vec![], vec![], vec![(1, 0.75), (1, 0.25), (0, 0.5)]]);
// The same places as filtering the whole list for each subpath.
for (si, here) in by_sub.iter().enumerate() {
let filtered: Vec<(usize, f64)> = on.iter().filter(|(s, ..)| *s == si).map(|&(_, seg, t)| (seg, t)).collect();
assert_eq!(*here, filtered);
}
assert!(super::places_by_subpath(&on, 0).is_empty());
}
#[test]
fn add_points_adds_to_the_selected_segments_of_each_subpath() {
let mut s = session();
let c = compound(&mut s, &SUBS);
let before = path(&s, c);
// The first segment of A and the second of D; a segment of C without its anchors selected.
select_segments(&mut s, c, &[(0, 0), (0, 1), (0, 2), (3, 0), (3, 1), (3, 2)], &[(0, 0), (2, 0), (3, 1)]);
let n = steps(&s);
assert_eq!(s.execute("addon.pathtools.addPoints", &json!({})).unwrap()["added"], json!(2));
let want = vec![
vec![(0.0, 0.0), (50.0, 0.0), (100.0, 0.0), (200.0, 0.0)],
vec![],
vec![(0.0, 50.0), (100.0, 50.0)],
vec![(0.0, 100.0), (100.0, 100.0), (150.0, 100.0), (200.0, 100.0)],
];
let after = path(&s, c);
assert_eq!(points(&after), want);
assert_eq!(steps(&s), n + 1);
let st = s.doc().unwrap();
assert_eq!((st.selection.objects.clone(), st.selection.anchors.get(&c), st.selection.segments.get(&c)), (vec![c], None, None));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(path(&s, c), before);
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(path(&s, c), after);
// Without selected segments: those between two selected anchors, here on the last subpath only.
for segments in [None, Some(BTreeSet::new())] {
s.execute("edit.undo", &json!({})).unwrap();
s.select(|_, sel| {
sel.set([c]);
sel.anchors.insert(c, [(0, 0), (3, 1), (3, 2)].into());
sel.segments.remove(&c);
if let Some(set) = segments.clone() {
sel.segments.insert(c, set);
}
})
.unwrap();
assert_eq!(s.execute("addon.pathtools.addPoints", &json!({})).unwrap()["added"], json!(1));
assert_eq!(
points(&path(&s, c)),
[points(&before)[..3].to_vec(), vec![vec![(0.0, 100.0), (100.0, 100.0), (150.0, 100.0), (200.0, 100.0)]]].concat()
);
}
}
#[test]
fn crossings_add_anchors_on_each_subpath_of_a_compound_path() {
let mut s = session();
// A and the last subpath cross both lines; the empty subpath and C, which ends short of them, do not.
let c = compound(&mut s, &[&[(0.0, 50.0), (200.0, 50.0)], &[], &[(0.0, 150.0), (40.0, 150.0)], &[(0.0, 250.0), (400.0, 250.0)]]);
let q = line(&mut s, &[(100.0, 0.0), (100.0, 300.0)], false);
let r = line(&mut s, &[(150.0, 0.0), (150.0, 300.0)], false);
select(&mut s, &[c, q, r]);
let n = steps(&s);
assert_eq!(s.execute("addon.pathtools.crossings", &json!({})).unwrap()["crossings"], json!(8));
let want = vec![
vec![(0.0, 50.0), (100.0, 50.0), (150.0, 50.0), (200.0, 50.0)],
vec![],
vec![(0.0, 150.0), (40.0, 150.0)],
vec![(0.0, 250.0), (100.0, 250.0), (150.0, 250.0), (400.0, 250.0)],
];
assert_eq!(points(&path(&s, c)), want);
assert_eq!(points(&path(&s, q)), [vec![(100.0, 0.0), (100.0, 50.0), (100.0, 250.0), (100.0, 300.0)]]);
assert_eq!(steps(&s), n + 1);
s.execute("edit.undo", &json!({})).unwrap();
// Cut: the compound path keeps its pieces as subpaths, in order; each line becomes three paths.
let out = ids(&s.execute("addon.pathtools.crossings", &json!({"cut": true})).unwrap());
assert_eq!(out.len(), 7);
assert_eq!(out[0], c);
let pieces = vec![
vec![(0.0, 50.0), (100.0, 50.0)],
vec![(100.0, 50.0), (150.0, 50.0)],
vec![(150.0, 50.0), (200.0, 50.0)],
vec![],
vec![(0.0, 150.0), (40.0, 150.0)],
vec![(0.0, 250.0), (100.0, 250.0)],
vec![(100.0, 250.0), (150.0, 250.0)],
vec![(150.0, 250.0), (400.0, 250.0)],
];
assert_eq!(points(&path(&s, c)), pieces);
let qs: Vec<Vec<Vec<(f64, f64)>>> = out[1..4].iter().map(|id| points(&path(&s, *id))).collect();
assert_eq!(qs, [[vec![(100.0, 0.0), (100.0, 50.0)]], [vec![(100.0, 50.0), (100.0, 250.0)]], [vec![(100.0, 250.0), (100.0, 300.0)]]]);
assert_eq!(steps(&s), n + 1);
}
// ---------- Parametric Shape Tool ----------
/// The parametric shape object `id` is now, as the tool reads it.
@@ -567,6 +713,71 @@ fn corner_commands_refuse_bad_params() {
}
}
#[test]
fn corner_commands_refuse_an_unknown_item_key() {
let mut s = session();
let id = square(&mut s);
let i = id.0;
let set = json!({"items": [{"id": i, "anchor": [0]}], "radius": 5});
let e = s.execute("addon.pathtools.cornerSet", &set).unwrap_err().to_string();
assert!(e.contains("unknown parameter `items[0].anchor`; did you mean `items[0].anchors`?"), "{e}");
let set_late = json!({"items": [{"id": i, "anchors": [0]}, {"id": i, "radius": 3}], "radius": 5});
let e = s.execute("addon.pathtools.cornerSet", &set_late).unwrap_err().to_string();
assert!(e.contains("unknown parameter `items[1].radius`; the command takes: items[1].id, items[1].anchors"), "{e}");
refuses(&mut s, "addon.pathtools.cornerSet", &[set, set_late]);
s.execute("addon.pathtools.cornerSet", &json!({"radius": 10})).unwrap();
let remove = json!({"items": [{"id": i, "anchor": [0]}]});
let e = s.execute("addon.pathtools.cornerRemove", &remove).unwrap_err().to_string();
assert!(e.contains("unknown parameter `items[0].anchor`; did you mean `items[0].anchors`?"), "{e}");
refuses(&mut s, "addon.pathtools.cornerRemove", &[remove]);
assert_eq!(drawn(&s, id, 0), 10.0);
}
#[test]
fn corner_items_take_their_documented_keys() {
let mut s = session();
let id = square(&mut s);
let i = id.0;
let r = s.execute("addon.pathtools.cornerSet", &json!({"items": [{"id": i, "anchors": [0]}], "radius": 5})).unwrap();
assert_eq!((r["corners"].clone(), drawn(&s, id, 0), drawn(&s, id, 1)), (json!(1), 5.0, 0.0));
// A member without `anchors` takes the request's.
s.execute("addon.pathtools.cornerSet", &json!({"items": [{"id": i}], "anchors": [2], "radius": 6})).unwrap();
assert_eq!(drawn(&s, id, 2), 6.0);
let r = s.execute("addon.pathtools.cornerRemove", &json!({"items": [{"id": i, "anchors": [0]}]})).unwrap();
assert_eq!((r["corners"].clone(), drawn(&s, id, 0), drawn(&s, id, 2)), (json!(1), 0.0, 6.0));
// A null `ids` beside `items` counts as not given.
s.execute("addon.pathtools.cornerRemove", &json!({"items": [{"id": i}], "ids": null})).unwrap();
assert_eq!(drawn(&s, id, 2), 0.0);
}
#[test]
fn corner_commands_refuse_items_with_ids() {
let mut s = session();
let id = square(&mut s);
let other = line(&mut s, &[(350.0, 10.0), (390.0, 10.0), (390.0, 50.0)], false);
let both = json!({"items": [{"id": id.0, "anchors": [0]}], "ids": [other.0], "radius": 5});
let e = s.execute("addon.pathtools.cornerSet", &both).unwrap_err().to_string();
assert!(e.contains("give `items` or `ids`, not both"), "{e}");
refuses(&mut s, "addon.pathtools.cornerSet", &[both]);
s.execute("addon.pathtools.cornerSet", &json!({"ids": [id.0], "radius": 5})).unwrap();
let both = json!({"items": [{"id": id.0}], "ids": [id.0]});
let e = s.execute("addon.pathtools.cornerRemove", &both).unwrap_err().to_string();
assert!(e.contains("give `items` or `ids`, not both"), "{e}");
refuses(&mut s, "addon.pathtools.cornerRemove", &[both]);
}
#[test]
fn saved_corner_steps_with_older_item_keys_still_play() {
let mut s = session();
let id = square(&mut s);
let other = line(&mut s, &[(350.0, 10.0), (390.0, 10.0), (390.0, 50.0)], false);
let saved = json!({"items": [{"id": id.0, "anchors": [0], "old": 1}], "ids": [other.0], "radius": 5});
s.replay("addon.pathtools.cornerSet", &saved).unwrap();
assert_eq!((drawn(&s, id, 0), drawn(&s, id, 1)), (5.0, 0.0));
s.replay("addon.pathtools.cornerRemove", &json!({"items": [{"id": id.0, "old": 1}]})).unwrap();
assert_eq!(drawn(&s, id, 0), 0.0);
}
/// A closed five-pointed star about (200, 150): its points at the even indices 0, 2… (the odd
/// numbers counting from 1), its inner corners at the odd ones.
fn star_path(s: &mut Session) -> NodeId {
@@ -887,6 +1098,35 @@ fn divide_into_dashes_divides_only_the_selected_segments() {
assert_eq!(layer, pieces, "in the path's place, in order");
}
#[test]
fn divide_into_dashes_divides_the_selected_segments_of_each_subpath() {
let mut s = session();
let c = compound(&mut s, &SUBS);
let before = path(&s, c);
// The first segment of A and the second of D; a segment of C without its anchors selected.
select_segments(&mut s, c, &[(0, 0), (0, 1), (0, 2), (3, 0), (3, 1), (3, 2)], &[(0, 0), (2, 0), (3, 1)]);
let n = steps(&s);
let r = s.execute("addon.pathtools.divideDashes", &json!({"dash": 25})).unwrap();
assert_eq!(steps(&s), n + 1);
assert_eq!(r["dashes"], json!(8));
let made: Vec<Vec<Vec<(f64, f64)>>> = ids(&r).iter().map(|id| points(&path(&s, *id))).collect();
let piece = |x0: f64, x1: f64, y: f64| vec![vec![(x0, y), (x1, y)]];
let mut want = vec![vec![vec![], vec![(0.0, 50.0), (100.0, 50.0)]]];
want.extend([(0.0, 25.0), (25.0, 50.0), (50.0, 75.0), (75.0, 100.0)].map(|(a, b)| piece(a, b, 0.0)));
want.push(vec![vec![(100.0, 0.0), (200.0, 0.0)]]);
want.push(vec![vec![(0.0, 100.0), (100.0, 100.0)]]);
want.extend([(100.0, 125.0), (125.0, 150.0), (150.0, 175.0), (175.0, 200.0)].map(|(a, b)| piece(a, b, 100.0)));
assert_eq!(made, want, "what stays of the path, then each subpath's pieces in order");
assert_eq!(s.doc().unwrap().selection.objects, ids(&r));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(path(&s, c), before);
// With no segments selected: those between two selected anchors, here on the last subpath only.
select_segments(&mut s, c, &[(0, 0), (3, 1), (3, 2)], &[]);
let r = s.execute("addon.pathtools.divideDashes", &json!({"dash": 25})).unwrap();
assert_eq!((ids(&r).len(), r["dashes"].clone()), (6, json!(4)));
assert_eq!(points(&path(&s, ids(&r)[0])), points(&before)[..3]);
}
#[test]
fn divide_into_dashes_refuses_bad_params_and_too_many_pieces() {
let mut s = session();
@@ -0,0 +1,321 @@
//! Trim at Crossings: remove the stretch of a path between the places where other paths, or the
//! path itself, cross it. The command takes the stretch at a point, every stretch a rectangle
//! touches, or every stretch a line through some points crosses. It works on every path that can
//! be edited, selected or not.
use std::collections::HashSet;
use serde_json::{Value, json};
use vectorcraft_doc::{Document, NodeId, NodeKind};
use vectorcraft_geom::kurbo::{Line, PathSeg};
use vectorcraft_geom::{PathData, Point, Rect, SubPath, hit};
use vectorcraft_pathops::addons::pathtools as pt;
use super::super::super::draw2::replace_with_pieces;
use super::super::super::pathops::Beside;
use super::super::super::{CommandSpec, bad, cmd, finite_numbers, has_doc, number_or};
use crate::{Result, Session};
#[cfg(test)]
mod tests;
/// The undo step's name.
const LABEL: &str = "Trim at Crossings";
/// How near `at` a path counts as under it by default (pt), and the most.
const TOLERANCE: f64 = 3.0;
const MAX_TOLERANCE: f64 = 100.0;
/// Most points of `points`.
const MAX_POINTS: usize = 100_000;
/// The farthest coordinate the command takes.
const MAX_COORD: f64 = 1e7;
pub(super) fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"addon.pathtools.trim",
"Trim at Crossings",
[],
None,
"{at: [x, y], tolerance?: pt 0..100 (3; how near `at` a path counts as under it)} or {rect: [x, y, width, height]} or {points: [[x, y]…] (2 to 100000 points)} remove stretches of paths, a stretch running between two neighboring places where the path is crossed by another path or by itself, or from such a place to an open end: `at` removes the stretch of the nearest path at that point, `rect` every stretch the rectangle touches, `points` every stretch the line through the points crosses. Give exactly one of the three. Every path that can be edited takes part, selected or not, compound path members included; hidden and locked paths, guides and clipping paths (compound ones' members included) are neither trimmed nor counted as crossing; in isolation mode only paths inside the isolated object are trimmed. A path that ends on another marks a place on the other; paths that lie along each other don't cross. A closed path that loses a stretch becomes open, an open path that loses a middle stretch becomes two paths with its appearance in its place in the stacking order, and a path nothing crosses is removed whole; a live shape becomes a plain path. One undo step, none when nothing is removed → {ids (the paths left of those trimmed), removed (stretches)}",
has_doc,
trim
)]
}
/// What picks the stretches to remove.
enum Pick {
/// The stretch of the nearest path within the tolerance of the point.
At(Point, f64),
/// Every stretch the rectangle touches.
Rect(Rect),
/// Every stretch the line through the points crosses.
Line(Vec<Point>, Rect),
}
fn pick(p: &Value) -> Result<Pick> {
const C: &str = "addon.pathtools.trim";
let given = |key: &str| p.get(key).filter(|v| !v.is_null());
let within = |v: &[f64]| v.iter().all(|x| x.abs() <= MAX_COORD);
match (given("at"), given("rect"), given("points")) {
(Some(at), None, None) => {
let [x, y] = finite_numbers(at).filter(|v| within(v)).ok_or_else(|| bad(C, "`at` must be a point [x, y]"))?;
let tolerance = number_or(p, "tolerance", TOLERANCE, C)?;
if !(0.0..=MAX_TOLERANCE).contains(&tolerance) {
return Err(bad(C, "`tolerance` must be from 0 to 100 pt"));
}
Ok(Pick::At(Point::new(x, y), tolerance))
}
(None, Some(rect), None) => {
let [x, y, w, h] = finite_numbers(rect).filter(|v| within(v)).ok_or_else(|| bad(C, "`rect` must be [x, y, width, height]"))?;
Ok(Pick::Rect(Rect::new(x, y, x + w, y + h).abs()))
}
(None, None, Some(points)) => {
let list = points.as_array().ok_or_else(|| bad(C, "`points` must be a list of [x, y] points"))?;
if !(2..=MAX_POINTS).contains(&list.len()) {
return Err(bad(C, "`points` must hold from 2 to 100000 points"));
}
let pts = list
.iter()
.map(|v| {
finite_numbers(v)
.filter(|xy| within(xy))
.map(|[x, y]| Point::new(x, y))
.ok_or_else(|| bad(C, format!("bad point {v}: expected [x, y]")))
})
.collect::<Result<Vec<Point>>>()?;
let bounds = pts.iter().fold(None, |r: Option<Rect>, q| Some(r.map_or(Rect::from_points(*q, *q), |r| r.union_pt(*q))));
Ok(Pick::Line(pts, bounds.unwrap_or_default()))
}
_ => Err(bad(C, "give exactly one of `at`, `rect` and `points`")),
}
}
/// A path that takes part: its id, geometry and control-point box.
type Part<'a> = (NodeId, &'a PathData, Rect);
/// The paths that take part, bottom to top: the ones that can be edited, without guides and
/// clipping paths. The clipping path of a clip group or a clipped layer is left out whole, the
/// members of a compound clipping path included.
fn parts(d: &Document) -> Vec<Part<'_>> {
let editable = d.editable();
let mut masks = HashSet::new();
d.walk(|n| {
if n.clips()
&& let Some(first) = n.children().and_then(|c| c.first())
{
first.walk(&mut |m| {
masks.insert(m.id);
});
}
});
let mut out = vec![];
d.walk(|n| {
if let NodeKind::Path { path, guide: false, clipping: false, .. } = &n.kind
&& !masks.contains(&n.id)
&& let Some(b) = path.control_bounds()
&& editable(n.id)
{
out.push((n.id, path, b));
}
});
out
}
/// Most box tests one command makes between a line's pieces and the paths' segments.
const MAX_LINE_TESTS: usize = 60_000_000;
/// Most tests one command makes between the boxes of the paths to trim and of the other paths.
const MAX_BOX_TESTS: usize = 50_000_000;
/// Does the line through `pts` cross `sp`? Each piece of the line compared costs one of `budget`;
/// `None` once it is spent.
fn crossed_by_line(sp: &SubPath, pts: &[Point], budget: &mut usize) -> Option<bool> {
let segs: Vec<_> = (0..sp.segment_count())
.map(|i| {
let c = sp.segment(i);
(c, Rect::from_points(c.p0, c.p1).union_pt(c.p2).union_pt(c.p3).inflate(1e-9, 1e-9))
})
.collect();
let Some(reach) = segs.iter().map(|s| s.1).reduce(|a, b| a.union(b)) else { return Some(false) };
for w in pts.windows(2) {
let [a, b] = w else { continue };
let piece = Rect::from_points(*a, *b);
*budget = budget.checked_sub(1)?;
if !reach.overlaps(piece) {
continue;
}
for (c, r) in &segs {
*budget = budget.checked_sub(1)?;
if r.overlaps(piece) && !PathSeg::Cubic(*c).intersect_line(Line::new(*a, *b)).is_empty() {
return Some(true);
}
}
}
Some(false)
}
/// Does the rectangle or line of `pick` touch the outline of `piece`? Never for `Pick::At`.
fn touches(piece: &SubPath, pick: &Pick, budget: &mut usize) -> Result<bool> {
match pick {
Pick::At(..) => Ok(false),
Pick::Rect(r) => Ok(hit::intersects_rect(&PathData::single(piece.clone()), *r)),
Pick::Line(pts, _) => crossed_by_line(piece, pts, budget)
.ok_or_else(|| bad("addon.pathtools.trim", "the line is too long, or the paths it passes too many, to check")),
}
}
/// `path` without the stretches `pick` takes (`on`: the place of `Pick::At` on it): its subpaths
/// then, and how many stretches went. `None` when none does. A rectangle or a line that touches no
/// part of `path` leaves it out before its crossings are looked for.
fn trimmed(
path: &PathData,
others: &[&PathData],
pick: &Pick,
on: Option<pt::Place>,
budget: &mut usize,
work: &mut pt::Work,
) -> Result<Option<(Vec<SubPath>, usize)>> {
const C: &str = "addon.pathtools.trim";
let reached = match pick {
Pick::At(..) => true,
Pick::Rect(r) => hit::intersects_rect(path, *r),
Pick::Line(..) => {
let mut any = false;
for sp in &path.subpaths {
if touches(sp, pick, budget)? {
any = true;
break;
}
}
any
}
};
if !reached {
return Ok(None);
}
let places =
pt::crossings_on_within(path, others, work).ok_or_else(|| bad(C, "the paths are too many or too tangled to find where they cross"))?;
let mut subs = vec![];
let mut removed = 0;
for (si, sp) in path.subpaths.iter().enumerate() {
// The places come in subpath order: this subpath's are one run of them.
let run = places.partition_point(|p| p.0 < si)..places.partition_point(|p| p.0 <= si);
let here: Vec<(usize, f64)> = places.get(run).unwrap_or_default().iter().map(|&(_, seg, t)| (seg, t)).collect();
let spans = pt::spans(sp, &here);
let marks: Vec<bool> = match pick {
Pick::At(..) => {
let at = on.filter(|(s, ..)| *s == si).and_then(|(_, seg, t)| pt::span_at(sp, &spans, seg, t));
(0..spans.len()).map(|i| Some(i) == at).collect()
}
_ => spans.iter().map(|s| touches(&pt::slice(sp, *s), pick, budget)).collect::<Result<_>>()?,
};
match pt::without_spans(sp, &spans, &marks) {
Some(pieces) => {
removed += marks.iter().filter(|m| **m).count();
subs.extend(pieces);
}
None => subs.push(sp.clone()),
}
}
Ok((removed > 0).then_some((subs, removed)))
}
fn trim(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "addon.pathtools.trim";
let pick = pick(p)?;
let st = s.doc()?;
let d = &st.doc;
let parts = parts(d);
// In isolation mode only the isolated object's paths are trimmed; paths outside it still cross them.
let root = crate::cmd::ordinary_isolation(st);
let in_scope = |id: NodeId| root.is_none_or(|r| id == r || crate::cmd::inside_isolation(d, r, id));
// The paths to trim, each with the place `at` falls on.
let targets: Vec<(usize, Option<pt::Place>)> = match &pick {
Pick::At(at, tolerance) => {
let mut best: Option<(usize, pt::Place, f64)> = None;
for (i, (id, path, b)) in parts.iter().enumerate() {
if !in_scope(*id) {
continue;
}
let b = b.inflate(*tolerance, *tolerance);
if !(b.x0 <= at.x && at.x <= b.x1 && b.y0 <= at.y && at.y <= b.y1) {
continue;
}
// Of paths equally near, the one on top.
if let Some((si, seg, t, _, dist)) = path.nearest(*at)
&& dist <= *tolerance
&& best.is_none_or(|b| dist <= b.2)
{
best = Some((i, (si, seg, t), dist));
}
}
best.map(|(i, on, _)| (i, Some(on))).into_iter().collect()
}
Pick::Rect(r) | Pick::Line(_, r) => {
parts.iter().enumerate().filter(|(_, (id, _, b))| in_scope(*id) && b.overlaps(*r)).map(|(i, _)| (i, None)).collect()
}
};
// Each path to trim has its box tested against every other path's.
if targets.len().saturating_mul(parts.len()) > MAX_BOX_TESTS {
return Err(bad(C, "the rectangle or line reaches too many paths to check"));
}
let mut plan: Vec<(NodeId, Vec<PathData>)> = vec![];
let mut removed = 0;
let mut budget = MAX_LINE_TESTS;
// One budget of crossing work for every path the command trims.
let mut work = pt::Work::default();
for (i, on) in targets {
let Some((id, path, b)) = parts.get(i) else { continue };
let reach = b.inflate(1e-3, 1e-3);
let others: Vec<&PathData> =
parts.iter().enumerate().filter(|(j, (_, _, ob))| *j != i && reach.overlaps(*ob)).map(|(_, (_, o, _))| *o).collect();
let Some((subs, n)) = trimmed(path, &others, &pick, on, &mut budget, &mut work)? else { continue };
removed += n;
// A path of one subpath becomes a path per piece; the pieces of one with more stay its subpaths.
let pieces = match (path.subpaths.len(), subs.is_empty()) {
(_, true) => vec![],
(1, false) => subs.into_iter().map(PathData::single).collect(),
_ => vec![PathData::new(subs)],
};
plan.push((*id, pieces));
}
if plan.is_empty() {
return Ok(json!({ "ids": [], "removed": 0 }));
}
let ids = s.edit(LABEL, |d, sel| {
let trimmed: Vec<NodeId> = plan.iter().map(|(id, _)| *id).collect();
// The compound paths that may lose their last member.
let mut compounds: Vec<NodeId> = trimmed
.iter()
.filter_map(|id| d.parent_of(*id))
.filter(|c| matches!(d.node(*c).map(|n| &n.kind), Some(NodeKind::Compound { .. })))
.collect();
compounds.dedup();
let mut beside = Beside::replacing(d, &trimmed);
let mut all = vec![];
for (id, pieces) in plan {
let selected = sel.contains(id);
sel.anchors.remove(&id);
sel.segments.remove(&id);
let made = replace_with_pieces(d, &mut beside, id, pieces)?;
// The pieces of a selected path are selected; what was not selected stays so.
if made.is_empty() {
sel.remove(id);
} else if selected {
for n in &made {
if !sel.contains(*n) {
sel.add(*n);
}
}
}
all.extend(made);
}
beside.finish(d)?;
for c in compounds {
if d.node(c).is_some_and(|n| n.children().is_some_and(|ch| ch.is_empty())) {
d.remove(c)?;
sel.remove(c);
}
}
Ok(all)
})?;
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "removed": removed }))
}
@@ -0,0 +1,527 @@
//! Trim at Crossings: the stretch at a point, the stretches a rectangle touches or a line crosses,
//! one undo step, and what takes no part.
use serde_json::{Value, json};
use vectorcraft_doc::{NodeId, NodeKind};
use vectorcraft_geom::{PathData, Point};
use crate::Session;
const TRIM: &str = "addon.pathtools.trim";
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
s
}
fn line(s: &mut Session, pts: &[(f64, f64)], closed: bool) -> NodeId {
let anchors: Vec<Value> = pts.iter().map(|(x, y)| json!({"x": x, "y": y})).collect();
let id = NodeId(s.execute("path.create", &json!({"anchors": anchors, "closed": closed})).unwrap()["id"].as_u64().unwrap());
s.execute("select.none", &json!({})).unwrap();
id
}
/// A line across at y = 100 from x = 0 to 300, and two uprights across it at x = 100 and x = 200.
fn across_and_uprights(s: &mut Session) -> (NodeId, NodeId, NodeId) {
let h = line(s, &[(0.0, 100.0), (300.0, 100.0)], false);
let v1 = line(s, &[(100.0, 50.0), (100.0, 150.0)], false);
let v2 = line(s, &[(200.0, 50.0), (200.0, 150.0)], false);
(h, v1, v2)
}
fn path(s: &Session, id: NodeId) -> PathData {
s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().clone()
}
fn exists(s: &Session, id: NodeId) -> bool {
s.doc().unwrap().doc.node(id).is_some()
}
/// The first and last anchor of the path's only subpath.
fn ends(s: &Session, id: NodeId) -> (Point, Point) {
let p = path(s, id);
assert_eq!(p.subpaths.len(), 1);
(p.subpaths[0].anchors.first().unwrap().p, p.subpaths[0].anchors.last().unwrap().p)
}
fn near(p: Point, x: f64, y: f64) -> bool {
p.distance(Point::new(x, y)) < 1e-6
}
fn steps(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
fn ids(v: &Value) -> Vec<NodeId> {
v["ids"].as_array().unwrap().iter().map(|x| NodeId(x.as_u64().unwrap())).collect()
}
/// The ids of the first layer's objects, bottom to top.
fn stack(s: &Session) -> Vec<NodeId> {
s.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id).collect()
}
fn set_flags(s: &mut Session, id: NodeId, locked: bool, visible: bool) {
s.edit("flags", |d, _| {
let n = d.node_mut(id).unwrap();
n.locked = locked;
n.visible = visible;
Ok(())
})
.unwrap();
}
#[test]
fn a_point_between_two_crossings_removes_that_stretch_and_splits_the_path() {
let mut s = session();
let (h, v1, v2) = across_and_uprights(&mut s);
let look = s.doc().unwrap().doc.node(h).unwrap().appearance.clone();
let (before, n) = (stack(&s), steps(&s));
let r = s.execute(TRIM, &json!({"at": [150, 101]})).unwrap();
assert_eq!(r["removed"], json!(1));
let made = ids(&r);
assert_eq!(made.len(), 2, "{r}");
assert_eq!(made[0], h, "the first piece keeps the id");
let (a, b) = (ends(&s, made[0]), ends(&s, made[1]));
assert!(near(a.0, 0.0, 100.0) && near(a.1, 100.0, 100.0), "{a:?}");
assert!(near(b.0, 200.0, 100.0) && near(b.1, 300.0, 100.0), "{b:?}");
// Both pieces look as the path did and stand where it stood, under the uprights.
assert!(made.iter().all(|id| s.doc().unwrap().doc.node(*id).unwrap().appearance == look));
assert_eq!(stack(&s), [made[0], made[1], v1, v2]);
assert_eq!(before, [h, v1, v2]);
// The uprights are as they were, nothing got selected, and it is one undo step.
assert_eq!((path(&s, v1).anchor_count(), path(&s, v2).anchor_count()), (2, 2));
assert!(s.doc().unwrap().selection.is_empty());
assert_eq!(steps(&s), n + 1);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(stack(&s), before);
assert!(near(ends(&s, h).1, 300.0, 100.0));
}
#[test]
fn an_end_stretch_runs_to_the_open_end_and_the_rest_stays_one_path() {
let mut s = session();
let (h, ..) = across_and_uprights(&mut s);
let r = s.execute(TRIM, &json!({"at": [40, 100]})).unwrap();
assert_eq!((ids(&r), r["removed"].clone()), (vec![h], json!(1)));
let e = ends(&s, h);
assert!(near(e.0, 100.0, 100.0) && near(e.1, 300.0, 100.0), "{e:?}");
// No anchor is added at the crossing the rest runs through.
assert_eq!(path(&s, h).anchor_count(), 2);
// A point on no path within the tolerance removes nothing and makes no step.
let n = steps(&s);
assert_eq!(s.execute(TRIM, &json!({"at": [250, 110]})).unwrap(), json!({"ids": [], "removed": 0}));
assert_eq!(s.execute(TRIM, &json!({"at": [250, 110], "tolerance": 0})).unwrap()["removed"], json!(0));
assert_eq!(steps(&s), n);
assert_eq!(s.execute(TRIM, &json!({"at": [250, 110], "tolerance": 12})).unwrap()["removed"], json!(1));
assert!(near(ends(&s, h).1, 200.0, 100.0));
}
#[test]
fn a_closed_path_that_loses_a_stretch_opens() {
let mut s = session();
let sq = NodeId(s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap());
s.execute("select.none", &json!({})).unwrap();
line(&mut s, &[(50.0, 150.0), (250.0, 150.0)], false);
// The top half of the square's outline, between the two places the line crosses it.
let r = s.execute(TRIM, &json!({"at": [150, 100]})).unwrap();
assert_eq!((ids(&r), r["removed"].clone()), (vec![sq], json!(1)));
let p = path(&s, sq);
assert_eq!(p.subpaths.len(), 1);
assert!(!p.subpaths[0].closed);
let pts: Vec<Point> = p.subpaths[0].anchors.iter().map(|a| a.p).collect();
assert_eq!(pts.len(), 4, "{pts:?}");
assert!(pts.iter().all(|q| q.y >= 150.0 - 1e-6), "only the lower half is left: {pts:?}");
assert!(pts.iter().any(|q| near(*q, 100.0, 200.0)) && pts.iter().any(|q| near(*q, 200.0, 200.0)));
// It is a plain path now.
assert!(matches!(&s.doc().unwrap().doc.node(sq).unwrap().kind, NodeKind::Path { live: None, .. }));
}
#[test]
fn a_rectangle_removes_every_stretch_it_touches_as_one_step() {
let mut s = session();
let (h, v1, v2) = across_and_uprights(&mut s);
let h2 = line(&mut s, &[(0.0, 120.0), (300.0, 120.0)], false);
let n = steps(&s);
// Over the middle of both lines across, touching neither upright.
let r = s.execute(TRIM, &json!({"rect": [140, 90, 20, 40]})).unwrap();
assert_eq!(r["removed"], json!(2));
assert_eq!(ids(&r).len(), 4);
assert_eq!(steps(&s), n + 1, "one undo step");
assert!(near(ends(&s, h).1, 100.0, 100.0) && near(ends(&s, h2).1, 100.0, 120.0));
assert_eq!((path(&s, v1).anchor_count(), path(&s, v2).anchor_count()), (2, 2));
s.execute("edit.undo", &json!({})).unwrap();
assert!(near(ends(&s, h).1, 300.0, 100.0) && near(ends(&s, h2).1, 300.0, 120.0));
// A rectangle given from its far corner is the same one; one over empty space removes nothing.
assert_eq!(s.execute(TRIM, &json!({"rect": [160, 130, -20, -40]})).unwrap()["removed"], json!(2));
let n = steps(&s);
assert_eq!(s.execute(TRIM, &json!({"rect": [300, 200, 50, 50]})).unwrap()["removed"], json!(0));
assert_eq!(steps(&s), n);
// An upright's stretches: above the upper line, between the two, below the lower. A rectangle
// over its top end takes the first only.
assert_eq!(s.execute(TRIM, &json!({"rect": [95, 45, 10, 10]})).unwrap()["removed"], json!(1));
assert!(near(ends(&s, v1).0, 100.0, 100.0) && near(ends(&s, v1).1, 100.0, 150.0));
}
#[test]
fn a_line_through_points_removes_the_stretches_it_crosses() {
let mut s = session();
let (h, v1, v2) = across_and_uprights(&mut s);
let n = steps(&s);
// Down through the middle of the line across, then right through the lower end of the second upright.
let r = s.execute(TRIM, &json!({"points": [[150, 80], [150, 130], [250, 130]]})).unwrap();
assert_eq!(r["removed"], json!(2));
assert_eq!(steps(&s), n + 1);
assert!(near(ends(&s, h).1, 100.0, 100.0));
assert!(near(ends(&s, v2).0, 200.0, 50.0) && near(ends(&s, v2).1, 200.0, 100.0));
assert_eq!(path(&s, v1).anchor_count(), 2);
}
#[test]
fn locked_and_hidden_paths_are_not_trimmed_and_do_not_count_as_crossing() {
let mut s = session();
let (h, v1, v2) = across_and_uprights(&mut s);
set_flags(&mut s, v1, true, true);
set_flags(&mut s, v2, false, false);
let n = steps(&s);
// On the locked upright, and a rectangle over the hidden one's top end: nothing goes.
assert_eq!(s.execute(TRIM, &json!({"at": [100, 60]})).unwrap()["removed"], json!(0));
assert_eq!(s.execute(TRIM, &json!({"rect": [195, 45, 10, 10]})).unwrap()["removed"], json!(0));
assert_eq!(steps(&s), n);
assert_eq!((path(&s, v1).anchor_count(), path(&s, v2).anchor_count()), (2, 2));
// Neither marks a place on the line across: with nothing else crossing it, it goes whole.
assert_eq!(s.execute(TRIM, &json!({"at": [150, 100]})).unwrap(), json!({"ids": [], "removed": 1}));
assert!(!exists(&s, h) && exists(&s, v1) && exists(&s, v2));
// A guide doesn't count either.
s.execute("edit.undo", &json!({})).unwrap();
set_flags(&mut s, v1, false, true);
s.execute("select.set", &json!({"ids": [v1.0]})).unwrap();
s.execute("view.guides.make", &json!({})).unwrap();
s.execute("select.none", &json!({})).unwrap();
s.execute(TRIM, &json!({"at": [150, 100]})).unwrap();
assert!(!exists(&s, h));
}
#[test]
fn a_path_of_two_subpaths_loses_the_stretch_on_the_subpath_under_the_point() {
let mut s = session();
// Lines of different lengths, so the places on one fall at other parameters than on the other.
let line_at = |x0: f64, x1: f64, y: f64| vectorcraft_geom::SubPath::polyline(&[Point::new(x0, y), Point::new(x1, y)], false);
let two = s
.edit("two", |d, _| {
let layer = d.layers[0].id;
let id = d.alloc_id();
let both = PathData::new(vec![line_at(0.0, 300.0, 100.0), line_at(50.0, 250.0, 120.0)]);
d.insert(Some(layer), 0, vectorcraft_doc::Node::path(id, both, Default::default()))?;
Ok(id)
})
.unwrap();
line(&mut s, &[(100.0, 50.0), (100.0, 150.0)], false);
line(&mut s, &[(200.0, 50.0), (200.0, 150.0)], false);
// The middle of the lower subpath goes; the upper one stays whole, both in the one path.
assert_eq!(s.execute(TRIM, &json!({"at": [150, 120]})).unwrap()["removed"], json!(1));
let p = path(&s, two);
let spans: Vec<(Point, Point)> = p.subpaths.iter().map(|sp| (sp.anchors[0].p, sp.anchors.last().unwrap().p)).collect();
assert_eq!(spans.len(), 3, "{spans:?}");
assert!(near(spans[0].0, 0.0, 100.0) && near(spans[0].1, 300.0, 100.0), "{spans:?}");
assert!(near(spans[1].0, 50.0, 120.0) && near(spans[1].1, 100.0, 120.0), "{spans:?}");
assert!(near(spans[2].0, 200.0, 120.0) && near(spans[2].1, 250.0, 120.0), "{spans:?}");
}
#[test]
fn a_clipping_path_is_not_trimmed_and_does_not_count_as_crossing() {
let mut s = session();
let (h, v1, _) = across_and_uprights(&mut s);
s.edit("clip", |d, _| {
if let NodeKind::Path { clipping, .. } = &mut d.node_mut(v1).unwrap().kind {
*clipping = true;
}
Ok(())
})
.unwrap();
assert_eq!(s.execute(TRIM, &json!({"at": [100, 60]})).unwrap()["removed"], json!(0));
assert_eq!(path(&s, v1).anchor_count(), 2);
// The line across is crossed by the second upright only: its stretch from the start goes.
assert_eq!(s.execute(TRIM, &json!({"at": [150, 100]})).unwrap()["removed"], json!(1));
assert!(near(ends(&s, h).0, 200.0, 100.0) && near(ends(&s, h).1, 300.0, 100.0));
// Type over the rest of it takes no part either: nothing crosses the rest, and it goes whole.
let t = NodeId(s.execute("text.create", &json!({"x": 220, "y": 115, "text": "HHHH", "size": 40})).unwrap()["id"].as_u64().unwrap());
s.execute("select.none", &json!({})).unwrap();
assert_eq!(s.execute(TRIM, &json!({"rect": [215, 70, 70, 50]})).unwrap(), json!({"ids": [], "removed": 1}));
assert!(!exists(&s, h) && exists(&s, t));
}
#[test]
fn the_members_of_a_compound_clipping_path_are_not_trimmed_and_do_not_count_as_crossing() {
let mut s = session();
let (h, v1, _) = across_and_uprights(&mut s);
let extra = line(&mut s, &[(250.0, 250.0), (260.0, 260.0)], false);
s.execute("select.set", &json!({"ids": [v1.0, extra.0]})).unwrap();
let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [h.0, compound.0]})).unwrap();
s.execute("object.clippingMask.make", &json!({})).unwrap();
s.execute("select.none", &json!({})).unwrap();
let n = steps(&s);
// A click on the clipping path's member changes nothing, and the rectangle over it neither.
assert_eq!(s.execute(TRIM, &json!({"at": [100, 60]})).unwrap()["removed"], json!(0));
assert_eq!(s.execute(TRIM, &json!({"rect": [245, 245, 20, 20]})).unwrap()["removed"], json!(0));
assert_eq!((steps(&s), path(&s, v1).anchor_count(), path(&s, extra).anchor_count()), (n, 2, 2));
// The clipped line across is crossed by the second upright only: its stretch from the start goes.
assert_eq!(s.execute(TRIM, &json!({"at": [150, 100]})).unwrap()["removed"], json!(1));
assert!(near(ends(&s, h).0, 200.0, 100.0) && near(ends(&s, h).1, 300.0, 100.0));
}
#[test]
fn in_isolation_mode_only_the_isolated_objects_paths_are_trimmed() {
let mut s = session();
let (h, v1, v2) = across_and_uprights(&mut s);
s.execute("select.set", &json!({"ids": [v1.0, v2.0]})).unwrap();
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
s.execute("select.none", &json!({})).unwrap();
// The line across is outside the group: a click or a rectangle on it leaves it whole.
assert_eq!(s.execute(TRIM, &json!({"at": [150, 100]})).unwrap()["removed"], json!(0));
assert_eq!(s.execute(TRIM, &json!({"rect": [140, 90, 20, 20]})).unwrap()["removed"], json!(0));
assert!(near(ends(&s, h).0, 0.0, 100.0) && near(ends(&s, h).1, 300.0, 100.0));
// It still crosses the uprights: a rectangle over the tops of both removes them down to it.
assert_eq!(s.execute(TRIM, &json!({"rect": [90, 40, 120, 20]})).unwrap()["removed"], json!(2));
assert!(near(ends(&s, v1).0, 100.0, 100.0) && near(ends(&s, v2).0, 200.0, 100.0));
assert!(near(ends(&s, h).0, 0.0, 100.0) && near(ends(&s, h).1, 300.0, 100.0));
// An isolated path is trimmed itself.
s.execute("object.exitIsolation", &json!({})).unwrap();
s.execute("object.isolate", &json!({"id": h.0})).unwrap();
assert_eq!(s.execute(TRIM, &json!({"at": [150, 100]})).unwrap()["removed"], json!(1));
assert!(near(ends(&s, h).1, 100.0, 100.0));
}
#[test]
fn a_rectangle_over_too_many_paths_to_check_is_refused() {
let mut s = session();
// 7,072 short lines apart from each other: each of them against every other is past the limit.
s.edit("many", |d, _| {
let layer = d.layers[0].id;
for i in 0..7072 {
let (x, y) = ((i % 100) as f64 * 3.0, (i / 100) as f64 * 3.0);
let sp = vectorcraft_geom::SubPath::polyline(&[Point::new(x, y), Point::new(x + 1.0, y)], false);
let id = d.alloc_id();
let top = d.node(layer).unwrap().children().unwrap().len();
d.insert(Some(layer), top, vectorcraft_doc::Node::path(id, PathData::single(sp), Default::default()))?;
}
Ok(())
})
.unwrap();
let n = steps(&s);
let err = s.execute(TRIM, &json!({"rect": [-10, -10, 400, 300]})).unwrap_err().to_string();
assert!(err.contains("too many paths"), "{err}");
assert_eq!((steps(&s), stack(&s).len()), (n, 7072));
// A rectangle over a few of them is checked.
assert_eq!(s.execute(TRIM, &json!({"rect": [-1, -1, 5, 2]})).unwrap()["removed"], json!(2));
}
#[test]
fn a_path_too_large_to_search_is_refused_only_when_touched() {
let mut s = session();
let (h, ..) = across_and_uprights(&mut s);
// A border of 10,001 segments round all of them, more than a path to trim may have.
let mut border: Vec<(f64, f64)> = (0..=10_001).map(|i| (-500.0 + i as f64 * 0.2, -500.0)).collect();
border.push((-500.0, 1500.0));
let b = line(&mut s, &border, true);
// A rectangle and a line over the middle of the line across reach inside the border's box only.
assert_eq!(s.execute(TRIM, &json!({"rect": [140, 90, 20, 20]})).unwrap()["removed"], json!(1));
assert!(near(ends(&s, h).1, 100.0, 100.0));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.execute(TRIM, &json!({"points": [[150, 80], [150, 120]]})).unwrap()["removed"], json!(1));
// A rectangle on the border is refused, and changes nothing.
let n = steps(&s);
let err = s.execute(TRIM, &json!({"rect": [-510, 0, 20, 20]})).unwrap_err().to_string();
assert!(err.contains("too many or too tangled"), "{err}");
assert_eq!((steps(&s), path(&s, b).anchor_count()), (n, 10_003));
}
#[test]
fn a_path_nothing_crosses_goes_whole_open_or_closed() {
let mut s = session();
let open = line(&mut s, &[(0.0, 10.0), (50.0, 10.0), (50.0, 40.0)], false);
let closed = line(&mut s, &[(100.0, 10.0), (150.0, 10.0), (150.0, 40.0)], true);
let n = steps(&s);
assert_eq!(s.execute(TRIM, &json!({"at": [25, 10]})).unwrap(), json!({"ids": [], "removed": 1}));
assert_eq!(s.execute(TRIM, &json!({"at": [125, 10]})).unwrap(), json!({"ids": [], "removed": 1}));
assert!(!exists(&s, open) && !exists(&s, closed));
assert_eq!(steps(&s), n + 2);
}
#[test]
fn a_path_that_ends_on_another_marks_a_place_and_paths_along_each_other_do_not() {
let mut s = session();
let h = line(&mut s, &[(0.0, 100.0), (300.0, 100.0)], false);
let stub = line(&mut s, &[(150.0, 100.0), (150.0, 160.0)], false);
// The stub ends on the line: the line's stretch stops there, and the stub is one stretch.
s.execute(TRIM, &json!({"at": [50, 100]})).unwrap();
assert!(near(ends(&s, h).0, 150.0, 100.0) && near(ends(&s, h).1, 300.0, 100.0));
assert_eq!(s.execute(TRIM, &json!({"at": [150, 130]})).unwrap()["removed"], json!(1));
assert!(!exists(&s, stub));
// A second line along the first doesn't mark it: the lower one goes whole.
let along = line(&mut s, &[(200.0, 100.0), (260.0, 100.0)], false);
s.execute(TRIM, &json!({"rect": [270, 90, 10, 20]})).unwrap();
assert!(!exists(&s, h) && exists(&s, along));
}
#[test]
fn a_self_crossing_path_loses_its_loop() {
let mut s = session();
// A bow: its first and third segments cross at (50, 50).
let bow = line(&mut s, &[(0.0, 0.0), (100.0, 100.0), (100.0, 0.0), (0.0, 100.0)], false);
let r = s.execute(TRIM, &json!({"at": [100, 50]})).unwrap();
assert_eq!(r["removed"], json!(1));
let made = ids(&r);
assert_eq!(made.len(), 2);
assert_eq!(made[0], bow);
assert!(near(ends(&s, made[0]).1, 50.0, 50.0) && near(ends(&s, made[1]).0, 50.0, 50.0));
}
#[test]
fn compound_path_members_are_trimmed_and_an_emptied_compound_path_goes() {
let mut s = session();
let a = line(&mut s, &[(0.0, 100.0), (300.0, 100.0)], false);
let b = line(&mut s, &[(100.0, 50.0), (100.0, 150.0)], false);
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
s.execute("select.none", &json!({})).unwrap();
let members = |s: &Session| s.doc().unwrap().doc.node(compound).map(|n| n.children().unwrap().len());
assert_eq!(members(&s), Some(2));
// The members cross each other: a middle stretch splits one member in the compound path.
assert_eq!(s.execute(TRIM, &json!({"at": [100, 75]})).unwrap()["removed"], json!(1));
assert_eq!(members(&s), Some(2));
assert_eq!(s.execute(TRIM, &json!({"at": [100, 125]})).unwrap()["removed"], json!(1));
assert_eq!(members(&s), Some(1));
assert_eq!(s.execute(TRIM, &json!({"at": [200, 100]})).unwrap()["removed"], json!(1));
assert_eq!(members(&s), None, "the emptied compound path is removed");
assert!(stack(&s).is_empty());
}
#[test]
fn the_selection_stays_as_it_was_and_the_pieces_of_a_selected_path_are_selected() {
let mut s = session();
let (_, v1, _) = across_and_uprights(&mut s);
s.execute("select.set", &json!({"ids": [v1.0]})).unwrap();
s.execute(TRIM, &json!({"at": [150, 100]})).unwrap();
assert_eq!(s.doc().unwrap().selection.objects, [v1], "the trimmed path was not selected");
let mut s = session();
let (h, ..) = across_and_uprights(&mut s);
s.execute("select.set", &json!({"ids": [h.0]})).unwrap();
let made = ids(&s.execute(TRIM, &json!({"at": [150, 100]})).unwrap());
assert_eq!(made.len(), 2);
let sel = &s.doc().unwrap().selection;
assert!(made.iter().all(|id| sel.contains(*id)), "{:?}", sel.objects);
// The second piece now ends on an upright: nothing crosses it, and it goes whole.
s.execute("select.set", &json!({"ids": [made[1].0]})).unwrap();
assert_eq!(s.execute(TRIM, &json!({"at": [250, 100]})).unwrap(), json!({"ids": [], "removed": 1}));
assert!(s.doc().unwrap().selection.is_empty(), "a removed path leaves the selection");
}
#[test]
fn many_paths_far_from_the_trimmed_one_cost_no_crossing_search() {
let mut s = session();
let (h, ..) = across_and_uprights(&mut s);
// 3,000 short lines far below, each crossing its neighbor.
s.edit("many", |d, _| {
let layer = d.layers[0].id;
for i in 0..3000 {
let x = (i % 100) as f64 * 3.0;
let y = 1000.0 + (i / 100) as f64 * 3.0;
let sp = vectorcraft_geom::SubPath::polyline(
&[Point::new(x, y), Point::new(x + 5.0, y + 5.0), Point::new(x + 5.0, y), Point::new(x, y + 5.0)],
false,
);
let id = d.alloc_id();
let top = d.node(layer).unwrap().children().unwrap().len();
d.insert(Some(layer), top, vectorcraft_doc::Node::path(id, PathData::single(sp), Default::default()))?;
}
Ok(())
})
.unwrap();
assert_eq!(s.execute(TRIM, &json!({"at": [150, 100]})).unwrap()["removed"], json!(1));
assert!(near(ends(&s, h).1, 100.0, 100.0));
// A rectangle over all of them takes every stretch it touches.
let r = s.execute(TRIM, &json!({"rect": [-10, 990, 400, 200]})).unwrap();
assert!(r["removed"].as_u64().unwrap() >= 3000, "{}", r["removed"]);
assert_eq!(stack(&s).len(), 4, "the line across in two pieces and the uprights");
}
#[test]
fn the_tool_trims_on_release_as_one_step_and_escape_drops_a_drag() {
use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey};
let mut s = session();
let (h, v1, _) = across_and_uprights(&mut s);
let h2 = line(&mut s, &[(0.0, 120.0), (300.0, 120.0)], false);
let view = crate::ViewInfo { smart_guides: false, ..crate::ViewInfo::default() };
s.select_tool("trimAtCrossings", view).unwrap();
assert_eq!(s.tool_id(), "trimAtCrossings");
let n = steps(&s);
// A drag over the middle of both lines across: nothing changes until the release.
s.pointer(&PointerEvent::new(PointerKind::Down, 140.0, 90.0), view).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 160.0, 130.0), view).unwrap();
assert!(near(ends(&s, h).1, 300.0, 100.0));
s.pointer(&PointerEvent::new(PointerKind::Up, 160.0, 130.0), view).unwrap();
assert!(near(ends(&s, h).1, 100.0, 100.0) && near(ends(&s, h2).1, 100.0, 120.0));
assert_eq!(steps(&s), n + 1, "one undo step for the drag");
// Escape during a drag: the release removes nothing.
s.pointer(&PointerEvent::new(PointerKind::Down, 90.0, 40.0), view).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 110.0, 60.0), view).unwrap();
s.tool_key(ToolKey::Escape, Mods::default(), view).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 110.0, 60.0), view).unwrap();
assert_eq!(steps(&s), n + 1);
assert!(near(ends(&s, v1).0, 100.0, 50.0));
// A click on the upright's top stretch removes it.
s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 70.0), view).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 100.0, 70.0), view).unwrap();
assert!(near(ends(&s, v1).0, 100.0, 100.0));
assert_eq!(steps(&s), n + 2);
}
#[test]
fn a_line_too_long_to_check_against_the_paths_is_refused() {
let mut s = session();
// A zigzag of 1,000 segments, and a line of 100,000 points inside its box that crosses none.
let zigzag: Vec<(f64, f64)> = (0..=1000).map(|i| (i as f64 * 0.3, (i % 2) as f64 * 200.0)).collect();
let z = line(&mut s, &zigzag, false);
let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s));
let points: Vec<Value> = (0..100_000).map(|i| json!([150.0 + (i % 2) as f64 * 0.01, 150.0])).collect();
let err = s.execute(TRIM, &json!({ "points": points })).unwrap_err().to_string();
assert!(err.contains("too long"), "{err}");
assert_eq!(steps(&s), n);
assert!(*s.doc().unwrap().doc == *before);
// A short line there is checked, and removes nothing.
assert_eq!(s.execute(TRIM, &json!({"points": [[150.0, 150.0], [150.01, 150.0]]})).unwrap()["removed"], json!(0));
assert!(exists(&s, z));
}
#[test]
fn bad_params_are_refused_and_change_nothing() {
let mut s = session();
across_and_uprights(&mut s);
let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s));
for bad in [
json!({}),
json!({"at": null}),
json!({"at": [150]}),
json!({"at": [150, "y"]}),
json!({"at": [150, 1e308]}),
json!({"at": [150, 100], "tolerance": -1}),
json!({"at": [150, 100], "tolerance": 101}),
json!({"at": [150, 100], "tolerance": "3"}),
json!({"at": [150, 100], "rect": [140, 90, 20, 40]}),
json!({"rect": [140, 90, 20]}),
json!({"rect": "all"}),
json!({"rect": [0, 0, 1e9, 5]}),
json!({"points": [[150, 80]]}),
json!({"points": [[150, 80], [150]]}),
json!({"points": "x"}),
json!({"points": [[150, 80], [150, 130]], "at": [1, 2]}),
] {
assert!(s.execute(TRIM, &bad).is_err(), "{bad}");
}
assert_eq!(steps(&s), n);
assert!(*s.doc().unwrap().doc == *before);
}
+323 -59
View File
@@ -19,7 +19,10 @@
//! shape that a Convert to Shape or Outline Object effect on them gives them, below or above the
//! image as its Contents row says; new ones go right below that row.
use std::{collections::HashMap, sync::Arc};
use std::{
collections::{HashMap, HashSet},
sync::Arc,
};
use serde_json::{Value, json};
use vectorcraft_color::{BlendMode, Paint};
@@ -45,7 +48,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add New Fill",
["Window", "Appearance"],
Some("Cmd+/"),
"{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row, with its top fill's paint (type without one: its characters' fill; else the default fill). With a fill row active (appearance.setActiveItem), no `ids`, no `id` and no `target: \"contents\"`, the new fill takes that row's paint, goes right above it, and becomes the active row; appearance.duplicateItem copies a whole row. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
"{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row, with its top fill's paint (type without one: its characters' fill; else the default fill). With a fill row active (appearance.setActiveItem), no `ids`, no `id` and no `target: \"contents\"`, the new fill takes that row's paint, goes right above it, and becomes the active row; appearance.duplicateItem copies a whole row. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind",
has_doc,
|s, p| add_item(s, p, true)
),
@@ -54,7 +57,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add New Stroke",
["Window", "Appearance"],
Some("Cmd+Alt+/"),
"{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row, with its top stroke's paint (else the default stroke) and that stroke's weight when it has paint, at least 1 pt. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
"{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row, with its top stroke's paint (else the default stroke) and that stroke's weight when it has paint, at least 1 pt. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind",
has_doc,
|s, p| add_item(s, p, false)
),
@@ -63,7 +66,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Clear Appearance",
["Window", "Appearance"],
None,
"{ids?|id?, target?} leave each object one empty fill and stroke (None; a group none of its own) and reset its opacity and blend mode. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md)",
"{ids?|id?, target?} leave each object one empty fill and stroke (None; a group none of its own) and reset its opacity and blend mode. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind",
has_doc,
clear_appearance
),
@@ -72,7 +75,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Reduce to Basic Appearance",
["Window", "Appearance"],
None,
"{ids?|id?, target?} keep only one visible fill and stroke (without ids: the Appearance panel's active row in place of the topmost one of its kind; else the topmost), without their own opacity, blend mode or effects (a group keeps no rows it lacked), and drop the object's effects. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
"{ids?|id?, target?} keep only one visible fill and stroke (without ids: the Appearance panel's active row in place of the topmost one of its kind; else the topmost), without their own opacity, blend mode or effects (a group keeps no rows it lacked), and drop the object's effects. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind",
has_doc,
reduce_basic
),
@@ -81,7 +84,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Appearance Item",
[],
None,
"{index: paint-order item index, ids?|id? (default: the selection), target?: \"object\"|\"contents\", opacity?: 0..100, blend?: name, visible?: bool, weight?: pt (strokes), color?|none?|swatch?|gradient? (as paint.setFill), tint?: 0..100, keepModel?: bool (both as paint.setFill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} edit one fill/stroke of each target object's own appearance stack. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
"{index: paint-order item index, ids?|id? (default: the selection), target?: \"object\"|\"contents\", opacity?: 0..100, blend?: name, visible?: bool, weight?: pt (strokes), color?|none?|swatch?|gradient? (as paint.setFill), tint?: 0..100, keepModel?: bool (both as paint.setFill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} edit one fill/stroke of each target object's own appearance stack. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind",
has_doc,
set_item
),
@@ -90,7 +93,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Remove Item",
[],
None,
"{index | indices: [..] (paint-order item indices), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} remove those fills/strokes from each target object's own stack. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
"{index | indices: [..] (paint-order item indices), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} remove those fills/strokes from each target object's own stack. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind",
has_doc,
remove_item
),
@@ -108,7 +111,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Duplicate Item",
["Window", "Appearance"],
None,
"{index | indices: [..] (paint-order item indices), to?: paint-order index of the copy (with several, of the lowest copy: they land together in their order; default: each right above its item; not with aligned rows of a mixed selection), contents?: count (with `to`: how many items paint below the Contents (Characters) row afterwards; default: it stays between the same items), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} copy fills/strokes with their effects, as Alt-dragging rows places them. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
"{index | indices: [..] (paint-order item indices), to?: paint-order index of the copy (with several, of the lowest copy: they land together in their order; default: each right above its item; not with aligned rows of a mixed selection), contents?: count (with `to`: how many items paint below the Contents (Characters) row afterwards; default: it stays between the same items), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} copy fills/strokes with their effects, as Alt-dragging rows places them. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind",
has_doc,
duplicate_item
),
@@ -117,7 +120,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Reorder Appearance Item",
[],
None,
"{from: paint-order item index | \"contents\", indices?: [..] (several items instead of from: they move as one block in their order, the lowest landing at `to`; a block landing next to the Contents row keeps its lowest item's side), to, contents?: count, ids?|id?, target?, aligned?: bool (refused when the targets' appearances differ)} move fill/stroke `from` to paint-order index `to`; on a group, layer or type the Contents (Characters) row stays between the same items (a moved item landing next to it keeps its side) unless `contents` says how many items paint below it afterwards. from \"contents\": move that row so `to` items paint below the members (characters) and the rest above. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md) → {index: where the item landed | contents: the row's slot}",
"{from: paint-order item index | \"contents\", indices?: [..] (several items instead of from: they move as one block in their order, the lowest landing at `to`; a block landing next to the Contents row keeps its lowest item's side), to, contents?: count, ids?|id?, target?, aligned?: bool (refused when the targets' appearances differ)} move fill/stroke `from` to paint-order index `to`; on a group, layer or type the Contents (Characters) row stays between the same items (a moved item landing next to it keeps its side) unless `contents` says how many items paint below it afterwards. from \"contents\": move that row so `to` items paint below the members (characters) and the rest above. On a path directly in a graph series (a series group's id stands for those paths, except with from \"contents\", which moves the group's own row), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind → {index: where the item landed | contents: the row's slot}",
has_doc,
move_item
),
@@ -126,7 +129,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Eyedropper",
[],
None,
"{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool, defaultsOnly?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes using effective character dimensions while preserving target transforms) from `source` to ids (default: highlighted characters while editing type, after Select All in a frame of threaded text the text of the story's frames, leaving out `source`, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `defaultsOnly` updates only paint defaults and cannot be combined with ids, reverse or append; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art); with an object of a dynamic symbol instance selected by Direct Selection and no ids, reverse, append or defaultsOnly, that object takes the source's fill and stroke (solid, none, gradient or pattern) for this instance only, as the Eyedropper Options allow, and a source that is not a path, compound path or type, or options that pick up neither color, are refused. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md) → {ids}",
"{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool, defaultsOnly?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes using effective character dimensions while preserving target transforms) from `source` to ids (default: highlighted characters while editing type, after Select All in a frame of threaded text the text of the story's frames, leaving out `source`, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `defaultsOnly` updates only paint defaults and cannot be combined with ids, reverse or append; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art); with an object of a dynamic symbol instance selected by Direct Selection and no ids, reverse, append or defaultsOnly, that object takes the source's fill and stroke (solid, none, gradient or pattern) for this instance only, as the Eyedropper Options allow, and a source that is not a path, compound path or type, or options that pick up neither color, are refused. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, the graph stores, for every label of its kind, the character attributes the pick gives all of its text, its object opacity and blend mode, and with `append` its topmost visible fill and stroke rows → {ids}",
has_doc,
copy_from
),
@@ -144,7 +147,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Show All Hidden Attributes",
["Window", "Appearance"],
None,
"{ids?|id?, target?} make every hidden fill, stroke and effect (the object's and each item's) of each selected object visible again; errors when nothing is hidden. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md) → {ids}",
"{ids?|id?, target?} make every hidden fill, stroke and effect (the object's and each item's) of each selected object visible again; errors when nothing is hidden. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind → {ids}",
has_doc,
show_all_hidden
),
@@ -162,7 +165,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Move Appearance",
[],
None,
"{source: id, target: id, copy?: bool} give `target` (a layer, group or object) the appearance (fills, strokes, effects) and transparency (opacity, blend mode, isolation, knockout) of `source`, as dragging a target circle onto another in the Layers panel does; the source is left with a cleared appearance (as appearance.clear) unless `copy` (Alt-drag). Opacity masks stay; placed gradients keep their place relative to each object's bounds. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md) → {source, target}",
"{source: id, target: id, copy?: bool} give `target` (a layer, group or object) the appearance (fills, strokes, effects) and transparency (opacity, blend mode, isolation, knockout) of `source`, as dragging a target circle onto another in the Layers panel does; the source is left with a cleared appearance (as appearance.clear) unless `copy` (Alt-drag). Opacity masks stay; placed gradients keep their place relative to each object's bounds. On a path directly in a graph series (a series group's id stands for those paths; as `source`, when the group has no effect, opacity, blend mode, isolation, knockout or style link of its own, the topmost one is read and a move clears them all; as `target` each takes the appearance and the group is cleared, a `source` among them keeps its look, and a `source` that is the group's only path is an error), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind → {source, target}",
has_doc,
transfer
),
@@ -416,9 +419,108 @@ pub(crate) fn appearance_targets(s: &Session, p: &Value) -> Result<Vec<NodeId>>
if targets_contents(p)? { leaf_targets(s, &roots) } else { Ok(roots) }
}
/// [`appearance_targets`] of `cmd`, which needs at least one.
fn require_targets(s: &Session, p: &Value, cmd: &str) -> Result<Vec<NodeId>> {
/// The refusal of an appearance edit whose targets are all the art of graph designs drawn in graph series.
const DESIGN_ART: &str = "the art of a graph design in a graph series is drawn again from the design: edit the design to change it";
/// The [`appearance_targets`] whose rows and effects a command edits: the art of graph designs drawn in graph series
/// ([`super::graph::is_design_art`]) is left out, as the graph draws it again from the design. A command whose targets
/// are all such art is refused.
pub(crate) fn edit_targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
let ids = appearance_targets(s, p)?;
without_design_art(&s.doc()?.doc, ids, "appearance")
}
/// `ids` without the art of graph designs drawn in graph series; `cmd` is refused when `ids` held nothing else.
pub(crate) fn without_design_art(d: &Document, mut ids: Vec<NodeId>, cmd: &str) -> Result<Vec<NodeId>> {
let given = ids.len();
ids.retain(|id| !super::graph::is_design_art(d, *id));
if given > 0 && ids.is_empty() {
return Err(bad(cmd, DESIGN_ART));
}
Ok(ids)
}
/// `ids` with each graph series group that has no fill or stroke row of its own replaced by the paths directly inside
/// it ([`super::graph::series_group_marks`]). A series group with rows, as a document saved earlier can hold, stays:
/// the Appearance panel lists those rows and edits them by index.
pub(crate) fn rowless_series_marks(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
super::graph::series_group_marks_where(d, ids, |group| group.appearance.items.is_empty())
}
/// Whether series group `group` holds nothing of its own, as the graph draws it: no fill or stroke row, no effect, the
/// default opacity, blend mode, isolation and knockout, and no graphic style link.
fn holds_no_look(group: &Node) -> bool {
let ap = &group.appearance;
ap.items.is_empty()
&& ap.effects.is_empty()
&& group.opacity == 1.0
&& group.blend == BlendMode::Normal
&& !group.isolate
&& group.knockout == Default::default()
&& !group.knockout_shape
&& group.extras().graphic_style.is_none()
}
/// The objects whose appearance a command reads for `id`: a graph series group that holds nothing of its own
/// ([`holds_no_look`]) gives the paths directly inside it, backmost first. A series group with an effect, an opacity or
/// another attribute of its own is read itself, with that attribute.
fn look_holders(d: &Document, id: NodeId) -> Vec<NodeId> {
super::graph::series_group_marks_where(d, &[id], holds_no_look)
}
/// The object whose appearance a command reads for `n`: a graph series group that holds nothing of its own stands for
/// the topmost path directly inside it ([`look_holders`]).
pub(crate) fn look_holder<'a>(d: &'a Document, n: &'a Node) -> &'a Node {
look_holders(d, n.id).last().and_then(|id| d.node(*id)).unwrap_or(n)
}
/// Objects whose fill and stroke rows a command edits: the [`edit_targets`], with a graph series group standing for the
/// paths directly inside it ([`rowless_series_marks`]), so the graph can store the edit.
pub(crate) fn row_targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
let ids = edit_targets(s, p)?;
Ok(rowless_series_marks(&s.doc()?.doc, &ids))
}
/// Objects whose whole appearance a command edits: the [`row_targets`], then each graph series group they stand for,
/// which can hold effects and a graphic style link of its own.
pub(crate) fn whole_targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
let own = edit_targets(s, p)?;
let mut ids = rowless_series_marks(&s.doc()?.doc, &own);
let groups = stood_for(&own, &ids);
ids.extend(groups);
Ok(ids)
}
/// The series groups among `own` that `ids` ([`rowless_series_marks`] of `own`) replaced with their paths.
pub(crate) fn stood_for(own: &[NodeId], ids: &[NodeId]) -> Vec<NodeId> {
let kept: HashSet<NodeId> = ids.iter().copied().collect();
own.iter().copied().filter(|id| !kept.contains(id)).collect()
}
/// Clear Appearance on each series group a command gave a whole new appearance through its paths, so the group's own
/// opacity, blend mode, isolation, knockout, effects and style link do not stay on top of it.
pub(crate) fn clear_stood_for(d: &mut Document, groups: &[NodeId]) {
for id in groups {
if let Some(n) = d.node_mut(*id) {
clear(n);
(n.isolate, n.knockout, n.knockout_shape) = (false, Default::default(), false);
n.extras_mut().graphic_style = None;
}
}
}
/// [`whole_targets`] of `cmd`, which needs at least one.
fn require_whole_targets(s: &Session, p: &Value, cmd: &str) -> Result<Vec<NodeId>> {
let ids = whole_targets(s, p)?;
if ids.is_empty() {
return Err(bad(cmd, "select objects or give ids"));
}
Ok(ids)
}
/// [`row_targets`] of `cmd`, which needs at least one.
fn require_targets(s: &Session, p: &Value, cmd: &str) -> Result<Vec<NodeId>> {
let ids = row_targets(s, p)?;
if ids.is_empty() {
return Err(bad(cmd, "select objects or give ids"));
}
@@ -427,8 +529,9 @@ fn require_targets(s: &Session, p: &Value, cmd: &str) -> Result<Vec<NodeId>> {
/// One undo step (`label`) running `f` on each of `ids` with the item a fill (`fill`) or stroke
/// edit aimed at `item` changes there (`None`: the topmost one; text then edits its characters).
/// Nothing targeted is not an edit, and when `f` leaves every target as it was, the document and
/// its undo history stay as they are.
/// What the edit changes on the topmost visible fill and stroke of graph series marks is stored on
/// their graphs in the same step ([`capture_series_changes`]). Nothing targeted is not an edit, and
/// when `f` leaves every target as it was, the document and its undo history stay as they are.
pub(crate) fn edit_items(
s: &mut Session,
ids: &[NodeId],
@@ -438,12 +541,13 @@ pub(crate) fn edit_items(
fill: bool,
f: impl FnMut(&mut Node, Option<usize>) -> Result<()>,
) -> Result<()> {
edit_items_then(s, ids, item, cmd, label, fill, f, |_, _| Ok(false))
edit_items_then(s, ids, item, cmd, label, fill, f, |before, d, edited| Ok(capture_series_changes(before, d, edited)))
}
/// [`edit_items`], then `after` on the ids `f` ran on, inside the same undo step. `after` returns
/// whether it changed the document; when it did not and `f` left every target as it was, the
/// document and its undo history stay as they are.
/// [`edit_items`], then `after` on the document as it was before the edit, the edited document and
/// the ids `f` ran on, inside the same undo step. `after` returns whether it changed the document;
/// when it did not and `f` left every target as it was, the document and its undo history stay as
/// they are.
#[allow(clippy::too_many_arguments)]
pub(crate) fn edit_items_then(
s: &mut Session,
@@ -453,7 +557,7 @@ pub(crate) fn edit_items_then(
label: &str,
fill: bool,
mut f: impl FnMut(&mut Node, Option<usize>) -> Result<()>,
mut after: impl FnMut(&mut vectorcraft_doc::Document, &[NodeId]) -> Result<bool>,
mut after: impl FnMut(&vectorcraft_doc::Document, &mut vectorcraft_doc::Document, &[NodeId]) -> Result<bool>,
) -> Result<()> {
if ids.is_empty() {
return Ok(());
@@ -462,15 +566,21 @@ pub(crate) fn edit_items_then(
let per = item.per_target(s, ids);
super::overprint::edit_counted(s, label, |d| {
let mut edited = Vec::new();
// The objects whose rows `f` edited: on type, no row means its characters.
let mut rows = Vec::new();
for (id, item) in ids.iter().zip(&per) {
let Some(item) = item else { continue };
let Some(n) = d.node_mut(*id) else { continue };
let index = item.resolve(&n.appearance, fill, cmd)?;
f(n, index)?;
edited.push(*id);
if index.is_some() {
rows.push(*id);
}
}
let more = after(d, &edited)?;
Ok(count_changed(d, &before, &edited) + usize::from(more))
let more = after(&before, d, &edited)?;
let labels = super::graph::capture_label_rows(d, &rows);
Ok(count_changed(d, &before, &edited) + usize::from(more || labels))
})?;
Ok(())
}
@@ -607,6 +717,7 @@ fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result<Value> {
let mut rows = top_paint_changed(&before, d, &ids);
rows.extend(painted_rows(d, added));
super::graph::capture_series_top_paints(d, &rows);
super::graph::capture_label_rows(d, &ids);
Ok(())
})?;
// A fill added above the active row becomes the active row; otherwise the rows above the new
@@ -616,7 +727,7 @@ fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result<Value> {
}
fn clear_appearance(s: &mut Session, p: &Value) -> Result<Value> {
let ids = require_targets(s, p, "appearance.clear")?;
let ids = require_whole_targets(s, p, "appearance.clear")?;
// When every object is cleared already, the document and its undo history stay as they are.
let before = s.doc()?.doc.clone();
super::overprint::edit_counted(s, "Clear Appearance", |d| {
@@ -629,7 +740,8 @@ fn clear_appearance(s: &mut Session, p: &Value) -> Result<Value> {
let kept = super::graph::capture_series_opacity(d, &both_kinds(&ids));
let painted = super::graph::capture_series_top_paints(d, &top_paint_changed(&before, d, &ids));
let object = super::graph::capture_series_object_opacity(d, &ids);
Ok(count_changed(d, &before, &ids) + usize::from(kept || painted || object))
let labels = super::graph::capture_label_rows(d, &ids);
Ok(count_changed(d, &before, &ids) + usize::from(kept || painted || object || labels))
})?;
s.active_appearance_item = None;
ok()
@@ -710,6 +822,52 @@ pub(super) fn capture_series_writes(
kept || painted || stored
}
/// Store on the graph what an edit of `ids` (from `before` to `d`) changed on the series marks among them: the paint,
/// weight, opacity or blend mode of the topmost visible fill and stroke, and the object opacity and blend mode. Rows
/// and objects the edit left as they were keep what the graph stores. When the edit changes several marks of one series,
/// the frontmost one sets what the graph stores, whatever order `ids` are in. Returns whether the stored paint changed.
pub(crate) fn capture_series_changes(before: &vectorcraft_doc::Document, d: &mut vectorcraft_doc::Document, ids: &[NodeId]) -> bool {
let marks = series_children_in_paint_order(d, ids);
!marks.is_empty() && capture_series_writes(before, d, &marks, (false, false), (false, false), false, false)
}
/// Each of `ids` directly in a series group, from the back to the front: a later mark's capture replaces an earlier
/// one's, so the frontmost one sets what the graph stores.
pub(crate) fn series_children_in_paint_order(d: &vectorcraft_doc::Document, ids: &[NodeId]) -> Vec<NodeId> {
// Only objects directly in a series group can be marks: other edits skip the search of the document for graphs.
let in_series = |id: &NodeId| d.parent_of(*id).and_then(|p| d.node(p)).is_some_and(|g| g.extras().series_index.is_some());
let mut marks: Vec<NodeId> = ids.iter().copied().filter(in_series).collect();
marks.sort_by_cached_key(|id| d.index_path(*id));
marks
}
/// Store on the graph the paint that an edit of `ids` (from `before` to `d`) leaves on the topmost visible fill and stroke
/// of the series marks among them: a paint or stroke weight that changed, and the paint of each row the edit wrote
/// (`written`: an object with the index of the row) when that row is the topmost visible one of its kind and has paint.
/// A row written under that one, and a hidden one, keep what the graph stores. When the edit reaches several marks of one
/// series, the frontmost one sets what the graph stores, whatever order `ids` are in. Returns whether the stored paint
/// changed.
pub(crate) fn capture_series_paint_writes(
before: &vectorcraft_doc::Document,
d: &mut vectorcraft_doc::Document,
ids: &[NodeId],
written: &[(NodeId, usize)],
) -> bool {
// Only objects directly in a series group can be marks: other edits skip the comparison of paints and the search of
// the document for graphs.
let in_series = |id: &NodeId| d.parent_of(*id).and_then(|p| d.node(p)).is_some_and(|g| g.extras().series_index.is_some());
let mut marks: Vec<NodeId> = ids.iter().copied().filter(in_series).collect();
// A later mark's capture replaces an earlier one's: take them in paint order, each with all of its rows.
marks.sort_by_cached_key(|id| d.index_path(*id));
let mut rows = Vec::new();
for id in &marks {
rows.extend(top_paint_changed(before, d, &[*id]));
let shown = written.iter().filter(|(w, _)| w == id).filter_map(|(_, at)| Some((*id, top_row_kind(&d.node(*id)?.appearance, *at)?)));
rows.extend(painted_rows(d, shown.collect::<Vec<_>>()));
}
super::graph::capture_series_top_paints(d, &rows)
}
/// The kind of the row at `at` (fill `true`, stroke `false`) when it is the topmost visible row of that kind in `ap`.
fn top_row_kind(ap: &Appearance, at: usize) -> Option<bool> {
let fill = ap.items.get(at)?.is_fill();
@@ -732,35 +890,71 @@ fn transfer(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(C, "`source` and `target` are the same object"));
}
let copy = switch_or(p, "copy", false, C)?;
// The art of a graph design in a series is read as a source, but neither takes an appearance nor gives one up.
without_design_art(&s.doc()?.doc, vec![target], C)?;
if !copy {
without_design_art(&s.doc()?.doc, vec![source], C)?;
}
// A graph series group stands for the paths directly inside it: as the source, the topmost of them is read and a
// move clears them all; as the target, each of them other than a source takes the appearance.
let sources = look_holders(&s.doc()?.doc, source);
let read = sources.last().copied().unwrap_or(source);
let from: Vec<NodeId> = sources.iter().copied().chain(stood_for(&[source], &sources)).collect();
let marks = rowless_series_marks(&s.doc()?.doc, &[target]);
let stands = !marks.contains(&target);
let within: HashSet<NodeId> = from.iter().copied().collect();
let mut targets: Vec<NodeId> = marks.iter().copied().filter(|id| !within.contains(id)).collect();
if targets.is_empty() {
if stands {
return Err(bad(C, "`source` is the only path in series group `target`"));
}
targets.push(target);
}
// A source that is one of the target group's paths keeps its look: the group stands for it too.
let part: HashSet<NodeId> = if stands { marks.into_iter().collect() } else { HashSet::new() };
let from: Vec<NodeId> = stood_for(&from, &targets);
let cleared: Vec<NodeId> = if copy { vec![] } else { from.iter().copied().filter(|id| !part.contains(id)).collect() };
// The group its paths stand for loses its own opacity, blend mode and effects, which would stay on top of them.
let group: Vec<NodeId> = if stands { vec![target] } else { vec![] };
// When both objects come out as they were, the document and its undo history stay as they are.
let before = s.doc()?.doc.clone();
super::overprint::edit_counted(s, if copy { "Copy Appearance" } else { "Move Appearance" }, |d| {
let src = d.node(source).cloned().ok_or(EngineError::NoNode(source))?;
let to = d.node_mut(target).ok_or(EngineError::NoNode(target))?;
let mut ap = src.appearance.clone();
if let (Some(f), Some(t)) = (src.geometric_bounds(), to.geometric_bounds()) {
ap.rebase_gradients(f, t);
d.node(source).ok_or(EngineError::NoNode(source))?;
let src = d.node(read).cloned().ok_or(EngineError::NoNode(read))?;
for id in &targets {
let to = d.node_mut(*id).ok_or(EngineError::NoNode(*id))?;
let mut ap = src.appearance.clone();
if let (Some(f), Some(t)) = (src.geometric_bounds(), to.geometric_bounds()) {
ap.rebase_gradients(f, t);
}
// Only groups, layers, type and images have a Contents (Characters) row to keep a slot for.
if to.contents_label().is_none() {
ap.contents_index = None;
}
to.appearance = ap;
(to.opacity, to.blend, to.isolate, to.knockout, to.knockout_shape) =
(src.opacity, src.blend, src.isolate, src.knockout, src.knockout_shape);
super::object::snap_if_aligned(to);
}
// Only groups, layers, type and images have a Contents (Characters) row to keep a slot for.
if to.contents_label().is_none() {
ap.contents_index = None;
clear_stood_for(d, &group);
for id in &cleared {
if let Some(n) = d.node_mut(*id) {
clear(n);
(n.isolate, n.knockout, n.knockout_shape) = (false, Default::default(), false);
super::object::snap_if_aligned(n);
}
}
to.appearance = ap;
(to.opacity, to.blend, to.isolate, to.knockout, to.knockout_shape) = (src.opacity, src.blend, src.isolate, src.knockout, src.knockout_shape);
super::object::snap_if_aligned(to);
if !copy && let Some(n) = d.node_mut(source) {
clear(n);
(n.isolate, n.knockout, n.knockout_shape) = (false, Default::default(), false);
super::object::snap_if_aligned(n);
}
let changed = if copy { vec![target] } else { vec![source, target] };
let changed: Vec<NodeId> = cleared.iter().chain(&targets).copied().collect();
let kept = super::graph::capture_series_opacity(d, &both_kinds(&changed));
// The target last: on marks of one series, its paint is the one the series keeps.
// The targets last: on marks of one series, their paint is the one the series keeps.
let mut rows = top_paint_changed(&before, d, &changed);
rows.extend(painted_rows(d, both_kinds(&[target])));
rows.extend(painted_rows(d, both_kinds(&targets)));
let painted = super::graph::capture_series_top_paints(d, &rows);
let object = super::graph::capture_series_object_opacity(d, &changed);
Ok(count_changed(d, &before, &[source, target]) + usize::from(kept || painted || object))
// The targets last: on two labels of one kind, the target's rows are the ones the kind keeps.
let labels = super::graph::capture_label_rows(d, &changed);
let all: Vec<NodeId> = from.iter().chain(&targets).chain(&group).copied().collect();
Ok(count_changed(d, &before, &all) + usize::from(kept || painted || object || labels))
})?;
s.active_appearance_item = None;
Ok(json!({ "source": source.0, "target": target.0 }))
@@ -772,7 +966,7 @@ fn is_group(n: &Node) -> bool {
}
fn reduce_basic(s: &mut Session, p: &Value) -> Result<Value> {
let ids = require_targets(s, p, "appearance.reduceToBasic")?;
let ids = require_whole_targets(s, p, "appearance.reduceToBasic")?;
// When every object comes out as it was, the document and its undo history stay as they are.
let before = s.doc()?.doc.clone();
// The Appearance panel's active row (a row of the first selected object's stack, and in each
@@ -816,7 +1010,8 @@ fn reduce_basic(s: &mut Session, p: &Value) -> Result<Value> {
}
let kept = super::graph::capture_series_opacity(d, &both_kinds(&ids));
let painted = super::graph::capture_series_top_paints(d, &top_paint_changed(&before, d, &ids));
Ok(count_changed(d, &before, &ids) + usize::from(kept || painted))
let labels = super::graph::capture_label_rows(d, &ids);
Ok(count_changed(d, &before, &ids) + usize::from(kept || painted || labels))
})?;
s.active_appearance_item = None;
ok()
@@ -828,7 +1023,7 @@ fn set_item(s: &mut Session, p: &Value) -> Result<Value> {
check_numbers(p, &["weight", "opacity"], "appearance.setItem")?;
check_switches(p, &["visible"], "appearance.setItem")?;
let paint = paint_from(s, p)?;
let ids = appearance_targets(s, p)?;
let ids = row_targets(s, p)?;
if ids.is_empty() {
return Err(bad("appearance.setItem", "select objects or give ids"));
}
@@ -891,7 +1086,8 @@ fn set_item(s: &mut Session, p: &Value) -> Result<Value> {
let mut rows = top_paint_changed(&before, d, &ids);
rows.extend(painted_rows(d, written));
let painted = super::graph::capture_series_top_paints(d, &rows);
Ok(count_changed(d, &before, &ids) + usize::from(kept || painted))
let labels = super::graph::capture_label_rows(d, &ids);
Ok(count_changed(d, &before, &ids) + usize::from(kept || painted || labels))
})?;
if let Some(pa) = &paint {
s.remember_paint(pa);
@@ -937,7 +1133,8 @@ fn remove_item(s: &mut Session, p: &Value) -> Result<Value> {
}
let kept = super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &ids));
let painted = super::graph::capture_series_top_paints(d, &top_paint_changed(&before, d, &ids));
Ok(count_changed(d, &before, &ids) + usize::from(kept || painted))
let labels = super::graph::capture_label_rows(d, &ids);
Ok(count_changed(d, &before, &ids) + usize::from(kept || painted || labels))
})?;
// The rows removed from the active row's object, which need not come first in `ids`.
let active = s.active_appearance_item.as_ref().and_then(|a| a.objects.first().copied());
@@ -1021,6 +1218,7 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result<Value> {
let mut rows = top_paint_changed(&before, d, &ids);
rows.extend(painted_rows(d, added));
super::graph::capture_series_top_paints(d, &rows);
super::graph::capture_label_rows(d, &ids);
Ok(())
})?;
// Rows at or above each copy move up by one (by the block, for copies placed at `to`).
@@ -1039,7 +1237,7 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result<Value> {
/// `appearance.showAllHidden`: shows every hidden fill, stroke and effect of the selected objects.
fn show_all_hidden(s: &mut Session, p: &Value) -> Result<Value> {
let roots = require_targets(s, p, "appearance.showAllHidden")?;
let roots = require_whole_targets(s, p, "appearance.showAllHidden")?;
let before = s.doc()?.doc.clone();
let ids = s.edit("Show All Hidden Attributes", |d, _| {
let shown: Vec<NodeId> = roots
@@ -1060,6 +1258,7 @@ fn show_all_hidden(s: &mut Session, p: &Value) -> Result<Value> {
}
super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &shown));
super::graph::capture_series_top_paints(d, &top_paint_changed(&before, d, &shown));
super::graph::capture_label_rows(d, &shown);
Ok(shown)
})?;
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() }))
@@ -1069,11 +1268,16 @@ fn show_all_hidden(s: &mut Session, p: &Value) -> Result<Value> {
fn move_item(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "appearance.moveItem";
let to = index_param(p, "to", C)?;
let ids = require_targets(s, p, C)?;
let aligned = aligned(p, C)?;
if p.get("from").and_then(Value::as_str) == Some("contents") {
// A graph series group's own Contents row, not its paths, which have none.
let ids = edit_targets(s, p)?;
if ids.is_empty() {
return Err(bad(C, "select objects or give ids"));
}
return move_contents(s, &ids, to);
}
let ids = require_targets(s, p, C)?;
// Where an aligned row would go in each of several different stacks isn't one place.
if aligned && appearances_differ(&s.doc()?.doc, &ids) {
return Err(bad(C, "rows of objects whose appearances differ can't be reordered together"));
@@ -1100,7 +1304,8 @@ fn move_item(s: &mut Session, p: &Value) -> Result<Value> {
}
let kept = super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &ids));
let painted = super::graph::capture_series_top_paints(d, &top_paint_changed(&before, d, &ids));
Ok(count_changed(d, &before, &ids) + usize::from(kept || painted))
let labels = super::graph::capture_label_rows(d, &ids);
Ok(count_changed(d, &before, &ids) + usize::from(kept || painted || labels))
})?;
// The moved row stays the active one; the rows it passed shift by one.
s.remap_appearance_item(&ids, |a| {
@@ -1145,7 +1350,8 @@ fn move_items(s: &mut Session, p: &Value, ids: &[NodeId], to: usize) -> Result<V
}
let kept = super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, ids));
let painted = super::graph::capture_series_top_paints(d, &top_paint_changed(&before, d, ids));
Ok(count_changed(d, &before, ids) + usize::from(kept || painted))
let labels = super::graph::capture_label_rows(d, ids);
Ok(count_changed(d, &before, ids) + usize::from(kept || painted || labels))
})?;
let m = idx.len();
let landed = first_landed.unwrap_or(to);
@@ -1177,7 +1383,9 @@ fn move_contents(s: &mut Session, ids: &[NodeId], to: usize) -> Result<Value> {
slot.get_or_insert(n.appearance.contents_at());
}
slot.ok_or_else(|| bad("appearance.moveItem", "only groups, layers, type and images have a Contents (Characters) row"))?;
Ok(count_changed(d, &before, ids))
// A graph label's kind keeps where its rows paint relative to the characters.
let labels = super::graph::capture_label_rows(d, ids);
Ok(count_changed(d, &before, ids) + usize::from(labels))
})?;
Ok(json!({ "contents": slot }))
}
@@ -1265,6 +1473,7 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
(Some(clicked), leaf_targets(s, &selected)?)
};
targets.retain(|id| Some(*id) != source);
let mut targets = without_design_art(&s.doc()?.doc, targets, C)?;
let node = match source {
Some(id) => Arc::new(s.doc()?.doc.node(id).ok_or(EngineError::NoNode(id))?.clone()),
None => s.eyedropper_sample.clone().ok_or_else(|| bad(C, "select the object to copy from"))?,
@@ -1332,9 +1541,46 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
if (targets.is_empty() && ranges.is_empty()) || attrs.is_empty() {
return Ok(finish(s, &[]));
}
// What a graph keeps for the kind of a label whose whole text took the pick: the attributes the pick gave its
// characters, with a picked gradient fitted to each label, and the picked paragraph attributes.
let source_rows = picked.placed(None);
let kept_text = |id: NodeId, st: &mut CharStyle| {
Picked::run(st, &source_rows, &attrs, characters.get(&id));
if attrs.appearance.fill.color {
st.fill = super::gradient::unplaced(&st.fill);
}
if attrs.appearance.stroke.color {
st.stroke = super::gradient::unplaced(&st.stroke);
}
};
let kept_para = picked.text.as_ref().filter(|_| attrs.paragraph).map(|(_, para)| para);
// Only a pick that applies character attributes or the paints, overprint and stroke options characters take changes
// what a kind keeps for its characters.
let (f, k) = (attrs.appearance.fill, attrs.appearance.stroke);
let to_characters = (attrs.character && picked.text.is_some())
|| f.color
|| f.overprint
|| k.color
|| k.overprint
|| k.weight
|| k.cap
|| k.join
|| k.miter
|| k.dash;
let kept_text: Option<super::graph::LabelTextChange> = to_characters.then_some(&kept_text);
if !ranges.is_empty() {
let ids: Vec<NodeId> = ranges.iter().map(|(f, _)| *f).collect();
let before = s.doc()?.doc.clone();
// The labels whose whole text is highlighted.
let whole: Vec<NodeId> = ranges
.iter()
.filter(|(id, range)| match (range, before.node(*id).map(|n| &n.kind)) {
(None, _) => true,
(Some((start, end)), Some(NodeKind::Text(t))) => *start == 0 && *end >= vectorcraft_text::edit::runs_len(&t.runs),
_ => false,
})
.map(|(id, _)| *id)
.collect();
super::overprint::edit_counted(s, "Eyedropper", |d| {
for &(id, range) in &ranges {
let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) else { return Err(EngineError::NoNode(id)) };
@@ -1347,7 +1593,8 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
super::typecmd::refresh_bounds(t);
}
check_text_bounds(d)?;
Ok(count_changed(d, &before, &ids))
let labels = super::graph::capture_label_text(d, &whole, kept_text, kept_para)?;
Ok(count_changed(d, &before, &ids) + usize::from(labels))
})?;
return Ok(finish(s, &ids));
}
@@ -1365,17 +1612,19 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
let (fill, stroke) = (attrs.appearance.fill, attrs.appearance.stroke);
let source_has = |kind: bool| picked.appearance.items.iter().any(|it| it.is_fill() == kind);
let source_shows = |kind: bool| picked.appearance.items.iter().any(|it| it.is_fill() == kind && it.visible());
// A whole pick replaces the stack: it removes the rows of a kind the source has no row of.
let whole = fill == FillAttrs::ALL && stroke == StrokeAttrs::ALL;
let (paints, opacities) = if append {
let rows = (fill.color && source_shows(true), stroke.color && source_shows(false));
(rows, rows)
} else {
(
(fill.color, stroke.color || (stroke.weight && source_has(false))),
(fill.transparency && source_has(true), stroke.transparency && source_has(false)),
(fill.transparency && (whole || source_has(true)), stroke.transparency && (whole || source_has(false))),
)
};
// A pick of some attributes edits the topmost row of its kind, which may be hidden; `append` and a whole pick write rows.
let rows_written = append || (fill == FillAttrs::ALL && stroke == StrokeAttrs::ALL);
let rows_written = append || whole;
let top_shows = |id: NodeId, kind: bool| {
let items = d.node(id).map_or(&[][..], |n| &n.appearance.items[..]);
items.iter().rev().find(|it| it.is_fill() == kind).is_some_and(|it| it.visible())
@@ -1389,6 +1638,9 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
.collect()
};
let mut opacity_rows = top_opacity_changed(&before, d, &targets);
// A written row that had paint before the pick counts too when the pick left it without paint, as in
// `capture_series_writes`.
opacity_rows.extend(painted_rows(&before, written(opacities)));
opacity_rows.extend(painted_rows(d, written(opacities)));
let mut rows = top_paint_changed(&before, d, &targets);
rows.extend(painted_rows(d, written(paints)));
@@ -1397,7 +1649,17 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
// A pick of the object's transparency writes it on every target.
let objects = if attrs.appearance.transparency { targets.clone() } else { object_opacity_changed(&before, d, &targets) };
let object = super::graph::capture_series_object_opacity(d, &objects);
Ok(count_changed(d, &before, &targets) + usize::from(kept || painted || object))
// Graph labels keep their new rows, characters and paragraphs per kind of label.
// On type, only `append` adds rows and a transparency pick changes the object's opacity and blend mode; the other
// attributes go to the characters.
let rows = if append {
super::graph::capture_label_rows(d, &targets)
} else {
attrs.appearance.transparency && super::graph::capture_label_object_opacity(d, &targets)
};
// `append` adds rows and leaves the characters as they were.
let text = !append && super::graph::capture_label_text(d, &targets, kept_text, kept_para)?;
Ok(count_changed(d, &before, &targets) + usize::from(kept || painted || object || rows || text))
})?;
Ok(finish(s, &targets))
}
@@ -1430,6 +1692,7 @@ fn copied_character_styles<'a>(source: &Node, targets: impl Iterator<Item = &'a
local.baseline_shift /= scale.points;
local.tcy_up_down /= scale.points;
local.tcy_left_right /= scale.points;
local.warichu_gap /= scale.points;
local.h_scale /= scale.horizontal;
// As with dimensional type commands, reject overflow and underflow before layout.
if !copied_dimensions_fit(&effective, &local) {
@@ -1448,6 +1711,7 @@ fn copied_dimensions_fit(from: &CharStyle, to: &CharStyle) -> bool {
(from.baseline_shift, to.baseline_shift),
(from.tcy_up_down, to.tcy_up_down),
(from.tcy_left_right, to.tcy_left_right),
(from.warichu_gap, to.warichu_gap),
(from.h_scale, to.h_scale),
]
.iter()
+34 -7
View File
@@ -18,7 +18,7 @@ use vectorcraft_doc::{Appearance, AppearanceItem, CustomArrowhead, Document, Nod
use vectorcraft_geom::{Affine, FillRule, PathData, Point, SubPath};
use vectorcraft_pathops::BoolOp;
use super::{CommandSpec, Result, Session, always, bad, cmd};
use super::{CommandSpec, EngineError, Result, Session, always, bad, cmd};
/// The arrowheads file's name, in the folder of the preferences.
pub const FILE_NAME: &str = "Arrowheads.vectorcraft";
@@ -37,7 +37,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Arrowheads",
[],
None,
"{} → {arrowheads: [{name (stroke.set `startArrow`/`endArrow` as {custom: name}), reach, halfWidth (in head weights)}], file: the arrowheads file's path or null (no file here, as on the web), skipped: [{name, reason}] symbols of the file that are not heads, error: why the file could not be read, or null} the custom arrowheads, listed after the built-in ones in the Stroke panel's arrowhead menus",
"{} → {arrowheads: [{name (stroke.set `startArrow`/`endArrow` as {custom: name}), reach, halfWidth (in head weights)}], file: the arrowheads file's path or null (no file here, as on the web, or the file is outside the automation read roots), skipped: [{name, reason}] symbols of the file that are not heads, error: why the file could not be read (naming the file by its file name outside the read roots), or null} the custom arrowheads, listed after the built-in ones in the Stroke panel's arrowhead menus",
always,
list
),
@@ -46,7 +46,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Edit Arrowheads",
[],
None,
"{} open the arrowheads file (a native document next to the preferences; created first with one example head when it is missing). Each symbol in it is one custom arrowhead named after the symbol: it points right, its registration point is the tip, and its height is drawn as wide as the built-in heads; its visible fills and outlined strokes make the head. Saving the file reloads the heads → {path, created: whether the file was made now}",
"{} open the arrowheads file (a native document next to the preferences; created first with one example head when it is missing). Each symbol in it is one custom arrowhead named after the symbol: it points right, its registration point is the tip, and its height is drawn as wide as the built-in heads; its visible fills and outlined strokes make the head. Saving the file reloads the heads. Under automation read roots, a file outside them is an error, and nothing is made or opened → {path, created: whether the file was made now}",
has_file,
edit
),
@@ -55,7 +55,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Reload Arrowheads",
[],
None,
"{} read the arrowheads file again (a save of it from VectorCraft does this already) → {count, skipped: [{name, reason}]}",
"{} read the arrowheads file again (a save of it from VectorCraft does this already; under automation read roots, a file outside them is an error and is not read) → {count, skipped: [{name, reason}]}",
has_file,
reload
),
@@ -409,13 +409,36 @@ fn skipped(s: &Session) -> Vec<Value> {
s.arrowheads.skipped.iter().map(|(name, reason)| json!({"name": name, "reason": reason})).collect()
}
/// The arrowheads file at `path` checked for reading against the automation roots in force: an agent
/// confined to read roots reaches the file only inside them. The error names the file by its file
/// name outside them.
fn may_reach(path: &str) -> Result<()> {
crate::file_access::check_read(path).map_err(|e| super::fileio::naming_in_error(EngineError::Other(e), path))
}
/// `msg`, an error about the arrowheads file at `path`, as the request being served may see it: the
/// file named whole inside the read roots, else by its file name.
fn shown_error(msg: &str, path: Option<&str>) -> String {
let Some(path) = path else { return msg.to_string() };
match super::fileio::naming_in_error(EngineError::Other(msg.to_string()), path) {
EngineError::Other(m) => m,
e => e.to_string(),
}
}
fn list(s: &mut Session, _: &Value) -> Result<Value> {
let heads: Vec<Value> = s.arrowheads.heads.iter().map(|h| json!({"name": h.name, "reach": h.reach(), "halfWidth": h.half_width()})).collect();
Ok(json!({"arrowheads": heads, "file": s.arrowheads.path, "skipped": skipped(s), "error": s.arrowheads.error}))
let path = s.arrowheads.path.as_deref();
let file = path.filter(|p| crate::file_access::check_read(p).is_ok());
let error = s.arrowheads.error.as_deref().map(|e| shown_error(e, path));
Ok(json!({"arrowheads": heads, "file": file, "skipped": skipped(s), "error": error}))
}
fn reload(s: &mut Session, _: &Value) -> Result<Value> {
const C: &str = "stroke.arrowheads.reload";
if let Some(path) = &s.arrowheads.path {
may_reach(path)?;
}
s.reload_arrowheads();
if let Some(e) = &s.arrowheads.error {
return Err(bad(C, e.clone()));
@@ -426,8 +449,11 @@ fn reload(s: &mut Session, _: &Value) -> Result<Value> {
fn edit(s: &mut Session, _: &Value) -> Result<Value> {
const C: &str = "stroke.arrowheads.edit";
let path = s.arrowheads.path.clone().ok_or_else(|| bad(C, "no arrowheads file here"))?;
// Checked before anything is made, brought to the front or opened.
may_reach(&path)?;
if let Some(dir) = std::path::Path::new(&path).parent() {
std::fs::create_dir_all(dir).map_err(|e| bad(C, format!("{}: {e}", dir.display())))?;
let dir = dir.to_string_lossy();
std::fs::create_dir_all(&*dir).map_err(|e| super::fileio::naming_in_error(bad(C, format!("{dir}: {e}")), &dir))?;
}
// Made only when no file is there, also when another run makes one at the same moment.
let bytes = vectorcraft_format::save_file(&starter());
@@ -446,7 +472,8 @@ fn edit(s: &mut Session, _: &Value) -> Result<Value> {
s.set_active(i);
}
None => {
crate::file_access::unconfined(|| s.execute("document.open", &json!({ "path": path })))?;
// Opened in the request's own scope, so the document keeps the roots it was opened under.
s.execute("document.open", &json!({ "path": path }))?;
}
}
Ok(json!({"path": path, "created": created}))
+2 -2
View File
@@ -199,7 +199,7 @@ pub fn specs() -> Vec<CommandSpec> {
"New Symbol…",
[],
None,
"{name?, ids?|id?, registration?: 0..8 (9-point grid, 4 = centre; Symbol Options › Registration), exportType?: movieClip (default)|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static (default)|dynamic (Symbol Options › Symbol Type)} make a symbol from the selection and replace it with an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds; nineSlice is Symbol Options › Enable Guides for 9-Slice Scaling, nineSliceGuides [left, top, right, bottom] as fractions 0..1 of the natural size (default a quarter each); an instance of a symbol with guides keeps its corners' size when scaled, its edges stretch along their length and its center in both directions → {name, id, registration, exportType, nineSlice, type}",
"{name?, ids?|id?, registration?: 0..8 (9-point grid, 4 = centre; Symbol Options › Registration), exportType?: movieClip (default)|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static (default)|dynamic (Symbol Options › Symbol Type)} make a symbol from the selection and replace it with an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds; nineSlice is Symbol Options › Enable Guides for 9-Slice Scaling, nineSliceGuides [left, top, right, bottom] as fractions of the natural size in from each edge, each -16..16 (below 0 or above 1 puts a guide outside the art), with left + right < 1 and top + bottom < 1 (default a quarter each); an instance of a symbol with guides keeps its corners' size when scaled, its edges stretch along their length and its center in both directions → {name, id, registration, exportType, nineSlice, type}",
has_selection,
symbol_new
),
@@ -208,7 +208,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Symbol Options…",
[],
None,
"{name?, newName?, registration?: 0..8, exportType?: movieClip|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static|dynamic} rename a symbol (its instances and the graphics mapped onto 3D objects follow the new name) and/or set Symbol Options › Registration, Export Type, 9-slice guides (nineSliceGuides [left, top, right, bottom] fractions 0..1) and Symbol Type (a dynamic symbol's instances may change the appearance of objects in its art and stay linked; making it static drops those changes); default name: current → {name, registration, exportType, nineSlice, type}",
"{name?, newName?, registration?: 0..8, exportType?: movieClip|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static|dynamic} rename a symbol (its instances and the graphics mapped onto 3D objects follow the new name) and/or set Symbol Options › Registration, Export Type, 9-slice guides (nineSliceGuides [left, top, right, bottom] fractions in from each edge, each -16..16, with left + right < 1 and top + bottom < 1) and Symbol Type (a dynamic symbol's instances may change the appearance of objects in its art and stay linked; making it static drops those changes); default name: current → {name, registration, exportType, nineSlice, type}",
has_doc,
symbol_options
),
+9 -10
View File
@@ -47,21 +47,20 @@ fn export_type_param(p: &Value, cmd: &str) -> Result<Option<SymbolExportType>> {
}
/// `nineSlice` (bool) and `nineSliceGuides` ([left, top, right, bottom] fractions of the natural
/// size): `None` leaves the symbol alone, `Some(None)` turns 9-slice off, `Some(Some(g))` turns it
/// on with guides `g` (the symbol's current ones, else a quarter in from each edge, when none are
/// given).
/// size, below 0 or above 1 for a guide outside the art): `None` leaves the symbol alone,
/// `Some(None)` turns 9-slice off, `Some(Some(g))` turns it on with guides `g` (the symbol's
/// current ones, else a quarter in from each edge, when none are given).
fn nine_slice_param(p: &Value, cmd: &str, current: Option<SymbolNineSlice>) -> Result<Option<Option<SymbolNineSlice>>> {
let on = match p.get("nineSlice") {
None | Some(Value::Null) => None,
Some(v) => Some(v.as_bool().ok_or_else(|| bad(cmd, "nineSlice must be true or false"))?),
};
let guides =
match p.get("nineSliceGuides") {
None | Some(Value::Null) => None,
Some(v) => Some(SymbolNineSlice::from_value(v).ok_or_else(|| {
bad(cmd, "nineSliceGuides must be [left, top, right, bottom], each 0..1, with left + right < 1 and top + bottom < 1")
})?),
};
let guides = match p.get("nineSliceGuides") {
None | Some(Value::Null) => None,
Some(v) => Some(SymbolNineSlice::from_value(v).ok_or_else(|| {
bad(cmd, "nineSliceGuides must be [left, top, right, bottom], each -16..16, with left + right < 1 and top + bottom < 1")
})?),
};
Ok(match (on, guides) {
(Some(false), _) => Some(None),
(None, None) => None,
+5 -5
View File
@@ -72,7 +72,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Make",
["Object", "Live Paint"],
Some("Cmd+Alt+X"),
"{ids?|id?} build a Live Paint group from the selected paths (paths, compound paths and groups of them; type, images and other objects are refused, nothing changes); each covered face starts with its front-most covering source's fill; with a Live Paint group among them, add the others to it as livePaint.merge does → {id, faces, edges}",
"{ids?|id?} build a Live Paint group from the selected paths (paths, compound paths and groups of them; type, images and other objects are refused, nothing changes); each covered face starts with its front-most covering source's fill; with a Live Paint group among them, add the others to it as livePaint.merge does; a Live Paint group alone has nothing to add, so it is selected and nothing changes (no undo step) → {id, faces, edges}",
has_selection_or_ids,
lp_make
),
@@ -81,7 +81,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Merge",
["Object", "Live Paint"],
None,
"{ids?|id?} add the other selected paths (compound paths, groups of paths and Live Paint groups too; type, images and other objects are refused, nothing changes) to the bottom-most Live Paint group, keeping its id, its paint and its own properties (name, lock, visibility, transparency, appearance, opacity mask, graphic style link) → {id, faces, edges}",
"{ids?|id?} add the other selected paths (compound paths, groups of paths and Live Paint groups too; type, images and other objects are refused, nothing changes) to the bottom-most Live Paint group, keeping its id, its paint and its own properties (name, lock, visibility, transparency, appearance, opacity mask, graphic style link); a Live Paint group alone has nothing to add, so it is selected and nothing changes (no undo step) → {id, faces, edges}",
has_multi_or_ids,
lp_merge
),
@@ -108,7 +108,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Gap Options",
[],
None,
"{id?, ids?: [id…] (instead of id; default: the selected Live Paint groups), detect?: bool (Gap Detection: paint stops at gaps up to size wide), size?: \"small\" (3 pt) | \"medium\" (6 pt) | \"large\" (12 pt) | pt (custom, over 0 up to 72) (Paint Stops At), color?: #rrggbb or a layer color's name such as \"Red\" (Gap Preview Color; a hex color with an alpha part, #rrggbbaa or #rgba, is an error), closeGaps?: bool (add an unpainted path across each gap up to size wide to the group's paths)} set the Gap Options of Live Paint groups (what is not given stays as it was; a group starts with detect false, small and Red) and make their faces again, keeping their paint → {ids, faces, gaps: [[x0,y0,x1,y1]…] (the gaps up to size wide that no path closes, from a loose end of a path to where it closes to; detect closes them for paint), closed (paths added)}",
"{id?, ids?: [id…] (instead of id; default: the selected Live Paint groups), detect?: bool (Gap Detection: paint stops at gaps up to size wide), size?: \"small\" (3 pt) | \"medium\" (6 pt) | \"large\" (12 pt) | pt (custom, over 0 up to 72) (Paint Stops At), color?: #rrggbb or a layer color's name such as \"Red\" (Gap Preview Color; a hex color with an alpha part, #rrggbbaa or #rgba, is an error), closeGaps?: bool (add an unpainted path across each gap up to size wide to the group's paths)} set the Gap Options of Live Paint groups (what is not given stays as it was; a group starts with detect false, small and Red) and make their faces again, keeping their paint; when every group already has the options and closeGaps finds no gap, nothing changes (no undo step) → {ids, faces, gaps: [[x0,y0,x1,y1]…] (the gaps up to size wide that no path closes, from a loose end of a path to where it closes to; detect closes them for paint), closed (paths added)}",
has_selection_or_ids,
lp_gap_options
),
@@ -117,7 +117,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Live Paint Bucket",
[],
None,
"{group?: id | ids?|id?: [id…] (paths to make live first, as livePaint.make does), point: [x,y], points?: [[x,y]…] (a drag polyline starting at point; 1 to 4096 finite canvas points; fills every crossed face of the same group), continuation?: [[[x,y]…]…] (further path chunks of 1 to 4096 finite canvas points each; each starts at the preceding chunk's last point; requires points), color?|swatch?|gradient?|none? (default: current fill; a color in #rrggbbaa or #rgba is refused), tint?: 0..100, keepModel?: bool (both as paint.setFill)} fill the face containing point, skipping hidden faces → {group, face}",
"{group?: id | ids?|id?: [id…] (paths to make live first, as livePaint.make does), point: [x,y], points?: [[x,y]…] (a drag polyline starting at point; 1 to 4096 finite canvas points; fills every crossed face of the same group), continuation?: [[[x,y]…]…] (further path chunks of 1 to 4096 finite canvas points each; each starts at the preceding chunk's last point; requires points), color?|swatch?|gradient?|none? (default: current fill; a color in #rrggbbaa or #rgba is refused), tint?: 0..100, keepModel?: bool (both as paint.setFill)} fill the face containing point, skipping hidden faces; when every face it reaches already has the paint, nothing changes (no undo step, and the recent colors stay as they are) → {group, face}",
has_doc,
lp_fill
),
@@ -126,7 +126,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Live Paint Bucket (Stroke)",
[],
None,
"{group: id, point: [x,y], color?|swatch?|none? (default: current stroke), width?: pt (default: current weight), tolerance?: pt (4), tint?: 0..100, keepModel?: bool (both as paint.setFill)} paint the edge nearest point → {group, edge}",
"{group: id, point: [x,y], color?|swatch?|none? (default: current stroke), width?: pt (default: current weight), tolerance?: pt (4), tint?: 0..100, keepModel?: bool (both as paint.setFill)} paint the edge nearest point; when it already has the paint and the width, nothing changes (no undo step, and the recent colors stay as they are) → {group, edge}",
has_doc,
lp_stroke_edge
),
+135 -33
View File
@@ -52,8 +52,34 @@ fn make_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId]) -> Result<
Ok((gid, nf, ne))
}
/// Select `ids` alone, without an undo step, when they are not selected that way already.
fn select_only(s: &mut Session, ids: &[NodeId]) -> Result<()> {
let st = s.doc()?;
let mut sel = st.selection.clone();
sel.set(ids.iter().copied());
if sel != st.selection {
s.select(|_, selection| *selection = sel)?;
}
Ok(())
}
/// Make or Merge given one Live Paint group and nothing else has nothing to add to it, so it leaves
/// the document as it is, records no undo step and selects the group: → its reply. `None` for any
/// other `roots`.
fn lone_live_group(s: &mut Session, roots: &[NodeId]) -> Result<Option<Value>> {
let d = &s.doc()?.doc;
let Some(&g) = roots.first().filter(|g| roots.iter().all(|r| r == *g)) else { return Ok(None) };
let Some(n) = d.node(g).filter(|n| is_live_paint(n)) else { return Ok(None) };
let reply = json!({ "id": g.0, "faces": b::faces(n).len(), "edges": b::edges(n).len() });
select_only(s, &[g])?;
Ok(Some(reply))
}
pub(super) fn lp_make(s: &mut Session, p: &Value) -> Result<Value> {
let roots = root_ids(s, p)?;
if let Some(reply) = lone_live_group(s, &roots)? {
return Ok(reply);
}
let (id, faces, edges) = s.edit("Make Live Paint", |d, sel| make_live(d, sel, &roots))?;
Ok(json!({ "id": id.0, "faces": faces, "edges": edges }))
}
@@ -130,6 +156,9 @@ fn merge_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId]) -> Result
pub(super) fn lp_merge(s: &mut Session, p: &Value) -> Result<Value> {
let roots = root_ids(s, p)?;
if let Some(reply) = lone_live_group(s, &roots)? {
return Ok(reply);
}
let (id, faces, edges) = s.edit("Merge Live Paint", |d, sel| merge_live(d, sel, &roots))?;
Ok(json!({ "id": id.0, "faces": faces, "edges": edges }))
}
@@ -230,27 +259,58 @@ pub(super) fn lp_gap_options(s: &mut Session, p: &Value) -> Result<Value> {
};
let close = switch_or(p, "closeGaps", false, C)?;
let targets = live_targets(s, p)?;
let with_params = |mut options: GapOptions| {
options.detect = detect.unwrap_or(options.detect);
options.size = size.unwrap_or(options.size);
options.color = color.unwrap_or(options.color);
options
};
// When every group already has these options and Close Gaps With Paths has no gap to close,
// nothing changes: no undo step, and the reply is the same.
let unchanged = {
let d = &s.doc()?.doc;
let (mut faces, mut gaps, mut same) = (0, vec![], true);
for g in &targets {
let old = d.node(*g).ok_or(EngineError::NoNode(*g))?;
let options = old.gap_options();
if with_params(options) != options {
same = false;
break;
}
let open = open_gaps(old, options);
if close && !open.is_empty() {
same = false;
break;
}
faces += b::faces(old).len();
gaps.extend(open);
}
same.then_some((faces, gaps))
};
if let Some((faces, gaps)) = unchanged {
select_only(s, &targets)?;
return Ok(json!({ "ids": ids_json(&targets), "faces": faces, "gaps": gaps_json(&gaps), "closed": 0 }));
}
let (faces, gaps, closed) = s.edit("Gap Options", |d, sel| {
let (mut faces, mut gaps, mut closed) = (0, vec![], 0);
let mut changed = Beside::replacing(d, &targets);
for g in &targets {
let old = d.node(*g).cloned().ok_or(EngineError::NoNode(*g))?;
let mut options = old.gap_options();
options.detect = detect.unwrap_or(options.detect);
options.size = size.unwrap_or(options.size);
options.color = color.unwrap_or(options.color);
let options = with_params(old.gap_options());
let mut sources = source_nodes(&old);
let mut added = 0;
if close {
// Close Gaps With Paths adds an unpainted line across each gap to the group's paths.
for gap in po::find_gaps(&source_shapes(&sources).0, options.size.points()) {
let line = PathData::single(SubPath::polyline(&gap, false));
sources.push(Arc::new(Node::path(d.alloc_id(), line, Appearance::default())));
closed += 1;
added += 1;
}
}
closed += added;
let mut n = old.clone();
// The faces change only with what paint stops at, or with new paths.
if close || options.max_gap() != old.gap_options().max_gap() {
if added > 0 || options.max_gap() != old.gap_options().max_gap() {
let (children, _, _) = build_children(d, sources, options.max_gap())?;
if let Some(ch) = n.children_mut() {
*ch = children;
@@ -305,27 +365,9 @@ pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result<Value> {
let paint = paint_from(s, p)?.unwrap_or_else(|| s.paint.fill.clone());
let group = object_param(p, "group", C)?;
let roots = if group.is_none() { root_ids(s, p)? } else { vec![] };
let (g, face) = s.edit("Live Paint Bucket", |d, sel| {
let gid = match group {
Some(g) => {
if !d.node(g).is_some_and(is_live_paint) {
return Err(bad(C, format!("{g} is not a Live Paint group")));
}
g
}
None => {
let live_at = |face: fn(&Node, Point) -> Option<&Arc<Node>>| {
roots.iter().copied().find(|r| d.node(*r).is_some_and(|n| is_live_paint(n) && face(n, pt).is_some()))
};
match (live_at(b::visible_face_at), live_at(face_at)) {
(Some(g), _) => g,
// At a point on a hidden face of a Live Paint group among the objects, the command returns an error
// and does not merge the objects.
(None, Some(_)) => return Err(EngineError::Other("no Live Paint face at that point".into())),
(None, None) => make_live(d, sel, &roots)?.0,
}
}
};
// The faces the click or drag paints in Live Paint group `gid`: the visible face at the point,
// and every visible face the drag crosses; → (the face at the point, the faces).
let targets_in = |d: &Document, gid: NodeId| -> Result<(NodeId, std::collections::BTreeSet<NodeId>)> {
let fid = d
.node(gid)
.and_then(|n| b::visible_face_at(n, pt))
@@ -355,11 +397,58 @@ pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result<Value> {
targets.extend(map.hits_along(&chunk, None).regions.iter().filter_map(|i| face_ids.get(*i).copied()));
}
}
for target in targets {
d.node_mut(target).ok_or(EngineError::NoNode(target))?.appearance.set_fill(paint.clone());
Ok((fid, targets))
};
// The Live Paint group the fill paints; `None` when the objects are made into one first.
let live = {
let d = &s.doc()?.doc;
match group {
Some(g) => {
if !d.node(g).is_some_and(is_live_paint) {
return Err(bad(C, format!("{g} is not a Live Paint group")));
}
Some(g)
}
None => {
let live_at = |face: fn(&Node, Point) -> Option<&Arc<Node>>| {
roots.iter().copied().find(|r| d.node(*r).is_some_and(|n| is_live_paint(n) && face(n, pt).is_some()))
};
match (live_at(b::visible_face_at), live_at(face_at)) {
(Some(g), _) => Some(g),
// At a point on a hidden face of a Live Paint group among the objects, the command returns an error
// and does not merge the objects.
(None, Some(_)) => return Err(EngineError::Other("no Live Paint face at that point".into())),
(None, None) => None,
}
}
}
Ok((gid, fid))
})?;
};
let (g, face) = match live {
Some(gid) => {
let (fid, targets) = targets_in(&s.doc()?.doc, gid)?;
// Faces that already have the paint stay as they are: when every face has it, nothing
// changes and no undo step is recorded.
let d = &s.doc()?.doc;
let unpainted: Vec<NodeId> = targets.into_iter().filter(|t| d.node(*t).is_none_or(|f| f.appearance.fill_paint() != paint)).collect();
if unpainted.is_empty() {
return Ok(json!({ "group": gid.0, "face": fid.0 }));
}
s.edit("Live Paint Bucket", |d, _| {
for target in unpainted {
d.node_mut(target).ok_or(EngineError::NoNode(target))?.appearance.set_fill(paint.clone());
}
Ok((gid, fid))
})?
}
None => s.edit("Live Paint Bucket", |d, sel| {
let gid = make_live(d, sel, &roots)?.0;
let (fid, targets) = targets_in(d, gid)?;
for target in targets {
d.node_mut(target).ok_or(EngineError::NoNode(target))?.appearance.set_fill(paint.clone());
}
Ok((gid, fid))
})?,
};
s.remember_paint(&paint);
Ok(json!({ "group": g.0, "face": face.0 }))
}
@@ -375,9 +464,22 @@ pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(C, "width out of range"));
}
let tol = number_or(p, "tolerance", 4.0, C)?.clamp(0.0, 1000.0);
let edge = s.edit("Live Paint Bucket", |d, _| {
let (eid, unchanged) = {
let d = &s.doc()?.doc;
let n = d.node(g).filter(|n| is_live_paint(n)).ok_or_else(|| bad(C, format!("{g} is not a Live Paint group")))?;
let eid = b::visible_edge_near(n, pt, tol).map(|e| e.id).ok_or_else(|| EngineError::Other("no Live Paint edge near that point".into()))?;
let e = b::visible_edge_near(n, pt, tol).ok_or_else(|| EngineError::Other("no Live Paint edge near that point".into()))?;
// An edge that already has the paint and the width (or has no stroke and gets none) stays as
// it is, and no undo step is recorded.
let unchanged = match e.appearance.stroke() {
Some(st) => st.paint == paint && st.width == width,
None => paint.is_none(),
};
(e.id, unchanged)
};
if unchanged {
return Ok(json!({ "group": g.0, "edge": eid.0 }));
}
let edge = s.edit("Live Paint Bucket", |d, _| {
let e = d.node_mut(eid).ok_or(EngineError::NoNode(eid))?;
e.appearance.set_stroke(paint.clone());
if let Some(st) = e.appearance.stroke_mut() {
+17 -13
View File
@@ -527,8 +527,9 @@ fn color_groups(cmd: &str, d: &mut Document, items: Vec<Arc<Node>>) -> Result<Ve
}
/// What a trace depends on: the object traced (an image, or an Image Trace object traced again),
/// its image, and the settings it is traced with. The tracer makes the same paths of the same
/// inputs, so a trace made away from the command ([`TraceRun`]) stands in for the command's own.
/// its image, the image's encoded bytes, and the settings it is traced with. The tracer makes the
/// same paths of the same inputs, so a trace made away from the command ([`TraceRun`]) stands in
/// for the command's own.
#[derive(Clone, Debug, PartialEq)]
struct TraceInputs {
target: NodeId,
@@ -538,6 +539,9 @@ struct TraceInputs {
/// Document Library: the library's colours, which the JSON leaves out
/// ([`tr::TraceParams::swatches`]).
swatches: Vec<[u8; 3]>,
/// The encoded image the tracer decodes: the blob under the image's key, shared with the
/// document. Two blobs are equal when they are the same allocation or hold the same bytes.
bytes: Arc<Vec<u8>>,
}
/// What `imageTrace.make` and `imageTrace.makeAndExpand` take from the session before they trace.
@@ -549,7 +553,6 @@ struct Prepared {
params_json: Value,
preset_label: String,
library: Vec<([u8; 3], Paint)>,
bytes: Arc<Vec<u8>>,
}
/// What command `c` with params `p` traces, and how, from the session: everything but the trace.
@@ -597,8 +600,8 @@ fn prepare(s: &Session, c: &str, p: &Value) -> Result<Prepared> {
let bytes = Arc::clone(&blob.bytes);
let library = trace_library(c, s, &mut params)?;
let traced_with = serde_json::to_value(&params).map_err(|e| EngineError::Other(e.to_string()))?;
let inputs = TraceInputs { target, image, params: traced_with, swatches: params.swatches.clone() };
Ok(Prepared { inputs, trace: params, view, params_json, preset_label, library, bytes })
let inputs = TraceInputs { target, image, params: traced_with, swatches: params.swatches.clone(), bytes };
Ok(Prepared { inputs, trace: params, view, params_json, preset_label, library })
}
/// What a trace made of an image: the size in pixels it was decoded at, and the paths.
@@ -616,11 +619,11 @@ impl Traced {
}
}
/// Decode the image `bytes` and trace it with `params`, telling `steps` how far it has got
/// ([`tr::trace_watched`]); [`EngineError::Cancelled`] once `steps` answers `false`.
fn trace_now(inputs: &TraceInputs, params: &tr::TraceParams, bytes: &[u8], steps: &(dyn Fn(u64, u64) -> bool + Sync)) -> Result<Traced> {
/// Decode the image bytes of `inputs` and trace them with `params`, telling `steps` how far it has
/// got ([`tr::trace_watched`]); [`EngineError::Cancelled`] once `steps` answers `false`.
fn trace_now(inputs: &TraceInputs, params: &tr::TraceParams, steps: &(dyn Fn(u64, u64) -> bool + Sync)) -> Result<Traced> {
// An image over the tracer's size is traced scaled down (the paths are scaled back).
let raster = tr::Raster::decode_to_fit(bytes).map_err(|e| EngineError::Other(e.to_string()))?;
let raster = tr::Raster::decode_to_fit(&inputs.bytes).map_err(|e| EngineError::Other(e.to_string()))?;
if !steps(0, 0) {
return Err(EngineError::Cancelled);
}
@@ -682,7 +685,8 @@ impl TraceRun {
(self.prepared.inputs.image.width, self.prepared.inputs.image.height)
}
/// Does it still apply: would the command trace the same object, image and settings now?
/// Does it still apply: would the command trace the same object, image, pixels and settings
/// now?
pub fn current(&self, s: &Session) -> bool {
prepare(s, self.command, &self.params).is_ok_and(|now| now.inputs == self.prepared.inputs)
}
@@ -691,13 +695,13 @@ impl TraceRun {
/// failed or stopped ([`EngineError::Cancelled`] once `steps` answers `false`). It touches no
/// document, so it can run on any thread.
pub fn run(&self, steps: &(dyn Fn(u64, u64) -> bool + Sync)) -> Result<Traced> {
trace_now(&self.prepared.inputs, &self.prepared.trace, &self.prepared.bytes, steps)
trace_now(&self.prepared.inputs, &self.prepared.trace, steps)
}
}
pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Value> {
let c = if expand { "imageTrace.makeAndExpand" } else { "imageTrace.make" };
let Prepared { inputs, trace, view, params_json, preset_label, library, bytes } = prepare(s, c, p)?;
let Prepared { inputs, trace, view, params_json, preset_label, library } = prepare(s, c, p)?;
let group_by_color = expand && by_color_param(c, p)?;
// A saved preset's settings join the journal entry, so a replay traces as this run did after
// the preset is changed, renamed or deleted.
@@ -709,7 +713,7 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
// A trace handed in for these very inputs ([`TraceRun`]), else one made now.
let Traced { raster, res, .. } = match s.trace_hand_off.take() {
Some(traced) if traced.inputs == inputs => traced,
_ => trace_now(&inputs, &trace, &bytes, &|_, _| true)?,
_ => trace_now(&inputs, &trace, &|_, _| true)?,
};
let TraceInputs { target, image: img, .. } = inputs;
let mut warnings = keep_warnings(&trace, &res);
+31 -11
View File
@@ -88,8 +88,9 @@ pub struct Clipboard {
/// The artboard the objects were copied from (none when they lie on no artboard; the first of
/// [`Self::artboards`] when there are any): Paste on All Artboards keeps their offset to it.
pub source_artboard: Option<Rect>,
/// Per object: the name of the layer it was copied from (Paste Remembers Layers).
pub source_layers: Vec<Option<String>>,
/// Per object: the layer or sublayer it was copied from and the layers around it (Paste
/// Remembers Layers); none when that layer has no name.
pub source_layers: Vec<Option<SourceLayer>>,
/// The open document the objects came from ([`DocState::uid`]): pasting back into it uses its
/// own resources as they are now.
pub source_doc: Option<u64>,
@@ -101,6 +102,29 @@ pub struct Clipboard {
pub guides: Vec<vectorcraft_doc::Guide>,
}
/// The layer an object was copied from, as Paste Remembers Layers finds it again: the top-level
/// layer first, down to the layer or sublayer that holds the object.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct SourceLayer {
/// The layers' ids in the source document ([`Clipboard::source_doc`]).
pub ids: Vec<NodeId>,
/// The layers' names (an unnamed layer above the one that holds the object is "").
pub names: Vec<String>,
}
impl SourceLayer {
/// The layers around the object `anc` ends with ([`Document::ancestry`]); none when the layer
/// that holds it has no name.
fn of(d: &Document, anc: &[NodeId]) -> Option<Self> {
let layers: Vec<&Node> = anc.iter().rev().skip(1).filter_map(|a| d.node(*a).filter(|l| l.is_layer())).collect();
layers.first()?.name.as_ref()?;
Some(Self {
ids: layers.iter().rev().map(|l| l.id).collect(),
names: layers.iter().rev().map(|l| l.name.clone().unwrap_or_default()).collect(),
})
}
}
/// Indices of segments selected on `sp` (either explicitly or via incident anchors).
pub(crate) fn subpath_selected_segments(
sp: &vectorcraft_geom::SubPath,
@@ -119,17 +143,13 @@ pub(crate) fn subpath_selected_segments(
let has_explicit_segs = seg_refs.is_some_and(|segments| !segments.is_empty());
if has_explicit_segs {
if let Some(segments) = seg_refs {
for &(s, seg) in segments {
if s == si && seg < seg_count {
selected_segs.insert(seg);
}
}
selected_segs.extend(super::path::subpath_refs(segments, si).filter(|&seg| seg < seg_count));
}
return selected_segs;
}
if let Some(anchors) = anchor_refs {
let sub_anchors: BTreeSet<usize> = anchors.iter().filter_map(|&(s, a)| (s == si && a < n).then_some(a)).collect();
let sub_anchors: BTreeSet<usize> = super::path::subpath_refs(anchors, si).filter(|&a| a < n).collect();
if !sub_anchors.is_empty() {
for i in 0..seg_count {
let next = (i + 1) % n;
@@ -256,7 +276,7 @@ impl Clipboard {
let mut compound_bounds: std::collections::HashMap<NodeId, Option<vectorcraft_geom::Rect>> = std::collections::HashMap::new();
for id in roots {
let (Some(n), Some(anc)) = (d.node(*id), d.ancestry(*id)) else { continue };
let layer_name = anc.iter().rev().skip(1).find_map(|a| d.node(*a).filter(|l| l.is_layer())).and_then(|l| l.name.clone());
let source_layer = SourceLayer::of(d, &anc);
let compound_parent = anc.iter().rev().skip(1).find_map(|a| d.node(*a).filter(|p| matches!(p.kind, NodeKind::Compound { .. })));
// Gradients fitted to the compound's bounds are pinned there, as a split pins them.
let gradient_box = compound_parent
@@ -299,11 +319,11 @@ impl Clipboard {
if direct && let Some(pieces) = extract_direct_selection(n, &st.selection) {
for piece in pieces {
nodes.push(inherit_appearance(piece));
source_layers.push(layer_name.clone());
source_layers.push(source_layer.clone());
}
} else {
nodes.push(inherit_appearance(n.clone()));
source_layers.push(layer_name);
source_layers.push(source_layer);
}
}
// Symbol instances are measured by their art.
@@ -123,6 +123,10 @@ fn node_refs(n: &Node, f: Visit) {
if let Some(mask) = &m.extras().mask {
node_refs(&mask.art, f);
}
// A color-masked image's masked pixels go with it.
if let Some(cm) = Document::color_mask_of(m) {
f(Ref::Name(Res::Image, &cm.key));
}
match &m.kind {
NodeKind::Text(t) => {
for r in &t.runs {
@@ -663,6 +667,10 @@ impl Relink {
if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) {
self.node(Arc::make_mut(&mut m.art));
}
if let Some(cm) = n.extras_if_any().and_then(|e| e.color_mask.as_deref_mut()) {
self.name(Res::Image, &mut cm.key);
self.name(Res::Image, &mut cm.from);
}
match &mut n.kind {
NodeKind::Text(t) => {
for r in &mut t.runs {
+258 -15
View File
@@ -3,7 +3,11 @@
//! shared colour visitor [`Recolor`]: fills and strokes (solid colours, gradient stops and text
//! runs), gradient meshes, embedded images and pattern fills. Colours linked to a global swatch are
//! unlinked when they change; Adjust Color Balance's Global mode shifts their tints instead.
//!
//! Convert to Indexed Color uses the same visitor for embedded images only, and stores each one as
//! a palette PNG.
use std::cell::Cell;
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
@@ -15,7 +19,9 @@ use vectorcraft_doc::live::lerp_color;
use vectorcraft_doc::pattern::PatternDef;
pub(crate) use vectorcraft_doc::recolor::map_paint;
use vectorcraft_doc::recolor::{ColorVisitor, Reach, map_links, recolor_node};
use vectorcraft_doc::{Document, ImageBlob, Node, NodeId, NodeKind};
use vectorcraft_doc::{Document, ImageBlob, MAX_RASTER_ALLOC, Node, NodeId, NodeKind};
use vectorcraft_render::encode::png::{PngOptions, encode_indexed};
use vectorcraft_render::encode::quantize::{Dither, Indexed, PaletteOptions, Reduction, quantize, quantize_to};
use super::edit::selected_roots;
use super::{
@@ -30,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Invert Colors",
["Edit", "Edit Colors"],
None,
"{fill?: true, stroke?: true, includeImages?: true, includePatterns?: true, ids?} replace each colour by its RGB inverse (keeps the colour model) in fills, strokes, text, gradient meshes (with fills), colorized image fills (their pixels stay unchanged), other embedded images (a recoloured copy) and pattern tiles (a new pattern swatch; the original stays), as one undo step → {changed, notChanged: {locked, hidden} (when the selection is everything select.all takes: the locked and hidden objects it left out whose colors would have changed; an object both hidden and locked counts as hidden), warning?: set when notChanged counts any object}",
"{fill?: true, stroke?: true, includeImages?: true, includePatterns?: true, ids?} replace each colour by its RGB inverse (keeps the colour model) in fills, strokes, text, gradient meshes (with fills), colorized image fills (their pixels stay unchanged), other embedded images (a recoloured copy) and pattern tiles (a new pattern swatch; the original stays), as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke (docs/mcp.md) → {changed, notChanged: {locked, hidden} (when the selection is everything select.all takes: the locked and hidden objects it left out whose colors would have changed; an object both hidden and locked counts as hidden), warning?: set when notChanged counts any object}",
has_selection,
|s, p| recolor(s, p, "edit.colors.invert", "Invert Colors", &invert)
),
@@ -66,6 +72,15 @@ pub fn specs() -> Vec<CommandSpec> {
})
}
),
cmd!(
"edit.colors.toIndexed",
"Convert to Indexed Color…",
["Edit", "Edit Colors"],
None,
"{reduction?: \"selective\" (default)|\"perceptual\"|\"adaptive\"|\"web\"|\"gray\"|\"blackWhite\" (chosen as for a PNG-8 export)|\"uniform\" (evenly spaced levels of red, green and blue: the most levels, 2 to 6, whose cube fits in `colors` with one entry left for transparency)|\"document\" (the colors of the document's swatches, at most 255), colors?: 2..256 (default 256; the most palette entries, the transparent one included; at least 9 for uniform; refused for blackWhite and document), dither?: \"diffusion\" (default)|\"pattern\"|\"noise\"|\"none\", ditherAmount?: 0..100 (default 100), ids?} store each embedded image in the selection (in groups too) as an indexed-color PNG: a palette of at most 256 RGB colors, each pixel the index of one; pixels under half opacity become one transparent entry and the others opaque, keeping their color; linked images, colorized images and the images of color glyphs in outlined type keep their pixels; each image changed becomes a new image, one undo step for all; an image that is an indexed PNG already and would show the same pixels is left as it is, and no undo step is recorded when no image changes; an image of more than 134,217,728 pixels (33,554,432 in the web app) is refused with an error and nothing changes; reduction and dither ids are read as for a PNG-8 export, ignoring case → {changed: images changed, notChanged: the locked and hidden objects Select All left out that hold an image that is not an indexed PNG yet, warning?} (as edit.colors.invert)",
has_selection,
to_indexed
),
cmd!(
"edit.colors.saturate",
"Saturate…",
@@ -89,7 +104,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Blend Front to Back",
["Edit", "Edit Colors"],
None,
"{} ≥3 filled objects (solid fills or gradient meshes, which keep their shading): intermediate fills graded between the frontmost and backmost fill → {changed}",
"{} ≥3 filled objects (solid fills or gradient meshes, which keep their shading): intermediate fills graded between the frontmost and backmost fill. On a path directly in a graph series, the graph also stores the new fill, as for the other Blend commands (docs/mcp.md); no undo step when no fill changes → {changed}",
has_selection,
|s, _| blend(s, BlendOrder::Stack)
),
@@ -98,7 +113,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Blend Horizontally",
["Edit", "Edit Colors"],
None,
"{} ≥3 filled objects or meshes: fills graded between the leftmost and rightmost → {changed}",
"{} ≥3 filled objects or meshes: fills graded between the leftmost and rightmost; no undo step when no fill changes → {changed}",
has_selection,
|s, _| blend(s, BlendOrder::Horizontal)
),
@@ -107,7 +122,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Blend Vertically",
["Edit", "Edit Colors"],
None,
"{} ≥3 filled objects or meshes: fills graded between the topmost and bottommost → {changed}",
"{} ≥3 filled objects or meshes: fills graded between the topmost and bottommost; no undo step when no fill changes → {changed}",
has_selection,
|s, _| blend(s, BlendOrder::Vertical)
),
@@ -149,6 +164,13 @@ fn gray_level(c: Color) -> f32 {
/// gradient stop): `(colour, link, tint)`, true when it changed them.
pub(crate) type LinkMap<'a> = dyn Fn(&mut Color, &mut Option<String>, &mut f32) -> bool + 'a;
/// What a pass that remakes whole images makes of one: its new copy, `None` when it stays as it is.
type Remake<'a> = dyn Fn(&ImageBlob) -> Option<ImageBlob> + 'a;
/// The objects a pass recolors, and the locked and hidden objects the selection left out, each
/// with whether it is hidden ([`pass_targets`]).
type Targets = (Vec<NodeId>, Vec<(NodeId, bool)>);
/// The identity colour map (a pass that only maps linked colours).
fn same(c: Color) -> Color {
c
@@ -191,6 +213,8 @@ pub(crate) struct Recolor<'a> {
scope: Scope,
/// Recolored images are stored with one gray channel ([`ImageBlob::map_gray`]).
gray_images: bool,
/// Makes each embedded image's new copy in place of `f` (`None`: it stays as it is).
remake: Option<&'a Remake<'a>>,
/// Image key → the key of its recoloured copy (`None`: unchanged).
images: HashMap<String, Option<String>>,
/// Pattern name → the name of its recoloured copy (`None`: unchanged, or being recoloured).
@@ -207,6 +231,7 @@ impl<'a> Recolor<'a> {
links: None,
scope,
gray_images: false,
remake: None,
images: HashMap::new(),
patterns: HashMap::new(),
new_images: vec![],
@@ -229,7 +254,7 @@ impl<'a> Recolor<'a> {
/// A pass that maps colors as this one does, with nothing recolored yet.
fn again(&self) -> Self {
Self { links: self.links, gray_images: self.gray_images, ..Self::new(self.scope, self.f) }
Self { links: self.links, gray_images: self.gray_images, remake: self.remake, ..Self::new(self.scope, self.f) }
}
/// The entries of `objects` (ids, each with a flag) whose object this pass would change, other
@@ -328,7 +353,9 @@ impl<'a> Recolor<'a> {
}
let f = self.f;
let blob = d.images.get(key)?;
let new = if self.gray_images {
let new = if let Some(remake) = self.remake {
remake(blob)
} else if self.gray_images {
blob.map_gray(|[r, g, b]| f(Color::rgb8(r, g, b)).to_rgba8(1.0)[0])
} else {
blob.map_rgb(|[r, g, b]| {
@@ -430,8 +457,8 @@ pub(crate) fn recolor_links(s: &mut Session, p: &Value, cmd: &str, label: &str,
run_pass(s, p, cmd, label, Recolor::with_links(Scope::of(p, cmd)?, f, links))
}
/// Run `pass` on the `ids` param's objects (default: the selection) as one undo step named `label`;
/// errors name the command `cmd`. The reply's `notChanged` counts the locked and hidden objects the
/// Run `pass` on the `ids` param's objects (default: the selection) as one undo step named `label`,
/// or none when the pass changes nothing; errors name the command `cmd`. The reply's `notChanged` counts the locked and hidden objects the
/// selection left out ([`left_out`]) that the pass would have changed.
fn run_pass(s: &mut Session, p: &Value, cmd: &str, label: &str, pass: Recolor) -> Result<Value> {
let (ids, left) = match ids_param(p, "ids", cmd)? {
@@ -444,17 +471,60 @@ fn run_pass(s: &mut Session, p: &Value, cmd: &str, label: &str, pass: Recolor) -
}
};
let colorized_ok = super::paint::check_colorized(&s.doc()?.doc).is_ok();
let (n, not_changed) = s.edit(label, |d, _| {
let (n, not_changed) = edit_if_changed(s, label, |_, d| {
let not_changed = NotChanged::of(pass.again().would_change(d, &left).into_iter().map(|(_, hidden)| hidden));
let n = pass.run(d, &ids);
super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad(cmd, e))?;
Ok((n, not_changed))
let n = keeping_series_paint(d, &ids, |d| {
let n = pass.run(d, &ids);
super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad(cmd, e))?;
Ok(n)
})?;
Ok(((n, not_changed), n > 0))
})?;
let mut out = json!({ "changed": n });
not_changed.report(&mut out);
Ok(out)
}
/// [`Session::edit`] for an Edit Colors pass, which may change nothing: `f` runs on a copy of the
/// document (it gets the document as it is too) and returns its result with whether it changed the
/// copy. Only a changed copy becomes the document, as one undo step named `label`; otherwise the
/// undo and redo steps and the saved state stay as they were.
pub(crate) fn edit_if_changed<T>(s: &mut Session, label: &str, f: impl FnOnce(&Document, &mut Document) -> Result<(T, bool)>) -> Result<T> {
if s.script_running() {
return Err(EngineError::Busy);
}
// A typing session ends here as `s.edit` would end it, before the copy is taken, so that the
// copy holds what was typed.
if !s.previewing && super::typing_in_progress(s) {
super::settle_interaction(s)?;
}
let before = s.doc()?.doc.clone();
let mut doc = (*before).clone();
let (v, changed) = f(&before, &mut doc)?;
// The document is shared with `before` no longer, so `s.edit` does not copy it again.
drop(before);
if changed {
s.edit(label, |d, _| {
*d = doc;
Ok(())
})?;
}
Ok(v)
}
/// Run `recolor` on `d` (it returns how many objects it changed) over `roots`, then store on their graphs what it changed
/// on the graph series marks among `roots` and inside them, so the marks keep their new paint when the graph is drawn
/// again.
pub(crate) fn keeping_series_paint(d: &mut Document, roots: &[NodeId], recolor: impl FnOnce(&mut Document) -> Result<usize>) -> Result<usize> {
let marks = super::graph::series_marks_in(d, roots);
let before = (!marks.is_empty()).then(|| d.clone());
let n = recolor(d)?;
if let Some(before) = before.filter(|_| n > 0) {
super::appearance::capture_series_changes(&before, d, &marks);
}
Ok(n)
}
/// The objects a recolor of `roots` leaves out of the art the user meant to recolor, each with
/// whether it is hidden (otherwise it is locked). When `roots` are exactly the objects Select All
/// takes (in isolation mode, those of the isolated group), these are the objects beside them that
@@ -534,6 +604,178 @@ impl NotChanged {
}
}
/// The objects a pass recolors (the `ids` param's, default: the selection's) and the locked and
/// hidden objects the selection left out ([`left_out`]), each with whether it is hidden.
fn pass_targets(s: &Session, p: &Value, cmd: &str) -> Result<Targets> {
Ok(match ids_param(p, "ids", cmd)? {
Some(v) => (v, vec![]),
None => {
let roots = selected_roots(s)?;
let st = s.doc()?;
let left = left_out(&st.doc, st.isolation, &roots);
(roots, left)
}
})
}
/// Edit › Edit Colors › Convert to Indexed Color: the embedded images of the objects stored as
/// indexed-color PNGs ([`Indexing`]). The pass runs on a copy of the document, so no undo step is
/// recorded when no image changes.
fn to_indexed(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "edit.colors.toIndexed";
let indexing = Indexing::of(s, p)?;
let remake = |b: &ImageBlob| indexing.convert(b);
let images = Scope { fill: false, stroke: false, images: true, patterns: false };
let pass = Recolor { remake: Some(&remake), ..Recolor::new(images, &same) };
// A left-out image counts as one the pass would change when it is an image that is not an
// indexed PNG yet; it is not converted to find out. The empty PNG only gives it a new key.
let would = |b: &ImageBlob| (!b.indexed_png() && b.pixel_size().is_some()).then(|| ImageBlob::png(vec![]));
let (ids, left) = pass_targets(s, p, C)?;
let (n, not_changed) = edit_if_changed(s, "Convert to Indexed Color", |now, doc| {
let colorized_ok = super::paint::check_colorized(now).is_ok();
let not_changed = NotChanged::of(
Recolor { remake: Some(&would), ..Recolor::new(images, &same) }.would_change(now, &left).into_iter().map(|(_, hidden)| hidden),
);
let n = pass.run(doc, &ids);
if let Some((w, h)) = indexing.too_large.get() {
return Err(bad(C, format!("an image of {w} × {h} pixels is too large to convert (at most {} pixels)", Indexing::MAX_PIXELS)));
}
super::paint::check_colorized_kept(colorized_ok, doc).map_err(|e| bad(C, e))?;
Ok(((n, not_changed), n > 0))
})?;
let mut out = json!({ "changed": n });
not_changed.report(&mut out);
Ok(out)
}
/// How Convert to Indexed Color reduces an image's colors: the palette options of a PNG-8
/// export, with transparency kept and no matte, and the fixed palette of the uniform and document
/// reductions.
struct Indexing {
options: PaletteOptions,
fixed: Option<Vec<[u8; 3]>>,
/// The size of an image [`Self::convert`] left as it is because it has more than
/// [`Self::MAX_PIXELS`] pixels.
too_large: Cell<Option<(u32, u32)>>,
}
impl Indexing {
/// The most pixels an image may have. Converting one holds at most about 8 bytes a pixel at
/// once: decoding (the decoded samples and the RGBA), quantizing (the RGBA, the colors and the
/// indices) and writing the PNG after the RGBA is freed (the indices, the packed and filtered
/// rows and the compressed data). 16 bytes a pixel keeps that within [`MAX_RASTER_ALLOC`] twice
/// over.
const MAX_PIXELS: u64 = MAX_RASTER_ALLOC / 16;
/// The reduction `p` asks for (see `edit.colors.toIndexed`); a value out of range or of the
/// wrong type is an error. Reduction and dither ids are read as a PNG-8 export reads them.
fn of(s: &Session, p: &Value) -> Result<Self> {
const C: &str = "edit.colors.toIndexed";
let reduction = text_param(p, "reduction", C)?.unwrap_or("selective");
let colors = match p.get("colors") {
None | Some(Value::Null) => None,
Some(v) => {
Some(v.as_u64().filter(|n| (2..=256).contains(n)).ok_or_else(|| bad(C, "`colors` must be a whole number from 2 to 256"))? as u16)
}
};
let dither = match text_param(p, "dither", C)? {
None => Dither::Diffusion,
Some(d) => Dither::from_id(d).ok_or_else(|| bad(C, format!("unknown dither `{d}` (diffusion, pattern, noise or none)")))?,
};
let dither_amount = match p.get("ditherAmount") {
None | Some(Value::Null) => 100,
Some(v) => {
v.as_f64().filter(|x| (0.0..=100.0).contains(x)).ok_or_else(|| bad(C, "`ditherAmount` must be a number from 0 to 100"))?.round() as u8
}
};
let options =
|r: Reduction| PaletteOptions { colors: colors.unwrap_or(256), reduction: r, dither, dither_amount, transparency: true, matte: None };
let refuse_colors = |name: &str| match colors {
Some(_) => Err(bad(C, format!("`colors` does not apply to the {name} reduction"))),
None => Ok(()),
};
let fixed = |palette: Vec<[u8; 3]>| Self { options: options(Reduction::Adaptive), fixed: Some(palette), too_large: Cell::new(None) };
Ok(match reduction.to_ascii_lowercase().as_str() {
"uniform" => {
let n = colors.unwrap_or(256);
// One entry is kept for transparent pixels.
let levels =
(2..=6u16).rev().find(|l| l.pow(3) < n).ok_or_else(|| bad(C, "`colors` must be at least 9 for the uniform reduction"))?;
let level = |i: u16| (u32::from(i) * 255 / u32::from(levels - 1)) as u8;
let mut palette = Vec::with_capacity(usize::from(levels.pow(3)));
for r in 0..levels {
for g in 0..levels {
for b in 0..levels {
palette.push([level(r), level(g), level(b)]);
}
}
}
fixed(palette)
}
"document" => {
refuse_colors("document")?;
let mut palette: Vec<[u8; 3]> = vec![];
for c in s.doc()?.doc.swatches_iter().filter_map(|sw| sw.paint.color()) {
let [r, g, b, _] = c.to_rgba8(1.0);
if !palette.contains(&[r, g, b]) {
palette.push([r, g, b]);
}
}
if palette.is_empty() {
return Err(bad(C, "the document has no color swatches"));
}
if palette.len() > 255 {
return Err(bad(C, format!("the document's swatches hold {} colors; the document reduction takes at most 255", palette.len())));
}
fixed(palette)
}
id => {
let r = Reduction::from_id(id).ok_or_else(|| {
bad(C, format!("unknown reduction `{reduction}` (selective, perceptual, adaptive, web, gray, blackWhite, uniform or document)"))
})?;
if r == Reduction::BlackWhite {
refuse_colors("blackWhite")?;
}
Self { options: options(r), fixed: None, too_large: Cell::new(None) }
}
})
}
/// Image `b` as an indexed-color PNG; `None` when it can't be decoded, when it has more than
/// [`Self::MAX_PIXELS`] pixels (noted in `too_large`), or when it is an indexed PNG already and
/// every pixel would show as it does.
fn convert(&self, b: &ImageBlob) -> Option<ImageBlob> {
let (w, h) = b.pixel_size()?;
if u64::from(w) * u64::from(h) > Self::MAX_PIXELS {
self.too_large.set(Some((w, h)));
return None;
}
let (w, h, rgba) = b.rgba()?;
let ix = match &self.fixed {
Some(palette) => quantize_to(&rgba, w, h, &self.options, palette),
None => quantize(&rgba, w, h, &self.options),
};
if b.indexed_png() && shows_same(&ix, &rgba) {
return None;
}
// The PNG writer's buffers take the place of the pixels.
drop(rgba);
Some(ImageBlob::png(encode_indexed(&ix, &PngOptions::default()).ok()?))
}
}
/// Whether palette image `ix` shows every pixel of straight RGBA `rgba` as it is: transparent
/// where they are transparent, and the same color where they are opaque.
fn shows_same(ix: &Indexed, rgba: &[u8]) -> bool {
let px = rgba.as_chunks::<4>().0;
px.len() == ix.indices.len()
&& px.iter().zip(&ix.indices).all(|(p, &i)| match (p[3], ix.transparent == Some(i)) {
(0, clear) => clear,
(255, false) => ix.palette.get(usize::from(i)).is_some_and(|c| c[..] == p[..3]),
_ => false,
})
}
fn saturate(s: &mut Session, p: &Value) -> Result<Value> {
let i = (f64_req(p, "intensity", "edit.colors.saturate")?.clamp(-100.0, 100.0) / 100.0) as f32;
recolor(s, p, "edit.colors.saturate", "Saturate", &move |c| {
@@ -679,7 +921,7 @@ fn blend(s: &mut Session, order: BlendOrder) -> Result<Value> {
};
let fills = Scope { fill: true, stroke: false, images: false, patterns: false };
let colorized_ok = super::paint::check_colorized(&s.doc()?.doc).is_ok();
let changed = s.edit(label, |d, _| {
let run = |d: &mut Document| -> Result<usize> {
let mut changed = 0;
for (i, id) in ids.iter().enumerate().take(n - 1).skip(1) {
let c = lerp_color(&first, &last, i as f32 / (n - 1) as f32).in_model(model);
@@ -698,7 +940,8 @@ fn blend(s: &mut Session, order: BlendOrder) -> Result<Value> {
}
super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad(label, e))?;
Ok(changed)
})?;
};
let changed = edit_if_changed(s, label, |_, d| keeping_series_paint(d, &ids, run).map(|n| (n, n > 0)))?;
Ok(json!({ "changed": changed }))
}
+18 -7
View File
@@ -5,9 +5,11 @@
//! Colour settings and the proof view are process-wide (`vectorcraft_color::cms::active`,
//! `vectorcraft_render::proof::view`). A document's assigned profiles are stored in
//! `Document::color_profiles` (files before format v3: `Document.unknown["colorProfiles"]`) and
//! take the place of the working spaces in the active settings when assigned, and when the working
//! settings change while the document is in front ([`use_front_profiles`]); the working spaces stay
//! as Edit → Color Settings set them.
//! take the place of the working spaces in the active settings while the document is in front
//! ([`use_front_profiles`]): when they are assigned, when the working settings change, and when the
//! document comes to the front or its assignment comes back (an open, a switch, a close, a revert,
//! an undo or a rollback, [`Session::sync_front_profiles`]); the working spaces stay as Edit → Color
//! Settings set them.
use std::collections::BTreeMap;
use std::sync::Arc;
@@ -88,7 +90,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Gamut Warning",
[],
None,
"{ids?|id?, colors?: [color] (#rrggbbaa and #rgba are refused)} colours that can't be printed in the working CMYK (selection, or the whole document when nothing is selected) → {checked, outOfGamut: [{hex, deltaE, count}]}",
"{ids?|id?, colors?: [color] (#rrggbbaa and #rgba are refused)} colors that can't be printed in the document's assigned CMYK profile, else the working CMYK (selection, or the whole document when nothing is selected) → {checked, outOfGamut: [{hex, deltaE, count}]}",
has_doc,
gamut_check
),
@@ -181,7 +183,7 @@ fn touch_all(s: &mut Session) {
/// Make the active settings the working settings with the profiles the front document is assigned
/// in place of the working spaces (none, or no document open: the working spaces). The open
/// documents redraw when the active settings change.
fn use_front_profiles(s: &mut Session) {
pub(crate) fn use_front_profiles(s: &mut Session) {
let (rgb, cmyk) = s.active().map(|d| doc_profiles(&d.doc)).unwrap_or_default();
if cms::use_document_profiles(rgb.as_deref(), cmyk.as_deref()) {
touch_all(s);
@@ -397,7 +399,9 @@ pub(crate) fn commit_new_art_colors(s: &mut Session) -> Result<()> {
Ok(())
}
fn record_new_art_colors(s: &mut Session, before: vectorcraft_tools::PaintDefaults) -> Result<()> {
/// Record new-art paints `before` and the session's current ones with the step just made (or the
/// interaction or undo group in progress), so Undo puts `before` back and Redo the current ones.
pub(super) fn record_new_art_colors(s: &mut Session, before: vectorcraft_tools::PaintDefaults) -> Result<()> {
let after = s.paint.clone();
if before != after || s.batch_stash.is_some() || s.doc()?.undo_group.is_some() {
let st = s.doc_mut()?;
@@ -422,7 +426,9 @@ fn record_new_art_colors(s: &mut Session, before: vectorcraft_tools::PaintDefaul
Ok(())
}
fn new_art_colors_before(s: &Session) -> Result<vectorcraft_tools::PaintDefaults> {
/// The new-art paints an undo step that starts now puts back: those at the start of the undo group
/// or interaction in progress, else the session's current ones.
pub(super) fn new_art_colors_before(s: &Session) -> Result<vectorcraft_tools::PaintDefaults> {
let st = s.doc()?;
Ok(st.undo_group.as_ref().map(|g| &g.paint).or_else(|| st.interaction.as_ref().map(|it| &it.paint)).cloned().unwrap_or_else(|| s.paint.clone()))
}
@@ -660,6 +666,11 @@ fn map_graph_colors(g: &mut vectorcraft_doc::GraphSpec, f: &mut dyn FnMut(&Color
map_paint_colors(&mut st.fill, f);
map_paint_colors(&mut st.stroke, f);
}
for r in [&mut styles.values_rows, &mut styles.categories_rows, &mut styles.legend_rows].into_iter().flatten() {
for paint in [&mut r.paint.fill, &mut r.paint.stroke].into_iter().flatten() {
map_paint_colors(paint, f);
}
}
}
/// `f` applied to solid, gradient-stop and freeform-control colors, with any swatch link.
@@ -536,6 +536,80 @@ fn a_document_replaced_in_the_back_is_measured_when_the_front_one_closes() {
assert_eq!(actual.cached_bounds, Some(expected));
}
/// The type of document `index` with id `id`, wherever its tab is.
fn text_in(s: &Session, index: usize, id: u64) -> vectorcraft_doc::TextObject {
match &s.documents()[index].doc.node(NodeId(id)).unwrap().kind {
NodeKind::Text(t) => (**t).clone(),
_ => panic!("not text"),
}
}
/// A document replaced while in the back has its type measured in its own composite fonts at once,
/// while the front document stays in front with its own definition registered; coming to the front
/// does not measure that type again.
#[test]
fn a_document_replaced_in_the_back_is_measured_before_it_comes_to_the_front() {
let (bytes, id, width) = full_roman_file("CF Pane");
let mut s = session();
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Pane")]})).unwrap();
assert!(s.replace_document(0, vectorcraft_format::load(&bytes).unwrap()));
assert_eq!(s.active_index(), Some(1));
let front = vectorcraft_text::FontDb::global().composite_font("CF Pane").unwrap();
assert_eq!(front.parts.get(vectorcraft_doc::CharClass::Roman).size, 50.0);
let measured = text_in(&s, 0, id);
assert!((measured.cached_bounds.unwrap().width() - width).abs() < 1e-6);
let node = s.documents()[0].doc.node(NodeId(id)).unwrap().geometric_bounds().unwrap();
assert!((node.width() - width).abs() < 1e-6);
let doc = std::sync::Arc::as_ptr(&s.documents()[0].doc);
assert!(s.set_active(0));
assert!(std::ptr::eq(doc, std::sync::Arc::as_ptr(&s.documents()[0].doc)));
assert_eq!(text(&s, id).cached_bounds, measured.cached_bounds);
}
/// Type a document replaced in the back sets in a composite font that only the front document
/// defines is measured in that font while the front one is registered, and again, as missing, when
/// the replaced document comes to the front.
#[test]
fn a_document_replaced_in_the_back_measures_a_font_it_lacks_again_in_front() {
let mut s = session();
let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Ab12", "size": 20, "font": "CF Lacked"})).unwrap()["id"].as_u64().unwrap();
let bytes = vectorcraft_format::save_file(&s.doc().unwrap().doc);
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Lacked")]})).unwrap();
assert!(s.replace_document(0, vectorcraft_format::load(&bytes).unwrap()));
let back = text_in(&s, 0, id);
let expected = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &back).bounds;
assert_eq!(back.cached_bounds, Some(expected));
assert!(s.set_active(0));
assert!(vectorcraft_text::FontDb::global().composite_font("CF Lacked").is_none());
let actual = text(&s, id);
let expected = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &actual).bounds;
assert_eq!(actual.cached_bounds, Some(expected));
}
/// Text holding an inline graphic whose symbol's art is type in a composite font, in a document
/// replaced in the back, is measured with the graphic at the size the document's own definition
/// gives it before it comes to the front.
#[test]
fn a_document_replaced_in_the_back_measures_inline_graphics_in_its_own_definition() {
let mut s = session();
let mut full = font("CF Back Inline");
full["parts"]["roman"]["size"] = json!(100);
s.execute("type.compositeFonts.set", &json!({"fonts": [full]})).unwrap();
let art =
s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Ab12", "size": 20, "font": "CF Back Inline"})).unwrap()["id"].as_u64().unwrap();
s.execute("symbol.new", &json!({"name": "CF Back Inline Mark", "ids": [art]})).unwrap();
let id = s.execute("text.create", &json!({"x": 10, "y": 150, "text": "x", "size": 20})).unwrap()["id"].as_u64().unwrap();
s.execute("text.insertInline", &json!({"id": id, "at": 0, "symbol": "CF Back Inline Mark"})).unwrap();
let width = text(&s, id).cached_bounds.unwrap().width();
let bytes = vectorcraft_format::save_file(&s.doc().unwrap().doc);
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Back Inline")]})).unwrap();
assert!(s.replace_document(0, vectorcraft_format::load(&bytes).unwrap()));
assert!((text_in(&s, 0, id).cached_bounds.unwrap().width() - width).abs() < 1e-6);
}
/// A failed batch takes back the composite fonts it set, in the font database too.
#[test]
fn a_failed_batch_takes_back_its_composite_fonts() {
+557 -102
View File
@@ -18,7 +18,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Document Info",
["Window", "Document Info"],
None,
"{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts (the type in opacity masks and in the art of symbols and patterns included; with selectionOnly: the selected type's), images, swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the brushes the art's drawn strokes use, each once; with selectionOnly: those the selected objects' strokes use), brushes: [{name, type: calligraphic|scatter|art|pattern|bristle|null}] (those brushes with their types; null: not in the Brushes panel), panelBrushNames (the Brushes panel's brushes), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient with a stop above opacity 0, at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, fills and strokes at an opacity of 0, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else Linear gradient, Radial gradient or Freeform gradient; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}. An image linked to a file outside the automation read roots has link null, and its Linked Images row names the file alone",
"{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document: {…, units (English), unitId: the units' Preferences › Units id (points, millimeters, feetInches, …), rasterEffectsPpi}, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts (the type in opacity masks and in the art of symbols and patterns included; with selectionOnly: the selected type's), fontDetails: [{font, match: exact|style|missingWithFallback|missing, family, style, file, embedding: allowed|editing|previewPrint|forbidden|null}] (each font of fonts, in order: how it was found, the face shown (null when none), that face's file name (null for a built-in face) and what its license allows), images, imageObjects: [{name, width, height, linked, file}] (the image objects in the order Linked Images and Embedded Images list them; file: what a linked image's row shows, null for an embedded one), swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the brushes the art's drawn strokes use, each once; with selectionOnly: those the selected objects' strokes use), brushes: [{name, type: calligraphic|scatter|art|pattern|bristle|null}] (those brushes with their types; null: not in the Brushes panel), panelBrushNames (the Brushes panel's brushes), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient that color a part of it above opacity 0 (a stop at opacity 0 counts only where it mixes with a stop above opacity 0 over a stretch of some width), at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, fills and strokes at an opacity of 0, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients, kinds}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else its kind's name, such as Linear gradient; kinds gives each one's kind, linear|radial|conic|diamond|freeform, when it is named by its kind, else null; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}. An image linked to a file outside the automation read roots has link null, and its Linked Images row names the file alone. brushNames, brushes, spotObjects, patternObjects and gradientObjects leave out hidden objects, objects at an opacity of 0 and the objects inside a hidden group or layer or one at an opacity of 0 (with selectionOnly too), their characters' paints and colorized images included; objects still counts them as paths, groups and the other kinds",
has_doc,
info
),
@@ -52,7 +52,7 @@ pub const CATEGORIES: [(&str, &str); 13] = [
];
/// The object counts of `document.info` and their labels.
const OBJECT_LABELS: [(&str, &str); 19] = [
pub const OBJECT_LABELS: [(&str, &str); 19] = [
("paths", "Paths"),
("compoundPaths", "Compound Paths"),
("groups", "Groups"),
@@ -85,17 +85,65 @@ pub struct Section {
/// What a font's `fsType` lets a copy of it do, read as exports read it ([`Embedding`]): the
/// most permissive usage bit wins, and bitmap-only fonts may not be embedded.
pub fn embedding_label(fs_type: u16) -> &'static str {
if Embedding::from_fs_type(fs_type) == Embedding::Forbidden {
"embedding not allowed"
} else if fs_type & 0x0008 != 0 {
"embedding for editing"
} else if fs_type & 0x0004 != 0 {
"embedding for preview and print"
} else {
"embedding allowed"
match embedding_id(fs_type) {
"forbidden" => "embedding not allowed",
"editing" => "embedding for editing",
"previewPrint" => "embedding for preview and print",
_ => "embedding allowed",
}
}
/// [`embedding_label`] as the `embedding` value of a `fontDetails` entry: `forbidden`, `editing`,
/// `previewPrint` or `allowed`.
pub fn embedding_id(fs_type: u16) -> &'static str {
if Embedding::from_fs_type(fs_type) == Embedding::Forbidden {
"forbidden"
} else if fs_type & 0x0008 != 0 {
"editing"
} else if fs_type & 0x0004 != 0 {
"previewPrint"
} else {
"allowed"
}
}
/// A font as Font Details lists it: its `fontDetails` entry and its row. The row gives the file
/// the font is drawn from (`built in` for a face with no file) and whether its license lets it be
/// embedded; for a style the family lacks, the face shown in its place; for a font that is not
/// installed, the face shown instead, or `missing`. The entry holds the same facts as values
/// (`match`: `exact`, `style`, `missingWithFallback` or `missing`), so the panel can show them in
/// the interface language.
fn font_detail(used: &super::fonts::UsedFont) -> (Value, (String, String)) {
let db = vectorcraft_text::FontDb::global();
let (family, style, version) = used;
let label = super::fonts::font_label(used);
// Found by any of its names (in the version the type names); a style the family lacks shows in
// another.
let resolved = db.resolve(family, style).map(|(f, m)| (db.face_version(family, style, version.as_deref()).unwrap_or(f), m));
let (entry, detail) = match resolved {
Some((f, m)) if m != vectorcraft_text::FontMatch::Missing => {
let file = f.path().and_then(|p| p.file_name()).map(|n| n.to_string_lossy().into_owned());
let found = format!("{}; {}", file.as_deref().unwrap_or("built in"), embedding_label(f.fs_type()));
let substituted = m == vectorcraft_text::FontMatch::Style;
let entry = json!({
"font": label,
"match": if substituted { "style" } else { "exact" },
"family": f.family,
"style": f.style,
"file": file,
"embedding": embedding_id(f.fs_type()),
});
(entry, if substituted { format!("substituted: shown in {} {} ({found})", f.family, f.style) } else { found })
}
Some((f, _)) => (
json!({ "font": label, "match": "missingWithFallback", "family": f.family, "style": f.style, "file": null, "embedding": null }),
format!("missing: shown in {} {}", f.family, f.style),
),
None => (json!({ "font": label, "match": "missing", "family": null, "style": null, "file": null, "embedding": null }), "missing".into()),
};
(entry, (label, detail))
}
/// An image object as Document Info lists it: (name, width, height, linked file).
type ImageRow = (String, u32, u32, Option<String>);
@@ -131,14 +179,15 @@ fn repeat_entry(d: &Document, n: &Node, spec: &RepeatSpec) -> (Value, (String, S
}
/// The Document Info categories of `d` (only `category` when given) from `info` (what
/// `document.info` reports), its fonts, its image objects, the rows of the brushes its art uses, the
/// rows of its Repeat objects and the rows of its objects filled or stroked with a spot color, with a
/// pattern and with a gradient.
/// `document.info` reports), its fonts and their Font Details rows, its image objects, the rows of
/// the brushes its art uses, the rows of its Repeat objects and the rows of its objects filled or
/// stroked with a spot color, with a pattern and with a gradient.
#[allow(clippy::too_many_arguments)]
fn sections(
d: &Document,
info: &Value,
fonts: &BTreeSet<super::fonts::UsedFont>,
font_details: &[(String, String)],
images: &[ImageRow],
brushes: &[(String, String)],
repeats: &[(String, String)],
@@ -192,34 +241,7 @@ fn sections(
"gradients" => gradient_objects.to_vec(),
"symbols" => names("symbols"),
"fonts" => fonts.iter().map(|f| (super::fonts::font_label(f), String::new())).collect(),
"fontDetails" => {
let db = vectorcraft_text::FontDb::global();
fonts
.iter()
.map(|used| {
let (family, style, version) = used;
// Found by any of its names (in the version the type names); a style the
// family lacks shows in another.
let resolved =
db.resolve(family, style).map(|(f, m)| (db.face_version(family, style, version.as_deref()).unwrap_or(f), m));
let detail = match resolved {
Some((f, m)) if m != vectorcraft_text::FontMatch::Missing => {
let file =
f.path().and_then(|p| p.file_name()).map_or_else(|| "built in".into(), |n| n.to_string_lossy().into_owned());
let found = format!("{file}; {}", embedding_label(f.fs_type()));
if m == vectorcraft_text::FontMatch::Style {
format!("substituted: shown in {} {} ({found})", f.family, f.style)
} else {
found
}
}
Some((f, _)) => format!("missing: shown in {} {}", f.family, f.style),
None => "missing".into(),
};
(super::fonts::font_label(used), detail)
})
.collect()
}
"fontDetails" => font_details.to_vec(),
"linkedImages" => {
images.iter().filter_map(|(name, w, h, link)| Some((name.clone(), format!("{w} × {h} px — {}", link.as_ref()?)))).collect()
}
@@ -277,6 +299,39 @@ fn gradient_label(p: &Paint) -> Option<String> {
}
}
/// Where [`gradient_label`]'s name for gradient paint `p` comes from: `swatch:<name>` for a
/// gradient linked to a swatch, else `kind:<kind>` (`linear`, `radial`, `conic`, `diamond` or
/// `freeform`). The two prefixes keep a swatch's name apart from a kind's name it reads like.
fn gradient_source(p: &Paint) -> Option<String> {
match p {
Paint::Gradient(g) => Some(match g.swatch.as_deref().filter(|s| !s.is_empty()) {
Some(swatch) => format!("swatch:{swatch}"),
None => format!("kind:{}", g.gradient.kind.label().to_ascii_lowercase()),
}),
_ => None,
}
}
/// For each of `names` (an object's [`gradient_label`]s), the kind it names when only a kind
/// gives that name: a name one of `sources` (the object's [`gradient_source`]s) gives as a kind's
/// and none gives as a swatch's, else null. A swatch named like a kind keeps its name even where
/// a gradient of that kind is listed under the same name.
fn gradient_kinds(names: &[String], sources: &[String]) -> Vec<Value> {
names
.iter()
.map(|name| {
if sources.iter().any(|s| s.strip_prefix("swatch:") == Some(name.as_str())) {
return Value::Null;
}
sources
.iter()
.filter_map(|s| s.strip_prefix("kind:"))
.find(|k| vectorcraft_color::GradientKind::parse(k).is_some_and(|kind| *name == format!("{} gradient", kind.label())))
.map_or(Value::Null, |k| json!(k))
})
.collect()
}
/// The names of `d`'s spot color swatches: the swatches whose prints go to a plate of their own
/// ([`vectorcraft_doc::inks::inks`]). A name held by several swatches is the first one's, as
/// [`Document::swatch`] finds it, and the Registration swatch prints on every plate, so it is not
@@ -289,10 +344,46 @@ fn spot_swatches(d: &Document) -> HashSet<&str> {
first.into_iter().filter(|&(name, spot)| spot && name != vectorcraft_color::swatch::REGISTRATION).map(|(name, _)| name).collect()
}
/// Which of gradient `g`'s stops color some part of it that draws, by the stretches
/// [`vectorcraft_color::Gradient::sample`] mixes in, for stops in any order: the pair of stop `k`
/// and stop `k + 1` covers the offsets above every offset of stops `0..=k` up to stop `k + 1`'s,
/// and both its stops count when that stretch has positive width and either stop is above opacity
/// 0. The first stop also counts when it is above opacity 0, since it colors the offsets up to its
/// own, and so does the last stop, since it colors the offsets above every stop's. Any other stop,
/// opaque or not, counts only through a pair: a stop out of order whose pairs have no width
/// (another stop before it reaches past both ends) colors nothing. A freeform gradient draws from
/// its points, so each of its stops counts while any stop is above opacity 0.
fn drawn_stops(g: &vectorcraft_color::Gradient) -> Vec<bool> {
let stops = &g.stops;
if g.kind == vectorcraft_color::GradientKind::Freeform {
let any = stops.iter().any(|s| s.opacity > 0.0);
return vec![any; stops.len()];
}
let mut drawn = vec![false; stops.len()];
if let (Some(first), Some(d)) = (stops.first(), drawn.first_mut()) {
*d = first.opacity > 0.0;
}
if let (Some(last), Some(d)) = (stops.last(), drawn.last_mut()) {
*d |= last.opacity > 0.0;
}
// `f32::max` skips a NaN offset, which the sampler never picks either.
let mut reach = f32::NEG_INFINITY;
for k in 0..stops.len().saturating_sub(1) {
reach = reach.max(stops[k].offset);
let (a, b) = (&stops[k], &stops[k + 1]);
if b.offset > reach && (a.opacity > 0.0 || b.opacity > 0.0) {
drawn[k] = true;
drawn[k + 1] = true;
}
}
drawn
}
/// The spot colors paint `p` prints (`spots`: [`spot_swatches`]): the spot swatch a solid color is
/// linked to, or those a gradient's stops are linked to, each once, in the order of the stops. A
/// link at a tint of 0 prints no ink, a gradient whose stops are all at an opacity of 0 draws
/// nothing, and a color that only looks like a spot color is not linked to one.
/// linked to, or those a gradient's drawn stops ([`drawn_stops`]) are linked to, each once, in the
/// order of the stops. A link at a tint of 0 prints no ink, a stop that colors only parts of a
/// gradient at an opacity of 0 prints none, and a color that only looks like a spot color is not
/// linked to one.
fn spot_labels(spots: &HashSet<&str>, p: &Paint) -> Vec<String> {
let mut out: Vec<String> = vec![];
let mut add = |swatch: &Option<String>, tint: f32| {
@@ -306,7 +397,10 @@ fn spot_labels(spots: &HashSet<&str>, p: &Paint) -> Vec<String> {
};
match p {
Paint::Solid { swatch, tint, .. } => add(swatch, *tint),
Paint::Gradient(g) if g.gradient.stops.iter().any(|s| s.opacity > 0.0) => g.gradient.stops.iter().for_each(|s| add(&s.swatch, s.tint)),
Paint::Gradient(g) => {
let drawn = drawn_stops(&g.gradient);
g.gradient.stops.iter().zip(drawn).filter(|&(_, d)| d).for_each(|(s, _)| add(&s.swatch, s.tint));
}
_ => {}
}
out
@@ -425,6 +519,66 @@ fn applied_brushes(d: &Document, n: &Node, members: &HashSet<*const Node>) -> Ve
if follows { used } else { vec![] }
}
/// Whether `n` draws, as far as its own state goes: a hidden object, and an object at an opacity
/// of 0, paint no color, and neither do their members.
fn draws(n: &Node) -> bool {
n.visible && n.opacity > 0.0
}
/// The object of `d` at index path `path`, with whether the groups and layers around it draw
/// ([`draws`]).
fn node_and_drawn<'a>(d: &'a Document, path: &[usize]) -> Option<(&'a Node, bool)> {
let (first, rest) = path.split_first()?;
let mut at: &Node = d.layers.get(*first)?;
let mut drawn = true;
for &i in rest {
drawn &= draws(at);
at = &**at.children()?.get(i)?;
}
Some((at, drawn))
}
/// The spot colors, the patterns and the gradients (`spots`: [`spot_swatches`]) that object `n`
/// paints, each once: those of its own fills and strokes ([`own_paints`], `members` included), of
/// its drawn characters and, for a grayscale or 1-bit image, of the color it is colorized with.
/// The fourth list gives where each gradient comes from: a swatch or a kind ([`gradient_source`]).
fn object_paints(d: &Document, spots: &HashSet<&str>, members: &HashSet<*const Node>, n: &Node) -> [Vec<String>; 4] {
let (spot, pattern, gradient) = (|p: &Paint| spot_labels(spots, p), one_label(pattern_label), one_label(gradient_label));
let gradient_from = one_label(gradient_source);
let labels: [&PaintNames<'_>; 4] = [&spot, &pattern, &gradient, &gradient_from];
let painted_runs = painted_runs(d, spots, n);
let mut used = labels.map(|label| own_paints(d, n, members, painted_runs.as_ref(), label));
// The characters' own paints: an inline graphic draws no outline and does not take its run's
// paint (a list marker set in its run does), and a stroke with no width paints nothing.
if let Some((t, painted)) = &painted_runs {
for run in painted.iter().filter_map(|i| t.runs.get(*i)) {
let stroke = (run.style.stroke_width > 0.0).then_some(&run.style.stroke);
for paint in std::iter::once(&run.style.fill).chain(stroke) {
for (used, label) in used.iter_mut().zip(labels) {
for name in label(paint) {
if !used.contains(&name) {
used.push(name);
}
}
}
}
}
}
// A grayscale or 1-bit image colorized with a spot color prints it, while its pixels take the
// color, as the renderer draws it.
if let NodeKind::Image(im) = &n.kind
&& let Some(colorize) = n.extras().colorize.as_deref()
&& d.image_blob(im).is_some_and(|b| b.takes_colorize())
{
for name in spot(colorize) {
if !used[0].contains(&name) {
used[0].insert(0, name);
}
}
}
used
}
fn info(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "document.info";
let category = str_param(p, "category");
@@ -440,8 +594,13 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
let st = s.doc()?;
let d = &st.doc;
let selection_only = bool_or(p, "selectionOnly", false);
let roots: Vec<&Node> =
if selection_only { st.selection.objects.iter().filter_map(|id| d.node(*id)).collect() } else { d.layers.iter().map(|l| &**l).collect() };
// Each root with whether the groups and layers around it draw: a selected object inside a hidden group or layer, or one
// at an opacity of 0, paints nothing.
let roots: Vec<(&Node, bool)> = if selection_only {
st.selection.objects.iter().filter_map(|id| node_and_drawn(d, &d.index_path(*id)?)).collect()
} else {
d.layers.iter().map(|l| (&**l, true)).collect()
};
let mut counts: BTreeMap<&str, usize> = BTreeMap::new();
// The paths' total length, as Document Info › Objects shows it (the length of a cut line, a
// strip of LEDs along the letters, #1958).
@@ -467,7 +626,6 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
let mut spot_objects: Vec<Value> = vec![];
let mut spot_rows: Vec<(String, String)> = vec![];
let mut spot = BTreeSet::new();
let (spot_label, pattern, gradient) = (|p: &Paint| spot_labels(&spot_swatches, p), one_label(pattern_label), one_label(gradient_label));
let mut styles: Vec<&str> = if selection_only { vec![] } else { d.graphic_styles.iter().map(|g| g.name.as_str()).collect() };
// `library` holds the Brushes panel's brushes, and `brushes` the brushes the visited objects' strokes draw with, each once,
// in walk order.
@@ -494,10 +652,18 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
members.extend(children.iter().map(|c| std::ptr::from_ref(&**c)));
}
});
for r in roots {
r.walk(&mut |n| {
// Depth first, in paint order, as `Node::walk` visits: each object with whether it and the groups and layers around it
// draw. An object that does not draw is still counted, and its members are visited.
let mut stack: Vec<(&Node, bool)> = vec![];
for (r, drawn) in roots {
stack.push((r, drawn));
while let Some((n, around)) = stack.pop() {
if !seen.insert(std::ptr::from_ref(n)) {
return;
continue;
}
let drawn = around && draws(n);
if let Some(ch) = n.children() {
stack.extend(ch.iter().rev().map(|c| (&**c, drawn)));
}
let k = match &n.kind {
// The Guides row counts paths made into guides; ruler guides are not objects.
@@ -545,42 +711,10 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(k) = k {
*counts.entry(k).or_default() += 1;
}
// The spot colors, the patterns and the gradients this object's fills and strokes paint, each once.
let painted_runs = painted_runs(d, &spot_swatches, n);
let mut used_spots = own_paints(d, n, &members, painted_runs.as_ref(), &spot_label);
let mut used_patterns = own_paints(d, n, &members, painted_runs.as_ref(), &pattern);
let mut used_gradients = own_paints(d, n, &members, painted_runs.as_ref(), &gradient);
// The characters' own paints: an inline graphic draws no outline and does not take its
// run's paint (a list marker set in its run does), and a stroke with no width paints
// nothing.
if let Some((t, painted)) = &painted_runs {
for run in painted.iter().filter_map(|i| t.runs.get(*i)) {
let stroke = (run.style.stroke_width > 0.0).then_some(&run.style.stroke);
for paint in std::iter::once(&run.style.fill).chain(stroke) {
let labels: [(&mut Vec<String>, &PaintNames<'_>); 3] =
[(&mut used_spots, &spot_label), (&mut used_patterns, &pattern), (&mut used_gradients, &gradient)];
for (used, label) in labels {
for name in label(paint) {
if !used.contains(&name) {
used.push(name);
}
}
}
}
}
}
// A grayscale or 1-bit image colorized with a spot color prints it, while its pixels take
// the color, as the renderer draws it.
if let NodeKind::Image(im) = &n.kind
&& let Some(colorize) = n.extras().colorize.as_deref()
&& d.image_blob(im).is_some_and(|b| b.takes_colorize())
{
for name in spot_label(colorize) {
if !used_spots.contains(&name) {
used_spots.insert(0, name);
}
}
}
// The spot colors, the patterns and the gradients this object paints, each once, and where each gradient comes from;
// none when it does not draw.
let [used_spots, used_patterns, used_gradients, used_sources] =
if drawn { object_paints(d, &spot_swatches, &members, n) } else { Default::default() };
// Objects counts the objects that Spot Color Objects, Pattern Objects and Gradient Objects list.
if !used_spots.is_empty() {
let name = n.display_name();
@@ -600,7 +734,8 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
let name = n.display_name();
gradients.extend(used_gradients.iter().cloned());
gradient_rows.push((name.clone(), used_gradients.join(", ")));
gradient_objects.push(json!({ "id": n.id.0, "name": name, "gradients": used_gradients }));
let kinds = gradient_kinds(&used_gradients, &used_sources);
gradient_objects.push(json!({ "id": n.id.0, "name": name, "gradients": used_gradients, "kinds": kinds }));
*counts.entry("gradients").or_default() += 1;
}
if n.extras().mask.is_some() {
@@ -615,9 +750,11 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
{
styles.push(&g.name);
}
for b in applied_brushes(d, n, &members) {
if !brushes.contains(&b) {
brushes.push(b);
if drawn {
for b in applied_brushes(d, n, &members) {
if !brushes.contains(&b) {
brushes.push(b);
}
}
}
if let NodeKind::Repeat(spec) = &n.kind {
@@ -625,7 +762,7 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
repeats.push(entry);
repeat_rows.push(row);
}
});
}
}
// The document's fonts include those of the type in opacity masks and in the art of its
// symbols and patterns, as Find Font lists them.
@@ -633,10 +770,21 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
fonts.extend(super::fonts::art_texts_of(d).into_iter().flat_map(|(_, t, _)| t.runs.iter().map(|r| super::fonts::font_of(&r.style))));
}
let font_names: Vec<String> = fonts.iter().map(super::fonts::font_label).collect();
// Each brush the art uses with its type, found by name in the Brushes panel as the renderer finds it (the last of two
let (font_entries, font_rows): (Vec<Value>, Vec<(String, String)>) = fonts.iter().map(font_detail).unzip();
// The image objects in walk order, as Linked Images and Embedded Images list them: `file` is a
// linked image's row value (its path, or its file name alone when the request may not read it),
// and null for an embedded one.
let image_objects: Vec<Value> = image_rows
.iter()
.map(|(name, w, h, file)| json!({ "name": name, "width": w, "height": h, "linked": file.is_some(), "file": file }))
.collect();
// Each brush the art uses with its type, found by name in the Brushes panel as the renderer finds it (the first of two
// brushes with one name); a brush the panel does not hold draws as a plain stroke and has no type. A row names the type
// as the New Brush dialog does (`Art Brush`), and the panel translates these values when it shows them.
let kinds: HashMap<&str, &vectorcraft_brush::BrushKind> = library.iter().map(|b| (b.name.as_str(), &b.kind)).collect();
let mut kinds: HashMap<&str, &vectorcraft_brush::BrushKind> = HashMap::new();
for b in &library {
kinds.entry(b.name.as_str()).or_insert(&b.kind);
}
let brush_entries: Vec<Value> =
brushes.iter().map(|name| json!({ "name": name, "type": kinds.get(name.as_str()).map(|k| k.type_id()) })).collect();
let brush_rows: Vec<(String, String)> = brushes
@@ -650,7 +798,9 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
"objects": counts,
"pathLength": path_length,
"fonts": font_names,
"fontDetails": font_entries,
"images": images,
"imageObjects": image_objects,
"symbols": symbols,
"spotColors": spot,
"spotColorNames": spot,
@@ -672,7 +822,7 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
});
// The document's name: its file's, else its title.
out["document"]["name"] = json!(st.title());
let sections = sections(d, &out, &fonts, &image_rows, &brush_rows, &repeat_rows, &spot_rows, &pattern_rows, &gradient_rows, category);
let sections = sections(d, &out, &fonts, &font_rows, &image_rows, &brush_rows, &repeat_rows, &spot_rows, &pattern_rows, &gradient_rows, category);
if text {
return Ok(json!({ "text": report_text(&st.title(), selection_only, &sections) }));
}
@@ -686,6 +836,7 @@ fn document_summary(d: &Document) -> Value {
"title": d.title,
"colorMode": match d.color_mode { ColorMode::Rgb => "RGB", ColorMode::Cmyk => "CMYK" },
"units": d.units.label(),
"unitId": d.units.key(),
"artboards": d.artboards.iter().map(|a| json!({ "name": a.name, "width": a.rect.width() / u, "height": a.rect.height() / u })).collect::<Vec<_>>(),
"rasterEffectsPpi": d.raster_effects_ppi,
})
@@ -910,7 +1061,7 @@ mod tests {
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
d.node_mut(NodeId(missing)).unwrap().appearance.stroke_mut().unwrap().paint = Paint::None;
assert_eq!(s.execute("document.info", &json!({"category": "brushes"})).unwrap()["brushes"], json!([]));
// Two panel brushes with one name: the type is the one the renderer draws with, the last one's.
// Two panel brushes with one name: the type is the one the renderer draws with, the first one's.
let twin = square(&mut s, 140.0);
s.execute("brush.apply", &json!({"ids": [twin], "name": "Charcoal"})).unwrap();
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
@@ -920,7 +1071,7 @@ mod tests {
lib.extend(kinds.into_iter().map(|kind| vectorcraft_brush::Brush { name: "Twin".into(), kind }));
vectorcraft_brush::store(d, &lib);
d.node_mut(NodeId(twin)).unwrap().appearance.stroke_mut().unwrap().brush = Some("Twin".into());
assert_eq!(s.execute("document.info", &json!({"category": "brushes"})).unwrap()["brushes"], json!([{"name": "Twin", "type": "scatter"}]));
assert_eq!(s.execute("document.info", &json!({"category": "brushes"})).unwrap()["brushes"], json!([{"name": "Twin", "type": "art"}]));
// Type: a brushed stroke on drawn characters is listed, one on spaces alone is not.
let blank = s.execute("text.create", &json!({"x": 10, "y": 60, "text": " "})).unwrap()["id"].as_u64().unwrap();
let word = s.execute("text.create", &json!({"x": 10, "y": 90, "text": "Hi"})).unwrap()["id"].as_u64().unwrap();
@@ -1212,11 +1363,11 @@ mod tests {
assert_eq!(
i["gradientObjects"],
json!([
{"id": a, "name": "Both", "gradients": ["Ramp", "Linear gradient"]},
{"id": b, "name": "<Rectangle>", "gradients": ["Radial gradient"]},
{"id": f, "name": "<Rectangle>", "gradients": ["Freeform gradient"]},
{"id": t, "name": "Type", "gradients": ["Ramp"]},
{"id": bar, "name": "Bar", "gradients": ["Ramp"]},
{"id": a, "name": "Both", "gradients": ["Ramp", "Linear gradient"], "kinds": [null, "linear"]},
{"id": b, "name": "<Rectangle>", "gradients": ["Radial gradient"], "kinds": ["radial"]},
{"id": f, "name": "<Rectangle>", "gradients": ["Freeform gradient"], "kinds": ["freeform"]},
{"id": t, "name": "Type", "gradients": ["Ramp"], "kinds": [null]},
{"id": bar, "name": "Bar", "gradients": ["Ramp"], "kinds": [null]},
])
);
assert_eq!(i["gradientNames"], json!(["Freeform gradient", "Linear gradient", "Radial gradient", "Ramp"]));
@@ -1455,6 +1606,204 @@ mod tests {
assert_eq!(spots(&mut s), (vec![], None, None));
}
/// Spot Color Objects leaves out a spot color linked only from gradient stops at an opacity of 0
/// whose stretches all lead to other stops at an opacity of 0 or have no width, while another
/// part of the gradient draws: an inner stop, an end stop and a stop at the offset of an opaque
/// stop. A clear stop next to an opaque stop tints the stretch between them, so it stays listed.
/// Type whose characters draw such a gradient follows the same rule, with and without Selection
/// Only, and the report writes the same rows.
#[test]
fn spot_color_objects_skip_spot_stops_only_in_clear_stretches() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
let ink = |c: f64| json!({"model": "cmyk", "c": c, "m": 0.5, "y": 0.0, "k": 0.0});
for (k, name) in ["Ink", "Near", "Far", "Edge", "Seam"].into_iter().enumerate() {
s.execute("swatch.new", &json!({"name": name, "color": ink(0.2 * k as f64), "spot": true})).unwrap();
}
let stop = |offset: f64, swatch: Option<&str>, opacity: f64| match swatch {
Some(sw) => json!({"offset": offset, "color": "#000", "swatch": sw, "opacity": opacity}),
None => json!({"offset": offset, "color": "#fff", "opacity": opacity}),
};
let fill = |s: &mut Session, id: &Value, stops: Value| {
s.execute("paint.setFill", &json!({"ids": [id], "gradient": {"kind": "linear", "stops": stops}})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [id], "none": true})).unwrap();
};
let square =
|s: &mut Session, x: f64| s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone();
// Near borders the opaque Ink stop; Far sits between clear stops; Edge ends the ramp after a
// clear stop.
let ramp = square(&mut s, 0.0);
fill(
&mut s,
&ramp,
json!([stop(0.0, Some("Ink"), 1.0), stop(0.4, Some("Near"), 0.0), stop(0.6, Some("Far"), 0.0), stop(1.0, Some("Edge"), 0.0)]),
);
s.execute("layer.setProps", &json!({"id": ramp, "name": "Ramp"})).unwrap();
// Seam meets the opaque half only at one offset, where nothing between them has width.
let seam = square(&mut s, 20.0);
fill(&mut s, &seam, json!([stop(0.0, None, 0.0), stop(0.5, Some("Seam"), 0.0), stop(0.5, None, 1.0), stop(1.0, None, 1.0)]));
let t = s.execute("text.create", &json!({"x": 0, "y": 200, "text": "Hi"})).unwrap()["id"].clone();
fill(&mut s, &t, json!([stop(0.0, Some("Ink"), 1.0), stop(0.5, None, 0.0), stop(1.0, Some("Far"), 0.0)]));
s.execute("layer.setProps", &json!({"id": t, "name": "Type"})).unwrap();
let check = |s: &mut Session, params: Value| {
let i = s.execute("document.info", &params).unwrap();
let listed: Vec<(String, Value)> =
i["spotObjects"].as_array().unwrap().iter().map(|o| (o["name"].as_str().unwrap().to_string(), o["spotColors"].clone())).collect();
assert_eq!(listed, vec![("Ramp".to_string(), json!(["Ink", "Near"])), ("Type".to_string(), json!(["Ink"]))], "{params}");
assert_eq!((i["spotColorNames"].clone(), i["objects"]["spots"].as_u64()), (json!(["Ink", "Near"]), Some(2)), "{params}");
let rows = i["sections"].as_array().unwrap().iter().find(|c| c["id"] == "spotColors").unwrap()["rows"].clone();
assert_eq!(rows, json!([["Ramp", "Ink, Near"], ["Type", "Ink"]]), "{params}");
};
check(&mut s, json!({}));
s.execute("select.set", &json!({"ids": [ramp, seam, t]})).unwrap();
check(&mut s, json!({"selectionOnly": true}));
let text = s.execute("document.info", &json!({"category": "spotColors", "format": "text"})).unwrap()["text"].as_str().unwrap().to_string();
assert!(text.contains("\nSPOT COLOR OBJECTS\nRamp: Ink, Near\nType: Ink\n"), "{text}");
assert!(!["Far", "Edge", "Seam"].iter().any(|n| text.contains(n)), "{text}");
}
/// A gradient's stops print where they color a stretch that draws, for stops in any order: the
/// sampler mixes stop `k` with stop `k + 1` above every offset of the stops before it, so an
/// out-of-order stop's pair can have no width.
#[test]
fn drawn_stops_follow_the_sampled_stretches() {
use vectorcraft_color::{Color, Gradient, GradientKind, GradientStop};
let stop = |offset: f32, opacity: f32| GradientStop { opacity, ..GradientStop::new(offset, Color::BLACK) };
let g = |stops: Vec<GradientStop>| Gradient::new(GradientKind::Linear, stops);
// In order: the clear stop next to the opaque one, not the one after it.
assert_eq!(drawn_stops(&g(vec![stop(0.0, 1.0), stop(0.5, 0.0), stop(1.0, 0.0)])), vec![true, true, false]);
// Out of order: the pair (0.8, 0.3) has no width, so the clear stop at 0.3 mixes only with
// the clear stop at 0.8 before it, and the pair (0.3, 1.0) is sampled above 0.8.
assert_eq!(drawn_stops(&g(vec![stop(0.0, 0.0), stop(0.8, 0.0), stop(0.3, 0.0), stop(1.0, 1.0)])), vec![false, false, true, true]);
// An opaque stop out of order: the pairs (0, 0.8) and (0.7, 1) cover every offset, so the
// pairs next to the stop at 0.3 have no width and it colors nothing.
let out_of_order = |o: f32| g(vec![stop(0.0, 0.0), stop(0.8, o), stop(0.3, 1.0), stop(0.7, 0.0), stop(1.0, 0.0)]);
assert_eq!(drawn_stops(&out_of_order(0.0)), vec![false; 5]);
// With the stop at 0.8 opaque, the pairs next to it with width are drawn.
assert_eq!(drawn_stops(&out_of_order(1.0)), vec![true, true, false, false, false]);
// The last stop colors the offsets above every stop's, even when it is out of order.
assert_eq!(drawn_stops(&g(vec![stop(0.0, 0.0), stop(0.6, 0.0), stop(0.5, 1.0)])), vec![false, false, true]);
// The first stop colors the offsets up to its own.
assert_eq!(drawn_stops(&g(vec![stop(0.0, 1.0), stop(0.0, 0.0), stop(1.0, 0.0)])), vec![true, false, false]);
// One stop, every stop clear, and no stops at all.
assert_eq!(drawn_stops(&g(vec![stop(0.5, 1.0)])), vec![true]);
assert_eq!(drawn_stops(&g(vec![stop(0.0, 0.0), stop(1.0, 0.0)])), vec![false, false]);
assert!(drawn_stops(&g(vec![])).is_empty());
// A freeform gradient draws from its points: its stops count while any is above opacity 0.
let mut free = g(vec![stop(0.0, 1.0), stop(0.5, 0.0), stop(1.0, 0.0)]);
free.kind = GradientKind::Freeform;
assert_eq!(drawn_stops(&free), vec![true, true, true]);
}
/// Brushes, Spot Color Objects, Pattern Objects and Gradient Objects leave out a hidden object,
/// an object at an opacity of 0 and the objects inside a hidden layer or a group at an opacity of
/// 0, with Selection Only too: their fills, strokes, characters and colorized pixels paint no
/// color. Objects still counts them.
#[test]
fn info_skips_paints_on_hidden_and_clear_objects_and_their_members() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
s.execute("swatch.new", &json!({"name": "Ink", "color": {"model": "cmyk", "c": 0, "m": 1, "y": 1, "k": 0}, "spot": true})).unwrap();
let square = |s: &mut Session, x: f64| {
s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap()
};
let tile = square(&mut s, 0.0);
s.execute("object.pattern.make", &json!({"ids": [tile], "name": "Dots", "edit": false})).unwrap();
// A patterned square that stays drawn, an object at an opacity of 0 and a hidden one.
let (shown, clear, hidden) = (square(&mut s, 20.0), square(&mut s, 40.0), square(&mut s, 60.0));
s.execute("paint.setFill", &json!({"ids": [shown, clear], "swatch": "Dots"})).unwrap();
s.execute("paint.setFill", &json!({"ids": [hidden], "swatch": "Ink"})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [shown, clear, hidden], "none": true})).unwrap();
// A brushed square in a group.
let (brushed, other) = (square(&mut s, 80.0), square(&mut s, 100.0));
s.execute("brush.apply", &json!({"ids": [brushed], "name": "Charcoal"})).unwrap();
s.execute("select.set", &json!({"ids": [brushed, other]})).unwrap();
let group = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap();
// Type whose characters are filled with the spot color.
let word = s.execute("text.create", &json!({"x": 0, "y": 200, "text": "Hi"})).unwrap()["id"].as_u64().unwrap();
s.execute("paint.setFill", &json!({"ids": [word], "swatch": "Ink"})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [word], "none": true})).unwrap();
// A grayscale image colorized with the spot color.
let mut bytes = Vec::new();
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(2, 1, vec![0, 255]).unwrap())
.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png)
.unwrap();
let image = s
.edit("Place", |d, sel| {
d.images.insert("gray".into(), vectorcraft_doc::ImageBlob::png(bytes));
let id = d.alloc_id();
let im = vectorcraft_doc::ImageObject {
key: "gray".into(),
width: 2,
height: 1,
xf: Default::default(),
link: None,
placement: Default::default(),
pixels: None,
};
d.insert(d.default_layer(), 0, Node::new(id, NodeKind::Image(Box::new(im))))?;
sel.set([id]);
Ok(id)
})
.unwrap();
s.execute("paint.setFill", &json!({"swatch": "Ink"})).unwrap();
// A square with a gradient on a layer of its own.
let layer = s.execute("layer.new", &json!({"name": "Back"})).unwrap()["id"].as_u64().unwrap();
let ramp = square(&mut s, 120.0);
s.execute(
"paint.setFill",
&json!({"ids": [ramp], "gradient": {"kind": "linear", "stops": [{"offset": 0, "color": "#000"}, {"offset": 1, "color": "#fff"}]}}),
)
.unwrap();
s.execute("paint.setStroke", &json!({"ids": [ramp], "none": true})).unwrap();
let listed = |s: &mut Session, p: Value| {
let i = s.execute("document.info", &p).unwrap();
let ids = |k: &str| -> Vec<u64> {
let mut ids: Vec<u64> = i[k].as_array().unwrap().iter().map(|o| o["id"].as_u64().unwrap()).collect();
ids.sort_unstable();
ids
};
(i["brushNames"].clone(), ids("spotObjects"), ids("patternObjects"), ids("gradientObjects"), i["objects"].clone())
};
// Everything drawn: each object is listed.
let (brushes, spots, patterns, gradients, before) = listed(&mut s, json!({}));
assert_eq!(brushes, json!(["Charcoal"]));
// New squares take the new spot color as their fill, the group's members included.
assert_eq!((spots, patterns, gradients), (vec![hidden, brushed, other, word, image.0], vec![shown, clear], vec![ramp]));
s.edit("hide", |d, _| {
d.node_mut(NodeId(clear)).unwrap().opacity = 0.0;
d.node_mut(NodeId(hidden)).unwrap().visible = false;
d.node_mut(NodeId(group)).unwrap().opacity = 0.0;
d.node_mut(NodeId(word)).unwrap().opacity = 0.0;
d.node_mut(image).unwrap().opacity = 0.0;
d.node_mut(NodeId(layer)).unwrap().visible = false;
Ok(())
})
.unwrap();
let (brushes, spots, patterns, gradients, after) = listed(&mut s, json!({}));
assert_eq!((brushes, spots, patterns, gradients), (json!([]), vec![], vec![shown], vec![]));
// Objects counts the listed objects, and every object as before.
assert_eq!((after["spots"].clone(), after["patterns"].clone(), after["gradients"].clone()), (Value::Null, json!(1), Value::Null));
for k in ["paths", "groups", "textObjects", "images"] {
assert_eq!(after[k], before[k], "{k}: {after}");
}
let rows = s.execute("document.info", &json!({"category": "brushes"})).unwrap()["sections"][0]["rows"].clone();
assert_eq!(rows, json!([]));
// Selection Only: an object selected inside a group at an opacity of 0 or a hidden layer paints nothing either.
s.execute("select.set", &json!({"ids": [brushed, ramp]})).unwrap();
let (brushes, _, _, gradients, after) = listed(&mut s, json!({"selectionOnly": true}));
assert_eq!((brushes, gradients, after["paths"].clone()), (json!([]), vec![], json!(2)));
// Drawn again, the group's brush and the layer's gradient are listed.
s.edit("show", |d, _| {
d.node_mut(NodeId(group)).unwrap().opacity = 1.0;
d.node_mut(NodeId(layer)).unwrap().visible = true;
Ok(())
})
.unwrap();
let (brushes, _, _, gradients, _) = listed(&mut s, json!({"selectionOnly": true}));
assert_eq!((brushes, gradients), (json!(["Charcoal"]), vec![ramp]));
}
/// Document Info › Objects counts an object with a gradient or a pattern on both its fill and
/// its stroke once, and with Selection Only a selection that holds a group and an object inside
/// it counts that object once.
@@ -1525,6 +1874,112 @@ mod tests {
assert_eq!(embedding_label(0x0003), "embedding not allowed");
assert_eq!(embedding_label(0x0006), "embedding for preview and print");
assert_eq!(embedding_label(0x000c), "embedding for editing");
// `fontDetails` names each permission by id.
assert_eq!(
[0, 0x0002, 0x0104, 0x0008, 0x0200, 0x000c].map(embedding_id),
["allowed", "forbidden", "previewPrint", "editing", "forbidden", "editing"]
);
}
/// `fontDetails` gives each Font Details row's facts as values, in the rows' order: how the
/// font was found, the face shown, its file (null for a built-in face) and its embedding
/// permission. The rows and the report stay in English.
#[test]
fn info_exposes_structured_font_details_without_changing_english_rows() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
s.execute("text.create", &json!({"x": 10, "y": 20, "text": "Hi"})).unwrap();
s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Heavy", "font": "Source Sans 3", "style": "Black Wide"})).unwrap();
s.execute("text.create", &json!({"x": 10, "y": 80, "text": "Gone", "font": "Qx Absent Family"})).unwrap();
let i = s.execute("document.info", &json!({"category": "fontDetails"})).unwrap();
let (entries, rows) = (i["fontDetails"].as_array().unwrap(), i["sections"][0]["rows"].as_array().unwrap());
assert_eq!(entries.iter().map(|e| e["font"].clone()).collect::<Vec<_>>(), rows.iter().map(|r| r[0].clone()).collect::<Vec<_>>());
let at = |prefix: &str| entries.iter().position(|e| e["font"].as_str().unwrap().starts_with(prefix)).unwrap();
let regular = at("Source Sans 3 Regular");
assert_eq!(
entries[regular],
json!({"font": "Source Sans 3 Regular", "match": "exact", "family": "Source Sans 3", "style": "Regular", "file": null, "embedding": "allowed"})
);
assert_eq!(rows[regular][1], "built in; embedding allowed");
let (wide, e) = (at("Source Sans 3 Black Wide"), &entries[at("Source Sans 3 Black Wide")]);
assert_eq!((e["match"].as_str(), e["family"].as_str()), (Some("style"), Some("Source Sans 3")), "{e}");
let file = e["file"].as_str().unwrap_or("built in");
let fs_type = [("allowed", 0), ("forbidden", 0x0002), ("previewPrint", 0x0004), ("editing", 0x0008)]
.into_iter()
.find_map(|(id, bits)| (e["embedding"] == id).then_some(bits))
.unwrap();
let found = format!("{file}; {}", embedding_label(fs_type));
assert_eq!(rows[wide][1], format!("substituted: shown in Source Sans 3 {} ({found})", e["style"].as_str().unwrap()));
let (gone, e) = (at("Qx Absent Family"), &entries[at("Qx Absent Family")]);
assert!(e["file"].is_null() && e["embedding"].is_null(), "{e}");
match e["match"].as_str() {
Some("missingWithFallback") => {
assert_eq!(rows[gone][1], format!("missing: shown in {} {}", e["family"].as_str().unwrap(), e["style"].as_str().unwrap()))
}
Some("missing") => assert_eq!((rows[gone][1].as_str(), e["family"].is_null()), (Some("missing"), true)),
m => panic!("{m:?}"),
}
let text = s.execute("document.info", &json!({"category": "fontDetails", "format": "text"})).unwrap()["text"].as_str().unwrap().to_string();
assert!(text.contains("Source Sans 3 Regular: built in; embedding allowed\n"), "{text}");
}
/// `document.unitId` names the document's units as Preferences › Units does, beside the English
/// `units`, and `imageObjects` lists the image objects in the order Embedded Images and Linked
/// Images list them, with the file a linked one shows (null for an embedded one).
#[test]
fn info_exposes_ordered_images_and_unit_id() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
s.edit("Units", |d, _| {
d.units = vectorcraft_doc::Unit::Millimeters;
Ok(())
})
.unwrap();
for x in [0.0, 50.0] {
let r = s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 20, "height": 10})).unwrap()["id"].clone();
s.execute("select.set", &json!({"ids": [r]})).unwrap();
s.execute("object.rasterize", &json!({"ppi": 72})).unwrap();
}
let i = s.execute("document.info", &json!({})).unwrap();
assert_eq!((i["document"]["units"].as_str(), i["document"]["unitId"].as_str()), (Some("Millimeters"), Some("millimeters")));
let section = |id: &str| i["sections"].as_array().unwrap().iter().find(|s| s["id"] == id).unwrap()["rows"].as_array().unwrap().clone();
assert!(section("document").iter().any(|r| *r == json!(["Units", "Millimeters"])));
let embedded = section("embeddedImages");
let objects = i["imageObjects"].as_array().unwrap();
assert_eq!(objects.len(), 2, "{objects:?}");
for (o, r) in objects.iter().zip(&embedded) {
assert_eq!((o["linked"].clone(), o["file"].clone(), o["name"].clone()), (json!(false), Value::Null, r[0].clone()), "{o}");
assert_eq!(r[1], format!("{} × {} px", o["width"], o["height"]));
}
assert!(section("linkedImages").is_empty());
}
/// A `gradientObjects` entry's `kinds` gives the kind of each gradient listed by its kind
/// rather than by a swatch, and null for a swatch's name, even one that reads like a kind and
/// one an object's gradient of that kind shares; a type object's characters count as its own.
#[test]
fn gradient_kinds_tell_kinds_from_swatch_names() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
let ramp = |kind: &str| json!({"kind": kind, "stops": [{"offset": 0, "color": "#000"}, {"offset": 1, "color": "#fff"}]});
s.execute("swatch.new", &json!({"name": "Radial gradient", "gradient": ramp("linear")})).unwrap();
let r = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone();
s.execute("paint.setFill", &json!({"ids": [r], "swatch": "Radial gradient"})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [r], "gradient": ramp("conic")})).unwrap();
let t = s.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi"})).unwrap()["id"].clone();
s.execute("paint.setFill", &json!({"ids": [t], "gradient": ramp("diamond")})).unwrap();
// The swatch's name and a radial gradient's kind name are listed once, as the name.
let both = s.execute("shape.rectangle", &json!({"x": 20, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone();
s.execute("paint.setFill", &json!({"ids": [both], "swatch": "Radial gradient"})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [both], "gradient": ramp("radial")})).unwrap();
let i = s.execute("document.info", &json!({})).unwrap();
let entry = |id: &Value| i["gradientObjects"].as_array().unwrap().iter().find(|e| e["id"] == *id).unwrap().clone();
assert_eq!(
(entry(&r)["gradients"].clone(), entry(&r)["kinds"].clone()),
(json!(["Radial gradient", "Conic gradient"]), json!([null, "conic"]))
);
assert_eq!((entry(&t)["gradients"].clone(), entry(&t)["kinds"].clone()), (json!(["Diamond gradient"]), json!(["diamond"])));
assert_eq!((entry(&both)["gradients"].clone(), entry(&both)["kinds"].clone()), (json!(["Radial gradient"]), json!([null])));
}
#[test]
+56 -17
View File
@@ -210,7 +210,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Guides",
[],
None,
"{} → [{index, vertical, pos, selected, artboard?: index (an artboard guide's), layer?: id (the layer it is on), shown, editable (its layer shown and unlocked)}…] the ruler guides",
"{} → [{index, id (its node, which `layer.setProps` hides or locks on its own), vertical, pos, selected, artboard?: index (an artboard guide's), layer?: id (the layer it is on), hidden, locked (its own visibility and lock), shown, editable (it and its layer shown and unlocked)}…] the ruler guides",
has_doc,
guide_list
),
@@ -219,7 +219,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Select Guides",
[],
None,
"{indexes: [index…], toggle?: bool} select ruler guides on their own (deselecting the art); toggle adds or removes them instead, keeping the selected art (a Shift-click on a guide) → {selected: [index…]}",
"{indexes: [index…] (at most 10,000), toggle?: bool} select ruler guides on their own (deselecting the art); toggle adds or removes them instead, keeping the selected art (a Shift-click on a guide) → {selected: [index…]}",
guides_unlocked,
guide_select
),
@@ -228,7 +228,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Remove Guide",
[],
None,
"{index?} delete ruler guide `index`, else the selected ones (as Delete / edit.clear does) → {count}",
"{index?, indexes?: [index…] (at most 10,000)} delete ruler guide `index` (or guides `indexes`, as dragging their rows onto the Layers panel's trash does), else the selected ones (as Delete / edit.clear does), in one undo step; give `index` or `indexes`, not both, and an index given twice counts once; a hidden or locked guide, or one on a hidden or locked layer, is an error → {count}",
guides_unlocked,
guide_remove
),
@@ -246,7 +246,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Move Guide to Layer",
[],
None,
"{index?, indexes?: [index…], layer: id} put ruler guide `index` (or guides `indexes`), else the selected guides, on layer `layer` (a layer or sublayer), as dragging their rows onto that layer's row in the Layers panel does → {count}",
"{index?, indexes?: [index…] (at most 10,000), layer: id} put ruler guide `index` (or guides `indexes`), else the selected guides, on layer `layer` (a layer or sublayer), as dragging their rows onto that layer's row in the Layers panel does; give `index` or `indexes`, not both, and an index given twice counts once → {count}",
guides_unlocked,
guide_set_layer
),
@@ -805,12 +805,17 @@ fn guide_list(s: &mut Session, _: &Value) -> Result<Value> {
let row = |(i, g): (usize, &Guide)| {
let selected = g.id.is_some_and(|id| st.selection.guides.contains(&id));
let mut r = json!({ "index": i, "vertical": g.vertical, "pos": g.pos, "selected": selected });
if let Some(id) = g.id {
r["id"] = json!(id.0);
}
if let Some(ab) = st.doc.artboards.iter().position(|a| Some(a.id) == g.artboard) {
r["artboard"] = json!(ab);
}
if let Some(l) = g.layer {
r["layer"] = json!(l.0);
}
r["hidden"] = json!(g.hidden);
r["locked"] = json!(g.locked);
r["shown"] = json!(st.doc.guide_shown(g));
r["editable"] = json!(st.doc.guide_editable(g));
r
@@ -824,27 +829,44 @@ fn guide_index_in(ids: &[NodeId], v: Option<&Value>, cmd: &str) -> Result<NodeId
ids.get(i).copied().ok_or_else(|| bad(cmd, format!("no guide {i}")))
}
/// The most guide indexes one `indexes` list may hold.
const MAX_GUIDE_INDEXES: usize = 10_000;
/// `indexes` as a list of at most [`MAX_GUIDE_INDEXES`] entries.
fn guide_index_list<'a>(v: &'a Value, cmd: &str) -> Result<&'a Vec<Value>> {
let list = v.as_array().ok_or_else(|| bad(cmd, "indexes must be an array of guide indexes"))?;
if list.len() > MAX_GUIDE_INDEXES {
return Err(bad(cmd, format!("indexes may hold at most {MAX_GUIDE_INDEXES} entries")));
}
Ok(list)
}
/// The id of ruler guide `index` of the active document (`index` validated).
fn guide_index(s: &Session, v: Option<&Value>, cmd: &str) -> Result<NodeId> {
guide_index_in(&guide_ids(&s.doc()?.doc), v, cmd)
}
/// Is ruler guide `id` one that can be moved or deleted: not on a hidden or locked layer?
/// Is ruler guide `id` one that can be moved or deleted: not hidden or locked itself, nor on a
/// hidden or locked layer?
fn check_editable_guide(s: &Session, id: NodeId) -> Result<NodeId> {
let d = &s.doc()?.doc;
if !d.ruler_guide(id).is_some_and(|g| d.guide_editable(&g)) {
let guide = d.ruler_guide(id);
if guide.as_ref().is_some_and(|g| g.hidden || g.locked) {
return Err(EngineError::Other("the guide is hidden or locked".into()));
}
if !guide.is_some_and(|g| d.guide_editable(&g)) {
return Err(EngineError::Other("the guide is on a hidden or locked layer".into()));
}
Ok(id)
}
/// [`guide_index`] of a guide that can be moved or deleted: not on a hidden or locked layer.
/// [`guide_index`] of a guide that can be moved or deleted ([`check_editable_guide`]).
fn editable_guide_index(s: &Session, v: Option<&Value>, cmd: &str) -> Result<NodeId> {
check_editable_guide(s, guide_index(s, v, cmd)?)
}
fn guide_select(s: &mut Session, p: &Value) -> Result<Value> {
let list = p.get("indexes").and_then(Value::as_array).ok_or_else(|| bad("guide.select", "missing indexes"))?;
let list = guide_index_list(p.get("indexes").ok_or_else(|| bad("guide.select", "missing indexes"))?, "guide.select")?;
let ids = guide_ids(&s.doc()?.doc);
let picked = list.iter().map(|v| guide_index_in(&ids, Some(v), "guide.select")).collect::<Result<Vec<_>>>()?;
if switch_or(p, "toggle", false, "guide.select")? {
@@ -861,18 +883,30 @@ fn guide_select(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "selected": guide_indexes(&st.doc, &st.selection.guides) }))
}
/// Delete ruler guide `index`, else the selected guides, in one undo step → {count}.
/// Delete ruler guide `index` (or guides `indexes`), else the selected guides, in one undo step
/// → {count}.
pub(crate) fn guide_remove(s: &mut Session, p: &Value) -> Result<Value> {
let gone: Vec<NodeId> = match p.get("index") {
Some(v) => vec![editable_guide_index(s, Some(v), "guide.remove")?],
None => s.doc()?.selection.guides.clone(),
const C: &str = "guide.remove";
let mut gone: Vec<NodeId> = match (p.get("index"), p.get("indexes")) {
(Some(_), Some(_)) => return Err(bad(C, "give index or indexes, not both")),
(Some(v), None) => vec![editable_guide_index(s, Some(v), C)?],
(None, Some(list)) => {
let list = guide_index_list(list, C)?;
let ids = guide_ids(&s.doc()?.doc);
// A set, so an index given twice deletes its guide once and the ids held never outnumber the guides.
let set = list.iter().map(|v| check_editable_guide(s, guide_index_in(&ids, Some(v), C)?)).collect::<Result<BTreeSet<_>>>()?;
set.into_iter().collect()
}
(None, None) => s.doc()?.selection.guides.clone(),
};
gone.sort_unstable();
gone.dedup();
if gone.is_empty() {
return Err(bad("guide.remove", "no guide selected"));
return Err(bad(C, "no guide selected"));
}
let label = if gone.len() == 1 { "Delete Guide" } else { "Delete Guides" };
s.edit(label, |d, sel| {
d.retain_guides(sel, |g| !g.id.is_some_and(|id| gone.contains(&id)));
d.retain_guides(sel, |g| !g.id.is_some_and(|id| gone.binary_search(&id).is_ok()));
Ok(())
})?;
Ok(json!({ "count": gone.len() }))
@@ -888,14 +922,19 @@ fn guide_set_layer(s: &mut Session, p: &Value) -> Result<Value> {
if super::layer::locked_within(d, layer) {
return Err(EngineError::Other("the layer or group is locked".into()));
}
let moving: Vec<NodeId> = match (p.get("index"), p.get("indexes").and_then(Value::as_array)) {
(Some(v), _) => vec![editable_guide_index(s, Some(v), C)?],
let mut moving: Vec<NodeId> = match (p.get("index"), p.get("indexes")) {
(Some(_), Some(_)) => return Err(bad(C, "give index or indexes, not both")),
(Some(v), None) => vec![editable_guide_index(s, Some(v), C)?],
(None, Some(list)) => {
let list = guide_index_list(list, C)?;
let ids = guide_ids(&s.doc()?.doc);
list.iter().take(10_000).map(|v| check_editable_guide(s, guide_index_in(&ids, Some(v), C)?)).collect::<Result<Vec<_>>>()?
list.iter().map(|v| check_editable_guide(s, guide_index_in(&ids, Some(v), C)?)).collect::<Result<Vec<_>>>()?
}
(None, None) => s.doc()?.selection.guides.clone(),
};
// An index given twice moves (and counts) its guide once; the others keep their order.
let mut seen = HashSet::new();
moving.retain(|id| seen.insert(*id));
if moving.is_empty() {
return Err(bad(C, "no guide selected (or give an index)"));
}
+83 -19
View File
@@ -116,8 +116,11 @@ pub(super) fn remove_anchor(s: &mut Session, p: &Value) -> Result<Value> {
return Err(EngineError::Other("no such anchor".into()));
}
let mut emptied = Beside::replacing(d, &[id]);
let removed = remove_anchors_of(d, sel, &mut emptied, id, [(si, ai)], curvature)?;
let removed = remove_anchors_of(d, sel, &mut emptied, id, vec![(si, ai)], curvature)?;
emptied.finish(d)?;
if removed {
sel.remove(id);
}
Ok(removed)
})?;
Ok(json!({ "removedObject": removed }))
@@ -136,14 +139,14 @@ pub(super) fn remove_anchors(s: &mut Session, _: &Value) -> Result<Value> {
return Err(bad("path.removeAnchors", "direct-select anchor points of a path"));
}
let removed = s.edit("Remove Anchor Points", |d, sel| {
let mut removed = 0;
let mut gone = Vec::new();
let mut emptied = Beside::replacing(d, &jobs.iter().map(|(id, _)| *id).collect::<Vec<_>>());
for (id, anchors) in jobs {
let shape: Vec<(usize, bool)> =
d.node(id).and_then(Node::path_data).map(|p| p.subpaths.iter().map(|sp| (sp.anchors.len(), sp.closed)).collect()).unwrap_or_default();
let next = following_anchors(&shape, &anchors);
if remove_anchors_of(d, sel, &mut emptied, id, anchors, false)? {
removed += 1;
gone.push(id);
} else if !next.is_empty() {
// The next anchor along is selected, so the next Remove Anchor Points goes on from
// there without picking it first (#2241).
@@ -151,7 +154,8 @@ pub(super) fn remove_anchors(s: &mut Session, _: &Value) -> Result<Value> {
}
}
emptied.finish(d)?;
Ok(removed)
sel.remove_all(gone.iter().copied());
Ok(gone.len())
})?;
Ok(json!({ "removedObjects": removed }))
}
@@ -160,19 +164,32 @@ pub(super) fn remove_anchors(s: &mut Session, _: &Value) -> Result<Value> {
/// path whose subpaths have `shape` (anchor count, closed): in each subpath, the anchor after its
/// last removed one, round the end of a closed subpath, or the one before it at an open subpath's
/// end. Indexes are those after the removal, without the subpaths left with fewer than two anchors.
/// `removed` is in ascending order without repeats, as a selection holds it, and each subpath reads
/// only its own pairs.
fn following_anchors(shape: &[(usize, bool)], removed: &[(usize, usize)]) -> BTreeSet<(usize, usize)> {
let mut next = BTreeSet::new();
let mut kept = 0;
let mut rest = removed;
for (si, &(n, closed)) in shape.iter().enumerate() {
let gone: BTreeSet<usize> = removed.iter().filter(|&&(s, a)| s == si && a < n).map(|&(_, a)| a).collect();
let (mine, after) = rest.split_at(rest.iter().take_while(|&&(s, _)| s == si).count());
rest = after;
let gone = &mine[..mine.partition_point(|&(_, a)| a < n)];
if n - gone.len() < 2 {
continue;
}
if let Some(&last) = gone.last() {
let wrap = if closed { 0..last } else { 0..0 };
let after = (last + 1..n).chain(wrap).find(|a| !gone.contains(a));
if let Some(a) = after.or_else(|| (0..last).rev().find(|a| !gone.contains(a))) {
next.insert((kept, a - gone.range(..a).count()));
if let Some(&(_, last)) = gone.last() {
// Anchors past `last` are all left. Below it, the first one left (round a closed
// subpath's end) is past the removed run from 0, and the last one left is below the
// removed run down from `last`.
let a = if last + 1 < n {
Some(last + 1)
} else if closed {
Some(gone.iter().zip(0..).take_while(|&(&(_, g), k)| g == k).count())
} else {
last.checked_sub(gone.iter().rev().zip((0..=last).rev()).take_while(|&(&(_, g), k)| g == k).count())
};
if let Some(a) = a {
next.insert((kept, a - gone.partition_point(|&(_, g)| g < a)));
}
}
kept += 1;
@@ -183,34 +200,37 @@ fn following_anchors(shape: &[(usize, bool)], removed: &[(usize, usize)]) -> BTr
/// Remove `anchors` (subpath, anchor) of path `id` without opening it, refitting the curve round
/// each one, or with `curvature` re-curving it as the Curvature tool curves its points
/// ([`vectorcraft_tools::draw2::curvature_remove`]). A subpath left with one anchor is removed,
/// and a path left with no subpath is removed through `emptied`. True when the path went.
/// and a path left with no subpath is removed through `emptied`; the caller then takes it out of
/// the selection. True when the path went.
fn remove_anchors_of(
d: &mut Document,
sel: &mut Selection,
emptied: &mut Beside,
id: NodeId,
anchors: impl IntoIterator<Item = (usize, usize)>,
mut anchors: Vec<(usize, usize)>,
curvature: bool,
) -> Result<bool> {
let mut anchors: Vec<(usize, usize)> = anchors.into_iter().collect();
// The last first, so the indexes still to come stay valid.
anchors.sort_unstable_by(|a, b| b.cmp(a));
anchors.dedup();
let path = path_mut(d, id)?;
for (si, ai) in anchors {
if let Some(sp) = path.subpaths.get_mut(si) {
if curvature {
let mut rest = &anchors[..];
while let Some(&(si, _)) = rest.first() {
let (mine, after) = rest.split_at(rest.iter().take_while(|&&(s, _)| s == si).count());
rest = after;
let Some(sp) = path.subpaths.get_mut(si) else { continue };
if curvature {
for &(_, ai) in mine {
vectorcraft_tools::draw2::curvature_remove(sp, ai);
} else {
po::remove_anchor(sp, ai);
}
} else {
po::remove_anchors(sp, &mine.iter().map(|&(_, ai)| ai).collect::<Vec<_>>());
}
}
path.subpaths.retain(|sp| sp.anchors.len() >= 2);
let gone = path.is_empty();
if gone {
emptied.put(d, id, vec![])?;
sel.remove(id);
} else {
sel.anchors.remove(&id);
sel.segments.remove(&id);
@@ -277,3 +297,47 @@ pub(super) fn reshape_segment(s: &mut Session, p: &Value) -> Result<Value> {
})?;
ok()
}
#[cfg(test)]
mod tests {
use super::*;
/// [`following_anchors`] by its definition: for each subpath, a search of the anchors after
/// its last removed one, round a closed end, then before it.
fn following_by_search(shape: &[(usize, bool)], removed: &[(usize, usize)]) -> BTreeSet<(usize, usize)> {
let mut next = BTreeSet::new();
let mut kept = 0;
for (si, &(n, closed)) in shape.iter().enumerate() {
let gone: BTreeSet<usize> = removed.iter().filter(|&&(s, a)| s == si && a < n).map(|&(_, a)| a).collect();
if n - gone.len() < 2 {
continue;
}
if let Some(&last) = gone.last() {
let wrap = if closed { 0..last } else { 0..0 };
let after = (last + 1..n).chain(wrap).find(|a| !gone.contains(a));
if let Some(a) = after.or_else(|| (0..last).rev().find(|a| !gone.contains(a))) {
next.insert((kept, a - gone.range(..a).count()));
}
}
kept += 1;
}
next
}
#[test]
fn following_anchors_matches_a_search_along_each_subpath() {
let mut seed = 0x2545_f491_4f6c_dd1d_u64;
let mut rnd = |m: u64| {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
(seed % m) as usize
};
for case in 0..2000 {
let shape: Vec<(usize, bool)> = (0..rnd(5) + 1).map(|_| (rnd(9), rnd(2) == 0)).collect();
let removed: BTreeSet<(usize, usize)> = (0..rnd(14)).map(|_| (rnd(shape.len() as u64 + 1), rnd(11))).collect();
let removed: Vec<_> = removed.into_iter().collect();
assert_eq!(following_anchors(&shape, &removed), following_by_search(&shape, &removed), "case {case}: {shape:?} removing {removed:?}");
}
}
}
+2 -2
View File
@@ -11,7 +11,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Pencil",
[],
None,
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks), fidelity?: pt (1.5), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\"|\"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end: \"start\"|\"end\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end; with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it",
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\"|\"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end: \"start\"|\"end\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end; with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it",
has_doc,
freehand
),
@@ -110,7 +110,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Smooth",
[],
None,
"{points: [[x,y]…], radius?: pt (12), fidelity?: pt (2.5)} smooth selected paths near the drag → {ids, before, after}",
"{points: [[x,y]…], radius?: pt (12), fidelity?: pt (2.5; kept within 0.000078125 and about 3195, the Smooth tool's 0.05 to 100 px at the highest and the lowest zoom: the tool sends its Fidelity in screen pixels divided by the zoom)} smooth selected paths near the drag → {ids, before, after}",
has_selection,
smooth_region
),
+8 -2
View File
@@ -151,7 +151,11 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
}
let pen = PenRecord::of_samples(&samples);
let mut pts: Vec<Point> = samples.into_iter().map(|s| s.pt).collect();
let tol = number_or(p, "fidelity", 1.5, C)?.clamp(vectorcraft_tools::draw2::MIN_FIT_TOLERANCE, 100.0);
let tol = number_or(p, "fidelity", 1.5, C)?;
let (lo, hi) = (vectorcraft_tools::draw2::MIN_FIT_TOLERANCE, vectorcraft_tools::draw2::MAX_FIT_TOLERANCE);
if !(lo..=hi).contains(&tol) {
return Err(bad(C, format!("`fidelity` must be from {lo} to {hi} pt")));
}
// The tolerance the stroke is fitted at; with `fit: false` it is not fitted.
let fit_tol = switch_or(p, "fit", true, C)?.then_some(tol);
let closed = switch_or(p, "closed", false, C)?;
@@ -200,7 +204,9 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
}
None => None,
};
let close_tol = (tol * 4.0).max(6.0);
// An extending stroke that ends within four Fidelities of the path's other end closes it:
// at least 6 pt and at most 400 pt, whatever the Fidelity it is fitted at.
let close_tol = (tol * 4.0).clamp(6.0, 400.0);
let closing = connect.is_none() && sp.anchors.len() >= 2 && pts.last().is_some_and(|p| p.distance(first) <= close_tol);
if closing && let Some(l) = pts.last_mut() {
*l = first;
+275 -24
View File
@@ -2,16 +2,40 @@ use vectorcraft_pathops::addons::pathtools as pt;
use super::common::{dist_to_polyline, ids_json, path_mut, path_of, points_param, poly_bounds, subpath_len, target_paths};
use super::{
Anchor, BezPath, CubicBez, NodeId, ParamCurve, ParamCurveNearest, PathData, Point, Result, Session, SimplifyOptions, SubPath, Value, json,
Anchor, BezPath, CubicBez, NodeId, ParamCurve, ParamCurveNearest, PathData, Point, Rect, Result, Session, SimplifyOptions, SubPath, Value, json,
number_or, po,
};
// ---------- Smooth ----------
/// Refit the anchors of an open run `a[lo..=hi]` keeping its end points and outer handles.
fn refit_run(anchors: &[Anchor], tol: f64) -> Vec<Anchor> {
/// The spread (points) of the Gaussian the Smooth tool smooths a path along its length with before
/// refitting it, as a share of the tool's reach: a third, so each point is averaged with the stretch
/// of path within the reach on either side of it. VectorCraft's own value.
const SMOOTH_SPREAD: f64 = 1.0 / 3.0;
/// The options the Smooth tool refits with: the path smoothed along its length by a Gaussian of
/// spread `sigma` (none at 0), then refitted within `tol` of that and within twice the distance the
/// smoothing moved it, keeping a corner only where the path turns back on itself. `free` says whether
/// the start and the end of the stretch refitted are ends of an open path, whose direction then
/// follows the smoothed path within the reach rather than the first or last segment.
fn refit_options(tol: f64, sigma: f64, free: [bool; 2]) -> SimplifyOptions {
SimplifyOptions {
tolerance: tol,
corner_angle_deg: 179.0,
straight_lines: false,
smooth: sigma,
smooth_moved_only: true,
free_start: free[0],
free_end: free[1],
}
}
/// Smooth and refit the anchors of an open run `a[lo..=hi]` keeping its end points and outer handles.
/// `free` says whether its first and last anchors are ends of an open path: the curve leaving or
/// arriving at such an end can turn.
fn refit_run(anchors: &[Anchor], tol: f64, sigma: f64, free: [bool; 2]) -> Vec<Anchor> {
let piece = PathData::single(SubPath::new(anchors.to_vec(), false));
let fitted = po::simplify_with(&piece, &SimplifyOptions { tolerance: tol, corner_angle_deg: 179.0, straight_lines: false, ..Default::default() });
let fitted = po::simplify_with(&piece, &refit_options(tol, sigma, free));
let Some(mut out) = fitted.subpaths.into_iter().next().map(|s| s.anchors).filter(|a| a.len() >= 2) else { return anchors.to_vec() };
let (f, l) = (anchors[0], anchors[anchors.len() - 1]);
let last = out.len() - 1;
@@ -25,19 +49,198 @@ fn refit_run(anchors: &[Anchor], tol: f64) -> Vec<Anchor> {
out
}
fn smooth_subpath(sp: &SubPath, near: &dyn Fn(Point) -> bool, tol: f64) -> Option<SubPath> {
/// Pieces of curve that one Smooth drag measures against the drag while it searches the segments
/// under it ([`reach_samples`]), shared equally by the curved segments that come within its reach,
/// each of which gets at least one: enough to search 300,000 pt of curve within the default reach
/// of the drag.
const MAX_REACH_PIECES: usize = 1 << 17;
/// The box around the control points of `s`, which holds all of `s`.
fn control_box(s: CubicBez) -> Rect {
Rect::from_points(s.p0, s.p1).union_pt(s.p2).union_pt(s.p3)
}
/// The stretches of the drag `pts` (stretch `k` runs from `pts[k]` to the next point; a drag of one
/// point has the point as its only stretch).
fn drag_stretches(pts: &[Point]) -> Vec<usize> {
(0..pts.len().saturating_sub(1).max(1)).collect()
}
/// The stretches of the drag `pts` among `of` whose bounds come within `radius` of `r` on both
/// axes: every stretch within `radius` of a point in `r`, and perhaps a few more.
fn stretches_near(pts: &[Point], of: &[usize], r: Rect, radius: f64) -> Vec<usize> {
let r = r.inflate(radius, radius);
of.iter()
.copied()
.filter(|&k| {
let Some(&a) = pts.get(k) else { return false };
let b = pts.get(k + 1).copied().unwrap_or(a);
a.x.min(b.x) <= r.x1 && a.x.max(b.x) >= r.x0 && a.y.min(b.y) <= r.y1 && a.y.max(b.y) >= r.y0
})
.collect()
}
/// The distance from `q` to the nearest of the stretches `of` of the drag `pts`.
fn dist_to_stretches(pts: &[Point], of: &[usize], q: Point) -> f64 {
of.iter()
.filter_map(|&k| {
let a = *pts.get(k)?;
Some(dist_to_polyline(&[a, pts.get(k + 1).copied().unwrap_or(a)], q))
})
.fold(f64::INFINITY, f64::min)
}
/// The place on `s` (0 to 1) nearest to the stretches `of` of the drag `pts`, and its distance from
/// them. For each stretch the nearest place is at one of the stretch's ends, at an end of `s`, or
/// where `s` crosses the stretch's line or stops moving toward or away from it.
fn nearest_to_stretches(s: CubicBez, pts: &[Point], of: &[usize]) -> (f64, f64) {
let (c1, c2, c3) = (3.0 * (s.p1 - s.p0), 3.0 * ((s.p2 - s.p1) - (s.p1 - s.p0)), (s.p3 - s.p0) - 3.0 * (s.p2 - s.p1));
let mut best = (0.5, f64::INFINITY);
for &k in of {
let Some(&a) = pts.get(k) else { continue };
let b = pts.get(k + 1).copied().unwrap_or(a);
let mut places: Vec<f64> = vec![0.0, 1.0, s.nearest(a, 1e-9).t, s.nearest(b, 1e-9).t];
let d = b - a;
if d.hypot() > 1e-12 {
let (f0, f1, f2, f3) = (d.cross(s.p0 - a), d.cross(c1), d.cross(c2), d.cross(c3));
places.extend(kurbo::common::solve_cubic(f0, f1, f2, f3));
places.extend(kurbo::common::solve_quadratic(f1, 2.0 * f2, 3.0 * f3));
}
for u in places.into_iter().filter(|u| (0.0..=1.0).contains(u)) {
let dist = dist_to_polyline(&[a, b], s.eval(u));
if dist < best.1 {
best = (u, dist);
}
}
}
best
}
/// How many curved segments of `pd` may come within `radius` of the drag `pts`.
fn segments_in_reach(pd: &PathData, pts: &[Point], radius: f64) -> usize {
let all = drag_stretches(pts);
pd.subpaths
.iter()
.map(|sp| {
(0..sp.segment_count())
.filter(|&i| {
!vectorcraft_tools::draw2::segment_is_straight(sp, i) && !stretches_near(pts, &all, control_box(sp.segment(i)), radius).is_empty()
})
.count()
})
.sum()
}
/// Samples along the part of `c` from `t0` to `t1`, in order: (t, whether the point there is within
/// `radius` of the stretches `of` of the drag `pts`). A piece no stretch comes near gives one sample
/// out of reach; the others are halved until their control polygon is no longer than half the
/// reach, or until `budget` pieces have been measured, and then give one sample: in reach at the
/// piece's middle or at its place nearest the drag when either is in reach, otherwise out of reach
/// at its middle. Each piece measures only the stretches near
/// the piece it was cut from, so a long drag along a long curve costs about one pass over the drag
/// per halving, plus the stretches near each piece.
fn reach_samples(c: CubicBez, (t0, t1): (f64, f64), (pts, of): (&[Point], &[usize]), radius: f64, budget: &mut usize, out: &mut Vec<(f64, bool)>) {
*budget = budget.saturating_sub(1);
let s = c.subsegment(t0..t1);
let mid = 0.5 * (t0 + t1);
let near = stretches_near(pts, of, control_box(s), radius);
if near.is_empty() {
out.push((mid, false));
return;
}
let len = s.p0.distance(s.p1) + s.p1.distance(s.p2) + s.p2.distance(s.p3);
if len <= (radius / 2.0).max(1e-3) || *budget == 0 || mid <= t0 || mid >= t1 {
// The piece's middle, or the place on it nearest the drag when the middle is out of reach.
let sample = if dist_to_stretches(pts, &near, c.eval(mid)) <= radius {
(mid, true)
} else {
let (u, dist) = nearest_to_stretches(s, pts, &near);
if dist <= radius { (t0 + u * (t1 - t0), true) } else { (mid, false) }
};
out.push(sample);
return;
}
reach_samples(c, (t0, mid), (pts, &near), radius, budget, out);
reach_samples(c, (mid, t1), (pts, &near), radius, budget, out);
}
/// `sp` cut where the reach `radius` of the drag `pts` crosses its curved segments, and whether each
/// anchor of the result is in reach. An anchor in reach is added in the middle of each stretch of a
/// segment in reach that does not run on from one of the segment's anchors in reach, and an anchor
/// out of reach in the middle of each stretch out of reach between two stretches in reach, so that a
/// stretch in reach is smoothed even when the segment's anchors are not, and the stretches between
/// stay as they are. A segment is searched no more than half the reach apart where it comes within
/// the reach of the drag ([`reach_samples`]), measuring up to `share` pieces of each segment.
fn mark_reached(sp: &SubPath, pts: &[Point], radius: f64, share: usize) -> (SubPath, Vec<bool>) {
let near = |q: Point| dist_to_polyline(pts, q) <= radius;
let n = sp.anchors.len();
let marked: Vec<bool> = sp.anchors.iter().map(|a| near(a.p)).collect();
if n < 3 || !marked.iter().any(|m| *m) {
let mut places = vec![];
let all = drag_stretches(pts);
for i in 0..sp.segment_count() {
if vectorcraft_tools::draw2::segment_is_straight(sp, i) {
continue;
}
let c = sp.segment(i);
let (mut samples, mut budget) = (vec![], share);
reach_samples(c, (0.0, 1.0), (pts, &all), radius, &mut budget, &mut samples);
// Stretches of samples alike, in order: (in reach, first, last).
let mut runs: Vec<(bool, usize, usize)> = vec![];
for (k, s) in samples.iter().enumerate() {
match runs.last_mut() {
Some(r) if r.0 == s.1 => r.2 = k,
_ => runs.push((s.1, k, k)),
}
}
let last = samples.len().saturating_sub(1);
let (start, end) = (marked[i], marked[(i + 1) % n]);
for (j, &(reached, first, to)) in runs.iter().enumerate() {
let mid = samples[(first + to) / 2].0;
let joined = (first == 0 && start) || (to == last && end);
if reached && !joined {
places.push((i, mid));
}
// A gap with reach on both sides: the segment's anchor or a stretch on each side.
let before = if j == 0 { start } else { runs[j - 1].0 };
let after = runs.get(j + 1).map_or(end, |r| r.0);
if !reached && before && after {
places.push((i, mid));
}
}
}
// A place on one of the segment's ends would name that anchor rather than add one.
places.retain(|(_, t)| (1e-5..=1.0 - 1e-5).contains(t));
if places.is_empty() {
return (sp.clone(), marked);
}
let (out, added) = pt::insert_at(sp, &places);
// The anchors already there keep their marks. A new anchor split off at a sample in reach can
// land a rounding error farther away than the sample.
let mut kept = marked.into_iter();
let marked = out
.anchors
.iter()
.enumerate()
.map(|(j, a)| if added.contains(&j) { dist_to_polyline(pts, a.p) <= radius + 1e-9 * radius.max(1.0) } else { kept.next().unwrap_or(false) })
.collect();
(out, marked)
}
fn smooth_subpath(sp: &SubPath, pts: &[Point], radius: f64, share: usize, tol: f64, sigma: f64) -> Option<SubPath> {
if sp.anchors.len() < 2 {
return None;
}
let near = &|q: Point| dist_to_polyline(pts, q) <= radius;
// A drag along a segment smooths it even when its anchors are out of reach.
let (sp, marked) = mark_reached(sp, pts, radius, share);
let sp = &sp;
if !marked.iter().any(|m| *m) {
return None;
}
if sp.closed {
let Some(k) = marked.iter().position(|m| !m) else {
// Everything is in range: smooth the whole closed path.
let f = po::simplify_with(
&PathData::single(sp.clone()),
&SimplifyOptions { tolerance: tol, corner_angle_deg: 179.0, straight_lines: false, ..Default::default() },
);
// Everything is in range: smooth the whole closed path, across its start too.
let f = po::simplify_with(&PathData::single(sp.clone()), &refit_options(tol, sigma, [false; 2]));
return f.subpaths.into_iter().next();
};
// Rotate so an untouched anchor comes first, duplicate it at the end and treat as open.
@@ -48,14 +251,14 @@ fn smooth_subpath(sp: &SubPath, near: &dyn Fn(Point) -> bool, tol: f64) -> Optio
open.anchors.push(open.anchors[0]);
m.push(false);
open.closed = false;
let mut res = smooth_open(&open.anchors, &m, near, tol);
let mut res = smooth_open(&open.anchors, &m, near, tol, sigma, false);
let l = res.pop()?;
if let Some(r0) = res.first_mut() {
r0.h_in = l.h_in;
}
return Some(SubPath::new(res, true));
}
Some(SubPath::new(smooth_open(&sp.anchors, &marked, near, tol), false))
Some(SubPath::new(smooth_open(&sp.anchors, &marked, near, tol, sigma, true), false))
}
/// The segment `c`, which ends in the drag's reach (`near`) and starts outside it, split where it
@@ -84,10 +287,13 @@ fn split_at_reach(c: CubicBez, near: &dyn Fn(Point) -> bool) -> Option<(CubicBez
(hi > 0.02).then(|| (part(0.0..hi), part(hi..1.0)))
}
/// `anchors` with each run of `marked` ones refitted, together with the stretch of the segments
/// leading into the run that is in the drag's reach (`near`): a short drag smooths what is under
/// it, and the rest of a long segment next to it stays as it was (#1512).
fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool, tol: f64) -> Vec<Anchor> {
/// `anchors` with each run of `marked` ones smoothed by a Gaussian of spread `sigma` and refitted
/// within `tol`, together with the stretch of the segments leading into the run that is in the
/// drag's reach (`near`): a short drag smooths what is under it, and the rest of a long segment next
/// to it stays as it was (#1512). With `open`, `anchors` are an open path, and the curve at its first
/// or last anchor turns with the smoothing when a run's refit reaches that anchor; a run's other ends,
/// and those of the open run a closed path is cut into, keep their direction.
fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool, tol: f64, sigma: f64, open: bool) -> Vec<Anchor> {
let n = anchors.len();
let mut runs = vec![];
let mut i = 0;
@@ -105,7 +311,7 @@ fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool
for (a, b) in runs.into_iter().rev() {
let lo = a.saturating_sub(1);
let hi = (b + 1).min(n - 1);
if hi - lo < 2 {
if hi == lo {
continue;
}
let mut piece = out[lo..=hi].to_vec();
@@ -127,7 +333,8 @@ fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool
head = Some(Anchor { h_out: far.p1, ..*outer });
*outer = Anchor::with_handles(far.p3, far.p2, reach.p1);
}
let new = refit_run(&piece, tol);
let free = [open && lo == 0 && head.is_none(), open && hi == n - 1 && tail.is_none()];
let new = refit_run(&piece, tol, sigma, free);
out.splice(lo..=hi, head.into_iter().chain(new).chain(tail));
}
out
@@ -137,18 +344,24 @@ pub(super) fn smooth_region(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "path.smoothRegion";
let pts = points_param(p, "points", C)?;
let radius = number_or(p, "radius", 12.0, C)?.max(0.0);
let tol = number_or(p, "fidelity", 2.5, C)?.clamp(vectorcraft_tools::draw2::SMOOTH_MIN_FIDELITY, 100.0);
let tol = number_or(p, "fidelity", 2.5, C)?.clamp(vectorcraft_tools::draw2::SMOOTH_MIN_TOLERANCE, vectorcraft_tools::draw2::SMOOTH_MAX_TOLERANCE);
let sigma = radius * SMOOTH_SPREAD;
let st = s.doc()?;
let near = |q: Point| dist_to_polyline(&pts, q) <= radius;
let mut plan = vec![];
let (mut before, mut after) = (0, 0);
let mut paths = vec![];
for id in target_paths(&st.doc, &st.selection, poly_bounds(&pts, radius)) {
let (pd, _) = path_of(&st.doc, id)?;
paths.push((id, path_of(&st.doc, id)?.0));
}
// Each curved segment in reach gets the same share of the search, whatever order they come in.
let in_reach: usize = paths.iter().map(|(_, pd)| segments_in_reach(pd, &pts, radius)).sum();
let share = (MAX_REACH_PIECES / in_reach.max(1)).max(1);
for (id, pd) in paths {
let mut changed = false;
let subs: Vec<SubPath> = pd
.subpaths
.iter()
.map(|sp| match smooth_subpath(sp, &near, tol) {
.map(|sp| match smooth_subpath(sp, &pts, radius, share, tol, sigma) {
Some(n) if n != *sp && n.anchors.len() >= 2 => {
changed = true;
n
@@ -167,9 +380,13 @@ pub(super) fn smooth_region(s: &mut Session, p: &Value) -> Result<Value> {
return Ok(json!({ "ids": [], "before": 0, "after": 0 }));
}
let ids: Vec<NodeId> = plan.iter().map(|(id, _)| *id).collect();
s.edit("Smooth", |d, _| {
s.edit("Smooth", |d, sel| {
for (id, np) in plan {
*path_mut(d, id)? = np;
// The smoothed path has new anchors, so the old anchor and segment indices are
// dropped and the path stays selected whole.
sel.anchors.remove(&id);
sel.segments.remove(&id);
}
Ok(())
})?;
@@ -399,3 +616,37 @@ pub(super) fn join_scrub(s: &mut Session, p: &Value) -> Result<Value> {
})?;
Ok(json!({ "id": ida.0 }))
}
#[cfg(test)]
mod tests {
use super::*;
/// Searching a curve 1,000,000 pt long under a drag of 1,000 points along it measures no more
/// pieces than the budget it is given, and a search with none left gives one sample.
#[test]
fn searching_a_segment_under_a_drag_stays_within_its_budget() {
let c = CubicBez::new(Point::new(0.0, 0.0), Point::new(300000.0, 0.0), Point::new(700000.0, 0.0), Point::new(1000000.0, 0.0));
let pts: Vec<Point> = (0..1000).map(|i| Point::new(f64::from(i) * 1000.0, 0.0)).collect();
let all = drag_stretches(&pts);
let mut budget = MAX_REACH_PIECES;
let (mut first, mut second) = (vec![], vec![]);
reach_samples(c, (0.0, 1.0), (&pts, &all), 12.0, &mut budget, &mut first);
reach_samples(c, (0.0, 1.0), (&pts, &all), 12.0, &mut budget, &mut second);
assert!(first.len() <= MAX_REACH_PIECES, "{} samples", first.len());
assert_eq!((budget, second.len()), (0, 1), "the budget is spent, so the next search gives one sample");
}
/// A small piece of curve is measured only against the few stretches of a drag of 100,000
/// points that come near it, and a drag of one point has that point as its stretch.
#[test]
fn a_small_piece_is_measured_against_the_stretches_near_it() {
let pts: Vec<Point> = (0..100_000).map(|i| Point::new(f64::from(i) * 5.0, 0.0)).collect();
let all = drag_stretches(&pts);
let near = stretches_near(&pts, &all, Rect::new(1000.0, 3.0, 1004.0, 6.0), 12.0);
assert_eq!(near, (197..=203).collect::<Vec<_>>());
assert!((dist_to_stretches(&pts, &near, Point::new(1002.0, 5.0)) - 5.0).abs() < 1e-12);
let one = [Point::new(10.0, 10.0)];
assert_eq!(drag_stretches(&one), vec![0]);
assert!((dist_to_stretches(&one, &[0], Point::new(13.0, 14.0)) - 5.0).abs() < 1e-12);
}
}
+128 -19
View File
@@ -1,6 +1,6 @@
//! File (document-level) and Edit commands, plus document queries.
use std::collections::{BTreeMap, BTreeSet};
use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::sync::Arc;
use serde_json::{Value, json};
@@ -13,7 +13,7 @@ use super::{
f64_req, finite_numbers, has_clipboard, has_doc, has_selection, has_selection_guides_or_artboard_tool, has_selection_or_guides, index, number_or,
object_param, ok, point_param, str_param, switch_or,
};
use crate::{Clipboard, EngineError, inspect};
use crate::{Clipboard, EngineError, SourceLayer, inspect};
/// Register editing commands, including document-to-document artwork drops and their parameter contracts.
pub fn specs() -> Vec<CommandSpec> {
@@ -179,7 +179,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Paste",
["Edit"],
Some("Cmd+V"),
"{center?: [x, y], artboardsAt?: [x, y], dx?, dy?, swatchConflict?} paste centred on `center` (the app passes the view centre), else offset by dx/dy (default: the Paste Offset preference). Pasting brings the image blobs, symbols, patterns, global and spot swatches (with the tint swatches of the tints used), gradient swatches, graphic styles, character and paragraph styles and brushes the objects use; one of the same name that differs comes in renamed. swatchConflict, for a swatch whose name the document gives another colour (clipboard.conflicts): \"merge\" (default: the objects take the document's swatch) | \"add\" (the pasted swatch comes in renamed) | {name: \"merge\"|\"add\"}. With Paste Remembers Layers on (layer.pasteRemembersLayers), objects go back into the layers they came from (by name; made when missing). Artboards copied with artboard.copy come with their art, together right of the last artboard as they lay, or centered on `artboardsAt` (the Artboard tool's canvas menu passes the right-click point; a value that is not [x, y] is an error) (the other paste commands but Paste on All Artboards: where they were), their art back in the layers it came from, and the Artboard tool, when chosen, selects them. In Draw Inside (view.drawMode) the objects go inside the object drawn into, as new art does, and Paste Remembers Layers doesn't apply; edit.pasteInPlace and edit.pasteOnAllArtboards do the same, and in Draw Behind they go behind the selection as edit.pasteInBack puts them; edit.pasteInFront and edit.pasteInBack ignore the drawing mode → {ids, artboard: the first new artboard's index or null, artboards: the new artboards' indices, added: resources added, merged: conflicts merged, renamed: [{kind, from, to}]}",
"{center?: [x, y], artboardsAt?: [x, y], dx?, dy?, swatchConflict?} paste centred on `center` (the app passes the view centre), else offset by dx/dy (default: the Paste Offset preference). Pasting brings the image blobs, symbols, patterns, global and spot swatches (with the tint swatches of the tints used), gradient swatches, graphic styles, character and paragraph styles and brushes the objects use; one of the same name that differs comes in renamed. swatchConflict, for a swatch whose name the document gives another colour (clipboard.conflicts): \"merge\" (default: the objects take the document's swatch) | \"add\" (the pasted swatch comes in renamed) | {name: \"merge\"|\"add\"}. With Paste Remembers Layers on (layer.pasteRemembersLayers), objects go back into the layers and sublayers they came from (by the names of the layer and the layers around it in another document; a missing sublayer is made inside its layer; a hidden or locked one is an error and nothing is pasted). Artboards copied with artboard.copy come with their art, together right of the last artboard as they lay, or centered on `artboardsAt` (the Artboard tool's canvas menu passes the right-click point; a value that is not [x, y] is an error) (the other paste commands but Paste on All Artboards: where they were), their art back in the layers it came from, and the Artboard tool, when chosen, selects them. In Draw Inside (view.drawMode) the objects go inside the object drawn into, as new art does, and Paste Remembers Layers doesn't apply; edit.pasteInPlace and edit.pasteOnAllArtboards do the same, and in Draw Behind they go behind the selection as edit.pasteInBack puts them; edit.pasteInFront and edit.pasteInBack ignore the drawing mode → {ids, artboard: the first new artboard's index or null, artboards: the new artboards' indices, added: resources added, merged: conflicts merged, renamed: [{kind, from, to}]}",
has_clipboard,
|s, p| paste(s, p, PasteMode::Offset)
),
@@ -678,12 +678,22 @@ fn undo_group_end(s: &mut Session, p: &Value) -> Result<Value> {
/// under an interaction that would then preview on, or cancel to, the document from before (#1719).
/// A typing session also ends in the Type tool, whose caret and marked text (IME) must follow the
/// document. A preview that Real-time Drawing off left unapplied is applied first, as the tool's own
/// commit applies it; when it fails, the interaction is canceled.
/// commit applies it; when it fails, the interaction is canceled. The applied preview's warning
/// goes to the running command's result or the tool's status messages, as the tool's own commit
/// reports it ([`Session::note_settled_warning`]).
pub(crate) fn settle_interaction(s: &mut Session) -> Result<()> {
let typing = typing_in_progress(s);
match s.unapplied_interaction_preview().filter(|_| !s.previewing) {
Some((cmd, p)) if s.preview(&cmd, &p).is_err() => s.cancel_interaction()?,
_ => s.commit_interaction()?,
Some((cmd, p)) => match s.preview(&cmd, &p) {
Ok(v) => {
if let Some(w) = v.get("warning").and_then(Value::as_str) {
s.note_settled_warning(w);
}
s.commit_interaction()?
}
Err(_) => s.cancel_interaction()?,
},
None => s.commit_interaction()?,
}
if typing {
s.set_tool_option("endTyping", &Value::Bool(true));
@@ -1086,7 +1096,7 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
subpaths.extend(super::path::without_segments(sp, &cuts));
} else {
// Picked anchors leave the path with their connections, as Clear removes them.
let gone: BTreeSet<usize> = anchor_refs.into_iter().flatten().filter_map(|&(s, a)| (s == si).then_some(a)).collect();
let gone: BTreeSet<usize> = anchor_refs.into_iter().flat_map(|refs| super::path::subpath_refs(refs, si)).collect();
subpaths.extend(super::path::without_anchors(sp, &gone));
}
}
@@ -1380,6 +1390,9 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
&& inside.is_none()
&& (st.doc.paste_remembers_layers || boards.is_some())
&& parent.is_some_and(|p| st.doc.node(p).is_some_and(Node::is_layer));
// Each object's remembered layer, found before anything is pasted: a hidden or locked one
// refuses the whole paste.
let remembered = if remember { remembered_layers(&st.doc, &clip.source_layers, same_doc)? } else { vec![] };
// Front/back: relative to the selection (top-most / bottom-most selected object); with
// nothing selected, the top / bottom of the current layer. Art other than paths goes beside
// the compound path that holds the selected object, not into it.
@@ -1423,7 +1436,8 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
.flat_map(|(all, dv)| all.iter().map(move |a| (a, dv)))
.map(|(a, dv)| super::panelcmds::push_artboard_copy(d, a, a.rect + dv))
.collect();
let mut layers: BTreeMap<&str, NodeId> = BTreeMap::new();
// The layers made for remembered layers the document lacks, by parent and name.
let mut made = HashMap::new();
// Objects pasted into each parent so far (keeps their order in front and back pastes).
let mut placed: BTreeMap<Option<NodeId>, usize> = BTreeMap::new();
let mut new_ids = vec![];
@@ -1437,8 +1451,9 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
// including the pattern phase, independently of transform-tool settings.
c.transform(xf, sc);
}
let layer = match clip.source_layers.get(k) {
Some(Some(name)) if remember => Some(*layers.entry(name).or_insert_with(|| layer_named(d, name))),
let layer = match remembered.get(k) {
Some(Some(Remembered::Layer(l))) => Some(*l),
Some(Some(Remembered::Make { parent, names })) => make_layers(d, &mut made, *parent, names)?,
_ => None,
};
// In a clip group or a clipping layer the bottom child is the clipping path: art pasted
@@ -1557,17 +1572,111 @@ fn paste_anchor(doc: &Document, id: NodeId, can_enter_compound: bool) -> NodeId
}
}
/// The first unlocked layer or sublayer called `name` (topmost first), or a new top layer.
fn layer_named(d: &mut Document, name: &str) -> NodeId {
let mut found = None;
for l in d.layers.iter().rev() {
l.walk(&mut |n| {
if found.is_none() && n.is_layer() && !n.locked && n.name.as_deref() == Some(name) {
found = Some(n.id);
/// Where Paste Remembers Layers puts an object: a layer or sublayer of the document, or new
/// layers `names`, each inside the one before, the first under `parent` (none: on top).
#[derive(Clone, Debug, PartialEq)]
enum Remembered {
Layer(NodeId),
Make { parent: Option<NodeId>, names: Vec<String> },
}
/// [`remembered_layer`] for each object's source layer, worked out once for each layer.
fn remembered_layers(d: &Document, sources: &[Option<SourceLayer>], same_doc: bool) -> Result<Vec<Option<Remembered>>> {
let mut found: HashMap<&SourceLayer, Remembered> = HashMap::new();
sources
.iter()
.map(|src| {
let Some(src) = src else { return Ok(None) };
if let Some(r) = found.get(src) {
return Ok(Some(r.clone()));
}
});
let r = remembered_layer(d, src, same_doc)?;
found.insert(src, r.clone());
Ok(Some(r))
})
.collect()
}
/// The layer `src` names in `d`. In the document it was copied from, the layer that held the
/// object is kept while it is there with its name, wherever it was moved; else the layers around
/// it still where they were (by id) are kept. Below them, and in another document from the top,
/// each name is matched among the layers inside the one above (the topmost of the same name whose
/// layers match the most names, a shown and unlocked one first). The names left unmatched are
/// made. A matched layer that is hidden or locked, or inside one that is, is an error.
fn remembered_layer(d: &Document, src: &SourceLayer, same_doc: bool) -> Result<Remembered> {
let held = |id: &NodeId| d.node(*id).is_some_and(|n| n.is_layer() && n.name.as_ref() == src.names.last());
let kept = if same_doc && src.ids.last().is_some_and(held) {
src.ids.len()
} else if same_doc {
(1..=src.ids.len())
.rev()
.find(|&j| d.node(src.ids[j - 1]).is_some_and(Node::is_layer) && d.ancestry(src.ids[j - 1]).is_some_and(|a| a == src.ids[..j]))
.unwrap_or(0)
} else {
0
};
let rest = &src.names[kept..];
let (end, matched, _) = named_chain(d, kept.checked_sub(1).map(|j| src.ids[j]), rest);
if let Some(l) = end
&& !d.ancestry(l).is_some_and(|a| a.iter().all(|i| d.node(*i).is_some_and(|n| n.visible && !n.locked)))
{
return Err(EngineError::Other("the target layer is locked or hidden".into()));
}
found.unwrap_or_else(|| d.add_layer(Some(name)))
Ok(match end {
Some(l) if matched == rest.len() => Remembered::Layer(l),
parent => Remembered::Make { parent, names: rest[matched..].to_vec() },
})
}
/// The deepest chain of layers inside `parent` (none: the top level) named `names` one inside the
/// other: its last layer (`parent` when none matches), how many names it matched and whether all
/// its layers are shown and unlocked. Of chains as deep, the topmost shown and unlocked one wins.
fn named_chain(d: &Document, parent: Option<NodeId>, names: &[String]) -> (Option<NodeId>, usize, bool) {
let mut best = (parent, 0, true);
let Some((name, rest)) = names.split_first() else { return best };
let siblings = match parent {
None => Some(&d.layers),
Some(p) => d.node(p).and_then(Node::children),
};
for l in siblings.into_iter().flatten().rev().filter(|l| l.is_layer() && l.name.as_deref() == Some(name.as_str())) {
let (end, n, open) = named_chain(d, Some(l.id), rest);
let chain = (end, n + 1, open && l.visible && !l.locked);
if (chain.1, chain.2) > (best.1, best.2) {
best = chain;
}
}
best
}
/// Layers `names`, each inside the one before, the first under `parent` (none: on top); `made`
/// keeps the ones a paste has made, by parent and name, so they are made once. The last one, or
/// none when `names` is empty.
fn make_layers(
d: &mut Document,
made: &mut HashMap<(Option<NodeId>, String), NodeId>,
parent: Option<NodeId>,
names: &[String],
) -> Result<Option<NodeId>> {
let mut at = parent;
for name in names {
let key = (at, name.clone());
let id = match made.get(&key) {
Some(id) => *id,
None => {
let id = match at {
None => d.add_layer(Some(name)),
Some(p) => {
let layer = super::layer::make_layer(d, Some(name));
d.insert(Some(p), usize::MAX, layer)?
}
};
made.insert(key, id);
id
}
};
at = Some(id);
}
Ok(at.filter(|_| !names.is_empty()))
}
fn duplicate(s: &mut Session, p: &Value) -> Result<Value> {
+29 -13
View File
@@ -13,10 +13,10 @@ use vectorcraft_doc::{Document, Effect, Node, NodeKind, StrokeLayer};
use vectorcraft_geom::{FillRule, PathData};
use vectorcraft_render::effects;
use super::appearance::{ItemTarget, aligned, appearance_targets, index_param, item_indices, item_target, item_target_at};
use super::appearance::{ItemTarget, aligned, appearance_targets, edit_targets, index_param, item_indices, item_target, item_target_at};
use super::expand::has_seeded;
use super::rasterfx;
use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, cmd, fileio, has_doc, str_param, switch_or};
use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, check_switches, cmd, fileio, has_doc, str_param, switch_or};
/// The name of the `svg.filter` effect drawing `xml`: its `<filter>` id. An effect names the
/// document's filter of that name, so `xml` that differs from the document's filter of the same
@@ -49,7 +49,7 @@ fn effect_specs() -> Vec<CommandSpec> {
"Apply Effect",
[],
None,
"{effect: id (see effect.list, e.g. \"stylize.dropShadow\", \"distort.roughen\", \"warp.arc\", or \"plugin.<id>\" for an installed effect plug-in), params?: {…} (missing keys take the dialog defaults), item?: appearance item index|null (apply to that fill/stroke only; omitted: the Appearance panel's active item, else the whole object), ids?|id?: [..] (layers too), target?: \"object\"|\"contents\" (contents: the objects inside groups and layers)} append a live effect to each selected object's appearance (a group's or layer's apply to its members as one piece: one combined shadow; a Pathfinder effect, which combines a group's contents, groups several loose selected objects first, in the same undo step) → {ids, index, item, grouped?}",
"{effect: id (see effect.list, e.g. \"stylize.dropShadow\", \"distort.roughen\", \"warp.arc\", or \"plugin.<id>\" for an installed effect plug-in), params?: {…} (missing keys take the dialog defaults), item?: appearance item index|null (apply to that fill/stroke only; omitted: the Appearance panel's active item, else the whole object), ids?|id?: [..] (layers too), target?: \"object\"|\"contents\" (contents: the objects inside groups and layers)} append a live effect to each selected object's appearance (a group's or layer's apply to its members as one piece: one combined shadow; a Pathfinder effect, which combines a group's contents, groups several loose selected objects first, in the same undo step); the art of a graph design in a graph series is left out, and objects that are all such art are an error (docs/mcp.md) → {ids, index, item, grouped?}",
has_doc,
apply
),
@@ -76,7 +76,7 @@ fn effect_specs() -> Vec<CommandSpec> {
"Effect Options",
[],
None,
"{index: int, params?: {…} (merged into the current parameters), warpStyle?: string (an existing Warp style suffix, e.g. arc or flag; changes only an applied Warp in place), threeDType?: plane|extrude|revolve|inflate (the 3D and Materials panel's object type: changes only an applied 3D effect in place into Rotate, Extrude & Bevel, Revolve or Inflate; the settings the new effect also takes keep their values, rotation angles wrapped into -180..180 outside Revolve, and the others start at its defaults; params then merge into the new effect's; the type the effect already has, with nothing else given, changes nothing and records no undo step), visible?: bool, item?: appearance item index|null (as effect.remove), ids?|id?: [..], target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} → {ids}",
"{index: int, params?: {…} (merged into the current parameters), warpStyle?: string (an existing Warp style suffix, e.g. arc or flag; changes only an applied Warp in place; params are checked against the new style), threeDType?: plane|extrude|revolve|inflate (the 3D and Materials panel's object type: changes only an applied 3D effect in place into Rotate, Extrude & Bevel, Revolve or Inflate; the settings the new effect also takes keep their values, rotation angles wrapped into -180..180 outside Revolve, and the others start at its defaults; params then merge into the new effect's; the type the effect already has, with nothing else given, changes nothing and records no undo step), visible?: bool (any other value but null is refused, when a step plays too), item?: appearance item index|null (as effect.remove), ids?|id?: [..], target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} → {ids}",
has_doc,
set_params
),
@@ -298,7 +298,7 @@ fn ids_json(ids: &[NodeId]) -> Value {
/// edits its equal item, or its equal object-level effect, each target matched on its own whatever
/// the other targets have; in a target without them, `item` and `index` stand for themselves.
pub(crate) fn effect_targets(s: &Session, p: &Value, item: ItemTarget, index: usize, cmd: &str) -> Result<Vec<(NodeId, Option<usize>, usize)>> {
let roots = appearance_targets(s, p)?;
let roots = edit_targets(s, p)?;
let d = &s.doc()?.doc;
let per = item.per_target(s, &roots);
let first = roots.first().and_then(|f| d.node(*f));
@@ -453,13 +453,14 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result<Value> {
}
let item = item_target(s, p, C)?;
if effects::is_three_d(id) {
let targets = appearance_targets(s, p)?;
let targets = edit_targets(s, p)?;
for (target, at) in targets.iter().copied().zip(item.per_target(s, &targets)) {
let d = &s.doc()?.doc;
let n = d.node(target).ok_or(EngineError::NoNode(target))?;
// A new effect goes after the item's others.
// A new effect goes after the item's (or the object's) others.
let on = at.and_then(|at| at.effects_item(&n.appearance, C).ok()).flatten();
let on = on.and_then(|i| Some((i, n.appearance.items.get(i)?.effects().len())));
let on = on.and_then(|i| Some((Some(i), n.appearance.items.get(i)?.effects().len())));
let on = on.unwrap_or((None, n.appearance.effects.len()));
effects::validate_three_d_at_in(Some(d), n, id, &effect.params, on).map_err(|e| bad(C, e))?;
if let Some(name) = effects::missing_symbol(d, &effect.params, None) {
return Err(bad(C, format!("no symbol named `{name}`")));
@@ -491,8 +492,9 @@ fn loose_for_pathfinder(s: &Session, p: &Value, id: &str) -> Result<Option<Vec<N
if !effects::is_pathfinder(id) || ["ids", "id", "item", "target"].iter().any(|k| p.get(k).is_some()) {
return Ok(None);
}
let roots = super::appearance::subject_roots(s)?;
let d = &s.doc()?.doc;
// The art of a graph design in a series stays where the graph draws it.
let roots = super::appearance::without_design_art(d, super::appearance::subject_roots(s)?, "appearance")?;
let grouped = roots.iter().any(|r| d.node(*r).is_some_and(|n| matches!(n.kind, NodeKind::Group { clip: false, .. } | NodeKind::Layer { .. })));
Ok((roots.len() >= 2 && !grouped).then_some(roots))
}
@@ -605,7 +607,7 @@ fn move_effect(s: &mut Session, p: &Value) -> Result<Value> {
let src = item_target_at(s, p, "fromItem", C)?;
let dst = if p.get("toItem").is_some() { item_target_at(s, p, "toItem", C)? } else { src };
let copy = switch_or(p, "copy", false, C)?;
let roots = appearance_targets(s, p)?;
let roots = edit_targets(s, p)?;
// Where an aligned effect would go in each of several different stacks isn't one place.
if aligned(p, C)? && super::appearance::appearances_differ(&s.doc()?.doc, &roots) {
return Err(bad(C, "effects of objects whose appearances differ can't be moved together"));
@@ -649,15 +651,28 @@ pub(crate) fn set_params_effects(s: &Session, p: &Value) -> Vec<String> {
return vec![];
};
let Ok(targets) = effect_targets(s, p, item, index, C) else { return vec![] };
// A 3D effect whose type `threeDType` changes takes the new effect's parameters.
// A 3D effect whose type `threeDType` changes, and a Warp whose style `warpStyle` changes, take
// the new effect's parameters.
let kind = three_d_type(p, C).ok().flatten();
let warp = p.get("warpStyle").and_then(Value::as_str).filter(|style| effects::WarpStyle::from_id(style).is_some());
let effect = |&(id, at, index): &(NodeId, Option<usize>, usize)| {
let id = &st.doc.node(id)?.appearance.effects_at(at)?.get(index)?.id;
Some(kind.filter(|_| effects::is_three_d(id)).map_or_else(|| id.clone(), str::to_string))
Some(edited_effect_id(id, kind, warp))
};
targets.iter().filter_map(effect).collect()
}
/// The id effect `id` has once `effect.setParams` sets its 3D type to `kind` or its Warp style to
/// `warp` (each when given and when `id` is an effect of that family).
fn edited_effect_id(id: &str, kind: Option<&str>, warp: Option<&str>) -> String {
let is_warp = id.strip_prefix("warp.").and_then(effects::WarpStyle::from_id).is_some();
match (kind, warp) {
(Some(to), _) if effects::is_three_d(id) => to.to_string(),
(_, Some(style)) if is_warp => format!("warp.{style}"),
_ => id.to_string(),
}
}
/// The effect `threeDType` in `p` turns a 3D effect into ([`effects::THREE_D_TYPES`]), when given.
fn three_d_type(p: &Value, cmd: &str) -> Result<Option<&'static str>> {
let key = "threeDType";
@@ -718,6 +733,7 @@ fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
Ok(format!("warp.{style}"))
})
.transpose()?;
check_switches(p, &["visible"], C)?;
let visible = p.get("visible").and_then(Value::as_bool);
let item = item_target(s, p, C)?;
let edited = set_params_effects(s, p);
@@ -772,7 +788,7 @@ fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(C, format!("no symbol named `{name}`")));
}
if visible != Some(false) {
effects::validate_three_d_at_in(Some(d), n, to, &prospective, target.map(|item| (item, index))).map_err(|e| bad(C, e))?;
effects::validate_three_d_at_in(Some(d), n, to, &prospective, (target, index)).map_err(|e| bad(C, e))?;
} else {
// Hidden, the effect draws nothing, so its object need not fit. The values given are
// checked, and after a change of 3D type so is every value it keeps.
+6 -6
View File
@@ -1,5 +1,5 @@
//! Window › 3D and Materials › Materials › Graphics: art kept as a document symbol (Add as Single
//! Graphic) and mapped onto the planar faces of 3D objects (Extrude & Bevel's caps, a plane). The
//! Graphic) and mapped onto 3D objects (Extrude & Bevel's caps, a plane, Revolve's side). The
//! graphics an object shows are the `graphics` parameter of its 3D effect, which `effect.setParams`
//! also edits.
@@ -7,7 +7,7 @@ use serde_json::{Map, Value, json};
use vectorcraft_doc::{Effect, Node};
use vectorcraft_render::effects;
use super::super::appearance::{appearance_targets, index_param, item_target};
use super::super::appearance::{edit_targets, index_param, item_target};
use super::super::brushsym::{normalize, selection_art, store_symbol};
use super::super::{CommandSpec, EngineError, NodeId, Result, Session, bad, cmd, has_doc, has_selection, str_param};
use super::{effect_targets, ids_json};
@@ -28,7 +28,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
"Map Graphic",
[],
None,
"{symbol: name of a document symbol, face?: front|back (front; Plane has only a front; the back reads left to right as seen from behind), x?: pt, y?: pt (0, 0: the offset of the graphic's center from the center of the object's bounds, in the face's own plane), scale?: % (1..10000; default 100, or less so the graphic fits inside the object), rotation?: degrees (-360..360, 0; counterclockwise), index?: int (the 3D effect's position; default: each object's first 3D effect, its own before its fills' and strokes'), item?: appearance item index|null (refused without index; as effect.setParams), ids?|id?} add a graphic to the 3D effect of each selected object, drawn on that face turned, foreshortened and shaded with it and clipped to it; every object's 3D effect must be Extrude & Bevel (on a solid cap) or Rotate (the Plane type); one undo step → {ids, graphic}",
"{symbol: name of a document symbol, face?: front|back (front; Plane has only a front; the back reads left to right as seen from behind; on Revolve the front is its swept side, which is the only face), x?: pt, y?: pt (0, 0: the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on Revolve from the middle of the side unrolled flat, x around the axis and y along the profile), scale?: % (1..10000; default 100, or less so the graphic fits inside the object, on Revolve inside the half of the side seen from the front), rotation?: degrees (-360..360, 0; counterclockwise), index?: int (the 3D effect's position; default: each object's first 3D effect, its own before its fills' and strokes'), item?: appearance item index|null (refused without index; as effect.setParams), ids?|id?} add a graphic to the 3D effect of each selected object, drawn on that face turned, foreshortened and shaded with it and clipped to it (on Revolve wrapped around the side, and drawn only where its outside faces the viewer); every object's 3D effect must be Extrude & Bevel (on a solid cap), Rotate (the Plane type) or Revolve; one undo step → {ids, graphic}",
has_doc,
map_graphic
),
@@ -95,7 +95,7 @@ fn map_graphic(s: &mut Session, p: &Value) -> Result<Value> {
effect_targets(s, p, item, index, C)?
} else {
let mut out = vec![];
for id in appearance_targets(s, p)? {
for id in edit_targets(s, p)? {
let (item, index) = d.node(id).and_then(first_three_d).ok_or_else(|| bad(C, format!("object {} needs a 3D effect", id.0)))?;
out.push((id, item, index));
}
@@ -111,7 +111,7 @@ fn map_graphic(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(C, format!("object {} needs a 3D effect at index {index}", id.0)));
};
if !effects::takes_graphics(&effect.id) {
return Err(bad(C, format!("object {}: Graphics map onto planar faces: use the Extrude or Plane object type", id.0)));
return Err(bad(C, format!("object {}: {}", id.0, effects::GRAPHICS_NOT_TAKEN)));
}
// A hollow Extrude & Bevel keeps the graphics it has, to show when Cap is turned on again,
// but has no cap to show a new one on.
@@ -131,7 +131,7 @@ fn map_graphic(s: &mut Session, p: &Value) -> Result<Value> {
graphic.scale = frame.fitting_scale(art);
}
let params = effects::with_graphic(&effects::merged_params(&effect.id, &effect.params), &graphic);
effects::validate_three_d_at_in(Some(d), n, &effect.id, &params, item.map(|i| (i, index))).map_err(|e| bad(C, e))?;
effects::validate_three_d_at_in(Some(d), n, &effect.id, &params, (item, index)).map_err(|e| bad(C, e))?;
edits.push((id, item, index, graphic));
}
let first = edits.first().map(|(.., g)| g.to_value());
@@ -68,12 +68,37 @@ fn a_large_graphic_starts_inside_its_object() {
assert!((scale - 100.0 * 100.0 / 401.0).abs() < 1e-9, "{scale}");
}
#[test]
fn map_graphic_puts_a_graphic_on_the_side_of_a_revolve() {
let (mut s, id) = setup("threeD.revolve");
let plain = vectorcraft_render::effects::revolve_art_in(Some(&s.doc().unwrap().doc), s.doc().unwrap().doc.node(id).unwrap());
let history = undo_len(&s);
s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "ids": [id.0]})).unwrap();
assert_eq!(graphics(&s, id), json!([{"symbol": "Mark", "face": "front", "x": 0.0, "y": 0.0, "scale": 100.0, "rotation": 0.0}]));
assert_eq!(undo_len(&s), history + 1);
let d = &s.doc().unwrap().doc;
assert_ne!(vectorcraft_render::effects::revolve_art_in(Some(d), d.node(id).unwrap()), plain, "the graphic is drawn");
// A large graphic starts inside the half of the side seen from the front: 100π around the
// axis (the square's far edge is 100 from it) and 300 along the profile (its edge on the axis
// sweeps nothing).
let big = s.execute("path.create", &json!({"d":"M0 0L400 0L400 200L0 200Z"})).unwrap()["id"].clone();
s.execute("threeD.addGraphic", &json!({"name": "Big", "ids": [big]})).unwrap();
s.execute("threeD.mapGraphic", &json!({"symbol": "Big", "ids": [id.0]})).unwrap();
let scale = graphics(&s, id)[1]["scale"].as_f64().unwrap();
assert!((scale - 100.0 * 100.0 * std::f64::consts::PI / 401.0).abs() < 1e-6, "{scale}");
// The side is its only face.
let history = undo_len(&s);
let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "back", "ids": [id.0]})).unwrap_err().to_string();
assert!(e.contains("side"), "{e}");
assert_eq!(undo_len(&s), history);
}
#[test]
fn map_graphic_refuses_what_cannot_take_it_and_changes_nothing() {
let (mut s, id) = setup("threeD.inflate");
let history = undo_len(&s);
let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "ids": [id.0]})).unwrap_err().to_string();
assert!(e.contains("Extrude or Plane"), "{e}");
assert!(e.contains("Plane, Extrude and Revolve"), "{e}");
let (mut s, id) = setup("threeD.rotate");
for (p, says) in [
(json!({"symbol": "Gone"}), "no symbol named"),
+82
View File
@@ -169,6 +169,44 @@ fn solid_effects_apply_to_a_group_and_its_members_stay_editable() {
assert_eq!(s.doc().unwrap().doc, before, "nothing changed");
}
/// Extrude & Bevel is refused, and nothing changes, on a path whose fill's and strokes' solids each
/// fit but together pass the limit of their faces; with one stroke the effect applies.
#[test]
fn extrude_is_refused_when_its_solids_together_are_too_complex() {
use vectorcraft_doc::color::{Color, Paint};
use vectorcraft_doc::{Appearance, AppearanceItem};
let (mut s, id) = session_with_rect();
let points: Vec<vectorcraft_geom::Point> = (0..16_384)
.map(|k| {
let (sin, cos) = (k as f64 * std::f64::consts::TAU / 16_384.0).sin_cos();
vectorcraft_geom::Point::new(20_000.0 + 10_000.0 * cos, 20_000.0 + 10_000.0 * sin)
})
.collect();
let polygon = vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&points, true));
let painted = |strokes: usize| {
let mut items = Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0).items;
let stroke = AppearanceItem::Stroke(vectorcraft_doc::StrokeLayer::new(Paint::solid(Color::WHITE), 20.0));
items.extend(std::iter::repeat_n(stroke, strokes));
items
};
let set = |s: &mut Session, strokes: usize| {
let n = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap();
let NodeKind::Path { path, live, .. } = &mut n.kind else { panic!("a path") };
*path = polygon.clone();
*live = None;
n.appearance.items = painted(strokes);
};
// The fill's solid and each stroke's fit on their own; sixty strokes' together do not.
set(&mut s, 60);
let before = s.doc().unwrap().doc.clone();
let err = s.execute("effect.apply", &json!({"effect": "threeD.extrude", "ids": [id.0], "item": null})).unwrap_err().to_string();
assert!(err.contains("The 3D surface is too complex; simplify the shape"), "{err}");
assert_eq!(s.doc().unwrap().doc, before, "nothing changed");
set(&mut s, 1);
s.execute("effect.apply", &json!({"effect": "threeD.extrude", "ids": [id.0], "item": null})).unwrap();
assert!(effects::solid_art(&node(&s, id)).is_some());
}
/// A group of a clipping group (a rectangle clipped by an ellipse) and a rectangle: the session,
/// the clipping group and the group.
fn group_with_a_clipping_group() -> (Session, NodeId, NodeId) {
@@ -626,6 +664,50 @@ fn warp_options_non_warp_target_rejection_is_atomic() {
assert!(!state.is_dirty());
}
/// `effect.setParams` refuses a `visible` that is not true or false, when called and when a step
/// plays, and the effect, the document and the undo history stay as they were. `null` leaves the
/// visibility as it is.
#[test]
fn set_params_refuses_a_visible_that_is_not_true_or_false() {
let (mut s, id) = session_with_rect();
s.execute("effect.apply", &json!({"effect": "distort.roughen", "item": null})).unwrap();
s.doc_mut().unwrap().mark_saved();
let before = s.doc().unwrap().doc.clone();
let undo = s.doc().unwrap().history.undo.len();
for visible in [json!(1), json!(0), json!("false"), json!([])] {
let p = json!({"index": 0, "item": null, "visible": visible, "params": {"size": 9}});
for replay in [false, true] {
let r = if replay { s.replay("effect.setParams", &p) } else { s.execute("effect.setParams", &p) };
let err = r.err().map(|e| e.to_string()).unwrap_or_default();
assert!(err.contains("`visible` must be true or false"), "{visible} (replay {replay}): {err}");
let state = s.doc().unwrap();
assert_eq!(state.doc, before, "{visible} (replay {replay})");
assert_eq!(state.history.undo.len(), undo, "{visible} (replay {replay})");
assert!(!state.is_dirty());
}
}
s.execute("effect.setParams", &json!({"index": 0, "item": null, "visible": null, "params": {"size": 9}})).unwrap();
let n = node(&s, id);
assert!(n.appearance.effects[0].visible);
assert_eq!(n.appearance.effects[0].params["size"], 9);
}
/// The effect `effect.setParams` checks the parameters against is the one it leaves: a Warp's new
/// style and a 3D effect's new type, and the effect as it is otherwise.
#[test]
fn set_params_checks_the_effect_it_leaves() {
use super::edited_effect_id;
assert_eq!(edited_effect_id("warp.arc", None, Some("flag")), "warp.flag");
assert_eq!(edited_effect_id("warp.arc", None, None), "warp.arc");
assert_eq!(edited_effect_id("distort.roughen", None, Some("flag")), "distort.roughen");
assert_eq!(edited_effect_id("threeD.extrude", Some("threeD.revolve"), None), "threeD.revolve");
assert_eq!(edited_effect_id("warp.arc", Some("threeD.revolve"), None), "warp.arc");
let (mut s, _) = session_with_rect();
s.execute("effect.apply", &json!({"effect": "warp.arc", "item": null})).unwrap();
let p = json!({"index": 0, "item": null, "warpStyle": "flag", "params": {"bend": 25}});
assert_eq!(super::set_params_effects(&s, &p), ["warp.flag"]);
}
#[test]
fn list_remove_and_set_params() {
let (mut s, id) = session_with_rect();
+95 -18
View File
@@ -18,14 +18,14 @@ use vectorcraft_color::{BlendMode, Color, Gradient, GradientKind, GradientPaint,
use vectorcraft_doc::appearance::{AppearanceItem, FillLayer};
use vectorcraft_doc::live::GradientMesh;
use vectorcraft_doc::pattern::{PatternDef, place_art};
use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, Scaling};
use vectorcraft_geom::{Affine, PathData, Point, Rect, SubPath, Vec2, shapes};
use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, Scaling, TextObject};
use vectorcraft_geom::{Affine, BezPath, PathData, Point, Rect, SubPath, Vec2, shapes};
use super::dimension::EndedLink;
use super::edit::selected_roots;
use super::menucmds::{run_raw, squash};
use super::object::as_clipping_path;
use super::pathops::{assemble, node_path, outline_strokes, replace_leaves, styled_copy, with_transparency};
use super::pathops::{assemble, node_path, outlinable, outline_strokes, replace_leaves, styled_copy, with_transparency};
use super::{CommandSpec, EngineError, Result, Session, bad, cmd, has_selection, number_or, switch_or, text_param};
const C: &str = "object.expand";
@@ -47,7 +47,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Expand…",
["Object"],
None,
"{object?: true (symbol instances without effects (their fills' and strokes' included) and not in perspective → their art, as Break Link to Symbol places it (the instances that art holds stay instances), type → outlines, live shapes → paths, effects baked, blends → groups of their steps, repeats → groups of their instances, Intertwine groups → groups of their objects and of the parts drawn over the others (clip groups), envelopes → their distorted content, placed documents → editable copies of their art, as placing the file without link gives, its symbols, patterns, swatches and images joining the document), fill?: true (gradient fills → `gradient` art, pattern fills → their tiles in a clip group shaped like the object), stroke?: true (strokes → filled outlines, the stroked paths that baking effects leaves included), gradient?: \"objects\" (default: `steps` solid strips, concentric ellipses for radial gradients, wedges around the center for conic ones, nested squares for diamond ones) | \"mesh\" (a gradient mesh); both in a clip group shaped like the object (freeform gradients always become a mesh shaped like it), steps?: 1..1000 (255; a gradient that repeats or reflects gets the same whole number of them in each run, at least one, so a run starts on an object's edge; one that needs more than 256 runs across the box stays a gradient)} one undo step; a dimension whose art an option changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked → {ids}",
"{object?: true (symbol instances without effects (their fills' and strokes' included) and not in perspective → their art, as Break Link to Symbol places it (the instances that art holds stay instances), type → outlines (its own fills and strokes on paths of its whole outline, which Fill and Stroke expand), live shapes → paths, effects baked, blends → groups of their steps, repeats → groups of their instances, Intertwine groups → groups of their objects and of the parts drawn over the others (clip groups), envelopes → their distorted content, placed documents → editable copies of their art, as placing the file without link gives, its symbols, patterns, swatches and images joining the document), fill?: true (gradient fills → `gradient` art, pattern fills → their tiles in a clip group shaped like the object), stroke?: true (strokes → filled outlines, the stroked paths that baking effects leaves included), gradient?: \"objects\" (default: `steps` solid strips, concentric ellipses for radial gradients, wedges around the center for conic ones, nested squares for diamond ones) | \"mesh\" (a gradient mesh); both in a clip group shaped like the object (freeform gradients always become a mesh shaped like it), steps?: 1..1000 (255; a gradient that repeats or reflects gets the same whole number of them in each run, at least one, so a run starts on an object's edge; one that needs more than 256 runs across the box stays a gradient)} one undo step; a dimension whose art an option changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked → {ids}",
has_selection,
expand
),
@@ -56,7 +56,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Expand Options",
[],
None,
"{} what each Expand option would change in the selection → {object, fill, stroke, gradient, appearance, symbolArt?: {fill, stroke, gradient}} (true: something to expand; gradient: a gradient fill that Fill expands, which Expand Gradient To applies to; appearance: appearance attributes Expand Appearance expands first, for which Object › Expand… is dimmed in the menus; symbolArt, when the selection holds symbol instances that Object expands: true when only their art holds it, which Fill and Stroke reach only with Object on)",
"{} what each Expand option would change in the selection → {object, fill, stroke, gradient, appearance, symbolArt?: {fill, stroke, gradient}} (true: something to expand; gradient: a gradient fill that Fill expands (in type, on the outline Object makes of a character, or of the whole type for the type object's own fills), which Expand Gradient To applies to; appearance: appearance attributes Expand Appearance expands first, for which Object › Expand… is dimmed in the menus; symbolArt, when the selection holds symbol instances that Object expands: true when only their art holds it, which Fill and Stroke reach only with Object on)",
has_selection,
|s, _| {
let roots = selected_roots(s)?;
@@ -189,21 +189,37 @@ impl Expandable {
e.placed |= matches!(c.kind, NodeKind::PlacedDocument(_));
e.repeats |= matches!(c.kind, NodeKind::Repeat(_));
e.intertwines |= matches!(c.kind, NodeKind::Intertwine { .. });
// Type's outlines take its characters' stroke and fill, and a path of its whole outline
// takes the type object's own fills and strokes (see `type.createOutlines`).
// Any stroke Outline Stroke outlines, not only the topmost one.
let own_stroke = c.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(st) if outlinable(st)));
let own_pattern = c.appearance.items.iter().any(|i| pattern_fill(d, i).is_some());
let own_gradient = c.appearance.items.iter().any(|i| gradient_fill(i).is_some());
// Type without an outline (empty, or only spaces) gets no path for its own fills and strokes.
let whole = match &c.kind {
NodeKind::Text(t) if own_stroke || own_pattern || own_gradient => text_whole_outline(t),
_ => None,
};
e.stroke |= match &c.kind {
// Type's outlines take its characters' stroke (see `type.createOutlines`).
NodeKind::Text(t) => t.runs.iter().any(|r| r.style.has_stroke()),
_ => shape && !c.appearance.stroke_paint().is_none(),
NodeKind::Text(t) => (own_stroke && whole.is_some()) || t.runs.iter().any(|r| r.style.has_stroke()),
_ => shape && own_stroke,
};
// Once one is found, the next path is not measured.
e.gradient = e.gradient
|| match &c.kind {
NodeKind::Text(t) => t.runs.iter().any(|r| matches!(r.style.fill, Paint::Gradient(_))),
NodeKind::Text(t) => {
text_gradient_expands(d, t)
|| (own_gradient && whole.as_ref().is_some_and(|(path, tb)| text_object_gradient_expands(d, c, path, *tb)))
}
_ => shape && gradient_expands(d, c),
};
e.fill |= e.gradient;
e.fill |= match &c.kind {
NodeKind::Text(t) => t.runs.iter().any(|r| matches!(&r.style.fill, Paint::Pattern { pattern, .. } if d.pattern(pattern).is_some())),
_ => shape && c.appearance.items.iter().any(|i| pattern_fill(d, i).is_some()),
NodeKind::Text(t) => {
(own_pattern && whole.is_some())
|| t.runs.iter().any(|r| matches!(&r.style.fill, Paint::Pattern { pattern, .. } if d.pattern(pattern).is_some()))
}
_ => shape && own_pattern,
};
});
}
@@ -247,6 +263,61 @@ fn gradient_expands(d: &Document, l: &Node) -> bool {
any
}
/// Whether type `t` has a gradient fill that Fill expands once Object has outlined it: one of the
/// paths `type.createOutlines` makes of its glyphs, ruby glyphs and underline and strikethrough
/// bars, each painted as its run, has one ([`gradient_expands`] on that path's own box). Inline
/// graphics and color glyphs become other art. Leaves the document as it is and stops at the
/// first such path.
fn text_gradient_expands(d: &Document, t: &TextObject) -> bool {
if !t.runs.iter().any(|r| matches!(r.style.fill, Paint::Gradient(_))) {
return false;
}
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
let expands = |run: usize, outline: &BezPath| {
let style = t.runs.get(run).map(|r| &r.style);
if !matches!(style.map_or_else(|| t.first_style().fill, |s| s.fill.clone()), Paint::Gradient(_)) {
return false;
}
let path = PathData::from_bezpath(outline).transformed(t.xf);
if path.is_empty() {
return false;
}
let appearance = style.map_or_else(|| t.first_style().appearance(), |s| s.appearance());
gradient_expands(d, &Node::path(NodeId(u64::MAX), path, appearance))
};
let inline = |gi: usize| lay.inlines.iter().find(|i| i.glyph == gi).is_some_and(|i| t.runs.get(i.run).is_some_and(|r| r.inline.is_some()));
lay.glyphs.iter().enumerate().any(|(gi, g)| !inline(gi) && g.image.is_none() && g.colour.is_none() && expands(g.run, &g.outline))
|| lay.ruby.iter().any(|g| expands(g.run, &g.outline))
|| vectorcraft_text::decorations(&lay, vectorcraft_text::FontDb::global(), t).iter().any(|(run, bar)| expands(*run, bar))
}
/// The path of type `t`'s whole outline in the document (glyphs, ruby glyphs and underline and
/// strikethrough bars), which `type.createOutlines` paints with the type object's own fills and
/// strokes, and the layout's bounds there; `None` when the type has no outline.
fn text_whole_outline(t: &TextObject) -> Option<(PathData, Rect)> {
let db = vectorcraft_text::FontDb::global();
let lay = vectorcraft_text::layout(db, t);
let mut all = BezPath::new();
for g in lay.glyphs.iter().chain(&lay.ruby) {
all.extend(g.outline.iter());
}
for (_, bar) in vectorcraft_text::decorations(&lay, db, t) {
all.extend(bar.iter());
}
let path = PathData::from_bezpath(&all).transformed(t.xf);
(!path.is_empty()).then(|| (path, t.xf.transform_rect_bbox(lay.bounds)))
}
/// Whether type node `n` has a gradient fill of its own (not its characters') that Fill expands
/// once Object has outlined it: [`gradient_expands`] on `path`, the type's whole outline
/// ([`text_whole_outline`]), with its unplaced gradients fixed to `tb`, the layout's bounds in the
/// document. Leaves the document as it is.
fn text_object_gradient_expands(d: &Document, n: &Node, path: &PathData, tb: Rect) -> bool {
let mut appearance = Appearance { items: n.appearance.items.clone(), ..Default::default() };
appearance.pin_gradients(tb);
gradient_expands(d, &Node::path(NodeId(u64::MAX), path.clone(), appearance))
}
/// [`gradient_expands`] for a path that no live-effect plug-in paints ([`expand_piece_fills`]).
fn piece_gradient_expands(d: &Document, l: &Node) -> bool {
if !l.appearance.items.iter().filter_map(gradient_fill).any(|(_, g)| g.gradient.is_spread()) {
@@ -606,7 +677,9 @@ pub(crate) fn reshaped(doc: &Document, l: &Node) -> Option<Node> {
if carry.moves(&m.appearance) {
carry.apply(&mut m.appearance);
}
// So do the raster effects of its fills and strokes.
// So do the raster effects of it and of its fills and strokes, by the Transform effects that
// moved it.
carry.hide_skipped(&mut m.appearance.effects);
vectorcraft_render::effects::follow_items(&mut m);
m.appearance.effects = without_geometry(&m.appearance.effects);
Some(m)
@@ -634,7 +707,8 @@ pub(crate) fn fill_shape(
if carry.moves(&one) {
carry.apply(&mut one);
}
let moved = one.items.pop().unwrap_or_else(|| item.clone());
let mut moved = one.items.pop().unwrap_or_else(|| item.clone());
carry.hide_skipped(moved.effects_mut());
Some((with_path(l, outline.clone()), outline, b, moved))
}
@@ -884,8 +958,8 @@ fn blended(n: &Node) -> bool {
n.opacity < 1.0 || n.blend != BlendMode::Normal
}
/// Whether `n` (art of `d`) is or holds an image with see-through pixels (key in `keys`), a
/// colorize paint that `colorize` counts, opacity or a blending mode of its own or of a group in
/// Whether `n` (art of `d`) is or holds an image with see-through pixels (key in `keys`, a
/// color-masked image's masked pixels counted as its own), a colorize paint that `colorize` counts, opacity or a blending mode of its own or of a group in
/// `n`, or anywhere when `on`, also in the tile art of the pattern fills of the paths in `n`, down
/// to `levels` patterns. Hidden art doesn't count.
fn transparent_image(d: &Document, n: &Node, keys: &BTreeSet<String>, colorize: &dyn Fn(&Document, &Node) -> bool, on: bool, levels: u32) -> bool {
@@ -894,7 +968,9 @@ fn transparent_image(d: &Document, n: &Node, keys: &BTreeSet<String>, colorize:
}
let on = on || blended(n);
match &n.kind {
NodeKind::Image(im) => on || keys.contains(&im.key) || (n.extras().colorize.is_some() && colorize(d, n)),
NodeKind::Image(im) => {
on || keys.contains(&im.key) || keys.contains(&d.shown_image(n, im).key) || (n.extras().colorize.is_some() && colorize(d, n))
}
NodeKind::Path { .. } | NodeKind::Compound { .. } => {
n.appearance.items.iter().any(|i| pattern_fill_holds_transparent_image(d, i, keys, colorize, on, levels))
}
@@ -1358,8 +1434,9 @@ fn band_edges(lo: f64, hi: f64, n: usize, runs: Option<(f64, usize)>) -> Vec<f64
fn breaks(g: &Gradient, t0: f64, t1: f64, max_gap: f64) -> Vec<(f64, (Color, f32))> {
let at = |t: f64| (t, g.sample_keep_model(t as f32));
let mut v = vec![at(t0)];
// A Perceptual gradient curves between its stops: the mesh takes a column at each of the stops
// its expansion adds, so the linear mix between columns follows that curve.
// A Perceptual gradient, or one mixed around the hue wheel, curves between its stops: the mesh
// takes a column at each of the stops its expansion adds, so the linear mix between columns
// follows that curve.
if !g.method.is_classic() {
v.extend(g.expanded().map(|(o, ..)| f64::from(o)).filter(|o| *o > t0 && *o < t1).map(at));
}
+7 -5
View File
@@ -13,10 +13,10 @@
//! per-format options (`file.formatOptions`); [`save_with`] is the one save path of every frontend.
//! - `pdf`: PDF settings and presets for every PDF export, `document.exportPdf`.
//! - `pdfimport`: the PDF pages, box and password `document.open` and Place read, `document.pdfInfo`.
//! - `dxf`: DXF export options, `document.exportDxf`, and the formats that can't be written (DWG, PICT).
//! - `dxf`: DXF export options, `document.exportDxf`, and the formats that can't be written (DWG, PageMaker).
//! - `eps`: EPS export options (flattened transparency, previews, the embedded document), `document.exportEps`.
//! - `dxfimport`: the DXF options `document.open` and Place read, `document.dxfInfo`.
//! - `metafile`: EMF and WMF export, open and place.
//! - `metafile`: EMF and WMF export, open and place; PICT open and place.
//! - `hpgl`: HP-GL export options and plots.
//! - `importer`: files that importer plug-ins open (`document.open {importer}`, and extensions no
//! built-in format reads).
@@ -69,8 +69,8 @@ pub use dxf::{UNSUPPORTED, Unsupported, unsupported};
pub use encode::{ARTBOARD_PARAMS, ArtboardPick, Encoded, Note, NoteKind, encode, encode_all, encode_with_notes, encode_with_warnings, note_texts};
pub(crate) use encode::{anti_alias, background, with_single_artboard};
pub(crate) use export::with_artboard_fills;
pub(crate) use export::{export_crop, isolated};
pub use export::{export_doc, export_source};
pub(crate) use export::{EXPORT_PARAMS, export_crop, isolated};
pub use export::{export_doc, export_source, unused_option_notes};
use load::err;
pub(crate) use load::import_svg;
pub(crate) use load::is_placeholder;
@@ -123,7 +123,7 @@ mod formats;
#[cfg(not(target_arch = "wasm32"))]
pub(crate) use access::list_dir;
pub use access::{write_file_with, write_save_file, write_save_file_with};
pub use access::{check_linked_scripts, write_file_with, write_save_file, write_save_file_with};
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests_readonly;
@@ -217,6 +217,8 @@ mod tests_dxfimport;
mod tests_hpgl;
#[cfg(test)]
mod tests_metafile;
#[cfg(test)]
mod tests_pict;
#[cfg(test)]
mod tests_pdfoutput;
+18
View File
@@ -121,6 +121,24 @@ pub(crate) fn naming_in_message(msg: &str, path: &str, name: &str) -> String {
out
}
/// The error for an SVG of a document that links a JavaScript file outside the read roots.
pub(crate) const SCRIPT_OUTSIDE: &str = "a linked JavaScript file is outside the read roots";
/// `cmd` may write `st`'s document in format `format` (a format id): any format but SVG and SVGZ,
/// and those too unless read roots are in force and the document links a JavaScript file outside
/// them (`svg_scripts`, a relative path taken from the document's folder; a URL is not checked),
/// which the file's `<script>` element would name. The error names no file or folder.
pub fn check_linked_scripts(cmd: &str, format: &str, st: &crate::DocState) -> Result<()> {
if !matches!(format, "svg" | "svgz") || crate::file_access::current().is_none() {
return Ok(());
}
let doc_path = st.path.as_deref();
if st.doc.svg_scripts.iter().any(|f| crate::cmd::links::script_hidden(f, doc_path)) {
return Err(bad(cmd, SCRIPT_OUTSIDE));
}
Ok(())
}
/// `path` checked for writing against the automation roots in force.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn may_write(path: &str) -> Result<()> {
+33 -5
View File
@@ -41,6 +41,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
roll_back(s, start, &stash);
s.notify_text_tool("batch.rollBack");
s.active = active;
s.sync_front_profiles();
(s.paint, s.fill_active, s.draw_mode, s.draw_inside, s.clipboard, s.untitled_counter, s.explicit_undo_group) = saved;
s.pending_paint = None;
return Err(e);
@@ -78,8 +79,13 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
/// `artboard`, as the Artboards panel shows it in the document the step runs in: past that
/// document's last artboard, the last one; a Paste in Place, in Front or in Back step that names
/// `artboards` keeps them, and one that names neither, while the Artboard tool is chosen with
/// several artboards selected, pastes on those. A step that resizes the active artboard
/// ([`crate::FIT_ACTIVE_ARTBOARD`]) and names no `index` gets that artboard as its `index`.
/// several artboards selected, pastes on those. A Fit to Artwork Bounds step that names neither
/// `index` nor `indices`, while the Artboard tool is chosen with two or more artboards selected when
/// the step runs, gets those as its `indices`. Otherwise a step that resizes the active artboard
/// ([`crate::FIT_ACTIVE_ARTBOARD`]) and names no `index` (nor `indices`, for Fit to Artwork Bounds)
/// gets that artboard as its `index`. A Fit to Artwork Bounds step that still names neither gets
/// `index` 0, the command's default. A Fit to Artwork Bounds step's journal entry records the
/// `indices` or `index` it got.
/// `grouped` gets each step's undo groups, as [`Session::batch_steps`] keeps them.
fn run_steps(
s: &mut Session,
@@ -100,7 +106,8 @@ fn run_steps(
if s.active().is_some() {
s.begin_interaction(label)?;
}
let mut params = c.get("params").cloned().unwrap_or(json!({}));
// `"params": null` reads as no params, so the artboards below can still be added.
let mut params = c.get("params").filter(|v| !v.is_null()).cloned().unwrap_or(json!({}));
let key = if crate::ON_ACTIVE_ARTBOARD.contains(&id.as_str()) {
Some("artboard")
} else {
@@ -110,15 +117,34 @@ fn run_steps(
// Artboard tool is chosen with several artboards selected, pastes on those.
let names_artboards = id.starts_with("edit.pasteIn")
&& (params.get("artboards").is_some() || (params.get("artboard").is_none() && !crate::cmd::edit::artboard_tool_picks(s).is_empty()));
// A Fit to Artwork Bounds step that names neither `index` nor `indices`, while the Artboard
// tool is chosen with two or more artboards selected, fits those.
let fit_unnamed = id == "artboard.fitToArt" && params.get("index").is_none() && params.get("indices").is_none();
let fit_picks = if fit_unnamed { crate::cmd::edit::artboard_tool_picks(s) } else { Vec::new() };
if !fit_picks.is_empty()
&& let Some(o) = params.as_object_mut()
{
o.insert("indices".into(), json!(fit_picks));
}
if let Some(a) = artboard
&& let Some(key) = key
&& params.get(key).is_none()
&& !(id == "artboard.fitToArt" && params.get("indices").is_some())
&& !names_artboards
&& let Some(last) = s.active().and_then(|d| d.doc.artboards.len().checked_sub(1))
&& let Some(o) = params.as_object_mut()
{
o.insert(key.into(), json!(usize::try_from(a).map_or(last, |a| a.min(last))));
}
// With neither, the step fits the command's default, the first artboard, named here so the
// journal records it.
if fit_unnamed
&& params.get("index").is_none()
&& params.get("indices").is_none()
&& let Some(o) = params.as_object_mut()
{
o.insert("index".into(), json!(0));
}
// The documents with an undo group open, held so that the step's first edit in one copies it.
let start = s.active().map(|d| d.uid);
let held: Vec<(u64, Arc<Document>)> = s.docs.iter().filter(|st| st.undo_group.is_some()).map(|st| (st.uid, st.doc.clone())).collect();
@@ -129,8 +155,10 @@ fn run_steps(
}
grouped.push(step_groups(s, start, &held));
// The step's journal entry records what it took from the preferences or the clock (a
// save's date, a new document's), as a command of its own would.
if noted != params
// save's date, a new document's), as a command of its own would, and the artboards a Fit to
// Artwork Bounds step took from the Artboard tool, the batch or the command's default, so a
// replay does not fit the artboards the Artboard tool has selected then.
if (noted != params || fit_unnamed)
&& let Some(c) = c.as_object_mut()
{
c.insert("params".into(), noted);
File diff suppressed because one or more lines are too long
+1 -7
View File
@@ -1,6 +1,6 @@
//! DXF export for every DXF path (`document.export {format: dxf}`, `document.exportDxf`, Export As
//! → DXF Options): the options parsed from the params, one drawing per artboard with Use
//! Artboards, and the formats that can't be written (DWG, PICT) with what to use instead.
//! Artboards, and the formats that can't be written (DWG, PageMaker) with what to use instead.
use std::sync::Arc;
@@ -106,12 +106,6 @@ pub const UNSUPPORTED: &[Unsupported] = &[
extensions: &["dwg"],
hint: "DWG is not available (no openly licensed writer exists): export DXF instead, which CAD apps open",
},
Unsupported {
id: "pict",
label: "PICT",
extensions: &["pict", "pct", "pic"],
hint: "PICT is a retired format and is not supported: convert the file to PDF or PNG first",
},
Unsupported {
id: "pmd",
label: "PageMaker",
+7
View File
@@ -629,6 +629,13 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
{
return Ok(Encoded::one_with_notes(bytes, notes));
}
// So does a `.ai` file of the art's bounds (a legacy version 7 `.ai` file has none to leave out).
if use_artboards == Some(false)
&& f.id == "ai"
&& let Some(enc) = super::save::encode_ai_art_page(C, f, doc, p)?
{
return Ok(enc);
}
if use_artboards == Some(false)
&& let Some((art, q)) = art_page(C, doc, p)?
{
+54 -4
View File
@@ -12,11 +12,50 @@ use crate::DocState;
use super::super::{Result, Session, bad, check_switches, edit, number_or, switch_or, text_param};
use super::encode::single_artboard;
use super::{
ARTBOARD_PARAMS, Format, default_name, encode_all, encode_with_warnings, merge, with_black_output, writable, write_encoded, write_or_return,
ARTBOARD_PARAMS, Format, check_linked_scripts, default_name, encode_all, encode_with_warnings, merge, with_black_output, writable, write_encoded,
write_or_return,
};
/// The keys the export commands take for every format, beside the path, the format and the
/// options `document.formats` lists for each: `richBlack` is Appearance of Black's setting for a
/// raster export, and `params` an exporter plug-in's own.
pub(crate) const EXPORT_PARAMS: [&str; 4] = ["includeArtboardFill", "selectedOnly", "richBlack", "params"];
/// A note for each option in `p` that some format takes but the file an export of `cmd` writes in
/// `f` doesn't read (`{format: pdf, quality: 80}`), in the wording of a save's note. An exporter
/// plug-in's format gets none. The notes cover the formats' options only: a key of the command's
/// own ([`EXPORT_PARAMS`]) and an artboard choice that a selection export leaves out get none.
pub fn unused_option_notes(cmd: &str, f: &Format, p: &Value) -> Vec<String> {
let Some(given) = p.as_object() else { return Vec::new() };
if vectorcraft_plugins::export::by_format(f.id).is_some() {
return Vec::new();
}
let listed = |k: &str| super::FORMATS.iter().filter(|f| f.write).flat_map(|f| f.options).any(|o| o.name == k);
let written = super::save::written_as(cmd, f, p);
let legacy = f.id == "ai" && super::legacy_ai::wanted(cmd, f, p).unwrap_or(false);
let reads = |k: &str| match (f.id, k) {
// A legacy `.ai` file is not a PDF: it reads its own options only.
("ai", _) if legacy => super::legacy_ai::reads(k),
// The other `.ai` files don't read the legacy file's options, and `preserveEditing` is
// on for them whatever is given.
("ai", "preserveEditing") => false,
("ai", _) if super::legacy_ai::LEGACY_ONLY.contains(&k) => false,
// An export writes one file: only a save writes each artboard to a file of its own, and
// a native file's `range` names those files.
("vectorcraft" | "template" | "ai", "separateArtboards") | ("vectorcraft" | "template", "range") => false,
_ => super::save::reads_option(f, k),
};
given
.iter()
.filter(|(k, v)| !v.is_null() && !EXPORT_PARAMS.contains(&k.as_str()) && listed(k) && !reads(k))
.map(|(k, _)| super::save::unused_option_note(k, &written))
.collect()
}
pub(super) fn serialize(s: &mut Session, p: &Value) -> Result<Value> {
let f = writable("document.serialize", Some(text_param(p, "format", "document.serialize")?.unwrap_or("vectorcraft")), None)?;
check_linked_scripts("document.serialize", f.id, s.doc()?)?;
let unused = unused_option_notes("document.serialize", f, p);
let expanded = expand_presets(s, "document.serialize", p)?;
let p = with_black_output(s, &expanded);
let (doc, display_doc_title) = source(s, f, &p, "document.serialize")?;
@@ -27,7 +66,8 @@ pub(super) fn serialize(s: &mut Session, p: &Value) -> Result<Value> {
{
o.insert("_displayDocTitle".into(), json!(display_doc_title));
}
let enc = encode_all(doc, f.id, &q)?;
let mut enc = encode_all(doc, f.id, &q)?;
enc.add_setting_notes(unused);
let files = enc.named(doc, &default_name(doc, f.extensions[0]));
let (main, linked) = files.split_at(enc.files.len());
// Text formats come back as text; an SVG in UTF-16 or ISO 8859-1 also as its bytes.
@@ -58,6 +98,8 @@ pub(super) fn export(s: &mut Session, p: &Value) -> Result<Value> {
super::check_not_lossy_overwrite(s.doc()?, path, p, "document.export")?;
}
let f = writable("document.export", text_param(p, "format", "document.export")?, path)?;
check_linked_scripts("document.export", f.id, s.doc()?)?;
let unused = unused_option_notes("document.export", f, p);
let expanded = expand_presets(s, "document.export", p)?;
let p = with_black_output(s, &expanded);
let (doc, display_doc_title) = source(s, f, &p, "document.export")?;
@@ -68,7 +110,8 @@ pub(super) fn export(s: &mut Session, p: &Value) -> Result<Value> {
{
o.insert("_displayDocTitle".into(), json!(display_doc_title));
}
let enc = encode_all(doc, f.id, &q)?;
let mut enc = encode_all(doc, f.id, &q)?;
enc.add_setting_notes(unused);
write_encoded(path, &default_name(doc, f.extensions[0]), doc, &enc, json!({ "format": f.id, "warnings": enc.notes() }))
}
@@ -315,12 +358,19 @@ pub(super) fn export_selection(s: &mut Session, p: &Value) -> Result<Value> {
super::check_not_lossy_overwrite(s.doc()?, path, p, C)?;
}
let f = writable(C, text_param(p, "format", C)?, path)?;
check_linked_scripts(C, f.id, s.doc()?)?;
let unused = unused_option_notes(C, f, p);
let expanded = expand_presets(s, C, p)?;
let p = with_black_output(s, &expanded);
let (d, bounds) = selection(s, C, f.id == "txt")?;
// The encoder's warnings (options accepted but not applied, features approximated or left
// out), as document.export reports them.
let (bytes, warnings) = encode_with_warnings(&d, f.id, &without_artboards(&p))?;
let (bytes, mut warnings) = encode_with_warnings(&d, f.id, &without_artboards(&p))?;
for note in unused {
if !warnings.contains(&note) {
warnings.push(note);
}
}
write_or_return(path, &bytes, json!({ "format": f.id, "warnings": warnings, "bounds": [bounds.x0, bounds.y0, bounds.width(), bounds.height()] }))
}
+10 -2
View File
@@ -520,6 +520,8 @@ pub const FORMATS: &[Format] = &[
reader("heif", "HEIC/HEIF", &["heic", "heif"], "image/heic", true),
// jxl-oxide reads a JPEG XL file's first frame, which is stored as PNG. Exports don't write it.
reader("jxl", "JPEG XL", &["jxl"], "image/jxl", true),
// QuickDraw pictures, read by `vectorcraft_metafile::import_pict` into paths, type and images.
reader("pict", "PICT", &["pct", "pic", "pict"], "image/x-pict", false),
];
/// Every extension `document.open` reads (the "All readable files" filter of open dialogs).
@@ -564,6 +566,9 @@ pub const OPEN_EXTS: &[&str] = &[
"dxf",
"emf",
"wmf",
"pct",
"pic",
"pict",
"plt",
"hpgl",
"hgl",
@@ -581,10 +586,10 @@ pub const OPEN_EXTS: &[&str] = &[
/// `.epsf`, `.ps`, Targa, PCX, Pixar, JPEG 2000, HEIC/HEIF or JPEG XL type, nor one for the `.pns`, `.dib` and `.rle` names of
/// PNG and BMP files (File › Open and Place still read them all). On Linux the desktop entry's EPS
/// type (shared-mime-info's) also covers `.epsf`, so file managers offer VectorCraft for it.
/// The packaging declares no type for HP-GL plot files either.
/// The packaging declares no type for HP-GL plot files or PICT pictures either.
pub const UNASSOCIATED_EXTS: &[&str] = &[
"psd", "pdd", "psb", "epsf", "ps", "pns", "dib", "rle", "tga", "vda", "icb", "vst", "pcx", "pxr", "jpf", "jpx", "jp2", "j2k", "j2c", "jpc",
"heic", "heif", "jxl", "plt", "hpgl", "hgl", "hpg",
"heic", "heif", "jxl", "plt", "hpgl", "hgl", "hpg", "pct", "pic", "pict",
];
/// The extension that picks each writable format when exporting (the format's first; PNG-8 shares
@@ -658,6 +663,9 @@ pub const PLACE_EXTS: &[&str] = &[
"dxf",
"emf",
"wmf",
"pct",
"pic",
"pict",
"plt",
"hpgl",
"hgl",
+16 -2
View File
@@ -65,6 +65,18 @@ pub(super) fn named(f: &Format) -> Format {
Format { label: "legacy .ai (version 7)", ..*f }
}
/// The `.ai` options that only a legacy file reads: a PDF-compatible `.ai` file and a `.ai` file
/// without PDF content don't.
pub(super) const LEGACY_ONLY: [&str; 3] = ["transparentImages", "hiddenObjects", "outlineText"];
/// Does an export of a legacy file read option `key`? It reads the version, the file's own
/// options ([`LEGACY_ONLY`]), the artboards to write, and `useArtboards`, which the export reads
/// before [`encode`] runs. It reads none of the other `.ai` options and none of the PDF options
/// that a PDF-compatible `.ai` file takes.
pub(super) fn reads(key: &str) -> bool {
matches!(key, "aiVersion" | "useArtboards") || LEGACY_ONLY.contains(&key) || super::ARTBOARD_PARAMS.contains(&key)
}
/// What a legacy `.ai` does with the images it can't hold (`transparentImages`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum SeeThrough {
@@ -185,7 +197,8 @@ fn expand_image_patterns(d: &mut Document) -> Result<()> {
}
/// The images of `d` a legacy `.ai` can't hold, in paint order with their places in it (as
/// [`Document::walk`] counts). These have see-through pixels or a colorize paint (except the
/// [`Document::walk`] counts). These have see-through pixels (a color-masked image's masked pixels
/// counted as its own) or a colorize paint (except the
/// colorized images the writer writes as image masks, clear pixels included,
/// [`vectorcraft_eps::writes_image_mask`]), or
/// have opacity or a blending mode of their own or, with `flatten`, of a group they are in.
@@ -197,7 +210,8 @@ fn see_through_images(d: &Document, mode: SeeThrough) -> Vec<(usize, NodeId)> {
let mut at = 0;
d.walk(|n| {
if let NodeKind::Image(im) = &n.kind
&& (((keys.contains(&im.key) || n.extras().colorize.is_some()) && !vectorcraft_eps::writes_image_mask(d, n))
&& (((keys.contains(&im.key) || keys.contains(&d.shown_image(n, im).key) || n.extras().colorize.is_some())
&& !vectorcraft_eps::writes_image_mask(d, n))
|| n.opacity < 1.0
|| n.blend != BlendMode::Normal
|| (mode == SeeThrough::Flatten && transparent(d, n.id)))
+53 -21
View File
@@ -73,6 +73,8 @@ pub struct RasterImage {
pub height: u32,
/// The resolution the file declares (see [`super::ppi::resolution`]).
pub ppi: Option<(f64, f64)>,
/// A DCS file's clipping path, in the image's pixel space ([`crate::cmd::place::dcs`]).
pub clip: Option<vectorcraft_geom::PathData>,
}
pub(super) fn err(e: impl std::fmt::Display) -> EngineError {
@@ -132,6 +134,12 @@ pub fn detect(name: &str, bytes: &[u8]) -> Option<&'static Format> {
if let Some(f) = image::guess_format(bytes).ok().and_then(image_format) {
return Some(f);
}
// A version 2 PICT is known by its version opcodes after the picture's frame, at byte 522 of a
// file or byte 10 of a bare picture (version 1 by its file's name), so a format whose
// signature starts the file is checked first.
if vectorcraft_metafile::is_pict(bytes) {
return format("pict");
}
if clipboard::looks_like_svg(&String::from_utf8_lossy(&bytes[..bytes.len().min(4096)])) {
return format("svg");
}
@@ -380,6 +388,10 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
let (mut doc, mut warnings, restored) = match format.id {
// EPS, .ps and PostScript .ai: the document our EPS files carry, else the PostScript read.
_ if matches!(format.id, "eps" | "ps") || vectorcraft_pdf::is_postscript(bytes) => {
// A DCS file's plates print from its file: it is only placed linked.
if crate::cmd::place::dcs::is_dcs(bytes) {
return Err(err(format!("can't open `{}`: {}", file_name(name), crate::cmd::place::dcs::LINK_ONLY)));
}
let editing = vectorcraft_eps::has_native(bytes).then_some((true, || vectorcraft_eps::native(bytes)));
restore_or_import(editing, || {
let r = vectorcraft_eps::import_names(bytes, opts.editing_data, opts.trust_editing_data, opts.legacy_names)
@@ -499,6 +511,10 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
let (doc, warnings) = super::metafile::import(bytes)?;
(doc, warnings, false)
}
"pict" => {
let (doc, warnings) = super::metafile::import_pict(bytes)?;
(doc, warnings, false)
}
"hpgl" => {
let i = vectorcraft_cad::hpgl::import(bytes).map_err(err)?;
(i.document, i.warnings, false)
@@ -852,9 +868,12 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option<String> {
/// A TIFF with more strips or tiles than the decoder can count
/// ([`vectorcraft_doc::cmyk::oversized_tiff`]) is refused as too large to draw. JPEG XL images are
/// read with [`jxlread`] and stored as PNG, with the ICC profile their colors are left in.
/// A PNG, JPEG, GIF, WebP or TIFF whose orientation ([`exif_orientation`]) turns or flips it is
/// A PNG, JPEG, GIF, WebP or TIFF whose orientation ([`vectorcraft_doc::cmyk::exif_orientation`]) turns or flips it is
/// stored as it is shown, with its resolution's axes swapped when it turns a quarter; a CMYK JPEG
/// or TIFF keeps its inks, 8 bits each, as a CMYK TIFF ([`vectorcraft_doc::cmyk::turned_cmyk`]).
/// or TIFF keeps its inks, at the 8 or 16 bits the file has, and its CMYK ICC profile as a CMYK
/// TIFF ([`vectorcraft_doc::cmyk::turned_cmyk`]). An image the decoder reads and that is stored as
/// PNG keeps its gray or RGB samples at 8 or 16 bits, and the gray or RGB ICC profile they are in;
/// other samples become 8-bit RGBA.
pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> {
let ppi = super::ppi::resolution(bytes);
if let Some((w, h)) = vectorcraft_doc::cmyk::oversized_tiff(bytes) {
@@ -893,7 +912,7 @@ pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> {
let f = image_format(kind).ok_or_else(|| err(format!("{kind:?} images can't be opened (see document.formats)")))?;
// A photo whose EXIF orientation turns or flips it (a camera held upright) is stored as it is
// seen, so it places the way it was taken (#4284); the others keep their own bytes.
let orientation = matches!(f.id, "png" | "jpg" | "gif" | "webp" | "tiff").then(|| exif_orientation(bytes)).flatten();
let orientation = matches!(f.id, "png" | "jpg" | "gif" | "webp" | "tiff").then(|| vectorcraft_doc::cmyk::exif_orientation(bytes)).flatten();
let turned = orientation.is_some();
// The resolution describes the stored pixels; a quarter turn swaps its axes.
let quarter = orientation.is_some_and(|o| o.to_exif() >= 5);
@@ -917,47 +936,60 @@ pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> {
let cms = vectorcraft_color::cms::active();
vectorcraft_doc::cmyk::extra_samples_tiff_rgba(bytes, |c| cms.cmyk_to_srgb(c, false))
};
// The ICC profile of the samples the image decoder reads; the other readers give sRGB pixels.
let mut icc = None;
let mut img = match (f.id == "tiff").then(extra_samples).flatten() {
Some(img) => image::DynamicImage::ImageRgba8(img),
None => match (f.id == "tiff").then(|| vectorcraft_doc::cmyk::group3_tiff_rgba(bytes)).flatten() {
Some(read) => image::DynamicImage::ImageRgba8(read.map_err(err)?),
None => {
use image::ImageDecoder as _;
let decoder = reader.into_decoder().map_err(err)?;
let mut decoder = reader.into_decoder().map_err(err)?;
// The allowance counts the decoded samples and the RGBA pixels they become (#1717).
let (w, h) = decoder.dimensions();
if decoder.total_bytes() > MAX_RASTER_ALLOC || u64::from(w) * u64::from(h) * 4 > MAX_RASTER_ALLOC {
return Err(err(format!("an image of {w} × {h} pixels is too large to draw")));
}
// A profile the decoder can't read leaves the image without one. The image decoder
// reads a TIFF's tags within the size of its pixels, so a small TIFF's profile is
// read by the TIFF decoder itself.
icc = match f.id {
"tiff" => vectorcraft_doc::cmyk::tiff_icc_profile(bytes),
_ => decoder.icc_profile().ok().flatten(),
};
image::DynamicImage::from_decoder(decoder).map_err(err)?
}
},
};
img.apply_orientation(orientation.unwrap_or(image::metadata::Orientation::NoTransforms));
let mut img = img.into_rgba8();
if f.id == "tga" {
let mut img = img.into_rgba8();
super::tgaread::fix_alpha(bytes, &mut img);
return as_png(img, None, shown_ppi);
}
as_png(img, None, shown_ppi)
use image::DynamicImage as D;
let img = match img {
D::ImageLuma8(_) | D::ImageLumaA8(_) | D::ImageRgb8(_) | D::ImageRgba8(_) => img,
D::ImageLuma16(_) | D::ImageLumaA16(_) | D::ImageRgb16(_) | D::ImageRgba16(_) => img,
other => D::ImageRgba8(other.into_rgba8()),
};
let icc = icc.filter(|icc| png_takes_icc(&img, icc));
as_png(img, icc, shown_ppi)
}
/// The EXIF orientation of encoded image `bytes` when it turns or flips the pixels; `None` when
/// it leaves them as stored, or the image has none. A TIFF the image decoder can't open (one with
/// extra samples) has its Orientation tag read from its first image
/// ([`vectorcraft_doc::cmyk::tiff_orientation`]).
pub(crate) fn exif_orientation(bytes: &[u8]) -> Option<image::metadata::Orientation> {
use image::ImageDecoder as _;
use image::metadata::Orientation;
let decoded = || image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?.into_decoder().ok()?.orientation().ok();
let tagged = || vectorcraft_doc::cmyk::tiff_orientation(bytes).and_then(|v| Orientation::from_exif(u8::try_from(v).ok()?));
decoded().or_else(tagged).filter(|o| *o != Orientation::NoTransforms)
/// Can a PNG of `img`'s samples carry ICC profile `icc`? Its color space must be the samples':
/// `GRAY` for gray samples, `RGB ` for RGB ones.
fn png_takes_icc(img: &image::DynamicImage, icc: &[u8]) -> bool {
let want = if img.color().has_color() { *b"RGB " } else { *b"GRAY" };
vectorcraft_doc::cmyk::icc_color_space(icc) == Some(want)
}
/// `img` stored as a PNG that keeps the file's resolution and carries `icc`, the ICC profile its
/// colors are in.
pub(super) fn as_png(img: image::RgbaImage, icc: Option<Vec<u8>>, ppi: Option<(f64, f64)>) -> Result<RasterImage> {
/// colors are in. `img` has samples a PNG holds: 8 or 16 bits of gray or RGB, with or without alpha.
pub(super) fn as_png(img: impl Into<image::DynamicImage>, icc: Option<Vec<u8>>, ppi: Option<(f64, f64)>) -> Result<RasterImage> {
use image::ImageEncoder as _;
let size = img.dimensions();
let img: image::DynamicImage = img.into();
let size = (img.width(), img.height());
let mut png = Vec::new();
let mut encoder = image::codecs::png::PngEncoder::new(&mut png);
if let Some(icc) = icc {
@@ -1014,13 +1046,13 @@ fn stored(bytes: Vec<u8>, mime: &'static str, (width, height): (u32, u32), ppi:
return Err(err("the image is empty"));
}
let blob = ImageBlob::new(mime, bytes);
Ok(RasterImage { key: blob.content_key(), blob, width, height, ppi })
Ok(RasterImage { key: blob.content_key(), blob, width, height, ppi, clip: None })
}
/// An image as a document of its physical size at the resolution it declares (as Place sizes it;
/// 72 ppi, 1 px = 1 pt, when it declares none), the image named after the file.
pub(super) fn raster_doc(name: &str, bytes: &[u8]) -> Result<Document> {
let RasterImage { key, blob, width, height, ppi } = raster_image(bytes)?;
let RasterImage { key, blob, width, height, ppi, .. } = raster_image(bytes)?;
let (sx, sy) = crate::cmd::place::pt_per_px(ppi);
let mut d = Document::new(width as f64 * sx, height as f64 * sy);
let layer = d.layers[0].id;
+7
View File
@@ -2,6 +2,7 @@
//! `document.export {format: emf|wmf}` and Export As (one picture of an artboard, or one per
//! artboard with Use Artboards; raster effects as images, rendered at the document's raster
//! effects resolution), `document.open` and File → Place (one artboard, the picture's frame).
//! QuickDraw pictures (PICT) open and place the same way; they are never written.
use serde_json::Value;
use vectorcraft_doc::Document;
@@ -52,3 +53,9 @@ pub(super) fn import(bytes: &[u8]) -> Result<(Document, Vec<String>)> {
let i = vectorcraft_metafile::import(bytes).map_err(super::err)?;
Ok((i.document, i.warnings))
}
/// A QuickDraw picture's document and the import's warnings.
pub(super) fn import_pict(bytes: &[u8]) -> Result<(Document, Vec<String>)> {
let p = vectorcraft_metafile::import_pict(bytes).map_err(super::err)?;
Ok((p.document, p.warnings))
}
+1 -1
View File
@@ -133,7 +133,7 @@ pub const AI_OPTIONS: &[FormatOption] = &[
name: "outlineText",
ty: "boolean",
default: "false",
description: "with aiVersion 7, type as its outlines instead of text (which apps reading the file set in the fonts it names: they need them installed); type 8-bit text can't hold (characters outside Windows Latin-1, vertical type, ruby, inline graphics, gradient or pattern fills) and type with rotated characters are always outlines",
description: "with aiVersion 7, type as its outlines instead of text (which apps reading the file set in the fonts it names: they need them installed); type 8-bit text can't hold (characters outside Windows Latin-1, vertical type, ruby, warichu, inline graphics, gradient or pattern fills) and type with rotated characters are always outlines",
},
];
File diff suppressed because one or more lines are too long
+46 -4
View File
@@ -317,7 +317,7 @@ pub fn save_plan(s: &Session, mode: SaveMode, p: &Value) -> Result<SavePlan> {
let notes = top
.filter(|k| !reads_option(format, k))
.chain(nested.filter(|k| !reads_option(format, k)).map(|k| format!("options.{k}")))
.map(|k| format!("`{k}` was not used: {} files don't read it", written.label))
.map(|k| unused_option_note(&k, &written))
.collect();
let lossy_source = super::lossy_source(st, p);
Ok(SavePlan { mode, path, format, options, name, folder, modified, notes, lossy_source })
@@ -467,6 +467,12 @@ pub fn reads_option(f: &Format, key: &str) -> bool {
f.options.iter().any(|o| o.name == key) || (is_pdf(f) && (super::pdf::OPTIONS.iter().any(|o| o.name == key) || super::pdf::is_setting(key)))
}
/// The note a save or an export gives for option `key`, as the request names it, which the file it
/// writes (`written`, see [`written_as`]) doesn't read.
pub(super) fn unused_option_note(key: &str, written: &Format) -> String {
format!("`{key}` was not used: {} files don't read it", written.label)
}
/// Formats that carry the whole native document: they lose nothing, and record links relative to
/// where they are written. A `.ai` or `.ait` file is a PDF carrying it; EPS carries it in comments.
fn is_native(f: &Format) -> bool {
@@ -636,7 +642,7 @@ fn without_pdf(f: &Format) -> Format {
/// `f` named, in its errors and notes, as the file a save with options `p` writes: a version 7
/// `.ai` as the legacy `.ai`, and a `.ai` or `.ait` with `pdfCompatible: false` as one saved
/// without PDF content.
fn written_as(cmd: &str, f: &Format, p: &Value) -> Format {
pub(super) fn written_as(cmd: &str, f: &Format, p: &Value) -> Format {
if f.id == "ai" && super::legacy_ai::wanted(cmd, f, p).unwrap_or(false) {
super::legacy_ai::named(f)
} else if matches!(f.id, "ai" | "ait") && !bool_or(p, "pdfCompatible", true) {
@@ -685,6 +691,31 @@ struct AiEditingData {
editing_data: Option<bool>,
}
/// Why a `.ai` file of the art's bounds (`useArtboards: false`) carries no editing data.
pub const AI_EDITING_NEEDS_THE_ARTBOARDS: &str =
"Preserve editing was left out: an .ai file of the art's bounds would replace the document's artboards when reopened";
/// The error for a `.ai` file of the art's bounds without PDF content.
pub const ART_PAGE_NEEDS_PDF: &str = "pdfCompatible: false needs the artboards to keep the editable artwork when useArtboards is false";
/// With `useArtboards: false` in `p`: the PDF-compatible `.ai` file of one page, the bounds of
/// `doc`'s visible art ([`super::encode::art_page`]). It carries neither the native document nor
/// the editing copy for other apps, and its notes end with [`AI_EDITING_NEEDS_THE_ARTBOARDS`].
/// `pdfCompatible: false` is refused. `None` when `p` asks for the artboards or for a legacy
/// version 7 `.ai` file.
pub(super) fn encode_ai_art_page(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result<Option<Encoded>> {
if super::encode::use_artboards(cmd, p)? != Some(false) || super::legacy_ai::wanted(cmd, f, p)? {
return Ok(None);
}
if !bool_or(p, "pdfCompatible", true) {
return Err(bad(cmd, ART_PAGE_NEEDS_PDF));
}
let Some((art, q)) = super::encode::art_page(cmd, doc, p)? else { return Ok(None) };
let mut enc = encode_ai_pages(cmd, f, &art, &q, false)?;
enc.setting_notes.push(AI_EDITING_NEEDS_THE_ARTBOARDS.to_string());
Ok(Some(enc))
}
/// The shared Save and Export encoder for `.ai` files (and `.ait` templates, the same file):
/// PDF-compatible by default, without PDF content (`pdfCompatible: false`), or legacy version 7
/// `.ai` files (`aiVersion: "7"`).
@@ -692,13 +723,23 @@ pub(super) fn encode_ai(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Res
if super::legacy_ai::wanted(cmd, f, p)? {
return super::legacy_ai::encode(cmd, f, doc, p);
}
encode_ai_pages(cmd, f, doc, p, true)
}
/// [`encode_ai`] of a `.ai` file with or without PDF content, carrying the native document and
/// the editing copy for other apps when `editing` is true, and neither otherwise.
fn encode_ai_pages(cmd: &str, f: &Format, doc: &Document, p: &Value, editing: bool) -> Result<Encoded> {
let mut params = if p.is_object() { p.clone() } else { json!({}) };
if let Some(o) = params.as_object_mut() {
o.insert("preserveEditing".into(), json!(true));
o.insert("preserveEditing".into(), json!(editing));
// Keep upstream AI PDF layers, including hidden layers, unless a standard decides.
if o.get("standard").is_none_or(Value::is_null) {
o.entry("createLayers").or_insert(json!(true));
}
// A page longer than 14,400 pt keeps its `UserUnit` (PDF export writes it in points).
if o.get("longPagesInPoints").is_none_or(Value::is_null) {
o.insert("longPagesInPoints".into(), json!(false));
}
if let Some(c) = o.get("compress").and_then(Value::as_bool) {
let compression = o.entry("compression").or_insert_with(|| json!({}));
if let Some(m) = compression.as_object_mut() {
@@ -781,6 +822,7 @@ pub(crate) fn job_for(s: &Session, st: &DocState, plan: SavePlan) -> Result<Save
fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option<i64>) -> Result<SaveJob> {
let cmd = plan.mode.command();
super::check_linked_scripts(cmd, plan.format.id, st)?;
let mut own = doc_to_save(st, plan.format);
// The file the document is saved as (else its own) titles it if New's name is all it has.
let file = plan.path.as_deref().filter(|_| plan.retargets()).or(st.path.as_deref());
@@ -1197,7 +1239,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
"Save Document",
[],
None,
"{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings say when the format doesn't read compress, version, preview or precision given flat, or a key given in options), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to <name>-<artboard>.<ext> beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to <name>_<artboard>.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel",
"{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings say when the format doesn't read compress, version, preview or precision given flat, or a key given in options), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to <name>-<artboard>.<ext> beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to <name>_<artboard>.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them; an svg or svgz save (a document whose own format is SVG or SVGZ included) is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), also by file.saveAs and file.saveCopy. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel",
has_doc,
|s, p| save(s, SaveMode::Save, p)
),
+4
View File
@@ -1030,6 +1030,10 @@ pub(crate) fn export(s: &mut Session, p: &Value) -> Result<Value> {
o.one_source()?;
// `<filename>`: the document's file, as Save names it, or its title before it is saved.
let st = s.doc()?;
// Before the folder is made or any row is written.
for r in &rows {
super::check_linked_scripts(C, r.format.id, st)?;
}
let naming = Naming::of(&o, st.path.as_deref().unwrap_or(&st.doc.title))?;
let selection = o.selection_mode()?;
let selected = if selection.is_some() { selected_artwork(s)? } else { vec![] };
+210
View File
@@ -1171,6 +1171,216 @@ fn png_webp_and_rgb_tiff_turned_a_quarter_swap_their_resolution() {
}
}
/// A made-up ICC profile of `len` bytes (at least a header's 128) whose header names the color
/// space `space`; the bytes after the header differ from place to place.
fn icc_profile(space: &[u8; 4], len: usize) -> Vec<u8> {
let mut icc: Vec<u8> = (0..len).map(|i| (i % 251) as u8).collect();
icc[..4].copy_from_slice(&u32::try_from(len).unwrap().to_be_bytes());
icc[12..16].copy_from_slice(b"mntr");
icc[16..20].copy_from_slice(space);
icc[36..40].copy_from_slice(b"acsp");
icc
}
/// `tiff` (little-endian) with an ICCProfile tag (34675, of type UNDEFINED) holding `icc`: its first
/// directory copied to the end of the file with the tag added in order, as [`tiff_oriented`] adds
/// its tag.
fn tiff_with_icc(tiff: &[u8], icc: &[u8]) -> Vec<u8> {
let at = usize::try_from(u32::from_le_bytes(tiff[4..8].try_into().unwrap())).unwrap();
let n = usize::from(u16::from_le_bytes([tiff[at], tiff[at + 1]]));
let mut entries: Vec<Vec<u8>> = tiff[at + 2..at + 2 + 12 * n].chunks(12).map(<[u8]>::to_vec).collect();
let mut out = tiff.to_vec();
if out.len() % 2 == 1 {
out.push(0);
}
let data = u32::try_from(out.len()).unwrap();
out.extend(icc);
if out.len() % 2 == 1 {
out.push(0);
}
let i = entries.iter().position(|e| u16::from_le_bytes([e[0], e[1]]) > 34675).unwrap_or(n);
let count = u32::try_from(icc.len()).unwrap();
entries.insert(i, [&34675u16.to_le_bytes()[..], &7u16.to_le_bytes(), &count.to_le_bytes(), &data.to_le_bytes()].concat());
let ifd = u32::try_from(out.len()).unwrap();
out[4..8].copy_from_slice(&ifd.to_le_bytes());
out.extend(u16::try_from(n + 1).unwrap().to_le_bytes());
out.extend(entries.concat());
out.extend([0; 4]);
out
}
/// The ICC profile and pixels of a stored image, read by the image decoder for its format.
fn stored_pixels(what: &str, img: &RasterImage) -> (Option<Vec<u8>>, image::ExtendedColorType, image::DynamicImage) {
use image::ImageDecoder as _;
let bytes = Cursor::new(img.blob.bytes.as_slice());
let mut d: Box<dyn image::ImageDecoder> = match img.blob.mime.as_str() {
"image/png" => Box::new(image::codecs::png::PngDecoder::new(bytes).unwrap()),
"image/tiff" => Box::new(image::codecs::tiff::TiffDecoder::new(bytes).unwrap()),
other => panic!("{what}: stored as {other}"),
};
let icc = d.icc_profile().unwrap();
let color = d.original_color_type();
(icc, color, image::DynamicImage::from_decoder(d).unwrap())
}
/// An image turned by its orientation and stored as PNG keeps the gray or RGB ICC profile its file
/// carries, and its 16-bit samples at 16 bits, from a PNG, a JPEG, a WebP and a TIFF; a TIFF the
/// image decoder reads, stored as PNG without a turn, keeps them too. A profile of another color
/// space than the samples' is left out.
#[test]
fn images_stored_as_png_keep_their_icc_profile_and_16_bit_samples() {
use image::{DynamicImage, ImageEncoder as _};
let (rgb_icc, gray_icc, cmyk_icc) = (icc_profile(b"RGB ", 600), icc_profile(b"GRAY", 300), icc_profile(b"CMYK", 400));
// 3 × 2, every sample's low byte different.
let rgb16 = image::ImageBuffer::from_fn(3, 2, |x, y| {
let v = u16::try_from(x * 0x1111 + y * 0x2345).unwrap();
image::Rgb([0x1000 + v, 0x8001 + v, 0xF0F3 - v])
});
let rgb16 = DynamicImage::ImageRgb16(rgb16);
let gray16 = DynamicImage::ImageLuma16(image::ImageBuffer::from_fn(3, 2, |x, y| image::Luma([u16::try_from(x * 0x3001 + y * 0x0107).unwrap()])));
let rgb8 = DynamicImage::ImageRgb8(image::RgbImage::from_fn(3, 2, |x, y| image::Rgb([u8::try_from(x * 70 + y * 9).unwrap(), 200, 13])));
let png = |img: &DynamicImage, icc: &[u8], orientation: u16| {
let mut out = Vec::new();
let mut enc = image::codecs::png::PngEncoder::new(&mut out);
enc.set_icc_profile(icc.to_vec()).unwrap();
enc.set_exif_metadata(exif_block(orientation, (150, 150))).unwrap();
img.write_with_encoder(enc).unwrap();
out
};
let webp = {
let mut out = Vec::new();
let mut enc = image::codecs::webp::WebPEncoder::new_lossless(&mut out);
enc.set_icc_profile(rgb_icc.clone()).unwrap();
enc.set_exif_metadata(exif_block(6, (150, 150))).unwrap();
rgb8.write_with_encoder(enc).unwrap();
out
};
let tiff = |orientation: Option<u16>| {
let mut out = Vec::new();
let mut enc = image::codecs::tiff::TiffEncoder::new(Cursor::new(&mut out));
enc.set_icc_profile(rgb_icc.clone()).unwrap();
rgb16.write_with_encoder(enc).unwrap();
match orientation {
Some(o) => tiff_oriented(&out, o, false, None),
None => out,
}
};
// (what, file, the ICC profile to keep, the pixels as they show, 16 bits)
type Case<'a> = (&'a str, Vec<u8>, Option<&'a [u8]>, DynamicImage, bool);
let cases: Vec<Case> = vec![
("16-bit RGB PNG, orientation 6", png(&rgb16, &rgb_icc, 6), Some(&rgb_icc), rgb16.rotate90(), true),
("16-bit gray PNG, orientation 8", png(&gray16, &gray_icc, 8), Some(&gray_icc), gray16.rotate270(), true),
("8-bit RGB PNG, orientation 3", png(&rgb8, &rgb_icc, 3), Some(&rgb_icc), rgb8.rotate180(), false),
("RGB PNG with a CMYK profile, orientation 6", png(&rgb8, &cmyk_icc, 6), None, rgb8.rotate90(), false),
("WebP, orientation 6", webp, Some(&rgb_icc), rgb8.rotate90(), false),
("16-bit RGB TIFF, not turned", tiff(None), Some(&rgb_icc), rgb16.clone(), true),
("16-bit RGB TIFF, orientation 6", tiff(Some(6)), Some(&rgb_icc), rgb16.rotate90(), true),
];
for (what, file, icc, want, wide) in cases {
let img = raster_image(&file).unwrap_or_else(|e| panic!("{what}: {e}"));
assert_eq!((img.width, img.height, img.blob.mime.as_str()), (want.width(), want.height(), "image/png"), "{what}");
let (kept, color, px) = stored_pixels(what, &img);
assert_eq!(kept.as_deref(), icc, "{what}: the ICC profile");
assert_eq!(color.bits_per_pixel() / u16::from(color.channel_count()), if wide { 16 } else { 8 }, "{what}: the sample depth");
if wide {
assert_eq!(px.to_rgb16(), want.to_rgb16(), "{what}: the samples");
} else {
assert_eq!(px.to_rgb8(), want.to_rgb8(), "{what}: the samples");
}
}
// A JPEG's samples change in encoding; its profile is kept.
let mut jpg = Vec::new();
let mut enc = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpg, 95);
enc.set_icc_profile(rgb_icc.clone()).unwrap();
rgb8.write_with_encoder(enc).unwrap();
let exif = [b"Exif\0\0".as_slice(), &exif_block(6, (150, 150))].concat();
let mut turned = jpg[..2].to_vec();
turned.extend([0xff, 0xe1]);
turned.extend(u16::try_from(exif.len() + 2).unwrap().to_be_bytes());
turned.extend(&exif);
turned.extend(&jpg[2..]);
let img = raster_image(&turned).unwrap();
assert_eq!((img.width, img.height, img.blob.mime.as_str()), (2, 3, "image/png"), "JPEG");
assert_eq!(stored_pixels("JPEG", &img).0, Some(rgb_icc.clone()), "JPEG: the ICC profile");
// Not turned, a PNG keeps its own bytes.
let plain = png(&rgb16, &rgb_icc, 1);
assert_eq!(raster_image(&plain).unwrap().blob.bytes.as_slice(), plain.as_slice(), "a PNG as taken keeps its bytes");
}
/// A CMYK TIFF stored again, because it stores one plane per ink or because its orientation turns
/// it, keeps its ICC profile as tag 34675 and its 8 or 16 bits a sample, exactly; one that stores
/// its inks together and isn't turned keeps its own bytes.
#[test]
fn cmyk_tiffs_written_again_keep_their_icc_profile_and_depth() {
use image::DynamicImage;
let icc = icc_profile(b"CMYK", 900);
// 3 × 2, no black, every sample's low byte different.
let ink = |c: usize, p: usize| -> u16 { u16::try_from(0x0101 * (c * 5 + p + 1) + 0x10 * p + c).unwrap() };
for bits in [8u16, 16] {
let sample = |c: usize, p: usize| match (c, bits) {
(3, _) => 0,
(_, 16) => ink(c, p),
_ => ink(c, p) & 0xFF,
};
let channels: Vec<Vec<u16>> = (0..4).map(|c| (0..6).map(|p| sample(c, p)).collect()).collect();
// The image decoder shows a CMYK pixel without black as 1 - C, 1 - M, 1 - Y, exactly.
let full = if bits == 16 { 0xFFFF } else { 0xFF };
let shown: Vec<u16> = (0..6).flat_map(|p| (0..3).map(|c| full - channels[c][p]).collect::<Vec<_>>()).collect();
let shown = if bits == 16 {
DynamicImage::ImageRgb16(image::ImageBuffer::from_raw(3, 2, shown).unwrap())
} else {
DynamicImage::ImageRgb8(image::RgbImage::from_raw(3, 2, shown.iter().map(|v| u8::try_from(*v).unwrap()).collect()).unwrap())
};
for planar in [false, true] {
let file = tiff_with_icc(&hand_tiff(5, bits, &[], planar, &channels), &icc);
for (orientation, want) in [(None, shown.clone()), (Some(6), shown.rotate90()), (Some(3), shown.rotate180())] {
let what = format!("{bits} bits, planar {planar}, orientation {orientation:?}");
let file = orientation.map_or_else(|| file.clone(), |o| tiff_oriented(&file, o, false, Some(150)));
let img = raster_image(&file).unwrap_or_else(|e| panic!("{what}: {e}"));
if orientation.is_none() && !planar {
assert_eq!(img.blob.bytes.as_slice(), file.as_slice(), "{what}: kept as it is");
}
let (kept, color, px) = stored_pixels(&what, &img);
assert_eq!(kept.as_deref(), Some(icc.as_slice()), "{what}: the ICC profile");
let depth = if bits == 16 { image::ExtendedColorType::Cmyk16 } else { image::ExtendedColorType::Cmyk8 };
assert_eq!(color, depth, "{what}: the sample depth");
assert_eq!(px, want, "{what}: the samples");
}
}
}
}
/// A CMYK JPEG turned by its orientation and stored as a CMYK TIFF keeps its whole ICC profile,
/// put together from the two APP2 segments a profile larger than one segment is split into.
#[test]
fn a_turned_cmyk_jpeg_keeps_its_icc_profile_from_every_segment() {
use vectorcraft_render::encode::jpeg::{self, ColorModel, JpegOptions};
let icc = icc_profile(b"CMYK", 70_000);
let inks: Vec<u8> = (0..16u32 * 8).flat_map(|i| [u8::try_from(i).unwrap(), 0, 0, 40]).collect();
let o = JpegOptions { color_model: ColorModel::Cmyk, embed_icc: false, ..Default::default() };
let jpg = jpeg::encode(&inks, 16, 8, 100, None, &o).unwrap();
let exif = [b"Exif\0\0".as_slice(), &exif_block(6, (300, 300))].concat();
let mut file = jpg[..2].to_vec();
file.extend([0xff, 0xe1]);
file.extend(u16::try_from(exif.len() + 2).unwrap().to_be_bytes());
file.extend(&exif);
let chunks: Vec<&[u8]> = icc.chunks(65_519).collect();
assert_eq!(chunks.len(), 2, "the profile takes two segments");
for (i, chunk) in chunks.iter().enumerate() {
file.extend([0xff, 0xe2]);
file.extend(u16::try_from(chunk.len() + 16).unwrap().to_be_bytes());
file.extend(b"ICC_PROFILE\0");
file.extend([u8::try_from(i + 1).unwrap(), 2]);
file.extend(*chunk);
}
file.extend(&jpg[2..]);
let img = raster_image(&file).unwrap();
assert_eq!((img.width, img.height, img.blob.mime.as_str()), (8, 16, "image/tiff"));
let (kept, color, _) = stored_pixels("CMYK JPEG", &img);
assert_eq!(color, image::ExtendedColorType::Cmyk8);
assert!(kept.as_deref() == Some(icc.as_slice()), "the whole ICC profile: {:?} bytes", kept.map(|k| k.len()));
}
/// With `importer` named, a file up to the importer's limit is read whole and a larger one is an
/// error, whatever its content.
#[test]
+26 -6
View File
@@ -424,25 +424,45 @@ fn a_graphic_style_library_in_a_ai_file_without_layers_loads_its_styles() {
/BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/FillStyle : 0 O\n{xa}0 1 Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n;\n"
)
};
// Styles of one paint (`/SimpleStyle`): a red 2 pt stroke and no fill, and a gradient fill,
// which isn't read, so it is left out rather than listed with no paint.
let one_paint = |name: &str, paint: &str| format!("/KnownStyle :\n({name}) /Name ,\n/SimpleStyle :\n{paint}/Paint ;\n/Def ;\n");
let styles = format!(
"%AI9_BeginArtStyles\n{}{}{}%AI9_EndArtStyles\n%AI9_BeginArtStyleList\n(Red)\n(Green)\n(Blue)\n%AI9_EndArtStyleList\n",
"%AI9_BeginArtStyles\n{}{}{}{}{}%AI9_EndArtStyles\n\
%AI9_BeginArtStyleList\n(Red)\n(Green)\n(Blue)\n(Red outline)\n(Sky fill)\n%AI9_EndArtStyleList\n",
style("Blue", "0 0 0 0 0 0 1 Xa\n"),
style("Green", "0 0 0 0 0 1 0 Xa\n"),
style("Red", "0 0 0 0 1 0 0 Xa\n")
style("Red", "0 0 0 0 1 0 0 Xa\n"),
one_paint("Red outline", "0 R\n0 1 1 0 K\n0 J 0 j 2 w 10 M []0 d\n1 0 Xd\n"),
one_paint("Sky fill", "0 O\n0 Bb\n2 (Sky) 0 0 0 100 1 0 0 1 0 0 Bg\n0 BB\n0 1 Xd\n")
);
let data = ai::editing_data(200.0, 100.0, &styles);
let file = ai::ai(&compressed(data.as_bytes()), "1 0 0 rg 10 50 30 40 re f");
let mut s = Session::new();
let p = json!({"dataBase64": vectorcraft_format::base64_encode(&file), "name": "fills.ai"});
let r = s.execute("graphicStyle.loadLibrary", &p).unwrap();
assert_eq!((&r["name"], &r["count"]), (&json!("fills"), &json!(3)), "{r}");
let lib = s.execute("graphicStyle.library", &json!({"library": r["library"]})).unwrap();
assert_eq!((&r["name"], &r["count"]), (&json!("fills"), &json!(4)), "{r}");
let library = r["library"].clone();
let lib = s.execute("graphicStyle.library", &json!({"library": library})).unwrap();
let names: Vec<&str> = lib["styles"].as_array().unwrap().iter().map(|g| g["name"].as_str().unwrap()).collect();
assert_eq!(names, ["Red", "Green", "Blue"], "{lib}");
assert_eq!(names, ["Red", "Green", "Blue", "Red outline"], "{lib}");
// The outline style strokes a rectangle red, 2 pt wide, and leaves it unfilled.
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
let id = NodeId(s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap());
let r = s.execute("graphicStyle.addFromLibrary", &json!({"library": library, "names": ["Red outline"], "apply": true, "ids": [id.0]})).unwrap();
assert_eq!(r["added"], json!(["Red outline"]), "{r}");
let doc = &s.doc().unwrap().doc;
let look = &doc.node(id).unwrap().appearance;
assert!(look.fill().is_none(), "{look:?}");
let strokes: Vec<_> = look.items.iter().filter(|i| matches!(i, vectorcraft_doc::AppearanceItem::Stroke(_))).collect();
assert_eq!(strokes.len(), 1, "{look:?}");
let stroke = look.stroke().unwrap();
assert_eq!((stroke.paint.color(), stroke.width), (Some(vectorcraft_color::Color::cmyk(0.0, 1.0, 1.0, 0.0)), 2.0), "{look:?}");
assert_eq!(doc.graphic_style("Red outline").map(|g| &g.appearance), Some(&**look));
let r = open(&mut s, "fills.ai", &file, json!({})).unwrap();
let doc = &s.doc().unwrap().doc;
let styles: Vec<(&str, u32)> = doc.graphic_styles.iter().map(|g| (g.name.as_str(), g.id)).collect();
assert_eq!(styles, [("Red", 1), ("Green", 2), ("Blue", 3)], "{r}");
assert_eq!(styles, [("Red", 1), ("Green", 2), ("Blue", 3), ("Red outline", 4)], "{r}");
}
/// A `.ai` symbol library (symbols and their list, no layers) opens with its symbols, and Other
+6 -5
View File
@@ -1,5 +1,5 @@
//! DXF export through the commands: options, artboards, selection, images, and the formats that
//! can't be written (DWG, PICT).
//! can't be written (DWG, PageMaker).
use serde_json::{Value, json};
@@ -275,23 +275,24 @@ fn formats_list_dxf_and_what_can_not_be_written() {
}
assert!(r["writable"].as_array().unwrap().contains(&json!("dxf")));
let unsupported: Vec<&str> = r["unsupported"].as_array().unwrap().iter().map(|u| u["id"].as_str().unwrap()).collect();
assert_eq!(unsupported, ["dwg", "pict", "pmd"]);
assert_eq!(unsupported, ["dwg", "pmd"]);
}
#[test]
fn dwg_and_pict_say_what_to_use_instead() {
fn dwg_and_pagemaker_say_what_to_use_instead() {
let mut s = two_boards();
for p in [json!({"format": "dwg"}), json!({"path": "/tmp/plan.DWG"})] {
let e = s.execute("document.export", &p).unwrap_err().to_string();
assert!(e.contains("DWG is not available") && e.contains("DXF"), "{p}: {e}");
}
// PICT opens; it isn't written.
let e = s.execute("document.export", &json!({"format": "pict"})).unwrap_err().to_string();
assert!(e.contains("PICT is a retired format"), "{e}");
assert!(e.contains("PICT files can be opened but not written"), "{e}");
let e = s
.execute("document.open", &json!({"name": "old.pct", "dataBase64": vectorcraft_format::base64_encode(&[0u8; 600])}))
.unwrap_err()
.to_string();
assert!(e.contains("old.pct") && e.contains("PICT"), "{e}");
assert!(e.contains("not a PICT file"), "{e}");
let e = s
.execute("document.open", &json!({"name": "site.dwg", "dataBase64": vectorcraft_format::base64_encode(b"AC1032\0\0")}))
.unwrap_err()
@@ -141,6 +141,137 @@ fn what_the_file_loses_comes_before_a_note_on_the_options() {
assert_eq!(r["warnings"], json!(w));
}
/// A session with one artboard and a selected rectangle on it.
fn with_art() -> Session {
let mut s = session(60.0, 40.0, 1);
s.execute("shape.rectangle", &json!({"x": 5, "y": 5, "width": 20, "height": 10})).unwrap();
s
}
/// The warnings of reply `r` that name an option the file doesn't read.
fn unused(r: &Value) -> Vec<String> {
r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).filter(|w| w.contains("was not used")).map(str::to_string).collect()
}
/// An option that only another format reads is accepted, and the reply's warnings name it in the
/// words of a save's note; `document.export`, `document.serialize` and `document.exportSelection`
/// give the same note.
#[test]
fn an_option_only_another_format_reads_gets_a_note() {
let (mut s, notes) = (with_art(), unused);
for cmd in ["document.export", "document.serialize", "document.exportSelection"] {
let r = s.execute(cmd, &json!({"format": "pdf", "quality": 80, "outlineText": true})).unwrap();
assert_eq!(
notes(&r),
["`outlineText` was not used: PDF files don't read it", "`quality` was not used: PDF files don't read it"],
"{cmd}: {r}"
);
}
// The format's own options, the keys every export takes and null values get none.
for p in [
json!({"format": "jpg", "quality": 80, "scale": 2}),
json!({"format": "ai", "compress": true, "compatibility": "1.7"}),
json!({"format": "pdf", "quality": null, "selectedOnly": false, "includeArtboardFill": false, "useArtboards": true}),
json!({"format": "svg", "outlineText": true, "svg": {"decimals": 2}}),
] {
let r = s.execute("document.export", &p).unwrap();
assert!(notes(&r).is_empty(), "{p}: {r}");
}
let r = s.execute("document.serialize", &json!({"format": "png", "compress": true, "marks": {"trim": true}, "svg": {"minify": true}})).unwrap();
assert_eq!(
notes(&r),
[
"`compress` was not used: PNG files don't read it",
"`marks` was not used: PNG files don't read it",
"`svg` was not used: PNG files don't read it"
],
"{r}"
);
// The note names the kind of file written, as a save's does.
let r = s.execute("document.export", &json!({"format": "ai", "pdfCompatible": false, "quality": 80})).unwrap();
assert_eq!(notes(&r), ["`quality` was not used: non-PDF-compatible .ai files don't read it"], "{r}");
let r = s.execute("document.export", &json!({"format": "pdf", "preserveEditing": false, "range": "1"})).unwrap();
assert!(notes(&r).is_empty(), "{r}");
let r = s.execute("document.export", &json!({"format": "vectorcraft", "artboard": 0})).unwrap();
assert_eq!(notes(&r), ["`artboard` was not used: VectorCraft files don't read it"], "{r}");
}
/// A legacy `.ai` file reads its own options and the artboards to write, not the other `.ai`
/// options or the PDF options.
#[test]
fn a_legacy_ai_export_notes_the_options_of_the_other_ai_files() {
let (mut s, notes) = (with_art(), unused);
let r = s.execute("document.export", &json!({"format": "ai", "aiVersion": "7", "compress": true, "marks": {"trim": true}})).unwrap();
assert_eq!(
notes(&r),
["`compress` was not used: legacy .ai (version 7) files don't read it", "`marks` was not used: legacy .ai (version 7) files don't read it"],
"{r}"
);
let r =
s.execute("document.export", &json!({"format": "ai", "aiVersion": "7", "outlineText": true, "hiddenObjects": "omit", "range": "1"})).unwrap();
assert!(notes(&r).is_empty(), "{r}");
let r = s.execute("document.export", &json!({"format": "ai", "aiVersion": "7", "useArtboards": false})).unwrap();
assert!(notes(&r).is_empty(), "{r}");
}
/// The `.ai` files other than the legacy one don't read the legacy file's own options.
#[test]
fn a_pdf_compatible_ai_export_notes_the_legacy_options() {
let (mut s, notes) = (with_art(), unused);
let unread = json!({"format": "ai", "aiVersion": "pdf", "outlineText": true, "hiddenObjects": "omit", "transparentImages": "omit"});
let r = s.execute("document.export", &unread).unwrap();
assert_eq!(
notes(&r),
[
"`hiddenObjects` was not used: PDF-compatible .ai files don't read it",
"`outlineText` was not used: PDF-compatible .ai files don't read it",
"`transparentImages` was not used: PDF-compatible .ai files don't read it"
],
"{r}"
);
}
/// `preserveEditing` is always on for a `.ai` file, so an export that gives it gets a note.
#[test]
fn an_ai_export_notes_preserve_editing() {
let (mut s, notes) = (with_art(), unused);
let r = s.execute("document.export", &json!({"format": "ai", "preserveEditing": false, "range": "1"})).unwrap();
assert_eq!(notes(&r), ["`preserveEditing` was not used: PDF-compatible .ai files don't read it"], "{r}");
}
/// An export writes one file: only a save writes each artboard to a file of its own, so an export
/// notes `separateArtboards`, and the `range` that names those files for a native file.
#[test]
fn an_export_notes_the_options_that_only_a_save_reads() {
let (mut s, notes) = (with_art(), unused);
let r = s.execute("document.export", &json!({"format": "ai", "separateArtboards": true, "range": "1"})).unwrap();
assert_eq!(notes(&r), ["`separateArtboards` was not used: PDF-compatible .ai files don't read it"], "{r}");
for (format, label) in [("vectorcraft", "VectorCraft"), ("template", "VectorCraft Template")] {
let r = s.execute("document.export", &json!({"format": format, "separateArtboards": true, "range": "1", "compress": true})).unwrap();
assert_eq!(
notes(&r),
[format!("`range` was not used: {label} files don't read it"), format!("`separateArtboards` was not used: {label} files don't read it")],
"{r}"
);
}
}
/// The legacy `.ai` options that the notes go by are the ones the `.ai` option table describes as
/// the legacy file's ("with aiVersion 7"), so an option added to the table is not noted as unread
/// on a legacy export by mistake.
#[test]
fn the_legacy_ai_options_are_the_ones_the_option_table_names() {
let described: Vec<&str> = native::AI_OPTIONS.iter().filter(|o| o.description.starts_with("with aiVersion 7")).map(|o| o.name).collect();
assert_eq!(described, legacy_ai::LEGACY_ONLY);
for key in described.iter().chain(&ARTBOARD_PARAMS).chain(&["aiVersion", "useArtboards"]) {
assert!(legacy_ai::reads(key), "{key}");
assert!(native::AI_OPTIONS.iter().any(|o| o.name == *key), "{key} is not a .ai option");
}
for key in ["compress", "pdfCompatible", "separateArtboards", "editingData", "marks"] {
assert!(!legacy_ai::reads(key), "{key}");
}
}
#[test]
fn note_texts_give_the_losses_first_each_kind_in_order() {
use super::encode::{Note, note_texts};
+64
View File
@@ -103,6 +103,70 @@ fn use_artboards_false_writes_one_page_of_the_arts_bounds() {
}
}
/// In a PDF without a standard, the warning for a page longer than 14,400 pt written with a
/// `UserUnit` above 1 names "Write pages longer than 200 in at full size in points": at PDF 1.5
/// (written as 1.6) and later, through `document.exportPdf`, `document.export`, a page of the
/// art's bounds and the Summary's export, with one such warning per page. PDF/A files and `.ai`
/// saves keep the warning without the option's name. Pages written in points (the option on, PDF
/// 1.4, PDF/X, a page too narrow for a `UserUnit` above 1) and a page too long and narrow for
/// 14,400 units have other warnings, which don't name it.
#[test]
fn a_page_with_a_user_unit_names_the_option_that_writes_it_in_points() {
use super::pdf::LONG_PAGES_IN_POINTS;
const SMALLER: &str = "so apps that ignore UserUnit show it that many times smaller";
let mut s = Session::new();
s.execute("file.new", &json!({"width": 20_000, "height": 1_000})).unwrap();
s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 19_000, "height": 500})).unwrap();
let warnings = |v: &Value| -> Vec<String> {
v["warnings"].as_array().unwrap().iter().filter_map(|w| w.as_str()).filter(|w| w.contains("UserUnit")).map(str::to_string).collect()
};
let named = |v: &Value| warnings(v).iter().any(|w| w.contains(LONG_PAGES_IN_POINTS));
for p in [
json!({"longPagesInPoints": false}),
json!({"longPagesInPoints": false, "compatibility": "1.5"}),
json!({"longPagesInPoints": false, "compatibility": "2.0"}),
json!({"longPagesInPoints": false, "useArtboards": false}),
] {
let mut q = p.clone();
q["includeDocument"] = json!(true);
for v in [export(&mut s, p.clone()), s.execute("document.export", &as_export(&p)).unwrap(), s.execute("document.pdfSettings", &q).unwrap()] {
let page: Vec<String> = warnings(&v).into_iter().filter(|w| w.starts_with("the page of artboard")).collect();
assert_eq!(page.len(), 1, "{p}: {v}");
assert!(page[0].ends_with(&format!("{SMALLER}{LONG_PAGES_IN_POINTS}")), "{p}: {page:?}");
assert_eq!(warnings(&v).iter().filter(|w| w.contains("apps that ignore UserUnit")).count(), 1, "{p}: {v}");
}
}
for p in [
json!({"longPagesInPoints": true}),
json!({"longPagesInPoints": false, "compatibility": "1.4"}),
json!({"longPagesInPoints": false, "preset": "PDF/X-4:2010"}),
] {
assert!(!named(&export(&mut s, p.clone())), "{p}");
}
for p in
[json!({"longPagesInPoints": false, "standard": "pdfA2b"}), json!({"longPagesInPoints": false, "standard": "pdfA2b", "compatibility": "1.4"})]
{
let v = export(&mut s, p.clone());
assert!(warnings(&v).iter().any(|w| w.ends_with(SMALLER)) && !named(&v), "{p}: {v}");
}
let ai = s.execute("document.export", &json!({"format": "ai", "longPagesInPoints": false})).unwrap();
assert!(warnings(&ai).iter().any(|w| w.ends_with(SMALLER)) && !named(&ai), "{ai}");
// The art's bounds are within 14,400 pt.
s.execute("select.all", &json!({})).unwrap();
s.execute("edit.clear", &json!({})).unwrap();
s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 500, "height": 500})).unwrap();
assert!(!named(&export(&mut s, json!({"longPagesInPoints": false, "useArtboards": false}))));
// A page 3 pt high keeps a UserUnit of 1, so it is written in points either way; a page
// 85,040 × 17 pt gets a UserUnit above 1 that leaves its long side past 14,400 units.
for (w, h) in [(20_000, 3), (85_040, 17)] {
let mut s = Session::new();
s.execute("file.new", &json!({"width": w, "height": h})).unwrap();
s.execute("shape.rectangle", &json!({"x": 100, "y": 0, "width": w - 1_000, "height": h})).unwrap();
let v = export(&mut s, json!({"longPagesInPoints": false}));
assert!(!named(&v), "{w} × {h}: {v}");
}
}
/// A PDF of the art's bounds carries no Preserve Editing data, through `document.exportPdf`,
/// `document.export` and the Summary's export in memory, and says so in a warning: reopened, its
/// editing data would replace the document's artboards with the one around the art. A PDF of the
+86 -29
View File
@@ -15,9 +15,8 @@ fn open(s: &mut Session, name: &str, bytes: &[u8]) -> Value {
s.execute("document.open", &json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(bytes)})).unwrap()
}
fn tmp(name: &str) -> String {
let dir = std::env::temp_dir().join(format!("vc-pdfedit-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
/// The path of `name` in the test's folder `dir`.
fn tmp(dir: &std::path::Path, name: &str) -> String {
dir.join(name).to_string_lossy().to_string()
}
@@ -114,8 +113,9 @@ fn the_legacy_payload_name_is_accepted() {
#[test]
fn ai_files_are_pdfs_that_save_and_reopen_editable() {
let scratch = vectorcraft_testkit::TempDir::new("pdfedit");
let mut s = rich();
let path = tmp("art.ai");
let path = tmp(&scratch, "art.ai");
let r = s.execute("document.save", &json!({"path": path, "preserveEditing": false, "range": "1"})).unwrap();
assert_eq!(r["path"], path.as_str());
// As saved (Save stamps the File Info dates).
@@ -134,11 +134,11 @@ fn ai_files_are_pdfs_that_save_and_reopen_editable() {
let again = vectorcraft_pdf::editing(&std::fs::read(&path).unwrap()).unwrap();
assert_eq!(vectorcraft_format::load(&again.data).unwrap().layers, s.doc().unwrap().doc.layers);
// Save As also writes a plain PDF (the document then saves back as PDF); PNG stays an export.
assert_eq!(s.execute("document.save", &json!({"path": tmp("x.pdf")})).unwrap()["format"], "pdf");
assert!(s.execute("document.save", &json!({"path": tmp("x.png")})).is_err(), "PNG is written with document.export");
assert_eq!(s.execute("document.save", &json!({"path": tmp(&scratch, "x.pdf")})).unwrap()["format"], "pdf");
assert!(s.execute("document.save", &json!({"path": tmp(&scratch, "x.png")})).is_err(), "PNG is written with document.export");
// A plain PDF named .ai opens as artwork, without a path to save over.
let plain = b64(&s.execute("document.exportPdf", &json!({"preserveEditing": false})).unwrap());
let plain_path = tmp("plain.ai");
let plain_path = tmp(&scratch, "plain.ai");
std::fs::write(&plain_path, plain).unwrap();
let r = s.execute("document.open", &json!({"path": plain_path})).unwrap();
assert_eq!(r["restored"], false);
@@ -149,9 +149,10 @@ fn ai_files_are_pdfs_that_save_and_reopen_editable() {
/// As does, leaving the document's own path alone.
#[test]
fn exports_write_ai_as_save_as_does() {
let scratch = vectorcraft_testkit::TempDir::new("pdfedit");
let mut s = rich();
let before = comparable(&s.doc().unwrap().doc);
let path = tmp("exported.ai");
let path = tmp(&scratch, "exported.ai");
let r = s.execute("document.export", &json!({"path": path})).unwrap();
assert_eq!(r["format"], "ai", "{r}");
let bytes = std::fs::read(&path).unwrap();
@@ -225,12 +226,13 @@ fn ait_templates_open_their_document_untitled() {
/// from Template opens it as an untitled copy of the document, layers and art included.
#[test]
fn save_as_template_writes_an_ait_that_new_from_template_opens_untitled() {
let scratch = vectorcraft_testkit::TempDir::new("pdfedit");
let mut s = rich();
s.execute("layer.new", &json!({"name": "Notes"})).unwrap();
s.execute("shape.ellipse", &json!({"x": 20, "y": 120, "width": 40, "height": 30})).unwrap();
let before = comparable(&s.doc().unwrap().doc);
assert_eq!(before.layers.len(), 2);
let path = tmp("brochure template.ait");
let path = tmp(&scratch, "brochure template.ait");
let r = s.execute("file.saveAsTemplate", &json!({"path": path})).unwrap();
assert_eq!(r["format"], "ait", "{r}");
let bytes = std::fs::read(&path).unwrap();
@@ -253,6 +255,7 @@ fn save_as_template_writes_an_ait_that_new_from_template_opens_untitled() {
/// writes a `.ait`.
#[test]
fn save_as_template_names_its_file_after_the_template_format() {
let scratch = vectorcraft_testkit::TempDir::new("pdfedit");
let mut s = rich();
for (name, format, saved) in [
("card.png", None, "card.vctemplate"),
@@ -261,7 +264,7 @@ fn save_as_template_names_its_file_after_the_template_format() {
("card.pdf", Some("ait"), "card.ait"),
("card v1.2", None, "card v1.2.vctemplate"),
] {
let (typed, want) = (tmp(&format!("named/{name}")), tmp(&format!("named/{saved}")));
let (typed, want) = (tmp(&scratch, &format!("named/{name}")), tmp(&scratch, &format!("named/{saved}")));
let _ = std::fs::create_dir_all(std::path::Path::new(&typed).parent().unwrap());
let _ = std::fs::remove_file(&typed);
let _ = std::fs::remove_file(&want);
@@ -273,7 +276,7 @@ fn save_as_template_names_its_file_after_the_template_format() {
assert!(ait || vectorcraft_format::load(&bytes).is_ok_and(|d| d.template), "{name}: a native template");
assert!(!std::path::Path::new(&typed).exists(), "{name}: nothing written under the typed name");
}
for (cmd, p) in [("file.saveAs", json!({"format": "ait"})), ("document.save", json!({"path": tmp("card.ait")}))] {
for (cmd, p) in [("file.saveAs", json!({"format": "ait"})), ("document.save", json!({"path": tmp(&scratch, "card.ait")}))] {
let e = s.execute(cmd, &p).unwrap_err().to_string();
assert!(e.contains("file.saveAsTemplate") && !e.contains("document.export"), "{cmd}: {e}");
}
@@ -284,8 +287,9 @@ fn save_as_template_names_its_file_after_the_template_format() {
/// nothing writes keeps its own error.
#[test]
fn exports_of_an_ait_name_save_as_template() {
let scratch = vectorcraft_testkit::TempDir::new("pdfedit");
let mut s = rich();
let path = tmp("exported.ait");
let path = tmp(&scratch, "exported.ait");
let _ = std::fs::remove_file(&path);
for (cmd, p) in [
("document.export", json!({"path": path})),
@@ -305,8 +309,9 @@ fn exports_of_an_ait_name_save_as_template() {
/// file; `aiVersion` "pdf" writes the PDF-compatible template.
#[test]
fn save_as_template_refuses_a_legacy_ait() {
let scratch = vectorcraft_testkit::TempDir::new("pdfedit");
let mut s = rich();
let path = tmp("legacy-ait/card.ait");
let path = tmp(&scratch, "legacy-ait/card.ait");
let dir = std::path::Path::new(&path).parent().unwrap().to_path_buf();
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
@@ -402,28 +407,76 @@ fn ai_export_validates_options_even_when_editing_data_is_omitted() {
}
}
#[test]
fn ai_export_without_artboards_keeps_art_outside_the_original_pages() {
/// Two artboards, a visible 30 × 20 pt rectangle outside them at (180, 100) and a hidden one.
fn art_outside_the_artboards() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 80, "artboards": 2})).unwrap();
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
s.execute("shape.rectangle", &json!({"x": 180, "y": 100, "width": 30, "height": 20})).unwrap();
s.execute("shape.rectangle", &json!({"x": 1000, "y": 1000, "width": 50, "height": 40})).unwrap();
s.execute("object.hide", &json!({})).unwrap();
s
}
/// Whether the `.ai` file `bytes` carries the editing copy of its art for other apps.
fn carries_private_data(bytes: &[u8]) -> bool {
let opts = LoadOptions { native: false, ..Default::default() };
load::load_with("a.ai", bytes, &opts).unwrap().editing_data
}
#[test]
fn an_ai_of_the_arts_bounds_carries_no_editing_data() {
let mut s = art_outside_the_artboards();
let before = comparable(&s.doc().unwrap().doc);
let r = s.execute("document.export", &json!({"format": "ai", "useArtboards": false, "range": "2"})).unwrap();
let bytes = b64(&r);
let pages = vectorcraft_pdf::import(&bytes).unwrap();
assert_eq!(pages.artboards.len(), 1);
assert_eq!((pages.artboards[0].rect.width(), pages.artboards[0].rect.height()), (30.0, 20.0));
let editing = vectorcraft_pdf::editing(&bytes).unwrap();
let exported = vectorcraft_format::load(&editing.data).unwrap();
assert_eq!(exported.artboards.len(), 1);
assert_eq!(exported.artboards[0].rect, vectorcraft_geom::Rect::new(180.0, 100.0, 210.0, 120.0));
assert_eq!(comparable(&s.doc().unwrap().doc), before);
let left_out = |v: &Value| v["warnings"].as_array().unwrap().iter().any(|w| w == super::save::AI_EDITING_NEEDS_THE_ARTBOARDS);
let scratch = vectorcraft_testkit::TempDir::new("pdfedit");
let path = tmp(&scratch, "art-bounds.ai");
for extra in [json!({}), json!({"range": "2"}), json!({"editingData": false}), json!({"path": path})] {
let mut params = json!({"format": "ai", "useArtboards": false});
params.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
let r = s.execute("document.export", &params).unwrap();
let bytes = if params.get("path").is_some() { std::fs::read(&path).unwrap() } else { b64(&r) };
// One page, the visible art's bounds, whatever range names.
let pages = vectorcraft_pdf::import(&bytes).unwrap();
assert_eq!(pages.artboards.len(), 1, "{params}");
assert_eq!((pages.artboards[0].rect.width(), pages.artboards[0].rect.height()), (30.0, 20.0), "{params}");
assert!(vectorcraft_pdf::editing(&bytes).is_none(), "{params}");
assert!(!carries_private_data(&bytes), "{params}");
assert!(left_out(&r), "{params}: {r}");
assert_eq!(comparable(&s.doc().unwrap().doc), before);
}
// The artboards keep both editing copies, without the warning.
for params in [json!({"format": "ai"}), json!({"format": "ai", "useArtboards": true})] {
let r = s.execute("document.export", &params).unwrap();
let bytes = b64(&r);
let editing = vectorcraft_pdf::editing(&bytes).expect("editing data");
assert_eq!(vectorcraft_format::load(&editing.data).unwrap().artboards.len(), 2, "{params}");
assert!(carries_private_data(&bytes), "{params}");
assert!(!left_out(&r), "{params}: {r}");
}
assert!(s.execute("document.export", &json!({"format": "ai", "useArtboards": "yes"})).is_err());
}
#[test]
fn an_ai_of_the_arts_bounds_without_pdf_is_refused() {
let mut s = art_outside_the_artboards();
let before = comparable(&s.doc().unwrap().doc);
for extra in [json!({}), json!({"editingData": false}), json!({"editingData": true})] {
for command in ["document.export", "document.serialize"] {
let mut params = json!({"format": "ai", "useArtboards": false, "pdfCompatible": false});
params.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
let e = s.execute(command, &params).unwrap_err().to_string();
assert!(e.contains(super::save::ART_PAGE_NEEDS_PDF), "{command} {params}: {e}");
assert_eq!(comparable(&s.doc().unwrap().doc), before);
}
}
// A document with no visible art is still refused for that.
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 80})).unwrap();
let e = s.execute("document.export", &json!({"format": "ai", "useArtboards": false})).unwrap_err().to_string();
assert!(e.contains("no visible art"), "{e}");
}
/// Color Halftone's Max Radius is in pixels of the raster effects resolution since document
/// version 3 (#3260). A PDF saved with Preserve Editing carries the native document, so one from
/// before that opens with the radius converted, drawing the same dots; one saved since opens as
@@ -623,6 +676,7 @@ fn editing_copy(bytes: &[u8]) -> vectorcraft_doc::Document {
/// writes the copy; the version 7 `.ai` keeps the compound path and the clipping group.
#[test]
fn transparency_clipping_and_opacity_masks_come_back_from_the_editing_copy() {
let scratch = vectorcraft_testkit::TempDir::new("pdfedit");
let mut s = see_through_session();
let before = (*s.doc().unwrap().doc).clone();
// The mask's art is one path, and it reads back as that path.
@@ -635,7 +689,7 @@ fn transparency_clipping_and_opacity_masks_come_back_from_the_editing_copy() {
assert_eq!(see_through_outline(&editing_copy(&bytes)), want, "{opts}");
}
// Each artboard in a file of its own: the first holds all the art.
let path = tmp("see-through.ai");
let path = tmp(&scratch, "see-through.ai");
let r = s.execute("document.save", &json!({"path": path, "separateArtboards": true})).unwrap();
let files: Vec<String> = r["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap().to_string()).collect();
assert_eq!(files.len(), 3, "{r}");
@@ -765,7 +819,8 @@ fn image_outline(doc: &vectorcraft_doc::Document) -> Vec<String> {
/// the linked image keeps its path and its path relative to the document's folder.
#[test]
fn images_come_back_from_the_editing_copy() {
let dir = tmp("ai-images");
let scratch = vectorcraft_testkit::TempDir::new("pdfedit");
let dir = tmp(&scratch, "ai-images");
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(format!("{dir}/art")).unwrap();
let png = |w: u32, h: u32, f: &dyn Fn(u32, u32) -> [u8; 4]| {
@@ -835,6 +890,7 @@ fn type_outline(doc: &vectorcraft_doc::Document) -> Vec<String> {
/// for other apps alone as type, with every save option that writes the copy.
#[test]
fn type_comes_back_from_the_editing_copy() {
let scratch = vectorcraft_testkit::TempDir::new("pdfedit");
let mut s = Session::new();
s.execute("file.new", &json!({"width": 300, "height": 200})).unwrap();
s.execute("text.create", &json!({"x": 20, "y": 40, "text": "Hello\nWorld", "size": 24})).unwrap();
@@ -842,7 +898,7 @@ fn type_comes_back_from_the_editing_copy() {
// The new type is selected.
s.execute("object.rotate", &json!({"angle": 30})).unwrap();
s.execute("text.create", &json!({"x": 20, "y": 120, "text": "Area type in a frame", "area": {"width": 120, "height": 60}})).unwrap();
let path = tmp("type.ai");
let path = tmp(&scratch, "type.ai");
s.execute("document.save", &json!({"path": path})).unwrap();
let before = type_outline(&s.doc().unwrap().doc);
assert_eq!(before.len(), 3, "{before:#?}");
@@ -924,6 +980,7 @@ fn gradient_session() -> Session {
/// gradient.
#[test]
fn gradients_and_patterns_come_back_from_the_editing_copy() {
let scratch = vectorcraft_testkit::TempDir::new("pdfedit");
let mut s = gradient_session();
let before = (*s.doc().unwrap().doc).clone();
let want = paint_outline(&before);
@@ -943,7 +1000,7 @@ fn gradients_and_patterns_come_back_from_the_editing_copy() {
let copy = editing_copy(&b64(&r));
assert_eq!(paint_outline(&copy), want, "{opts}");
}
let path = tmp("gradients.ai");
let path = tmp(&scratch, "gradients.ai");
let r = s.execute("document.save", &json!({"path": path, "separateArtboards": true})).unwrap();
let files: Vec<String> = r["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap().to_string()).collect();
assert_eq!(files.len(), 3, "{r}");
@@ -59,7 +59,7 @@ fn live_texts(s: &Session) -> Vec<String> {
#[test]
fn pdf_place_keeps_live_text_from_bytes_and_unlinked_paths() {
let bytes = live_text_pdf();
let dir = vectorcraft_testkit::temp_dir("pdf-place-live-text");
let dir = vectorcraft_testkit::TempDir::new("pdf-place-live-text");
let path = dir.join("text.pdf");
std::fs::write(&path, &bytes).unwrap();
for source in [json!({"name": "text.pdf", "dataBase64": vectorcraft_format::base64_encode(&bytes)}), json!({"path": path, "link": false})] {
@@ -71,7 +71,6 @@ fn pdf_place_keeps_live_text_from_bytes_and_unlinked_paths() {
assert_eq!(live_texts(&s), ["Second page"], "{r}");
assert!(!r["warnings"].to_string().contains("outlines"), "{r}");
}
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
+104
View File
@@ -0,0 +1,104 @@
//! PICT pictures through the commands: `document.open` by extension or by content, File › Place as
//! one group clipped to the picture's frame, the dialogs' filters and the format list, and files
//! that aren't pictures, or a PICT export, refused with a message.
use serde_json::json;
use vectorcraft_doc::NodeKind;
use super::*;
fn b64(bytes: &[u8]) -> String {
vectorcraft_format::base64_encode(bytes)
}
/// A version 2 PICT file of a 200 × 100 pt frame: a red rectangle and a line.
fn picture() -> Vec<u8> {
let words = |v: &[i16]| v.iter().flat_map(|x| x.to_be_bytes()).collect::<Vec<u8>>();
let mut b = vec![0; 512];
b.extend(words(&[0, 0, 0, 100, 200]));
b.extend([0x00, 0x11, 0x02, 0xFF, 0x0C, 0x00]);
b.extend(words(&[-1, 0]));
b.extend([0; 20]);
b.extend(words(&[0x1A, -1, 0, 0, 0x31, 10, 20, 50, 80, 0x20, 70, 10, 70, 190, 0xFF]));
b
}
#[test]
fn document_open_reads_a_picture() {
let mut s = Session::new();
let r = s.execute("document.open", &json!({"name": "logo.pct", "dataBase64": b64(&picture())})).unwrap();
assert_eq!((r["format"].as_str(), r["title"].as_str()), (Some("pict"), Some("logo.pct")), "{r}");
assert_eq!(r["warnings"], json!([]));
let st = s.doc().unwrap();
assert_eq!(st.doc.artboards[0].rect.size(), (200.0, 100.0).into());
let mut paths = vec![];
st.doc.walk(|n| {
if let NodeKind::Path { .. } = n.kind {
paths.push(n.clone());
}
});
assert_eq!(paths.len(), 2);
let b = paths[0].geometric_bounds().unwrap();
assert!((b.x0 - 20.0).abs() < 1e-9 && (b.width() - 60.0).abs() < 1e-9, "{b:?}");
// Opened as artwork: Save asks for a name.
assert!(st.path.is_none());
// A picture opens by its content under a name no format reads, and in each of its names.
for name in ["logo.PICT", "logo.pic", "logo.bin", "logo"] {
let r = Session::new().execute("document.open", &json!({"name": name, "dataBase64": b64(&picture())})).unwrap();
assert_eq!(r["format"].as_str(), Some("pict"), "{name}: {r}");
}
assert_eq!(detect("logo.dat", &picture()).map(|f| f.id), Some("pict"));
assert_eq!(detect("bare.dat", &picture()[512..]).map(|f| f.id), Some("pict"));
}
#[test]
fn file_place_places_a_picture_as_one_clipped_group() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap();
let p = json!({"name": "logo.pct", "dataBase64": b64(&picture()), "at": [150, 150]});
let info = s.execute("file.place.info", &p).unwrap();
assert_eq!(info["format"], "pict", "{info}");
assert!((info["width"].as_f64().unwrap() - 200.0).abs() < 1e-9, "{info}");
let r = s.execute("file.place", &p).unwrap();
assert_eq!((&r["format"], r["ids"].as_array().map(Vec::len)), (&json!("pict"), Some(1)), "{r}");
let doc = &s.doc().unwrap().doc;
let group = doc.node(vectorcraft_doc::NodeId(r["ids"][0].as_u64().unwrap())).unwrap();
assert_eq!(group.name.as_deref(), Some("logo.pct"));
let NodeKind::Group { clip: true, .. } = &group.kind else { panic!("a clipping group, got {:?}", group.kind) };
let b = group.geometric_bounds().unwrap();
assert!((b.width() - 200.0).abs() < 1e-6 && (b.height() - 100.0).abs() < 1e-6, "{b:?}");
}
#[test]
fn files_that_are_not_pictures_are_refused() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap();
let e = s.execute("document.open", &json!({"name": "old.pct", "dataBase64": b64(&[0; 600])})).expect_err("refused");
assert!(e.to_string().contains("not a PICT file"), "{e}");
assert_eq!(s.doc().unwrap().doc.artboards[0].rect.size(), (100.0, 50.0).into());
assert!(s.execute("file.place", &json!({"name": "old.pct", "dataBase64": b64(&[0; 600])})).is_err());
// Other formats' files aren't taken for pictures by their content.
// A file that starts with a PNG signature and holds a picture's version opcodes at byte 522.
let mut png = b"\x89PNG\r\n\x1a\n".to_vec();
png.extend(&picture()[8..]);
assert!(detect("x.png", &png).is_none_or(|f| f.id != "pict"));
let e = s.execute("document.export", &json!({"format": "pict"})).expect_err("refused").to_string();
assert!(e.contains("PICT files can be opened but not written"), "{e}");
}
#[test]
fn the_dialogs_and_the_format_list_name_pict() {
let exts = ["pct", "pic", "pict"];
for e in exts {
assert!(OPEN_EXTS.contains(&e) && PLACE_EXTS.contains(&e) && UNASSOCIATED_EXTS.contains(&e), "{e}");
assert_eq!(format_for_name(&format!("a.{e}")).map(|f| f.id), Some("pict"), "{e}");
}
let filter = ("PICT", &exts[..]);
assert!(open_filters().any(|f| f == filter) && place_filters().any(|f| f == filter));
let r = Session::new().execute("document.formats", &json!({})).unwrap();
let f = r["formats"].as_array().unwrap().iter().find(|f| f["id"] == "pict").unwrap().clone();
assert_eq!((f["read"].as_bool(), f["write"].as_bool(), f["raster"].as_bool()), (Some(true), Some(false), Some(false)), "{f}");
assert_eq!(f["mime"], "image/x-pict");
assert!(writable_format(None, Some("x/logo.pct")).is_err());
}
@@ -9,7 +9,7 @@ use crate::{EngineError, READ_ONLY_LOCATION, Session};
#[test]
fn readonly_error_is_typed_and_other_writers_keep_their_error() {
let dir = vectorcraft_testkit::temp_dir("save-refusal");
let dir = vectorcraft_testkit::TempDir::new("save-refusal");
let path = dir.join("Poster.vectorcraft").to_string_lossy().into_owned();
for kind in [ErrorKind::PermissionDenied, ErrorKind::ReadOnlyFilesystem, ErrorKind::StorageFull, ErrorKind::NotFound, ErrorKind::Other] {
let typed = write_save_file_with(&path, &mut |_| Err(io::Error::new(kind, "injected"))).unwrap_err();
@@ -26,7 +26,6 @@ fn readonly_error_is_typed_and_other_writers_keep_their_error() {
}
assert!(!std::path::Path::new(&path).exists());
}
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
+193 -34
View File
@@ -76,12 +76,13 @@ pub(crate) fn see_through_images(doc: &Document) -> BTreeSet<String> {
doc.images.iter().filter(|(_, b)| see_through(b)).map(|(k, _)| k.clone()).collect()
}
/// `n` shows an image of `keys` (itself or inside).
/// `n` shows an image of `keys` (itself or inside), a color-masked image's masked pixels counted as
/// what it shows.
pub(super) fn draws_image(n: &Node, keys: &BTreeSet<String>) -> bool {
!keys.is_empty()
&& n.visible
&& match &n.kind {
NodeKind::Image(im) => keys.contains(&im.key),
NodeKind::Image(im) => keys.contains(&im.key) || Document::color_mask_of(n).is_some_and(|m| m.made_for(im) && keys.contains(&m.key)),
_ => n.children().is_some_and(|ch| ch.iter().any(|c| draws_image(c, keys))),
}
}
@@ -134,6 +135,9 @@ fn touch(a: &Rect, b: &Rect) -> bool {
struct Sets {
parent: Vec<usize>,
seeded: Vec<bool>,
/// How many open boxes the sweep's boxes met.
#[cfg(test)]
meets: usize,
}
impl Sets {
@@ -179,17 +183,25 @@ impl Sets {
/// tops that knows the lowest bottom below each of its branches, so each box meets only the open
/// boxes it overlaps, not every open one (many objects stacked in a column, sharing their
/// horizontal extent, would otherwise compare every pair). An open box inside a later box of
/// its group, ending no further right, is closed early: whatever overlaps it overlaps that box.
/// Fails only when cancelled ([`vectorcraft_doc::cancel`]).
/// its group, ending no further right, is closed early, and a box inside an open box of its group,
/// ending no further right, isn't opened: whatever overlaps it overlaps that box. Fails only when
/// cancelled ([`vectorcraft_doc::cancel`]).
pub(super) fn overlapping(bounds: &[Option<Rect>]) -> Result<Vec<Vec<usize>>, Cancelled> {
Ok(sweep(bounds, None)?.groups())
}
/// [`overlapping`]'s sweep. With `see_through`, two boxes are joined only when one of them is
/// see-through, and an open box is closed early only inside a later see-through box.
/// see-through, and an open box is closed early, or a box isn't opened, only inside a see-through
/// box. The open
/// see-through boxes and the open boxes without transparency are then in trees of their own, and
/// a box without transparency meets only the see-through ones.
fn sweep(bounds: &[Option<Rect>], see_through: Option<&[bool]>) -> Result<Sets, Cancelled> {
let mut sets = Sets { parent: (0..bounds.len()).collect(), seeded: (0..bounds.len()).map(|i| see_through.is_some_and(|s| s[i])).collect() };
let joins = |a: usize, b: usize| see_through.is_none_or(|s| s[a] || s[b]);
let mut sets = Sets {
parent: (0..bounds.len()).collect(),
seeded: (0..bounds.len()).map(|i| see_through.is_some_and(|s| s[i])).collect(),
#[cfg(test)]
meets: 0,
};
let boxes: Vec<(usize, Rect)> = bounds.iter().enumerate().filter_map(|(i, b)| b.filter(finite).map(|b| (i, b))).collect();
let n = boxes.len();
// Each box's place in the tree: by top (then index).
@@ -200,9 +212,11 @@ fn sweep(bounds: &[Option<Rect>], see_through: Option<&[bool]>) -> Result<Sets,
for (pos, &k) in by_top.iter().enumerate() {
leaf[k] = pos;
}
// The lowest bottom of the open boxes below each node (−∞: none open).
// The lowest bottom of the open boxes below each node (−∞: none open), in the tree of the
// boxes without transparency (every box without `see_through`) and the see-through boxes'.
let size = n.next_power_of_two().max(1);
let mut low = vec![f64::NEG_INFINITY; 2 * size];
let mut low = [vec![f64::NEG_INFINITY; 2 * size], if see_through.is_some() { vec![f64::NEG_INFINITY; 2 * size] } else { vec![] }];
let tree = |k: usize| usize::from(see_through.is_some_and(|s| s[boxes[k].0]));
let set = |low: &mut [f64], pos: usize, v: f64| {
let mut i = pos + size;
low[i] = v;
@@ -225,43 +239,63 @@ fn sweep(bounds: &[Option<Rect>], see_through: Option<&[bool]>) -> Result<Sets,
while let Some(&c) = by_right.get(closing)
&& boxes[c].1.x1 < b.x0
{
set(&mut low, leaf[c], f64::NEG_INFINITY);
set(&mut low[tree(c)], leaf[c], f64::NEG_INFINITY);
closing += 1;
}
// The open boxes with their top at most this bottom and their bottom at least this top.
// The open boxes it joins with their top at most this bottom and their bottom at least
// this top: every one, or with `see_through` the see-through ones and, for a see-through
// box, the others too.
let shadows = see_through.is_none_or(|s| s[boxes[k].0]);
let looks: &[usize] = match see_through {
None => &[0],
Some(_) if shadows => &[0, 1],
Some(_) => &[1],
};
let below = tops.partition_point(|t| *t <= b.y1);
met.clear();
stack.clear();
stack.push((1, 0, size));
while let Some((node, lo, hi)) = stack.pop() {
work += 1;
if work.is_multiple_of(4096) {
vectorcraft_doc::cancel::check()?;
for &t in looks {
stack.clear();
stack.push((1, 0, size));
while let Some((node, lo, hi)) = stack.pop() {
work += 1;
if work.is_multiple_of(4096) {
vectorcraft_doc::cancel::check()?;
}
if lo >= below || low[t][node] < b.y0 {
continue;
}
if hi - lo == 1 {
met.push(by_top[lo]);
continue;
}
let mid = (lo + hi) / 2;
stack.push((2 * node + 1, mid, hi));
stack.push((2 * node, lo, mid));
}
if lo >= below || low[node] < b.y0 {
continue;
}
if hi - lo == 1 {
met.push(by_top[lo]);
continue;
}
let mid = (lo + hi) / 2;
stack.push((2 * node + 1, mid, hi));
stack.push((2 * node, lo, mid));
}
#[cfg(test)]
{
sets.meets += met.len();
}
// An open box it met that holds it, ending no further right, and that joins whatever it
// overlaps: whatever later overlaps this box overlaps that one and joins it, so this box
// isn't opened.
let holder = met.iter().copied().find(|&o| {
let ob = boxes[o].1;
see_through.is_none_or(|s| s[boxes[o].0]) && b.x1 <= ob.x1 && ob.y0 <= b.y0 && b.y1 <= ob.y1
});
// Whatever overlaps a box inside this one overlaps this one, and joins it when this one is
// see-through.
let shadows = see_through.is_none_or(|s| s[boxes[k].0]);
for &o in &met {
if joins(boxes[k].0, boxes[o].0) {
sets.join(boxes[k].0, boxes[o].0);
}
sets.join(boxes[k].0, boxes[o].0);
let ob = boxes[o].1;
if shadows && ob.x1 <= b.x1 && b.y0 <= ob.y0 && ob.y1 <= b.y1 {
set(&mut low, leaf[o], f64::NEG_INFINITY);
if shadows && Some(o) != holder && ob.x1 <= b.x1 && b.y0 <= ob.y0 && ob.y1 <= b.y1 {
set(&mut low[tree(o)], leaf[o], f64::NEG_INFINITY);
}
}
set(&mut low, leaf[k], b.y1);
if holder.is_none() {
set(&mut low[tree(k)], leaf[k], b.y1);
}
}
Ok(sets)
}
@@ -391,6 +425,11 @@ mod tests {
/// What [`overlapping`] gives, comparing every pair.
fn every_pair(bounds: &[Option<Rect>]) -> Vec<Vec<usize>> {
every_pair_joining(bounds, |_, _| true)
}
/// The groups of `bounds` comparing every pair, joining overlapping pairs that `joins`.
fn every_pair_joining(bounds: &[Option<Rect>], joins: impl Fn(usize, usize) -> bool) -> Vec<Vec<usize>> {
let n = bounds.len();
let mut group: Vec<usize> = (0..n).collect();
let hit = |a: &Rect, b: &Rect| a.x0 <= b.x1 && b.x0 <= a.x1 && a.y0 <= b.y1 && b.y0 <= a.y1;
@@ -400,6 +439,7 @@ mod tests {
for j in 0..n {
if let (Some(a), Some(b)) = (bounds[i], bounds[j])
&& hit(&a, &b)
&& joins(i, j)
&& group[j] < group[i]
{
group[i] = group[j];
@@ -463,6 +503,69 @@ mod tests {
assert_eq!(overlapping(&odd).unwrap(), vec![vec![0, 2], vec![1]]);
}
/// `n` boxes sharing their left and top edges, each inside the one before.
fn shrinking_nest(n: usize) -> Vec<Option<Rect>> {
(0..n).map(|i| Some(Rect::new(0.0, 0.0, 2.0 * (n - i) as f64, 2.0 * (n - i) as f64))).collect()
}
/// Each box of a nest that shrinks to the right and bottom meets only the outermost box, which
/// stays open and holds it, not every box around it.
#[test]
fn a_shrinking_nest_meets_only_its_outermost_box() {
let n = 512;
let bounds = shrinking_nest(n);
let mut sets = sweep(&bounds, None).unwrap();
assert_eq!(sets.meets, n - 1);
assert_eq!(sets.groups(), every_pair(&bounds));
assert_eq!(sets.groups(), vec![(0..n).collect::<Vec<_>>()]);
// Equal boxes: the later one isn't opened and the earlier one stays open for the third.
let same = [Some(Rect::new(0.0, 0.0, 10.0, 10.0)), Some(Rect::new(0.0, 0.0, 10.0, 10.0)), Some(Rect::new(9.0, 9.0, 20.0, 20.0))];
assert_eq!(overlapping(&same).unwrap(), vec![vec![0, 1, 2]]);
// With transparency, an opaque box isn't opened inside a see-through box, and boxes inside
// an opaque box are opened: an opaque box that overlaps only the inner one still joins it
// when that one is see-through.
let see = [true, false];
let mut sets = sweep(&bounds[..2], Some(&see)).unwrap();
assert_eq!(sets.groups(), vec![vec![0, 1]]);
let held = [Some(Rect::new(0.0, 0.0, 20.0, 20.0)), Some(Rect::new(0.0, 0.0, 10.0, 10.0)), Some(Rect::new(5.0, 5.0, 8.0, 8.0))];
let mut sets = sweep(&held, Some(&[false, true, false])).unwrap();
assert_eq!(sets.groups(), vec![vec![0, 1, 2]]);
let mut sets = sweep(&held, Some(&[true, false, false])).unwrap();
assert_eq!(sets.groups(), vec![vec![0, 1, 2]]);
let mut sets = sweep(&held, Some(&[false, false, true])).unwrap();
assert_eq!(sets.groups(), vec![vec![0, 1, 2]]);
let mut sets = sweep(&held, Some(&[false, false, false])).unwrap();
assert_eq!(sets.groups(), vec![vec![0], vec![1], vec![2]]);
}
/// Boxes nested at shared corners and placed at random, some see-through, group with and
/// without transparency as comparing every pair groups them.
#[test]
fn nested_and_scattered_boxes_group_as_comparing_every_pair() {
let mut seed = 0x51_7cc1_b727_220au64;
let mut next = |m: f64| {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
(seed % 1000) as f64 / 1000.0 * m
};
for round in 0..40 {
let n = 6 + round * 3;
let bounds: Vec<Option<Rect>> = (0..n)
.map(|_| {
// Corners on a coarse grid so that edges are often shared and boxes often nest.
let (x, y) = ((next(6.0).floor()) * 10.0, (next(6.0).floor()) * 10.0);
let (w, h) = ((next(5.0).floor() + 1.0) * 10.0, (next(5.0).floor() + 1.0) * 10.0);
Some(Rect::new(x, y, x + w, y + h))
})
.collect();
assert_eq!(overlapping(&bounds).unwrap(), every_pair(&bounds), "round {round}");
let see: Vec<bool> = (0..n).map(|_| next(1.0) < 0.3).collect();
let mut sets = sweep(&bounds, Some(&see)).unwrap();
assert_eq!(sets.groups(), every_pair_joining(&bounds, |i, j| see[i] || see[j]), "round {round}, with transparency");
}
}
/// A filled rectangle, unstroked.
fn filled(id: u64, r: Rect) -> Node {
let look = vectorcraft_doc::Appearance::basic(
@@ -582,6 +685,62 @@ mod tests {
assert_eq!(flatten_groups(&reach, &painted, &vec![false; n], 0.0).unwrap().len(), n);
}
/// A small see-through box, then `n` opaque boxes nested around it, each inside the one
/// before and sharing its left and top edges.
fn nest_around_a_see_through_box(n: usize) -> (Vec<Option<Rect>>, Vec<bool>) {
let mut bounds = vec![Some(Rect::new(0.0, 0.0, 1.0, 1.0))];
bounds.extend((0..n).map(|i| Some(Rect::new(0.0, 0.0, 2.0 * (n - i) as f64 + 1.0, 2.0 * (n - i) as f64 + 1.0))));
let mut see = vec![false; n + 1];
see[0] = true;
(bounds, see)
}
/// Opaque boxes nested in each other around a see-through box each meet only the see-through
/// box, not the open opaque boxes they can't join, and all join it.
#[test]
fn nested_opaque_boxes_meet_only_the_see_through_box() {
let n = 512;
let (bounds, see) = nest_around_a_see_through_box(n);
let mut sets = sweep(&bounds, Some(&see)).unwrap();
assert_eq!(sets.meets, n);
assert_eq!(sets.groups(), vec![(0..=n).collect::<Vec<_>>()]);
// The unfiltered sweep that runs before it meets each box once too.
let mut sets = sweep(&bounds, None).unwrap();
assert_eq!(sets.meets, n);
assert_eq!(sets.groups(), vec![(0..=n).collect::<Vec<_>>()]);
let (painted, see) = nest_around_a_see_through_box(40);
let reach: Vec<Option<Rect>> = painted.iter().map(|b| b.map(|b| b.inflate(1.0, 1.0))).collect();
for fringe in [0.0, 0.7] {
let groups = flatten_groups(&reach, &painted, &see, fringe).unwrap();
check(&reach, &painted, &see, fringe, &groups, &format!("nest, fringe {fringe}"));
assert_eq!(groups, vec![(0..=40).collect::<Vec<_>>()]);
}
}
/// An opaque box inside a later see-through box is closed: later boxes meet the see-through
/// box instead, and join the opaque one through it.
#[test]
fn a_see_through_box_closes_an_opaque_box_inside_it() {
// An opaque box, a see-through box around it, a see-through box over both and an opaque
// box over the first.
let bounds = [
Some(Rect::new(0.0, 0.0, 10.0, 10.0)),
Some(Rect::new(0.0, 0.0, 20.0, 20.0)),
Some(Rect::new(5.0, 5.0, 30.0, 30.0)),
Some(Rect::new(8.0, 8.0, 12.0, 12.0)),
];
let see = [false, true, true, false];
let mut sets = sweep(&bounds, Some(&see)).unwrap();
// The second box meets the first; the third meets the second; the fourth meets the second
// and the third.
assert_eq!(sets.meets, 4);
assert_eq!(sets.groups(), vec![vec![0, 1, 2, 3]]);
// Opaque boxes alone meet nothing.
let mut sets = sweep(&bounds, Some(&[false; 4])).unwrap();
assert_eq!(sets.meets, 0);
assert_eq!(sets.groups().len(), 4);
}
/// An opaque box between a member and its group's top that paints over the member joins, and
/// so on along a chain; one under the member stays, but for one within the fringe.
#[test]
+2 -1
View File
@@ -155,7 +155,8 @@ impl FlattenOptions {
/// the paint ([`vectorcraft_doc::ImageBlob::takes_colorize`]) never counts: it draws uncolorized.
pub(crate) fn counts_colorize(&self, d: &Document, n: &Node) -> bool {
let NodeKind::Image(im) = &n.kind else { return true };
let blob = d.image_blob(im);
let shown = d.shown_image(n, im);
let blob = d.image_blob(&shown);
if blob.is_some_and(|b| !b.takes_colorize()) {
return false;
}
+414 -40
View File
@@ -39,7 +39,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Select Text by Font",
[],
None,
"{family, style?, scope?: \"document\" (default) | {artboards: [index, …] (0-based)} | {layers: [id, …] (layers or sublayers)}} select the text objects using the font, the instances of the symbols whose art uses it, the objects painted with a pattern whose art uses it and the objects whose opacity mask uses it (in type that is not hidden or locked in that art), that are not hidden or locked, in a hidden or locked group or layer, or on a locked artboard; a pattern swatch that nothing paints, or a layer's mask, selects nothing; with scope, only those on one of the artboards (as All on Active Artboard takes them: their bounds overlap it or their center is on it) or in one of the layers → {count}",
"{family, style?, scope?: \"document\" (default) | {artboards: [index, …] (0-based)} | {layers: [id, …] (layers or sublayers)}} select the text objects using the font, the instances of the symbols whose art uses it, the text whose inline graphics draw such a symbol, the objects painted with a pattern whose art uses it (by a visible fill or stroke whose opacity is above 0, a stroke wider than 0) and the objects whose opacity mask uses it (in type that is not hidden or locked in that art), that are not hidden or locked, in a hidden or locked group or layer, or on a locked artboard; a pattern swatch that nothing paints, or a layer's mask, selects nothing; with scope, only those on one of the artboards (as All on Active Artboard takes them: their bounds overlap it or their center is on it) or in one of the layers → {count}",
has_doc,
select_font
),
@@ -108,23 +108,85 @@ fn pattern_being_edited(d: &Document, name: &str) -> bool {
d.pattern_edit.as_ref().is_some_and(|e| e.pattern == name)
}
/// Whether fill or stroke `i` paints: it is visible, its opacity is above 0 and, a stroke, it is
/// wider than 0.
fn paints(i: &AppearanceItem) -> bool {
i.visible() && i.opacity() > 0.0 && !matches!(i, AppearanceItem::Stroke(s) if s.width <= 0.0)
}
/// The name of pattern paint `p`.
fn pattern_name(p: &Paint) -> Option<&str> {
match p {
Paint::Pattern { pattern, .. } => Some(pattern.as_str()),
_ => None,
}
}
/// Whether `r` is laid out as an inline graphic: it has one and holds only its character.
fn draws_inline(r: &TextRun) -> bool {
r.inline.is_some() && vectorcraft_text::edit::is_inline_text(&r.text)
}
/// The fill and, when it is wider than 0, the stroke of the characters of `r`.
fn run_paints(r: &TextRun) -> impl Iterator<Item = &Paint> {
[Some(&r.style.fill), (r.style.stroke_width > 0.0).then_some(&r.style.stroke)].into_iter().flatten()
}
/// [`run_paints`] of run `r` of `t` when its characters draw with them. The characters of an
/// inline graphic draw no glyph: their fill and stroke paint only their underline and
/// strikethrough (not on a path or in vertical type, see `vectorcraft_text::decorations`) and the
/// ruby readings that layout draws with their run (`ruby`, as [`ruby_runs`] finds them).
fn drawn_run_paints<'a>(t: &TextObject, ruby: &HashSet<*const TextRun>, r: &'a TextRun) -> impl Iterator<Item = &'a Paint> {
let drawn = !draws_inline(r) || inline_decorated(t, ruby, r);
run_paints(r).filter(move |_| drawn)
}
/// The inline graphic runs of `t` that layout draws a ruby reading with. A reading takes the run
/// of the first base character on its line, and type on a path has no ruby. `t` is laid out only
/// when it has ruby and an inline graphic painted with a pattern.
fn ruby_runs(t: &TextObject) -> HashSet<*const TextRun> {
let patterned = |r: &TextRun| draws_inline(r) && run_paints(r).any(|p| pattern_name(p).is_some());
if t.ruby.is_empty() || !t.runs.iter().any(patterned) {
return HashSet::new();
}
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
lay.ruby.iter().filter_map(|g| t.runs.get(g.run)).filter(|r| draws_inline(r)).map(std::ptr::from_ref).collect()
}
/// Whether inline graphic run `r` of `t` has an underline or strikethrough that draws, or a ruby
/// reading that layout draws with it (it is in `ruby`).
fn inline_decorated(t: &TextObject, ruby: &HashSet<*const TextRun>, r: &TextRun) -> bool {
let bars = !t.vertical && !matches!(t.kind, TextKind::OnPath { .. });
if bars && (r.style.underline || r.style.strikethrough) {
return true;
}
ruby.contains(&std::ptr::from_ref(r))
}
/// The patterns that the fills and strokes `n` draws name (of a text object, also those of its
/// characters): visible ones, and strokes wider than 0.
fn paint_patterns(n: &Node) -> impl Iterator<Item = &str> {
let runs = match &n.kind {
NodeKind::Text(t) => t.runs.as_slice(),
_ => &[],
};
n.appearance
.items
.iter()
.filter(|i| i.visible() && !matches!(i, AppearanceItem::Stroke(s) if s.width <= 0.0))
.map(AppearanceItem::paint)
.chain(runs.iter().flat_map(|r| [Some(&r.style.fill), (r.style.stroke_width > 0.0).then_some(&r.style.stroke)]).flatten())
.filter_map(|p| match p {
Paint::Pattern { pattern, .. } => Some(pattern.as_str()),
_ => None,
})
/// characters): those that [`paints`] holds for, and the character paints of the runs that draw
/// (as [`drawn_runs`] finds them: not the overset runs of area type or type on a path) where they
/// draw (as [`drawn_run_paints`] says).
fn paint_patterns(n: &Node) -> Vec<&str> {
let mut out: Vec<&str> = n.appearance.items.iter().filter(|i| paints(i)).filter_map(|i| pattern_name(i.paint())).collect();
if let NodeKind::Text(t) = &n.kind
&& t.runs.iter().flat_map(run_paints).any(|p| pattern_name(p).is_some())
{
let ruby = ruby_runs(t);
out.extend(drawn_runs(t).0.into_iter().flat_map(|r| drawn_run_paints(t, &ruby, r)).filter_map(pattern_name));
}
out
}
/// The symbols that the inline graphics in the type of `n` draw (as [`drawn_runs`] finds them: not
/// those in the overset runs of area type or type on a path).
fn inline_symbols(n: &Node) -> Vec<&str> {
match &n.kind {
NodeKind::Text(t) if t.runs.iter().any(draws_inline) => {
drawn_runs(t).0.into_iter().filter(|r| draws_inline(r)).filter_map(|r| r.inline.as_ref().map(|art| art.symbol.as_str())).collect()
}
_ => vec![],
}
}
/// Symbols and patterns, by name: those whose art is in scope.
@@ -135,13 +197,15 @@ struct Resources {
}
impl Resources {
/// Adds what `n` itself shows: the symbol of an instance, the patterns its paints name, and
/// what the art of its opacity mask shows (not hidden or locked objects of that art).
/// Adds what `n` itself shows: the symbol of an instance, the symbols of the inline graphics in
/// its type, the patterns its paints name, and what the art of its opacity mask shows (not
/// hidden or locked objects of that art).
fn add_own(&mut self, n: &Node) {
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind {
self.symbols.insert(symbol.clone());
}
self.patterns.extend(paint_patterns(n).map(str::to_string));
self.symbols.extend(inline_symbols(n).into_iter().map(str::to_string));
self.patterns.extend(paint_patterns(n).into_iter().map(str::to_string));
if let Some(m) = n.extras().mask.as_deref() {
self.add(&m.art);
}
@@ -486,17 +550,16 @@ impl Printed<'_> {
NodeKind::Text(t) => drawn_runs(t),
_ => (vec![], false),
};
let items: Vec<&AppearanceItem> =
n.appearance.items.iter().filter(|i| i.visible() && !matches!(i, AppearanceItem::Stroke(s) if s.width <= 0.0)).collect();
let patterns: Vec<&str> = items
.iter()
.map(|i| i.paint())
.chain(runs.iter().flat_map(|r| [Some(&r.style.fill), (r.style.stroke_width > 0.0).then_some(&r.style.stroke)]).flatten())
.filter_map(|p| match p {
Paint::Pattern { pattern, .. } => Some(pattern.as_str()),
_ => None,
})
.collect();
let items: Vec<&AppearanceItem> = n.appearance.items.iter().filter(|i| paints(i)).collect();
let ruby = match &n.kind {
NodeKind::Text(t) => ruby_runs(t),
_ => HashSet::new(),
};
let run_patterns = runs.iter().flat_map(|r| match &n.kind {
NodeKind::Text(t) => Some(drawn_run_paints(t, &ruby, r)),
_ => None,
});
let patterns: Vec<&str> = items.iter().map(|i| i.paint()).chain(run_patterns.flatten()).filter_map(pattern_name).collect();
let brushed = vectorcraft_brush::has_brush(n);
if (mask.is_some() || !patterns.is_empty() || brushed) && areas.is_none_or(|a| !open || self.meets(n, a)) {
if let Some(m) = mask {
@@ -527,7 +590,7 @@ impl Printed<'_> {
for r in runs {
self.fonts.extend(run_fonts(r));
// Inline graphics draw their symbols' art.
if let Some(art) = &r.inline {
if let Some(art) = r.inline.as_ref().filter(|_| draws_inline(r)) {
self.symbol(&art.symbol);
}
}
@@ -910,14 +973,16 @@ fn replace(s: &mut Session, p: &Value) -> Result<Value> {
}
/// Whether `n` or a descendant that is not hidden or locked, nor in a hidden or locked group,
/// shows type in a font `uses` matches: text set in it, an instance of a symbol in `found`, a paint
/// naming a pattern in `found`, or such type in the art of its opacity mask.
/// shows type in a font `uses` matches: text set in it, an instance of a symbol in `found`, an
/// inline graphic of a symbol in `found`, a paint naming a pattern in `found`, or such type in the
/// art of its opacity mask.
fn reaches(n: &Node, uses: &impl Fn(&TextObject) -> bool, found: &Resources) -> bool {
n.visible
&& !n.locked
&& (matches!(&n.kind, NodeKind::Text(t) if uses(t))
|| matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if found.symbols.contains(symbol))
|| paint_patterns(n).any(|p| found.patterns.contains(p))
|| inline_symbols(n).into_iter().any(|sym| found.symbols.contains(sym))
|| paint_patterns(n).into_iter().any(|p| found.patterns.contains(p))
|| n.extras().mask.as_deref().is_some_and(|m| reaches(&m.art, uses, found))
|| n.children().is_some_and(|ch| ch.iter().any(|c| reaches(c, uses, found))))
}
@@ -964,14 +1029,16 @@ fn select_font(s: &mut Session, p: &Value) -> Result<Value> {
found.patterns.extend(patterns);
}
// The objects the Selection tool can reach that show such type: the instances of those
// symbols, the objects that those patterns paint, and the objects whose opacity mask holds it
// (not layers, which the Selection tool doesn't select).
// symbols, the text whose inline graphics draw them, the objects that those patterns paint,
// and the objects whose opacity mask holds it (not layers, which the Selection tool doesn't
// select).
let masked: HashSet<NodeId> = masked.into_iter().collect();
if !found.symbols.is_empty() || !found.patterns.is_empty() || !masked.is_empty() {
let texts: HashSet<NodeId> = hits.iter().copied().collect();
d.walk(&mut |n: &Node| {
let shows = matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if found.symbols.contains(symbol))
|| paint_patterns(n).any(|p| found.patterns.contains(p))
|| inline_symbols(n).into_iter().any(|sym| found.symbols.contains(sym))
|| paint_patterns(n).into_iter().any(|p| found.patterns.contains(p))
|| (masked.contains(&n.id) && n.extras().mask.as_deref().is_some_and(|m| reaches(&m.art, &uses, &found)));
if shows && !n.is_layer() && !texts.contains(&n.id) && editable(n.id) {
hits.push(n.id);
@@ -1076,7 +1143,9 @@ pub(crate) fn rescan(s: &mut Session, _: &Value) -> Result<Value> {
#[cfg(target_arch = "wasm32")]
let faces = 0;
// The canvas redraws type in the fonts available now (renderers lay it out again when the
// fonts change), and the bounds follow; that isn't an edit to save.
// fonts change), and the bounds follow, also of the type in opacity masks and in the art of
// symbols and patterns; that isn't an edit to save. The type in art is laid out first, and the
// inline graphics of the type on the layers then take the new bounds of their symbols' art.
for d in &mut s.docs {
let mut texts = vec![];
d.doc.walk(|n| {
@@ -1084,9 +1153,11 @@ pub(crate) fn rescan(s: &mut Session, _: &Value) -> Result<Value> {
texts.push(n.id);
}
});
if !texts.is_empty() {
if !texts.is_empty() || !art_texts_of(&d.doc).is_empty() {
d.change_unsaved(|doc| {
let doc = std::sync::Arc::make_mut(doc);
edit_art_texts_of(doc, &|_| true, &mut refresh_bounds);
doc.resolve_inline_art_with(&mut refresh_bounds);
for id in texts {
if let Some(NodeKind::Text(t)) = doc.node_mut(id).map(|n| &mut n.kind) {
refresh_bounds(t);
@@ -1751,6 +1822,309 @@ mod tests {
assert_eq!(symbol_texts(&s.doc().unwrap().doc, None)[0].0.runs[0].style.font_family, "Source Sans 3");
}
/// A pattern in a fill whose opacity is 0 paints nothing: Find doesn't select the object for
/// the pattern's type, a selection-only Change leaves that type in its font, and Print doesn't
/// count its font.
#[test]
fn find_font_skips_patterns_at_an_opacity_of_0() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
let t = s.execute("text.create", &json!({"x": 10, "y": 20, "text": "Ab", "font": "Source Serif 4"})).unwrap()["id"].as_u64().unwrap();
s.execute("object.pattern.make", &json!({"ids": [t], "name": "Dots", "edit": false})).unwrap();
s.execute("select.set", &json!({"ids": [t]})).unwrap();
s.execute("edit.clear", &json!({})).unwrap();
let painted = s.execute("shape.rectangle", &json!({"x": 0, "y": 20, "width": 50, "height": 20})).unwrap()["id"].as_u64().unwrap();
s.execute("paint.setFill", &json!({"swatch": "Dots", "ids": [painted]})).unwrap();
let printed = |s: &Session| {
let d = &s.doc().unwrap().doc;
printed_type(d, &d.layers, &[Rect::new(-1000.0, -1000.0, 1000.0, 1000.0)]).0.into_iter().map(|(family, ..)| family).collect::<Vec<_>>()
};
assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"], 1);
assert_eq!(printed(&s), ["Source Serif 4"]);
s.edit("Clear the fill", |d, _| {
for it in d.node_mut(NodeId(painted)).unwrap().appearance.items.iter_mut() {
if let AppearanceItem::Fill(f) = it {
f.opacity = 0.0;
}
}
Ok(())
})
.unwrap();
assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"], 0);
assert!(printed(&s).is_empty(), "{:?}", printed(&s));
s.execute("select.set", &json!({"ids": [painted]})).unwrap();
let r = s
.execute("text.replaceFont", &json!({"from": {"family": "Source Serif 4"}, "to": {"family": "Source Sans 3"}, "selectionOnly": true}))
.unwrap();
assert_eq!(r, json!({"runs": 0}));
assert_eq!(pattern_families(&s, "Dots"), ["Source Serif 4"]);
}
/// Characters of area type that don't fit its frame paint nothing: their pattern's type isn't
/// found through them until they are drawn.
#[test]
fn find_font_skips_patterns_of_overset_characters() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
let t = s.execute("text.create", &json!({"x": 10, "y": 20, "text": "Ab", "font": "Source Serif 4"})).unwrap()["id"].as_u64().unwrap();
s.execute("object.pattern.make", &json!({"ids": [t], "name": "Dots", "edit": false})).unwrap();
s.execute("select.set", &json!({"ids": [t]})).unwrap();
s.execute("edit.clear", &json!({})).unwrap();
let area = s
.execute(
"text.create",
&json!({"x": 10, "y": 60, "text": "A\nB", "font": "Source Sans 3", "size": 20, "area": {"width": 100, "height": 40}}),
)
.unwrap()["id"]
.as_u64()
.unwrap();
s.execute("text.setRangeStyle", &json!({"id": area, "start": 2, "end": 3, "font": "Inter"})).unwrap();
let paint_run = |s: &mut Session, letter: &'static str| {
s.edit("Paint a run with the pattern", |d, _| {
if let Some(NodeKind::Text(t)) = d.node_mut(NodeId(area)).map(|n| &mut n.kind) {
for r in t.runs.iter_mut().filter(|r| r.text.contains(letter)) {
r.style.fill = Paint::Pattern { pattern: "Dots".into(), xf: Default::default() };
}
}
Ok(())
})
.unwrap();
};
paint_run(&mut s, "B");
let laid = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), text(&s.doc().unwrap().doc, NodeId(area)).unwrap());
assert!(laid.overflow, "the second line doesn't fit the frame");
assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"], 0);
paint_run(&mut s, "A");
assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"], 1);
}
/// An inline graphic that doesn't fit its area type draws nothing, and neither does an inline
/// graphic named on a run of other characters: Find doesn't select the text for its symbol.
#[test]
fn find_font_skips_undrawn_inline_graphics() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
let t = s.execute("text.create", &json!({"x": 10, "y": 20, "text": "Ab", "font": "Source Serif 4"})).unwrap()["id"].as_u64().unwrap();
s.execute("object.pattern.make", &json!({"ids": [t], "name": "Dots", "edit": false})).unwrap();
s.execute("select.set", &json!({"ids": [t]})).unwrap();
s.execute("edit.clear", &json!({})).unwrap();
let mark = s.execute("text.create", &json!({"x": 10, "y": 20, "text": "Se", "font": "Inter"})).unwrap()["id"].clone();
s.execute("symbol.new", &json!({"name": "Mark", "ids": [mark]})).unwrap();
s.execute("edit.clear", &json!({})).unwrap();
let area = s
.execute(
"text.create",
&json!({"x": 10, "y": 60, "text": "A\nB", "font": "Source Sans 3", "size": 20, "area": {"width": 100, "height": 40}}),
)
.unwrap()["id"]
.as_u64()
.unwrap();
s.execute("text.insertInline", &json!({"id": area, "at": 3, "symbol": "Mark"})).unwrap();
let laid = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), text(&s.doc().unwrap().doc, NodeId(area)).unwrap());
assert!(laid.overflow && laid.inlines.is_empty(), "the inline graphic doesn't fit the frame");
assert_eq!(s.execute("select.font", &json!({"family": "Inter"})).unwrap()["count"], 0);
let point = s.execute("text.create", &json!({"x": 10, "y": 140, "text": "Hi", "font": "Source Sans 3"})).unwrap()["id"].as_u64().unwrap();
s.execute("text.insertInline", &json!({"id": point, "at": 0, "symbol": "Mark"})).unwrap();
assert_eq!(s.execute("select.font", &json!({"family": "Inter"})).unwrap()["count"], 1);
assert_eq!(s.doc().unwrap().selection.objects, [NodeId(point)]);
// A run that names an inline graphic but holds other characters is laid out as those
// characters: its fill paints them, and it draws no symbol.
let plain = s.execute("text.create", &json!({"x": 10, "y": 180, "text": "Ok", "font": "Source Sans 3"})).unwrap()["id"].as_u64().unwrap();
let art = text(&s.doc().unwrap().doc, NodeId(point)).unwrap().runs.iter().find_map(|r| r.inline.clone()).unwrap();
s.edit("Name an inline graphic on plain characters", |d, _| {
if let Some(NodeKind::Text(t)) = d.node_mut(NodeId(plain)).map(|n| &mut n.kind) {
for r in &mut t.runs {
r.inline = Some(art.clone());
r.style.fill = Paint::Pattern { pattern: "Dots".into(), xf: Default::default() };
}
}
Ok(())
})
.unwrap();
assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"], 1);
assert_eq!(s.doc().unwrap().selection.objects, [NodeId(plain)]);
assert_eq!(s.execute("select.font", &json!({"family": "Inter"})).unwrap()["count"], 1);
assert_eq!(s.doc().unwrap().selection.objects, [NodeId(point)]);
}
/// The characters of an inline graphic draw no glyph: their pattern fill paints only their
/// underline, strikethrough or ruby reading. Without one, Find doesn't select the text for the
/// pattern's type and Print doesn't count its font.
#[test]
fn find_font_skips_patterns_of_undecorated_inline_graphics() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
let t = s.execute("text.create", &json!({"x": 10, "y": 20, "text": "Ab", "font": "Source Serif 4"})).unwrap()["id"].as_u64().unwrap();
s.execute("object.pattern.make", &json!({"ids": [t], "name": "Dots", "edit": false})).unwrap();
s.execute("select.set", &json!({"ids": [t]})).unwrap();
s.execute("edit.clear", &json!({})).unwrap();
let mark = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone();
s.execute("symbol.new", &json!({"name": "Mark", "ids": [mark]})).unwrap();
s.execute("edit.clear", &json!({})).unwrap();
let point = s.execute("text.create", &json!({"x": 10, "y": 100, "text": "Hi", "font": "Source Sans 3"})).unwrap()["id"].as_u64().unwrap();
s.execute("text.insertInline", &json!({"id": point, "at": 1, "symbol": "Mark"})).unwrap();
let style = |s: &mut Session, f: &dyn Fn(&mut TextObject)| {
s.edit("Style the inline graphic", |d, _| {
if let Some(NodeKind::Text(t)) = d.node_mut(NodeId(point)).map(|n| &mut n.kind) {
f(t);
}
Ok(())
})
.unwrap();
};
let found = |s: &mut Session| s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"].as_u64();
let printed = |s: &Session| {
let d = &s.doc().unwrap().doc;
printed_type(d, &d.layers, &[Rect::new(-1000.0, -1000.0, 1000.0, 1000.0)]).0.into_iter().map(|(family, ..)| family).collect::<Vec<_>>()
};
style(&mut s, &|t| {
for r in t.runs.iter_mut().filter(|r| r.inline.is_some()) {
r.style.fill = Paint::Pattern { pattern: "Dots".into(), xf: Default::default() };
}
});
assert_eq!(found(&mut s), Some(0));
assert_eq!(printed(&s), ["Source Sans 3"]);
// An underline paints with the pattern.
style(&mut s, &|t| t.runs.iter_mut().filter(|r| r.inline.is_some()).for_each(|r| r.style.underline = true));
assert_eq!(found(&mut s), Some(1));
assert_eq!(printed(&s), ["Source Sans 3", "Source Serif 4"]);
// Vertical type draws no underline.
style(&mut s, &|t| t.vertical = true);
assert_eq!(found(&mut s), Some(0));
// A ruby reading that starts over the character before the inline graphic draws with that
// character's paint.
style(&mut s, &|t| {
assert!(t.runs[1].inline.is_some(), "the inline graphic is the second run");
t.ruby.push(vectorcraft_doc::RubySpan {
start: 0,
end: t.runs[0].text.len() + t.runs[1].text.len(),
text: "x".into(),
position: Default::default(),
align: Default::default(),
size_percent: 50.0,
overhang: true,
});
});
assert_eq!(found(&mut s), Some(0));
// A ruby reading that starts over the inline graphic paints with the pattern.
style(&mut s, &|t| t.ruby[0].start = t.runs[0].text.len());
assert_eq!(found(&mut s), Some(1));
}
/// Text whose inline graphic draws a symbol shows the symbol's type: Find selects that text
/// and the objects painted with a pattern whose art holds it, and a selection-only Change
/// changes the symbol's type.
#[test]
fn find_font_reaches_symbols_through_inline_graphics() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
let serif = s.execute("text.create", &json!({"x": 10, "y": 20, "text": "Se", "font": "Source Serif 4"})).unwrap()["id"].clone();
s.execute("symbol.new", &json!({"name": "Mark", "ids": [serif]})).unwrap();
s.execute("edit.clear", &json!({})).unwrap();
let inline = |s: &mut Session, y: i32| {
let id = s.execute("text.create", &json!({"x": 10, "y": y, "text": "In", "font": "Inter"})).unwrap()["id"].as_u64().unwrap();
s.execute("text.insertInline", &json!({"id": id, "at": 0, "symbol": "Mark"})).unwrap();
id
};
let listed = inline(&mut s, 60);
let tiled = inline(&mut s, 100);
s.execute("object.pattern.make", &json!({"ids": [tiled], "name": "Loop", "edit": false})).unwrap();
s.execute("select.set", &json!({"ids": [tiled]})).unwrap();
s.execute("edit.clear", &json!({})).unwrap();
let painted = s.execute("shape.rectangle", &json!({"x": 0, "y": 140, "width": 50, "height": 20})).unwrap()["id"].as_u64().unwrap();
s.execute("paint.setFill", &json!({"swatch": "Loop", "ids": [painted]})).unwrap();
let mut instances = 0;
s.doc().unwrap().doc.walk(|n| instances += usize::from(matches!(n.kind, NodeKind::SymbolInstance { .. })));
assert_eq!(instances, 0, "the symbol is drawn only by inline graphics");
assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"], 2);
let mut selected = s.doc().unwrap().selection.objects.clone();
selected.sort();
assert_eq!(selected, [NodeId(listed), NodeId(painted)]);
s.execute("select.set", &json!({"ids": [painted]})).unwrap();
let rows = font_rows(&mut s, json!({"selectionOnly": true}));
assert_eq!(rows, [("Inter".to_string(), 2, 1), ("Source Serif 4".to_string(), 1, 1)]);
let r = s
.execute("text.replaceFont", &json!({"from": {"family": "Source Serif 4"}, "to": {"family": "Source Sans 3"}, "selectionOnly": true}))
.unwrap();
assert_eq!(r, json!({"runs": 1}));
assert_eq!(symbol_texts(&s.doc().unwrap().doc, None)[0].0.runs[0].style.font_family, "Source Sans 3");
}
/// Refresh Font List lays out again the type in opacity masks and in the art of symbols and
/// patterns, as it does the type on the layers, and the inline graphics of the type on the
/// layers follow the symbols' type as laid out again.
#[test]
fn rescanning_fonts_refreshes_the_bounds_of_type_in_art() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
let owner = s.execute("shape.rectangle", &json!({"x": 0, "y": 20, "width": 50, "height": 20})).unwrap()["id"].as_u64().unwrap();
let masked = s.execute("text.create", &json!({"x": 10, "y": 20, "text": "Mask", "font": "Inter"})).unwrap()["id"].as_u64().unwrap();
mask_with(&mut s, owner, masked);
let tiled = s.execute("text.create", &json!({"x": 10, "y": 60, "text": "Tile", "font": "Inter"})).unwrap()["id"].as_u64().unwrap();
s.execute("object.pattern.make", &json!({"ids": [tiled], "name": "Dots", "edit": false})).unwrap();
s.execute("select.set", &json!({"ids": [tiled]})).unwrap();
s.execute("edit.clear", &json!({})).unwrap();
let stale = Rect::new(0.0, 0.0, 1.0, 1.0);
s.edit("Make the bounds stale", |d, _| {
edit_art_texts_of(d, &|_| true, &mut |t| t.cached_bounds = Some(stale));
Ok(())
})
.unwrap();
let bounds = |s: &Session| art_texts_of(&s.doc().unwrap().doc).iter().map(|(_, t, _)| t.cached_bounds).collect::<Vec<_>>();
assert_eq!(bounds(&s), [Some(stale), Some(stale)]);
s.execute("text.rescanFonts", &json!({})).unwrap();
let after = bounds(&s);
assert_eq!(after.len(), 2);
assert!(after.iter().all(|b| b.is_some_and(|b| b != stale && b.width() > 1.0)), "{after:?}");
let marked = s.execute("text.create", &json!({"x": 10, "y": 100, "text": "Se", "font": "Inter"})).unwrap()["id"].clone();
s.execute("symbol.new", &json!({"name": "Mark", "ids": [marked]})).unwrap();
s.execute("edit.clear", &json!({})).unwrap();
let line = s.execute("text.create", &json!({"x": 10, "y": 140, "text": "In", "font": "Inter"})).unwrap()["id"].as_u64().unwrap();
s.execute("text.insertInline", &json!({"id": line, "at": 0, "symbol": "Mark"})).unwrap();
s.edit("Make the bounds stale", |d, _| {
edit_art_texts_of(d, &|_| true, &mut |t| t.cached_bounds = Some(stale));
d.resolve_inline_art();
Ok(())
})
.unwrap();
let resolved = |s: &Session| {
let d = &s.doc().unwrap().doc;
matches!(d.inline_resolved(text(d, NodeId(line)).unwrap()), std::borrow::Cow::Borrowed(_))
};
assert!(resolved(&s), "the inline graphic took the stale bounds");
s.execute("text.rescanFonts", &json!({})).unwrap();
assert!(resolved(&s), "the inline graphic follows the symbol's type laid out again");
// So does an inline graphic in the art of another symbol.
let held = s.execute("text.create", &json!({"x": 10, "y": 180, "text": "Out", "font": "Inter"})).unwrap()["id"].as_u64().unwrap();
s.execute("text.insertInline", &json!({"id": held, "at": 0, "symbol": "Mark"})).unwrap();
s.execute("symbol.new", &json!({"name": "Outer", "ids": [held]})).unwrap();
s.execute("edit.clear", &json!({})).unwrap();
s.edit("Make the bounds stale", |d, _| {
edit_art_texts_of(d, &|_| true, &mut |t| t.cached_bounds = Some(stale));
Ok(())
})
.unwrap();
let shrunk = s.doc().unwrap().doc.symbol_art_bounds("Mark");
s.edit("Take the stale bounds", |d, _| {
edit_art_texts_of(d, &|_| true, &mut |t| {
for a in t.runs.iter_mut().filter_map(|r| r.inline.as_mut()) {
a.bounds = shrunk;
}
});
Ok(())
})
.unwrap();
let nested = |s: &Session| {
let d = &s.doc().unwrap().doc;
art_texts_of(d).iter().flat_map(|(_, t, _)| t.runs.iter().filter_map(|r| r.inline.as_ref().map(|a| a.bounds))).collect::<Vec<_>>()
};
assert_eq!(nested(&s), [shrunk]);
s.execute("text.rescanFonts", &json!({})).unwrap();
let mark = s.doc().unwrap().doc.symbol_art_bounds("Mark");
assert_ne!(mark, shrunk);
assert_eq!(nested(&s), [mark], "the inline graphic in the art of Outer follows Mark's type laid out again");
}
/// The font family of text object `id`'s first run.
fn text_family(s: &Session, id: u64) -> String {
text(&s.doc().unwrap().doc, NodeId(id)).unwrap().runs[0].style.font_family.clone()
+1 -1
View File
@@ -19,7 +19,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add Freeform Point",
[],
None,
"{at: [x,y] (document coordinates), color? (default: the gradient's colour there; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %; the radius of pure colour around the point, a fraction of half the object's larger side; default 0), line?: true (join it to the selected point: extends the line ending there, else starts one), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\"} add a point to the freeform gradient (an unplaced one keeps its automatic points first) and select it → {index}",
"{at: [x,y] (document coordinates), color? (default: the gradient's colour there; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %; the radius of pure colour around the point, a fraction of half the object's larger side; default 0), line?: true (join it to the selected point: extends the line ending there, else starts one), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\"} add a point to the freeform gradient (an unplaced one keeps its automatic points first) and select it. On a path directly in a graph series, the graph also stores the edited gradient when it is on the topmost visible fill or stroke, as for the other paint.freeform edits (docs/mcp.md); on a graph label's row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind → {index}",
has_doc,
add_point
),
+34 -10
View File
@@ -49,6 +49,10 @@
//! member with another order, and any other change to the list (items moved, or several added
//! or removed at once), takes the model's whole list of fills and strokes.
//!
//! A path directly in a graph series that takes an edit from another member (a graph's paths are
//! members only while the graph is isolated) also has what changed stored on its graph, so that
//! every path of the series takes it when the graph is drawn again (docs/mcp.md).
//!
//! Members that are hidden or locked at the time are left as they are. An edit that would take any
//! member past the canvas (beyond [`vectorcraft_doc::MAX_COORD`]) is refused whole, as one that
//! takes the selection there is. Whenever the document is put back (Undo, Redo, a cancelled drag
@@ -432,16 +436,24 @@ fn can_toggle(s: &Session) -> std::result::Result<(), String> {
let [id] = st.selection.objects.as_slice() else {
return Err(if st.selection.is_empty() { "nothing selected" } else { "select one object" }.into());
};
// A group's contents are checked when Global Edit starts: measuring them here would walk
// every object in it each time the menu or the Properties panel asks. Other objects are
// measured ([`supported`]), not reduced to their form: the Control bar asks every frame.
match st.doc.node(*id) {
Some(n) if n.extras().mask.is_none() && plain_group(n) => Ok(()),
Some(n) if supported(n) => Ok(()),
_ => Err(UNSUPPORTED.into()),
}
// The object, a group's contents included, is measured ([`supported`]), not reduced to its
// form, and the answer is kept until the document's revision moves: the Control bar asks
// every frame, and a group's walk takes time with the anchors in it.
let ok = match st.global_edit_support.get() {
Some((rev, key, ok)) if rev == st.revision && key == *id => ok,
_ => {
let ok = st.doc.node(*id).is_some_and(supported);
st.global_edit_support.set(Some((st.revision, *id, ok)));
ok
}
};
if ok { Ok(()) } else { Err(UNSUPPORTED.into()) }
}
/// [`can_toggle`]'s answer for the one selected object: the revision and the object it was found
/// for, and whether Global Edit supports it.
pub type SupportCache = std::cell::Cell<Option<(u64, NodeId, bool)>>;
fn toggle(s: &mut Session, p: &Value) -> Result<Value> {
if s.doc()?.global_edit.is_some() {
let st = s.doc_mut()?;
@@ -778,9 +790,22 @@ pub(crate) fn propagate(before: &Document, d: &mut Document, ge: &GlobalEdit, se
}
super::object::keep_compound_aligned(d, *id, Scaling::default());
}
keep_series_changes(before, d, &edited);
edited
}
/// Store on their graphs what the members `edited`, and the objects in them, took on the paths directly in a graph
/// series, for the graph's next redraw. The edited member is left to the edit's own command.
fn keep_series_changes(before: &Document, d: &mut Document, edited: &[NodeId]) {
let mut taken = vec![];
for id in edited {
if let Some(n) = d.node(*id) {
n.walk(&mut |c: &Node| taken.push(c.id));
}
}
super::appearance::capture_series_changes(before, d, &taken);
}
/// The outlines of the members of the active document's Global Edit that are not selected, hold
/// no selected object and sit inside no selected object, in their layer's colour: the canvas
/// highlights them while Global Edit is on. While it is off, with one supported object selected,
@@ -989,8 +1014,7 @@ mod tests {
continue;
}
asked += 1;
let today = n.extras().mask.is_none() && plain_group(&n) || by_form(&n);
assert_eq!(can_toggle(&s).is_ok(), today, "seed {seed}");
assert_eq!(can_toggle(&s).is_ok(), by_form(&n), "seed {seed}");
match s.execute(C, &json!({})) {
Ok(_) => {
assert!(by_form(&n), "seed {seed}");
+7 -3
View File
@@ -24,7 +24,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Gradient",
["Window", "Gradient"],
None,
"{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; diamond runs the stops from the center out to a square with a corner at the end of the vector; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual (how the colours between the stops mix: in display RGB, or perceptually (OKLab) so the steps look even; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial, conic or diamond, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), spread?: pad|repeat|reflect (linear, radial, conic and diamond: what the gradient paints past the ends of its stops: pad carries the end colors on; repeat and reflect run the stops `repeats` times along the vector (around the circle, for a conic) and on past both ends, reflect mirroring every other run; an error on a freeform gradient), repeats?: 1..100 (a whole number: how many times repeat and reflect run the stops along the vector; VectorCraft's own limit; pad keeps it unused), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial, conic and diamond: the vector turns about the center), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep and is an error for the other kinds), reverse?: bool, dither?: bool (fills only: a linear, radial, conic or diamond gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient",
"{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; diamond runs the stops from the center out to a square with a corner at the end of the vector; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (how the colours between the stops mix: in display RGB, perceptually (OKLab) so the steps look even, or around the hue wheel: hue, saturation and brightness each change evenly from one stop to the next, the hue angle falling with hue-clockwise (red, magenta, blue, cyan, green, yellow) and rising with hue-counterclockwise; two stops whose hues are less than half a color level apart keep that hue; a stop whose RGB numbers are less than half a color level apart is gray and takes the hue of the stop it mixes with, and black that stop's saturation too; these two methods are VectorCraft's own, and SVG and PDF exports draw their gradients as RGB images, CMYK and spot color stops included; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial, conic or diamond, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), spread?: pad|repeat|reflect (linear, radial, conic and diamond: what the gradient paints past the ends of its stops: pad carries the end colors on; repeat and reflect run the stops `repeats` times along the vector (around the circle, for a conic) and on past both ends, reflect mirroring every other run; an error on a freeform gradient), repeats?: 1..100 (a whole number: how many times repeat and reflect run the stops along the vector; VectorCraft's own limit; pad keeps it unused), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial, conic and diamond: the vector turns about the center), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep and is an error for the other kinds), reverse?: bool (the same ramp the other way round: the stops in reverse order, and a hue method turned the other way unless `method` is given too), dither?: bool (fills only: a linear, radial, conic or diamond gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient. On a path directly in a graph series, the graph also stores the gradient when it is on the topmost visible fill or stroke (docs/mcp.md); on a graph label's row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind",
has_doc,
edit_gradient
),
@@ -33,7 +33,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Gradient Vector",
[],
None,
"{start?: [x,y], end?: [x,y] (document coordinates; both or neither: omitted, the vector stays), aspect?: % (radial, conic and diamond: the extent's height / width across the vector, a negative one mirroring a conic's sweep and an error for the other kinds; default: kept), focal?: [x,y] (document coordinates) | null (radial: the focal point, where the first stop sits, pulled inside the extent ellipse; null centres it; default: it keeps its place in the ellipse; an error on a conic or diamond gradient), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (alias: index; omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\", index?: appearance item index (as item)} set the gradient vector, aspect ratio and focal point (solid paints become the default gradient; type objects set it on their runs, in text space)",
"{start?: [x,y], end?: [x,y] (document coordinates; both or neither: omitted, the vector stays), aspect?: % (radial, conic and diamond: the extent's height / width across the vector, a negative one mirroring a conic's sweep and an error for the other kinds; default: kept), focal?: [x,y] (document coordinates) | null (radial: the focal point, where the first stop sits, pulled inside the extent ellipse; null centres it; default: it keeps its place in the ellipse; an error on a conic or diamond gradient), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (alias: index; omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\", index?: appearance item index (as item)} set the gradient vector, aspect ratio and focal point (solid paints become the default gradient; type objects set it on their runs, in text space). On a path directly in a graph series, the graph also stores the gradient with its placement when it is on the topmost visible fill or stroke (docs/mcp.md); on a graph label's row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, with the gradient fitted to each label",
has_doc,
set_gradient_geom
),
@@ -126,7 +126,11 @@ fn parse_kind(k: &str) -> Parsed<GradientKind> {
fn method_param(p: &Value) -> Parsed<Option<GradientMethod>> {
match p.get("method") {
None | Some(Value::Null) => Ok(None),
Some(v) => v.as_str().and_then(GradientMethod::parse).map(Some).ok_or_else(|| "`method` must be classic or perceptual".into()),
Some(v) => v
.as_str()
.and_then(GradientMethod::parse)
.map(Some)
.ok_or_else(|| "`method` must be classic, perceptual, hue-clockwise or hue-counterclockwise".into()),
}
}
+1 -1
View File
@@ -215,7 +215,7 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
o.insert("stroke".into(), json!(stroke));
o.insert("kind".into(), json!(g.kind.label().to_lowercase()));
o.insert("stops".into(), stops_json(&g.stops));
o.insert("method".into(), json!(g.method.label().to_lowercase()));
o.insert("method".into(), json!(g.method.id()));
// A freeform preset takes no spread (paint.editGradient refuses one).
if g.kind != vectorcraft_color::GradientKind::Freeform {
o.insert("spread".into(), json!(g.spread.label().to_lowercase()));
+4 -2
View File
@@ -45,8 +45,10 @@ use generate::generate;
#[cfg(test)]
use series::default_series_color;
pub(crate) use series::{
capture_label_anti_alias, capture_label_paragraphs, capture_label_styles, capture_series_object_opacity, capture_series_opacity,
capture_series_paints, capture_series_top_paints, paint_targets, series_object_opacity_differs, shown_paint,
LabelTextChange, capture_label_anti_alias, capture_label_object_opacity, capture_label_paragraphs, capture_label_rows, capture_label_styles,
capture_label_text, capture_series_object_opacity, capture_series_opacity, capture_series_top_paints, is_design_art,
label_object_opacity_differs, paint_targets, series_group_marks, series_group_marks_where, series_marks_in, series_object_opacity_differs,
shown_paint,
};
#[cfg(test)]
+48 -2
View File
@@ -73,6 +73,44 @@ pub(super) fn label_anti_alias(styles: &vectorcraft_doc::LabelStyles, role: Role
kept.unwrap_or_default()
}
/// The object rows labels of `role` keep, if any.
fn kept_rows(styles: &vectorcraft_doc::LabelStyles, role: Role) -> Option<&vectorcraft_doc::LabelRows> {
match role {
Role::Value => styles.values_rows.as_ref(),
Role::Category => styles.categories_rows.as_ref(),
Role::Legend => styles.legend_rows.as_ref(),
}
}
/// Give label `n` the object rows `kept` keeps: a fill row and a stroke row for the kept paints, in their kept order and
/// place relative to the characters, and the object opacity and blend mode. An opacity read from a file is held to 0..1
/// and a weight to 0..1000 pt; one that is not a number is left out (a stroke then takes 1 pt).
fn apply_label_rows(n: &mut Node, kept: &vectorcraft_doc::LabelRows) {
use vectorcraft_doc::{AppearanceItem, FillLayer, StrokeLayer};
let rows = &kept.paint;
let unit = |o: Option<f32>| o.filter(|o| o.is_finite()).map(|o| o.clamp(0.0, 1.0));
let fill = rows.fill.as_ref().map(|paint| {
let mut f = FillLayer::new(paint.clone());
f.opacity = unit(rows.fill_opacity).unwrap_or(1.0);
f.blend = rows.fill_blend.unwrap_or_default();
AppearanceItem::Fill(f)
});
let stroke = rows.stroke.as_ref().map(|paint| {
let width = rows.stroke_width.filter(|w| w.is_finite()).map_or(1.0, |w| w.clamp(0.0, 1000.0));
let mut st = StrokeLayer::new(paint.clone(), width);
st.opacity = unit(rows.stroke_opacity).unwrap_or(1.0);
st.blend = rows.stroke_blend.unwrap_or_default();
AppearanceItem::Stroke(st)
});
let items: Vec<AppearanceItem> = if kept.stroke_under { [stroke, fill] } else { [fill, stroke] }.into_iter().flatten().collect();
let mut ap = Appearance::clone(&n.appearance);
ap.items = items;
ap.set_contents_at(usize::from(kept.below.unwrap_or(0)));
n.appearance = ap.into();
n.opacity = unit(rows.opacity).unwrap_or(1.0);
n.blend = rows.blend.unwrap_or_default();
}
/// How big labels of `role` are set: a kept style's size, else 9 pt. The labels' spacing follows it.
pub(super) fn label_size(styles: &vectorcraft_doc::LabelStyles, role: Role) -> f64 {
label_style(styles, role).size
@@ -90,7 +128,15 @@ impl Gen<'_> {
}
pub(super) fn text(&mut self, role: Role, at: Point, s: &str, justify: Justify) -> Arc<Node> {
let t = self.text_object(role, at, s, justify);
Arc::new(Node::new(self.d.alloc_id(), NodeKind::Text(Box::new(t))))
self.label_node(role, t)
}
/// Label text `t` of `role` as a node, with the object rows its kind keeps.
fn label_node(&mut self, role: Role, t: TextObject) -> Arc<Node> {
let mut n = Node::new(self.d.alloc_id(), NodeKind::Text(Box::new(t)));
if let Some(rows) = kept_rows(self.styles, role) {
apply_label_rows(&mut n, rows);
}
Arc::new(n)
}
/// Label `s` of `role` set at `at` and laid out, not yet in the document.
fn text_object(&self, role: Role, at: Point, s: &str, justify: Justify) -> TextObject {
@@ -121,7 +167,7 @@ impl Gen<'_> {
t.xf = Affine::translate((0.0, half - (first + last) / 2.0)) * t.xf;
}
}
Arc::new(Node::new(self.d.alloc_id(), NodeKind::Text(Box::new(t))))
self.label_node(role, t)
}
pub(super) fn group(&mut self, name: &str, children: Vec<Arc<Node>>) -> Arc<Node> {
let mut g = Node::group(self.d.alloc_id(), children);
+247 -38
View File
@@ -79,6 +79,11 @@ struct SeriesRef {
index: usize,
}
/// How many series groups `spec`'s graph has: a group whose index is past it (the index comes from the file) is not one.
fn series_count(spec: &GraphSpec) -> usize {
spec.rows.iter().map(Vec::len).max().unwrap_or(0).clamp(1, vectorcraft_doc::MAX_GRAPH_SERIES)
}
/// Every node in a graph's series groups (the groups too), found in one pass over the document.
/// Axes, the legend and groups whose index is past the graph's series (the index comes from the
/// file) are left out.
@@ -86,7 +91,7 @@ fn series_members(doc: &Document) -> HashMap<NodeId, SeriesRef> {
let mut out = HashMap::new();
doc.walk(|n| {
let Some(spec) = n.extras().graph.as_deref() else { return };
let count = spec.rows.iter().map(Vec::len).max().unwrap_or(0).clamp(1, vectorcraft_doc::MAX_GRAPH_SERIES);
let count = series_count(spec);
for group in n.children().into_iter().flatten() {
let Some(index) = group.extras().series_index.and_then(|i| usize::try_from(i).ok()).filter(|i| *i < count) else { continue };
let r = SeriesRef { graph: n.id, group: group.id, index };
@@ -98,6 +103,25 @@ fn series_members(doc: &Document) -> HashMap<NodeId, SeriesRef> {
out
}
/// The objects directly in a series group among `roots` and inside them, for an edit that reaches graph series marks
/// without naming them. They may include objects of groups that only look like series groups; the capture functions
/// check each one.
pub(crate) fn series_marks_in(doc: &Document, roots: &[NodeId]) -> Vec<NodeId> {
let mut out = Vec::new();
for id in roots {
if doc.parent_of(*id).and_then(|p| doc.node(p)).is_some_and(|g| g.extras().series_index.is_some()) {
out.push(*id);
}
let Some(root) = doc.node(*id) else { continue };
root.walk(&mut |n| {
if n.extras().series_index.is_some() {
out.extend(n.children().into_iter().flatten().map(|c| c.id));
}
});
}
out
}
/// Group Selection on a graph series targets its constituent marks and legend swatch, not a
/// group-level appearance which the generated art does not inherit. Other ids pass through.
pub(crate) fn paint_targets(doc: &Document, ids: &[NodeId]) -> Vec<NodeId> {
@@ -107,7 +131,7 @@ pub(crate) fn paint_targets(doc: &Document, ids: &[NodeId]) -> Vec<NodeId> {
}
let mut out = Vec::new();
for id in ids {
// The series' own marks: the art of a marker design inside it keeps the design's paint (painting it would
// The series' own marks: the art of a graph design inside it keeps the design's paint (painting it would
// last only until the graph is drawn again), so edit the design to change it.
match members.get(id) {
Some(r) if r.group == *id => {
@@ -115,7 +139,7 @@ pub(crate) fn paint_targets(doc: &Document, ids: &[NodeId]) -> Vec<NodeId> {
out.extend(group.children().into_iter().flatten().filter(|m| matches!(m.kind, NodeKind::Path { .. })).map(|m| m.id));
}
}
Some(r) if doc.parent_of(*id) != Some(r.group) => {}
Some(r) if doc.parent_of(*id) != Some(r.group) || doc.node(*id).is_some_and(|n| !matches!(n.kind, NodeKind::Path { .. })) => {}
_ => out.push(*id),
}
}
@@ -124,27 +148,49 @@ pub(crate) fn paint_targets(doc: &Document, ids: &[NodeId]) -> Vec<NodeId> {
out
}
/// Copy the paint just applied to generated series art into that series' fill or stroke. Called
/// inside the same document edit, so the visible paint and future regeneration undo together.
/// Gradients, patterns and swatch links are kept as [`Paint`], not reduced to a solid colour.
/// Returns whether a series' captured fill or stroke changed.
pub(crate) fn capture_series_paints(doc: &mut Document, ids: &[NodeId], fill: bool) -> bool {
let members = series_members(doc);
if members.is_empty() {
return false;
/// `ids` with each graph series group replaced by the paths directly inside it, as [`paint_targets`] reads a series
/// group: the graph draws its series groups again with no rows of their own. A series group with no such path, other
/// ids and the art of a graph design pass through, and the order of `ids` is kept.
pub(crate) fn series_group_marks(doc: &Document, ids: &[NodeId]) -> Vec<NodeId> {
series_group_marks_where(doc, ids, |_| true)
}
/// [`series_group_marks`] for the series groups `stands` accepts; the others pass through.
pub(crate) fn series_group_marks_where(doc: &Document, ids: &[NodeId], stands: impl Fn(&Node) -> bool) -> Vec<NodeId> {
let mut seen = std::collections::HashSet::new();
let mut out = Vec::new();
for id in ids {
match doc.node(*id) {
Some(group) if is_series_group(doc, group) && stands(group) => {
let marks: Vec<NodeId> =
group.children().into_iter().flatten().filter(|m| matches!(m.kind, NodeKind::Path { .. })).map(|m| m.id).collect();
if marks.is_empty() { out.push(*id) } else { out.extend(marks) }
}
_ => out.push(*id),
}
}
out.retain(|id| seen.insert(*id));
out
}
/// Whether `n` is a graph series group: a child of a graph with one of the graph's series indexes ([`series_members`]).
/// It is looked up through its parent, with no pass over the document: the panels call this while they draw.
fn is_series_group(doc: &Document, n: &Node) -> bool {
let Some(index) = n.extras().series_index.and_then(|i| usize::try_from(i).ok()) else { return false };
let graph = doc.parent_of(n.id).and_then(|parent| doc.node(parent)).and_then(|parent| parent.extras().graph.as_deref());
graph.is_some_and(|spec| index < series_count(spec))
}
/// Whether `id` is the art of a graph design drawn in a graph series (Object › Graph › Column or Marker): an object
/// inside a series group other than a path directly in it. The graph draws that art again from the design.
pub(crate) fn is_design_art(doc: &Document, id: NodeId) -> bool {
let Some(chain) = doc.ancestry(id) else { return false };
let Some(at) = chain.iter().position(|a| doc.node(*a).is_some_and(|n| is_series_group(doc, n))) else { return false };
match chain.len() - at {
1 => false,
2 => doc.node(id).is_some_and(|n| !matches!(n.kind, NodeKind::Path { .. })),
_ => true,
}
let captures: Vec<_> = ids
.iter()
.filter_map(|id| {
// Only a series' own marks set its paint, not the art of a marker design.
let r = members.get(id).filter(|r| doc.parent_of(*id) == Some(r.group))?;
let node = doc.node(*id)?;
let paint = node.appearance.paint_at(None, fill)?.clone();
let width = (!fill).then(|| node.appearance.stroke_width());
Some((r.graph, r.index, fill, paint, width))
})
.collect();
store_series_paints(doc, captures)
}
/// The paint of the topmost visible fill (`true`) or stroke (`false`) of `node`, and a stroke's weight (0 without paint).
@@ -159,7 +205,8 @@ pub(crate) fn shown_paint(node: &Node, fill: bool) -> (Paint, f64) {
/// Copy the paint of the topmost visible fill (`true`) or stroke (`false`), and a stroke's weight, of generated series
/// art just edited (`edited`: each object with the kind of row, later entries replacing earlier ones) into that series'
/// fill or stroke; art left without such a row keeps no paint. A series that draws Filled Lines bands stores no stroke: its
/// fill or stroke; art left without such a row keeps no paint. Gradients, patterns and swatch links are kept as
/// [`Paint`], not reduced to a solid color. A series that draws Filled Lines bands stores no stroke: its
/// bands keep their own outline. Called inside the same document edit, so both undo together. Returns whether a series'
/// captured fill or stroke changed.
pub(crate) fn capture_series_top_paints(doc: &mut Document, edited: &[(NodeId, bool)]) -> bool {
@@ -212,13 +259,35 @@ fn series_draws_bands(g: &GraphSpec, i: usize) -> bool {
}
}
/// Store each capture (graph, series index, fill or stroke, paint, stroke weight) in its series. Returns whether a
/// series' captured fill or stroke changed.
fn store_series_paints(doc: &mut Document, captures: Vec<(NodeId, usize, bool, Paint, Option<f64>)>) -> bool {
/// Each graph's stored series paints before an edit's first capture into it. A later capture can put back what an earlier
/// one changed, so an edit compares what it leaves with these ([`settle_series_paints`]).
type SeriesPaintsBefore = HashMap<NodeId, Vec<vectorcraft_doc::SeriesPaint>>;
/// What an edit gave the characters of graph label `id`, applied to a character style ([`capture_label_text`]).
pub(crate) type LabelTextChange<'a> = &'a dyn Fn(NodeId, &mut CharStyle);
/// Does any graph in `before` now store other series paints than it did before the edit's first capture? Slots the
/// captures added past the old end and left empty are removed again, so they do not count as a change.
fn settle_series_paints(doc: &mut Document, before: SeriesPaintsBefore) -> bool {
let mut changed = false;
for (graph, was) in before {
let Some(spec) = doc.node_mut(graph).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { continue };
let empty = vectorcraft_doc::SeriesPaint::default();
if spec.series_paints.get(was.len()..).is_some_and(|added| added.iter().all(|slot| *slot == empty)) {
spec.series_paints.truncate(was.len());
}
changed |= spec.series_paints != was;
}
changed
}
/// Store each capture (graph, series index, fill or stroke, paint, stroke weight) in its series. Returns whether a
/// series' captured fill or stroke differs from what the graph stored before the first capture.
fn store_series_paints(doc: &mut Document, captures: Vec<(NodeId, usize, bool, Paint, Option<f64>)>) -> bool {
let mut before = SeriesPaintsBefore::new();
for (graph, index, fill, paint, width) in captures {
let Some(spec) = doc.node_mut(graph).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { continue };
let was = spec.series_paints.clone();
before.entry(graph).or_insert_with(|| spec.series_paints.clone());
// `index` is below the graph's series count (`series_members`).
if spec.series_paints.len() <= index {
spec.series_paints.resize(index + 1, vectorcraft_doc::SeriesPaint::default());
@@ -230,9 +299,8 @@ fn store_series_paints(doc: &mut Document, captures: Vec<(NodeId, usize, bool, P
slot.stroke = Some(paint);
slot.stroke_width = width;
}
changed |= spec.series_paints != was;
}
changed
settle_series_paints(doc, before)
}
/// Copy the opacity and blend mode of the topmost visible fill (`true`) or stroke (`false`) of generated series art just
@@ -259,14 +327,14 @@ pub(crate) fn capture_series_opacity(doc: &mut Document, edited: &[(NodeId, bool
Some((r.graph, r.index, *fill, (opacity < 1.0).then_some(opacity), (blend != BlendMode::Normal).then_some(blend)))
})
.collect();
let mut changed = false;
let mut before = SeriesPaintsBefore::new();
for (graph, index, fill, kept, blend) in captures {
let Some(spec) = doc.node_mut(graph).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { continue };
// A fully opaque Normal row on a series the graph keeps nothing for leaves the graph as it is.
if kept.is_none() && blend.is_none() && spec.series_paints.len() <= index {
continue;
}
let was = spec.series_paints.clone();
before.entry(graph).or_insert_with(|| spec.series_paints.clone());
// `index` is below the graph's series count (`series_members`).
if spec.series_paints.len() <= index {
spec.series_paints.resize(index + 1, vectorcraft_doc::SeriesPaint::default());
@@ -277,32 +345,30 @@ pub(crate) fn capture_series_opacity(doc: &mut Document, edited: &[(NodeId, bool
} else {
(slot.stroke_opacity, slot.stroke_blend) = (kept, blend);
}
changed |= spec.series_paints != was;
}
changed
settle_series_paints(doc, before)
}
/// Copy the object opacity and blend mode of generated series art just edited (`edited`) into that series' object opacity
/// and blend mode. Called inside the same document edit, so both undo together. Returns whether a series' kept object
/// opacity or blend mode changed.
pub(crate) fn capture_series_object_opacity(doc: &mut Document, edited: &[NodeId]) -> bool {
let mut changed = false;
let mut before = SeriesPaintsBefore::new();
for (graph, index, opacity, blend) in object_opacity_captures(doc, edited) {
let Some(spec) = doc.node_mut(graph).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { continue };
// A fully opaque Normal object on a series the graph keeps nothing for leaves the graph as it is.
if opacity.is_none() && blend.is_none() && spec.series_paints.len() <= index {
continue;
}
let was = spec.series_paints.clone();
before.entry(graph).or_insert_with(|| spec.series_paints.clone());
// `index` is below the graph's series count (`series_members`).
if spec.series_paints.len() <= index {
spec.series_paints.resize(index + 1, vectorcraft_doc::SeriesPaint::default());
}
let Some(slot) = spec.series_paints.get_mut(index) else { continue };
(slot.opacity, slot.blend) = (opacity, blend);
changed |= spec.series_paints != was;
}
changed
settle_series_paints(doc, before)
}
/// Would [`capture_series_object_opacity`] change what the graph stores for `edited`? Reads the document without copying
@@ -472,6 +538,149 @@ pub(crate) fn capture_label_paragraphs(
Ok(changed)
}
/// The object rows graph label `n` shows ([`vectorcraft_doc::LabelRows`]): the paint, weight, opacity and blend mode of
/// its topmost visible fill and stroke row, its object opacity and blend mode, and where those rows paint. A placed
/// gradient is kept without its placement, so it fits each label it lands on. `None`: no visible row, opaque and Normal.
pub(crate) fn label_rows(n: &Node) -> Option<vectorcraft_doc::LabelRows> {
use vectorcraft_doc::AppearanceItem;
let items = &n.appearance.items;
let top = |fill: bool| items.iter().rposition(|it| it.is_fill() == fill && it.visible());
let opacity = |o: f32| (o != 1.0).then_some(o);
let blend = |b: BlendMode| (b != BlendMode::Normal).then_some(b);
let unplaced = crate::cmd::gradient::unplaced;
let mut rows = vectorcraft_doc::SeriesPaint { opacity: opacity(n.opacity), blend: blend(n.blend), ..Default::default() };
let (fill, stroke) = (top(true), top(false));
if let Some(f) = fill.and_then(|i| items.get(i)) {
(rows.fill, rows.fill_opacity, rows.fill_blend) = (Some(unplaced(f.paint())), opacity(f.opacity()), blend(f.blend()));
}
if let Some(AppearanceItem::Stroke(st)) = stroke.and_then(|i| items.get(i)) {
(rows.stroke, rows.stroke_width, rows.stroke_opacity, rows.stroke_blend) =
(Some(unplaced(&st.paint)), Some(st.width), opacity(st.opacity), blend(st.blend));
}
let contents = n.appearance.contents_at();
let below = [fill, stroke].into_iter().flatten().filter(|i| *i < contents).fold(0u8, |k, _| k + 1);
let rows = vectorcraft_doc::LabelRows {
paint: rows,
below: (below > 0).then_some(below),
stroke_under: matches!((fill, stroke), (Some(f), Some(s)) if s < f),
};
(rows != vectorcraft_doc::LabelRows::default()).then_some(rows)
}
/// Keep the object rows ([`label_rows`]) of graph labels `ids` for every label of their kind, as
/// [`capture_label_styles`] keeps a character format, even when a label already showed them: the last label of a kind
/// in the order of `ids` sets what that kind keeps. Objects other than type are left out before the graph's labels are
/// looked up. Called inside the same edit, so they undo together. Returns whether kept rows changed.
pub(crate) fn capture_label_rows(doc: &mut Document, ids: &[NodeId]) -> bool {
store_label_rows(doc, ids, false)
}
/// Keep the object opacity and blend mode of graph labels `ids` for every label of their kind, as [`capture_label_rows`]
/// keeps them, and leave the kept fill and stroke rows as they are. Returns whether what the graph keeps changed.
pub(crate) fn capture_label_object_opacity(doc: &mut Document, ids: &[NodeId]) -> bool {
store_label_rows(doc, ids, true)
}
/// Would [`capture_label_object_opacity`] change what a graph keeps for labels `ids`? Reads the document without copying
/// it.
pub(crate) fn label_object_opacity_differs(doc: &Document, ids: &[NodeId]) -> bool {
label_rows_of(doc, ids).into_iter().any(|(graph, role, rows)| {
let Some(spec) = doc.node(graph).and_then(|n| n.extras().graph.as_deref()) else { return false };
let slot = match role {
Role::Value => &spec.label_styles.values_rows,
Role::Category => &spec.label_styles.categories_rows,
Role::Legend => &spec.label_styles.legend_rows,
};
*slot != kept_label_rows(slot, rows, true)
})
}
/// [`capture_label_rows`], or with `object_only` [`capture_label_object_opacity`].
fn store_label_rows(doc: &mut Document, ids: &[NodeId], object_only: bool) -> bool {
let mut changed = false;
for (graph, role, rows) in label_rows_of(doc, ids) {
let Some(spec) = doc.node_mut(graph).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { continue };
let slot = match role {
Role::Value => &mut spec.label_styles.values_rows,
Role::Category => &mut spec.label_styles.categories_rows,
Role::Legend => &mut spec.label_styles.legend_rows,
};
let kept = kept_label_rows(slot, rows, object_only);
changed |= *slot != kept;
*slot = kept;
}
changed
}
/// What a kind keeps after a label of it shows `rows`: those rows, or with `object_only` what `slot` keeps with the
/// label's object opacity and blend mode.
fn kept_label_rows(
slot: &Option<vectorcraft_doc::LabelRows>,
rows: Option<vectorcraft_doc::LabelRows>,
object_only: bool,
) -> Option<vectorcraft_doc::LabelRows> {
if !object_only {
return rows;
}
let mut kept = slot.clone().unwrap_or_default();
let shown = rows.unwrap_or_default();
(kept.paint.opacity, kept.paint.blend) = (shown.paint.opacity, shown.paint.blend);
(kept != vectorcraft_doc::LabelRows::default()).then_some(kept)
}
/// The graph, kind and rows ([`label_rows`]) of the last label of each kind among `ids`.
fn label_rows_of(doc: &Document, ids: &[NodeId]) -> Vec<(NodeId, Role, Option<vectorcraft_doc::LabelRows>)> {
// Graph labels are type: without type among `ids`, the graph's labels are not looked up.
if !ids.iter().any(|id| doc.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Text(_)))) {
return vec![];
}
let labels = graph_labels(doc);
let mut picked: Vec<(NodeId, Role, Option<vectorcraft_doc::LabelRows>)> = vec![];
for (&(g, role), n) in ids.iter().rev().filter_map(|id| Some((labels.get(id)?, doc.node(*id)?))) {
if !picked.iter().any(|(pg, pr, _)| *pg == g && *pr == role) {
picked.push((g, role, label_rows(n)));
}
}
picked
}
/// Keep what an edit gave all of the text of graph labels `ids` for every label of their kind: `change`, when given (the
/// character attributes the edit applied to label `id`), on the kind's kept style, as [`capture_label_styles`] keeps a
/// character format, and `para`, when given, as the kind's paragraph attributes ([`capture_label_paragraphs`]).
/// Attributes the edit did not apply stay as the kind keeps them. Returns whether a kept style or set of attributes
/// changed.
pub(crate) fn capture_label_text(
doc: &mut Document,
ids: &[NodeId],
change: Option<LabelTextChange>,
para: Option<&vectorcraft_doc::ParaStyle>,
) -> Result<bool> {
if (change.is_none() && para.is_none()) || !ids.iter().any(|id| doc.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Text(_)))) {
return Ok(false);
}
// The last label of each kind sets what the kind keeps.
let labels = graph_labels(doc);
let mut last: Vec<((NodeId, Role), NodeId)> = vec![];
for id in ids.iter().rev() {
if let Some(kind) = labels.get(id).filter(|k| !last.iter().any(|(l, _)| l == *k)) {
last.push((*kind, *id));
}
}
let mut changed = false;
for id in last.iter().rev().map(|(_, id)| id) {
if let Some(change) = change {
changed |= capture_label_styles(doc, &[*id], &|st| change(*id, st));
}
if let Some(para) = para {
changed |= capture_label_paragraphs(doc, &[*id], &|p| {
*p = para.clone();
Ok(())
})?;
}
}
Ok(changed)
}
/// The graphs and kinds of label among `ids`, each once.
fn label_kinds(doc: &Document, ids: &[NodeId]) -> Vec<(NodeId, Role)> {
if ids.is_empty() {
File diff suppressed because it is too large Load Diff
+5 -7
View File
@@ -22,16 +22,14 @@ pub fn specs() -> Vec<CommandSpec> {
}
/// Inline graphics follow their symbols: after an edit of a document that has (or had) symbols,
/// resolve the inline art of every text again (only texts whose art changed are touched).
/// resolve the inline art of every text again, in the layers and in the art of symbols, graph
/// designs, pattern tiles and opacity masks, and lay out again the texts whose art changed (a
/// symbol's type before the type that shows that symbol inline).
pub(crate) fn refresh(before: &Document, d: &mut Document) {
if before.symbols.is_empty() && d.symbols.is_empty() {
return;
}
for id in d.resolve_inline_art() {
if let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) {
refresh_bounds(t);
}
}
d.resolve_inline_art_with(&mut refresh_bounds);
}
fn insert_inline(s: &mut Session, p: &Value) -> Result<Value> {
@@ -85,7 +83,7 @@ fn insert_inline(s: &mut Session, p: &Value) -> Result<Value> {
}
let caret = s.edit("Insert Inline Symbol", |d, _| {
let mut art = InlineArt { scale, baseline_shift: shift, ..InlineArt::new(symbol.clone()) };
art.bounds = d.symbol_art_bounds(&symbol);
art.bounds = d.inline_art_bounds(&symbol);
let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) else { return Err(EngineError::NoNode(id)) };
let style = edit::insertion_style(&t.runs, a, b);
let caret = edit::replace_range_styled(&mut t.runs, a, b, &[TextRun::inline(art, style)]);
+32 -11
View File
@@ -3,10 +3,14 @@
//! document links (`svgInteractivity.addFile`, `removeFile`). SVG export writes the events as
//! event attributes (`onclick="…"`) and the files as `<script xlink:href>` elements; SVG import
//! reads both back as text. The panel reads everything with `svgInteractivity.info`.
//!
//! While read roots are in force, a reply names a linked file outside them by its file name alone
//! ([`links::shown_script`]), and `removeFile` also takes that name for it.
use serde_json::{Value, json};
use vectorcraft_doc::{Document, MAX_SVG_SCRIPTS, NodeId, SVG_EVENTS};
use vectorcraft_doc::{Document, LinkInfo, MAX_SVG_SCRIPTS, NodeId, SVG_EVENTS};
use super::links::{self, LinkBase};
use super::overprint::edit_counted;
use super::{CommandSpec, Result, Session, bad, cmd, has_doc, str_param, targets};
@@ -17,7 +21,7 @@ pub fn specs() -> Vec<CommandSpec> {
"SVG Interactivity",
[],
None,
"{ids?|id?} → {ids, events: [{event, script}…] in the panel's order | null (the objects' events differ), files: [the linked JavaScript files…], eventNames: [the events the panel lists…]} the SVG Interactivity panel's values for ids or the selection",
"{ids?|id?} → {ids, events: [{event, script}…] in the panel's order | null (the objects' events differ), files: [the linked JavaScript files…; with automation read roots in force, a file outside them by its file name alone, a URL as it is], eventNames: [the events the panel lists…]} the SVG Interactivity panel's values for ids or the selection",
has_doc,
info
),
@@ -53,7 +57,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add JavaScript File",
[],
None,
"{file: path or URL (written as given, without surrounding spaces)} link a JavaScript file to the document, after the others: SVG export writes a <script xlink:href> for each linked file. A file already linked stays where it is; a document links at most 64 files → {files}",
"{file: path or URL (written as given, without surrounding spaces)} link a JavaScript file to the document, after the others: SVG export writes a <script xlink:href> for each linked file. A file already linked (the same text) stays where it is; a document links at most 64 files → {files} (as svgInteractivity.info gives them)",
has_doc,
add_file
),
@@ -62,7 +66,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Remove JavaScript File",
[],
None,
"{file} unlink a JavaScript file from the document → {files}",
"{file} unlink a JavaScript file from the document: the file linked as `file` or, with automation read roots in force, a file outside them whose file name is `file`; an error, unlinking nothing, when `file` fits more than one → {files} (as svgInteractivity.info gives them)",
has_doc,
remove_file
),
@@ -111,7 +115,8 @@ fn edit_events(s: &mut Session, p: &Value, cmd: &str, label: &str, f: impl Fn(&m
fn info(s: &mut Session, p: &Value) -> Result<Value> {
let ids = targets(s, p)?;
let d = &s.doc()?.doc;
let st = s.doc()?;
let d = &st.doc;
let lists: Vec<Vec<(String, String)>> = ids.iter().map(|id| events_of(d, *id)).collect();
let events = lists
.first()
@@ -120,7 +125,7 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({
"ids": ids.iter().map(|id| id.0).collect::<Vec<_>>(),
"events": events,
"files": d.svg_scripts,
"files": shown_files(st),
"eventNames": SVG_EVENTS,
}))
}
@@ -157,8 +162,14 @@ fn file_param(p: &Value, cmd: &str) -> Result<String> {
f.map(str::to_string).ok_or_else(|| bad(cmd, "give `file`, the JavaScript file's path or URL"))
}
/// The JavaScript files `st` links, in order, as a reply to the caller asking now may name them
/// ([`links::shown_script`]).
fn shown_files(st: &crate::DocState) -> Vec<String> {
st.doc.svg_scripts.iter().map(|f| links::shown_script(st, f).into_owned()).collect()
}
fn files(s: &Session) -> Result<Value> {
Ok(json!({ "files": s.doc()?.doc.svg_scripts }))
Ok(json!({ "files": shown_files(s.doc()?) }))
}
fn add_file(s: &mut Session, p: &Value) -> Result<Value> {
@@ -180,11 +191,21 @@ fn add_file(s: &mut Session, p: &Value) -> Result<Value> {
fn remove_file(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "svgInteractivity.removeFile";
let file = file_param(p, C)?;
if !s.doc()?.doc.svg_scripts.contains(&file) {
return Err(bad(C, format!("{file:?} isn't linked")));
}
let st = s.doc()?;
let linked = &st.doc.svg_scripts;
// A file a reply names by its file name alone is also unlinked by that name, unless the name
// also fits another linked file.
let doc_path = LinkBase::of(st).doc;
let named: Vec<&String> =
linked.iter().filter(|f| **f != file && LinkInfo::new(f.as_str()).name() == file && links::script_hidden(f, doc_path)).collect();
let stored = match (linked.contains(&file), named.as_slice()) {
(true, []) => file,
(false, [f]) => (*f).clone(),
(false, []) => return Err(bad(C, format!("{file:?} isn't linked"))),
_ => return Err(bad(C, format!("{file:?} names more than one linked JavaScript file"))),
};
s.edit("Remove JavaScript File", |d, _| {
d.svg_scripts.retain(|f| *f != file);
d.svg_scripts.retain(|f| *f != stored);
Ok(())
})?;
files(s)
+53 -14
View File
@@ -14,8 +14,8 @@ use vectorcraft_doc::{Artboard, ArtboardSide, Document, LAYER_COLORS, LayerColor
use vectorcraft_geom::{Affine, Rect};
use super::{
CommandSpec, Result, Session, bad, bool_or, check_numbers, check_switches, checked_id, checked_ids_param, cmd, color_value, f64_or, has_doc,
has_selection, ids_param, index, object_param, ok, str_param, switch_or,
CommandSpec, Result, Session, bad, bool_or, check_numbers, check_switches, checked_id, checked_ids_param, checked_node, checked_nodes_param, cmd,
color_value, f64_or, has_doc, has_selection, ids_param, index, object_param, ok, str_param, switch_or,
};
use crate::EngineError;
@@ -83,7 +83,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Layer Options…",
["Window", "Layers"],
None,
"{ids?|id? (default: the highlighted rows, else the current layer), name? (with prefs.identifyObjectsBy xmlId: a valid XML ID, stored as the object name), visible?, locked?, template?, printable?, preview?, dimImages?: 0..100|false, color?: index 0..26|\"#rrggbb\"|preset name (a hex color with an alpha part, #rrggbbaa or #rgba, is an error)} Layer Options; rows that are not layers take name, visible and locked. Template on also locks the layer and dims its images to 50% (unless given); off unlocks it and stops dimming. One undo step",
"{ids?|id? (default: the highlighted rows, else the current layer), name? (with prefs.identifyObjectsBy xmlId: a valid XML ID, stored as the object name), visible?, locked?, template?, printable?, preview?, dimImages?: 0..100|false, color?: index 0..26|\"#rrggbb\"|preset name (a hex color with an alpha part, #rrggbbaa or #rgba, is an error)} Layer Options; rows that are not layers take name, visible and locked, and `ids` may name ruler guides (their `guide.list` id), which hide or lock on their own. Template on also locks the layer and dims its images to 50% (unless given); off unlocks it and stops dimming. One undo step",
has_doc,
set_props
),
@@ -200,7 +200,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Paste Remembers Layers",
["Window", "Layers"],
None,
"{on?} (default: toggle) the document option: on, the Paste commands put objects back into the layers they were copied from (by name; a missing one is made on top), off into the current layer; one undo step when it changes (document.inspect → pasteRemembersLayers) → {on}",
"{on?} (default: toggle) the document option: on, the Paste commands put objects back into the layers or sublayers they were copied from (in that document while they are still there, else by the names of the layer and the layers around it, the topmost match first; a missing sublayer is made inside its layer, a missing top-level layer on top; a hidden or locked one is an error and nothing is pasted), off into the current layer; one undo step when it changes (document.inspect → pasteRemembersLayers) → {on}",
has_doc,
paste_remembers_layers
),
@@ -210,11 +210,16 @@ pub fn specs() -> Vec<CommandSpec> {
/// The rows a panel command acts on: `ids` or `id`, else the highlighted rows, else the current
/// layer (capped at [`MAX_ROWS`]).
pub(crate) fn rows_param(s: &Session, p: &Value, command: &str) -> Result<Vec<NodeId>> {
rows_or_guides_param(s, p, command, false)
}
/// The rows [`rows_param`] reads; given ruler guide ids are taken too when `guides`, else refused.
fn rows_or_guides_param(s: &Session, p: &Value, command: &str, guides: bool) -> Result<Vec<NodeId>> {
// Presence is explicit intent: validate every target before fallback, truncation or edits.
let mut ids = if p.get("ids").is_some() {
checked_ids_param(s, p, "ids", command)?
checked_nodes_param(s, p, "ids", command, guides)?
} else if let Some(id) = p.get("id") {
vec![checked_id(s, id, command)?]
vec![checked_node(s, id, command, guides)?]
} else {
let st = s.doc()?;
let rows = st.highlighted_rows();
@@ -637,7 +642,8 @@ fn set_props(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "layer.setProps";
let xml_id = s.prefs.identify_objects_by == "xmlId";
check_options(C, p, xml_id)?;
let ids = rows_param(s, p, C)?;
// A ruler guide's row takes visible and locked: its own eye and lock.
let ids = rows_or_guides_param(s, p, C, true)?;
if ids.is_empty() {
return Err(bad(C, "no rows"));
}
@@ -988,20 +994,53 @@ fn artboard_delete(s: &mut Session, p: &Value) -> Result<Value> {
ok()
}
/// Delete artboards `indices` (sorted) of `d` with their guides; at least one must be left.
fn remove_artboards(d: &mut Document, sel: &mut vectorcraft_doc::Selection, indices: &[usize]) -> Result<()> {
/// Delete artboards `indices` (sorted, each once) of `d` with their guides; at least one must be
/// left. The other artboards keep their order, no later artboard takes a deleted one's id, and
/// `sel` forgets the deleted guides. One walk over the artboards and one over the ruler guides,
/// however many go. Delete Artboard, Delete Empty Artboards, Cut Artboard and Artwork Cleanup's
/// Empty Artboards.
pub(crate) fn remove_artboards(d: &mut Document, sel: &mut vectorcraft_doc::Selection, indices: &[usize]) -> Result<()> {
if indices.iter().any(|i| *i >= d.artboards.len()) {
return Err(EngineError::Other("no such artboard".into()));
}
if indices.len() >= d.artboards.len() {
return Err(EngineError::Other("a document needs at least one artboard".into()));
}
// The last first, so the others keep their places; their guides go with them.
for &i in indices.iter().rev() {
let id = d.artboards.remove(i).id;
d.retire_artboard_id(id);
d.retain_guides(sel, |g| g.artboard != Some(id));
if indices.is_empty() {
return Ok(());
}
let mut gone: HashSet<u32> = HashSet::with_capacity(indices.len());
let mut i = 0;
d.artboards.retain(|a| {
let keep = indices.binary_search(&i).is_err();
i += 1;
if !keep {
gone.insert(a.id);
}
keep
});
count_artboard_pass();
for &id in &gone {
d.retire_artboard_id(id);
}
d.retain_guides(sel, |g| !g.artboard.is_some_and(|a| gone.contains(&a)));
count_artboard_pass();
Ok(())
}
#[cfg(test)]
thread_local! {
/// Tests: how many walks [`remove_artboards`] made over the artboards and the ruler guides on
/// this thread.
pub(crate) static ARTBOARD_PASSES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// Tests: count one walk over the artboards or the ruler guides.
fn count_artboard_pass() {
#[cfg(test)]
ARTBOARD_PASSES.set(ARTBOARD_PASSES.get() + 1);
}
/// The artboards Delete Empty Artboards deletes: those with no artwork
/// ([`Document::artboard_has_art`]) that aren't locked, but artboard 1 when every artboard is one
/// of them (a document keeps one, as Delete Artboards keeps artboard 1).
+158 -2
View File
@@ -346,6 +346,36 @@ impl Library {
}
}
/// Name item `r` `name`, in its place in its kind's list; an item keyed by its name keeps its
/// group under the new name (a graphic is keyed by its id, which stays).
fn rename_item(&mut self, r: &ItemRef, name: &str) {
fn set<'a>(mut names: impl Iterator<Item = &'a mut String>, from: &str, to: &str) {
if let Some(n) = names.find(|n| n.as_str() == from) {
*n = to.to_string();
}
}
let from = r.item.as_str();
match r.kind {
ItemKind::Color => set(self.colors.iter_mut().map(|c| &mut c.name), from, name),
ItemKind::Gradient => set(self.gradients.iter_mut().map(|g| &mut g.name), from, name),
ItemKind::Pattern => set(self.patterns.iter_mut().map(|p| &mut p.name), from, name),
ItemKind::CharStyle => set(self.char_styles.iter_mut().map(|t| &mut t.name), from, name),
ItemKind::ParaStyle => set(self.para_styles.iter_mut().map(|t| &mut t.name), from, name),
ItemKind::Graphic => {
if let Some(g) = self.graphics.iter_mut().find(|g| g.id == from) {
g.name = name.to_string();
}
return;
}
ItemKind::Unknown => return,
}
for x in self.groups.iter_mut().flat_map(|g| g.items.iter_mut()) {
if x == r {
x.item = name.to_string();
}
}
}
/// Move item `r` next to `to`, an item of its kind: just before it, or just after it when
/// `after`, in their kind's list (the order the panel shows them in).
fn place_next_to(&mut self, r: &ItemRef, to: &ItemRef, after: bool) {
@@ -683,7 +713,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Use Library Item",
[],
None,
"{library?, kind, item: name (graphic: id or name), center?: [x, y] (graphic; default: the first artboard's centre), to?: fill|stroke (colors, gradients, patterns; default: the kind's), recorded?: the item as it was when used (recorded in the journal so a replay matches)} graphic: place a copy centred on `center`, its resources pasted along, selected, one undo step; colors and gradients: paint the selection (and the defaults) as paint.setFill/paint.setStroke, a gradient fitting each object; a spot color links to the document's spot swatch of its ink's name, added when the document has none of that colour (a name taken by another colour gets a number), one undo step; patterns: add the pattern and its swatch to the document (a name the document gives another pattern gets a number; the same pattern is reused) and paint the selection (and the defaults) with it, one undo step; charStyle/paraStyle: add the style to the document (a name taken by different attributes gets a number) and apply it to the selected text, one undo step → {kind, ids?, style?}",
"{library?, kind, item: name (graphic: id or name), center?: [x, y] (graphic; default: the first artboard's centre), to?: fill|stroke (colors, gradients, patterns; default: the kind's), recorded?: the item as it was when used (recorded in the journal so a replay matches)} graphic: place a copy centred on `center`, its resources pasted along, selected, one undo step; colors and gradients: paint the selection (and the defaults) as paint.setFill/paint.setStroke, a gradient fitting each object; a spot color links to the document's spot swatch of its ink's name, added when the document has none of that colour (a name taken by another colour gets a number), one undo step; patterns: add the pattern and its swatch to the document (a name the document gives another pattern gets a number; the same pattern is reused) and paint the selection (and the defaults) with it, one undo step; charStyle/paraStyle: add the style to the document (a name taken by different attributes gets a number; a character style's color linked to a swatch that isn't a global or spot swatch of the document keeps the color it shows, unlinked) and apply it to the selected text, one undo step → {kind, ids?, style?}",
has_doc,
use_item
),
@@ -696,6 +726,24 @@ pub fn specs() -> Vec<CommandSpec> {
always,
remove_item
),
cmd!(
"library.renameItem",
"Rename Library Item",
[],
None,
"{library?, kind, item: name (graphic: id or name), name: string (trimmed; 1 to 256 characters)} rename an item; it keeps its place and its group; another item of its kind with that name is an error, and its own name changes nothing; not undoable → {library, kind, item: its key now (graphic: its id), name}",
always,
rename_item
),
cmd!(
"library.addToCharacterStyles",
"Add to Character Styles",
[],
None,
"{library?, item: a character style's name, recorded?: the style as it was when added (recorded in the journal so a replay matches)} add a library character style to the document's character styles without applying it (no text needs to be selected): a document style of that name with the same attributes is reused, a name taken by different attributes gets a number; a color linked to a swatch that isn't a global or spot swatch of the document keeps the color it shows, unlinked; a new style is one undo step, a reused one none → {style: its name in the document, existing: bool}",
has_doc,
add_to_char_styles
),
cmd!(
"library.createGroup",
"New Library Group",
@@ -1231,8 +1279,13 @@ fn use_item(s: &mut Session, p: &Value) -> Result<Value> {
Kind::CharStyle | Kind::ParaStyle => {
let para = kind == Kind::ParaStyle;
let name = data.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()).unwrap_or("Style").to_string();
let attrs = data.get("attrs").and_then(Value::as_object).cloned().unwrap_or_default();
let mut attrs = data.get("attrs").and_then(Value::as_object).cloned().unwrap_or_default();
let doc = &s.doc()?.doc;
if !para {
unlink_missing_swatches(doc, &mut attrs);
}
// Compared in the form the document stores them in.
let attrs = super::textstyles::stored_style_attrs(doc, para, &attrs).unwrap_or(attrs);
// The document's style of that name when it is the same; else a new one.
let same = super::textstyles::style_attrs(doc, para, &name).is_some_and(|a| a == attrs);
let style = if same { name } else { unique(&name, |n| super::textstyles::style_attrs(doc, para, n).is_some()) };
@@ -1361,6 +1414,109 @@ fn remove_item(s: &mut Session, p: &Value) -> Result<Value> {
ok()
}
fn rename_item(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "library.renameItem";
let (id, kind, item) = item_param(s, p, C)?;
let name = match p.get("name") {
None | Some(Value::Null) => return Err(bad(C, "missing `name`")),
Some(Value::String(n)) => n.trim().to_string(),
Some(_) => return Err(bad(C, "`name` must be a string")),
};
if name.is_empty() {
return Err(bad(C, "missing `name`"));
}
if name.chars().count() > MAX_NAME {
let (label, max) = ("`name`", MAX_NAME);
return Err(bad(C, format!("{label} must be at most {max} characters")));
}
let lib = s.libraries.get(&id).ok_or_else(|| bad(C, format!("no library `{id}`")))?;
let r = lib.item_ref(kind.item_kind(), item).ok_or_else(|| bad(C, format!("the library has no item `{item}`")))?;
// The item's name now, and whether another item of its kind has the new one.
let mut same = false;
let mut taken = false;
for (_, key, shown) in lib.items().filter(|(k, ..)| *k == r.kind) {
if key == r.item {
same = shown == name;
} else if shown == name {
taken = true;
}
}
let key = if r.kind == ItemKind::Graphic { r.item.clone() } else { name.clone() };
let out = json!({ "library": id, "kind": str_param(p, "kind"), "item": key, "name": name });
if same {
return Ok(out);
}
if taken {
return Err(bad(C, format!("the library has another item of that kind named `{name}`")));
}
s.libraries.change(&id, |lib| {
lib.rename_item(&r, &name);
Ok(())
})?;
Ok(out)
}
fn add_to_char_styles(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "library.addToCharacterStyles";
// A replay (the journal) carries what the style was, so it doesn't depend on the library.
let data = match p.get("recorded").cloned() {
Some(r) => r,
None => {
let id = library_id(s, p, C)?;
let item = str_param(p, "item").ok_or_else(|| bad(C, "missing `item`"))?;
let lib = s.libraries.get(&id).ok_or_else(|| bad(C, format!("no library `{id}`")))?;
let t = lib.char_styles.iter().find(|t| t.name == item).ok_or_else(|| bad(C, format!("the library has no item `{item}`")))?;
let data = json!({ "name": t.name, "attrs": t.attrs });
s.note_journal("recorded", data.clone());
data
}
};
let name = data.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()).unwrap_or("Style").to_string();
let mut attrs = data.get("attrs").and_then(Value::as_object).cloned().ok_or_else(|| bad(C, "the library item is damaged"))?;
let doc = &s.doc()?.doc;
unlink_missing_swatches(doc, &mut attrs);
// Compared in the form the document stores them in.
let attrs = super::textstyles::stored_style_attrs(doc, false, &attrs).unwrap_or(attrs);
// The document's style of that name when it is the same; else a new one, which isn't applied.
if super::textstyles::style_attrs(doc, false, &name).is_some_and(|a| a == attrs) {
return Ok(json!({ "style": name, "existing": true }));
}
let style = unique(&name, |n| super::textstyles::style_attrs(doc, false, n).is_some());
s.execute("charStyle.new", &json!({ "name": style, "attrs": attrs }))?;
Ok(json!({ "style": style, "existing": false }))
}
/// Unlink a library character style's `fill` and `stroke` colors (solid, and each gradient stop)
/// from swatches that are not global or spot swatches of `doc`: an unlinked color keeps the color
/// it shows at full tint, as [`clean_gradient`] keeps a library gradient's stops. A link to a
/// global or spot swatch `doc` has stays, and takes that swatch's color.
fn unlink_missing_swatches(doc: &vectorcraft_doc::Document, attrs: &mut Map<String, Value>) {
let keep = |name: &str| doc.global_color(name).is_some();
for key in ["fill", "stroke"] {
let Some(mut paint) = attrs.get(key).and_then(|v| serde_json::from_value::<Paint>(v.clone()).ok()) else { continue };
let mut changed = false;
let mut unlink = |swatch: &mut Option<String>, tint: &mut f32| {
if swatch.as_deref().is_some_and(|n| !keep(n)) {
*swatch = None;
*tint = 1.0;
changed = true;
}
};
match &mut paint {
Paint::Solid { swatch, tint, .. } => unlink(swatch, tint),
Paint::Gradient(g) => {
for st in &mut g.gradient.stops {
unlink(&mut st.swatch, &mut st.tint);
}
}
_ => {}
}
if changed && let Ok(v) = serde_json::to_value(&paint) {
attrs.insert(key.to_string(), v);
}
}
}
/// `p`'s `name`, trimmed and clipped, else `default`.
fn name_param(p: &Value, default: &str) -> String {
let mut name = str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()).unwrap_or(default).to_string();
+9 -3
View File
@@ -13,7 +13,7 @@ use serde_json::{Value, json};
use vectorcraft_doc::NodeKind;
use super::findfiles::{self, Limits, Visitor};
use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, bool_or, checked_ids_param, cmd};
use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, bool_or, cmd, ids_param};
/// The most linked files one search looks for.
const MAX_LINKS: usize = 1_000;
@@ -143,8 +143,14 @@ fn find(s: &mut Session, p: &Value) -> Result<Value> {
let ids = match p.get("ids") {
None | Some(Value::Null) => None,
Some(_) => {
let ids = checked_ids_param(s, p, "ids", C)?;
let linkable = |id: &NodeId| matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::Image(_) | NodeKind::PlacedDocument(_)));
// Images and placed documents in opacity-mask art and in the art of symbols, graph
// designs and patterns are named by their ids too (`links.list`).
let ids = ids_param(p, "ids", C)?.unwrap_or_default();
let kind = |id: &NodeId| st.doc.stored_node(*id).map(|(n, _)| &n.kind);
if let Some(value) = ids.iter().find(|id| kind(id).is_none()).map(|id| id.0) {
return Err(bad(C, format!("no such object id {value}")));
}
let linkable = |id: &NodeId| matches!(kind(id), Some(NodeKind::Image(_) | NodeKind::PlacedDocument(_)));
if let Some(id) = ids.iter().find(|id| !linkable(id)) {
return Err(bad(C, format!("object {} is not an image or a linked file", id.0)));
}
File diff suppressed because it is too large Load Diff
+7 -7
View File
@@ -172,7 +172,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Make with Top Object",
["Object", "Envelope Distort"],
Some("Cmd+Alt+C"),
"{ids?} the topmost selected path becomes the envelope of the others: its outline splits into four sides at its corners, and each piece of a side takes a share of the content in proportion to its control polygon's length (type maps from its glyph outline bounds) → {id}",
"{ids?} the topmost selected path becomes the envelope of the others: its outline splits into four sides at its corners, and each piece of a side takes a share of the content in proportion to its control polygon's length, and a side whose pieces are all one curve split at anchors follows that curve's parameter (type maps from its glyph outline bounds) → {id}",
has_multi,
env_make_top
),
@@ -244,7 +244,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Move Envelope Mesh Point",
[],
None,
"{id, index, x, y, handle?: 0 right|1 left|2 down|3 up} move a point of a mesh envelope (its handles follow), or with `handle` place that handle end at (x, y); object.mesh.movePoint, addLine and deletePoint edit mesh envelopes too",
"{id, index, x, y, handle?: 0 right|1 left|2 down|3 up} move a point of a mesh or warp envelope (its handles follow), or with `handle` place that handle end at (x, y); a warp's points are those of its grid (4×4 patches, or 8×8 or 16×16 where 4×4 draws more than 0.1% of its diagonal away from the warp), and its first edit makes it a mesh envelope on that grid in the same undo step (a warp no such grid follows is refused: Reset with Mesh first); object.mesh.movePoint, movePoints, addLine and deletePoint edit mesh and warp envelopes too",
has_doc,
env_set_mesh_point
),
@@ -263,7 +263,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Set Mesh Point Color",
[],
None,
"{id, index | points: [index…] | items: [{id, index | points}…], color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1} colour and/or opacity of gradient mesh points (one undo step; an index out of range changes nothing)",
"{id, index | points: [index…] | items: [{id, index | points}…], color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1} colour and/or opacity of gradient mesh points (one undo step; an index out of range changes nothing, and so does a call that changes no point, with no undo step)",
has_doc,
mesh_set_color
),
@@ -272,7 +272,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Move Mesh Point",
[],
None,
"{id, index, x, y, handle?: 0 right|1 left|2 down|3 up} move a point of a gradient mesh or mesh envelope (its handles follow), or with `handle` place that handle end at (x, y)",
"{id, index, x, y, handle?: 0 right|1 left|2 down|3 up} move a point of a gradient mesh or a mesh or warp envelope (its handles follow; a warp becomes a mesh envelope, see object.envelope.setMeshPoint), or with `handle` place that handle end at (x, y)",
has_doc,
mesh_move_point
),
@@ -281,7 +281,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Move Mesh Points",
[],
None,
"{id, points: [index…] | items: [{id, index | points}…], dx, dy} move points of gradient meshes or mesh envelopes by (dx, dy), their handles with them (one undo step; an index out of range changes nothing)",
"{id, points: [index…] | items: [{id, index | points}…], dx, dy} move points of gradient meshes or mesh or warp envelopes by (dx, dy), their handles with them (warps become mesh envelopes, see object.envelope.setMeshPoint; one undo step; an index out of range changes nothing, and so does a call that moves no point, with no undo step)",
has_doc,
mesh_move_points
),
@@ -290,7 +290,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add Mesh Line",
[],
None,
"{id, x, y, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), tolerance?: pt (0)} add a row and a column through (x, y) to a gradient mesh (new point in `color`) or a mesh envelope; a point outside within `tolerance` of the edge adds them through the nearest point of the edge → {index}",
"{id, x, y, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), tolerance?: pt (0)} add a row and a column through (x, y), inside or on the edge, to a gradient mesh (new point in `color`) or a mesh or warp envelope (a warp becomes a mesh envelope, see object.envelope.setMeshPoint); a point outside within `tolerance` of the edge adds them through the nearest point of the edge; at a point that is already a mesh point it adds no line, and records no undo step unless `color` changes a gradient mesh's point (an envelope's points have no color) → {index}",
has_doc,
mesh_add_line
),
@@ -299,7 +299,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Delete Mesh Point",
[],
None,
"{id, index} delete the mesh lines through a point of a gradient mesh or mesh envelope",
"{id, index} delete the mesh lines through a point of a gradient mesh or a mesh or warp envelope (a warp becomes a mesh envelope, see object.envelope.setMeshPoint)",
has_doc,
mesh_delete_point
),
+15 -3
View File
@@ -1,6 +1,6 @@
use super::super::object::choice;
use super::common::{fix_ids, ids_json, is_envelope, roots_param, selected_of, wrap};
use super::mesh::{handle_param, index_param, whole};
use super::mesh::{envelope_edit_grid, handle_param, index_param, mesh_envelope, warp_point_stays, whole};
use super::{
Affine, Appearance, Arc, Beside, Color, Document, EngineError, EnvelopeKind, EnvelopeMap, EnvelopeOptions, Node, NodeId, NodeKind, Paint,
PathData, Point, PreserveShape, Result, Session, Value, bad, check_numbers, f64_or, f64_req, json, live, object_param, ok, switch_or, text_param,
@@ -79,8 +79,7 @@ fn mesh_kind(map: &EnvelopeMap, maintain: bool, rows: u32, cols: u32) -> Envelop
return EnvelopeKind::Mesh { rows, cols, points: map.grid(rows, cols), handles: vec![] };
}
// The surface's points with handles along it: the grid lines keep the current shape.
let m = map.surface_mesh(rows, cols, Color::BLACK);
EnvelopeKind::Mesh { rows, cols, points: m.points.iter().map(|q| q.p).collect(), handles: m.points.iter().map(|q| q.handles).collect() }
mesh_envelope(&map.surface_mesh(rows, cols, Color::BLACK))
}
pub(super) fn env_make_mesh(s: &mut Session, p: &Value) -> Result<Value> {
@@ -428,7 +427,20 @@ pub(super) fn env_set_mesh_point(s: &mut Session, p: &Value) -> Result<Value> {
let index = index_param(p, "index", C)?;
let q = Point::new(f64_req(p, "x", C)?, f64_req(p, "y", C)?);
let handle = handle_param(p, C)?;
// A warp whose point or handle stays where it is stays a warp.
if warp_point_stays(&s.doc()?.doc, id, index, handle, q, C)? {
return ok();
}
s.edit("Move Envelope Point", |d, _| {
// A warp's first edited point makes it a mesh envelope on its grid, in the same step.
if let Some(n) = d.node(id)
&& matches!(&n.kind, NodeKind::Envelope { kind, .. } if matches!(**kind, EnvelopeKind::Warp { .. }))
{
let grid = envelope_edit_grid(n, C).ok_or_else(|| bad(C, "not a mesh envelope point"))??;
if let Some(NodeKind::Envelope { kind, .. }) = d.node_mut(id).map(|n| &mut n.kind) {
**kind = mesh_envelope(&grid);
}
}
let Some(NodeKind::Envelope { kind, .. }) = d.node_mut(id).map(|n| &mut n.kind) else {
return Err(bad(C, "not a mesh envelope point"));
};
+129 -18
View File
@@ -119,27 +119,90 @@ fn with_mesh<T>(s: &mut Session, p: &Value, cmd: &str, label: &str, envelopes: b
s.edit(label, move |d, _| edit_grid(d, id, cmd, envelopes, f))
}
/// Run `f` on the gradient mesh `id` of `d`; with `envelopes`, a mesh envelope's grid too (its
/// points and handles are written back: editing fills in the handles).
fn edit_grid<T>(d: &mut Document, id: NodeId, cmd: &str, envelopes: bool, f: impl FnOnce(&mut GradientMesh) -> Result<T>) -> Result<T> {
match d.node_mut(id).map(|n| &mut n.kind) {
Some(NodeKind::Mesh(m)) => f(m),
Some(NodeKind::Envelope { kind, .. }) if envelopes && matches!(**kind, EnvelopeKind::Mesh { .. }) => {
let EnvelopeKind::Mesh { rows, cols, points, handles } = &mut **kind else {
return Err(bad(cmd, "not a gradient mesh or mesh envelope"));
};
let mut m = live::envelope_grid(*rows, *cols, points, handles).ok_or_else(|| bad(cmd, "the envelope's mesh is malformed"))?;
let r = f(&mut m)?;
(*rows, *cols) = (m.rows, m.cols);
*points = m.points.iter().map(|q| q.p).collect();
*handles = m.points.iter().map(|q| q.handles).collect();
Ok(r)
/// The grid an edit of envelope `n`'s points starts from: a mesh envelope's own grid, or a warp's
/// grid ([`live::warp_grid`]), which the edit turns into a mesh envelope. `None` for other nodes.
pub(super) fn envelope_edit_grid(n: &Node, cmd: &str) -> Option<Result<GradientMesh>> {
let NodeKind::Envelope { kind, .. } = &n.kind else { return None };
match &**kind {
EnvelopeKind::Mesh { rows, cols, points, handles } => {
Some(live::envelope_grid(*rows, *cols, points, handles).ok_or_else(|| bad(cmd, "the envelope's mesh is malformed")))
}
Some(_) => Err(bad(cmd, if envelopes { "not a gradient mesh or mesh envelope" } else { "not a gradient mesh" })),
EnvelopeKind::Warp { .. } => {
Some(live::warp_grid(n).ok_or_else(|| bad(cmd, "this warp's points can't be edited: use Reset with Mesh first")))
}
EnvelopeKind::TopObject { .. } => None,
}
}
/// The mesh envelope kind of grid `m`, with its points' handles.
pub(super) fn mesh_envelope(m: &GradientMesh) -> EnvelopeKind {
EnvelopeKind::Mesh {
rows: m.rows,
cols: m.cols,
points: m.points.iter().map(|q| q.p).collect(),
handles: m.points.iter().map(|q| q.handles).collect(),
}
}
/// Does placing point `index` of warp envelope `id` of `d`, or that point's `handle` end, at `q`
/// leave it where it is? Such a placement is no edit. `false` for other objects and for an index
/// out of range, whose edits run as before.
pub(super) fn warp_point_stays(d: &Document, id: NodeId, index: usize, handle: Option<usize>, q: Point, cmd: &str) -> Result<bool> {
let Some(n) = d.node(id).filter(|n| matches!(&n.kind, NodeKind::Envelope { kind, .. } if matches!(**kind, EnvelopeKind::Warp { .. }))) else {
return Ok(false);
};
let grid = envelope_grid_to_edit(n, cmd, true)?;
Ok(grid.points.get(index).is_some_and(|pt| match handle {
// The caller sends a handle's end as point plus handle; `q - p` can round away from it.
Some(h) => pt.handles.get(h).is_some_and(|v| pt.p + *v == q),
None => pt.p == q,
}))
}
/// The grid of envelope `n` that [`edit_grid`] edits (only `envelopes`), or the error it fails with.
fn envelope_grid_to_edit(n: &Node, cmd: &str, envelopes: bool) -> Result<GradientMesh> {
match envelope_edit_grid(n, cmd).filter(|_| envelopes) {
Some(grid) => grid,
None => Err(bad(cmd, if envelopes { "not a gradient mesh or mesh envelope" } else { "not a gradient mesh" })),
}
}
/// The grid of mesh `id` of `d` that [`edit_grid`] edits, as it is now.
fn grid_to_edit(d: &Document, id: NodeId, cmd: &str, envelopes: bool) -> Result<GradientMesh> {
match d.node(id) {
Some(Node { kind: NodeKind::Mesh(m), .. }) => Ok(m.clone()),
Some(n) => envelope_grid_to_edit(n, cmd, envelopes),
None => Err(EngineError::NoNode(id)),
}
}
/// Run `f` on the gradient mesh `id` of `d`; with `envelopes`, a warp or mesh envelope's grid too
/// (see [`edit_node`]).
fn edit_grid<T>(d: &mut Document, id: NodeId, cmd: &str, envelopes: bool, f: impl FnOnce(&mut GradientMesh) -> Result<T>) -> Result<T> {
edit_node(d.node_mut(id).ok_or(EngineError::NoNode(id))?, cmd, envelopes, f)
}
/// [`edit_grid`] on a node: with `envelopes`, a warp or mesh envelope's grid
/// ([`envelope_edit_grid`]) is edited too, and its points and handles are written back as a mesh
/// envelope (editing fills in the handles, and makes a warp a mesh envelope).
fn edit_node<T>(n: &mut Node, cmd: &str, envelopes: bool, f: impl FnOnce(&mut GradientMesh) -> Result<T>) -> Result<T> {
if let NodeKind::Mesh(m) = &mut n.kind {
return f(m);
}
let start = envelope_grid_to_edit(n, cmd, envelopes)?;
let mut m = start.clone();
let r = f(&mut m)?;
// A warp stays a warp when the edit changed nothing.
let warp = matches!(&n.kind, NodeKind::Envelope { kind, .. } if matches!(**kind, EnvelopeKind::Warp { .. }));
if warp && m == start {
return Ok(r);
}
if let NodeKind::Envelope { kind, .. } = &mut n.kind {
**kind = mesh_envelope(&m);
}
Ok(r)
}
/// Most mesh points one command names, over all its meshes.
const MAX_POINTS: usize = 1 << 20;
@@ -174,7 +237,8 @@ fn point_items(p: &Value, cmd: &str) -> Result<Vec<(NodeId, BTreeSet<usize>)>> {
}
/// Run `f` on each mesh point `items` names, as one undo step `label` (an index out of range
/// fails it, changing nothing); with `envelopes`, on mesh envelopes' points too.
/// fails it, changing nothing); with `envelopes`, on warp and mesh envelopes' points too. When `f`
/// changes no point, nothing changes and no undo step is recorded.
fn with_points(
s: &mut Session,
items: &[(NodeId, BTreeSet<usize>)],
@@ -183,6 +247,20 @@ fn with_points(
envelopes: bool,
mut f: impl FnMut(&mut live::MeshPoint) -> Result<()>,
) -> Result<()> {
let doc = &s.doc()?.doc;
let mut changes = false;
for (id, points) in items {
let mut m = grid_to_edit(doc, *id, cmd, envelopes)?;
for i in points {
let q = m.points.get_mut(*i).ok_or_else(|| bad(cmd, "index out of range"))?;
let before = q.clone();
f(q)?;
changes |= *q != before;
}
}
if !changes {
return Ok(());
}
s.edit(label, |d, _| {
for (id, points) in items {
edit_grid(d, *id, cmd, envelopes, |m| {
@@ -251,6 +329,10 @@ pub(super) fn mesh_move_point(s: &mut Session, p: &Value) -> Result<Value> {
let index = index_param(p, "index", C)?;
let q = Point::new(f64_req(p, "x", C)?, f64_req(p, "y", C)?);
let handle = handle_param(p, C)?;
let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing `id`"))?;
if warp_point_stays(&s.doc()?.doc, id, index, handle, q, C)? {
return ok();
}
with_mesh(s, p, C, "Move Mesh Point", true, |m| {
let pt = m.points.get_mut(index).ok_or_else(|| bad(C, "index out of range"))?;
match handle {
@@ -281,12 +363,41 @@ pub(super) fn mesh_add_line(s: &mut Session, p: &Value) -> Result<Value> {
check_numbers(p, &["tolerance"], C)?;
let tol = f64_or(p, "tolerance", 0.0).max(0.0);
let color = color_param(p, "color", C)?.map(|c| crate::cmd::paint::new_color(s, p, c));
let index = with_mesh(s, p, C, "Add Mesh Line", true, |m| {
let add = move |m: &mut GradientMesh| {
let i = m.add_lines_at(q, tol).ok_or_else(|| bad(C, "point is outside the mesh"))?;
if let Some(c) = color {
m.points[i].color = c;
}
Ok(i)
};
let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing `id`"))?;
if s.script_running() {
return Err(EngineError::Busy);
}
// The lines are added to a copy of the object. A point that is already a mesh point adds none:
// when its color stays too, nothing changes and no undo step is recorded. The grid is compared,
// not the node: a mesh envelope stored without handles takes them in any edit, a warp becomes
// a mesh envelope, and neither keeps colors, so only their points and handles count.
let orig = s.doc()?.doc.node(id).ok_or(EngineError::NoNode(id))?.clone();
let colored = matches!(orig.kind, NodeKind::Mesh(_));
let mut node = orig.clone();
let (i, same) = edit_node(&mut node, C, true, |m| {
let before = m.clone();
let i = add(m)?;
let shape = |g: &GradientMesh| (g.rows, g.cols, g.points.iter().map(|q| (q.p, q.handles)).collect::<Vec<_>>());
Ok((i, if colored { *m == before } else { shape(m) == shape(&before) }))
})?;
if same {
return Ok(json!({ "index": i }));
}
let index = s.edit("Add Mesh Line", move |d, _| {
let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?;
// Settling typed values before the edit may have changed the object: add the lines again.
if n.kind != orig.kind {
return edit_node(n, C, true, add);
}
n.kind = node.kind;
Ok(i)
})?;
Ok(json!({ "index": index }))
}
+5
View File
@@ -1053,6 +1053,11 @@ fn crop_image(s: &mut Session, p: &Value) -> Result<Value> {
bare.blend = Default::default();
bare.appearance = Appearance::default().into();
bare.visible = true;
// The image's own pixels are cut, not the masked ones a color mask shows: the mask is made
// again for the cut pixels after the edit.
if let Some(e) = bare.extras_if_any() {
e.color_mask = None;
}
let tmp = isolated_doc(&st.doc, vec![bare]);
let region = Rect::new(r.x0, r.y0, r.x0 + (r.width() * scale).round().max(1.0) / scale, r.y0 + (r.height() * scale).round().max(1.0) / scale);
let (png, w, h, warning) =
+13 -6
View File
@@ -63,7 +63,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Edit Profile",
[],
None,
"{name: a category of file.newPresets} open the category's New Document profile as a document to edit (File › Save keeps the changes for the next file.new); a category without a profile file gets the shipped profile written first → document.open's result",
"{name: a category of file.newPresets} open the category's New Document profile as a document to edit (File › Save keeps the changes for the next file.new); a category without a profile file gets the shipped profile written first; under automation roots it needs write and read access to the file, and an error names the file by its file name outside the read roots → document.open's result",
always,
edit_profile
),
@@ -72,7 +72,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Reset Profile",
[],
None,
"{name: a category of file.newPresets} delete the category's profile file, so the shipped profile (today's defaults) applies again; an open copy of it stays open → {name, reset: whether a file was deleted}",
"{name: a category of file.newPresets} delete the category's profile file, so the shipped profile (today's defaults) applies again; an open copy of it stays open; under automation roots it needs write access to the file, and an error names the file by its file name outside the read roots → {name, reset: whether a file was deleted}",
always,
reset_profile
),
@@ -999,10 +999,17 @@ fn list_profiles(s: &mut Session, _: &Value) -> Result<Value> {
Ok(json!({ "profiles": profiles, "folder": s.new_doc_profile_dir().and_then(shown) }))
}
/// `msg`, an error about the profile file at `path`, as the request being served may see it: the
/// file named whole inside the read roots, else by its file name.
fn profile_error(msg: String, path: &str) -> super::EngineError {
super::fileio::naming_in_error(super::EngineError::Other(msg), path)
}
/// The file of profile `name` for `cmd` to change, checked against the request's write access.
fn writable_profile(s: &Session, name: &str, cmd: &str) -> Result<std::path::PathBuf> {
let path = s.profile_path(name).ok_or_else(|| bad(cmd, "New Document profiles need the preferences folder, which this run doesn't have"))?;
crate::file_access::check_write(&path.to_string_lossy()).map_err(super::EngineError::Other)?;
let file = path.to_string_lossy();
crate::file_access::check_write(&file).map_err(|e| profile_error(e, &file))?;
Ok(path)
}
@@ -1012,13 +1019,13 @@ fn edit_profile(s: &mut Session, p: &Value) -> Result<Value> {
let file = writable_profile(s, name, C)?;
let path = file.to_string_lossy().to_string();
// document.open reads it next: a profile it can't open is not written either.
crate::file_access::check_read(&path).map_err(super::EngineError::Other)?;
crate::file_access::check_read(&path).map_err(|e| profile_error(e, &path))?;
if !file.exists() {
let bytes = vectorcraft_format::save(&shipped_profile(s, name), false);
file.parent()
.map_or(Ok(()), std::fs::create_dir_all)
.and_then(|()| std::fs::write(&file, bytes))
.map_err(|e| super::EngineError::Other(format!("{path}: {e}")))?;
.map_err(|e| profile_error(format!("{path}: {e}"), &path))?;
}
s.execute("document.open", &json!({ "path": path }))
}
@@ -1031,7 +1038,7 @@ fn reset_profile(s: &mut Session, p: &Value) -> Result<Value> {
let reset = match std::fs::remove_file(&file) {
Ok(()) => true,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => false,
Err(e) => return Err(super::EngineError::Other(format!("{path}: {e}"))),
Err(e) => return Err(profile_error(format!("{path}: {e}"), &path)),
};
Ok(json!({ "name": name, "reset": reset }))
}
+28 -9
View File
@@ -169,28 +169,47 @@ pub(super) fn lock(s: &mut Session, _: &Value) -> Result<Value> {
ok()
}
/// The selected objects ([`selected_roots`]) that Lock › Selection and Hide › Selection change: in
/// isolation mode, only those inside the isolated object, where a path of the isolated compound
/// path is an object of its own.
/// The selected objects ([`selected_roots`]) and ruler guides that Lock › Selection and Hide ›
/// Selection change: in isolation mode, only the objects inside the isolated object, where a path
/// of the isolated compound path is an object of its own. A guide counts while it can be edited
/// (it and its layer shown and unlocked, and Lock Guides off).
fn selected_lock_hide_roots(s: &Session) -> Result<Vec<NodeId>> {
match crate::cmd::ordinary_isolation(s.doc()?) {
let st = s.doc()?;
match crate::cmd::ordinary_isolation(st) {
Some(root) => crate::cmd::edit::selected_roots_inside(s, root, false),
None => selected_roots(s),
None => {
let mut ids = selected_roots(s)?;
if !s.guides_locked() {
let d = &st.doc;
ids.extend(st.selection.guides.iter().copied().filter(|id| d.ruler_guide(*id).is_some_and(|g| d.guide_editable(&g))));
}
Ok(ids)
}
}
}
/// The objects and ruler guides in `d` that `f` picks (layers never).
fn collect_flag(d: &Document, f: impl Fn(&Node) -> bool) -> Vec<NodeId> {
let mut v = vec![];
d.walk(|n| {
if !n.is_layer() && !n.is_ruler_guide() && f(n) {
if !n.is_layer() && f(n) {
v.push(n.id)
}
});
v
}
/// Select what Unlock All or Show All changed (`ids`): the objects, and the ruler guides among
/// them as guides (a guide that still can't be edited is then dropped from the selection).
fn select_changed(d: &Document, sel: &mut vectorcraft_doc::Selection, ids: &[NodeId]) {
let guides: std::collections::HashSet<NodeId> = d.ruler_guides().into_iter().filter_map(|g| g.id).collect();
let (on_guides, objects): (Vec<NodeId>, Vec<NodeId>) = ids.iter().copied().partition(|id| guides.contains(id));
sel.set(objects);
sel.guides = on_guides;
}
/// The objects that `f` picks for `object.unlockAll` and `object.showAll` (`cmd`): in the whole
/// document, inside the isolated object in isolation mode, or with `scope: "group"` inside the
/// document (its ruler guides included), inside the isolated object in isolation mode, or with `scope: "group"` inside the
/// groups that hold the selected objects (in isolation mode, only the objects of those groups
/// that are inside the isolated object). A selected group is the group that holds its own
/// members, and the objects of a group inside another such group are taken once. With
@@ -253,7 +272,7 @@ pub(super) fn unlock_all(s: &mut Session, p: &Value) -> Result<Value> {
n.locked = false;
}
}
sel.set(ids.iter().copied());
select_changed(d, sel, &ids);
Ok(())
})?;
Ok(json!({ "count": ids.len() }))
@@ -292,7 +311,7 @@ pub(super) fn show_all(s: &mut Session, p: &Value) -> Result<Value> {
n.visible = true;
}
}
sel.set(ids.iter().copied());
select_changed(d, sel, &ids);
Ok(())
})?;
Ok(json!({ "count": ids.len() }))
+8 -8
View File
@@ -7,7 +7,7 @@ use super::props::set_props;
use super::shape::{expand_shape, set_live_shape};
use super::transform::{move_cmd, nudge, reflect, rotate, scale, shear, transform, transform_again};
use super::{CommandSpec, cmd, has_doc, has_multi, has_selection, has_selection_or_guides};
use crate::cmd::has_selected_member;
use crate::cmd::has_selected_member_or_guide;
pub fn specs() -> Vec<CommandSpec> {
vec![
@@ -151,8 +151,8 @@ pub fn specs() -> Vec<CommandSpec> {
"Selection",
["Object", "Lock"],
Some("Cmd+2"),
"{ids?: [id…] (selected first; default: the selection; in isolation mode, only those inside the isolated object)}",
has_selected_member,
"{ids?: [id…] (selected first; default: the selection, selected ruler guides included; in isolation mode, only the objects inside the isolated object)}",
has_selected_member_or_guide,
lock
),
cmd!(
@@ -160,7 +160,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Unlock All",
["Object"],
Some("Cmd+Alt+2"),
"{scope?: \"document\"|\"group\" (default document, which in isolation mode is the isolated object; group: only the objects inside the groups that hold the selected objects, a selected group holding its own; the in-window menu item chosen with Shift+Alt)} unlock the locked objects and select them → {count}",
"{scope?: \"document\"|\"group\" (default document, which in isolation mode is the isolated object; group: only the objects inside the groups that hold the selected objects, a selected group holding its own; the in-window menu item chosen with Shift+Alt)} unlock the locked objects and select them; document scope outside isolation mode also unlocks ruler guides locked on their own → {count}",
has_doc,
unlock_all
),
@@ -169,8 +169,8 @@ pub fn specs() -> Vec<CommandSpec> {
"Selection",
["Object", "Hide"],
Some("Cmd+3"),
"{ids?: [id…] (selected first; default: the selection; in isolation mode, only those inside the isolated object)}",
has_selected_member,
"{ids?: [id…] (selected first; default: the selection, selected ruler guides included; in isolation mode, only the objects inside the isolated object)}",
has_selected_member_or_guide,
hide
),
cmd!(
@@ -178,7 +178,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Show All",
["Object"],
Some("Cmd+Alt+3"),
"{scope?: \"document\"|\"group\" (default document, which in isolation mode is the isolated object; group: only the objects inside the groups that hold the selected objects, a selected group holding its own; the in-window menu item chosen with Shift+Alt)} show the hidden objects and select them → {count}",
"{scope?: \"document\"|\"group\" (default document, which in isolation mode is the isolated object; group: only the objects inside the groups that hold the selected objects, a selected group holding its own; the in-window menu item chosen with Shift+Alt)} show the hidden objects and select them; document scope outside isolation mode also shows ruler guides hidden on their own → {count}",
has_doc,
show_all
),
@@ -251,7 +251,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Object Properties",
[],
None,
"{ids?|id?, name?, visible?, locked? (visible: false or locked: true deselects every selected object hidden or locked after the call, the key object included), opacity?: 0..100, blend?: \"Multiply\"…, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, data?: {key: \"value\" | null (removes it)} (the object's own data, SVG data-* attributes: {pivot: \"100,180\"} is data-pivot; document.node → attrs.data)}. On a path directly in a graph series, the graph also stores the object's opacity and blend mode (exceptions: docs/mcp.md)",
"{ids?|id?, name?, visible?, locked? (visible: false or locked: true deselects every selected object hidden or locked after the call, the key object included), opacity?: 0..100, blend?: \"Multiply\"…, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, data?: {key: \"value\" | null (removes it)} (the object's own data, SVG data-* attributes: {pivot: \"100,180\"} is data-pivot; document.node → attrs.data)}. On a path directly in a graph series, the graph also stores the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, the graph stores the label's opacity and blend mode for every label of its kind",
has_doc,
set_props
),
+5 -3
View File
@@ -65,10 +65,11 @@ pub(super) fn set_props(s: &mut Session, p: &Value) -> Result<Value> {
})
};
let d = &s.doc()?.doc;
// A graph keeps the object opacity and blend mode set on a mark of a series for the whole series, so a value a mark
// already has still replaces the one another mark left on the graph.
// A graph keeps the object opacity and blend mode set on a mark of a series for the whole series, and set on a label
// for its kind of label, so a value a mark or label already has still replaces the one another left on the graph.
let transparency = opacity.is_some() || blend.is_some();
let stores = || transparency && crate::cmd::graph::series_object_opacity_differs(d, &ids);
let stores =
|| transparency && (crate::cmd::graph::series_object_opacity_differs(d, &ids) || crate::cmd::graph::label_object_opacity_differs(d, &ids));
if ids.iter().all(|id| d.node(*id).is_some_and(has_values)) && !stores() {
// Hidden or locked objects can't stay selected.
if hides {
@@ -124,6 +125,7 @@ pub(super) fn set_props(s: &mut Session, p: &Value) -> Result<Value> {
}
if transparency {
crate::cmd::graph::capture_series_object_opacity(d, &ids);
crate::cmd::graph::capture_label_object_opacity(d, &ids);
}
// Hidden or locked objects can't stay selected.
if hides {
+3 -2
View File
@@ -135,9 +135,7 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
.map_err(|_| bad("object.setLiveShape", format!("`kind` must be \"round\", \"invertedRound\" or \"chamfer\", not {v}")))
})
.transpose()?;
let radius = p.get("radius").and_then(Value::as_f64);
let relative_radii = p.get("relativeRadii").and_then(Value::as_bool);
let sides = p.get("sides").and_then(Value::as_u64);
// A number that must be `what` (None when absent).
let number = |k: &str, ok: fn(f64) -> bool, what: &str| -> Result<Option<f64>> {
match p.get(k) {
@@ -151,6 +149,9 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
};
let angle = |k: &str| Ok::<_, EngineError>(number(k, |_| true, "an angle in degrees")?.map(|a| a.rem_euclid(360.0)));
let length = |k: &str| number(k, |x| x > 0.0 && x <= crate::MAX_COORD, "a length in points above 0");
let radius = number("radius", |r| r >= 0.0, "a radius of 0 or more")?;
// A polygon's side count: a whole number from 3 to 1000.
let sides = number("sides", |n| n.fract() == 0.0 && (3.0..=1000.0).contains(&n), "a whole number from 3 to 1000")?.map(|n| n as u64);
// An ellipse's pie (Ellipse Properties: Pie Start and End Angle, degrees; Invert Pie swaps them).
let (pie_start, pie_end) = (angle("pieStart")?, angle("pieEnd")?);
let invert = p.get("invertPie").and_then(Value::as_bool) == Some(true);
+54 -2
View File
@@ -12,7 +12,8 @@
//! `object.objectsOnPath.selectMember` chooses one object of a selected group (its Select/Move
//! widget), and `object.objectsOnPath.moveMember` moves one object to another's place along the
//! path, the objects between it and that place each moving one place toward where it was; hidden
//! and locked objects keep their places.
//! and locked objects keep their places. `object.objectsOnPath.detach` takes one object out of its
//! group, just above it, and the others move up the path.
//!
//! After every edit, [`refresh`] puts the objects of each Objects on Path group that changed back
//! on its path: editing the path moves them, an object moved on its own goes back to its place,
@@ -21,7 +22,8 @@
//!
//! Behavior: <https://helpx.adobe.com/illustrator/using/objects-on-path.html> (the tool and
//! Object › Objects on Path › Attach; the order on the path, the attachment point, the distribution,
//! the objects squared to the path; Pivot and Rotate; path edits realign the objects; Expand).
//! the objects squared to the path; Pivot and Rotate; path edits realign the objects; Detach and
//! the objects that move up the path after it; Expand).
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
@@ -75,6 +77,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
move_member
),
cmd!(
"object.objectsOnPath.detach",
"Detach Object from Path",
[],
None,
"{member?: id of an object of an Objects on Path group (default: the object chosen with the selected group's Select/Move widget); neither the object nor the group may be hidden or locked} take one object off the path, out of its group and just above the group in the Layers panel, where it stays as drawn and is selected alone. The group's other objects move up the path in their order: with Auto Space they spread evenly again, and a Space value and the start are kept. The group and its path stay, even with one object or none left → {group, member}",
has_doc,
detach
),
cmd!(
"object.objectsOnPath.expand",
"Expand",
@@ -383,6 +394,47 @@ fn move_member(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "group": g.0, "member": member.0, "index": index }))
}
// ---------- Detach ----------
/// The object chosen with the Select/Move widget of the one selected Objects on Path group.
fn chosen_member(s: &Session) -> Option<NodeId> {
let st = s.active()?;
match st.selection.objects[..] {
[_] => st.selection.on_path_member,
_ => None,
}
}
fn detach(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "object.objectsOnPath.detach";
const CHOOSE: &str = "choose the object to detach with its Select/Move widget";
let (g, member) = if p.get("member").is_none_or(Value::is_null) {
let chosen = chosen_member(s).ok_or_else(|| bad(C, CHOOSE))?;
let found = member_param(s, &json!({ "member": chosen.0 }), "member", C)?;
if s.active().is_none_or(|st| st.selection.objects[..] != [found.0]) {
return Err(bad(C, CHOOSE));
}
found
} else {
member_param(s, p, "member", C)?
};
// The object goes just above the group, in the group's parent, and keeps where it is drawn.
// When the group is itself an object on another group's path, the object goes above that
// group instead (and so on outward), so it does not join that path. The refresh after the edit
// removes it from the group's record and moves the others up the path.
s.edit("Detach Object from Path", |d, sel| {
let mut above = g;
while let Some(p) = d.parent_of(above).filter(|p| d.node(*p).is_some_and(is_objects_on_path)) {
above = p;
}
let (parent, index, _) = d.position(above).ok_or(EngineError::NoNode(above))?;
d.move_node(member, parent, index + 1)?;
sel.set([member]);
Ok(())
})?;
Ok(json!({ "group": g.0, "member": member.0 }))
}
// ---------- Expand ----------
fn expand(s: &mut Session, p: &Value) -> Result<Value> {
+86 -23
View File
@@ -6,7 +6,7 @@ use serde_json::{Value, json};
use vectorcraft_color::{BlendMode, Color, GradientPaint, Paint};
use vectorcraft_doc::{Appearance, CharStyle, Document, GraySource, Node, NodeId, NodeKind};
use super::appearance::{ItemTarget, appearance_targets, edit_items, edit_items_then, item_target};
use super::appearance::{ItemTarget, edit_items, edit_items_then, item_target, row_targets};
use super::gradient::{item_paint_bounds, place_paint, place_run_paint, run_paint_mut, run_stroke_weight, unplaced};
use super::{
Affine, CommandSpec, Result, Session, always, bad, bool_or, check_numbers, check_switches, cmd, color_value, has_doc, leaf_targets, ok,
@@ -21,7 +21,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Fill",
[],
None,
"{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid colour recolours only the gradient mesh point last clicked with the Mesh tool or Direct Selection; while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern) → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}",
"{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid colour recolours only the gradient mesh point last clicked with the Mesh tool or Direct Selection; while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}",
has_doc,
|s, p| set_paint(s, p, true)
),
@@ -30,7 +30,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Stroke",
[],
None,
"{…as paint.setFill, item?: the stroke item to set} same as paint.setFill, for the stroke; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's stroke changes for this instance only (solid, none, gradient or pattern)",
"{…as paint.setFill, item?: the stroke item to set} same as paint.setFill, for the stroke; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's stroke changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint and weight of the topmost visible stroke when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, as paint.setFill",
has_doc,
|s, p| { set_paint(s, p, false) }
),
@@ -64,16 +64,24 @@ pub fn specs() -> Vec<CommandSpec> {
Ok(json!({ "fillActive": s.fill_active }))
}
),
cmd!("paint.none", "None", [], Some("/"), "{} set the active proxy (fill or stroke) to None → {objects}", has_doc, |s, _| {
let f = s.fill_active;
set_paint(s, &json!({"none": true}), f)
}),
cmd!(
"paint.none",
"None",
[],
Some("/"),
"{} set the active proxy (fill or stroke) to None, as paint.setFill or paint.setStroke with none does → {objects}",
has_doc,
|s, _| {
let f = s.fill_active;
set_paint(s, &json!({"none": true}), f)
}
),
cmd!(
"transparency.set",
"Transparency",
["Window", "Transparency"],
None,
"{ids?|id?, opacity?: 0..100, blend?: name, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, item?: appearance item index|null, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} for `ids`, the selection, or the object whose opacity mask is being edited; opacity and blend go to the targeted fill/stroke item (omitted: the Appearance panel's active item, else the objects; a gradient mesh point last clicked with the Mesh tool or Direct Selection takes the opacity itself). With an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, opacity and blend change that object for this instance only (isolate, knockout, knockoutShape, aligned and target are refused). On a path directly in a graph series, the graph also stores the opacity and blend mode of the object and of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
"{ids?|id?, opacity?: 0..100, blend?: name, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, item?: appearance item index|null, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} for `ids`, the selection, or the object whose opacity mask is being edited; opacity and blend go to the targeted fill/stroke item (omitted: the Appearance panel's active item, else the objects; a gradient mesh point last clicked with the Mesh tool or Direct Selection takes the opacity itself). With an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, opacity and blend change that object for this instance only (isolate, knockout, knockoutShape, aligned and target are refused). On a path directly in a graph series (for a fill or stroke item, a series group's id stands for those paths), the graph also stores the opacity and blend mode of the object and of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, the graph stores the label's object opacity and blend mode for every label of its kind, and with `item` its topmost visible fill and stroke rows too",
has_doc,
transparency
),
@@ -88,7 +96,7 @@ pub fn proxy_specs() -> Vec<CommandSpec> {
"Invert",
[],
None,
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents) keeping each colour's model, as edit.colors.invert does; the Appearance panel's active fill/stroke item (appearance.setActiveItem) is inverted instead when it is of that kind and no ids are given; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's solid color changes for this instance only, and a gradient or pattern, or type whose characters differ in color, is refused; with nothing selected, invert the default → {changed}",
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents) keeping each colour's model, as edit.colors.invert does; the Appearance panel's active fill/stroke item (appearance.setActiveItem) is inverted instead when it is of that kind and no ids are given; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's solid color changes for this instance only, and a gradient or pattern, or type whose characters differ in color, is refused; with nothing selected, invert the default. On a path directly in a graph series, the graph also stores the new color of the topmost visible fill or stroke (docs/mcp.md); no undo step when no color changes → {changed}",
has_doc,
|s, p| proxy_recolor(s, p, "paint.invert", "Invert", &super::colorcmds::invert)
),
@@ -97,7 +105,7 @@ pub fn proxy_specs() -> Vec<CommandSpec> {
"Complement",
[],
None,
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, target?: \"object\"|\"contents\"} replace the active proxy's colours by their complements ((highest + lowest) − each component, over RGB or CMY; grey unchanged) keeping each colour's model; honours the Appearance panel's active item and a selected object of a dynamic symbol instance as paint.invert does; with nothing selected, the default → {changed}",
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, target?: \"object\"|\"contents\"} replace the active proxy's colours by their complements ((highest + lowest) − each component, over RGB or CMY; grey unchanged) keeping each colour's model; honours the Appearance panel's active item and a selected object of a dynamic symbol instance as paint.invert does; with nothing selected, the default; no undo step when no color changes → {changed}",
has_doc,
|s, p| proxy_recolor(s, p, "paint.complement", "Complement", &|c: Color| c.complement_keep_model())
),
@@ -467,6 +475,14 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool)
let ids: Vec<NodeId> = ranges.iter().map(|(f, _, _)| *f).collect();
// When the type comes out as it was, the document and its undo history stay as they are.
let before = s.doc()?.doc.clone();
// The graph labels whose whole text takes the paint: a graph keeps it for their kind of label.
let whole: Vec<NodeId> = ranges
.iter()
.filter(|(id, a, b)| {
*a == 0 && matches!(before.node(*id).map(|n| &n.kind), Some(NodeKind::Text(t)) if *b >= vectorcraft_text::edit::runs_len(&t.runs))
})
.map(|(id, _, _)| *id)
.collect();
super::overprint::edit_counted(s, if fill { "Fill Color" } else { "Stroke Color" }, |d| {
for &(id, a, b) in &ranges {
let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) else { return Err(EngineError::NoNode(id)) };
@@ -483,7 +499,17 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool)
});
super::typecmd::refresh_bounds(t);
}
Ok(super::appearance::count_changed(d, &before, &ids))
let labels = super::graph::capture_label_styles(d, &whole, &|st| {
if fill {
st.fill = unplaced(&paint);
} else {
if !paint.is_none() {
run_stroke_weight(st);
}
st.stroke = unplaced(&paint);
}
});
Ok(super::appearance::count_changed(d, &before, &ids) + usize::from(labels))
})?;
if focus {
s.fill_active = fill;
@@ -523,6 +549,12 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool)
vec![]
};
let label = if fill { "Fill Color" } else { "Stroke Color" };
// Each object whose appearance took the paint, with the row it went to, for the paint a graph stores for its series
// (a series mark is a path, so it always has a row here).
let written = std::cell::RefCell::new(Vec::new());
// The type objects whose characters took the paint (no row targeted): only those change what a graph's labels keep
// for their characters; a row edit is kept with the label's rows.
let characters = std::cell::RefCell::new(Vec::new());
edit_items_then(
s,
&ids,
@@ -531,6 +563,9 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool)
label,
fill,
|n, index| {
if index.is_none() && matches!(n.kind, NodeKind::Text(_)) {
characters.borrow_mut().push(n.id);
}
if index.is_none() && colorized.contains(&n.id) {
n.extras_mut().colorize = paint.color().map(|_| Box::new(paint.clone()));
return Ok(());
@@ -581,18 +616,23 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool)
if !fill {
super::object::snap_if_aligned(n);
}
let at = match index {
Some(_) => n.appearance.item_of_kind(index, fill),
None => n.appearance.items.iter().rposition(|it| it.is_fill() == fill),
};
written.borrow_mut().extend(at.map(|at| (n.id, at)));
Ok(())
},
|d, changed| {
let series = super::graph::capture_series_paints(d, changed, fill);
let labels = super::graph::capture_label_styles(d, changed, &|st| {
|before, d, changed| {
let series = super::appearance::capture_series_paint_writes(before, d, changed, &written.borrow());
let labels = super::graph::capture_label_styles(d, &characters.borrow(), &|st| {
if fill {
st.fill = paint.clone();
st.fill = unplaced(&paint);
} else {
if !paint.is_none() {
run_stroke_weight(st);
}
st.stroke = paint.clone();
st.stroke = unplaced(&paint);
}
});
Ok(series || labels)
@@ -690,7 +730,9 @@ fn placed_across(d: &Document, ids: &[NodeId], paint: Paint, p: &Value, fill: bo
/// The images among `ids` that a fill of `paint` colorizes: grayscale and 1-bit images, for a solid
/// color (or none on a colorized image, which takes the color off). The color may be black, white,
/// a process color or a spot color; on an image with an alpha channel, only a spot color, black or
/// white, and other colors are an error.
/// white, and other colors are an error. A colorized image that shows a preview that isn't
/// grayscale, such as a missing link's placeholder, takes a solid color as its new colorize paint;
/// while its paint is one an alpha channel allows, a process color is an error there too.
fn colorized_images(d: &Document, ids: &[NodeId], paint: &Paint) -> std::result::Result<Vec<NodeId>, String> {
let mut out = vec![];
for id in ids {
@@ -701,7 +743,22 @@ fn colorized_images(d: &Document, ids: &[NodeId], paint: &Paint) -> std::result:
out.push(*id);
continue;
}
let Some(gray) = d.image_blob(im).and_then(|b| b.gray_source()) else { continue };
// The Fill proxy shows such an image's colorize paint. Its pixels are not known until the
// file is relinked: a process color replaces only a process color, which the image's
// pixels already accepted, so a relink can't bring back an alpha channel under one.
if matches!(paint, Paint::Solid { .. })
&& let Some(old) = n.extras().colorize.as_deref()
&& d.image_blob(im).is_some_and(|b| !b.takes_colorize())
{
if !colorizes_transparency(d, paint) && colorizes_transparency(d, old) {
return Err(PROCESS_ON_TRANSPARENCY.into());
}
out.push(*id);
continue;
}
// A color-masked image is colorized as it shows: its masked pixels, which have an alpha
// channel.
let Some(gray) = d.image_blob(&d.shown_image(n, im)).and_then(|b| b.gray_source()) else { continue };
match paint {
// Without a color, `none` goes to the image's fill item.
Paint::None => continue,
@@ -758,11 +815,17 @@ pub(super) fn check_colorized_kept(was_ok: bool, d: &Document) -> std::result::R
if was_ok { check_colorized(d) } else { Ok(()) }
}
/// How the pixels of `n` are gray, when `n` is a grayscale or 1-bit image colorized with a color
/// that [`colorizes_transparency`] refuses. Such an image can't have an alpha channel.
/// Is `n` an image colorized with a color that [`colorizes_transparency`] refuses? When its pixels
/// are grayscale or 1-bit, they can't have an alpha channel.
pub(super) fn colorized_with_process(d: &Document, n: &Node) -> bool {
matches!(n.kind, NodeKind::Image(_)) && n.extras().colorize.as_deref().is_some_and(|paint| !colorizes_transparency(d, paint))
}
/// How the pixels `n` shows are gray, when `n` is a grayscale or 1-bit image colorized with a
/// color that [`colorizes_transparency`] refuses ([`colorized_with_process`]).
pub(super) fn gray_colorized_with_process(d: &Document, n: &Node) -> Option<GraySource> {
let (NodeKind::Image(im), Some(paint)) = (&n.kind, n.extras().colorize.as_deref()) else { return None };
if colorizes_transparency(d, paint) { None } else { d.image_blob(im).and_then(|b| b.gray_source()) }
let NodeKind::Image(im) = &n.kind else { return None };
if colorized_with_process(d, n) { d.image_blob(&d.shown_image(n, im)).and_then(|b| b.gray_source()) } else { None }
}
/// Is `e` the refusal of [`check_colorized`]?
@@ -1039,7 +1102,7 @@ fn transparency(s: &mut Session, p: &Value) -> Result<Value> {
return s.execute("object.setProps", &Value::Object(q));
};
// Opacity and blend belong to the targeted fill/stroke; isolate/knockout/knockoutShape stay object-level.
let item_ids = if editing_mask { ids } else { appearance_targets(s, p)? };
let item_ids = if editing_mask { ids } else { row_targets(s, p)? };
if explicit {
let d = &s.doc()?.doc;
if !item_ids.iter().any(|id| d.node(*id).is_some_and(|n| index < n.appearance.items.len())) {
File diff suppressed because one or more lines are too long
+135 -27
View File
@@ -8,15 +8,17 @@
//! (`…settings as file.new`), or, naming none, any key (the options of the format an export picks). Objects inside a value aren't
//! described key by key, so only the top level is checked, except in the options of an export, a
//! save or Export for Screens: those are checked against the options of the formats the command
//! can write, in `marks`, `bleed` and the other objects too ([`check_export_options`]).
//! can write, in `marks`, `bleed` and the other objects too ([`check_export_options`]); and in the
//! objects of an array whose keys `MEMBER_KEYS` lists, such as the `items` of
//! `object.setLiveShape` and `addon.pathtools.cornerSet`.
//!
//! [`Session::execute`] answers a key the description doesn't name with a parameter error
//! ([`check_params`]), for every caller (the app, the control channel, MCP, the CLI) and for the
//! commands a command runs, the steps of a `command.batch` or an `action.batch` included: a
//! misspelled `widht` no longer runs the command with its default. So are the `params` of an
//! effect (#1592): `effect.apply` and
//! `effect.setParams` answer a key the effect doesn't take, or a value of another type than its
//! default, with a parameter error ([`check_effect_params`]).
//! `effect.setParams` answer a key the effect doesn't take, or a value of another type than the
//! effect reads, with a parameter error ([`check_effect_params`]).
//!
//! A command with a parameter schema (`CommandSpec::schema`) is also checked against the schema
//! before it runs ([`crate::schemas::check`]): the schema refuses a value of the wrong type or out
@@ -172,6 +174,13 @@ fn accepted(doc: &'static str, depth: usize) -> Option<Vec<&'static str>> {
Some(keys)
}
/// Every key the description `doc` takes, those of the commands its `…` entries name included, or
/// `None` when that isn't known: it doesn't parse, a `…` entry names no command, or one names a
/// command in [`UNCHECKED`].
pub(crate) fn accepted_keys(doc: &'static str) -> Option<Vec<&'static str>> {
accepted(doc, 0)
}
/// Does the description `doc` name `key` as a parameter (its own keys, and those of the commands
/// its `…` entries name)?
pub(crate) fn takes_key(doc: &'static str, key: &str) -> bool {
@@ -247,6 +256,22 @@ pub fn check_keys(id: &str, doc: &'static str, params: &Value) -> Result<()> {
}
}
/// Parameters a command takes instead of one another: (command, key, other key). Giving both,
/// neither null, is a parameter error ([`check_exclusive_keys`]).
const EXCLUSIVE_KEYS: &[(&str, &str, &str)] = &[("addon.pathtools.cornerSet", "items", "ids"), ("addon.pathtools.cornerRemove", "items", "ids")];
/// `params` of command `id` give at most one of each pair in [`EXCLUSIVE_KEYS`], or the parameter
/// error naming the pair.
fn check_exclusive_keys(id: &str, params: &Value) -> Result<()> {
let given = |key: &str| params.get(key).filter(|v| !v.is_null());
for (_, key, other) in EXCLUSIVE_KEYS.iter().filter(|(c, ..)| *c == id) {
if given(key).is_some() && given(other).is_some() {
return Err(bad(id, format!("give `{key}` or `{other}`, not both")));
}
}
Ok(())
}
/// The parameter error of command `id` for `key`, which isn't one of `keys`: with the nearest of
/// them, or all of them.
pub(crate) fn unknown(id: &str, key: &str, keys: &[&str]) -> crate::EngineError {
@@ -262,16 +287,55 @@ pub(crate) fn unknown(id: &str, key: &str, keys: &[&str]) -> crate::EngineError
)
}
/// Commands whose params hold an array of objects with keys of their own: the command, the key of
/// the array and the keys each of its objects takes.
const MEMBER_KEYS: &[(&str, &str, &[&str])] = &[
("object.setLiveShape", "items", &["id", "corners"]),
("addon.pathtools.cornerSet", "items", &["id", "anchors"]),
("addon.pathtools.cornerRemove", "items", &["id", "anchors"]),
];
/// Each object in the arrays [`MEMBER_KEYS`] names for command `id` has only the keys it lists, or
/// the parameter error naming the first other one with its place (`items[0].corner`), and the
/// nearest accepted key or the accepted ones. A member that isn't an object is the command's to
/// report.
fn check_member_keys(id: &str, params: &Value) -> Result<()> {
for (_, list, keys) in MEMBER_KEYS.iter().filter(|(c, ..)| *c == id) {
let Some(members) = params.get(*list).and_then(Value::as_array) else { continue };
for (i, member) in members.iter().enumerate() {
let Value::Object(given) = member else { continue };
let Some(key) = given.keys().find(|k| !keys.contains(&k.as_str())) else { continue };
let at = |k: &str| format!("{list}[{i}].{k}");
let near = nearest(key, keys);
let key = at(&shown_key(key));
return Err(bad(
id,
match near {
Some(near) => {
let near = at(near);
format!("unknown parameter `{key}`; did you mean `{near}`?")
}
None => {
let keys = keys.iter().map(|k| at(k)).collect::<Vec<_>>().join(", ");
format!("unknown parameter `{key}`; the command takes: {keys}")
}
},
));
}
}
Ok(())
}
/// `params` of built-in effect `effect`, as command `id` was given them (#1592): only keys the
/// effect takes (those of its dialog defaults and of its params description), each of its
/// default's type, a `color` the effect can draw ([`check_effect_color`]) and a Levels or Curves
/// `channel` the effect has ([`check_effect_channel`]). Numbers out of range pass: the effect
/// clamps them when it draws. An effect plug-in resolves its own against its manifest, and an
/// unknown effect is the command's to report.
/// effect takes (those of its dialog defaults and of its params description), each of the type
/// the effect reads ([`check_effect_types`]), a `color` the effect can draw ([`check_effect_color`])
/// and a Levels or Curves `channel` the effect has ([`check_effect_channel`]). Numbers out of range
/// pass: the effect clamps them when it draws. An installed effect plug-in's are checked against its
/// manifest, and an unknown effect is the command's to report.
pub fn check_effect_params(id: &str, effect: &str, params: &Value) -> Result<()> {
let Value::Object(given) = params else { return Ok(()) };
if effect.starts_with(vectorcraft_plugins::effect::PREFIX) {
return Ok(());
return check_effect_types(id, effect, params);
}
let Some(info) = vectorcraft_render::effects::effect_info(effect) else { return Ok(()) };
let defaults = info.defaults.as_object();
@@ -282,18 +346,10 @@ pub fn check_effect_params(id: &str, effect: &str, params: &Value) -> Result<()>
keys.push(key);
}
}
for (key, v) in given {
if !keys.contains(&key.as_str()) {
return Err(unknown(id, key, &keys));
}
match defaults.and_then(|d| d.get(key)) {
Some(Value::Number(_)) if !v.is_number() => return Err(bad(id, format!("`{key}` must be a number"))),
Some(Value::Bool(_)) if !v.is_boolean() => return Err(bad(id, format!("`{key}` must be true or false"))),
// (A colour is also taken as `[r, g, b]` or as a colour object.)
Some(Value::String(_)) if v.is_number() || v.is_boolean() => return Err(bad(id, format!("`{key}` must be a string"))),
_ => {}
}
if let Some(key) = given.keys().find(|k| !keys.contains(&k.as_str())) {
return Err(unknown(id, key, &keys));
}
check_effect_types(id, effect, params)?;
// An SVG filter's XML is one drawable <filter> element.
if effect == vectorcraft_render::effects::SVG_FILTER
&& let Some(xml) = given.get("xml")
@@ -329,6 +385,59 @@ pub fn check_effect_params(id: &str, effect: &str, params: &Value) -> Result<()>
check_effect_channel(id, effect, params)
}
/// The type of the values in `params` of effect `effect`, as command `id` was given them: a key
/// the effect has a dialog default for takes a value of its default's type, a key only the
/// effect's params description names takes the type the effect reads ([`undefaulted_type`]), and
/// an installed effect plug-in's take the types its manifest gives them. The `style` of Crop Marks
/// is `roman` or `japanese`. A number given as text (`"10 pt"`), `true` for a number, `1` for a
/// switch and `null` for either are refused.
fn check_effect_types(id: &str, effect: &str, params: &Value) -> Result<()> {
let Value::Object(given) = params else { return Ok(()) };
if effect.starts_with(vectorcraft_plugins::effect::PREFIX) {
return match vectorcraft_plugins::effect::installed(effect) {
Some(plugin) => plugin.manifest().resolve_params(params).map(drop).map_err(|why| bad(id, why.to_string())),
None => Ok(()),
};
}
let Some(info) = vectorcraft_render::effects::effect_info(effect) else { return Ok(()) };
for (key, v) in given {
let want = info.defaults.get(key).cloned().or_else(|| undefaulted_type(effect, key));
match want {
Some(Value::Number(_)) if !v.is_number() => return Err(bad(id, format!("`{key}` must be a number"))),
Some(Value::Bool(_)) if !v.is_boolean() => return Err(bad(id, format!("`{key}` must be true or false"))),
// (A colour is also taken as `[r, g, b]` or as a colour object.)
Some(Value::String(_)) if v.is_number() || v.is_boolean() => return Err(bad(id, format!("`{key}` must be a string"))),
_ => {}
}
}
// Crop Marks draw one of two styles.
if effect == vectorcraft_render::effects::CROP_MARKS
&& let Some(style) = given.get("style")
&& style.as_str().and_then(vectorcraft_doc::marks::MarkStyle::parse).is_none()
{
return Err(bad(id, "`style` must be roman or japanese"));
}
Ok(())
}
/// A value of the type effect `effect` reads for `key`, a parameter its params description names
/// without a dialog default: the earlier 3D Perspective and light (`perspective`, `lightAzimuth`,
/// `lightElevation`) and Scribble `variation` are numbers, an Outline Stroke's `width` is a number
/// and a Gaussian Blur's `linear` is true or false. A Glass or Texturizer `textureImage`, an SVG
/// filter's `name` and `xml`, a Warp's `version` and the `style` of Crop Marks have checks of their
/// own; they aren't listed.
pub(crate) fn undefaulted_type(effect: &str, key: &str) -> Option<Value> {
use vectorcraft_render::effects;
let number = || Some(Value::from(0.0));
match key {
"perspective" | "lightAzimuth" | "lightElevation" if effects::is_three_d(effect) => number(),
"variation" if effect == "stylize.scribble" => number(),
"width" if effect == "path.outlineStroke" => number(),
"linear" if effect == "blur.gaussian" => Some(Value::Bool(false)),
_ => None,
}
}
/// Can an effect read `v` as its `color`: a string [`Color::from_hex`] reads (`#rrggbb`, `#rgb`,
/// `#rrggbbaa`, black, white, red, green, blue), `[r, g, b]` whose first three entries are numbers
/// (read on a 0..1 scale) or a color object (`{"model": "rgb", "r": …}`)? The effect draws its
@@ -474,7 +583,6 @@ pub const UNCHECKED: &[&str] = &[
"object.rasterize",
"object.repeat.options",
"object.setBounds",
"object.setLiveShape",
"object.setOverprint",
"object.setProps",
"object.slice.divide",
@@ -728,9 +836,7 @@ fn check_export_options(id: &str, params: &Value) -> Result<()> {
NO_SAVE_FORMAT
}
"document.export" | "document.exportSelection" | "document.serialize" => {
// `richBlack` is Appearance of Black's setting for a raster export, and `params` an
// exporter plug-in's own.
keys.extend(["includeArtboardFill", "selectedOnly", "richBlack", "params"]);
keys.extend(super::fileio::EXPORT_PARAMS);
keys.extend(FORMATS.iter().filter(|f| f.write).flat_map(|f| f.options).map(|o| o.name));
NO_FORMAT
}
@@ -762,9 +868,9 @@ fn check_export_options(id: &str, params: &Value) -> Result<()> {
check_option_keys(id, "", given, &keys, why_not, &trees)
}
/// [`check_keys`] for an engine command, the steps of a `command.batch` or an `action.batch` included,
/// [`check_effect_params`] for the effect `effect.apply` adds and [`check_export_options`] for an
/// export. A command the engine doesn't have passes: running it reports that.
/// [`check_keys`], [`check_exclusive_keys`] and [`check_member_keys`] for an engine command, the steps of a `command.batch` or an
/// `action.batch` included, [`check_effect_params`] for the effect `effect.apply` adds and
/// [`check_export_options`] for an export. A command the engine doesn't have passes: running it reports that.
pub fn check_params(id: &str, params: &Value) -> Result<()> {
check_params_in(id, params, false)
}
@@ -783,6 +889,8 @@ fn check_params_in(id: &str, params: &Value, in_batch: bool) -> Result<()> {
return Ok(());
}
check_keys(id, spec.params, params)?;
check_exclusive_keys(id, params)?;
check_member_keys(id, params)?;
if in_batch {
crate::schemas::check(spec, params, false)?;
}

Some files were not shown because too many files have changed in this diff Show More