Merge main into feat/save-for-web-shift-color

This commit is contained in:
dotCooCoo
2026-11-18 01:32:40 -08:00
430 changed files with 30451 additions and 2010 deletions
+15 -2
View File
@@ -407,7 +407,18 @@ pub fn command_specs() -> &'static [CommandSpec] {
/// The command `id`: a built-in one, or a command an installed plug-in adds
/// ([`plugin::command_specs`]).
pub fn find_command(id: &str) -> Option<&'static CommandSpec> {
command_specs().iter().find(|c| c.id == id).or_else(|| plugin::find_spec(id))
static INDEX: std::sync::OnceLock<std::collections::HashMap<&'static str, &'static CommandSpec>> = std::sync::OnceLock::new();
INDEX.get_or_init(|| index_by_id(command_specs())).get(id).copied().or_else(|| plugin::find_spec(id))
}
/// `specs` by id. An id that more than one spec has names the first of them, as a search of
/// `specs` in order finds.
pub(crate) fn index_by_id(specs: &[CommandSpec]) -> std::collections::HashMap<&'static str, &CommandSpec> {
let mut index = std::collections::HashMap::with_capacity(specs.len());
for spec in specs {
index.entry(spec.id).or_insert(spec);
}
index
}
/// Runs command `spec`'s implementation with `p`. A plug-in command's runs the plug-in
@@ -826,9 +837,11 @@ pub use addons::{fold_source, print_hidden};
/// 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 edit::{Unrecorded, settle_interaction, typing_in_progress};
pub(crate) use object::bounds_rewrite;
pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned};
/// The rules `object.scale`, `object.reflect` and `object.shear` check their params with.
pub use object::{reflect_axis, scale_factors, shear_tangent};
pub use plugin_call::{Location, ParamsPlace, key_location, location_in, location_keys};
pub use select::SIMILAR;
pub(crate) use vectorcraft_doc::range::parse_range;
+4 -1
View File
@@ -3,11 +3,13 @@
//! 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, Expand Dashes
//! into Paths, Trim at Crossings ([`trim`]), Common Tangents ([`tangents`]) and Tangent Circle
//! into Paths, Trim at Crossings ([`trim`]), Smooth Bridge ([`bridge`]), Common Tangents
//! ([`tangents`]) and Tangent Circle
//! ([`tangent_circle`]).
//! Its tools, panels and submenu (Object › Plug-ins › Path Precision Tools) are the tools crate's
//! and the UI's.
mod bridge;
mod corners;
#[cfg(test)]
mod effect_tests;
@@ -183,6 +185,7 @@ pub fn specs() -> Vec<CommandSpec> {
v.extend(corners::specs());
v.extend(shared_edge::specs());
v.extend(trim::specs());
v.extend(bridge::specs());
v.extend(tangent_circle::specs());
v.extend(tangents::specs());
v
@@ -0,0 +1,95 @@
//! Smooth Bridge: two selected circles joined into one outline by two concave arcs that touch both
//! circles, replacing the circles or added above them.
use serde_json::{Value, json};
use vectorcraft_doc::{NodeId, NodeKind};
use vectorcraft_geom::PathData;
use vectorcraft_pathops::addons::pathtools as pt;
use super::super::super::pathops::{Beside, remove_each};
use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_selection, switch_or};
use super::given;
use crate::{EngineError, Result, Session};
#[cfg(test)]
mod tests;
/// The command, and its undo step's name.
const C: &str = "addon.pathtools.bridge";
const LABEL: &str = "Smooth Bridge";
/// The arcs' radius as a percentage of the smaller circle's radius: by default, and the range.
const RADIUS: f64 = 100.0;
const RADII: (f64, f64) = (1.0, 1000.0);
pub(super) fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"addon.pathtools.bridge",
"Smooth Bridge",
["Object", "Plug-ins", "Path Precision Tools"],
None,
"{radius?: % 1..1000 (100; the radius of the bridge's two arcs as a percentage of the smaller circle's radius: larger makes a wider, gentler bridge), keepOriginals?: bool (false: the outline replaces the two circles, painted as the upper one; true: it goes directly above the upper one and the circles stay), ids?: [id, id] (default: the selection)} join two circles (paths whose outline is a circle, not hidden or locked) into one closed outline: around each circle on its side away from the other, and along two concave arcs, one on each side, that touch both circles so the outline runs on smoothly into them. Overlapping and touching circles are joined too; one circle inside the other, or circles too far apart for the radius (the arcs would not reach both, or would cross), is an error, which suggests a larger radius when one up to 1000% would bridge them. One undo step; the outline is selected → {id}",
has_selection,
bridge
)]
}
fn bridge(s: &mut Session, p: &Value) -> Result<Value> {
let percent = given(p, "radius", Some(RADII), C)?.unwrap_or(RADIUS);
let keep = switch_or(p, "keepOriginals", false, C)?;
let roots = checked_ids_or_selection(s, p, C)?;
let circles: Vec<(NodeId, pt::Circle)> = {
let d = &s.doc()?.doc;
let editable = d.editable();
d.paint_order(roots.iter().copied())
.into_iter()
.filter_map(|id| match &d.node(id)?.kind {
NodeKind::Path { path, guide: false, clipping: false, .. } if editable(id) => Some((id, pt::circle_of(path)?)),
_ => None,
})
.collect()
};
let ([(below, a), (above, b)], 2) = (circles.as_slice(), roots.len()) else {
return Err(bad(C, "select two circles to bridge"));
};
let (below, above) = (*below, *above);
let at = |percent: f64| pt::smooth_bridge(*a, *b, a.radius.min(b.radius) * percent / 100.0);
let outline = match at(percent) {
Ok(sp) => PathData::single(sp),
Err(pt::BridgeError::Inside) => return Err(bad(C, "one circle is inside the other")),
// A larger radius bridges circles a smaller one cannot, so only suggest one that is allowed.
Err(pt::BridgeError::TooFar) if at(RADII.1).is_ok() => {
return Err(bad(C, "the circles are too far apart for this radius: raise the radius"));
}
Err(pt::BridgeError::TooFar) => return Err(bad(C, "the circles are too far apart for this radius")),
Err(pt::BridgeError::Bad) => return Err(bad(C, "select two circles to bridge")),
};
let id = s.edit(LABEL, |d, sel| {
let id = if keep {
// A copy of the upper circle (its appearance) with the outline as its path, right above
// it; the circles stay as they are, live shapes included.
// Fresh ids throughout, its opacity mask's art included.
let upper = d.node(above).cloned().ok_or(EngineError::NoNode(above))?;
let mut n = d.reid(&upper);
if let NodeKind::Path { path, live, .. } = &mut n.kind {
*path = outline;
*live = None;
}
let id = n.id;
let mut beside = Beside::above(d, &[above]);
beside.put(d, above, vec![n])?;
beside.finish(d)?;
id
} else {
// The upper circle becomes the outline (a plain path now) and the lower one goes.
if let Some(NodeKind::Path { path, live, .. }) = d.node_mut(above).map(|n| &mut n.kind) {
*path = outline;
*live = None;
}
remove_each(d, &[below])?;
above
};
sel.set([id]);
Ok(id)
})?;
Ok(json!({ "id": id.0 }))
}
@@ -0,0 +1,184 @@
//! Smooth Bridge: the outline in place of the circles or above them, one undo step, the radius,
//! and what it refuses.
use serde_json::{Value, json};
use vectorcraft_doc::{NodeId, NodeKind};
use vectorcraft_geom::kurbo::Shape;
use crate::Session;
const BRIDGE: &str = "addon.pathtools.bridge";
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
s
}
/// A circle about (`x`, `y`) with radius `r`.
fn circle(s: &mut Session, x: f64, y: f64, r: f64) -> NodeId {
let id = s.execute("shape.ellipse", &json!({"x": x - r, "y": y - r, "width": 2.0 * r, "height": 2.0 * r})).unwrap()["id"].as_u64().unwrap();
NodeId(id)
}
fn select(s: &mut Session, ids: &[NodeId]) {
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
}
fn top_level(s: &Session) -> Vec<NodeId> {
s.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id).collect()
}
fn area(s: &Session, id: NodeId) -> f64 {
s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().to_bezpath().area().abs()
}
fn err(s: &mut Session, p: Value) -> String {
s.execute(BRIDGE, &p).unwrap_err().to_string()
}
#[test]
fn two_circles_become_one_outline_in_the_upper_ones_place() {
let mut s = session();
let a = circle(&mut s, 100.0, 100.0, 20.0);
let b = circle(&mut s, 160.0, 100.0, 20.0);
select(&mut s, &[a, b]);
let steps = s.doc().unwrap().history.undo.len();
let r = s.execute(BRIDGE, &json!({})).unwrap();
assert_eq!(r["id"], json!(b.0));
assert_eq!(top_level(&s), [b]);
let d = &s.doc().unwrap().doc;
let NodeKind::Path { path, live, .. } = &d.node(b).unwrap().kind else { panic!("a path") };
assert!(live.is_none(), "a plain path now");
assert!(path.subpaths.len() == 1 && path.subpaths[0].closed);
let bounds = path.bounds().unwrap();
assert!((bounds.x0 - 80.0).abs() < 1e-2 && (bounds.x1 - 180.0).abs() < 1e-2 && (bounds.height() - 40.0).abs() < 1e-2, "{bounds:?}");
// Both circles and the bridge between them: more than the two circles' area.
assert!(area(&s, b) > 2.0 * std::f64::consts::PI * 400.0);
assert_eq!(s.doc().unwrap().selection.objects.to_vec(), [b]);
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "one undo step");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(top_level(&s), [a, b]);
assert!(matches!(&s.doc().unwrap().doc.node(b).unwrap().kind, NodeKind::Path { live: Some(_), .. }), "the circle is back as it was");
}
#[test]
fn keep_originals_adds_the_outline_above_the_upper_circle() {
let mut s = session();
let a = circle(&mut s, 100.0, 100.0, 30.0);
let b = circle(&mut s, 170.0, 100.0, 10.0);
let c = circle(&mut s, 300.0, 250.0, 5.0);
s.execute("paint.setFill", &json!({"ids": [b.0], "color": "#00ff00"})).unwrap();
let steps = s.doc().unwrap().history.undo.len();
let id = NodeId(s.execute(BRIDGE, &json!({"ids": [b.0, a.0], "keepOriginals": true, "radius": 400})).unwrap()["id"].as_u64().unwrap());
assert_eq!(top_level(&s), [a, b, id, c]);
let d = &s.doc().unwrap().doc;
assert_eq!(d.node(id).unwrap().appearance, d.node(b).unwrap().appearance, "painted as the upper circle");
assert!(matches!(&d.node(a).unwrap().kind, NodeKind::Path { live: Some(_), .. }), "the circles stay as they are");
assert!(matches!(&d.node(b).unwrap().kind, NodeKind::Path { live: Some(_), .. }));
let bounds = d.node(id).unwrap().path_data().unwrap().bounds().unwrap();
assert!((bounds.x0 - 70.0).abs() < 1e-2 && (bounds.x1 - 180.0).abs() < 1e-2 && (bounds.y0 - 70.0).abs() < 1e-2, "{bounds:?}");
assert_eq!(s.doc().unwrap().selection.objects.to_vec(), [id]);
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1);
}
#[test]
fn a_kept_outline_gets_its_own_mask_art() {
let mut s = session();
let a = circle(&mut s, 100.0, 100.0, 20.0);
let b = circle(&mut s, 150.0, 100.0, 20.0);
let m = NodeId(s.execute("shape.rectangle", &json!({"x": 130, "y": 80, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap());
s.execute("transparency.makeOpacityMask", &json!({"ids": [b.0, m.0]})).unwrap();
let id = NodeId(s.execute(BRIDGE, &json!({"ids": [a.0, b.0], "keepOriginals": true})).unwrap()["id"].as_u64().unwrap());
let d = &s.doc().unwrap().doc;
let art = |n: NodeId| d.node(n).unwrap().extras().mask.as_deref().map(|m| m.art.id);
let (kept, copied) = (art(b).unwrap(), art(id).unwrap());
assert_ne!(kept, copied, "the outline's mask art has ids of its own");
}
#[test]
fn a_larger_radius_makes_a_wider_bridge() {
let area_at = |radius: f64| {
let mut s = session();
let a = circle(&mut s, 100.0, 100.0, 20.0);
let b = circle(&mut s, 150.0, 100.0, 15.0);
let id = NodeId(s.execute(BRIDGE, &json!({"ids": [a.0, b.0], "radius": radius})).unwrap()["id"].as_u64().unwrap());
area(&s, id)
};
let (default, wider, widest) = (area_at(100.0), area_at(200.0), area_at(400.0));
assert!(default < wider && wider < widest, "{default} {wider} {widest}");
let (narrow, default, wide) = (area_at(65.0), default, area_at(300.0));
assert!(narrow < default && default < wide, "{narrow} {default} {wide}");
// The default is 100%: the smaller circle's radius.
let mut s = session();
let a = circle(&mut s, 100.0, 100.0, 20.0);
let b = circle(&mut s, 150.0, 100.0, 15.0);
let id = NodeId(s.execute(BRIDGE, &json!({"ids": [a.0, b.0]})).unwrap()["id"].as_u64().unwrap());
assert!((area(&s, id) - default).abs() < 1e-9);
}
#[test]
fn overlapping_and_touching_circles_are_joined() {
for (gap, radius) in [(-15.0, 50.0), (0.0, 50.0), (0.0, 1.0)] {
let mut s = session();
let a = circle(&mut s, 100.0, 100.0, 20.0);
let b = circle(&mut s, 140.0 + gap, 100.0, 20.0);
let id = NodeId(s.execute(BRIDGE, &json!({"ids": [a.0, b.0], "radius": radius})).unwrap()["id"].as_u64().unwrap());
assert_eq!(top_level(&s), [id], "gap {gap}");
}
// Unequal overlapping circles at every radius, the largest included.
for radius in [1.0, 100.0, 300.0, 1000.0] {
let mut s = session();
let a = circle(&mut s, 100.0, 100.0, 10.0);
let b = circle(&mut s, 125.0, 100.0, 30.0);
let id = NodeId(s.execute(BRIDGE, &json!({"ids": [a.0, b.0], "radius": radius})).unwrap()["id"].as_u64().unwrap());
assert_eq!(top_level(&s), [id], "radius {radius}");
}
}
#[test]
fn far_apart_nested_and_other_objects_are_refused() {
let mut s = session();
let a = circle(&mut s, 50.0, 100.0, 10.0);
let far = circle(&mut s, 250.0, 100.0, 10.0);
let near = circle(&mut s, 110.0, 100.0, 10.0);
let inner = circle(&mut s, 52.0, 100.0, 4.0);
let square = NodeId(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap());
let oval = NodeId(s.execute("shape.ellipse", &json!({"x": 300, "y": 0, "width": 40, "height": 20})).unwrap()["id"].as_u64().unwrap());
let before = top_level(&s);
let steps = s.doc().unwrap().history.undo.len();
// 60 pt apart: the default radius (10 pt) cannot reach, the largest (100 pt) can.
assert!(err(&mut s, json!({"ids": [a.0, near.0]})).ends_with("too far apart for this radius: raise the radius"));
assert!(s.execute(BRIDGE, &json!({"ids": [a.0, near.0], "radius": 1000})).is_ok());
s.execute("edit.undo", &json!({})).unwrap();
// 200 pt apart even the largest radius (1000%, 100 pt) closes the neck: it stays open only above
// ((200 / 2)² − 10²) / (2 × 10) = 495 pt. No larger radius is suggested.
for radius in [100, 1000] {
let e = err(&mut s, json!({"ids": [a.0, far.0], "radius": radius}));
assert!(e.ends_with("the circles are too far apart for this radius"), "{e}");
}
assert!(err(&mut s, json!({"ids": [a.0, inner.0]})).contains("one circle is inside the other"));
for ids in [json!([a.0, square.0]), json!([a.0, oval.0]), json!([a.0]), json!([a.0, far.0, inner.0])] {
assert!(err(&mut s, json!({ "ids": ids })).contains("select two circles to bridge"), "{ids}");
}
assert!(err(&mut s, json!({"ids": [a.0, far.0], "radius": 0.5})).contains("`radius` must be from 1 to 1000"));
assert!(err(&mut s, json!({"ids": [a.0, far.0], "radius": 1001})).contains("`radius`"));
assert!(err(&mut s, json!({"ids": [a.0, far.0], "radius": "big"})).contains("`radius` must be a number"));
assert!(err(&mut s, json!({"ids": [a.0, far.0], "keepOriginals": "yes"})).contains("`keepOriginals` must be true or false"));
assert_eq!(top_level(&s), before);
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "nothing changed, no undo step");
}
#[test]
fn locked_and_hidden_circles_are_not_bridged() {
let mut s = session();
let a = circle(&mut s, 100.0, 100.0, 20.0);
let b = circle(&mut s, 150.0, 100.0, 20.0);
select(&mut s, &[b]);
s.execute("object.lock", &json!({})).unwrap();
assert!(err(&mut s, json!({"ids": [a.0, b.0]})).contains("select two circles to bridge"));
s.execute("object.unlockAll", &json!({})).unwrap();
select(&mut s, &[a]);
s.execute("object.hide", &json!({})).unwrap();
assert!(err(&mut s, json!({"ids": [a.0, b.0]})).contains("select two circles to bridge"));
}
+3 -3
View File
@@ -165,7 +165,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Brush Options…",
[],
None,
"{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180° (counter-clockwise from level), roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180° (counter-clockwise), modes: [fixed|random|pressure|tilt|bearing|rotation for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°), rotation_relative_to_path. art: width 1..1000%, width_mode: null (fixed)|pressure|tilt|bearing|rotation, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest; tilt: width with the pen lying flat to width_max upright; bearing and rotation: width at −180° to width_max at 180°; half way on a stroke drawn without that input), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art (drawn as the corner that joins a side tile on its right to one below it) or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}",
"{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180° (counter-clockwise from level), roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180° (counter-clockwise), modes: [fixed|random|pressure|tilt|bearing|rotation for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°), rotation_relative_to_path, hue_jitter 0..180° (each copy turns the hue of its solid colors, after the colorization, by its own amount up to this far either way, the same on every redraw; colors without a hue stay; 0: off). art: width 1..1000%, width_mode: null (fixed)|pressure|tilt|bearing|rotation, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest; tilt: width with the pen lying flat to width_max upright; bearing and rotation: width at −180° to width_max at 180°; half way on a stroke drawn without that input), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art (drawn as the corner that joins a side tile on its right to one below it) or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}",
has_doc,
brush_options
),
@@ -211,7 +211,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), alignToPixelGrid?: bool (default false; Symbol Options › Align to Pixel Grid)} 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; alignToPixelGrid keeps the symbol's instances on the pixel grid as symbol.options describes → {name, id, registration, exportType, nineSlice, type, alignToPixelGrid}",
"{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), alignToPixelGrid?: bool (default false; Symbol Options › Align to Pixel Grid), keepArt?: false} make a symbol from the selection and replace it with an instance, or with keepArt: true leave the selection as ordinary art where it is, still selected, with id null; a frame of threaded text in the selection that becomes an instance 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; alignToPixelGrid keeps the symbol's instances on the pixel grid as symbol.options describes → {name, id, registration, exportType, nineSlice, type, alignToPixelGrid}",
has_selection,
symbol_new
),
@@ -265,7 +265,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Redefine Symbol",
[],
None,
"{name, ids?|id?} replace the symbol's art with the selection (instances update, keeping their appearance changes to the objects at paths the new art still has; the selection becomes an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds) → {name, id}",
"{name, ids?|id?, keepArt?: false} replace the symbol's art with the selection (instances update, keeping their appearance changes to the objects at paths the new art still has; the selection becomes an instance, or with keepArt: true stays ordinary art where it is, still selected, and id is null; a frame of threaded text in the selection that becomes an instance leaves its thread with the text it shows, which the symbol's art holds; art that holds an instance of the symbol (opacity masks included), directly or through the symbols it nests, is refused) → {name, id}",
has_selection,
symbol_update
),
+6 -1
View File
@@ -32,7 +32,12 @@ pub(super) fn brush_list(s: &mut Session, _: &Value) -> Result<Value> {
pub(super) fn brush_get(s: &mut Session, p: &Value) -> Result<Value> {
let name = name_param(p, "brush.get")?;
let b = brush::find(&s.doc()?.doc, name).ok_or_else(|| EngineError::Other(format!("no brush named `{name}`")))?;
Ok(serde_json::to_value(b).unwrap_or_default())
let mut v = serde_json::to_value(&b).unwrap_or_default();
// A scatter brush saves its hue jitter only when it is not 0; brush.get shows it either way.
if let (BrushKind::Scatter(sc), Some(o)) = (&b.kind, v.as_object_mut()) {
o.entry("hue_jitter").or_insert(json!(sc.hue_jitter));
}
Ok(v)
}
/// The art `brush.new` takes from `ids` or `id`, else from the selection ([`selection_art`]).
+33 -4
View File
@@ -253,6 +253,9 @@ pub(super) fn symbol_new(s: &mut Session, p: &Value) -> Result<Value> {
let nine = nine_slice_param(p, C, None)?.flatten();
let dynamic = type_param(p, C)?.unwrap_or(false);
let pixel = pixel_grid_param(p, C)?.unwrap_or(false);
// `keepArt` leaves the art as ordinary art instead of replacing it with an instance.
let keep_art = switch_or(p, "keepArt", false, C)?;
let iso = s.doc()?.isolation;
// Keep the art where it was: the geometric centre stays at `c`, whatever the registration is.
let place = place_xf(c + reg.offset_from_center(size.0, size.1), size, reg);
let id = s.edit("New Symbol", |d, sel| {
@@ -264,13 +267,20 @@ pub(super) fn symbol_new(s: &mut Session, p: &Value) -> Result<Value> {
d.set_symbol_export_type(&name, export);
d.set_symbol_nine_slice(&name, nine);
d.set_symbol_pixel_aligned(&name, pixel);
if keep_art {
// The art stays where it is and stays selected, apart from art that is hidden or
// locked, in a hidden or locked group or layer, or on a locked artboard.
let locks = d.locked_artboards();
sel.set(ids.iter().copied().filter(|i| crate::cmd::select::is_selectable(d, iso, &locks, *i)));
return Ok(None);
}
let id = instance_in_place(d, &ids, &name, place)?;
sel.set([id]);
Ok(id)
Ok(Some(id))
})?;
Ok(json!({
"name": name,
"id": id.0,
"id": id.map(|i| i.0),
"registration": reg.0,
"exportType": export.id(),
"nineSlice": nine.map_or(Value::Null, SymbolNineSlice::to_value),
@@ -612,6 +622,8 @@ pub(super) fn symbol_update(s: &mut Session, p: &Value) -> Result<Value> {
}
// Redefining the symbol being edited leaves symbol editing mode in the same step.
let session = s.doc()?.doc.symbol_edit.clone().filter(|e| e.symbol == name);
// `keepArt` leaves the art as ordinary art instead of replacing it with an instance.
let keep_art = switch_or(p, "keepArt", false, C)?;
if session.is_some() {
crate::cmd::settle_interaction(s)?;
s.end_text_edit();
@@ -625,10 +637,20 @@ pub(super) fn symbol_update(s: &mut Session, p: &Value) -> Result<Value> {
}
}
let mut art = selection_art(s, p)?.ok_or_else(|| EngineError::Other("nothing selected".into()))?;
// Nor can art that holds an instance of it, directly or through the symbols it nests.
if crate::cmd::symboledit::holds_symbol(&s.doc()?.doc, &art, &name, &mut Default::default()) {
return Err(EngineError::Other("a symbol can't hold an instance of itself".into()));
}
crate::cmd::threads::keep_shown_text(&s.doc()?.doc, &mut art);
let (art, size, c) = normalize(art)?;
let old = natural_size(&s.doc()?.doc, &name);
let editing = session.is_some();
// The isolation the kept art is selected in: the one from before symbol editing mode when
// the step leaves it.
let iso = match &session {
Some(se) => se.back_isolation,
None => s.doc()?.isolation,
};
let id = s.edit("Redefine Symbol", |d, sel| {
if editing {
crate::cmd::symboledit::finish(d, sel);
@@ -647,15 +669,22 @@ pub(super) fn symbol_update(s: &mut Session, p: &Value) -> Result<Value> {
}
// Each instance keeps its appearance changes to the objects the new art still has.
fit_overrides(d, &instances);
if keep_art {
// The art stays where it is and stays selected, apart from art that is hidden or
// locked, in a hidden or locked group or layer, or on a locked artboard.
let locks = d.locked_artboards();
sel.set(ids.iter().copied().filter(|i| crate::cmd::select::is_selectable(d, iso, &locks, *i)));
return Ok(None);
}
let reg = d.symbol_registration(&name);
let id = instance_in_place(d, &ids, &name, place_xf(c + reg.offset_from_center(size.0, size.1), size, reg))?;
sel.set([id]);
Ok(id)
Ok(Some(id))
})?;
if let Some(se) = &session {
crate::cmd::symboledit::leave_editing(s, se)?;
}
Ok(json!({ "name": name, "id": id.0 }))
Ok(json!({ "name": name, "id": id.map(|i| i.0) }))
}
/// How many levels of nested instances Delete Symbol expands before it gives up.
+8 -1
View File
@@ -121,7 +121,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Separations Preview",
[],
None,
"{on?: bool, plates?: [names], toggle?: plate, only?: plate} Separations Preview: show the chosen plates (one plate = greyscale ink coverage) → {on, plates: [{name, spot, visible, rgb}]}",
"{on?: bool, plates?: [names], toggle?: plate, only?: plate, soloToggle?: plate (only that plate, or every plate when it is the only one shown)} Separations Preview: show the chosen plates (one plate = grayscale ink coverage) → {on, plates: [{name, spot, visible, rgb}]}",
always,
separations
),
@@ -1055,6 +1055,13 @@ fn separations(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(n) = text_param(p, "only", C)? {
v.separations = Some(vec![check(n)?]);
}
// The panel's Alt-click on a plate's eye: that plate alone, or every plate when it already
// shows alone among the active document's plates.
if let Some(n) = text_param(p, "soloToggle", C)? {
let n = check(n)?;
let alone = v.separations.as_ref().is_some_and(|vis| all.iter().filter(|a| vis.contains(a)).eq([&n]));
v.separations = Some(if alone { all.clone() } else { vec![n] });
}
if let Some(n) = text_param(p, "toggle", C)? {
let n = check(n)?;
let vis = v.separations.get_or_insert_with(|| all.clone());
+56 -33
View File
@@ -62,7 +62,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Circle Through Points",
[],
None,
"{points?: [[x, y], [x, y], [x, y]] (left out: the three selected anchor points, where a path selected whole counts all its anchors and selected segments' ends do not count)} → {id, cx, cy, radius}: a circle with the current paint whose edge passes through the three points, not pixel-aligned even while Align New Objects to Pixel Grid is on; two points that are the same or three on one line are an error, and nothing is drawn",
"{points?: [[x, y], [x, y]] or [[x, y], [x, y], [x, y]] (two: the ends of a diameter; left out: the two or three selected anchor points, where a path selected whole counts all its anchors and selected segments' ends do not count)} → {id, cx, cy, radius}: a circle with the current paint whose edge passes through the points, not pixel-aligned even while Align New Objects to Pixel Grid is on; two points that are the same, three on one line, or a circle reaching past the canvas are an error, and nothing is drawn",
has_doc,
circle_through_points
),
@@ -126,7 +126,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Create Text",
[],
None,
"{x, y, text, rotation?: deg clockwise about x, y (0: level), vertical?: bool = false, size?: pt 0.1..1296 (outside it: an error, and no type is made), font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (as text.areaOptions)}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on",
"{x, y, text, rotation?: deg clockwise about x, y (0: level), vertical?: bool = false, size?: pt 0.1..1296 (outside it: an error, and no type is made), font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused; size, font, style and color left out come from [Normal Character Style], the defaults unless the document redefined it), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (as text.areaOptions)}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on",
has_doc,
text_create
),
@@ -413,16 +413,16 @@ fn ellipse(s: &mut Session, p: &Value) -> Result<Value> {
add_art_turned(s, "Ellipse", path_kind(live.to_path(), Some(live)), rotation)
}
/// A live ellipse whose edge passes through three points: `points`, or the three selected anchor
/// points ([`selected_anchor_points`]). One undo step, named as an Ellipse tool drag is.
/// A live ellipse whose edge passes through two or three points: `points`, or the two or three
/// selected anchor points ([`selected_anchor_points`]). Two points are the ends of a diameter. One
/// undo step, named as an Ellipse tool drag is.
fn circle_through_points(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "shape.circleThroughPoints";
let points = match p.get("points").filter(|v| !v.is_null()) {
Some(v) => three_points(v).ok_or_else(|| bad(C, "`points` must be three [x, y] pairs of numbers"))?,
None => selected_anchor_points(s)?.ok_or_else(|| bad(C, "direct-select three anchor points, or give `points`"))?,
Some(v) => two_or_three_points(v).ok_or_else(|| bad(C, "`points` must be two or three [x, y] pairs of numbers"))?,
None => selected_anchor_points(s)?.ok_or_else(|| bad(C, "direct-select two or three anchor points, or give `points`"))?,
};
let [a, b, c] = points;
let (center, radius) = shapes::circle_through(a, b, c)
let (center, radius) = shapes::circle_through_points(&points)
.ok_or_else(|| bad(C, "no circle passes through these points: two are the same or all three lie on one line"))?;
let r = Rect::new(center.x - radius, center.y - radius, center.x + radius, center.y + radius);
let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: Affine::translate(r.origin().to_vec2()) };
@@ -434,24 +434,25 @@ fn circle_through_points(s: &mut Session, p: &Value) -> Result<Value> {
Ok(out)
}
/// The three points `[[x, y], [x, y], [x, y]]` holds, each pair two finite numbers.
fn three_points(v: &Value) -> Option<[Point; 3]> {
/// The two or three points `[[x, y], [x, y]]` or `[[x, y], [x, y], [x, y]]` holds, each pair two
/// finite numbers.
fn two_or_three_points(v: &Value) -> Option<Vec<Point>> {
let pair = |v: &Value| match v.as_array().map(Vec::as_slice) {
Some([x, y]) => x.as_f64().zip(y.as_f64()).filter(|(x, y)| x.is_finite() && y.is_finite()).map(|(x, y)| Point::new(x, y)),
_ => None,
};
match v.as_array().map(Vec::as_slice) {
Some([a, b, c]) => Some([pair(a)?, pair(b)?, pair(c)?]),
match v.as_array() {
Some(pairs) if matches!(pairs.len(), 2 | 3) => pairs.iter().map(pair).collect(),
_ => None,
}
}
/// The positions of the selected anchor points, when there are exactly three. They are counted as
/// The positions of the selected anchor points, when there are two or three. They are counted as
/// the other anchor commands count them ([`super::path::anchor_targets`]): a selected path with
/// anchors picked by Direct Selection gives those, and a path selected whole gives all of its own.
/// A selected segment's ends are not selected anchor points, so a selection with segments gives
/// none; so does a selection holding an object that is not a path, or an anchor that is gone.
fn selected_anchor_points(s: &Session) -> Result<Option<[Point; 3]>> {
fn selected_anchor_points(s: &Session) -> Result<Option<Vec<Point>>> {
let st = s.doc()?;
if st.selection.segments.values().any(|set| !set.is_empty()) {
return Ok(None);
@@ -472,10 +473,7 @@ fn selected_anchor_points(s: &Session) -> Result<Option<[Point; 3]>> {
return Ok(None);
}
}
Ok(match points.as_slice() {
&[a, b, c] => Some([a, b, c]),
_ => None,
})
Ok(matches!(points.len(), 2 | 3).then_some(points))
}
/// The whole-number count `p` gives for `key` (`5` or `5.0`), or `default` when it is left out or
@@ -942,7 +940,13 @@ fn text_create(s: &mut Session, p: &Value) -> Result<Value> {
let id = made.get("id").and_then(Value::as_u64).map(NodeId);
let made = super::typecmd::with_bounds(s, id, made);
let mut made = super::typecmd::with_overflow(s, id.as_slice(), made);
if p.get("font").is_some() || p.get("style").is_some() {
// A face from a redefined [Normal Character Style] is checked too, as one given here is.
let normal_face = s
.doc()
.ok()
.and_then(|d| super::textstyles::style_attrs(&d.doc, false, super::textstyles::NORMAL_CHAR))
.is_some_and(|m| m.contains_key("font_family") || m.contains_key("font_style"));
if p.get("font").is_some() || p.get("style").is_some() || normal_face {
let runs = match id.and_then(|i| s.doc().ok()?.doc.node(i)).map(|n| &n.kind) {
Some(NodeKind::Text(t)) => t.runs.iter().flat_map(super::fonts::run_fonts).collect(),
_ => Default::default(),
@@ -970,8 +974,9 @@ pub(crate) fn new_type_para() -> vectorcraft_doc::ParaStyle {
/// The paragraph alignment, leading model and character alignment new type starts with (`t`'s
/// paragraph and runs): `justify` from `p` (else as [`new_type_para`] left it), `leadingModel`
/// and `charAlign` from `p`, else em box top to top and em box centre while the
/// interface is in Japanese (#432), else the Roman baseline for both. Noted in the journal, so a
/// and `charAlign` from `p` (`charAlign` else from a redefined `[Normal Character Style]` that
/// sets it), else em box top to top and em box centre while the interface is in Japanese (#432),
/// else the Roman baseline for both. Noted in the journal, so a
/// replay sets the same whatever the interface.
pub(crate) fn new_type_alignment(s: &mut Session, p: &Value, cmd: &str, t: &mut TextObject) -> Result<()> {
use vectorcraft_doc::{CharAlign, LeadingModel};
@@ -991,7 +996,14 @@ pub(crate) fn new_type_alignment(s: &mut Session, p: &Value, cmd: &str, t: &mut
l
}
};
let align = match super::textedit::char_align_param(p, cmd)? {
// A redefined [Normal Character Style] that sets Character Alignment gives it to new type.
let normal_align = s
.doc()
.ok()
.and_then(|d| super::textstyles::style_attrs(&d.doc, false, super::textstyles::NORMAL_CHAR))
.filter(|m| m.contains_key("charAlign"))
.and(t.runs.first().map(|r| r.style.char_align));
let align = match super::textedit::char_align_param(p, cmd)?.or(normal_align) {
Some(a) => a,
None => {
let a = if japanese { CharAlign::EmBoxCenter } else { CharAlign::RomanBaseline };
@@ -1019,17 +1031,25 @@ pub(crate) fn new_area_fit(s: &Session, p: &Value, c: &str, t: &mut TextObject)
}
/// The character style new type gets: `size`, `font`, `style` and `color` from `p` (an RGB
/// `color` in a CMYK document as [`super::paint::new_color`] stores it), else the defaults,
/// filled as `[Normal Character Style]` is (black unless redefined; never the current fill,
/// #7975), in the document's
/// language. A `size` outside [`super::typecmd::TYPE_SIZES`] is an error.
/// `color` in a CMYK document as [`super::paint::new_color`] stores it), else
/// `[Normal Character Style]`'s (the default font, size and black fill unless redefined;
/// never the current fill, #7975), in the style's language, else the document's. A `size` outside
/// [`super::typecmd::TYPE_SIZES`] is an error.
pub(crate) fn new_type_style(s: &Session, p: &Value, cmd: &str) -> Result<CharStyle> {
let mut style = CharStyle::default();
let mut style = s.doc().map_or_else(|_| CharStyle::default(), |d| super::textstyles::normal_char_style(&d.doc));
if let Some(sz) = p.get("size").and_then(Value::as_f64) {
style.size = super::typecmd::given_type_size(sz, cmd)?;
}
if str_param(p, "font").is_some() || str_param(p, "style").is_some() {
// A face given to the command takes its own version and axis settings, as a font change
// does, not those [Normal Character Style] gave another face.
style.font_version = None;
style.font_axes.clear();
}
if let Some(f) = str_param(p, "font") {
style.font_family = f.to_string();
// A family alone starts in Regular, whatever style [Normal Character Style] has.
style.font_style = CharStyle::default().font_style;
}
if let Some(f) = str_param(p, "style") {
style.font_style = f.to_string();
@@ -1039,12 +1059,15 @@ pub(crate) fn new_type_style(s: &Session, p: &Value, cmd: &str) -> Result<CharSt
}
style.fill = match p.get("color").and_then(color_value) {
Some(c) => vectorcraft_color::Paint::solid(super::paint::new_color(s, p, c)),
None => s.doc().map_or_else(|_| CharStyle::default().fill, |d| super::textstyles::normal_char_fill(&d.doc)),
None => style.fill,
};
// In the language Document Setup chose, else Preferences › Hyphenation › Default Language; none
// for the default. Type already in a document keeps its own.
let chosen = |name: &str| vectorcraft_doc::setup::char_language(name).ok().flatten();
let document = s.doc().ok().and_then(|d| chosen(&d.doc.setup.language));
style.language = document.or_else(|| chosen(&s.prefs.hyphenation_language)).map(str::to_string);
// In the language a redefined [Normal Character Style] gives, else the one Document Setup chose,
// else Preferences › Hyphenation › Default Language; none for the default. Type already in a
// document keeps its own.
if style.language.is_none() {
let chosen = |name: &str| vectorcraft_doc::setup::char_language(name).ok().flatten();
let document = s.doc().ok().and_then(|d| chosen(&d.doc.setup.language));
style.language = document.or_else(|| chosen(&s.prefs.hyphenation_language)).map(str::to_string);
}
Ok(style)
}
+3 -10
View File
@@ -3,10 +3,8 @@ use super::{CommandSpec, EngineError, Result, Session, cmd, has_doc};
use serde_json::{Value, json};
use std::sync::Arc;
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::dimension::{
ArrowStyle, Dimension, DimensionMode, DimensionOptions, DimensionSource, LineType, Orientation, TextAlignment, TextPosition,
};
use vectorcraft_doc::{Appearance, Arrowhead, CharStyle, ColorMode, Dash, Document, Node, NodeId, NodeKind, TextObject};
use vectorcraft_doc::dimension::{Dimension, DimensionMode, DimensionOptions, DimensionSource, LineType, Orientation, TextAlignment, TextPosition};
use vectorcraft_doc::{Appearance, CharStyle, ColorMode, Dash, Document, Node, NodeId, NodeKind, TextObject};
use vectorcraft_geom::{Affine, BezPath, PathData, Point, Vec2};
pub fn specs() -> Vec<CommandSpec> {
@@ -567,12 +565,7 @@ fn appearance(o: &DimensionOptions, mode: ColorMode, ext: bool, arrows: bool) ->
LineType::Solid => None,
};
if arrows {
let head = match o.arrow_style {
ArrowStyle::Filled => Some(Arrowhead::Triangle),
ArrowStyle::Open => Some(Arrowhead::TriangleOpen),
ArrowStyle::Tick => Some(Arrowhead::Slash),
ArrowStyle::None => None,
};
let head = o.arrow_style.arrowhead();
st.start_arrow = head.clone();
st.end_arrow = head;
st.arrow_scale = (o.arrow_scale, o.arrow_scale);
+88 -12
View File
@@ -16,7 +16,7 @@ use vectorcraft_tools::distort::{PinSet, arap, collect_points, mesh_for, project
use super::edit::{duplicate_in, outermost, refuse_symbol_part, selected_roots};
use super::{
CommandSpec, Result, Session, bad, check_numbers, check_switches, cmd, f64_or, f64_req, finite_numbers, has_doc, has_selection, matrix_param,
named_id, named_ids, number_or, object_param, ok, point_indices, point_param, str_param, switch_or, targets,
named_id, named_ids, number_or, object_param, ok, point_indices, point_param, str_param, switch_or, targets, text_param, u64_req,
};
use crate::EngineError;
@@ -35,7 +35,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Width Point",
[],
None,
"{id, t: 0..1 (fraction of the path length), left, right: side widths in pt, index?: width point to edit or move, adjustAdjoining?: bool (the nearest points either side change their widths in proportion, using the sampled widths for a new point)} → {index}. Without index a point already at t is replaced; a point moved onto another one's t joins it as a discontinuous point (on the side it came from), so the width steps there. Creates a uniform profile first if needed",
"{id, t: 0..1 (fraction of the path length), left, right: side widths in pt, index?: width point to edit or move, adjustAdjoining?: bool (the nearest points either side change their widths in proportion, using the sampled widths for a new point), outIndex?, outLeft, outRight: the outgoing half of the discontinuous point whose incoming half is index, single?: \"incoming\" | \"outgoing\"} → {index}. Without index a point already at t is replaced; a point moved onto another one's t joins it as a discontinuous point (on the side it came from), so the width steps there. With outIndex both halves change in one step and keep their place (t must be theirs); adjustAdjoining then changes the nearest point before from the incoming half and the nearest point after from the outgoing half. single keeps only that half's widths, leaving one continuous point. Creates a uniform profile first if needed",
has_doc,
width_point_set
),
@@ -214,6 +214,15 @@ fn uniform() -> WidthProfile {
/// Width points closer than this (in t) are at the same place: a discontinuous point.
const SAME_T: f64 = 1e-6;
/// The outgoing half of the discontinuous width point whose incoming half is point `a`: point `a`
/// and the next one are the two halves when they are the only points within 1e-6 (in t) of `a`'s
/// place. None when `a` is out of range or not such an incoming half.
pub fn width_point_pair(points: &[(f64, f64, f64)], a: usize) -> Option<usize> {
let t = points.get(a)?.0;
let at: Vec<usize> = (0..points.len()).filter(|i| (points[*i].0 - t).abs() <= SAME_T).collect();
(at == [a, a + 1]).then_some(a + 1)
}
/// The stroke of `id` that width point commands edit (a compound path's for its members).
fn stroke_mut(d: &mut Document, id: NodeId) -> Result<&mut vectorcraft_doc::StrokeLayer> {
let id = stroke_owner(d, id);
@@ -265,9 +274,9 @@ fn place(points: &mut Vec<(f64, f64, f64)>, mut pt: (f64, f64, f64), from_below:
}
/// Adjust Adjoining Width Points: point `i` changes from `old` to `new` widths, and the nearest
/// points at other positions either side change in proportion (by the same amount from zero).
fn adjust_adjoining(points: &mut [(f64, f64, f64)], i: usize, old: (f64, f64, f64), new: (f64, f64, f64)) {
let t = points[i].0;
/// points farther than [`SAME_T`] from place `t` on the sides `sides` names (before, after)
/// change in proportion (by the same amount from zero).
fn adjust_adjoining(points: &mut [(f64, f64, f64)], i: usize, t: f64, old: (f64, f64, f64), new: (f64, f64, f64), sides: [bool; 2]) {
let scale = |v: f64, o: f64, n: f64| {
let width = if o > 1e-9 {
let product = v * n;
@@ -284,8 +293,8 @@ fn adjust_adjoining(points: &mut [(f64, f64, f64)], i: usize, old: (f64, f64, f6
};
width.max(0.0)
};
let before = (0..i).rev().find(|j| (points[*j].0 - t).abs() > SAME_T);
let after = (i + 1..points.len()).find(|j| (points[*j].0 - t).abs() > SAME_T);
let before = (0..i).rev().find(|j| (points[*j].0 - t).abs() > SAME_T).filter(|_| sides[0]);
let after = (i + 1..points.len()).find(|j| (points[*j].0 - t).abs() > SAME_T).filter(|_| sides[1]);
for j in before.into_iter().chain(after) {
let q = &mut points[j];
(q.1, q.2) = (scale(q.1, old.1, new.1), scale(q.2, old.2, new.2));
@@ -303,6 +312,46 @@ fn same_points(a: Option<&WidthProfile>, b: Option<&WidthProfile>) -> bool {
}
}
/// Set both halves of the discontinuous point whose incoming half is `i` and outgoing half `j` to
/// the widths of `inc` and `out` (their places are ignored: the point keeps its place). With
/// `single` (`true` for the outgoing half) only that half's widths remain, as one continuous point.
/// With `adjust`, the nearest point before changes with the incoming half and the nearest point after
/// with the outgoing half, once each. → the index of the point (its incoming half).
fn set_pair(
points: &mut Vec<(f64, f64, f64)>,
(i, inc): (usize, (f64, f64, f64)),
(j, out): (usize, (f64, f64, f64)),
adjust: bool,
single: Option<bool>,
) -> Result<usize> {
const C: &str = "stroke.widthPoint.set";
if width_point_pair(points, i) != Some(j) {
return Err(bad(C, "`index` and `outIndex` must be the two halves of one discontinuous width point"));
}
let at = points[i].0;
let (old_in, old_out) = (points[i], points[j]);
if (old_in.0 - inc.0).abs() > SAME_T {
return Err(bad(C, "a discontinuous width point keeps its place"));
}
let (new_in, new_out) = match single {
None => ((old_in.0, inc.1, inc.2), (old_out.0, out.1, out.2)),
Some(false) => ((old_in.0, inc.1, inc.2), (old_in.0, inc.1, inc.2)),
Some(true) => ((old_in.0, out.1, out.2), (old_in.0, out.1, out.2)),
};
// Both halves measure their neighbors from the point's place, so a point within SAME_T of the
// outgoing half but not of that place is the point after the pair.
if adjust {
adjust_adjoining(points, i, at, old_in, new_in, [true, false]);
adjust_adjoining(points, j, at, old_out, new_out, [false, true]);
}
points[i] = new_in;
points[j] = new_out;
if single.is_some() {
points.remove(j);
}
Ok(i)
}
fn width_point_set(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "stroke.widthPoint.set";
let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?;
@@ -312,6 +361,25 @@ fn width_point_set(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(C, "left/right must be non-negative widths"));
}
let adjust = switch_or(p, "adjustAdjoining", false, C)?;
let single = match text_param(p, "single", C)? {
None => None,
Some(side @ ("incoming" | "outgoing")) => Some(side == "outgoing"),
Some(_) => return Err(bad(C, "`single` must be `incoming` or `outgoing`")),
};
// The outgoing half of a discontinuous point: its index and side widths (points).
// `single`, `outLeft` or `outRight` without `outIndex` is refused as a missing `outIndex`.
let out_widths = ["outLeft", "outRight"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null()));
let out = match p.get("outIndex") {
None | Some(Value::Null) if single.is_none() && !out_widths => None,
_ => {
let j = usize::try_from(u64_req(p, "outIndex", C)?).map_err(|_| bad(C, "no such width point"))?;
let (l, r) = (f64_req(p, "outLeft", C)?, f64_req(p, "outRight", C)?);
if !(l.is_finite() && r.is_finite()) || l < 0.0 || r < 0.0 || l.max(r) > 1.0e5 {
return Err(bad(C, "left/right must be non-negative widths"));
}
Some((j, l, r))
}
};
// When the profile comes out as it was, within a rounding error (1e-9), the document and its undo
// history stay as they are.
let mut pos = 0;
@@ -324,11 +392,19 @@ fn width_point_set(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(C, "width factors must be finite"));
}
let mut prof = st.profile.take().unwrap_or_else(uniform);
pos = match point_index(p, &prof, C)? {
Some(i) => {
pos = match (point_index(p, &prof, C)?, out) {
(None, Some(_)) => return Err(bad(C, "missing index")),
(Some(i), Some((j, l, r))) => {
let out = (t, l / half, r / half);
if !out.1.is_finite() || !out.2.is_finite() {
return Err(bad(C, "width factors must be finite"));
}
set_pair(&mut prof.points, (i, pt), (j, out), adjust, single)?
}
(Some(i), None) => {
let old = prof.points[i];
if adjust {
adjust_adjoining(&mut prof.points, i, old, pt);
adjust_adjoining(&mut prof.points, i, old.0, old, pt, [true, true]);
}
if (old.0 - t).abs() <= SAME_T {
// Widths only: it keeps its place (and its side of a discontinuous point).
@@ -339,12 +415,12 @@ fn width_point_set(s: &mut Session, p: &Value) -> Result<Value> {
place(&mut prof.points, pt, old.0 < t)
}
}
None => {
(None, None) => {
let old = adjust.then(|| prof.at(t));
prof.points.retain(|q| (q.0 - t).abs() > SAME_T);
let i = place(&mut prof.points, pt, true);
if let Some((left, right)) = old {
adjust_adjoining(&mut prof.points, i, (t, left, right), pt);
adjust_adjoining(&mut prof.points, i, pt.0, (t, left, right), pt, [true, true]);
}
i
}
+2 -1
View File
@@ -238,7 +238,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Move Guide",
[],
None,
"{index, pos: pt} | {dx?, dy?: pt, copy?: bool} put ruler guide `index` at `pos`, or move the selected guides (vertical ones by dx, horizontal ones by dy); copy leaves them and selects the moved copies",
"{index, pos: pt} | {dx?, dy?: pt, copy?: bool, interpolate?: bool (with art selected too: as object.move's)} put ruler guide `index` at `pos`, or move the selected guides (vertical ones by dx, horizontal ones by dy); copy leaves them and selects the moved copies",
guides_unlocked,
guide_move
),
@@ -990,6 +990,7 @@ pub(crate) fn guide_move(s: &mut Session, p: &Value) -> Result<Value> {
let dx = number_or(p, "dx", 0.0, "guide.move")?;
let dy = number_or(p, "dy", 0.0, "guide.move")?;
let copy = switch_or(p, "copy", false, "guide.move")?;
switch_or(p, "interpolate", false, "guide.move")?;
if !s.doc()?.selection.is_empty() {
let ids = super::edit::selected_roots(s)?;
return super::object::apply_transform(
+1 -1
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, 0..360: 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. A pressure, tilt or rotation outside its range, or a point array of more than six numbers, is an error), 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\" (default) | \"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?: \"end\" (default) | \"start\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); 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. Any other style, extend end or connect end is an error, and nothing changes",
"{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, 0..360: 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. A pressure, tilt or rotation outside its range, or a point array of more than six numbers, is an error), 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\" (default) | \"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?: \"end\" (default) | \"start\"}, connect?: {id, end: \"start\"|\"end\"} (only with extend), redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); 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. Any other style, extend end or connect end, connect without extend, and a connect that names no other path with an open end are errors, a stroke of one point included, and nothing changes",
has_doc,
freehand
),
+24 -19
View File
@@ -213,7 +213,11 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s
let label = if brush || brush_name.is_some() { "Paintbrush" } else { "Pencil" };
let keep_selected = switch_or(p, "keepSelected", true, C)?;
let filled = switch_or(p, "fill", false, C)?;
if let Some(ext) = p.get("extend").filter(|v| !v.is_null()) {
let extend = p.get("extend").filter(|v| !v.is_null());
if extend.is_none() && p.get("connect").is_some_and(|v| !v.is_null()) {
return Err(bad(C, "connect needs extend"));
}
if let Some(ext) = extend {
let id = object_param(ext, "id", C)?.ok_or_else(|| bad(C, "extend needs id"))?;
let at_start = match ext.get("end").filter(|v| !v.is_null()).map(Value::as_str) {
None | Some(Some("end")) => false,
@@ -238,26 +242,9 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s
};
let Some(p0) = pts.first_mut() else { return Err(bad(C, "needs points")) };
*p0 = end;
if pts.len() < 2 {
// No stroke to add: the brush alone changes, when it is not the path's already, and the
// path is selected or deselected as a longer continuation leaves it.
if let Some(name) = brush_name
&& s.doc()?.doc.node(target).and_then(|n| n.appearance.stroke()).is_some_and(|st| st.brush.as_deref() != Some(name))
{
s.edit("Paintbrush", |d, sel| {
set_brush(d, target, name);
if keep_selected {
sel.set([id]);
} else {
sel.remove(id);
}
Ok(())
})?;
}
return Ok(json!({ "id": id.0 }));
}
// A stroke that ends on an open end of another path connects the two: (that path, its last
// open subpath, that subpath starting at the end the stroke ends on, it ends at its end).
// It is checked before a stroke of one point returns, so a bad `connect` is refused there too.
let connect = match p.get("connect").filter(|v| !v.is_null()) {
Some(cn) => {
let other = object_param(cn, "id", C)?.ok_or_else(|| bad(C, "connect needs id"))?;
@@ -280,6 +267,24 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s
}
None => None,
};
if pts.len() < 2 {
// No stroke to add: the brush alone changes, when it is not the path's already, and the
// path is selected or deselected as a longer continuation leaves it.
if let Some(name) = brush_name
&& s.doc()?.doc.node(target).and_then(|n| n.appearance.stroke()).is_some_and(|st| st.brush.as_deref() != Some(name))
{
s.edit("Paintbrush", |d, sel| {
set_brush(d, target, name);
if keep_selected {
sel.set([id]);
} else {
sel.remove(id);
}
Ok(())
})?;
}
return Ok(json!({ "id": id.0 }));
}
// `closed`, when given, says whether the stroke closes the path: the Pencil and the
// Paintbrush send it, by their Close Paths When Ends Are Within and Alt at the release.
// Left out, an extending stroke that ends within four Fidelities of the path's other end
+98 -17
View File
@@ -6,6 +6,7 @@ use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind, RulerMode, Unit};
use vectorcraft_geom::{Affine, Point, Vec2};
use vectorcraft_tools::distort::perspective::{PerspectiveGrid, Plane};
use super::clipboard::SwatchChoices;
use super::{
@@ -713,6 +714,85 @@ pub(crate) fn settle_interaction(s: &mut Session) -> Result<()> {
Ok(())
}
/// The document state that commands also change without an undo step: the perspective grid's view
/// options (whether it shows, Lock Grid, Lock Station Point, Snap to Grid and Show Rulers), its
/// active plane, the grid preferences, the export settings, and the current brush and symbol. Each
/// undo and redo step keeps it as the document on its other side had it
/// ([`crate::HistoryEntry::unrecorded`]).
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct Unrecorded {
grid: vectorcraft_doc::GridPrefs,
export_settings: serde_json::Map<String, Value>,
brush: Option<Value>,
symbol: Option<Value>,
options: [bool; 5],
plane: Plane,
}
impl Unrecorded {
pub(crate) fn of(d: &Document) -> Self {
let g = PerspectiveGrid::current(d);
Unrecorded {
grid: d.grid.clone(),
export_settings: d.export_settings.clone(),
brush: d.unknown.get(vectorcraft_brush::CURRENT_KEY).cloned(),
symbol: d.unknown.get(super::brushsym::CURRENT_SYMBOL).cloned(),
options: [g.visible, g.locked, g.lock_station, g.snap, g.rulers],
plane: g.plane,
}
}
}
/// Undo and redo bring back `d`; `step` is that state as the document on the step's other side had
/// it. A part the step did not change (`d` has it as `step` does) stays as it is in `now`, the
/// document before the undo or redo, since it changed after the step without an undo step. A part
/// the step changed comes back with `d`. A current brush or symbol that `d` does not hold also
/// comes back with `d`. The point Automatic Plane Positioning holds comes back with `d`, and is let go when the
/// active plane kept is not the one it holds.
fn keep_unrecorded(now: &Document, step: &Unrecorded, d: &mut Arc<Document>) {
fn pick<T: Clone + PartialEq>(back: &T, step: &T, now: &T) -> T {
if back == step { now.clone() } else { back.clone() }
}
let back = Unrecorded::of(d);
let cur = Unrecorded::of(now);
let mut want = Unrecorded {
grid: pick(&back.grid, &step.grid, &cur.grid),
export_settings: pick(&back.export_settings, &step.export_settings, &cur.export_settings),
brush: pick(&back.brush, &step.brush, &cur.brush),
symbol: pick(&back.symbol, &step.symbol, &cur.symbol),
options: std::array::from_fn(|i| pick(&back.options[i], &step.options[i], &cur.options[i])),
plane: pick(&back.plane, &step.plane, &cur.plane),
};
if want.brush != back.brush && want.brush.as_ref().and_then(Value::as_str).is_some_and(|n| vectorcraft_brush::find(d, n).is_none()) {
want.brush = back.brush.clone();
}
if want.symbol != back.symbol && want.symbol.as_ref().and_then(Value::as_str).is_some_and(|n| !d.symbols.iter().any(|s| s.name == n)) {
want.symbol = back.symbol.clone();
}
if want == back {
return;
}
let m = Arc::make_mut(d);
for (key, v) in [(vectorcraft_brush::CURRENT_KEY, &want.brush), (super::brushsym::CURRENT_SYMBOL, &want.symbol)] {
match v {
Some(v) => m.unknown.insert(key.into(), v.clone()),
None => m.unknown.remove(key),
};
}
if (want.options, want.plane) != (back.options, back.plane) {
let mut g = PerspectiveGrid::current(m);
[g.visible, g.locked, g.lock_station, g.snap, g.rulers] = want.options;
if g.plane != want.plane {
g.plane = want.plane;
g.inferred = None;
}
g.keep_positioning_valid();
super::distortcmds::store_grid(m, &g);
}
m.grid = want.grid;
m.export_settings = want.export_settings;
}
fn undo(s: &mut Session, _: &Value) -> Result<Value> {
settle_interaction(s)?;
let menu = s.menu.clone();
@@ -723,6 +803,7 @@ fn undo(s: &mut Session, _: &Value) -> Result<Value> {
let editing = st.doc.mask_edit.map(|m| m.layer);
let editing_symbol = st.doc.symbol_edit.clone();
let doc = std::mem::replace(&mut st.doc, e.doc);
keep_unrecorded(&doc, &e.unrecorded, &mut st.doc);
let selection = std::mem::replace(&mut st.selection, Arc::unwrap_or_clone(e.selection));
let selection = shared_selection(selection, st.history.redo.last());
let mut turned = crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs);
@@ -758,6 +839,7 @@ fn redo(s: &mut Session, _: &Value) -> Result<Value> {
let editing = st.doc.mask_edit.map(|m| m.layer);
let editing_symbol = st.doc.symbol_edit.clone();
let doc = std::mem::replace(&mut st.doc, e.doc);
keep_unrecorded(&doc, &e.unrecorded, &mut st.doc);
let selection = std::mem::replace(&mut st.selection, Arc::unwrap_or_clone(e.selection));
let selection = shared_selection(selection, st.history.undo.last());
let mut turned = crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs);
@@ -1076,8 +1158,10 @@ fn cut(s: &mut Session, p: &Value) -> Result<Value> {
/// Select every surviving piece while retaining intentional compound-path structure.
/// `roots` contains the copied targets: whole-object roots are removed in full, while partial paths
/// lose only the copied geometry. An exhausted partial path is removed, along with its compound
/// parent if now empty; layers remain. Returns JSON `null` on success, replacing direct-selection
/// references with surviving object IDs.
/// parent if now empty; a compound left with one member stays a compound path, as after Clear;
/// layers remain. Removed and replaced roots go through one [`super::pathops::Beside`], which
/// rebuilds each parent's children once when the roots are separate. Returns JSON `null` on
/// success, replacing direct-selection references with surviving object IDs.
fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
let st = s.doc()?;
let sel = st.selection.clone();
@@ -1085,13 +1169,18 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
// The selected ruler guides were copied too (#3226): they go in the same undo step.
let gone = selection.guides.clone();
d.retain_guides(selection, |g| !g.id.is_some_and(|id| gone.contains(&id)));
// The compound paths that hold a root; one left with no members goes too.
let compounds: BTreeSet<NodeId> = roots
.iter()
.filter_map(|id| d.parent_of(*id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. }))))
.collect();
let mut survivors = vec![];
let mut pieces = super::pathops::Beside::replacing(d, roots);
for id in roots {
let Some(node) = d.node(*id) else { continue };
let has_direct = sel.anchors.contains_key(id) || sel.segments.contains_key(id);
if !has_direct || node.path_data().is_none() {
remove_leaving_no_empty_compound(d, *id)?;
pieces.put(d, *id, vec![])?;
continue;
}
let original = super::path::deletion_source(d, *id)?;
@@ -1114,12 +1203,14 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
}
subpaths.retain(|sp| sp.anchors.len() >= 2);
if subpaths.is_empty() {
remove_leaving_no_empty_compound(d, *id)?;
pieces.put(d, *id, vec![])?;
} else {
survivors.extend(super::path::replace_deleted_pieces(d, &mut pieces, original, subpaths)?);
}
}
pieces.finish(d)?;
let emptied: Vec<NodeId> = compounds.into_iter().filter(|p| d.node(*p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty()))).collect();
super::pathops::remove_each(d, &emptied)?;
selection.set(survivors);
selection.anchors.clear();
selection.segments.clear();
@@ -1128,19 +1219,6 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
ok()
}
/// Remove object `id`, and the compound path that held it when it was the compound's last member.
/// A compound left with one member stays a compound path, as after Clear.
fn remove_leaving_no_empty_compound(d: &mut Document, id: NodeId) -> Result<()> {
let parent = d.parent_of(id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })));
d.remove(id)?;
if let Some(p) = parent
&& d.node(p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty()))
{
d.remove(p)?;
}
Ok(())
}
fn clear(s: &mut Session, p: &Value) -> Result<Value> {
let guides = switch_or(p, "guides", false, "edit.clear")?;
let explicit = if p.get("ids").is_some() { Some(checked_ids_param(s, p, "ids", "edit.clear")?) } else { None };
@@ -1751,3 +1829,6 @@ pub(crate) fn copy_above(d: &mut Document, roots: &[NodeId], mut change: impl Fn
pub(crate) fn arc_nodes(v: Vec<Node>) -> Vec<Arc<Node>> {
v.into_iter().map(Arc::new).collect()
}
#[cfg(test)]
mod tests;
+343
View File
@@ -0,0 +1,343 @@
//! Cut with direct-selected anchors removes the objects selected whole and the paths it empties
//! through one [`Beside`](super::super::pathops::Beside), and leaves the document, the selection,
//! the clipboard and the undo history exactly as removing each of them on its own does.
use std::collections::BTreeSet;
use std::time::{Duration, Instant};
use serde_json::{Value, json};
use vectorcraft_doc::{Document, NodeId, NodeKind, tree_walks};
use super::*;
use crate::tests_large_edits::{session, square};
/// Cut's removal with every root selected whole or emptied taken out by its own
/// [`Document::remove`], and its compound path removed right after when that left it empty. The
/// tests compare [`cut_direct_selection`] with it.
fn cut_one_at_a_time(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
let st = s.doc()?;
let sel = st.selection.clone();
s.edit("Cut", |d, selection| {
let gone = selection.guides.clone();
d.retain_guides(selection, |g| !g.id.is_some_and(|id| gone.contains(&id)));
let mut survivors = vec![];
let mut pieces = super::super::pathops::Beside::replacing(d, roots);
for id in roots {
let Some(node) = d.node(*id) else { continue };
let has_direct = sel.anchors.contains_key(id) || sel.segments.contains_key(id);
if !has_direct || node.path_data().is_none() {
remove_one(d, *id)?;
continue;
}
let original = super::super::path::deletion_source(d, *id)?;
let seg_refs = sel.segments.get(id);
let anchor_refs = sel.anchors.get(id);
let mut subpaths = Vec::new();
let owned = std::mem::take(&mut super::super::path::path_mut(d, *id)?.subpaths);
for (si, sp) in owned.into_iter().enumerate() {
let cuts = super::super::clipboard::subpath_selected_segments(&sp, si, seg_refs, anchor_refs);
if cuts.is_empty() {
subpaths.push(sp);
} else if seg_refs.is_some_and(|segments| !segments.is_empty()) {
subpaths.extend(super::super::path::without_segments(sp, &cuts));
} else {
let gone: BTreeSet<usize> = anchor_refs.into_iter().flat_map(|refs| super::super::path::subpath_refs(refs, si)).collect();
subpaths.extend(super::super::path::without_anchors(sp, &gone));
}
}
subpaths.retain(|sp| sp.anchors.len() >= 2);
if subpaths.is_empty() {
remove_one(d, *id)?;
} else {
survivors.extend(super::super::path::replace_deleted_pieces(d, &mut pieces, original, subpaths)?);
}
}
pieces.finish(d)?;
selection.set(survivors);
selection.anchors.clear();
selection.segments.clear();
Ok(())
})?;
ok()
}
/// Removes object `id`, and the compound path that held it when it was the compound's last member.
fn remove_one(d: &mut Document, id: NodeId) -> Result<()> {
let parent = d.parent_of(id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })));
d.remove(id)?;
if let Some(p) = parent
&& d.node(p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty()))
{
d.remove(p)?;
}
Ok(())
}
/// Cut as `edit.cut` runs it for a direct selection, with [`cut_one_at_a_time`] in place of
/// [`cut_direct_selection`].
fn reference_cut(s: &mut Session) {
let (direct, roots) = copy_cut_targets(s).unwrap();
assert!(direct, "the selection is a direct selection");
copy(s, &json!({})).unwrap();
cut_one_at_a_time(s, &roots).unwrap();
}
fn run(s: &mut Session, cmd: &str, p: Value) -> Value {
s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}"))
}
/// Selects `whole` as objects, then anchors `anchors` of each path in `partial`.
fn select_direct(s: &mut Session, whole: &[NodeId], partial: &[(NodeId, Value)]) {
run(s, "select.set", json!({"ids": whole.iter().map(|id| id.0).collect::<Vec<_>>()}));
for (id, anchors) in partial {
run(s, "select.anchors", json!({"id": id.0, "anchors": anchors, "mode": "add"}));
}
}
/// The ids of every node of the document, depth first, with the depth of each.
fn tree(d: &Document) -> Vec<(usize, NodeId)> {
fn walk(n: &vectorcraft_doc::Node, depth: usize, out: &mut Vec<(usize, NodeId)>) {
out.push((depth, n.id));
for c in n.children().into_iter().flatten() {
walk(c, depth + 1, out);
}
}
let mut out = vec![];
for l in &d.layers {
walk(l, 0, &mut out);
}
out
}
/// Whether `a` and `b` hold the same document, selection, clipboard and number of undo and redo
/// steps.
fn assert_same(a: &Session, b: &Session, when: &str) {
let (x, y) = (a.doc().unwrap(), b.doc().unwrap());
assert_eq!(tree(&x.doc), tree(&y.doc), "{when}: the tree");
assert!(*x.doc == *y.doc, "{when}: the document");
assert_eq!(x.selection, y.selection, "{when}: the selection");
// Each session's document has its own uid; the clipboard names the one it came from.
assert_eq!(a.clipboard.source_doc.is_some(), b.clipboard.source_doc.is_some(), "{when}: the clipboard's source");
let unsourced = |c: &Clipboard| Clipboard { source_doc: None, ..c.clone() };
assert!(unsourced(&a.clipboard) == unsourced(&b.clipboard), "{when}: the clipboard");
assert_eq!(x.history.undo.len(), y.history.undo.len(), "{when}: the undo steps");
assert_eq!(x.history.redo.len(), y.history.redo.len(), "{when}: the redo steps");
}
/// Runs `edit.cut` on one session that `make` builds and [`reference_cut`] on another, and checks
/// that both hold the same after the Cut, after Undo and after Redo. Returns the first session after
/// the Cut.
fn same_as_one_at_a_time(make: impl Fn() -> Session) -> Session {
let (mut a, mut b) = (make(), make());
let before = a.doc().unwrap().doc.clone();
assert_same(&a, &b, "before");
run(&mut a, "edit.cut", json!({}));
reference_cut(&mut b);
assert_same(&a, &b, "Cut");
let after = a.doc().unwrap().doc.clone();
run(&mut a, "edit.undo", json!({}));
run(&mut b, "edit.undo", json!({}));
assert_same(&a, &b, "Undo");
assert!(*a.doc().unwrap().doc == *before, "Undo gives back the document");
run(&mut a, "edit.redo", json!({}));
run(&mut b, "edit.redo", json!({}));
assert_same(&a, &b, "Redo");
assert!(*a.doc().unwrap().doc == *after, "Redo gives back the Cut");
run(&mut a, "edit.undo", json!({}));
run(&mut a, "edit.redo", json!({}));
a
}
/// A new document; [`rect`] adds squares to it.
fn new_doc() -> Session {
let mut s = Session::new();
run(&mut s, "file.new", json!({"width": 800, "height": 600}));
s
}
/// Adds a 10 pt square to the current layer, 20 pt right of the last one.
fn rect(s: &mut Session) -> NodeId {
let x = 20.0 * s.doc().unwrap().doc.node_count() as f64;
NodeId(run(s, "shape.rectangle", json!({"x": x, "y": 10, "width": 10, "height": 10}))["id"].as_u64().unwrap())
}
/// Makes a compound path of `ids` and returns it with its members in order.
fn compound(s: &mut Session, ids: &[NodeId]) -> (NodeId, Vec<NodeId>) {
run(s, "select.set", json!({"ids": ids.iter().map(|id| id.0).collect::<Vec<_>>()}));
let c = NodeId(run(s, "object.compoundPath.make", json!({}))["id"].as_u64().unwrap());
let members = s.doc().unwrap().doc.node(c).unwrap().children().unwrap().iter().map(|m| m.id).collect();
(c, members)
}
/// Anchors 0 to 2 of a square: Cut leaves it no segment, so it is removed.
fn three_anchors() -> Value {
json!([[0, 0], [0, 1], [0, 2]])
}
/// Anchors 0 and 1 of a square: Cut keeps its other three sides.
fn two_anchors() -> Value {
json!([[0, 0], [0, 1]])
}
/// The compound path whose members are cut one whole and one emptied goes with them; the other
/// compound path keeps its one member left, as a compound path.
#[test]
fn cut_removes_a_compound_whose_members_all_go_and_keeps_one_with_one_member_left() {
let make = || {
let mut s = new_doc();
let first = [(); 2].map(|()| rect(&mut s));
let (gone, gone_members) = compound(&mut s, &first);
let second = [(); 3].map(|()| rect(&mut s));
let (kept, kept_members) = compound(&mut s, &second);
let other = rect(&mut s);
select_direct(
&mut s,
&[gone_members[0], kept_members[0]],
&[(gone_members[1], three_anchors()), (kept_members[1], three_anchors()), (other, two_anchors())],
);
(s, gone, kept, kept_members[2], other)
};
let s = same_as_one_at_a_time(|| make().0);
let (_, gone, kept, left, other) = make();
let d = &s.doc().unwrap().doc;
assert!(d.node(gone).is_none(), "the compound path whose members all went is removed");
let kept = d.node(kept).expect("the compound path with a member left stays");
assert!(matches!(kept.kind, NodeKind::Compound { .. }));
assert_eq!(kept.children().unwrap().iter().map(|m| m.id).collect::<Vec<_>>(), [left]);
assert_eq!(s.doc().unwrap().selection.objects, [other], "the cut square's other sides stay selected");
}
/// Objects inside two groups and on the layer, removed whole, emptied or cut apart between kept
/// siblings, keep the order and ids that removing them one at a time leaves.
#[test]
fn cut_inside_groups_keeps_the_order_and_ids_of_removing_one_at_a_time() {
let make = || {
let mut s = new_doc();
let a = [(); 4].map(|()| rect(&mut s));
run(&mut s, "select.set", json!({"ids": a.iter().map(|id| id.0).collect::<Vec<_>>()}));
run(&mut s, "object.group", json!({}));
let b = [(); 4].map(|()| rect(&mut s));
run(&mut s, "select.set", json!({"ids": b.iter().map(|id| id.0).collect::<Vec<_>>()}));
run(&mut s, "object.group", json!({}));
let c = [(); 4].map(|()| rect(&mut s));
select_direct(
&mut s,
&[a[0], a[2], b[3], c[1]],
&[(a[1], two_anchors()), (b[0], three_anchors()), (b[2], two_anchors()), (c[3], three_anchors())],
);
s
};
let s = same_as_one_at_a_time(make);
assert_eq!(s.doc().unwrap().selection.objects.len(), 2, "the two squares cut apart stay selected");
}
/// Selected ruler guides go with the objects, in the Cut's undo step.
#[test]
fn cut_removes_the_selected_guides_with_the_objects() {
let make = || {
let mut s = new_doc();
let [a, b, c] = [(); 3].map(|()| rect(&mut s));
run(&mut s, "guide.add", json!({"vertical": true, "pos": 30}));
run(&mut s, "guide.add", json!({"vertical": false, "pos": 40}));
select_direct(&mut s, &[a, c], &[(b, two_anchors())]);
run(&mut s, "guide.select", json!({"indexes": [1], "toggle": true}));
s
};
let s = same_as_one_at_a_time(make);
assert_eq!(s.doc().unwrap().doc.ruler_guides().len(), 1, "the selected guide is removed");
assert_eq!(s.clipboard.guides.len(), 1, "the selected guide is on the clipboard");
}
/// Roots that are not separate (one inside another) are removed one at a time, as before.
#[test]
fn cut_of_roots_inside_another_root_matches_removing_one_at_a_time() {
let make = || {
let mut s = new_doc();
let a = [(); 3].map(|()| rect(&mut s));
run(&mut s, "select.set", json!({"ids": a.iter().map(|id| id.0).collect::<Vec<_>>()}));
let group = NodeId(run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap());
let b = rect(&mut s);
select_direct(&mut s, &[group, b], &[(a[1], two_anchors())]);
(s, vec![a[1], group, b])
};
let (mut x, roots) = make();
let (mut y, _) = make();
copy(&mut x, &json!({})).unwrap();
copy(&mut y, &json!({})).unwrap();
cut_direct_selection(&mut x, &roots).unwrap();
cut_one_at_a_time(&mut y, &roots).unwrap();
assert_same(&x, &y, "Cut");
}
/// One layer of 10,000 squares with every fifth of the first 10,000 selected whole (2,000) and
/// anchors 0 and 1 of the square after them picked.
fn many() -> Session {
let mut s = session(10_001, square);
let ids = crate::tests_large_edits::layer(&s, 0);
let whole: Vec<NodeId> = ids.iter().take(10_000).step_by(5).copied().collect();
select_direct(&mut s, &whole, &[(ids[10_000], two_anchors())]);
s
}
/// The tree walks [`tree_walks`] counts while `f` runs on `s`.
fn walks(s: &mut Session, f: impl FnOnce(&mut Session)) -> u64 {
let before = tree_walks();
f(s);
tree_walks() - before
}
/// Cut of 2,000 objects selected whole among 10,000, with a direct selection, walks the document's
/// tree a few times, where removing them one at a time walks it several times for each object.
#[test]
fn direct_selection_cut_of_2000_of_10000_objects_takes_few_tree_walks() {
let s = same_as_one_at_a_time(many);
assert_eq!(crate::tests_large_edits::layer(&s, 0).len(), 8_001);
let (mut a, mut b) = (many(), many());
let batched = walks(&mut a, |s| {
run(s, "edit.cut", json!({}));
});
let one_at_a_time = walks(&mut b, reference_cut);
println!("tree walks: Cut {batched}, one at a time {one_at_a_time}");
assert!(batched <= 64, "Cut walked the document's tree {batched} times");
assert!(one_at_a_time >= 4 * batched.max(1), "one at a time walked it {one_at_a_time} times, Cut {batched}");
}
/// This thread's CPU time, where the system reports it (`/proc/thread-self/schedstat` on Linux).
fn cpu_time() -> Option<Duration> {
let stat = std::fs::read_to_string("/proc/thread-self/schedstat").ok()?;
stat.split_whitespace().next()?.parse().ok().map(Duration::from_nanos)
}
/// The middle of `v`.
fn median(mut v: Vec<Duration>) -> Duration {
v.sort_unstable();
v[v.len() / 2]
}
/// Times Cut of [`many`] and [`reference_cut`] seven times each, in turn, and prints every run's
/// CPU and wall-clock time with the medians. Run it with
/// `cargo test --release -p vectorcraft-engine --lib -- --ignored --nocapture direct_selection_cut_timing`.
#[test]
#[ignore = "timing; prints the numbers"]
fn direct_selection_cut_timing() {
let mut runs: [(Vec<Duration>, Vec<Duration>); 2] = Default::default();
for round in 0..7 {
for (k, (cpu, wall)) in runs.iter_mut().enumerate() {
let mut s = many();
let (c0, w0) = (cpu_time(), Instant::now());
if k == 0 {
reference_cut(&mut s);
} else {
run(&mut s, "edit.cut", json!({}));
}
let w = w0.elapsed();
let c = c0.zip(cpu_time()).map(|(a, b)| b.saturating_sub(a)).unwrap_or(w);
println!("round {round} {}: cpu {c:?}, wall {w:?}", ["one at a time", "Cut"][k]);
cpu.push(c);
wall.push(w);
}
}
for (k, (cpu, wall)) in runs.into_iter().enumerate() {
println!("median {}: cpu {:?}, wall {:?}", ["one at a time", "Cut"][k], median(cpu), median(wall));
}
}
+17 -7
View File
@@ -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; 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}",
"{symbol: name of a document symbol, face?: front|back|side (front; Plane has only a front; the back reads left to right as seen from behind; side is Extrude & Bevel's walls and bevels; 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 a side from the middle of the side unrolled flat: on Extrude & Bevel x along the outline, clockwise from its top, and y from the front toward the back; on Revolve x around the axis and y along the profile), scale?: % (1..10000; default 100, or less so the graphic fits inside the object, on Extrude & Bevel's side inside the side unrolled about x = 0, short of its cut, 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 a side wrapped around it, and drawn only where its outside faces the viewer); every object's 3D effect must be Extrude & Bevel (on a solid cap, or on the side, hollow or not), Rotate (the Plane type) or Revolve; one undo step → {ids, graphic}",
has_doc,
map_graphic
),
@@ -113,22 +113,32 @@ fn map_graphic(s: &mut Session, p: &Value) -> Result<Value> {
if !effects::takes_graphics(&effect.id) {
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.
// A hollow Extrude & Bevel keeps the graphics it has on its caps, to show when Cap is turned
// on again, but has no cap to show a new one on. Its side takes graphics.
let merged = effects::merged_params(&effect.id, &effect.params);
let extrude = (effect.id == effects::EXTRUDE).then(|| effects::extrude_options(&merged));
if extrude.is_some_and(|o| o.depth > 0.0 && !o.cap) {
let side = base.face == effects::PlanarFace::Side;
if !side && extrude.is_some_and(|o| o.depth > 0.0 && !o.cap) {
return Err(bad(C, format!("object {}: a hollow Extrude & Bevel has no caps: turn on Cap to map a graphic", id.0)));
}
// With a depth of 0 the art is a plane, which has only a front.
if base.face == effects::PlanarFace::Back && extrude.is_some_and(|o| o.depth <= 0.0) {
if base.face != effects::PlanarFace::Front && extrude.is_some_and(|o| o.depth <= 0.0) {
return Err(bad(C, format!("object {}: with a depth of 0 the object has one face: map its graphics onto the front", id.0)));
}
let mut graphic = base.clone();
if p.get("scale").is_none()
&& let (Some(frame), Some(art)) = (effects::graphic_frame_at(Some(d), n, item, index), effects::graphic_bounds(d, &graphic.symbol))
&& let Some(art) = effects::graphic_bounds(d, &graphic.symbol)
{
graphic.scale = frame.fitting_scale(art);
// A graphic on the side starts fitting inside the side unrolled about x = 0, short of
// its cut; one on a cap inside the object's bounds.
let fit = if side {
effects::graphic_side_size(Some(d), n, item, index).map(|(w, h)| effects::graphic_fitting_scale(w, h, art))
} else {
effects::graphic_frame_at(Some(d), n, item, index).map(|frame| frame.fitting_scale(art))
};
if let Some(fit) = fit {
graphic.scale = fit;
}
}
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, index)).map_err(|e| bad(C, e))?;
@@ -135,6 +135,47 @@ fn map_graphic_refuses_what_cannot_take_it_and_changes_nothing() {
assert!(s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "ids": [id.0]})).is_ok());
}
#[test]
fn map_graphic_puts_a_graphic_on_the_side_of_an_extrude() {
let (mut s, id) = setup("threeD.extrude");
// A hollow Extrude & Bevel takes a graphic on its side.
s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": {"cap": false}})).unwrap();
s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "side", "y": 4.0, "ids": [id.0]})).unwrap();
assert_eq!(graphics(&s, id), json!([{"symbol": "Mark", "face": "side", "x": 0.0, "y": 4.0, "scale": 100.0, "rotation": 0.0}]));
// A plane, and a depth of 0, have no side.
let (mut s, plane) = setup("threeD.rotate");
let history = undo_len(&s);
let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "side", "ids": [plane.0]})).unwrap_err().to_string();
assert!(e.contains("one face"), "{e}");
assert_eq!(undo_len(&s), history);
let (mut s, flat) = setup("threeD.extrude");
s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": {"depth": 0.0}})).unwrap();
let history = undo_len(&s);
let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "side", "ids": [flat.0]})).unwrap_err().to_string();
assert!(e.contains("one face"), "{e}");
assert_eq!(undo_len(&s), history);
// A graphic taller than the side starts scaled to fit it: the side of the 100 × 100 square is
// about 300 pt wide short of its cut and 10 pt deep here, and the graphic with its stroke is
// 11 × 21.
let (mut s, id) = setup("threeD.extrude");
s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": {"depth": 10.0}})).unwrap();
s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "side", "ids": [id.0]})).unwrap();
let scale = graphics(&s, id)[0]["scale"].as_f64().unwrap();
assert!((scale - 1000.0 / 21.0).abs() < 1e-9, "{scale}");
// A graphic wider than the side is kept short of the cut, at a bottom corner of the square: the
// part about x = 0 is three quarters of the outline.
let (mut s, id) = setup("threeD.extrude");
let wide = s.execute("path.create", &json!({"d":"M0 380L400 380L400 390L0 390Z"})).unwrap()["id"].clone();
s.execute("threeD.addGraphic", &json!({"name": "Wide", "ids": [wide]})).unwrap();
s.execute("threeD.mapGraphic", &json!({"symbol": "Wide", "face": "side", "ids": [id.0]})).unwrap();
let d = &s.doc().unwrap().doc;
let (span, _) = vectorcraft_render::effects::graphic_side_size(Some(d), d.node(id).unwrap(), None, 0).unwrap();
let art = vectorcraft_render::effects::graphic_bounds(d, "Wide").unwrap();
assert!((span - 300.0).abs() < 1e-6 || (span - 303.0).abs() < 1e-6, "{span}");
let scale = graphics(&s, id)[0]["scale"].as_f64().unwrap();
assert!((scale - 100.0 * span / art.width()).abs() < 1e-9, "{scale}");
}
#[test]
fn set_params_edits_graphics_and_checks_them() {
let (mut s, id) = setup("threeD.extrude");
+2 -1
View File
@@ -65,6 +65,7 @@ pub mod zip;
use serde_json::{Value, json};
pub(crate) use action_batch::action_step;
pub use action_batch::batch_overwrites_one_file;
pub use dxf::{UNSUPPORTED, Unsupported, unsupported};
pub use encode::{
@@ -95,7 +96,7 @@ pub use naming::{NameParts as FileNameParts, parse_date as parse_file_date, rend
pub(crate) use native::preview_png;
pub use native::with_compression_pref;
pub(crate) use pdfimport::opened_page_document;
pub use pdfimport::{LoadOptions, page_document};
pub use pdfimport::{LoadOptions, page_document, pages_can_link};
pub(crate) use psdlayers::import_active as psd_layers;
pub use psdlayers::{PsdInfo, info as psd_info};
pub(crate) use psdslices::over as psd_slices;
+6 -3
View File
@@ -144,8 +144,9 @@ pub(crate) fn check_scripts_of(cmd: &str, doc: &vectorcraft_doc::Document, doc_p
}
/// Does a file of a document with `artboards` artboards, written in format `format` with options
/// `p`, name the JavaScript files the document links? SVG, SVGZ, native files, native templates and
/// EPS files always do. A `.ai` or `.ait` file does unless it is a legacy version 7 `.ai` file or `p`
/// `p`, name the JavaScript files the document links? SVG, SVGZ, native files, native templates,
/// EPS files and the files of an exporter plug-in's format (`plugin.<id>`, whose plug-in is given
/// the native document's JSON) always do. A `.ai` or `.ait` file does unless it is a legacy version 7 `.ai` file or `p`
/// picks only some of the artboards; a PDF does with Preserve Editing on (as its preset, standard and
/// options leave it) unless `p` picks only some of the artboards. Neither a `.ai` file nor a PDF
/// does when `useArtboards` is false in `p` (one page, the bounds of the art). Options the encoder
@@ -159,6 +160,7 @@ pub(crate) fn names_linked_scripts(cmd: &str, format: &str, p: &Value, artboards
let art_page = || super::encode::use_artboards(cmd, p).is_ok_and(|u| u == Some(false));
match format {
"svg" | "svgz" | "vectorcraft" | "template" | "eps" => true,
_ if vectorcraft_plugins::export::plugin_id(format).is_some() => true,
"ai" | "ait" => {
let legacy = super::format(format).is_some_and(|f| super::legacy_ai::wanted(cmd, f, p).unwrap_or(false));
!legacy && !(format == "ai" && art_page()) && every_artboard()
@@ -228,7 +230,8 @@ pub(crate) fn check_images_in(cmd: &str, format: &str, d: &vectorcraft_doc::Docu
/// `cmd` may write `d` in format `format` (a format id other than SVG and SVGZ) with options `p`:
/// always, unless read roots are in force, the file carries the native document (a native file or
/// template, an EPS file, a `.ai` or `.ait` file or a PDF with Preserve Editing, as
/// template, an EPS file, a `.ai` or `.ait` file, a PDF with Preserve Editing or an exporter
/// plug-in's file, as
/// [`names_linked_scripts`] counts them with `d`'s artboards) and that document names a file
/// outside them ([`crate::cmd::links::names_hidden_file`]: a linked image or placed file, the
/// relative path kept of one taken from `base`, a data set's image, or stored brushes that can't be
+117 -32
View File
@@ -54,24 +54,19 @@ pub(super) fn action_batch(s: &mut Session, p: &Value) -> Result<Value> {
}
for (i, c) in cmds.iter().enumerate() {
let id = c.get("command").and_then(Value::as_str).unwrap_or("");
let refuse = |reason: &str| bad(C, action_step(i, id, reason));
if id.is_empty() {
return Err(bad(C, format!("commands[{i}]: missing `command`")));
return Err(refuse("missing `command`"));
}
if id == "command.batch" || id == "action.batch" {
return Err(bad(C, "batches cannot nest"));
return Err(refuse("batches cannot nest"));
}
// `command.batch` refuses the batch when it reaches this step, which would fail every file or data set it plays.
if id == "prefs.import" {
return Err(bad(C, format!("commands[{i}]: `prefs.import` runs on its own, not as a batch step")));
return Err(refuse("`prefs.import` runs on its own, not as a batch step"));
}
if find_command(id).is_none() {
return Err(bad(
C,
match super::super::params::nearest_command(id) {
Some(near) => format!("commands[{i}]: unknown command `{id}`; did you mean `{near}`?"),
None => format!("commands[{i}]: unknown command `{id}`"),
},
));
return Err(refuse(&super::super::params::unknown_command(id).to_string()));
}
}
// Every option is checked before the destination folder is made.
@@ -160,7 +155,7 @@ pub fn batch_overwrites_one_file(s: &Session, p: &Value) -> bool {
Some(f) => own_format.is_some_and(|own| super::format(f).is_some_and(|f| f.id == own)),
};
match c.get("command").and_then(Value::as_str).unwrap_or("") {
"document.save" | "file.save" => !save && (path || own_file()),
"document.save" => !save && (path || own_file()),
"file.saveAs" => !save && path,
"file.saveCopy" | "file.saveAsTemplate" => path,
"document.export" | "document.exportSelection" => !export && path,
@@ -184,7 +179,7 @@ fn saves_move_to_each_file(steps: &[Value], redirected: bool) -> bool {
/// in the destination folder when `redirected`) and makes that file the document's own: a save in
/// the native template format writes a copy and leaves the document's file as it was.
fn retargeting_save(c: &Value, redirected: bool) -> bool {
if !matches!(c.get("command").and_then(Value::as_str), Some("document.save" | "file.save" | "file.saveAs")) {
if !matches!(c.get("command").and_then(Value::as_str), Some("document.save" | "file.saveAs")) {
return false;
}
let params = c.get("params");
@@ -219,7 +214,7 @@ fn batch_folder(s: &mut Session, cmd: &str, p: &Value, override_open: bool, run:
// open, so its artboard files count ([`dataset_output_paths`]). No output takes the name of a
// source file in the destination folder, other than that file's own output, or of a subfolder
// of the destination folder that holds source files.
let (steps, places) = filter_steps(run.steps, override_open, false);
let (steps, places) = filter_steps(run.steps, override_open);
let run = Run { steps: &steps, ..*run };
let in_dest: Vec<Option<(String, bool)>> = files.iter().map(|path| name_in_folder(path, run.dest_folder)).collect();
let mut picker =
@@ -272,7 +267,7 @@ fn batch_datasets(s: &mut Session, cmd: &str, run: &Run<'_>) -> Result<Value> {
}
let doc_stem = st.path.as_deref().and_then(|p| std::path::Path::new(p).file_stem().and_then(|s| s.to_str())).unwrap_or("Untitled").to_string();
let stems = dataset_stems(&names, &doc_stem, run.dataset_file_naming, run, &st.doc)?;
let (steps, places) = filter_steps(run.steps, true, false);
let (steps, places) = filter_steps(run.steps, true);
let run = Run { steps: &steps, ..*run };
let mut processed = Vec::new();
let mut failed = 0usize;
@@ -353,22 +348,13 @@ impl StemPicker {
}
}
/// Drop Open (and optionally Close) steps when the batch supplies the file itself → the steps that
/// stay, and the index of each in `cmds`.
/// Drop the `document.open` steps when `drop_open` (the batch opens each source file itself) → the
/// steps that stay, and the index of each in `cmds`.
#[cfg(not(target_arch = "wasm32"))]
fn filter_steps(cmds: &[Value], drop_open: bool, drop_close: bool) -> (Vec<Value>, Vec<usize>) {
fn filter_steps(cmds: &[Value], drop_open: bool) -> (Vec<Value>, Vec<usize>) {
cmds.iter()
.enumerate()
.filter(|(_, c)| {
let id = c.get("command").and_then(Value::as_str).unwrap_or("");
if drop_open && matches!(id, "document.open" | "file.open") {
return false;
}
if drop_close && matches!(id, "file.close" | "document.close") {
return false;
}
true
})
.filter(|(_, c)| !(drop_open && c.get("command").and_then(Value::as_str) == Some("document.open")))
.map(|(i, c)| (c.clone(), i))
.unzip()
}
@@ -385,12 +371,24 @@ fn play_steps(s: &mut Session, run: &Run<'_>, places: &[usize], commands: Vec<Va
let Some((n, id, reason)) = batch_step_failure(&text) else { return e };
let same = run.steps.get(n).and_then(|c| c.get("command")).and_then(Value::as_str) == Some(id);
match places.get(n) {
Some(place) if same => EngineError::Other(format!("action step {} (`{id}`) failed: {reason}", place + 1)),
Some(&place) if same => EngineError::Other(action_step(place, id, reason)),
_ => e,
}
})
}
/// The text naming the member at `index` of an `action.batch`'s `commands`, counted from 1, with
/// its command id when it has one, and `reason`: ``action step 2 (`object.move`) failed: …``. The
/// checks before a batch runs and the errors of its steps as they run give the same text.
pub(crate) fn action_step(index: usize, id: &str, reason: &str) -> String {
let n = index.saturating_add(1);
if id.is_empty() {
format!("action step {n} failed: {reason}")
} else {
format!("action step {n} (`{}`) failed: {reason}", vectorcraft_apischema::shown_key(id))
}
}
/// The step number, command id and reason in the error `command.batch` gives when one of its steps
/// fails (``batch step 2 (`object.move`) failed: …``); none for any other error.
#[cfg(not(target_arch = "wasm32"))]
@@ -540,7 +538,7 @@ fn dataset_output_extensions(run: &Run<'_>, doc: &vectorcraft_doc::Document, def
outputs.push(DatasetOutput { ext: String::new(), artboards: false, joiner: "-", folder: true });
continue;
}
let writes = (run.override_save && matches!(id, "document.save" | "file.save" | "file.saveAs"))
let writes = (run.override_save && matches!(id, "document.save" | "file.saveAs"))
|| (run.override_export && matches!(id, "document.export" | "document.exportSelection"));
if writes {
let format = step.get("params").and_then(|p| p.get("format")).and_then(Value::as_str).filter(|f| !f.is_empty());
@@ -551,7 +549,7 @@ fn dataset_output_extensions(run: &Run<'_>, doc: &vectorcraft_doc::Document, def
};
if safe_extension(&ext) {
let format_id = super::format(format.unwrap_or(default_ext)).map(|f| f.id).unwrap_or("vectorcraft");
let is_save = matches!(id, "document.save" | "file.save" | "file.saveAs");
let is_save = matches!(id, "document.save" | "file.saveAs");
let artboards = if is_save {
!doc.artboards.is_empty() && matches!(format_id, "vectorcraft" | "template" | "ai" | "ait")
} else {
@@ -693,7 +691,7 @@ fn rewrite_paths(
.map(|c| {
let id = c.get("command").and_then(Value::as_str).unwrap_or("");
let mut c = c.clone();
let rewrite = (override_save && matches!(id, "document.save" | "file.save" | "file.saveAs"))
let rewrite = (override_save && matches!(id, "document.save" | "file.saveAs"))
|| (override_export && matches!(id, "document.export" | "document.exportForScreens" | "document.exportSelection" | "assets.export"));
if !rewrite {
return c;
@@ -2385,10 +2383,97 @@ mod tests {
let mut s = Session::new();
let p = json!({"folder": src.to_string_lossy(), "commands": [{"command": "object.unlockAll"}, {"command": "prefs.import", "params": {}}]});
let e = s.execute("action.batch", &p).unwrap_err().to_string();
assert!(e.contains("commands[1]: `prefs.import` runs on its own, not as a batch step"), "{e}");
assert!(e.contains("action step 2 (`prefs.import`) failed: `prefs.import` runs on its own, not as a batch step"), "{e}");
assert!(s.active().is_none(), "no file was opened");
}
/// Each step the checks before the batch refuse is named by its place in `commands`, from 1,
/// as a step that fails as it runs is, and no source file is opened.
#[test]
fn a_refused_step_is_named_by_its_place_from_1() {
let src = tmp("step-number-refused-src");
write_svg(&src, "a.svg", "#f00");
let prefix = "invalid parameters for `action.batch`: ";
let cases = [
(json!({"params": {}}), "action step 2 failed: missing `command`"),
(json!({"command": "select.al"}), "action step 2 (`select.al`) failed: unknown command `select.al`; did you mean `select.all`?"),
(json!({"command": "command.batch", "params": {"commands": []}}), "action step 2 (`command.batch`) failed: batches cannot nest"),
(json!({"command": "action.batch", "params": {}}), "action step 2 (`action.batch`) failed: batches cannot nest"),
(
json!({"command": "view.saved.new", "params": {"center": [0, 0], "zoom": 0}}),
"action step 2 (`view.saved.new`) failed: invalid parameters for `view.saved.new`: `zoom` must be a number > 0, not 0",
),
];
for (step, want) in cases {
let mut s = Session::new();
let p = json!({"folder": src.to_string_lossy(), "commands": [{"command": "object.unlockAll"}, step]});
let e = s.execute("action.batch", &p).unwrap_err().to_string();
assert_eq!(e, format!("{prefix}{want}"), "{step}");
assert!(s.active().is_none(), "{step}: a file was opened");
assert!(s.journal.is_empty(), "{step}: a step ran");
}
}
/// The parameter check of an `action.batch` names the step whose params it refuses, from 1;
/// that of a `command.batch` passes the step's error on as it is.
#[test]
fn the_parameter_check_names_the_refused_step() {
let bad_view = json!({"command": "view.saved.new", "params": {"center": [0, 0], "zoom": 0}});
let commands = json!([{"command": "object.unlockAll"}, {"command": "select.all"}, bad_view]);
let own = "invalid parameters for `view.saved.new`: `zoom` must be a number > 0, not 0";
let e = crate::cmd::params::check_params("action.batch", &json!({"commands": commands})).unwrap_err().to_string();
assert_eq!(e, format!("invalid parameters for `action.batch`: action step 3 (`view.saved.new`) failed: {own}"));
let e = crate::cmd::params::check_params("command.batch", &json!({"commands": commands})).unwrap_err().to_string();
assert_eq!(e, own);
}
/// The ids of the File menu's Open… and Save in the app (`file.open`, `file.save`) and
/// `document.close` are not engine commands, so a step with one is refused before the batch
/// starts, with Override Open and Override Save on or off.
#[test]
fn steps_with_ids_that_are_not_engine_commands_are_refused() {
let src = tmp("step-number-aliases-src");
write_svg(&src, "a.svg", "#f00");
for id in ["file.open", "file.save", "document.close"] {
for overrides in [true, false] {
let mut s = Session::new();
let p = json!({
"folder": src.to_string_lossy(),
"overrideOpen": overrides,
"overrideSave": overrides,
"commands": [{"command": "object.unlockAll"}, {"command": id, "params": {}}],
});
let e = s.execute("action.batch", &p).unwrap_err().to_string();
assert!(
e.starts_with(&format!("invalid parameters for `action.batch`: action step 2 (`{id}`) failed: unknown command `{id}`")),
"{e}"
);
assert!(s.active().is_none(), "{id}: a file was opened");
}
}
}
/// `command.batch` keeps its own numbering, from 0, for a step that fails.
#[test]
fn command_batch_keeps_its_own_step_numbers() {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let e = s
.execute("command.batch", &json!({"commands": [{"command": "object.unlockAll"}, {"command": "object.align", "params": {}}]}))
.unwrap_err();
assert!(e.to_string().starts_with("batch step 1 (`object.align`) failed: "), "{e}");
}
/// A step's id in the error is cut short, as an unknown key's is.
#[test]
fn a_long_step_id_is_cut_short() {
let id = "x".repeat(10_000);
let shown = action_step(0, &id, "why");
assert!(shown.len() < 1_000, "{}", shown.len());
assert!(shown.starts_with("action step 1 (`xxx") && shown.ends_with("…`) failed: why"), "{shown}");
assert_eq!(action_step(usize::MAX, "", "why"), format!("action step {} failed: why", usize::MAX));
}
/// Only the error `command.batch` gives for a failed step is read as one.
#[test]
fn batch_step_failure_reads_only_a_step_error() {
+1 -1
View File
@@ -117,7 +117,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Batch…",
[],
None,
"{commands: [{command, params}] (the action's steps), source?: folder (default) | datasets, folder? (required for folder: the source folder), includeSubdirs?: false, destination?: none (default: leave each file open) | saveAndClose (save over the source and close; for source datasets, save the open document over its own file after each data set, and refuse a document that was never saved, was converted from an older version or was restored by Data Recovery, unless a recorded Save or Save As step writes a file first; a Save or Save As step that overrideSave points into destinationFolder makes each data set's file the document's own) | folder (save or export into destinationFolder and close), destinationFolder? (required when destination is folder; also the folder Override Save/Export write into), datasetFileNaming?: fileNumber | fileDataSetName (default) | dataSetName (used only for source datasets; ignored for folder), overrideOpen?: true (skip document.open / file.open steps: the batch opens each source file), overrideSave?: true (point document.save / file.save / file.saveAs at destinationFolder/{stem}.{ext}), overrideExport?: true (point document.export / document.exportSelection the same way, and give document.exportForScreens / assets.export the folder destinationFolder/{stem}, one for each source file or data set, in which the export names its files as it does outside Batch), stopOnError?: true, label?} play the commands on every readable file in folder (and its subfolders when includeSubdirs; {stem} is the file's name without its extension and without trailing periods and spaces, with `-2`, `-3`… added to a name an earlier file used or whose file or folder has the name of one an earlier file wrote or of another source file or a folder of source files in destinationFolder), or on every data set of the open document. Data set names use the document stem plus a three-digit ordinal, the document stem and an underscore plus the data set name, or the data set name alone. Invalid file name characters become `-` and trailing periods and spaces are dropped; a name already used in the batch or whose output file or folder already exists in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix before the format-derived extension. Caps: 500 files or data sets, 8 folder levels, 256 steps. Batches cannot nest, and a prefs.import step is refused (commands[i], from 0) before any file is opened. A switch (includeSubdirs, overrideOpen, overrideSave, overrideExport, stopOnError) that is not true or false, or a source, folder, destination, destinationFolder, datasetFileNaming or label that is not a string, is an error before any folder is made or file opened; null reads as left out. A step that fails is named in the error by its place in commands, from 1, counting the Open steps the batch skips (action step 3 (`object.align`) failed: …); the batch's own opening of a file, choosing of a data set and destination save, export or close give their errors without a step number. → {processed: [{path|dataset, result|error}…], count, failed, stopped, warning?} (warning: for source datasets, when Save and Close without such a step, or a Save, Save a Copy, Save as Template or export step (document.export, exportSelection, exportForScreens, exportPdf, exportEps, exportDxf, exportForWeb, exportForOffice) that writes a file and is not pointed into destinationFolder, saves every data set over the same file)",
"{commands: [{command, params}] (the action's steps), source?: folder (default) | datasets, folder? (required for folder: the source folder), includeSubdirs?: false, destination?: none (default: leave each file open) | saveAndClose (save over the source and close; for source datasets, save the open document over its own file after each data set, and refuse a document that was never saved, was converted from an older version or was restored by Data Recovery, unless a recorded Save or Save As step writes a file first; a Save or Save As step that overrideSave points into destinationFolder makes each data set's file the document's own) | folder (save or export into destinationFolder and close), destinationFolder? (required when destination is folder; also the folder Override Save/Export write into), datasetFileNaming?: fileNumber | fileDataSetName (default) | dataSetName (used only for source datasets; ignored for folder), overrideOpen?: true (skip document.open steps: the batch opens each source file), overrideSave?: true (point document.save / file.saveAs at destinationFolder/{stem}.{ext}), overrideExport?: true (point document.export / document.exportSelection the same way, and give document.exportForScreens / assets.export the folder destinationFolder/{stem}, one for each source file or data set, in which the export names its files as it does outside Batch), stopOnError?: true, label?} play the commands on every readable file in folder (and its subfolders when includeSubdirs; {stem} is the file's name without its extension and without trailing periods and spaces, with `-2`, `-3`… added to a name an earlier file used or whose file or folder has the name of one an earlier file wrote or of another source file or a folder of source files in destinationFolder), or on every data set of the open document. Data set names use the document stem plus a three-digit ordinal, the document stem and an underscore plus the data set name, or the data set name alone. Invalid file name characters become `-` and trailing periods and spaces are dropped; a name already used in the batch or whose output file or folder already exists in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix before the format-derived extension. Caps: 500 files or data sets, 8 folder levels, 256 steps. A step without a command, with a command the engine doesn't have, with params its command refuses, or with command.batch, action.batch or prefs.import (batches cannot nest) is refused before any file is opened, named by its place in commands, from 1 (action step 2 (`select.al`) failed: unknown command `select.al`; did you mean `select.all`?). A switch (includeSubdirs, overrideOpen, overrideSave, overrideExport, stopOnError) that is not true or false, or a source, folder, destination, destinationFolder, datasetFileNaming or label that is not a string, is an error before any folder is made or file opened; null reads as left out. A step that fails as it runs is named the same way, counting the Open steps the batch skips (action step 3 (`object.align`) failed: …); the batch's own opening of a file, choosing of a data set and destination save, export or close give their errors without a step number. → {processed: [{path|dataset, result|error}…], count, failed, stopped, warning?} (warning: for source datasets, when Save and Close without such a step, or a Save, Save a Copy, Save as Template or export step (document.export, exportSelection, exportForScreens, exportPdf, exportEps, exportDxf, exportForWeb, exportForOffice) that writes a file and is not pointed into destinationFolder, saves every data set over the same file)",
always,
action_batch::action_batch
),
+3 -2
View File
@@ -226,9 +226,10 @@ pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option<bool>) ->
vec![(Some(b), rect(b)?, false)]
}
};
let regions: Vec<(Rect, bool)> = drawings.iter().map(|&(_, region, crop)| (region, crop)).collect();
let outs = vectorcraft_cad::export_drawings(doc, &opts, &regions).map_err(|e| bad(C, e))?;
let mut enc = Encoded::default();
for (board, region, crop) in drawings {
let out = vectorcraft_cad::export(doc, &DxfOptions { region, crop, ..opts.clone() }).map_err(|e| bad(C, e))?;
for ((board, _, _), out) in drawings.into_iter().zip(outs) {
enc.files.push((board, out.bytes));
for w in out.warnings {
if !enc.warnings.contains(&w) {
+6 -4
View File
@@ -1053,12 +1053,14 @@ fn encode_all_of(doc: &Document, format: &str, p: &Value) -> Result<Encoded> {
/// The file exporter plug-in `plugin` writes of `doc` in its format `f`
/// ([`vectorcraft_plugins::export`]). The plug-in is given the native file's JSON
/// ([`vectorcraft_format::json_part`]) and `p`'s `params`, for the file `p`'s `path` names (else
/// one named after the document) with that path's extension when the plug-in lists it, else its
/// first. Its warnings come back with the file, as losses (the plug-in gives them no kind).
/// ([`vectorcraft_format::json_part`]), without an Export for Screens folder outside the read roots
/// ([`super::access::with_readable_settings_folder`]), and `p`'s `params`, for the file `p`'s `path`
/// names (else one named after the document) with that path's extension when the plug-in lists it,
/// else its first. Its warnings come back with the file, as losses (the plug-in gives them no kind).
fn plugin_file(doc: &Document, plugin: &vectorcraft_plugins::Plugin, f: &Format, p: &Value) -> Result<Encoded> {
use vectorcraft_plugins::{Error, export};
let doc = &*doc.without_edit_modes();
let doc = doc.without_edit_modes();
let doc = &*super::access::with_readable_settings_folder(&doc);
let file = vectorcraft_format::save_with(doc, &vectorcraft_format::SaveOptions::default()).map_err(|e| EngineError::Other(e.to_string()))?;
let path = p.get("path").and_then(Value::as_str);
let listed = path.map(super::extension).and_then(|e| f.extensions.iter().copied().find(|x| *x == e));
+6 -3
View File
@@ -26,13 +26,16 @@ pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option<bool>, kin
Some(true) => pick.resolve(n).map_err(|e| bad(C, e))?.unwrap_or_else(|| (0..n).collect()),
_ => vec![pick.one(n).map_err(|e| bad(C, e))?],
};
let rects = boards
.iter()
.map(|&b| doc.artboards.get(b).map(|a| a.rect).ok_or_else(|| bad(C, format!("no artboard {}", b + 1))))
.collect::<Result<Vec<_>>>()?;
// Raster effects (shadows, glows, blurs) as images, as PDF export does.
let flat = crate::flatten_raster_effects(doc);
let src = flat.as_ref().unwrap_or(doc);
let outs = vectorcraft_metafile::export_regions(src, &rects, kind).map_err(|e| bad(C, e))?;
let mut enc = Encoded::default();
for b in boards {
let region = doc.artboards.get(b).ok_or_else(|| bad(C, format!("no artboard {}", b + 1)))?.rect;
let out = vectorcraft_metafile::export(src, region, kind).map_err(|e| bad(C, e))?;
for (b, out) in boards.into_iter().zip(outs) {
enc.files.push((Some(b), out.bytes));
for w in out.warnings {
if !enc.warnings.contains(&w) {
File diff suppressed because one or more lines are too long
@@ -222,6 +222,13 @@ fn page_options(page: usize, o: &LoadOptions) -> ImportOptions {
ImportOptions { pages: Some(vec![page]), crop: o.crop, password: o.password.clone(), text_as: o.text_as, layers: false, ..Default::default() }
}
/// Whether `document.open`'s `linkPages` takes the file `name` holding `bytes`: a PDF or a
/// PDF-compatible `.ai` or `.ait` of at most [`document::MAX_FILE`] bytes. Its path, a password
/// and `textAs` are checked apart ([`linked_pages`]).
pub fn pages_can_link(name: &str, bytes: &[u8]) -> bool {
bytes.len() <= document::MAX_FILE && document::is_pdf(name, bytes)
}
/// `document.open` with `linkPages`: the pages `o` picks of the PDF (or PDF-compatible `.ai` or
/// `.ait`) `name`, read from `path`, as a document holding one placed document per page, linked to
/// that page of the file as File › Place with Link places one ([`document::source`]). Each page
+18
View File
@@ -116,6 +116,24 @@ fn use_artboards_writes_one_drawing_per_artboard() {
assert!(e.contains("useArtboards"), "{e}");
}
#[test]
fn each_artboard_s_drawing_is_the_drawing_of_that_artboard_alone() {
let mut s = two_boards();
// A second rectangle on the second artboard, so the two drawings differ.
let second = s.doc().unwrap().doc.artboards[1].rect.x0;
s.execute("shape.rectangle", &json!({"x": second + 50.0, "y": 50, "width": 20, "height": 20})).unwrap();
let r = s.execute("document.export", &json!({"format": "dxf", "useArtboards": true, "unit": "pt"})).unwrap();
let files = r["files"].as_array().unwrap();
let doc = &s.doc().unwrap().doc;
let o = dxf::options(&json!({"unit": "pt"})).unwrap();
assert_eq!(files.len(), doc.artboards.len());
assert_ne!(b64(&files[0]), b64(&files[1]));
for (f, board) in files.iter().zip(&doc.artboards) {
let alone = vectorcraft_cad::export(doc, &vectorcraft_cad::DxfOptions { region: board.rect, crop: true, ..o.clone() }).unwrap();
assert_eq!(b64(f), alone.bytes, "{}", f["name"]);
}
}
#[test]
fn selected_only_exports_the_selection_in_its_layers() {
let mut s = two_boards();
@@ -410,3 +410,16 @@ fn a_placeholder_only_pdf_part_is_detected() {
assert!(open(&mut s, &two, json!({"pages": "1"})).is_err());
open(&mut s, &two, json!({})).unwrap();
}
/// `linkPages` takes a PDF up to the largest file placed, and nothing else.
#[test]
fn pages_can_link_a_pdf_up_to_the_largest_file_placed() {
let small = three_pages();
assert!(pages_can_link("pages.pdf", &small));
assert!(!pages_can_link("pages.svg", b"<svg xmlns=\"http://www.w3.org/2000/svg\"/>"));
let mut big = vec![0u8; crate::cmd::place::document::MAX_FILE + 1];
big[..small.len()].copy_from_slice(&small);
assert!(!pages_can_link("pages.pdf", &big), "over the limit");
big.pop();
assert!(pages_can_link("pages.pdf", &big), "at the limit");
}
+26 -5
View File
@@ -3,7 +3,7 @@
use serde_json::{Value, json};
use vectorcraft_doc::text::INLINE_MAX_SCALE;
use vectorcraft_doc::{Document, InlineArt, NodeId, NodeKind, TextRun};
use vectorcraft_doc::{Document, InlineArt, InlineMeasured, NodeId, NodeKind, TextRun};
use vectorcraft_text::edit;
use super::brushsym::current_symbol;
@@ -25,12 +25,33 @@ 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, 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) {
/// symbol's type before the type that shows that symbol inline). `last` is the document the last
/// refresh left resolved, with what it measured: when nothing the inline art depends on changed
/// since, only the layer trees that differ from its own are checked
/// ([`Document::resolve_inline_art_since`]). Returns what this refresh measured, or `None` when
/// neither document has symbols and nothing was checked.
pub(crate) fn refresh(last: Option<&Resolved>, before: &Document, d: &mut Document) -> Option<InlineMeasured> {
if before.symbols.is_empty() && d.symbols.is_empty() {
return;
return None;
}
d.resolve_inline_art_with(&mut refresh_bounds);
#[cfg(test)]
let last = last.filter(|_| !FULL_PASS.get());
let pass = d.resolve_inline_art_since(last.map(|(doc, m)| (&**doc, m)), &mut refresh_bounds);
#[cfg(test)]
PASSES.with(|p| p.borrow_mut().push((pass.partial, pass.changed.clone())));
Some(pass.measured)
}
/// A document a [`refresh`] left resolved, and what that refresh measured.
pub(crate) type Resolved = (std::sync::Arc<Document>, InlineMeasured);
#[cfg(test)]
thread_local! {
/// Each [`refresh`] on this thread that checked the document: whether it checked only the
/// changed layer trees, and the ids of the texts in the layers that changed.
pub(crate) static PASSES: std::cell::RefCell<Vec<(bool, Vec<NodeId>)>> = const { std::cell::RefCell::new(vec![]) };
/// Set: every [`refresh`] on this thread takes the full pass.
pub(crate) static FULL_PASS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
fn insert_inline(s: &mut Session, p: &Value) -> Result<Value> {
+22 -13
View File
@@ -29,7 +29,7 @@ pub fn specs() -> Vec<CommandSpec> {
"New Layer…",
["Window", "Layers"],
Some("Cmd+L"),
"{name?, top?: bool, below?: bool, color?, template?, locked?, visible?, printable?, preview?, dimImages?} a layer directly above the current layer, at its level (a sublayer beside a current sublayer); `top`: above all layers (Ctrl/Cmd-click the button); `below`: directly below the current layer, at its level (Ctrl/Cmd+Alt-click the button), not with `top`. Options as layer.setProps; refused while an opacity mask is edited (the Layers panel lists only the mask) → {id}",
"{name?, top?: bool, below?: bool, color?, template?, locked?, visible?, printable?, preview?, dimImages?} a layer directly above the current layer, at its level (a sublayer beside a current sublayer), or directly below it in Draw Behind; `top`: above all layers (Ctrl/Cmd-click the button); `below`: directly below the current layer, at its level (Ctrl/Cmd+Alt-click the button), not with `top`. Options as layer.setProps; refused while an opacity mask is edited (the Layers panel lists only the mask) → {id}",
super::maskedit::outside_mask_editing,
new_layer
),
@@ -110,7 +110,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Move Rows",
[],
None,
"{ids|id, target, place?: \"above\"|\"below\"|\"inside\" (default inside), copy?: bool} drag rows in the Layers panel: above or below the target row (beside it, in its layer or group), or inside a layer, group or Intertwine group (on top of its contents). Layers go only in layers or at the top level, objects in layers, groups and Intertwine groups; an object placed beside a top-level layer goes inside it. An object placed in an Intertwine group becomes a member drawn in its row's order, with no arranged areas, and one placed in a group that is a member becomes part of that member; one that is or holds an Intertwine group, a Repeat, a graph or a Live Paint group is refused. A member moved out of its Intertwine group drops its arranged areas, and a group left with one member is replaced by that member, or becomes a plain group of it when the group has an opacity, blending, appearance, mask, lock or hidden state of its own (with no member, it is removed). A row never goes into itself; a locked layer or group takes nothing. `copy` (Alt-drag) moves copies. Every selected object left hidden or locked, such as one moved into a hidden layer or group, is deselected (the key object too). One undo step → {ids}",
"{ids|id, target, place?: \"above\"|\"below\"|\"inside\" (default inside), copy?: bool} drag rows in the Layers panel: above or below the target row (beside it, in its layer or group), or inside a layer, group or Intertwine group (on top of its contents). Layers go only in layers or at the top level, objects in layers, groups and Intertwine groups; an object placed beside a top-level layer goes inside it. An object placed in an Intertwine group becomes a member drawn in its row's order, with no arranged areas, and one placed in a group that is a member becomes part of that member; one that is or holds an Intertwine group, a Repeat, a graph or a Live Paint group is refused. A member moved out of its Intertwine group drops its arranged areas, and a group left with one member is replaced by that member, or becomes a plain group of it when the group has an opacity, blending, appearance, mask, lock or hidden state of its own (with no member, it is removed). A row never goes into itself; a locked layer or group takes nothing. `copy` (Alt-drag) moves copies, which may also go above or below a row they copy (the target among `ids`). Every selected object left hidden or locked, such as one moved into a hidden layer or group, is deselected (the key object too). One undo step → {ids}",
has_doc,
move_rows
),
@@ -526,12 +526,15 @@ fn add_layer(s: &mut Session, p: &Value, cmd: &str, label: &str, place: impl FnO
fn new_layer(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "layer.new";
let below = switch_or(p, "below", false, C)?;
if below && bool_or(p, "top", false) {
let top = bool_or(p, "top", false);
if below && top {
return Err(bad(C, "`top` and `below` can't both be true"));
}
// In Draw Behind a layer given neither `top` nor `below` goes below the current layer.
let below = below || (!top && s.draw_mode == crate::DrawMode::Behind);
let st = s.doc()?;
// Above the current layer, at its level; below it with `below`; on top of everything with `top`.
let cur = st.current_layer().filter(|_| !bool_or(p, "top", false));
let cur = st.current_layer().filter(|_| !top);
add_layer(s, p, C, "New Layer", |d| match cur.and_then(|c| d.position(c)) {
Some((parent, i, _)) => Ok((parent, if below { i } else { i + 1 })),
None => Ok((None, if below { 0 } else { usize::MAX })),
@@ -723,19 +726,18 @@ fn select_art(s: &mut Session, p: &Value) -> Result<Value> {
} else {
vec![id]
};
let all_selected = !ids.is_empty() && ids.iter().all(|i| st.selection.contains(*i));
let all_selected = add && !ids.is_empty() && {
let selected: HashSet<NodeId> = st.selection.objects.iter().copied().collect();
ids.iter().all(|i| selected.contains(i))
};
let rows = st.layer_rows.clone();
s.select(|_, sel| {
if !add {
sel.set(ids.iter().copied());
} else if all_selected {
for i in &ids {
sel.remove(*i);
}
sel.remove_all(ids.iter().copied());
} else {
for i in &ids {
sel.add(*i);
}
sel.add_all(ids.iter().copied());
}
})?;
let st = s.doc_mut()?;
@@ -774,9 +776,11 @@ fn move_rows(s: &mut Session, p: &Value) -> Result<Value> {
if ids.is_empty() {
return Err(bad(C, "no such rows"));
}
// Never into itself or a row inside it.
// Never into itself or a row inside it. A copy may go above or below one of the rows it
// copies, which a move there would leave where it is (#8237).
let beside_itself = copy && place != Place::Inside && ids.contains(&target);
let around = d.ancestry(target).unwrap_or_default();
if ids.iter().any(|i| around.contains(i)) {
if ids.iter().any(|i| around.contains(i) && !(beside_itself && *i == target)) {
return Err(bad(C, "a row can't go into itself"));
}
let nodes: Vec<&Node> = ids.iter().filter_map(|i| d.node(*i)).collect();
@@ -788,6 +792,11 @@ fn move_rows(s: &mut Session, p: &Value) -> Result<Value> {
parent => (parent, Some(target)),
},
};
// A copy beside a top-level layer it copies, with objects among the rows, would go inside
// that layer: into itself.
if parent.is_some_and(|p| ids.contains(&p)) {
return Err(bad(C, "a row can't go into itself"));
}
if let Some(n) = nodes.iter().find(|n| !accepts(d, parent, n)) {
let into = parent.and_then(|p| d.node(p)).map_or("the top level", |p| if p.is_layer() { "a layer" } else { p.kind_label() });
return Err(bad(C, format!("{} can't go into {into}", n.display_name())));
+13 -4
View File
@@ -132,7 +132,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Locate Object",
["Window", "Layers"],
None,
"{id?} (default: the last selected object) highlight the object's row; the Layers panel opens the layers around it and scrolls to it → {id, ancestry: [layer…, id]}",
"{id?, layersOnly?} (default: the last selected object) highlight the object's row; the Layers panel opens the layers around it and scrolls to it, also when the row was already highlighted →{id, ancestry: [layer…, id]}. layersOnly (default false; the panel sends true while Show Layers Only is on, as Locate Layer) highlights the innermost layer or sublayer holding the object instead, or a layer id itself → {id: layer, objectId, ancestry: [layer…]}",
has_doc,
locate
),
@@ -435,10 +435,19 @@ fn reverse(s: &mut Session, p: &Value) -> Result<Value> {
fn locate(s: &mut Session, p: &Value) -> Result<Value> {
let id = object_param(p, "id", "layer.locate")?;
let layers_only = switch_or(p, "layersOnly", false, "layer.locate")?;
let st = s.doc_mut()?;
let id = id.or_else(|| st.selection.objects.last().copied()).ok_or_else(|| bad("layer.locate", "nothing selected"))?;
let ancestry = st.doc.ancestry(id).ok_or(EngineError::NoNode(id))?;
st.layer_rows = vec![id];
let mut ancestry = st.doc.ancestry(id).ok_or(EngineError::NoNode(id))?;
if layers_only {
// Locate Layer: the innermost layer or sublayer holding the object (a layer locates itself).
let at = ancestry.iter().rposition(|a| st.doc.node(*a).is_some_and(Node::is_layer)).ok_or(EngineError::NoNode(id))?;
ancestry.truncate(at + 1);
}
let row = ancestry.last().copied().ok_or(EngineError::NoNode(id))?;
st.layer_rows = vec![row];
st.locate_reveal = Some(row);
st.revision += 1;
Ok(json!({ "id": id.0, "ancestry": ancestry.iter().map(|i| i.0).collect::<Vec<_>>() }))
let ancestry: Vec<u64> = ancestry.iter().map(|i| i.0).collect();
Ok(if layers_only { json!({ "id": row.0, "objectId": id.0, "ancestry": ancestry }) } else { json!({ "id": id.0, "ancestry": ancestry }) })
}
+2
View File
@@ -29,6 +29,8 @@ mod commands;
mod common;
mod envelope;
mod mesh;
#[cfg(test)]
mod selected_tests;
pub(crate) use blend::expand_blends;
pub use commands::specs;
+2 -3
View File
@@ -657,9 +657,8 @@ pub(super) fn blend_replace_spine(s: &mut Session, _: &Value) -> Result<Value> {
}
/// Is any selected blend one made without a spine?
fn any_without_spine(s: &Session) -> bool {
let Ok(st) = s.doc() else { return false };
selected_of(s, is_blend).iter().any(|b| matches!(st.doc.node(*b).map(|n| &n.kind), Some(NodeKind::Blend { spec, .. }) if spec.no_spine))
pub(super) fn any_without_spine(s: &Session) -> bool {
super::common::any_selected_of(s, is_blend, |n| matches!(&n.kind, NodeKind::Blend { spec, .. } if spec.no_spine))
}
pub(super) fn blend_reverse_spine(s: &mut Session, _: &Value) -> Result<Value> {
+21 -11
View File
@@ -1,3 +1,5 @@
use std::collections::HashSet;
use super::mesh::whole;
use super::{
Arc, BlendEase, BlendEaseType, BlendOrientation, BlendSpacing, Document, EngineError, Node, NodeId, NodeKind, Result, Selection, Session, Value,
@@ -20,13 +22,14 @@ pub(super) fn roots_param(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
let mut sel = Selection::default();
sel.set(ids.iter().copied().filter(|id| st.doc.node(*id).is_some_and(|n| !n.is_layer())));
let ordered = sel.in_paint_order(&st.doc);
let given: HashSet<NodeId> = ordered.iter().copied().collect();
// Drop ids nested inside other given ids.
return Ok(ordered
.iter()
.copied()
.filter(|id| {
let anc = st.doc.ancestry(*id).unwrap_or_default();
!anc[..anc.len().saturating_sub(1)].iter().any(|a| ordered.contains(a))
!anc[..anc.len().saturating_sub(1)].iter().any(|a| given.contains(a))
})
.collect());
}
@@ -37,20 +40,27 @@ pub(super) fn roots_param(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
/// dynamic symbol instance's art is selected.
pub(super) fn selected_of(s: &Session, pred: fn(&Node) -> bool) -> Vec<NodeId> {
let Some(st) = s.active().filter(|st| st.selection.symbol_part.is_none()) else { return vec![] };
let mut find = st.doc.nearest_finder();
let mut seen = HashSet::new();
let mut out = vec![];
for id in &st.selection.objects {
for a in st.doc.ancestry(*id).unwrap_or_default().into_iter().rev() {
if st.doc.node(a).is_some_and(pred) {
if !out.contains(&a) {
out.push(a);
}
break;
}
if let Some(n) = find.nearest(*id, pred)
&& seen.insert(n.id)
{
out.push(n.id);
}
}
out
}
/// Whether some selected object's node of a kind ([`selected_of`]) passes `test`; stops at the
/// first one that does.
pub(super) fn any_selected_of(s: &Session, pred: fn(&Node) -> bool, test: impl Fn(&Node) -> bool) -> bool {
let Some(st) = s.active().filter(|st| st.selection.symbol_part.is_none()) else { return false };
let mut find = st.doc.nearest_finder();
st.selection.objects.iter().any(|id| find.nearest(*id, pred).is_some_and(&test))
}
pub(super) fn is_blend(n: &Node) -> bool {
matches!(n.kind, NodeKind::Blend { .. })
}
@@ -66,19 +76,19 @@ pub(super) fn is_mesh(n: &Node) -> bool {
pub(super) fn has_blend(s: &Session) -> std::result::Result<(), String> {
has_selection(s)?;
crate::cmd::edit::no_symbol_part(s)?;
if selected_of(s, is_blend).is_empty() { Err("select a blend".into()) } else { Ok(()) }
if any_selected_of(s, is_blend, |_| true) { Ok(()) } else { Err("select a blend".into()) }
}
pub(super) fn has_envelope(s: &Session) -> std::result::Result<(), String> {
has_selection(s)?;
crate::cmd::edit::no_symbol_part(s)?;
if selected_of(s, is_envelope).is_empty() { Err("select an envelope".into()) } else { Ok(()) }
if any_selected_of(s, is_envelope, |_| true) { Ok(()) } else { Err("select an envelope".into()) }
}
pub(super) fn has_mesh(s: &Session) -> std::result::Result<(), String> {
has_selection(s)?;
crate::cmd::edit::no_symbol_part(s)?;
if selected_of(s, is_mesh).is_empty() { Err("select a gradient mesh".into()) } else { Ok(()) }
if any_selected_of(s, is_mesh, |_| true) { Ok(()) } else { Err("select a gradient mesh".into()) }
}
/// Wrap `roots` (paint order) into a new node built by `make`, placed where the topmost root was.
@@ -0,0 +1,324 @@
//! The selected blend, envelope and mesh ([`selected_of`] and the checks built on it) are the ones
//! the lookup of every ancestor by id found: the same ids in the same order, the same availability
//! and errors, on selections with keys, nested blends, stale and repeated ids and a damaged tree.
use std::sync::atomic::{AtomicUsize, Ordering};
use serde_json::json;
use vectorcraft_doc::{Node, NodeId, NodeKind, SymbolPart};
use super::Session;
use super::blend::any_without_spine;
use super::common::{any_selected_of, has_blend, has_envelope, has_mesh, is_blend, is_envelope, is_mesh, selected_of};
/// [`selected_of`] as each ancestor was looked up by id: `ancestry`, then `node` for each id from
/// the object up, repeats dropped by a scan of the list.
fn selected_of_by_ids(s: &Session, pred: fn(&Node) -> bool) -> Vec<NodeId> {
let Some(st) = s.active().filter(|st| st.selection.symbol_part.is_none()) else { return vec![] };
let mut out = vec![];
for id in &st.selection.objects {
for a in st.doc.ancestry(*id).unwrap_or_default().into_iter().rev() {
if st.doc.node(a).is_some_and(pred) {
if !out.contains(&a) {
out.push(a);
}
break;
}
}
}
out
}
/// The availability [`has_blend`] and the others gave, from [`selected_of_by_ids`].
fn has_by_ids(s: &Session, pred: fn(&Node) -> bool, msg: &str) -> std::result::Result<(), String> {
super::has_selection(s)?;
crate::cmd::edit::no_symbol_part(s)?;
if selected_of_by_ids(s, pred).is_empty() { Err(msg.into()) } else { Ok(()) }
}
/// The no-spine check [`any_without_spine`] made, from [`selected_of_by_ids`].
fn without_spine_by_ids(s: &Session) -> bool {
let Ok(st) = s.doc() else { return false };
selected_of_by_ids(s, is_blend).iter().any(|b| matches!(st.doc.node(*b).map(|n| &n.kind), Some(NodeKind::Blend { spec, .. }) if spec.no_spine))
}
/// Every check on the current selection gives what the lookups by id gave.
fn agree(s: &Session, what: &str) {
type Has = fn(&Session) -> std::result::Result<(), String>;
for (name, pred, has, msg) in [
("blend", is_blend as fn(&Node) -> bool, has_blend as Has, "select a blend"),
("envelope", is_envelope, has_envelope, "select an envelope"),
("mesh", is_mesh, has_mesh, "select a gradient mesh"),
] {
let want = selected_of_by_ids(s, pred);
assert_eq!(selected_of(s, pred), want, "{what}: selected {name}s");
assert_eq!(any_selected_of(s, pred, |_| true), !want.is_empty(), "{what}: any {name}");
assert_eq!(has(s), has_by_ids(s, pred, msg), "{what}: has {name}");
}
assert_eq!(any_without_spine(s), without_spine_by_ids(s), "{what}: a blend without a spine");
}
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
s
}
fn id_of(v: &serde_json::Value) -> NodeId {
NodeId(v["id"].as_u64().unwrap())
}
fn rect(s: &mut Session, x: f64) -> NodeId {
id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 20, "height": 20})).unwrap())
}
fn select(s: &mut Session, ids: &[NodeId]) {
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
}
fn run(s: &mut Session, cmd: &str, ids: &[NodeId], p: serde_json::Value) -> NodeId {
select(s, ids);
id_of(&s.execute(cmd, &p).unwrap())
}
/// Every node id under the layers, parents before children (as Direct Selection can pick them).
fn all_ids(s: &Session) -> Vec<NodeId> {
fn walk(nodes: &[std::sync::Arc<Node>], out: &mut Vec<NodeId>) {
for n in nodes {
out.push(n.id);
if let Some(ch) = n.children() {
walk(ch, out);
}
}
}
let mut out = vec![];
for l in &s.doc().unwrap().doc.layers {
walk(l.children().map_or(&[][..], |c| c.as_slice()), &mut out);
}
out
}
/// The active document, to change in place.
fn doc_mut(s: &mut Session) -> &mut vectorcraft_doc::Document {
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc)
}
/// Set the selection's objects as given, stale and repeated ids included.
fn set_objects(s: &mut Session, ids: Vec<NodeId>) {
s.doc_mut().unwrap().selection.objects = ids;
}
/// Two blends, a blend in a key group of a third, an envelope and a mesh; one blend has no spine.
/// Returns the blends `a`, `b` and `c`, the group `g` of `c` that holds `a`, the envelope, and a key
/// of `a`.
fn document() -> (Session, [NodeId; 6]) {
let mut s = session();
let r: Vec<NodeId> = (0..10).map(|i| rect(&mut s, 40.0 * i as f64)).collect();
let a = run(&mut s, "object.blend.make", &[r[0], r[1]], json!({}));
let b = run(&mut s, "object.blend.make", &[r[2], r[3]], json!({}));
let g = run(&mut s, "object.group", &[a, r[4]], json!({}));
let c = run(&mut s, "object.blend.make", &[g, r[5]], json!({}));
let e = run(&mut s, "object.envelope.makeWithWarp", &[r[6]], json!({"style": "arch", "bend": 50}));
select(&mut s, &[r[7]]);
s.execute("object.mesh.create", &json!({"ids": [r[7].0], "rows": 1, "cols": 1})).unwrap();
if let Some(NodeKind::Blend { spec, .. }) = doc_mut(&mut s).node_mut(b).map(|n| &mut n.kind) {
spec.no_spine = true;
}
(s, [a, b, c, g, e, r[0]])
}
#[test]
fn selected_blends_envelopes_and_meshes_match_the_lookups_by_id() {
let (mut s, [a, b, c, g, e, inner_key]) = document();
s.execute("select.all", &json!({})).unwrap();
agree(&s, "select all");
let all = all_ids(&s);
let keys: Vec<NodeId> = all.iter().copied().filter(|id| ![a, b, c, g, e].contains(id)).collect();
set_objects(&mut s, keys.clone());
agree(&s, "keys, as Direct Selection picks them");
set_objects(&mut s, all.iter().rev().copied().collect());
agree(&s, "every node, children first");
set_objects(&mut s, vec![a, keys[0], b, keys[1], keys[0], NodeId(999_999), a]);
agree(&s, "repeated and stale ids, in first-seen order");
assert_eq!(selected_of(&s, is_blend), vec![a, b], "the blend with no spine is listed once, in order");
set_objects(&mut s, vec![NodeId(999_999)]);
agree(&s, "only a stale id");
set_objects(&mut s, vec![]);
agree(&s, "nothing");
// A blend in another blend's key group: the inner one.
set_objects(&mut s, vec![inner_key]);
agree(&s, "a key of a blend nested in another's key group");
assert_eq!(selected_of(&s, is_blend), vec![a]);
// An object of a dynamic symbol instance's art: nothing.
set_objects(&mut s, all.clone());
s.doc_mut().unwrap().selection.symbol_part = Some(SymbolPart { instance: a, path: vec![0] });
agree(&s, "a symbol part");
assert!(selected_of(&s, is_blend).is_empty());
}
/// A damaged tree: an earlier node of another kind with the id of a blend on the selected key's
/// path. `node` gives the earlier node, so that blend does not count, before and after the cache is
/// built again.
#[test]
fn a_repeated_id_counts_as_its_first_node() {
let (mut s, [a, _, c, _, _, inner_key]) = document();
let all = all_ids(&s);
s.doc().unwrap().doc.node(a);
let doc = doc_mut(&mut s);
if let Some(ch) = std::sync::Arc::make_mut(&mut doc.layers[0]).children_mut() {
ch.insert(0, std::sync::Arc::new(Node::group(a, vec![])));
}
set_objects(&mut s, all.clone());
agree(&s, "a repeated id, the cache older than the tree");
s.doc().unwrap().doc.drop_lookup_cache();
agree(&s, "a repeated id, no cache");
s.doc().unwrap().doc.node(a);
agree(&s, "a repeated id, cached afresh");
set_objects(&mut s, vec![inner_key]);
assert_eq!(selected_of(&s, is_blend), vec![c], "the nested blend's id is the group's, so the outer blend counts");
}
/// Large selections: with the lookup cache built, finding the selected blends looks no id up, and
/// the checks stop at the first selected object that has one.
#[test]
fn selected_blends_take_no_lookups_by_id() {
let mut s = session();
let mut keys = vec![];
for i in 0..300 {
let (x, y) = (rect(&mut s, i as f64), rect(&mut s, i as f64 + 30.0));
run(&mut s, "object.blend.make", &[x, y], json!({}));
keys.extend([x, y]);
}
for i in 0..1_000 {
rect(&mut s, i as f64);
}
s.execute("select.all", &json!({})).unwrap();
s.doc().unwrap().doc.drop_lookup_cache();
s.doc().unwrap().doc.node(keys[0]);
let before = vectorcraft_doc::path_lookups();
assert_eq!(selected_of(&s, is_blend).len(), 300);
assert!(!any_selected_of(&s, is_mesh, |_| true));
set_objects(&mut s, keys.clone());
assert_eq!(selected_of(&s, is_blend).len(), 300, "each blend once from its two keys");
assert_eq!(vectorcraft_doc::path_lookups() - before, 0, "lookups by id");
// The first key is in a blend: the check tests that key and its blend only.
static TESTED: AtomicUsize = AtomicUsize::new(0);
fn counted(n: &Node) -> bool {
TESTED.fetch_add(1, Ordering::Relaxed);
is_blend(n)
}
assert!(any_selected_of(&s, counted, |_| true));
assert_eq!(TESTED.load(Ordering::Relaxed), 2, "nodes tested");
}
/// `n` and everything under it with new ids.
fn renumber(d: &mut vectorcraft_doc::Document, n: &Node) -> Node {
let mut n = n.clone();
n.id = d.alloc_id();
if let Some(ch) = n.children_mut() {
for c in ch.iter_mut() {
*c = std::sync::Arc::new(renumber(d, c));
}
}
n
}
/// This thread's CPU time in nanoseconds, where the system reports it (Linux).
fn cpu_ns() -> Option<u64> {
std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok()
}
/// Milliseconds one call of `f` takes over `calls` calls, in CPU time where the system reports it,
/// otherwise in wall-clock time.
fn ms_per_call(calls: u32, f: &dyn Fn()) -> f64 {
let (cpu, wall) = (cpu_ns(), std::time::Instant::now());
for _ in 0..calls {
f();
}
let ms = match (cpu, cpu_ns()) {
(Some(a), Some(b)) => b.saturating_sub(a) as f64 / 1e6,
_ => wall.elapsed().as_secs_f64() * 1e3,
};
ms / f64::from(calls)
}
/// The medians of 7 runs of `a` and of `b`, the runs taking turns.
fn medians(calls: u32, a: &dyn Fn(), b: &dyn Fn()) -> (f64, f64) {
let (mut ta, mut tb) = (vec![], vec![]);
for _ in 0..7 {
ta.push(ms_per_call(calls, a));
tb.push(ms_per_call(calls, b));
}
ta.sort_by(f64::total_cmp);
tb.sort_by(f64::total_cmp);
(ta[3], tb[3])
}
/// Timings of the lookups by id and of the one-path lookup on 100,000 rectangles in 10 layers,
/// 2,000 two-key blends (every fourth one in a group) and 200 envelopes, all selected. Run with
/// `cargo test --release -p vectorcraft-engine --lib selected_tests::timing -- --ignored --nocapture`.
#[test]
#[ignore = "timing; run by hand"]
fn timing_of_the_selected_blend_checks() {
let mut s = session();
let (a, b, c) = (rect(&mut s, 0.0), rect(&mut s, 40.0), rect(&mut s, 80.0));
let square = rect(&mut s, 120.0);
let blend = run(&mut s, "object.blend.make", &[a, b], json!({}));
let envelope = run(&mut s, "object.envelope.makeWithWarp", &[c], json!({"style": "arch", "bend": 50}));
let doc = doc_mut(&mut s);
let templates: Vec<Node> = [square, blend, envelope].iter().map(|id| doc.node(*id).cloned().unwrap()).collect();
let mut layers = vec![];
for l in 0..10 {
let mut layer = Node::layer(doc.alloc_id(), &format!("Layer {l}"), vectorcraft_doc::LayerColor::Preset(0));
let mut kids = vec![];
for _ in 0..10_000 {
kids.push(std::sync::Arc::new(renumber(doc, &templates[0])));
}
for i in 0..200 {
let b = renumber(doc, &templates[1]);
let b = if i % 4 == 0 { Node::group(doc.alloc_id(), vec![std::sync::Arc::new(b)]) } else { b };
kids.push(std::sync::Arc::new(b));
}
for _ in 0..20 {
kids.push(std::sync::Arc::new(renumber(doc, &templates[2])));
}
if let Some(ch) = layer.children_mut() {
*ch = kids;
}
layers.push(std::sync::Arc::new(layer));
}
doc.layers = layers;
s.execute("select.all", &json!({})).unwrap();
let first = s.doc().unwrap().selection.objects[0];
s.doc().unwrap().doc.drop_lookup_cache();
s.doc().unwrap().doc.node(first);
println!("{} objects selected", s.doc().unwrap().selection.objects.len());
type Check = fn(&Session) -> bool;
let checks: [(&str, Check, Check); 5] = [
("has_blend", |s| has_by_ids(s, is_blend, "").is_ok(), |s| has_blend(s).is_ok()),
("has_envelope", |s| has_by_ids(s, is_envelope, "").is_ok(), |s| has_envelope(s).is_ok()),
("has_mesh", |s| has_by_ids(s, is_mesh, "").is_ok(), |s| has_mesh(s).is_ok()),
(
"selected blends (object.blend.info and the Blend commands)",
|s| !selected_of_by_ids(s, is_blend).is_empty(),
|s| !selected_of(s, is_blend).is_empty(),
),
("a blend without a spine (Reverse Spine, the Blend panel)", without_spine_by_ids, any_without_spine),
];
assert_eq!(selected_of(&s, is_blend), selected_of_by_ids(&s, is_blend));
println!("| Check | Lookups by id (ms) | One path (ms) |");
println!("|---|---:|---:|");
for (name, by_ids, one_path) in checks {
assert_eq!(by_ids(&s), one_path(&s), "{name}");
let (old, new) = medians(
15,
&|| {
std::hint::black_box(by_ids(&s));
},
&|| {
std::hint::black_box(one_path(&s));
},
);
println!("| {name} | {old:.3} | {new:.3} |");
}
}
+34 -2
View File
@@ -7,12 +7,16 @@
//! panel's New Art Has Basic Appearance off, the whole appearance of the last selection. With the
//! option on (the default) an inherited appearance gives new art its top stroke's options only,
//! and a change of selection loads only the proxies. `paint.default` resets it.
//!
//! A document whose Default Graphic Style no longer has the shipped look (a New Document profile
//! redefined it) gives the reset that style's fills, strokes and effects instead, and `file.new`
//! resets new art when it opens such a document.
use std::borrow::Cow;
use serde_json::{Value, json};
use vectorcraft_color::{BlendMode, Paint};
use vectorcraft_doc::{Appearance, AppearanceItem, FillLayer, GraphicStyle, Node, NodeKind, StrokeLayer};
use vectorcraft_doc::{Appearance, AppearanceItem, ColorMode, DEFAULT_GRAPHIC_STYLE, Document, FillLayer, GraphicStyle, Node, NodeKind, StrokeLayer};
use vectorcraft_tools::PaintDefaults;
use super::gradient::unplaced;
@@ -263,7 +267,35 @@ fn describe(s: &mut Session, _: &Value) -> Result<Value> {
}))
}
/// The defaults for new art reset (`paint.default`): white fill, 1 pt black stroke, no template.
/// The defaults for new art reset (`paint.default`): white fill, 1 pt black stroke, no template;
/// in a document whose Default Graphic Style was redefined, that style's fills, strokes and effects
/// at full opacity, not linked to the style.
pub(crate) fn reset(s: &mut Session) {
s.paint = PaintDefaults::default();
let style = s.doc().ok().and_then(|st| redefined_default_style(&st.doc)).cloned();
if let Some(g) = style {
let ap = if g.unit_box { g.appearance } else { unplace_all(g.appearance) };
s.take_new_art(ap, 1.0, BlendMode::Normal, None, false);
}
}
/// `d`'s Default Graphic Style when its fills, strokes, effects or transparency differ from the
/// shipped style's (white fill, 1 pt black stroke), the shipped colors converted to `d`'s color mode
/// as a New Document profile's are.
pub(crate) fn redefined_default_style(d: &Document) -> Option<&GraphicStyle> {
let g = d.graphic_styles.iter().find(|g| g.name == DEFAULT_GRAPHIC_STYLE)?;
let same =
|o: &GraphicStyle| (&o.appearance, o.opacity, o.blend, o.isolate, o.knockout) == (&g.appearance, g.opacity, g.blend, g.isolate, g.knockout);
if same(&GraphicStyle::new(DEFAULT_GRAPHIC_STYLE, Appearance::default_art())) {
return None;
}
if d.color_mode != ColorMode::Rgb {
let mut shipped = Document::new_with_mode(1.0, 1.0, ColorMode::Rgb);
shipped.graphic_styles.retain(|o| o.name == DEFAULT_GRAPHIC_STYLE);
super::colormgmt::set_color_mode(&mut shipped, d.color_mode, true, None, super::colormgmt::Grays::Profile);
if shipped.graphic_styles.first().is_some_and(same) {
return None;
}
}
Some(g)
}
+4
View File
@@ -814,6 +814,10 @@ pub(crate) fn file_new(s: &mut Session, p: &Value) -> Result<Value> {
// The profile's links keep their relative paths, which name places from the profile's file, as
// a new document from a history state keeps its source's.
s.doc_mut()?.links_from = links_from;
// A profile whose Default Graphic Style was redefined gives new art in the document that style.
if super::newart::redefined_default_style(&s.doc()?.doc).is_some() {
super::newart::reset(s);
}
// Overprint Preview is the engine's (the UI turns Pixel Preview on from `previewMode`). Both
// are views of the whole app, so Default leaves them as they are.
if settings.preview_mode == PreviewMode::Overprint {
+1
View File
@@ -42,3 +42,4 @@ pub(crate) use pixelgrid::{
};
pub(super) use shape::recut;
pub(crate) use transform::{apply_transform, preview_copies, scaling, transform_node, transform_patterns, transforms_objects};
pub use transform::{reflect_axis, scale_factors, shear_tangent};
+14 -3
View File
@@ -384,6 +384,11 @@ fn add_drawn_live_paint(s: &mut Session, isolated: NodeId, next: Option<NodeId>)
}
pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result<Value> {
let key = "all";
let all = match p.get(key) {
None => false,
Some(v) => v.as_bool().ok_or_else(|| bad("object.exitIsolation", format!("`{key}` must be true or false")))?,
};
// Opacity mask editing, pattern editing and symbol editing isolate their editing layer. Leaving
// isolation mode then leaves that mode, as Stop Editing Opacity Mask and the isolation bar's
// Done do. A group isolated inside the symbol's art goes back to the symbol's layer.
@@ -419,12 +424,18 @@ pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result<Value> {
return ok();
}
let menu = s.menu.clone();
let prev = s.active().and_then(|d| d.isolation);
let prev = st.isolation;
// An isolated sublayer goes up to its parent layer, which stays isolated, unless `all` is true or
// that layer is hidden or locked; anything else leaves isolation mode.
let up = prev
.filter(|i| !all && st.doc.node(*i).is_some_and(Node::is_layer))
.and_then(|i| st.doc.parent_of(i))
.filter(|parent| st.doc.is_editable(*parent));
if let Some(i) = prev {
crate::cmd::settle_interaction(s)?;
let left = add_drawn_live_paint(s, i, None)?.unwrap_or(i);
let left = add_drawn_live_paint(s, i, up)?.unwrap_or(i);
let st = s.doc_mut()?;
st.isolation = None;
st.isolation = up;
crate::cmd::distortcmds::finish_edit_text(st, i);
let target = st.doc.parent_of(left).filter(|p| st.doc.node(*p).is_some_and(|n| n.extras().shaper.is_some())).unwrap_or(left);
st.selection.set([target]);
+1 -1
View File
@@ -59,7 +59,7 @@ fn bounds_transform(s: &Session, p: &Value, ids: Vec<NodeId>, least: f64, anchor
let refi = reference_index(p)?;
let st = s.doc()?;
check_switches(p, &TRANSFORM_SWITCHES, "object.setBounds")?;
check_switches(p, &["proportional"], "object.setBounds")?;
check_switches(p, &["proportional", "interpolate"], "object.setBounds")?;
let how = s.bounds_measure();
if anchors
&& transforms_objects(p)
+8 -8
View File
@@ -16,7 +16,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Transform",
[],
None,
"{matrix: [a,b,c,d,e,f], copy?: bool, ids?, strokes?: bool, corners?: bool, typeAreas?: bool, anchors?: bool, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), releaseOutside?: bool} apply an affine to the selection (or ids); anchors (without ids or copy): paths with anchors selected with Direct Selection have only those anchors and their handles transformed, as the Transform tools and object.move/rotate/scale/reflect/shear do (default: the whole objects); strokes/corners: Scale Strokes & Effects / Scale Corners (default: the preferences); typeAreas: area type among them (not type inside a group) reshapes its frame by the matrix and its text reflows at its size, as a bounding-box handle drag does (default: the type transforms too); releaseOutside (without copy or anchors): a Shaper Group's original shape that ends wholly outside the bounds the group's original shapes had before takes shaper.releaseSource in the same undo step, named Remove from Shaper Group, as the Selection tool's moves in Construction mode do",
"{matrix: [a,b,c,d,e,f], copy?: bool, ids?, strokes?: bool, corners?: bool, typeAreas?: bool, anchors?: bool, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), releaseOutside?: bool, interpolate?: bool (with anchors and a matrix that only moves them: the handles of each segment with one moved end are re-mapped, as path.moveAnchors's; default: prefs interpolateControlPoints)} apply an affine to the selection (or ids); anchors (without ids or copy): paths with anchors selected with Direct Selection have only those anchors and their handles transformed, as the Transform tools and object.move/rotate/scale/reflect/shear do (default: the whole objects); strokes/corners: Scale Strokes & Effects / Scale Corners (default: the preferences); typeAreas: area type among them (not type inside a group) reshapes its frame by the matrix and its text reflows at its size, as a bounding-box handle drag does (default: the type transforms too); releaseOutside (without copy or anchors): a Shaper Group's original shape that ends wholly outside the bounds the group's original shapes had before takes shaper.releaseSource in the same undo step, named Remove from Shaper Group, as the Selection tool's moves in Construction mode do",
has_doc,
transform
),
@@ -25,7 +25,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Move…",
["Object", "Transform"],
Some("Cmd+Shift+M"),
"{ids?: [id…] (selected first; default: the selection), dx, dy, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.",
"{ids?: [id…] (selected first; default: the selection), dx, dy, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), interpolate?: bool (as path.moveAnchors's; default: prefs interpolateControlPoints)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.",
has_selection_or_guides,
move_cmd
),
@@ -61,7 +61,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Shear…",
["Object", "Transform"],
None,
"{ids?: [id…] (selected first; default: the selection), angle: deg (positive turns the vertical edges clockwise with the horizontal axis, the top to the right; the horizontal edges clockwise with the vertical axis, the right side down), axis?: \"horizontal\"|\"vertical\", origin?, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.",
"{ids?: [id…] (selected first; default: the selection), angle: deg (-359 to 359, sheared by its tangent, so 120 slants as -60; 0 and ±180 have no slant and, without copy, change nothing; ±90 and ±270 are an error; positive turns the vertical edges clockwise with the horizontal axis, the top to the right; the horizontal edges clockwise with the vertical axis, the right side down), axis?: \"horizontal\"|\"vertical\"|deg (the line the art slides along, counter-clockwise from horizontal on the page, -359 to 359; 0: horizontal, 90: vertical; omitted: horizontal), origin?, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.",
has_selection,
shear
),
@@ -70,7 +70,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Transform Again",
["Object", "Transform"],
Some("Cmd+D"),
"{copy?, strokes?, corners?, patterns?, typeAreas?: bool (as object.transform's; default: the value the transform it repeats used, else object.transform's default)} the last transform's matrix on the selection (after a perspective move or scale: that plane-space transform, without these params)",
"{copy?, strokes?, corners?, patterns?, typeAreas?, interpolate?: bool (as object.transform's; default: the value the transform it repeats used, else object.transform's default)} the last transform's matrix on the selection (after a perspective move or scale: that plane-space transform, without these params)",
has_selection,
transform_again
),
@@ -79,7 +79,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Nudge",
[],
None,
"{dx: -1|0|1, dy: -1|0|1, big?: bool (×10), copy?: bool, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move)} arrow-key nudge by the keyboard increment (the selected anchors, else objects, along the x and y axes turned by the constrainAngle preference; else ruler guides, along the page axes)",
"{dx: -1|0|1, dy: -1|0|1, big?: bool (×10), copy?: bool, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move), interpolate?: bool (as path.moveAnchors's; default: prefs interpolateControlPoints)} arrow-key nudge by the keyboard increment (the selected anchors, else objects, along the x and y axes turned by the constrainAngle preference; else ruler guides, along the page axes)",
has_selection_or_guides,
nudge
),
@@ -250,7 +250,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Exit Isolation Mode",
[],
None,
"{} leave isolation mode; leaving an isolated Live Paint group adds the paths, compound paths and groups of them drawn in it (shown and unlocked with everything in them) to the group as livePaint.merge does, in one undo step, and leaves type, images and other objects in it as they are; object.isolate on a level outside the group does the same",
"{all?: bool (default false)} leave isolation mode; from an isolated sublayer, go up one level to its parent layer instead (the next call goes up again), unless all is true or the parent layer is hidden or locked; no undo step for the move up; while a symbol is edited, a group isolated in its art goes back to the symbol's layer first, with or without all; leaving an isolated Live Paint group adds the paths, compound paths and groups of them drawn in it (shown and unlocked with everything in them) to the group as livePaint.merge does, in one undo step, and leaves type, images and other objects in it as they are; object.isolate on a level outside the group does the same",
has_doc,
exit_isolation
),
@@ -295,7 +295,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Set Bounds",
[],
None,
"{x?, y?, width?, height?, reference?: whole number >= 0 (9-point grid 0..8; 0.0 equals 0; a whole number past 8 is read as 8; omitted/null: center, 4), proportional?, strokes?, corners?, copy?: bool, patterns?: bool (Transform Patterns), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move)} (Transform panel; width/height and the reference point follow the bounding box, rotated with rotated objects; x, y are page coordinates; with Use Preview Bounds the values measure the visual bounds; with the typeGlyphBounds preference, each point type object selected as an object (not inside a selected group) is measured by its glyphs' ink (underline and strikethrough included), which the scale gives the size asked for; strokes/corners as object.scale; with anchor points selected (Direct Selection) and no copy, the values are the box around those points, square to the page, and only they move or scale, as with object.move (#1824))",
"{x?, y?, width?, height?, reference?: whole number >= 0 (9-point grid 0..8; 0.0 equals 0; a whole number past 8 is read as 8; omitted/null: center, 4), proportional?, strokes?, corners?, copy?: bool, patterns?: bool (Transform Patterns), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move), interpolate?: bool (with anchor points selected and only x or y changed: as path.moveAnchors's; default: prefs interpolateControlPoints)} (Transform panel; width/height and the reference point follow the bounding box, rotated with rotated objects; x, y are page coordinates; with Use Preview Bounds the values measure the visual bounds; with the typeGlyphBounds preference, each point type object selected as an object (not inside a selected group) is measured by its glyphs' ink (underline and strikethrough included), which the scale gives the size asked for; strokes/corners as object.scale; with anchor points selected (Direct Selection) and no copy, the values are the box around those points, square to the page, and only they move or scale, as with object.move (#1824))",
has_selection,
set_bounds
),
@@ -305,7 +305,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Live Shape Properties",
[],
None,
"{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding, as in the reference app: store radii as fractions of each corner's maximum so they scale with the shape), corners?: [i…], items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse)} (Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius)",
"{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding, as in the reference app: store radii as fractions of each corner's maximum so they scale with the shape), corners?: [i…], items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint)} (Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)",
has_selection,
set_live_shape
),
+71 -3
View File
@@ -6,6 +6,7 @@ use super::{
BTreeSet, CornerKind, EngineError, LiveCorners, LiveShape, NodeId, NodeKind, Result, Session, Value, bad, check_numbers, check_switches,
convert_radii_relative, ok, selected_roots, set_corners, targets,
};
use crate::MAX_COORD;
/// The largest scale of 0 or more at which `spans`, with the margins that scale grown by `k`,
/// reach across `size` together. Returns 1 when their geometric boxes reach 1e-9 or less across
@@ -98,8 +99,32 @@ fn corners_param(p: &Value) -> Result<Option<BTreeSet<usize>>> {
list.iter().map(|k| k.as_u64().and_then(|k| usize::try_from(k).ok()).ok_or_else(err)).collect::<Result<_>>().map(Some)
}
/// Live line `l` with Line Length `len` (its first end stays) and then Line Angle `angle` (about
/// its midpoint; a line whose ends meet has none to turn), or None when neither changes it.
fn line_edit(l: &LiveShape, len: Option<f64>, angle: Option<f64>) -> Option<LiveShape> {
let now = l.line_length()?;
let mut new = l.clone();
let mut changed = false;
if let Some(len) = len
&& (len - now).abs() > 1e-9 * len.max(now)
{
new.set_line_length(len);
changed = true;
}
if let Some(a) = angle
&& new.line_length().is_some_and(|n| n > 0.0)
&& let Some(turn) = new.line_angle().map(|now| (a - now).rem_euclid(360.0))
&& turn > 1e-9
&& turn < 360.0 - 1e-9
{
new.set_line_angle(a);
changed = true;
}
(changed && new != *l).then_some(new)
}
pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
check_switches(p, &["invertPie", "makeSidesEqual", "relativeRadii"], "object.setLiveShape")?;
check_switches(p, &["constrainPie", "invertPie", "makeSidesEqual", "relativeRadii"], "object.setLiveShape")?;
check_numbers(p, &["radius", "sides"], "object.setLiveShape")?;
// `items`: objects each with its own `corners`; else `ids` (or the selection) sharing them.
let items = match p.get("items").filter(|v| !v.is_null()) {
@@ -148,7 +173,7 @@ 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 length = |k: &str| number(k, |x| x > 0.0 && x <= MAX_COORD, "a length in points above 0");
// Saved steps ([`Session::replay`]) can hold values a direct call refuses, recorded before these
// checks: a negative radius is 0, a whole side count of 0 or more is brought into 3 to 1000, and
// a fractional or negative one is ignored. A whole number written as 5.0 counts as 5, as in a
@@ -168,21 +193,58 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
// 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);
// Constrain Pie Angle: the one angle given moves the other by as much, so each ellipse keeps
// its span (its end angle less its start angle, counterclockwise).
let constrain = p.get("constrainPie").and_then(Value::as_bool) == Some(true);
if constrain && (invert || pie_start.is_some() == pie_end.is_some()) {
return Err(bad("object.setLiveShape", "`constrainPie` needs one of `pieStart` and `pieEnd`, without `invertPie`"));
}
// A polygon's Polygon Properties: its angle, radius or side length, Make Sides Equal.
let (polygon_angle, polygon_radius, side) = (angle("polygonAngle")?, length("polygonRadius")?, length("sideLength")?);
let equal = p.get("makeSidesEqual").and_then(Value::as_bool) == Some(true);
// A line's Line Properties: its length (its first end stays) and its angle (about its midpoint).
// A line's length can reach across the whole canvas, past `MAX_COORD`: its ends are checked below.
let line_length = number("lineLength", |x| x > 0.0, "a length in points above 0")?;
let line_angle = angle("lineAngle")?;
// An ellipse's pie becomes `pie_of(pie)`. An end of 0 is a full turn (Illustrator shows a whole
// ellipse as 0° to 360°).
let end_of = |a: f64| if a == 0.0 { 360.0 } else { a };
let pie_of = |pie: (f64, f64)| {
let pie = (pie_start.unwrap_or(pie.0), pie_end.map_or(pie.1, end_of));
let span = (pie.1 - pie.0).rem_euclid(360.0);
let pie = match (constrain, pie_start, pie_end) {
// The angle it already has: nothing moves.
(true, Some(a), _) if a == pie.0 => pie,
(true, _, Some(a)) if end_of(a) == pie.1 => pie,
// A whole ellipse (a span of 0) stays whole.
(true, Some(a), _) => (a, end_of((a + span).rem_euclid(360.0))),
(true, _, Some(a)) => ((a - span).rem_euclid(360.0), end_of(a)),
_ => (pie_start.unwrap_or(pie.0), pie_end.map_or(pie.1, end_of)),
};
if invert { (pie.1.rem_euclid(360.0), end_of(pie.0)) } else { pie }
};
// When every value given is the current one, the document and its undo history stay as they
// are.
let st = s.doc()?;
// The lines that Line Length or Line Angle changes, as they become. A line that would reach
// past the document's coordinate limit is an error before anything changes.
let mut lines = std::collections::BTreeMap::new();
if line_length.is_some() || line_angle.is_some() {
for id in &ids {
let Some(NodeKind::Path { live: Some(l), .. }) = st.doc.node(*id).map(|n| &n.kind) else { continue };
if let Some(new) = line_edit(l, line_length, line_angle) {
let LiveShape::Line { a, b } = &new else { continue };
if ![a.x, a.y, b.x, b.y].iter().all(|c| c.abs() <= MAX_COORD) {
return Err(bad("object.setLiveShape", format!("coordinate out of range (limit ±{MAX_COORD} pt)")));
}
lines.insert(*id, new);
}
}
}
let has_values = |id: &NodeId| {
let Some(NodeKind::Path { path, live, .. }) = st.doc.node(*id).map(|n| &n.kind) else { return true };
if lines.contains_key(id) {
return false;
}
match live.as_deref() {
Some(l @ LiveShape::Polygon { sides: now, .. })
if !(sides.is_none_or(|n| n.clamp(3, 1000) == u64::from(*now))
@@ -244,6 +306,12 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
}
*path = l.to_path();
}
if let Some(new) = lines.get(id)
&& let Some(l) = live.as_deref_mut()
{
*l = new.clone();
*path = l.to_path();
}
if let Some(on) = relative_radii
&& let Some(l) = live.as_deref_mut()
{
+83 -22
View File
@@ -125,9 +125,14 @@ fn apply_transform_moving_guides(
let d = &s.doc()?.doc;
let paths = d.index_paths(ids.iter().copied());
let none = paths.is_empty() && !has_guides;
// A move of direct-selected anchors may re-map the handles beside them (`interpolate`).
let mut interpolate = None;
let ids = if anchors && objects && !copy && !s.doc()?.selection.anchors.is_empty() {
if c[..4] == [1.0, 0.0, 0.0, 1.0] {
interpolate = Some(crate::cmd::path::interpolates_handles(s, p, label)?);
}
if xf != Affine::IDENTITY {
crate::cmd::path::transform_anchors(s, label, xf, sc)?;
crate::cmd::path::transform_anchors(s, label, xf, sc, interpolate.unwrap_or(false))?;
}
ids
} else if none || (!copy && xf == Affine::IDENTITY) {
@@ -195,6 +200,9 @@ fn apply_transform_moving_guides(
options["strokes"] = json!(sc.strokes);
options["corners"] = json!(!sc.keep_corners);
}
if let Some(on) = interpolate {
options["interpolate"] = json!(on);
}
st.last_transform = Some(LastTransform::Matrix(xf, options));
st.last_perspective = None;
}
@@ -248,7 +256,7 @@ fn resize_type_area(n: &mut Node, xf: Affine) -> bool {
pub(super) fn transform(s: &mut Session, p: &Value) -> Result<Value> {
check_switches(p, &TRANSFORM_SWITCHES, "object.transform")?;
check_switches(p, &["anchors", "releaseOutside"], "object.transform")?;
check_switches(p, &["anchors", "releaseOutside", "interpolate"], "object.transform")?;
let m = matrix_param(p, "matrix").ok_or_else(|| bad("object.transform", "missing matrix [a,b,c,d,e,f]"))?;
// An object selected in a symbol instance's art stays where the symbol puts it: the selection
// is left as it is, and the reply's warning goes to the status bar.
@@ -292,6 +300,7 @@ pub(super) fn transform(s: &mut Session, p: &Value) -> Result<Value> {
pub(super) fn move_cmd(s: &mut Session, p: &Value) -> Result<Value> {
check_numbers(p, &["dx", "dy"], "object.move")?;
check_switches(p, &TRANSFORM_SWITCHES, "object.move")?;
check_switches(p, &["interpolate"], "object.move")?;
let ids = selected_roots_to_transform(s)?;
apply_transform(s, "Move", ids, Affine::translate((f64_or(p, "dx", 0.0), f64_or(p, "dy", 0.0))), p, true)
}
@@ -311,7 +320,7 @@ pub(crate) fn along_constrain_angle(dx: f64, dy: f64, deg: f64) -> (f64, f64) {
pub(super) fn nudge(s: &mut Session, p: &Value) -> Result<Value> {
check_numbers(p, &["dx", "dy"], "object.nudge")?;
check_switches(p, &TRANSFORM_SWITCHES, "object.nudge")?;
check_switches(p, &["big"], "object.nudge")?;
check_switches(p, &["big", "interpolate"], "object.nudge")?;
let k = s.prefs.keyboard_increment * if bool_or(p, "big", false) { 10.0 } else { 1.0 };
let (dx, dy) = (f64_or(p, "dx", 0.0) * k, f64_or(p, "dy", 0.0) * k);
// Guides keep to the page's axes; art and anchors move along the constrain angle's.
@@ -322,7 +331,7 @@ pub(super) fn nudge(s: &mut Session, p: &Value) -> Result<Value> {
if dx == 0.0 && dy == 0.0 {
return ok();
}
return crate::cmd::path::move_anchors(s, &json!({ "dx": dx, "dy": dy, "patterns": p.get("patterns") }));
return crate::cmd::path::move_anchors(s, &json!({ "dx": dx, "dy": dy, "patterns": p.get("patterns"), "interpolate": p.get("interpolate") }));
}
if s.doc()?.selection.is_empty() {
let copy = bool_or(p, "copy", false);
@@ -360,15 +369,22 @@ pub(super) fn scale(s: &mut Session, p: &Value) -> Result<Value> {
check_switches(p, &TRANSFORM_SWITCHES, "object.scale")?;
let ids = selected_roots_to_transform(s)?;
let o = origin_of(s, p, &ids)?;
let sx = f64_req(p, "sx", "object.scale")? / 100.0;
let sy = f64_or(p, "sy", sx * 100.0) / 100.0;
if sx == 0.0 || sy == 0.0 {
return Err(bad("object.scale", "scale must be non-zero"));
}
let sx = f64_req(p, "sx", "object.scale")?;
let (sx, sy) = scale_factors(sx, f64_or(p, "sy", sx)).map_err(|e| bad("object.scale", e))?;
let frame = basis_frame(s, p, "object.scale", &ids)?;
apply_transform(s, "Scale", ids, about(o, frame.conjugate(Affine::scale_non_uniform(sx, sy))), p, true)
}
/// The factors `object.scale` applies for `sx` and `sy` in percent, or the error it returns when
/// either factor is 0.
pub fn scale_factors(sx: f64, sy: f64) -> std::result::Result<(f64, f64), String> {
let (sx, sy) = (sx / 100.0, sy / 100.0);
if sx == 0.0 || sy == 0.0 {
return Err("scale must be non-zero".into());
}
Ok((sx, sy))
}
/// The frame that `object.scale` and a named `object.reflect` act in, from the `basis` param:
/// `"box"` (the default) is the bounding box of `ids`, turned with rotated objects until Reset
/// Bounding Box ([`Document::bbox_angle`]); `"page"` is the page's axes. Anchors selected with
@@ -393,16 +409,7 @@ pub(super) fn reflect(s: &mut Session, p: &Value) -> Result<Value> {
let ids = selected_roots_to_transform(s)?;
let o = origin_of(s, p, &ids)?;
// A named axis is the bounding box's own (see [`basis_frame`]); an angle is a line on the page.
let named = match p.get("axis") {
Some(Value::String(a)) if a == "horizontal" => Some(Affine::scale_non_uniform(1.0, -1.0)),
Some(Value::Number(_)) => None,
None | Some(Value::Null) => Some(Affine::scale_non_uniform(-1.0, 1.0)),
Some(Value::String(a)) if a == "vertical" => Some(Affine::scale_non_uniform(-1.0, 1.0)),
Some(v) => {
let given = v.as_str().map_or_else(|| v.to_string(), str::to_string);
return Err(bad("object.reflect", format!("axis must be \"vertical\", \"horizontal\" or an angle in degrees, not `{given}`")));
}
};
let named = reflect_axis(p.get("axis")).map_err(|e| bad("object.reflect", e))?;
let m = match named {
Some(m) => basis_frame(s, p, "object.reflect", &ids)?.conjugate(m),
None => {
@@ -414,22 +421,76 @@ pub(super) fn reflect(s: &mut Session, p: &Value) -> Result<Value> {
apply_transform(s, "Reflect", ids, about(o, m), p, true)
}
/// The reflection `object.reflect` applies for its `axis` param: the matrix for a named axis
/// (`"vertical"`, the default, or `"horizontal"`), in the bounding box's frame; `None` for an angle,
/// which is a line on the page; or the error for any other value.
pub fn reflect_axis(axis: Option<&Value>) -> std::result::Result<Option<Affine>, String> {
match axis {
Some(Value::String(a)) if a == "horizontal" => Ok(Some(Affine::scale_non_uniform(1.0, -1.0))),
Some(Value::Number(_)) => Ok(None),
None | Some(Value::Null) => Ok(Some(Affine::scale_non_uniform(-1.0, 1.0))),
Some(Value::String(a)) if a == "vertical" => Ok(Some(Affine::scale_non_uniform(-1.0, 1.0))),
Some(v) => {
let given = v.as_str().map_or_else(|| v.to_string(), str::to_string);
Err(format!("axis must be \"vertical\", \"horizontal\" or an angle in degrees, not `{given}`"))
}
}
}
/// Angles closer than this many degrees to ±90 or ±270, or to 0 or ±180, count as those angles. It
/// is far above the rounding error of an angle up to 359° and below any angle a field shows.
const SHEAR_ANGLE_TOLERANCE: f64 = 1e-9;
/// The slant `object.shear` applies for `angle` in degrees: its tangent, and 0 for 0 and ±180. An
/// angle outside -359 to 359, or ±90 or ±270, is an error.
pub fn shear_tangent(angle: f64) -> std::result::Result<f64, String> {
if !(-359.0..=359.0).contains(&angle) {
return Err(format!("`angle` must be from -359 to 359 degrees, not {angle}"));
}
// ±90 and ±270 slant an edge onto the shear axis: their tangent is unbounded.
let flat = angle.rem_euclid(180.0);
if (flat - 90.0).abs() < SHEAR_ANGLE_TOLERANCE {
return Err(format!("`angle` cannot be {angle}: ±90 and ±270 degrees have no shear"));
}
// 0 and ±180 have no slant, but the tangent of ±180° in radians is about 1e-16, not 0.
Ok(if flat < SHEAR_ANGLE_TOLERANCE || 180.0 - flat < SHEAR_ANGLE_TOLERANCE { 0.0 } else { angle.to_radians().tan() })
}
pub(super) fn shear(s: &mut Session, p: &Value) -> Result<Value> {
check_numbers(p, &["angle"], "object.shear")?;
check_switches(p, &TRANSFORM_SWITCHES, "object.shear")?;
let t = shear_tangent(f64_or(p, "angle", 0.0)).map_err(|e| bad("object.shear", e))?;
let ids = selected_roots_to_transform(s)?;
let o = origin_of(s, p, &ids)?;
let t = f64_or(p, "angle", 0.0).clamp(-89.0, 89.0).to_radians().tan();
let vertical = choice(p, "object.shear", "axis", &["horizontal", "vertical"])? == Some("vertical");
let m = if vertical { Affine::new([1.0, t, 0.0, 1.0, 0.0, 0.0]) } else { Affine::new([1.0, 0.0, -t, 1.0, 0.0, 0.0]) };
let horizontal = Affine::new([1.0, 0.0, -t, 1.0, 0.0, 0.0]);
// A named axis, or a line on the page at an angle in degrees, counter-clockwise from horizontal.
let m = match p.get("axis") {
None | Some(Value::Null) => horizontal,
Some(Value::String(a)) if a == "horizontal" => horizontal,
Some(Value::String(a)) if a == "vertical" => Affine::new([1.0, t, 0.0, 1.0, 0.0, 0.0]),
Some(Value::Number(n)) if n.as_f64().is_some_and(|a| (-SHEAR_AXIS_MAX..=SHEAR_AXIS_MAX).contains(&a)) => {
// y is down, so the page's counter-clockwise angle turns the other way on screen.
let r = -n.as_f64().unwrap_or(0.0).to_radians();
Affine::rotate(r) * horizontal * Affine::rotate(-r)
}
Some(v) => {
let given = v.as_str().map_or_else(|| v.to_string(), str::to_string);
let range = format!("from -{SHEAR_AXIS_MAX} to {SHEAR_AXIS_MAX}");
return Err(bad("object.shear", format!("axis must be \"horizontal\", \"vertical\" or an angle in degrees {range}, not `{given}`")));
}
};
apply_transform(s, "Shear", ids, about(o, m), p, true)
}
/// The largest angle, either way from horizontal, of the axis `object.shear` takes in degrees.
const SHEAR_AXIS_MAX: f64 = 359.0;
/// The last transform on the selection, with the options `last_transform` keeps for it; an option
/// that `p` sets to true or false (a recorded Transform Again's) takes precedence. A Transform
/// Each is repeated by running it again (its transform is per object, about each one's bounds).
pub(super) fn transform_again(s: &mut Session, p: &Value) -> Result<Value> {
check_switches(p, &TRANSFORM_SWITCHES, "object.transformAgain")?;
check_switches(p, &["interpolate"], "object.transformAgain")?;
if let Some(again) = s.doc()?.last_perspective.clone() {
return crate::cmd::distortcmds::transform_again(s, &again);
}
+64 -19
View File
@@ -24,7 +24,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Package",
[],
None,
"{folder?, name?: (default: \"<document> Folder\"), copyLinks?: true, linksFolder?: true (the linked files go in Links/, else next to the document), relink?: true (the packaged document links to the copies), copyFonts?: true (the fonts its type uses go in Fonts/; fonts whose licence doesn't allow embedding are left out), report?: true (<document> Report.txt)} copy the saved document as it is now into folder/name as <document>.vectorcraft with its linked files and fonts; the open document doesn't change → {folder, files: [paths relative to folder/name], links, fonts (counts copied), missingLinks: [file names not found], skippedFonts: [{font, reason}], warnings: [nested files copied unchanged or cycles/depth stopped]}; no folder → the same with {name: \"<name>.zip\", dataBase64} (a zip of the files in <name>/) instead of folder. The warnings and the report name a file outside the automation read roots by its file name. Under automation read roots, the package is refused, before any file is written, while the document, or a linked native document or a linked PDF, .ai or EPS file's native document, links a JavaScript file outside them (svgInteractivity; a URL is not checked)",
"{folder?, name?: (default: \"<document> Folder\"), copyLinks?: true, linksFolder?: true (the linked files go in Links/, else next to the document), relink?: true (the packaged document links to the copies), copyFonts?: true (the fonts its type uses go in Fonts/; fonts whose licence doesn't allow embedding are left out), report?: true (<document> Report.txt)} copy the saved document as it is now into folder/name as <document>.vectorcraft with its linked files and fonts; the open document doesn't change → {folder, files: [paths relative to folder/name], links, fonts (counts copied), missingLinks: [file names not found], skippedFonts: [{font, reason}], warnings: [nested files copied unchanged or cycles/depth stopped]}; no folder → the same with {name: \"<name>.zip\", dataBase64} (a zip of the files in <name>/) instead of folder. The warnings and the report name a file outside the automation read roots by its file name. Under automation read roots, the package is refused, before any file is written, while the document, or a linked native document or a linked PDF, .ai or EPS file's native document, links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while a linked native document, or a linked PDF, .ai or EPS file that carries one, can't be read to check it (a damaged file, or a PDF that needs a password to open); a PDF or EPS file without editing data is copied",
has_doc,
package
)]
@@ -113,27 +113,65 @@ thread_local! {
pub(crate) static PARTS_READ: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// The native document that the linked file `name` (`bytes`) is, or carries as the editing data of
/// a PDF, `.ai` or EPS file; `None` for other files and for data that can't be read.
fn carried_document(name: &str, bytes: &[u8]) -> Option<Document> {
if super::place::document::is_native(name, bytes) {
return vectorcraft_format::load_file(bytes).ok().map(|f| f.doc);
}
let data =
if super::place::document::is_pdf(name, bytes) { vectorcraft_pdf::editing(bytes).map(|e| e.data) } else { vectorcraft_eps::native(bytes) };
vectorcraft_format::load(&data?).ok()
/// The native document a linked file is or carries ([`carried_document`]).
enum Carried {
/// The file is no native document and carries none: an image, or a PDF, `.ai` or EPS file
/// without editing data.
Absent,
/// The native document, read.
Readable(Box<Document>),
/// The file is a native document, or carries one, that can't be read: a damaged native file,
/// a PDF or `.ai` file that can't be opened without a password or can't be read at all, a PDF
/// or `.ai` file listing an editing file whose data can't be resolved, a PDF or `.ai` file
/// whose attachments are too many to search to their end, or editing data that doesn't read as
/// a native document.
Unreadable,
}
/// The native document that the linked file `name` (`bytes`) is, or carries as the editing data of
/// a PDF, `.ai` or EPS file.
fn carried_document(name: &str, bytes: &[u8]) -> Carried {
let read = |data: &[u8]| vectorcraft_format::load(data).map_or(Carried::Unreadable, |d| Carried::Readable(Box::new(d)));
if super::place::document::is_native(name, bytes) {
return vectorcraft_format::load_file(bytes).map_or(Carried::Unreadable, |f| Carried::Readable(Box::new(f.doc)));
}
if super::place::document::is_pdf(name, bytes) {
// A PDF that can't be opened may carry editing data all the same.
return match vectorcraft_pdf::open_pdf(bytes, None) {
// Attachments left unsearched may list another editing file, which can't be checked.
Ok(opened) if opened.editing_search_cut() => Carried::Unreadable,
// An editing file listed whose data can't be resolved can't be checked either.
Ok(opened) => match opened.editing() {
Some(e) => read(&e.data),
None if opened.has_editing_file() => Carried::Unreadable,
None => Carried::Absent,
},
Err(_) => Carried::Unreadable,
};
}
if !vectorcraft_eps::has_native(bytes) {
return Carried::Absent;
}
vectorcraft_eps::native(bytes).map_or(Carried::Unreadable, |data| read(&data))
}
/// The error for a linked file the package would copy whose native document can't be read to
/// check the files and folders it names against the read roots.
const UNREADABLE: &str = "a linked file's editing data can't be read to check it against the read roots";
/// Under read roots, the linked file `name` (`bytes`, found at `path`) is copied only when the
/// native document it is or carries ([`carried_document`]) links no JavaScript file outside them (a
/// relative path taken from the file's folder): the copy would name it.
/// native document it is or carries ([`carried_document`]) can be read and links no JavaScript file
/// outside them (a relative path taken from the file's folder): the copy would name it. A file
/// whose native document can't be read is refused, as its links can't be checked. The error names
/// no file or folder.
fn check_carried_scripts(name: &str, bytes: &[u8], path: &str) -> Result<()> {
if crate::file_access::current().is_none() {
return Ok(());
}
match carried_document(name, bytes) {
Some(carried) => super::fileio::check_scripts_of(C, &carried, Some(path), || true),
None => Ok(()),
Carried::Readable(carried) => super::fileio::check_scripts_of(C, &carried, Some(path), || true),
Carried::Unreadable => Err(bad(C, UNREADABLE)),
Carried::Absent => Ok(()),
}
}
@@ -150,7 +188,10 @@ fn check_carried_folder(name: &str, bytes: &[u8]) -> Result<()> {
return Ok(());
}
match carried_document(name, bytes) {
Some(carried) if matches!(super::fileio::with_readable_settings_folder(&carried), std::borrow::Cow::Owned(_)) => Err(bad(C, FOLDER_OUTSIDE)),
Carried::Readable(carried) if matches!(super::fileio::with_readable_settings_folder(&carried), std::borrow::Cow::Owned(_)) => {
Err(bad(C, FOLDER_OUTSIDE))
}
Carried::Unreadable => Err(bad(C, UNREADABLE)),
_ => Ok(()),
}
}
@@ -498,6 +539,9 @@ pub struct Package {
root: Option<PathBuf>,
info: Option<String>,
doc: std::sync::Arc<Document>,
/// The read roots in force where the package was prepared: [`Package::write`] collects under
/// them.
scope: crate::file_access::ScopeHandle,
}
impl Session {
@@ -544,21 +588,22 @@ fn prepare(s: &mut Session, p: &Value) -> Result<Package> {
let doc = s.doc()?.doc.clone();
let doc = if let std::borrow::Cow::Owned(kept) = super::fileio::with_readable_settings_folder(&doc) { std::sync::Arc::new(kept) } else { doc };
let links_from = s.doc()?.links_from.clone().unwrap_or_else(|| doc_path.clone());
Ok(Package { o, doc_path, links_from, stem, name, root, info, doc })
let scope = crate::file_access::ScopeHandle::capture();
Ok(Package { o, doc_path, links_from, stem, name, root, info, doc, scope })
}
impl Package {
/// Collect the linked files and fonts and write the package's files with `write` into
/// `folder/name`, making its folders first, or into the zip without a folder → the reply of
/// `file.package`.
/// `file.package`, with the read roots in force where it was prepared, on any thread.
pub fn write(self, write: &mut dyn FnMut(&str, &[u8]) -> Result<()>) -> Result<Value> {
collect_and_write(self, write)
self.scope.clone().run(|| collect_and_write(self, write))
}
}
/// [`Package::write`].
fn collect_and_write(package: Package, write: &mut dyn FnMut(&str, &[u8]) -> Result<()>) -> Result<Value> {
let Package { o, doc_path, links_from, stem, name, root, info, doc: original } = package;
let Package { o, doc_path, links_from, stem, name, root, info, doc: original, scope: _ } = package;
let mut doc = (*original).clone();
let doc_name = format!("{stem}.{}", vectorcraft_format::EXTENSION);
let base = LinkBase { doc: Some(&doc_path), relative: Some(&links_from) };
+25 -12
View File
@@ -48,7 +48,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Default Fill and Stroke",
[],
Some("D"),
"{ids?|id?} white fill and 1 pt black stroke for the selection and the defaults; type gets black fill and no stroke. 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 on a graph label the black fill and no stroke of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (exceptions: docs/mcp.md)",
"{ids?|id?} white fill and 1 pt black stroke for the selection and the defaults (in a document whose Default Graphic Style differs from the shipped one, as a New Document profile can redefine it: that style's fills, strokes and effects, without its opacity or a link to it); type gets black fill and no stroke. 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 on a graph label the black fill and no stroke of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (exceptions: docs/mcp.md)",
has_doc,
default_paint
),
@@ -274,8 +274,9 @@ impl DocState {
/// Whether the selected objects' fills and strokes differ as the proxies show them (a "?"
/// proxy; a group whose contents differ counts). `item` (the Appearance panel's active item)
/// stands for the proxy of its kind, as in [`Session::proxy_paints`]: that fill or stroke of
/// each selected object's own stack is compared. One walk of the document, so callers that ask
/// every frame cache it by revision.
/// each selected object's own stack is compared. The selected objects are found through the id
/// cache ([`vectorcraft_doc::Document::nodes_in_order`]); a large selection takes one walk
/// of the document, so callers that ask every frame cache it by revision.
pub fn proxy_mixed(&self, item: Option<usize>) -> (bool, bool) {
self.proxy_mixed_with(item, &[])
}
@@ -290,15 +291,17 @@ impl DocState {
if self.selection.symbol_part.is_some() {
return (false, false);
}
let ids: std::collections::HashSet<NodeId> = self.selection.objects.iter().copied().collect();
let (mut selected, mut nodes) = (vec![], vec![]);
self.doc.walk(|n| {
if ids.contains(&n.id) {
selected.push(n);
painted(n, true, &mut nodes);
}
});
// Looking the first object up builds the id cache when there is none.
let first = self.selection.objects.first().and_then(|id| self.doc.node(*id));
let (mut selected, mut nodes) = (vec![], vec![]);
// Every node with a selected id, in tree order: a repeated id (a damaged file) counts at each
// place it appears.
for n in self.doc.nodes_in_order(self.selection.objects.iter().copied()) {
#[cfg(test)]
tests::note_gathered();
selected.push(n);
painted(n, true, &mut nodes);
}
let differ = |stroke: bool| {
let item = first.and_then(|f| f.appearance.item_of_kind(item, !stroke));
let set = if item.is_some() { &selected } else { &nodes };
@@ -1035,6 +1038,8 @@ fn default_paint(s: &mut Session, p: &Value) -> Result<Value> {
if !ids.is_empty() {
// When every object comes out as it was, the document and its undo history stay as they are.
let before = s.doc()?.doc.clone();
// A redefined Default Graphic Style gives other art its fills, strokes and effects, placed on each object.
let style = super::newart::redefined_default_style(&before).cloned();
super::overprint::edit_counted(s, "Default Fill and Stroke", |d| {
for id in &ids {
let Some(n) = d.node_mut(*id) else { continue };
@@ -1045,7 +1050,12 @@ fn default_paint(s: &mut Session, p: &Value) -> Result<Value> {
r.style.stroke = Paint::None;
}
}
_ => n.appearance = Appearance::default_art().into(),
_ => {
n.appearance = match &style {
Some(g) => g.appearance_on(n).into_owned().into(),
None => Appearance::default_art().into(),
}
}
}
}
let kept = super::appearance::capture_series_writes(&before, d, &ids, (true, true), (true, true), false, false);
@@ -1316,3 +1326,6 @@ fn transparency(s: &mut Session, p: &Value) -> Result<Value> {
}
s.execute("object.setProps", &Value::Object(q))
}
#[cfg(test)]
mod tests;
+335
View File
@@ -0,0 +1,335 @@
//! The Fill/Stroke proxies' "?" ([`DocState::proxy_mixed`]) finds the selected objects through the
//! id cache: it answers as a walk of the whole document does, and with a few objects selected it
//! reads only those.
use std::cell::Cell;
use std::collections::HashSet;
use std::sync::Arc;
use serde_json::json;
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{Appearance, Document, LayerColor, Node, NodeId, NodeKind};
use vectorcraft_geom::{Rect, shapes};
use super::{painted, picked_colors, proxy_paint, same_in_proxy};
use crate::{DocState, Session};
thread_local! {
/// [`gathered`] of this thread.
static GATHERED: Cell<u64> = const { Cell::new(0) };
}
/// Adds one to [`gathered`]: `proxy_mixed_with` read a node while looking for the selected ones.
pub(super) fn note_gathered() {
GATHERED.set(GATHERED.get() + 1);
}
/// How many nodes `proxy_mixed_with` has read on this thread while looking for the selected ones.
fn gathered() -> u64 {
GATHERED.get()
}
/// `proxy_mixed_with` as it was when it found the selected objects by walking the whole document.
fn walked(st: &DocState, item: Option<usize>, points: &[(NodeId, Vec<usize>)]) -> (bool, bool) {
if st.selection.is_empty() {
return (false, false);
}
if st.selection.symbol_part.is_some() {
return (false, false);
}
let ids: HashSet<NodeId> = st.selection.objects.iter().copied().collect();
let (mut selected, mut nodes) = (vec![], vec![]);
st.doc.walk(|n| {
if ids.contains(&n.id) {
selected.push(n);
painted(n, true, &mut nodes);
}
});
let first = st.selection.objects.first().and_then(|id| st.doc.node(*id));
let differ = |stroke: bool| {
let item = first.and_then(|f| f.appearance.item_of_kind(item, !stroke));
let set = if item.is_some() { &selected } else { &nodes };
let mut paints = set.iter().flat_map(|n| match picked_colors(n, if stroke || item.is_some() { &[] } else { points }) {
c if c.is_empty() => vec![proxy_paint(n, stroke, item)],
c => c.into_iter().map(Paint::solid).collect(),
});
let Some(p0) = paints.next() else { return false };
paints.any(|p| !same_in_proxy(&p0, &p))
};
(differ(false), differ(true))
}
/// `proxy_mixed_with` answers as [`walked`] does for `st`'s selection, for every Appearance item
/// and with and without `points`, with the id cache built and without it.
fn agree(st: &DocState, points: &[(NodeId, Vec<usize>)], what: &str) {
for cold in [true, false] {
if cold {
st.doc.drop_lookup_cache();
}
for item in [None, Some(0), Some(1), Some(2), Some(3)] {
for points in [points, &[]] {
assert_eq!(
st.proxy_mixed_with(item, points),
walked(st, item, points),
"{what}: item {item:?}, {} picked points, cold cache {cold}",
points.len()
);
}
}
}
}
fn id_of(v: &serde_json::Value) -> NodeId {
NodeId(v["id"].as_u64().unwrap())
}
fn rect(s: &mut Session, x: f64, fill: &str, stroke: &str) -> NodeId {
let id = id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 20, "height": 20})).unwrap());
s.execute("paint.setFill", &json!({"ids": [id.0], "color": fill})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [id.0], "color": stroke})).unwrap();
id
}
/// Every case of [`DocState::proxy_mixed`]'s rule, each answered as a walk answers it: one object,
/// different fills or strokes, a group with different contents, a group with one of its objects,
/// objects on two layers, a hidden object, an object with two fills under an Appearance item, a
/// gradient mesh with points picked beside another object, ids not in the document and an id that
/// appears twice (a damaged file) with different paints.
#[test]
fn the_question_marks_match_a_walk_of_the_document() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
let a = rect(&mut s, 10.0, "#ff0000", "#000000");
let b = rect(&mut s, 40.0, "#0000ff", "#000000");
let c = rect(&mut s, 70.0, "#ff0000", "#00ff00");
// Two fills: [Fill, Stroke, Fill].
s.execute("select.set", &json!({"ids": [c.0]})).unwrap();
s.execute("appearance.addFill", &json!({})).unwrap();
s.execute("appearance.setItem", &json!({"index": 2, "color": "#0000ff"})).unwrap();
let e = rect(&mut s, 100.0, "#ff0000", "#000000");
let f = rect(&mut s, 130.0, "#00ff00", "#000000");
let g = id_of(&s.execute("object.group", &json!({"ids": [e.0, f.0]})).unwrap());
let mesh = rect(&mut s, 160.0, "#ff0000", "#000000");
s.execute("object.mesh.create", &json!({"ids": [mesh.0], "rows": 2, "cols": 2})).unwrap();
let hidden = rect(&mut s, 190.0, "#0000ff", "#000000");
s.execute("object.hide", &json!({"ids": [hidden.0]})).unwrap();
s.execute("layer.new", &json!({})).unwrap();
let h = rect(&mut s, 220.0, "#ff0000", "#000000");
let missing = NodeId(999_999);
let Some(NodeKind::Mesh(m)) = s.doc().unwrap().doc.node(mesh).map(|n| &n.kind) else { panic!("a gradient mesh") };
let (p00, p01, p11) = (m.idx(0, 0), m.idx(0, 1), m.idx(1, 1));
s.execute("object.mesh.setPointColor", &json!({"id": mesh.0, "index": p00, "color": "#00ff00"})).unwrap();
let points = vec![(mesh, vec![p00, p01])];
let points_alike = vec![(mesh, vec![p01, p11])];
let selections = [
vec![a],
vec![a, b],
vec![b, a],
vec![a, h],
vec![g],
vec![g, e],
vec![e, g],
vec![f, e],
vec![c],
vec![c, a],
vec![a, c],
vec![mesh],
vec![mesh, a],
vec![a, mesh, h],
vec![hidden],
vec![hidden, b],
vec![missing],
vec![missing, a],
vec![a, missing, b],
vec![a, a],
];
let check = |s: &mut Session, what: &str| {
for sel in &selections {
let st = s.active_mut().unwrap();
st.selection.objects = sel.clone();
let st = s.active().unwrap();
agree(st, &points, &format!("{what}: {sel:?}"));
agree(st, &points_alike, &format!("{what}: {sel:?}, alike points"));
}
s.execute("select.all", &json!({})).unwrap();
agree(s.active().unwrap(), &points, &format!("{what}: Select All"));
};
check(&mut s, "unique ids");
// A second node with a's id and another fill, at the end of the tree.
let st = s.active_mut().unwrap();
let mut copy = st.doc.node(a).unwrap().clone();
copy.appearance.set_fill(Paint::solid(Color::rgb(0.0, 0.0, 1.0)));
let doc = Arc::make_mut(&mut st.doc);
let last = doc.layers.len() - 1;
Arc::make_mut(&mut doc.layers[last]).children_mut().unwrap().push(Arc::new(copy));
doc.drop_lookup_cache();
check(&mut s, "a repeated id");
let st = s.active_mut().unwrap();
st.selection.objects = vec![a];
assert_eq!(st.proxy_mixed_with(None, &[]), (true, false), "the two places of a's id differ in fill");
}
/// A document of `layers` layers, each with `groups` groups of `per_group` rectangles; every other
/// rectangle red, the rest blue. Returns it with the rectangles' ids, in tree order.
fn big(layers: usize, groups: usize, per_group: usize) -> (Document, Vec<NodeId>) {
let mut d = Document::new(612.0, 792.0);
d.layers.clear();
let mut rects = vec![];
for l in 0..layers {
let mut layer = Node::layer(d.alloc_id(), &format!("L{l}"), LayerColor::Preset(0));
for _ in 0..groups {
let children = (0..per_group)
.map(|_| {
let id = d.alloc_id();
let mut ap = Appearance::default_art();
let red = rects.len() % 2 == 0;
ap.set_fill(Paint::solid(if red { Color::rgb(1.0, 0.0, 0.0) } else { Color::rgb(0.0, 0.0, 1.0) }));
rects.push(id);
Arc::new(Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), ap))
})
.collect();
let group = Node::group(d.alloc_id(), children);
layer.children_mut().unwrap().push(Arc::new(group));
}
d.layers.push(Arc::new(layer));
}
(d, rects)
}
fn state(doc: Document) -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 612, "height": 792})).unwrap();
s.active_mut().unwrap().doc = Arc::new(doc);
s
}
/// With one object selected, the "?" reads only that object, not every node of the document, and
/// does not walk the tree once the id cache is built; with every object selected it walks the tree
/// once.
#[test]
fn the_question_marks_read_only_the_selected_objects() {
let (doc, rects) = big(2, 40, 25);
let mut s = state(doc);
let st = s.active_mut().unwrap();
st.selection.objects = vec![rects[777]];
assert_eq!(st.proxy_mixed(None), (false, false));
let (read, walks) = (gathered(), vectorcraft_doc::tree_walks());
assert_eq!(st.proxy_mixed(None), (false, false));
assert_eq!(gathered() - read, 1, "only the selected object is read");
assert_eq!(vectorcraft_doc::tree_walks() - walks, 0, "the cached path answers");
st.selection.objects = vec![rects[3], rects[1500]];
let (read, walks) = (gathered(), vectorcraft_doc::tree_walks());
assert_eq!(st.proxy_mixed(None), (true, false));
assert_eq!((gathered() - read, vectorcraft_doc::tree_walks() - walks), (2, 0));
st.selection.objects = rects.clone();
let (read, walks) = (gathered(), vectorcraft_doc::tree_walks());
assert_eq!(st.proxy_mixed(None), (true, false));
assert_eq!(gathered() - read, rects.len() as u64);
assert!(vectorcraft_doc::tree_walks() - walks <= 1, "one walk for a large selection");
}
/// Random selections of a document with nested groups answer as a walk does.
#[test]
fn random_selections_match_a_walk_of_the_document() {
let (doc, rects) = big(3, 12, 6);
let mut s = state(doc);
let groups: Vec<NodeId> = s.active().unwrap().doc.layers.iter().flat_map(|l| l.children().unwrap().iter().map(|g| g.id)).collect();
let layers: Vec<NodeId> = s.active().unwrap().doc.layers.iter().map(|l| l.id).collect();
let all: Vec<NodeId> = rects.iter().chain(&groups).chain(&layers).copied().chain([NodeId(999_999)]).collect();
let mut r = 0x2545_f491_4f6c_dd1d_u64;
let mut next = |n: usize| {
r ^= r << 13;
r ^= r >> 7;
r ^= r << 17;
(r % n as u64) as usize
};
for round in 0..200 {
let count = 1 + next(if round % 10 == 0 { all.len() } else { 6 });
let sel: Vec<NodeId> = (0..count).map(|_| all[next(all.len())]).collect();
let st = s.active_mut().unwrap();
st.selection.objects = sel.clone();
agree(s.active().unwrap(), &[], &format!("round {round}: {sel:?}"));
}
}
/// The CPU time this thread has used, from Linux's scheduler statistics; `None` elsewhere.
fn thread_cpu() -> Option<std::time::Duration> {
let stat = std::fs::read_to_string("/proc/thread-self/schedstat").ok()?;
stat.split_whitespace().next()?.parse().ok().map(std::time::Duration::from_nanos)
}
/// The time `f` takes: this thread's CPU time where Linux reports it, otherwise the wall clock.
fn time(f: impl FnOnce()) -> std::time::Duration {
match thread_cpu() {
Some(before) => {
f();
thread_cpu().map_or(std::time::Duration::ZERO, |after| after.saturating_sub(before))
}
None => {
let start = std::time::Instant::now();
f();
start.elapsed()
}
}
}
/// The time of `proxy_mixed` against a walk of the document, on 50,000 rectangles in 500 groups on
/// 5 layers: `cargo test --release -p vectorcraft-engine --lib proxy_mixed_timing -- --ignored --nocapture`.
#[test]
#[ignore = "timing; run by hand"]
fn proxy_mixed_timing() {
let (doc, rects) = big(5, 100, 100);
let mut s = state(doc);
let groups: Vec<NodeId> = s.active().unwrap().doc.layers.iter().flat_map(|l| l.children().unwrap().iter().map(|g| g.id)).collect();
let cases: [(&str, Vec<NodeId>); 5] = [
("1 object", vec![rects[25_000]]),
("2 objects, different fills", vec![rects[10], rects[40_001]]),
("a group of 100", vec![groups[250]]),
("all 500 groups", groups.clone()),
("all 50,000 objects", rects.clone()),
];
const CALLS: usize = 200;
let median = |mut v: Vec<f64>| {
v.sort_by(f64::total_cmp);
v[v.len() / 2]
};
println!("proxy_mixed_timing: {}", if thread_cpu().is_some() { "thread CPU time" } else { "wall clock" });
println!("| Selection | Id cache | Walk (µs/call) | Id cache (µs/call) | Runs (walk / id cache, µs) |");
println!("|---|---|---|---|---|");
for (name, sel) in &cases {
for cold in [false, true] {
let st = s.active_mut().unwrap();
st.selection.objects = sel.clone();
let st = s.active().unwrap();
assert_eq!(st.proxy_mixed_with(None, &[]), walked(st, None, &[]), "{name}");
let (mut old, mut new) = (vec![], vec![]);
let calls = if cold { CALLS / 10 } else { CALLS };
for _ in 0..7 {
for (times, use_walk) in [(&mut old, true), (&mut new, false)] {
let d = time(|| {
for _ in 0..calls {
if cold {
st.doc.drop_lookup_cache();
}
std::hint::black_box(if use_walk { walked(st, None, &[]) } else { st.proxy_mixed_with(None, &[]) });
}
});
times.push(d.as_secs_f64() * 1e6 / calls as f64);
}
}
let runs = |v: &[f64]| v.iter().map(|x| format!("{x:.1}")).collect::<Vec<_>>().join(" ");
println!(
"| {name} | {} | {:.1} | {:.1} | {} / {} |",
if cold { "dropped before each call" } else { "built" },
median(old.clone()),
median(new.clone()),
runs(&old),
runs(&new)
);
}
}
}
+137 -11
View File
@@ -36,6 +36,9 @@
//! `channel` that the effect doesn't have are refused by `effect.apply` and `effect.setParams`
//! themselves ([`check_effect_color`], [`check_effect_channel`]).
use std::collections::HashMap;
use std::sync::OnceLock;
use serde_json::Value;
use vectorcraft_apischema::shown_key;
@@ -43,7 +46,7 @@ use super::{bad, command_specs, find_command};
use crate::Result;
/// What a params description says about the keys of the params object.
#[derive(Debug, Default, PartialEq)]
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ParamKeys<'a> {
/// The keys it names.
pub keys: Vec<&'a str>,
@@ -107,6 +110,8 @@ pub(crate) fn is_key(s: &str) -> bool {
/// The keys a params description names, or what in it doesn't read as one.
pub fn doc_keys(doc: &str) -> std::result::Result<ParamKeys<'_>, String> {
#[cfg(test)]
PARSES.with(|n| n.set(n.get() + 1));
let mut out = ParamKeys::default();
let (mut body, mut rest) = object_body(doc)?;
let mut entries = split_top(body, ',');
@@ -155,7 +160,12 @@ fn named_commands(more: &str) -> impl Iterator<Item = &'static super::CommandSpe
/// `None`: any key (a `…` entry naming no command, or a description that doesn't parse, which
/// the tests rule out).
fn accepted(doc: &'static str, depth: usize) -> Option<Vec<&'static str>> {
let parsed = doc_keys(doc).ok()?;
resolve(doc, depth, &mut |doc| doc_keys(doc).ok())
}
/// [`accepted`], with `parse` reading each description it reaches.
fn resolve(doc: &'static str, depth: usize, parse: &mut dyn FnMut(&'static str) -> Option<ParamKeys<'static>>) -> Option<Vec<&'static str>> {
let parsed = parse(doc)?;
let mut keys = parsed.keys;
for more in parsed.more {
let mut named = named_commands(more).peekable();
@@ -168,22 +178,120 @@ fn accepted(doc: &'static str, depth: usize) -> Option<Vec<&'static str>> {
if UNCHECKED.contains(&spec.id) {
return None;
}
keys.extend(accepted(spec.params, depth + 1)?);
keys.extend(resolve(spec.params, depth + 1, parse)?);
}
}
Some(keys)
}
/// What the params description of a built-in command says about its keys, read once per process
/// ([`known`]).
#[derive(Debug)]
struct Known {
/// The keys it names itself; none when it doesn't parse.
own: Vec<&'static str>,
/// [`accepted`] of it.
accepted: Option<Vec<&'static str>>,
/// [`id_stands_for_ids`] of it.
id_stands_for_ids: bool,
}
impl Known {
/// [`takes_key`] of the description.
fn takes(&self, key: &str) -> bool {
self.own.contains(&key) || self.accepted.as_ref().is_some_and(|keys| keys.contains(&key))
}
}
/// The place and length of `doc`'s text: a description with the same words elsewhere (a plug-in's)
/// has another place.
fn text_key(doc: &str) -> (usize, usize) {
(doc.as_ptr().addr(), doc.len())
}
/// [`Known`] of each description in `docs`, each one and each one its `…` entries name parsed once.
/// A description is left out when one it reaches has a `…` entry naming a plug-in command, whose
/// keys change as plug-ins are installed and removed.
fn read_descriptions(docs: impl IntoIterator<Item = &'static str>) -> HashMap<(usize, usize), Known> {
let names_plugin =
|more: &str| more.split_whitespace().any(|w| w.trim_matches(|c: char| !c.is_ascii_alphanumeric()).starts_with(vectorcraft_plugins::PREFIX));
let mut parsed: HashMap<(usize, usize), (Option<ParamKeys<'static>>, bool)> = HashMap::new();
let mut table = HashMap::new();
for doc in docs {
if table.contains_key(&text_key(doc)) {
continue;
}
let mut live = false;
let mut parse = |doc: &'static str| {
let (keys, plugin) = parsed.entry(text_key(doc)).or_insert_with(|| {
let keys = doc_keys(doc).ok();
let plugin = keys.as_ref().is_some_and(|k| k.more.iter().any(|m| names_plugin(m)));
(keys, plugin)
});
live |= *plugin;
keys.clone()
};
let own = parse(doc).map(|p| p.keys).unwrap_or_default();
let accepted = resolve(doc, 0, &mut parse);
if live {
continue;
}
let mut known = Known { own, accepted, id_stands_for_ids: false };
known.id_stands_for_ids = known.takes("ids") && known.takes("id") && no_required_id_beside_ids(doc);
table.insert(text_key(doc), known);
}
table
}
/// [`Known`] of `doc` when it is the params description of a built-in command.
fn known(doc: &str) -> Option<&'static Known> {
#[cfg(test)]
if UNCACHED.get() {
return None;
}
static TABLE: OnceLock<HashMap<(usize, usize), Known>> = OnceLock::new();
TABLE.get_or_init(|| read_descriptions(command_specs().iter().map(|c| c.params))).get(&text_key(doc))
}
#[cfg(test)]
thread_local! {
/// The times [`doc_keys`] parsed a description on this thread.
pub(crate) static PARSES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
/// Whether [`known`] is skipped on this thread ([`uncached`]).
static UNCACHED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
/// Whether [`read_descriptions`] keeps what `doc` says.
#[cfg(test)]
pub(crate) fn read_once(doc: &'static str) -> bool {
read_descriptions([doc]).contains_key(&text_key(doc))
}
/// `f`'s result with every description parsed again where it is used, as without [`known`].
#[cfg(test)]
pub(crate) fn uncached<T>(f: impl FnOnce() -> T) -> T {
let before = UNCACHED.replace(true);
let out = f();
UNCACHED.set(before);
out
}
/// 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)
match known(doc) {
Some(known) => known.accepted.clone(),
None => accepted(doc, 0),
}
}
/// Does the description `doc` name `key` as a parameter (its own keys, and those of the commands
/// its `…` entries name)?
pub fn takes_key(doc: &'static str, key: &str) -> bool {
if let Some(known) = known(doc) {
return known.takes(key);
}
doc_keys(doc).is_ok_and(|parsed| parsed.keys.contains(&key)) || accepted(doc, 0).is_some_and(|keys| keys.contains(&key))
}
@@ -191,12 +299,17 @@ pub fn takes_key(doc: &'static str, key: &str) -> bool {
/// (instead of id)}`, `{id} or {ids: […]}`): it names both keys, and no params object of it names
/// `ids` beside a required `id`, which is something else (`plugin.run {id, ids?}`: the plug-in's)?
pub(crate) fn id_stands_for_ids(doc: &'static str) -> bool {
if let Some(known) = known(doc) {
return known.id_stands_for_ids;
}
takes_key(doc, "ids") && takes_key(doc, "id") && no_required_id_beside_ids(doc)
}
/// No params object of `doc` names `ids` beside a required `id`.
fn no_required_id_beside_ids(doc: &str) -> bool {
fn head(alternative: &str) -> &str {
alternative.split([':', '=', '(']).next().unwrap_or_default().trim()
}
if !takes_key(doc, "ids") || !takes_key(doc, "id") {
return false;
}
let mut rest = doc;
while let Ok((body, after)) = object_body(rest) {
let entries = split_top(body, ',');
@@ -249,9 +362,17 @@ pub fn check_keys(id: &str, doc: &'static str, params: &Value) -> Result<()> {
if given.is_empty() {
return Ok(());
}
let Some(keys) = accepted(doc, 0) else { return Ok(()) };
let live;
let keys = match known(doc) {
Some(known) => known.accepted.as_deref(),
None => {
live = accepted(doc, 0);
live.as_deref()
}
};
let Some(keys) = keys else { return Ok(()) };
match given.keys().find(|k| !keys.contains(&k.as_str())) {
Some(key) => Err(unknown(id, key, &keys)),
Some(key) => Err(unknown(id, key, keys)),
None => Ok(()),
}
}
@@ -933,9 +1054,14 @@ fn check_params_in(id: &str, params: &Value, in_batch: bool) -> Result<()> {
crate::schemas::check(spec, params, false)?;
}
if matches!(id, "command.batch" | "action.batch") && !in_batch {
for step in params.get("commands").and_then(Value::as_array).into_iter().flatten() {
for (i, step) in params.get("commands").and_then(Value::as_array).into_iter().flatten().enumerate() {
if let Some(step_id) = step.get("command").and_then(Value::as_str) {
check_params_in(step_id, step.get("params").unwrap_or(&Value::Null), true)?;
let checked = check_params_in(step_id, step.get("params").unwrap_or(&Value::Null), true);
// An `action.batch` names the step it refuses by its place, from 1, as its own checks and its steps' errors do.
match checked {
Err(e) if id == "action.batch" => return Err(bad(id, super::fileio::action_step(i, step_id, &e.to_string()))),
checked => checked?,
}
}
}
}
+154 -10
View File
@@ -1,10 +1,10 @@
//! Path editing commands (used by the Pen and Direct Selection tools and Object → Path).
use std::collections::BTreeSet;
use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind, Scaling, Selection};
use vectorcraft_doc::{AnchorRef, Document, Node, NodeId, NodeKind, Scaling, Selection};
use vectorcraft_geom::{Anchor, AnchorKind, Anchors, PathData, Point, SubPath, Vec2};
use super::create::anchor_from_json;
@@ -41,7 +41,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Move Anchors",
[],
None,
"{dx, dy, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles)} move direct-selected anchors (whole paths if fully selected); refused while an object of a symbol instance's art is selected",
"{dx, dy, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), interpolate?: bool (Interpolate Control Points: the handles of each segment with one moved end are re-mapped by the turn, scale and move that take its old ends to its new ends; default: prefs interpolateControlPoints)} move direct-selected anchors (whole paths if fully selected); refused while an object of a symbol instance's art is selected",
has_selection,
move_anchors
),
@@ -245,28 +245,43 @@ fn close(s: &mut Session, p: &Value) -> Result<Value> {
pub(crate) fn move_anchors(s: &mut Session, p: &Value) -> Result<Value> {
let d = Vec2::new(number_or(p, "dx", 0.0, "path.moveAnchors")?, number_or(p, "dy", 0.0, "path.moveAnchors")?);
check_switches(p, &["patterns"], "path.moveAnchors")?;
check_switches(p, &["patterns", "interpolate"], "path.moveAnchors")?;
// An object selected in a symbol instance's art stays where the symbol puts it.
super::edit::refuse_symbol_part(s)?;
// Objects selected whole move as objects, and their pattern tiles move with them when
// `patterns` (default: General › Transform Pattern Tiles) is on.
let whole = s.doc()?.selection.whole();
let sc = Scaling { patterns: super::object::transform_patterns(s, p, &whole)?, ..Scaling::default() };
transform_anchors(s, "Move", vectorcraft_geom::Affine::translate(d), sc)?;
let interpolate = interpolates_handles(s, p, "path.moveAnchors")?;
transform_anchors(s, "Move", vectorcraft_geom::Affine::translate(d), sc, interpolate)?;
// Transform Again repeats a move that moved something; a drag records it when it commits.
let st = s.doc_mut()?;
if st.interaction.is_none() && (d.x != 0.0 || d.y != 0.0) {
let options = json!({ "copy": false, "patterns": sc.patterns });
let options = json!({ "copy": false, "patterns": sc.patterns, "interpolate": interpolate });
st.last_transform = Some(crate::LastTransform::Matrix(vectorcraft_geom::Affine::translate(d), options));
st.last_perspective = None;
}
ok()
}
/// Interpolate Control Points: does a move of direct-selected anchors re-map the handles of the
/// segments beside them (`interpolate` param, else General › Interpolate Control Points When
/// Moving Anchors)? Noted in the journal, so a replay re-maps them alike whatever the preference
/// is then. A saved step without `interpolate` ([`Session::replay`]) was recorded before the
/// preference existed, so it moves the handles as it did then, without re-mapping them.
pub(crate) fn interpolates_handles(s: &mut Session, p: &Value, cmd: &str) -> Result<bool> {
let default = s.prefs.interpolate_control_points && !s.replaying();
let on = switch_or(p, "interpolate", default, cmd)?;
s.note_journal("interpolate", json!(on));
Ok(on)
}
/// Apply `xf` to the direct-selected anchors, their handles with them, and (with `sc`) to the
/// objects selected whole (those with no entry in the selection's `anchors`). An object inside
/// another selected object, such as a path in a selected group, moves once, with that object.
pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_geom::Affine, sc: Scaling) -> Result<()> {
/// When `xf` is a move and `interpolate` is on, the handles of each segment with one moved end
/// are re-mapped ([`move_interpolating_handles`]).
pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_geom::Affine, sc: Scaling, interpolate: bool) -> Result<()> {
let sel = s.doc()?.selection.clone();
let ids = super::edit::outermost(&s.doc()?.doc, sel.objects.clone());
let c = xf.as_coeffs();
@@ -277,9 +292,15 @@ pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_ge
match sel.anchors.get(id) {
Some(set) => {
let path = path_mut(doc, *id)?;
for &(si, ai) in set {
if let Some(a) = path.anchor_mut(si, ai) {
*a = a.transform(xf);
// Only an exact move takes the interpolating path: a near-identity scale or
// turn still transforms the anchors as asked.
if interpolate && c[..4] == [1.0, 0.0, 0.0, 1.0] {
move_interpolating_handles(path, set, delta);
} else {
for &(si, ai) in set {
if let Some(a) = path.anchor_mut(si, ai) {
*a = a.transform(xf);
}
}
}
// A pixel-aligned path, or the pixel-aligned compound path that holds it, snaps
@@ -307,6 +328,129 @@ pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_ge
})
}
/// Move the anchors `set` of `path` by `d`, their handles with them, then re-map the two handles
/// of each segment with exactly one moved end by the map that takes the segment's old ends to its
/// new ends: a turn, a uniform scale and a move. Between two corner anchors the segment keeps its
/// shape relative to its ends. A segment with both ends moved, or with its ends at the same place
/// before or after the move, moves as it does without the preference. A smooth anchor keeps its
/// two handles in line ([`line_up_handles`]).
fn move_interpolating_handles(path: &mut PathData, set: &BTreeSet<AnchorRef>, d: Vec2) {
// (subpath, anchor, outgoing handle?, new position)
let mut placed: Vec<(usize, usize, bool, Point)> = Vec::new();
if d != Vec2::ZERO {
// Only the segments beside a moved anchor can have one moved end: (subpath, first anchor).
let mut segments: BTreeSet<AnchorRef> = BTreeSet::new();
for &(si, ai) in set {
let Some(sp) = path.subpaths.get(si) else { continue };
let n = sp.anchors.len();
if ai >= n || n < 2 {
continue;
}
if ai > 0 || sp.closed {
segments.insert((si, (ai + n - 1) % n));
}
if ai + 1 < n || sp.closed {
segments.insert((si, ai));
}
}
for (si, from) in segments {
let Some(sp) = path.subpaths.get(si) else { continue };
let to = (from + 1) % sp.anchors.len().max(1);
let (moved_from, moved_to) = (set.contains(&(si, from)), set.contains(&(si, to)));
if moved_from == moved_to {
continue;
}
let (Some(a), Some(b)) = (sp.anchors.get(from), sp.anchors.get(to)) else { continue };
let old = b.p - a.p;
let len2 = old.hypot2();
if len2 <= 1e-12 || !len2.is_finite() {
continue;
}
let start = if moved_from { a.p + d } else { a.p };
let end = if moved_to { b.p + d } else { b.p };
let new = end - start;
// A move that puts the two ends at the same place would collapse both handles onto
// them, past recovering by moving back.
if new.hypot2() <= 1e-12 {
continue;
}
// `new / old` as complex numbers: the turn and scale between the two chords.
let (re, im) = ((new.x * old.x + new.y * old.y) / len2, (new.y * old.x - new.x * old.y) / len2);
let map = |h: Point| {
let v = h - a.p;
start + Vec2::new(v.x * re - v.y * im, v.x * im + v.y * re)
};
// A retracted handle goes to its anchor's new place exactly: mapped, it could land a
// rounding error away, which `line_up_handles` would read as a direction.
let h_out = if a.h_out == a.p { start } else { map(a.h_out) };
let h_in = if b.h_in == b.p { end } else { map(b.h_in) };
if h_out.is_finite() && h_in.is_finite() {
placed.push((si, from, true, h_out));
placed.push((si, to, false, h_in));
}
}
}
for &(si, ai) in set {
if let Some(a) = path.anchor_mut(si, ai) {
a.translate(d);
}
}
// For each anchor with a re-mapped handle: its handles as the plain move left them, and which
// of them (outgoing, incoming) were re-mapped.
let mut touched: BTreeMap<AnchorRef, (Point, Point, bool, bool)> = BTreeMap::new();
for &(si, ai, out, pos) in &placed {
if let Some(a) = path.anchor_mut(si, ai) {
let e = touched.entry((si, ai)).or_insert((a.h_out, a.h_in, false, false));
if out {
a.h_out = pos;
e.2 = true;
} else {
a.h_in = pos;
e.3 = true;
}
}
}
for ((si, ai), (rigid_out, rigid_in, out, inn)) in touched {
let Some(a) = path.anchor_mut(si, ai) else { continue };
if a.kind == AnchorKind::Smooth && !line_up_handles(a, out, inn) {
a.h_out = rigid_out;
a.h_in = rigid_in;
}
}
}
/// Put the handles of the smooth anchor `a` back in line after [`move_interpolating_handles`]
/// re-mapped its outgoing handle (`out`), its incoming handle (`inn`) or both. A re-mapped handle
/// turns to point away from the other handle, at its own new length; when both were re-mapped,
/// both point along the mean of their directions. A retracted handle is left as it is. False when
/// both were re-mapped to point the same way, which has no mean direction: the caller then moves
/// both handles with the anchor.
fn line_up_handles(a: &mut Anchor, out: bool, inn: bool) -> bool {
let (v_out, v_in) = (a.h_out - a.p, a.h_in - a.p);
let (l_out, l_in) = (v_out.hypot(), v_in.hypot());
if l_out <= 0.0 || l_in <= 0.0 || !l_out.is_finite() || !l_in.is_finite() {
return true;
}
let dir = match (out, inn) {
(true, true) => v_out / l_out - v_in / l_in,
(true, false) => -v_in / l_in,
(false, true) => v_out / l_out,
(false, false) => return true,
};
let l = dir.hypot();
if l <= 1e-12 || !l.is_finite() {
return false;
}
let dir = dir / l;
if out {
a.h_out = a.p + dir * l_out;
}
if inn {
a.h_in = a.p - dir * l_in;
}
true
}
fn set_handle(s: &mut Session, p: &Value) -> Result<Value> {
let id = object_param(p, "id", "path.setHandle")?.ok_or_else(|| bad("path.setHandle", "missing id"))?;
let si = usize_opt(p, "subpath", "path.setHandle")?.unwrap_or(0);
+15 -3
View File
@@ -161,6 +161,8 @@ pub struct FilterRun {
parent: Option<NodeId>,
/// The document it was made from, and that document's revision then.
document: (u64, u64),
/// The plug-in's limits with the Plug-in Instruction Budget in force when it was made.
limits: vectorcraft_plugins::Limits,
}
/// A filter's output handed in by a [`FilterRun`] made away from `plugin.run`, with what the run
@@ -245,7 +247,11 @@ impl FilterRun {
let capacity = (plugin.limits().max_memory_bytes / 2).min(i32::MAX as usize).saturating_sub(params.len());
let (input, read_only) = objects::encode_input_with(&st.doc, &inputs, &kinds, capacity).map_err(err)?;
let document = (st.uid, st.revision);
Ok(FilterRun { plugin, command, input, params, inputs, read_only, parent, document })
let limits = match s.prefs.plugin_instruction_budget {
crate::PluginBudget::Normal => plugin.limits().clone(),
crate::PluginBudget::Large => plugin.large_limits(),
};
Ok(FilterRun { plugin, command, input, params, inputs, read_only, parent, document, limits })
}
/// The plug-in, for its name and budget.
@@ -274,7 +280,13 @@ impl FilterRun {
/// can run on any thread; inside a [`vectorcraft_doc::cancel::scope`] Cancel stops it between
/// two slices of its budget.
pub fn run(&self) -> Result<Vec<u8>> {
self.plugin.run(&self.input, &self.params).map_err(err)
self.plugin.run_limited(&self.input, &self.params, &self.limits).map_err(err)
}
/// The limits it runs under: the plug-in's, with the Plug-in Instruction Budget in force when
/// it was made.
pub fn limits(&self) -> &vectorcraft_plugins::Limits {
&self.limits
}
/// Does the plug-in call commands (its manifest's `commandAllowlist`)? Then it runs only in the
@@ -289,7 +301,7 @@ impl FilterRun {
let may = self.plugin.manifest().permissions();
let calls = super::plugin_call::Calls::of(s, may.contains(&Permission::DocRead), may.contains(&Permission::DocWrite));
let mut bridge = |id: &str, args: &Value| super::plugin_call::call(s, &calls, id, args);
self.plugin.run_calling(&self.input, &self.params, self.plugin.limits(), &mut bridge).0.map_err(err)
self.plugin.run_calling(&self.input, &self.params, &self.limits, &mut bridge).0.map_err(err)
}
/// Runs a plug-in that calls commands and applies its output: the calls and the output are one
+1
View File
@@ -64,6 +64,7 @@ const DENIED_PREFIXES: &[&str] = &[
"edit.newDocument",
"edit.colorSettings",
"edit.dropSelection",
"symbol.placeFromDocument",
"artboard.copy",
"artboard.cut",
"text.rescanFonts",
@@ -46,6 +46,7 @@ pub(super) const ALLOWED: &[&str] = &[
"addon.packaging.setRole",
"addon.packaging.setRoleSwatch",
"addon.pathtools.addPoints",
"addon.pathtools.bridge",
"addon.pathtools.close",
"addon.pathtools.commonTangents",
"addon.pathtools.corner",
+9
View File
@@ -139,6 +139,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[
p!("cornerRadius", "General", "", "Corner Radius", len(0.0, 1296.0, General)),
p!("pasteOffset", "General", "", "Paste Offset", len(0.0, 1296.0, General)),
p!("disableAutoAddDelete", "General", "Options", "Disable Auto Add/Delete", bool),
p!("interpolateControlPoints", "General", "Options", "Interpolate Control Points When Moving Anchors", bool),
p!("usePreciseCursors", "General", "Options", "Use Precise Cursors", bool),
p!("showToolTips", "General", "Options", "Show Tool Tips", bool),
p!("showExternalScriptWarning", "General", "Options", "Show External Script Warning", bool),
@@ -323,6 +324,14 @@ pub const PREF_SPECS: &[PrefSpec] = &[
p!("hyphenationExceptions", "Hyphenation", "", "Exceptions (comma separated)", text),
// Plug-ins & Scratch Disks
p!("pluginsFolder", "Plug-ins & Scratch Disks", "Plug-ins", "Additional Plug-ins Folder", text),
// The instructions each object filter run gets: Large gives at least 250 M besides those for each byte of input.
p!(
"pluginInstructionBudget",
"Plug-ins & Scratch Disks",
"Plug-ins",
"Plug-in Instruction Budget",
choice(&[("normal", "Normal"), ("large", "Large")])
),
p!("scratchPrimary", "Plug-ins & Scratch Disks", "Scratch Disks", "Primary", text),
p!("scratchSecondary", "Plug-ins & Scratch Disks", "Scratch Disks", "Secondary", text),
// User Interface
+57 -11
View File
@@ -375,6 +375,59 @@ fn is_selectable_within(d: &Document, iso: Option<NodeId>, locks: Option<&Locked
}
}
/// The object Next Object Above (`dir` > 0) or Next Object Below selects from `cur`: the nearest
/// sibling of `cur` in that direction that [`walk_selectable`] visits. Hidden and locked objects
/// and sublayers are passed over. Only the siblings are read, not the rest of the document.
fn step_target(d: &Document, iso: Option<NodeId>, cur: NodeId, dir: i64) -> Option<NodeId> {
let path = d.index_path(cur)?;
let (&idx, up) = path.split_last()?;
// The objects that hold `cur` and its siblings, from the top-level layer down.
let mut holders = Vec::with_capacity(up.len());
let mut siblings = &d.layers;
for &i in up {
let n = siblings.get(i)?;
holders.push(n.as_ref());
siblings = n.children()?;
}
let iso = iso.and_then(|i| d.node(i));
let locks = d.locked_artboards();
let visits = |n: &Node| walk_visits(&holders, n, iso, &locks);
let next = if dir > 0 { siblings.iter().skip(idx + 1).find(|n| visits(n)) } else { siblings.iter().take(idx).rev().find(|n| visits(n)) };
next.map(|n| n.id)
}
/// Whether [`walk_selectable`] visits `n`, read from the objects that hold it: `holders` are its
/// layer and the sublayers, groups and other containers inside it that hold `n`, outermost first
/// (its [`Document::ancestry`] without `n`). `iso` is the isolated object. Unlike
/// [`is_selectable`], it passes over sublayers and the ruler guides of a layer, which the walk
/// looks through or leaves out.
fn walk_visits(holders: &[&Node], n: &Node, iso: Option<&Node>, locks: &LockedArtboards) -> bool {
let len = holders.len() + 1;
let at = |i: usize| holders.get(i).copied().unwrap_or(n);
let open = |i: usize| at(i).visible && !at(i).locked;
let start = match iso {
Some(c) => {
let Some(p) = (0..len).find(|&i| at(i).id == c.id) else { return false };
if !(0..=p).all(|i| open(i) && !at(i).is_template()) {
return false;
}
// A single object isolated is all there is to select.
if !c.is_container() {
return p + 1 == len;
}
p + 1
}
None => 0,
};
// The object Select All takes: the first one that is not a layer, inside visible, unlocked
// layers and sublayers that are not template layers.
let Some(top) = (start..len).find(|&i| !at(i).is_layer()) else { return false };
(start..top).all(|i| open(i) && !at(i).is_template())
&& !at(top).is_ruler_guide()
&& (top..len).all(open)
&& (iso.is_some() || locks.is_empty() || !locks.holds(at(top)))
}
/// The first selected object, in selection order, that [`is_selectable`] accepts.
pub(crate) fn first_selectable(st: &DocState) -> Option<&Node> {
let locks = st.doc.locked_artboards();
@@ -475,17 +528,7 @@ fn inverse(s: &mut Session, _: &Value) -> Result<Value> {
fn step(s: &mut Session, dir: i64) -> Result<Value> {
let st = s.doc()?;
let Some(cur) = st.selection.objects.first().copied() else { return ok() };
let Some((par, idx, _)) = st.doc.position(cur) else { return ok() };
let Some(siblings) = st.doc.children(par) else { return ok() };
// The nearest sibling in that direction that `walk_selectable` visits: hidden and locked
// objects and sublayers are passed over.
let can = selectable_ids(&st.doc, st.isolation);
let next = if dir > 0 {
siblings.iter().skip(idx + 1).find(|n| can.contains(&n.id))
} else {
siblings.iter().take(idx).rev().find(|n| can.contains(&n.id))
};
let Some(id) = next.map(|n| n.id) else { return ok() };
let Some(id) = step_target(&st.doc, st.isolation, cur, dir) else { return ok() };
s.select(|_, sel| sel.set([id]))?;
ok()
}
@@ -1399,5 +1442,8 @@ fn not_pixel_aligned(s: &mut Session, _: &Value) -> Result<Value> {
#[cfg(test)]
mod same_tests;
#[cfg(test)]
mod step_tests;
#[cfg(test)]
mod tests;
+347
View File
@@ -0,0 +1,347 @@
//! Select > Next Object Above and Below through [`step_target`], which reads only the siblings of
//! the selected object, against a copy of the search that collected every object
//! [`walk_selectable`] visits on each step.
use std::sync::Arc;
use std::time::{Duration, Instant};
use serde_json::json;
use vectorcraft_doc::{Appearance, Document, LayerColor, Node, NodeId, NodeKind};
use vectorcraft_geom::{Rect, shapes};
use super::{selectable_ids, step_target, walk_visits};
use crate::Session;
/// The search as it was before it read only the siblings: the nearest sibling in that direction
/// that `walk_selectable` visits, from the set of every object it visits.
fn step_base(d: &Document, iso: Option<NodeId>, cur: NodeId, dir: i64) -> Option<NodeId> {
let (par, idx, _) = d.position(cur)?;
let siblings = d.children(par)?;
let can = selectable_ids(d, iso);
let next = if dir > 0 {
siblings.iter().skip(idx + 1).find(|n| can.contains(&n.id))
} else {
siblings.iter().take(idx).rev().find(|n| can.contains(&n.id))
};
next.map(|n| n.id)
}
/// A small xorshift generator, so that each seed gives the same document every run.
struct Rng(u64);
impl Rng {
fn next(&mut self) -> u64 {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
self.0
}
fn below(&mut self, n: u64) -> u64 {
self.next() % n
}
/// True `pct` times in 100.
fn chance(&mut self, pct: u64) -> bool {
self.below(100) < pct
}
}
fn rect_node(d: &mut Document, x: f64, y: f64) -> Node {
Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, y, x + 40.0, y + 40.0)), Appearance::default())
}
fn layer_node(d: &mut Document, children: Vec<Node>) -> Node {
let mut l = Node::layer(d.alloc_id(), "Layer", LayerColor::Preset(0));
if let Some(ch) = l.children_mut() {
ch.extend(children.into_iter().map(Arc::new));
}
l
}
fn ruler_guide(d: &mut Document, pos: f64) -> Node {
Node::new(d.alloc_id(), NodeKind::RulerGuide { vertical: pos > 300.0, pos, artboard: None })
}
/// Up to six objects: rectangles on and off the artboard, guides made from paths, ruler guides,
/// groups, and sublayers, some hidden, locked or template layers. Groups and sublayers hold more
/// below `depth`. Sublayers and ruler guides also go inside groups, which the app does not make,
/// so that every shape of tree is compared.
fn objects(r: &mut Rng, d: &mut Document, depth: u32) -> Vec<Node> {
(0..r.below(7))
.map(|_| {
let (x, y) = (r.below(1400) as f64 - 300.0, r.below(1000) as f64 - 200.0);
let mut n = match r.below(if depth == 0 { 6 } else { 10 }) {
0..=3 => rect_node(d, x, y),
4 => {
let mut n = rect_node(d, x, y);
if let NodeKind::Path { guide, .. } = &mut n.kind {
*guide = true;
}
n
}
5 => ruler_guide(d, x),
6 | 7 => {
let kids = objects(r, d, depth - 1);
Node::group(d.alloc_id(), kids.into_iter().map(Arc::new).collect())
}
_ => {
let kids = objects(r, d, depth - 1);
layer_node(d, kids)
}
};
n.visible = !r.chance(10);
n.locked = r.chance(10);
if let NodeKind::Layer { template, .. } = &mut n.kind {
*template = r.chance(15);
}
n
})
.collect()
}
/// A document of one to three layers, some hidden, locked or template layers, holding
/// [`objects`], with its artboard locked in some seeds.
fn random_document(seed: u64) -> Document {
let mut r = Rng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1);
let mut d = Document::new(800.0, 600.0);
let layers = (0..1 + r.below(3))
.map(|_| {
let kids = objects(&mut r, &mut d, 3);
let mut l = layer_node(&mut d, kids);
l.visible = !r.chance(10);
l.locked = r.chance(10);
if let NodeKind::Layer { template, .. } = &mut l.kind {
*template = r.chance(10);
}
Arc::new(l)
})
.collect();
d.layers = layers;
if let Some(a) = d.artboards.first_mut() {
a.locked = r.chance(40);
}
d
}
/// Every node of `d`, layers included, in tree order.
fn all_ids(d: &Document) -> Vec<NodeId> {
let mut ids = vec![];
d.walk(|n| ids.push(n.id));
ids
}
/// The objects that hold `id`, outermost first, and the node itself.
fn holders(d: &Document, id: NodeId) -> (Vec<&Node>, &Node) {
let a = d.ancestry(id).unwrap();
let (last, up) = a.split_last().unwrap();
(up.iter().map(|i| d.node(*i).unwrap()).collect(), d.node(*last).unwrap())
}
/// For every node of random documents, outside isolation mode and with each of several nodes
/// isolated, `walk_visits` says what the set of the objects `walk_selectable` visits says, and
/// Next Object Above and Below from it give what the search over that set gave.
#[test]
fn next_object_gives_what_the_search_over_every_selectable_object_gave() {
let (mut steps, mut moved, mut isolated) = (0, 0, 0);
for seed in 0..300 {
let d = random_document(seed);
let ids = all_ids(&d);
let mut r = Rng(seed + 7);
let mut isos = vec![None];
isos.extend((0..10).map(|_| Some(ids[r.below(ids.len() as u64) as usize])));
let locks = d.locked_artboards();
for iso in isos {
let can = selectable_ids(&d, iso);
let iso_node = iso.and_then(|i| d.node(i));
for &id in &ids {
let (up, n) = holders(&d, id);
assert_eq!(walk_visits(&up, n, iso_node, &locks), can.contains(&id), "seed {seed}, isolating {iso:?}, node {id:?}");
}
for &cur in &ids {
for dir in [1, -1] {
let want = step_base(&d, iso, cur, dir);
assert_eq!(step_target(&d, iso, cur, dir), want, "seed {seed}, isolating {iso:?}, from {cur:?}, direction {dir}");
steps += 1;
moved += usize::from(want.is_some());
isolated += usize::from(want.is_some() && iso.is_some());
}
}
}
}
// The documents give many steps that select something, inside isolation mode too.
eprintln!("{moved} of {steps} steps select an object, {isolated} of them in isolation mode");
assert!(moved > 5_000, "{moved} of {steps} steps select an object");
assert!(isolated > 500, "{isolated} steps select an object in isolation mode");
}
/// A session holding `d`, with `iso` isolated and `cur` selected.
fn session(d: Document, iso: Option<NodeId>, cur: NodeId) -> Session {
let mut s = Session::new();
s.add_document(d, None);
let st = s.doc_mut().unwrap();
st.isolation = iso;
st.selection.set([cur]);
s
}
fn selected(s: &Session) -> Vec<NodeId> {
s.doc().unwrap().selection.objects.to_vec()
}
/// In an isolated layer, Next Object Above and Below pass over a sublayer beside the selected object,
/// as the walk looks through it.
#[test]
fn next_object_passes_over_a_sublayer_in_an_isolated_layer() {
let mut d = Document::new(800.0, 600.0);
let a = rect_node(&mut d, 0.0, 0.0);
let inner = rect_node(&mut d, 100.0, 0.0);
let b = rect_node(&mut d, 200.0, 0.0);
let sub = layer_node(&mut d, vec![inner]);
let (a_id, b_id) = (a.id, b.id);
let l = layer_node(&mut d, vec![a, sub, b]);
let layer = l.id;
d.layers = vec![Arc::new(l)];
assert_eq!(step_base(&d, Some(layer), a_id, 1), Some(b_id));
let mut s = session(d, Some(layer), a_id);
s.execute("select.nextAbove", &json!({})).unwrap();
assert_eq!(selected(&s), vec![b_id]);
s.execute("select.nextBelow", &json!({})).unwrap();
assert_eq!(selected(&s), vec![a_id]);
}
/// Next Object Above passes over a ruler guide of the layer, which the walk leaves out, unless the
/// guide is the object isolated.
#[test]
fn next_object_passes_over_a_ruler_guide_of_the_layer() {
let mut d = Document::new(800.0, 600.0);
let a = rect_node(&mut d, 0.0, 0.0);
let b = rect_node(&mut d, 200.0, 0.0);
let guide = ruler_guide(&mut d, 100.0);
let (a_id, b_id, guide_id) = (a.id, b.id, guide.id);
let l = layer_node(&mut d, vec![a, b, guide]);
d.layers = vec![Arc::new(l)];
// Nothing above the rectangle but the guide: the selection stays.
assert_eq!(step_base(&d, None, b_id, 1), None);
let mut s = session(d.clone(), None, b_id);
s.execute("select.nextAbove", &json!({})).unwrap();
assert_eq!(selected(&s), vec![b_id]);
s.execute("select.nextBelow", &json!({})).unwrap();
assert_eq!(selected(&s), vec![a_id]);
// The guide isolated on its own is what there is to select.
assert_eq!(step_base(&d, Some(guide_id), b_id, 1), Some(guide_id));
assert_eq!(step_target(&d, Some(guide_id), b_id, 1), Some(guide_id));
}
/// The first selected object anchors the search even when it can no longer be selected itself.
#[test]
fn next_object_steps_from_a_hidden_first_selected_object() {
let mut d = Document::new(800.0, 600.0);
let mut a = rect_node(&mut d, 0.0, 0.0);
a.visible = false;
let b = rect_node(&mut d, 200.0, 0.0);
let (a_id, b_id) = (a.id, b.id);
let l = layer_node(&mut d, vec![a, b]);
d.layers = vec![Arc::new(l)];
assert_eq!(step_base(&d, None, a_id, 1), Some(b_id));
let mut s = session(d, None, a_id);
s.execute("select.nextAbove", &json!({})).unwrap();
assert_eq!(selected(&s), vec![b_id]);
}
/// The CPU time this thread has used, from Linux's scheduler statistics; `None` elsewhere.
fn thread_cpu() -> Option<Duration> {
let stat = std::fs::read_to_string("/proc/thread-self/schedstat").ok()?;
stat.split_whitespace().next()?.parse().ok().map(Duration::from_nanos)
}
/// The time `f` takes: this thread's CPU time where Linux reports it, otherwise the wall clock.
fn time(f: impl FnOnce()) -> Duration {
match thread_cpu() {
Some(before) => {
f();
thread_cpu().map_or(Duration::ZERO, |after| after.saturating_sub(before))
}
None => {
let start = Instant::now();
f();
start.elapsed()
}
}
}
/// A document of `groups` groups of `per` rectangles on one layer, or of `per` rectangles when
/// `groups` is 0 → the document and the object in the middle of the layer.
fn wide(groups: usize, per: usize) -> (Document, NodeId) {
let mut d = Document::new(800.0, 600.0);
let mut top = vec![];
if groups == 0 {
top.extend((0..per).map(|i| rect_node(&mut d, (i % 200) as f64 * 4.0, (i / 200 % 150) as f64 * 4.0)));
} else {
for g in 0..groups {
let kids: Vec<Arc<Node>> = (0..per).map(|i| Arc::new(rect_node(&mut d, (i % 20) as f64 * 4.0, (g % 150) as f64 * 4.0))).collect();
top.push(Node::group(d.alloc_id(), kids));
}
}
let mid = top[top.len() / 2].id;
let l = layer_node(&mut d, top);
d.layers = vec![Arc::new(l)];
(d, mid)
}
/// A search for the object Next Object Above or Below selects: [`step_base`] or [`step_target`].
type Step = fn(&Document, Option<NodeId>, NodeId, i64) -> Option<NodeId>;
/// Timings of Next Object Above and Below, stepping up and down from the object in the middle of
/// the layer, by the search over every selectable object (200 steps a run) and by the siblings
/// alone (200,000 steps a run, as one step takes too little time to measure), on 100,000
/// rectangles and on 1,000 groups of 100, run in turn on the same document, 7 runs each. Ignored by
/// default; it prints the median, fastest and slowest time per step and sets no bound on them:
/// `cargo test --release -p vectorcraft-engine --lib next_object_perf -- --ignored --nocapture`.
#[test]
#[ignore = "a benchmark: run with --ignored --nocapture"]
fn next_object_perf() {
const RUNS: usize = 7;
const OLD_STEPS: usize = 200;
const NEW_STEPS: usize = 200_000;
let per_step = |d: Duration, steps: usize| d.as_secs_f64() * 1e6 / steps as f64;
eprintln!("next_object_perf: {}", if thread_cpu().is_some() { "thread CPU time" } else { "wall clock" });
eprintln!("next_object_perf: {:<26} {:>32} {:>32}", "document", "every object µs/step (min-max)", "siblings µs/step (min-max)");
for (name, groups, per) in [("100,000 rectangles", 0, 100_000), ("1,000 groups of 100", 1_000, 100)] {
let (d, mid) = wide(groups, per);
let walk = |f: Step, steps: usize| {
let mut cur = mid;
let mut seen = Vec::with_capacity(steps);
for i in 0..steps {
cur = f(&d, None, cur, if i % 2 == 0 { 1 } else { -1 }).unwrap_or(cur);
seen.push(cur);
}
std::hint::black_box(seen)
};
let (mut old, mut new) = (Vec::new(), Vec::new());
let (mut a, mut b) = (vec![], vec![]);
for run in 0..RUNS {
// The two take turns going first.
if run % 2 == 0 {
old.push(time(|| a = walk(step_base, OLD_STEPS)));
new.push(time(|| b = walk(step_target, NEW_STEPS)));
} else {
new.push(time(|| b = walk(step_target, NEW_STEPS)));
old.push(time(|| a = walk(step_base, OLD_STEPS)));
}
assert_eq!(a[..], b[..OLD_STEPS], "{name}");
assert_ne!(a[0], mid, "{name}: the first step selects another object");
}
old.sort();
new.sort();
eprintln!(
"next_object_perf: {name:<26} {:>12.3} ({:>8.3}-{:>9.3}) {:>12.3} ({:>8.3}-{:>9.3})",
per_step(old[RUNS / 2], OLD_STEPS),
per_step(old[0], OLD_STEPS),
per_step(old[RUNS - 1], OLD_STEPS),
per_step(new[RUNS / 2], NEW_STEPS),
per_step(new[0], NEW_STEPS),
per_step(new[RUNS - 1], NEW_STEPS),
);
}
}
+139 -1
View File
@@ -220,8 +220,10 @@ fn own_stroke_or_leaves(s: &Session, p: &Value) -> Result<Vec<vectorcraft_doc::N
})
};
let (mut out, rest): (Vec<_>, Vec<_>) = picked.into_iter().partition(own);
// A leaf already listed is skipped; a set keeps this linear in the number of leaves.
let mut seen: std::collections::HashSet<vectorcraft_doc::NodeId> = out.iter().copied().collect();
for id in super::leaf_targets(s, &rest)? {
if !out.contains(&id) {
if seen.insert(id) {
out.push(id);
}
}
@@ -429,6 +431,52 @@ impl Session {
painted(first, true, &mut nodes);
node_stroke(nodes.first()?)
}
/// Do all the strokes that `stroke.set` edits without `ids` or `item` draw with a brush
/// ([`vectorcraft_brush::keeps_brush_size`])? If they do, a width profile changes none of
/// them, and the result is `Some`, holding whether any of them has a width profile. The result
/// is `None` when a profile changes at least one of them.
///
/// The strokes are the ones `stroke.set` edits:
/// - the Appearance panel's active stroke row in each target that has an equal row
/// ([`ItemTarget::per_target`]), and the top stroke in the others;
/// - else a selected group's own stroke;
/// - else the top strokes of the objects it paints ([`own_stroke_or_leaves`]).
///
/// The art of graph designs is left out, and so are images and symbol instances without an
/// active row. The result is also `None` with nothing selected, with an object inside a symbol
/// instance selected, with type among the targets while no Appearance row is active for it,
/// and with a target that has no stroke row, since `stroke.set` gives such a target a plain
/// stroke.
pub fn brushed_strokes_profiled(&self) -> Option<bool> {
const C: &str = "stroke.set";
let st = self.active()?;
if st.selected_symbol_part().is_some() {
return None;
}
let p = json!({});
let item = item_target(self, &p, C).ok()?.of_kind(self, false);
let ids = if item == ItemTarget::Top { own_stroke_or_leaves(self, &p).ok()? } else { item.targets(self, &p).ok()? };
let mut ids = super::appearance::drop_design_art_rows(self, ids, item, false, C).ok()?;
if item == ItemTarget::Top {
ids.retain(|id| !matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::Image(_) | NodeKind::SymbolInstance { .. })));
}
let mut strokes = vec![];
for (id, each) in ids.iter().zip(item.per_target(self, &ids)) {
let n = st.doc.node(*id)?;
let row = each?.resolve(&n.appearance, false, C).ok()?;
if row.is_none() && matches!(n.kind, NodeKind::Text(_)) {
return None;
}
strokes.push(n.appearance.stroke_at(row).filter(|s| s.brush.is_some())?);
}
if strokes.is_empty() {
return None;
}
// The library is read only when every stroke names a brush.
let lib = vectorcraft_brush::library(&st.doc);
strokes.iter().all(|s| vectorcraft_brush::keeps_brush_size(&lib, s)).then(|| strokes.iter().any(|s| s.profile.is_some()))
}
}
impl DocState {
@@ -678,6 +726,7 @@ fn profile_list(s: &mut Session, _: &Value) -> Result<Value> {
#[cfg(test)]
mod tests {
use super::*;
use vectorcraft_doc::NodeId;
#[test]
fn weight_steps_follow_units_and_stop_at_their_bounds() {
@@ -693,4 +742,93 @@ mod tests {
assert!((step_weight(mm, Unit::Millimeters, true) - 2.0 * mm).abs() < 1e-9);
assert!((step_weight(mm, Unit::Millimeters, false) - 0.75 * mm).abs() < 1e-9);
}
fn run(s: &mut Session, id: &str, p: Value) -> Value {
s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"))
}
fn made(v: Value) -> NodeId {
NodeId(v["id"].as_u64().unwrap_or_else(|| panic!("no id in {v}")))
}
/// The targets of [`own_stroke_or_leaves`] merged by a linear search of the growing list.
fn listed_merge(s: &Session, p: &Value) -> Vec<NodeId> {
let d = &s.doc().unwrap().doc;
let own = |id: &NodeId| {
d.node(*id).is_some_and(|n| {
matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) && !n.is_compound_shape() && n.appearance.stroke().is_some()
})
};
let (mut out, rest): (Vec<_>, Vec<_>) = super::super::targets(s, p).unwrap().into_iter().partition(own);
for id in super::super::leaf_targets(s, &rest).unwrap() {
if !out.contains(&id) {
out.push(id);
}
}
out
}
/// `stroke.set` with no `item` lists the same targets in the same order as a linear merge:
/// groups and layers with a stroke of their own (repeats kept), the leaves of plain groups and
/// layers, compound paths and compound shapes for their members, and each leaf once, also
/// when it is named both directly and through its group.
#[test]
fn stroke_targets_match_the_listed_merge() {
let mut s = Session::new();
run(&mut s, "file.new", json!({"width": 2000, "height": 400}));
let base = s.doc().unwrap().doc.layers[0].id;
let mut x = 0.0;
let mut rect = |s: &mut Session| {
x += 120.0;
made(run(s, "shape.rectangle", json!({"x": x, "y": 100, "width": 100, "height": 100})))
};
let (a, b) = (rect(&mut s), rect(&mut s));
let plain = made(run(&mut s, "object.group", json!({"ids": [a.0, b.0]})));
let (c, d) = (rect(&mut s), rect(&mut s));
let owned = made(run(&mut s, "object.group", json!({"ids": [c.0, d.0]})));
run(&mut s, "appearance.addStroke", json!({"ids": [owned.0]}));
let (e, f) = (rect(&mut s), rect(&mut s));
run(&mut s, "select.set", json!({"ids": [e.0, f.0]}));
let compound = made(run(&mut s, "object.compoundPath.make", json!({})));
let (g, h) = (rect(&mut s), rect(&mut s));
run(&mut s, "select.set", json!({"ids": [g.0, h.0]}));
let shape = made(run(&mut s, "object.compoundShape.make", json!({})));
let lone = rect(&mut s);
let layer = made(run(&mut s, "layer.new", json!({})));
let (j, k) = (rect(&mut s), rect(&mut s));
run(&mut s, "appearance.addStroke", json!({"ids": [layer.0]}));
{
let doc = &s.doc().unwrap().doc;
assert_eq!((doc.parent_of(j), doc.parent_of(k)), (Some(layer), Some(layer)), "the new layer holds the last two");
assert_eq!((doc.parent_of(e), doc.parent_of(g)), (Some(compound), Some(shape)));
assert!(doc.node(owned).unwrap().appearance.stroke().is_some() && doc.node(layer).unwrap().appearance.stroke().is_some());
}
let named = json!({"ids": [plain.0, a.0, owned.0, owned.0, c.0, e.0, compound.0, g.0, lone.0, layer.0, j.0]});
let cases = [
named.clone(),
json!({"ids": [j.0, h.0, f.0, b.0, plain.0, layer.0, owned.0, k.0, shape.0]}),
json!({"ids": [base.0, layer.0, base.0]}),
json!({"ids": [d.0, owned.0, base.0]}),
json!({"ids": []}),
];
for p in &cases {
assert_eq!(own_stroke_or_leaves(&s, p).unwrap(), listed_merge(&s, p), "{p}");
}
run(&mut s, "select.set", json!({"ids": [lone.0, owned.0, f.0, plain.0, b.0, layer.0]}));
assert_eq!(own_stroke_or_leaves(&s, &json!({})).unwrap(), listed_merge(&s, &json!({})), "the selection");
// The edit reaches every listed target, counting a repeated one once, and leaves the other
// member of the group with its own stroke alone.
let want = listed_merge(&s, &named);
assert_eq!(want.iter().filter(|id| **id == owned).count(), 2, "{want:?}");
let distinct: std::collections::HashSet<_> = want.iter().collect();
let before = s.doc().unwrap().doc.node(d).unwrap().clone();
let r = run(&mut s, "stroke.set", json!({"ids": named["ids"], "weight": 3}));
let doc = &s.doc().unwrap().doc;
assert_eq!(r["objects"], distinct.len(), "{r} {want:?}");
for id in &want {
assert_eq!(doc.node(*id).unwrap().appearance.stroke().map(|st| st.width), Some(3.0), "{id:?}");
}
assert_eq!(doc.node(d), Some(&before), "a member reached only through its group's own stroke is left alone");
}
}
+50 -21
View File
@@ -76,7 +76,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Redefine Graphic Style",
["Window", "Appearance"],
None,
"{name?, id?} replace the style (default: the one the object was last linked to) with the look of object `id` or the first selected object (a graph series group with no fill, stroke, effect, opacity, blend mode, isolation, knockout or style link of its own: the topmost path directly in it; a graph's Axes or Legend group: its topmost line or label); the objects still linked to it update, and that object becomes linked. The art of a graph design in a series keeps its look and is unlinked, as the source or as a linked object. A linked graph series group passes the style to the paths directly in it, a linked Axes group to its lines and labels and a linked Legend group to its labels, other than the source and paths linked to the style whose look was edited, and is left cleared (as appearance.clear) and unlinked. On a linked 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, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind → {name}",
"{name?, id?} | {name, from} replace the style (default: the one the object was last linked to) with the look of object `id` or the first selected object (a graph series group with no fill, stroke, effect, opacity, blend mode, isolation, knockout or style link of its own: the topmost path directly in it; a graph's Axes or Legend group: its topmost line or label); the objects still linked to it update, and that object becomes linked. With `from`, the style takes the look of the style named `from` (its fills, strokes, effects, opacity, blend mode, isolate and knockout) and keeps its own name and place; `from` and the objects linked to it stay as they are, `from` naming the style itself or a style with the same look changes nothing, and `from` with `id` is an error. The art of a graph design in a series keeps its look and is unlinked, as the source or as a linked object. A linked graph series group passes the style to the paths directly in it, a linked Axes group to its lines and labels and a linked Legend group to its labels, other than the source and paths linked to the style whose look was edited, and is left cleared (as appearance.clear) and unlinked. On a linked 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, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind → {name}",
has_doc,
style_redefine
),
@@ -318,8 +318,14 @@ impl Session {
/// it is still linked (still has that style's look). A graph series group that holds nothing of its own stands
/// for the topmost path directly inside it, which a style applied to the group links.
pub fn selection_graphic_style(&self) -> Option<(&GraphicStyle, bool)> {
self.graphic_style_of(*self.active()?.selection.subjects().first()?)
}
/// The graphic style of object `id` of the active document, as [`Self::selection_graphic_style`]
/// gives it for the first selected object.
pub fn graphic_style_of(&self, id: NodeId) -> Option<(&GraphicStyle, bool)> {
let st = self.active()?;
let n = super::appearance::look_holder(&st.doc, st.doc.node(*st.selection.subjects().first()?)?);
let n = super::appearance::look_holder(&st.doc, st.doc.node(id)?);
let g = st.doc.graphic_style_by_id(n.extras().graphic_style?)?;
Some((g, in_sync(n, g)))
}
@@ -483,22 +489,43 @@ pub(crate) fn style_json(g: &GraphicStyle) -> Value {
fn style_redefine(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "graphicStyle.redefine";
let (src, n) = source(s, p, cmd)?;
let d = &s.doc()?.doc;
// A series group that holds nothing of its own is redefined from the topmost of its paths, which a style links.
let n = super::appearance::look_holder(d, n);
let src = if n.id == src { src } else { n.id };
let i = match str_param(p, "name") {
Some(name) => style_index(d, name)?,
None => n
.extras()
.graphic_style
.and_then(|id| d.graphic_style_by_id(id))
.and_then(|g| d.graphic_style_index(&g.name))
.ok_or_else(|| bad(cmd, "the object has no graphic style (pass `name`)"))?,
// The style to replace, its new look, and the object that look comes from (none for another style's look).
let (i, look, src) = match p.get("from") {
Some(from) => {
let from = from.as_str().ok_or_else(|| bad(cmd, "`from` must be a graphic style name"))?;
if p.get("id").is_some() {
return Err(bad(cmd, "pass `id` or `from`, not both"));
}
let name = str_param(p, "name").ok_or_else(|| bad(cmd, "missing name (the style `from` replaces)"))?;
let d = &s.doc()?.doc;
let (i, j) = (style_index(d, name)?, style_index(d, from)?);
// A style dropped on itself, or on a style with the same look, stays as it is.
let target = &d.graphic_styles[i];
let look = GraphicStyle { name: target.name.clone(), id: target.id, ..d.graphic_styles[j].clone() };
if i == j || look == *target {
return Ok(json!({ "name": name }));
}
(i, look, None)
}
None => {
let (src, n) = source(s, p, cmd)?;
let d = &s.doc()?.doc;
// A series group that holds nothing of its own is redefined from the topmost of its paths, which a style links.
let n = super::appearance::look_holder(d, n);
let src = if n.id == src { src } else { n.id };
let i = match str_param(p, "name") {
Some(name) => style_index(d, name)?,
None => n
.extras()
.graphic_style
.and_then(|id| d.graphic_style_by_id(id))
.and_then(|g| d.graphic_style_index(&g.name))
.ok_or_else(|| bad(cmd, "the object has no graphic style (pass `name`)"))?,
};
(i, GraphicStyle::of(String::new(), captured(n), n), Some(src))
}
};
let look = GraphicStyle::of(String::new(), captured(n), n);
let name = d.graphic_styles[i].name.clone();
let name = s.doc()?.doc.graphic_styles[i].name.clone();
let chars = s.prefs.override_char_color;
let before = s.doc()?.doc.clone();
s.edit_named("Redefine Graphic Style “{name}”", &name, false, |d, _| {
@@ -507,7 +534,7 @@ fn style_redefine(s: &mut Session, p: &Value) -> Result<Value> {
// Objects still linked follow the new definition; edited ones are unlinked (they keep their look), and the
// source keeps its own. The art of a graph design in a series is unlinked and keeps its look too, as the
// source or as a linked object: the graph draws it again from the design.
let linked = objects_where(d, |n| n.extras().graphic_style == Some(id) && n.id != src);
let linked = objects_where(d, |n| n.extras().graphic_style == Some(id) && Some(n.id) != src);
let (follow, edited): (Vec<NodeId>, Vec<NodeId>) =
linked.into_iter().partition(|nid| !super::graph::is_design_art(d, *nid) && d.node(*nid).is_some_and(|n| in_sync(n, &old)));
set_link(d, &edited, None);
@@ -515,7 +542,7 @@ fn style_redefine(s: &mut Session, p: &Value) -> Result<Value> {
// goes back to the empty appearance the graph draws it with. The source and the edited paths keep their look.
let mut follow_marks = super::graph::series_group_marks(d, &follow);
let edited: HashSet<NodeId> = edited.into_iter().collect();
follow_marks.retain(|nid| *nid != src && !edited.contains(nid));
follow_marks.retain(|nid| Some(*nid) != src && !edited.contains(nid));
super::appearance::clear_stood_for(d, &super::appearance::stood_for(&follow, &follow_marks));
let g = d.graphic_styles[i].clone();
let mut shared = None;
@@ -524,8 +551,10 @@ fn style_redefine(s: &mut Session, p: &Value) -> Result<Value> {
}
super::appearance::capture_series_writes(&before, d, &follow_marks, (true, true), (true, true), false, true);
super::graph::capture_label_rows(d, &follow_marks);
let link = (!super::graph::is_design_art(d, src)).then_some(id);
set_link(d, &[src], link);
if let Some(src) = src {
let link = (!super::graph::is_design_art(d, src)).then_some(id);
set_link(d, &[src], link);
}
Ok(())
})?;
Ok(json!({ "name": name }))
+4 -4
View File
@@ -314,12 +314,12 @@ pub(crate) fn follow_history(st: &mut crate::DocState, was: Option<&SymbolEdit>)
}
}
/// Does `n` hold an instance of symbol `name`, directly or through the art of the symbols it holds
/// instances of?
fn holds_symbol(d: &Document, n: &Node, name: &str, seen: &mut HashSet<String>) -> bool {
/// Does `n` hold an instance of symbol `name` (opacity masks included), directly or through the art
/// of the symbols it holds instances of?
pub(crate) fn holds_symbol(d: &Document, n: &Node, name: &str, seen: &mut HashSet<String>) -> bool {
let mut found = false;
let mut nested = vec![];
n.walk(&mut |c| {
vectorcraft_doc::swatches::walk_with_masks(n, &mut |c| {
if let NodeKind::SymbolInstance { symbol, .. } = &c.kind {
if symbol == name {
found = true;
+50 -1
View File
@@ -20,7 +20,7 @@ use super::clipboard::Clipboard;
use super::clipboard::resources::SwatchChoices;
use super::swatch::str_list;
use super::swatchlib::{FileData, LibraryFile, LibraryInfo, concealed_library_id, concealed_library_ids, shown_id, shown_library_id, stem};
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, number_or, str_param};
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, number_or, str_param, u64_req};
/// The extension of saved symbol libraries: native documents.
pub const SYMBOLS_EXT: &str = vectorcraft_format::EXTENSION;
@@ -54,6 +54,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
add
),
cmd!(
"symbol.placeFromDocument",
"Place Symbol Instance",
[],
None,
"{sourceDocument: uid, name: a symbol of that document, x?, y?} place an instance of a symbol of another open document so its registration point is at (x, y) (default: the first artboard's center), as a symbol dragged from that document's Symbols panel onto the canvas is placed. The symbol, the symbols it nests and the resources they use are added as a drop of art from that document adds them, in the same undo step as the instance: a symbol the active document already has with the same name, art and Symbol Options is used, and one with the same name but other art or Symbol Options gets a number (\"Leaf 2\"); each symbol added takes its Symbol Options along. When sourceDocument is the active document, its own symbol is placed, as symbol.place places it. An error, with no edit, when that document is no longer open or has no symbol `name` → {id, name: the symbol's name in the active document}",
has_doc,
place_from_document
),
cmd!(
"symbol.saveLibrary",
"Save Symbol Library…",
@@ -630,6 +639,46 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
Ok(out)
}
/// `symbol.placeFromDocument`: an instance of symbol `name` of the open document `sourceDocument`
/// placed in the active document, with the symbol and the resources it uses added as a drop of
/// art from that document adds them, in one undo step. The source document is not changed.
fn place_from_document(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "symbol.placeFromDocument";
let uid = u64_req(p, "sourceDocument", C)?;
let name = str_param(p, "name").ok_or_else(|| bad(C, "missing `name`"))?;
let st = s.doc()?;
let centre = st.doc.artboards.first().map(|a| a.rect.center()).unwrap_or(Point::ZERO);
let at = Point::new(number_or(p, "x", centre.x, C)?, number_or(p, "y", centre.y, C)?);
let parent = st.target_parent()?;
let same = uid == st.uid;
let src = s.documents().iter().find(|d| d.uid == uid).map(|d| Arc::clone(&d.doc));
let src = src.ok_or_else(|| bad(C, "the document the symbol came from is no longer open"))?;
if !src.symbols.iter().any(|sym| sym.name == name) {
return Err(bad(C, format!("no symbol named `{name}` in the document it came from")));
}
// A symbol of the active document itself is placed as it is.
let clip = (!same).then(|| Clipboard::gather(&src, vec![instance(name)]));
// The source's colors are kept even where the active document has swatches of the same names.
let choices = SwatchChoices::parse(C, &json!({"swatchConflict": "add"}))?;
let (id, placed) = s.edit("Place Symbol Instance", |d, sel| {
let placed = match &clip {
// Each symbol added takes its Symbol Options along.
Some(clip) => {
let imported = clip.import_into(d, &choices, false)?;
let renamed = imported.renamed.iter().find(|r| r["kind"] == "symbol" && r["from"] == name).and_then(|r| r["to"].as_str());
renamed.unwrap_or(name).to_string()
}
None => name.to_string(),
};
let xf = place_xf(at, natural_size(d, &placed), d.symbol_registration(&placed));
let id = d.alloc_id();
d.insert(parent, usize::MAX, Node::new(id, NodeKind::SymbolInstance { symbol: placed.clone(), xf }))?;
sel.set([id]);
Ok((id, placed))
})?;
Ok(json!({ "id": id.0, "name": placed }))
}
fn save(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "symbol.saveLibrary";
let st = s.doc()?;
+9 -7
View File
@@ -522,14 +522,16 @@ pub(crate) fn style_attrs(d: &Document, para: bool, name: &str) -> Option<Map<St
if para { Kind::Para } else { Kind::Char }.attrs(d, name)
}
/// The fill of `[Normal Character Style]` in `d`: black, or the fill a redefinition gave it. New
/// type starts in that style ([Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html):
/// every character is in it by default; [FAQs on fonts](https://helpx.adobe.com/illustrator/using/fonts-faq.html):
/// new type's defaults are changed by editing it), so it takes this fill, not the current fill
/// left from the last shape (#7975).
pub(crate) fn normal_char_fill(d: &Document) -> vectorcraft_color::Paint {
/// `[Normal Character Style]` in `d`: the defaults, with whatever a redefinition gave it (font,
/// size, fill…). New type starts in that style ([Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html):
/// every character is in it by default; [FAQs on fonts](https://helpx.adobe.com/illustrator/using/fonts-faq.html)
/// and [Change the default font](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/change-the-default-font-in-illustrator.html):
/// new type's defaults, its font included, are changed by editing it), so it takes this style's
/// font and fill, not the current fill left from the last shape (#7975). Attributes that don't
/// pass its checks leave the defaults.
pub(crate) fn normal_char_style(d: &Document) -> CharStyle {
let normal = Kind::Char.attrs(d, NORMAL_CHAR).unwrap_or_default();
with_attrs(&CharStyle::default(), &normal, "text.create").map_or_else(|_| CharStyle::default().fill, |st| st.fill)
with_attrs(&CharStyle::default(), &normal, "text.create").unwrap_or_default()
}
/// `attrs` in the form `charStyle.new` (`para`: `paraStyle.new`) stores them in `d`, or `None`
+25
View File
@@ -1991,6 +1991,31 @@ fn frames_made_into_a_symbol_leave_their_thread_with_their_text() {
}
}
/// New Symbol and Redefine Symbol with `keepArt: true` on a frame of threaded text leave the
/// thread as it was: every frame stays a frame of the thread with the text it holds, and the
/// symbol's art holds a copy of the text the frame shows.
#[test]
fn frames_kept_as_art_by_a_new_or_redefined_symbol_stay_in_their_thread() {
for command in ["symbol.new", "symbol.update"] {
let (mut s, frames) = three_frames(&TEXT.repeat(4), 200.0);
let shown = frames.map(|id| text(&s, id));
let name = if command == "symbol.update" {
let mark = new_id(s.execute("shape.rectangle", &json!({"x": 400, "y": 200, "width": 20, "height": 20})).unwrap());
s.execute("select.set", &json!({"ids": [mark]})).unwrap();
s.execute("symbol.new", &json!({"name": "Mark"})).unwrap();
"Mark"
} else {
"Story"
};
s.execute("select.set", &json!({"ids": [frames[1]]})).unwrap();
let r = s.execute(command, &json!({"name": name, "keepArt": true})).unwrap();
assert!(r["id"].is_null(), "{command}: {r}");
assert_eq!(threads(&s), [frames], "{command}: the thread is as it was");
assert_eq!(frames.map(|id| text(&s, id)), shown, "{command}: each frame keeps its text");
assert_eq!(symbol_texts(&s, name), [shown[1].clone()], "{command}: the symbol's art holds the text the frame shows");
}
}
/// A frame of a numbered thread pasted while an opacity mask is edited numbers from 1 in the
/// mask art too.
#[test]
+10
View File
@@ -25,6 +25,10 @@ pub struct DocState {
/// Panel state, not art selection: not saved, not undoable (`layer.setCurrent`,
/// `layer.highlight`).
pub layer_rows: Vec<NodeId>,
/// The row the last Locate Object or Locate Layer (`layer.locate`) highlighted, until the
/// Layers panel takes it: the panel opens the layers around that row and scrolls to it, also
/// when the row was already highlighted. Panel state: not saved, not undoable.
pub locate_reveal: Option<NodeId>,
/// The variable highlighted in the Variables panel: what its Delete, Options… and Select
/// Bound Object act on. Panel state, not art selection: not saved, not undoable
/// (`variable.highlight`). A name, so renaming a variable moves the highlight with it.
@@ -136,6 +140,10 @@ pub struct DocState {
/// same document comes to the front, its type set in them is not measured again. While this
/// reference lasts, its allocation holds no other document. Not saved.
pub(crate) measured_in_own: Option<(std::sync::Weak<Document>, std::collections::HashSet<String>)>,
/// The document as the last edit's refresh of inline graphics left it, and what that refresh
/// measured: the next refresh checks only the layer trees that differ from it
/// ([`cmd::inline::refresh`]). Not saved.
pub(crate) inline_resolved: Option<cmd::inline::Resolved>,
}
/// Whether a document has an artboard for Delete Empty Artboards to delete, with the document that
@@ -318,6 +326,7 @@ impl DocState {
revision: 1,
active_layer,
layer_rows: vec![],
locate_reveal: None,
variables_highlight: None,
variables_sort: Default::default(),
isolation: None,
@@ -355,6 +364,7 @@ impl DocState {
plugin_effects: Default::default(),
art_to_fit: Default::default(),
measured_in_own: None,
inline_resolved: None,
}
}
/// `measure`'s answer for the document now. `measure` runs once for each version of the document,
+7
View File
@@ -32,6 +32,9 @@ pub struct HistoryEntry {
pub(crate) color_mode_paints: Option<(vectorcraft_tools::PaintDefaults, vectorcraft_tools::PaintDefaults)>,
/// Owned new-art snapshots included in both directional estimates.
color_mode_bytes: usize,
/// The state that changes without an undo step as the next state had it: undo and redo compare
/// it with `doc` to tell what the step changed.
pub(crate) unrecorded: Arc<crate::cmd::Unrecorded>,
}
impl Clone for HistoryEntry {
@@ -49,6 +52,7 @@ impl Clone for HistoryEntry {
serial: self.serial,
color_mode_paints: self.color_mode_paints.clone(),
color_mode_bytes: self.color_mode_bytes,
unrecorded: self.unrecorded.clone(),
}
}
}
@@ -94,6 +98,7 @@ impl HistoryEntry {
serial: next_serial(),
color_mode_paints: None,
color_mode_bytes: 0,
unrecorded: Arc::new(crate::cmd::Unrecorded::of(next)),
}
}
@@ -126,6 +131,7 @@ impl HistoryEntry {
serial: next_serial(),
color_mode_paints: None,
color_mode_bytes: 0,
unrecorded: Arc::new(crate::cmd::Unrecorded::of(now)),
}
}
@@ -337,6 +343,7 @@ impl History {
e.next_bytes = after.saturating_add(e.color_mode_bytes);
e.next = std::ptr::from_ref(now) as usize;
e.serial = next_serial();
e.unrecorded = Arc::new(crate::cmd::Unrecorded::of(now));
}
}
}
+2 -2
View File
@@ -28,7 +28,7 @@ use vectorcraft_tools::{PaintDefaults, Tool};
pub use cmd::clipboard::{Clipboard, SourceLayer};
pub use cmd::create::constrain_click;
pub use cmd::distortcmds::perspective_click;
pub use cmd::distortcmds::{perspective_click, width_point_pair};
pub use cmd::graph::{GraphTypeSubject, calculated_axes as graph_calculated_axes, graph_type_subject};
pub use cmd::params::{check_keys, check_params};
pub use cmd::pathops::auto_simplify_level;
@@ -415,7 +415,7 @@ use history::history_budget_for;
pub use history::{History, HistoryEntry, NamedStep, default_history_budget};
pub(crate) use interaction::PreviewCopies;
pub use interaction::{Interaction, LastTransform, UndoGroup, UndoScope};
pub use prefs::{DrawMode, Prefs};
pub use prefs::{DrawMode, PluginBudget, Prefs};
pub use sanity::TOO_DEEP;
pub(crate) use sanity::{deselect_hidden, is_guide_path};
#[cfg(test)]
+33
View File
@@ -10,6 +10,26 @@ pub enum DrawMode {
Inside,
}
/// Plug-ins & Scratch Disks › Plug-in Instruction Budget: the instructions an object filter's run
/// may use ([`vectorcraft_plugins::Plugin::large_limits`]).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "lowercase")]
pub enum PluginBudget {
/// The plug-in's own limits.
#[default]
Normal,
/// At least [`vectorcraft_plugins::LARGE_FUEL`] instructions besides those for each byte of
/// input; the time budget is unchanged.
Large,
}
/// A saved Plug-in Instruction Budget: any value but `large`, of any type, reads as Normal, and the
/// other preferences are read as they are.
fn plugin_budget<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<PluginBudget, D::Error> {
let saved = <Value as serde::Deserialize>::deserialize(d)?;
Ok(if saved.as_str() == Some("large") { PluginBudget::Large } else { PluginBudget::Normal })
}
/// A saved Default Language as its tag: older preferences hold the language's name, and one the list
/// no longer has reads as the default.
fn language_tag<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<String, D::Error> {
@@ -29,6 +49,12 @@ pub struct Prefs {
pub constrain_angle: f64,
pub corner_radius: f64,
pub disable_auto_add_delete: bool,
/// General › Interpolate Control Points When Moving Anchors: the default of the `interpolate`
/// param of the commands that move direct-selected anchors (a Direct Selection drag, the arrow
/// keys, Move, Transform Again). On, the handles of each segment with one moved end are
/// re-mapped by the turn, scale and move that take its old ends to its new ends. Off (the
/// default), the handles of a moved anchor move with it and the other handles stay.
pub interpolate_control_points: bool,
pub use_precise_cursors: bool,
pub show_tool_tips: bool,
/// Other Script… warns before it runs a chosen script.
@@ -173,6 +199,11 @@ pub struct Prefs {
pub fonts_folder: String,
// Plug-ins & Scratch Disks
pub plugins_folder: String,
/// Plug-in Instruction Budget: the instructions each object filter run gets, from
/// `plugin.run`, a plug-in command and the app alike. Live effects, exporters and importers
/// keep their own budgets.
#[serde(deserialize_with = "plugin_budget")]
pub plugin_instruction_budget: PluginBudget,
pub scratch_primary: String,
pub scratch_secondary: String,
// User Interface
@@ -397,6 +428,7 @@ impl Default for Prefs {
constrain_angle: 0.0,
corner_radius: 12.0,
disable_auto_add_delete: false,
interpolate_control_points: false,
use_precise_cursors: false,
show_tool_tips: true,
show_external_script_warning: true,
@@ -489,6 +521,7 @@ impl Default for Prefs {
hyphenation_exceptions: String::new(),
fonts_folder: String::new(),
plugins_folder: String::new(),
plugin_instruction_budget: PluginBudget::Normal,
scratch_primary: s("Startup"),
scratch_secondary: s("None"),
ui_brightness: s("mediumDark"),
+11 -4
View File
@@ -53,7 +53,8 @@ impl Session {
let mut symbol_synced =
if st.doc.symbol_edit.is_some() { cmd::symboledit::sync(&before, Arc::make_mut(&mut st.doc)) } else { Ok(()) };
// Inline graphics in text follow their symbols.
cmd::inline::refresh(&before, Arc::make_mut(&mut st.doc));
let measured = cmd::inline::refresh(st.inline_resolved.as_ref(), &before, Arc::make_mut(&mut st.doc));
let mut resolved = measured.map(|m| (st.doc.clone(), m));
// The document the passes below start from, for the symbol to follow what they
// change on its editing layer.
let synced = st.doc.symbol_edit.is_some().then(|| st.doc.clone());
@@ -86,7 +87,10 @@ impl Session {
let new = art(&st.doc);
if symbol_synced.is_ok() && !matches!((&old, &new), (Some(a), Some(b)) if Arc::ptr_eq(a, b)) {
let resynced = st.doc.clone();
cmd::inline::refresh(synced, Arc::make_mut(&mut st.doc));
let last = resolved.as_ref().or(st.inline_resolved.as_ref());
if let Some(m) = cmd::inline::refresh(last, synced, Arc::make_mut(&mut st.doc)) {
resolved = Some((st.doc.clone(), m));
}
if !st.doc.text_threads.is_empty() {
cmd::threads::reflow(&resynced, Arc::make_mut(&mut st.doc));
}
@@ -100,6 +104,7 @@ impl Session {
if !st.doc.variables.bindings.is_empty() {
Arc::make_mut(&mut st.doc).prune_variable_bindings();
}
st.inline_resolved = resolved;
if let Err(e) = symbol_synced {
Err(e)
} else if st.doc.too_deep(Some(&before)) {
@@ -437,8 +442,10 @@ impl Session {
// selected): Transform Again moves the selected anchors and the objects selected whole
// by the same distance. A drag that ends where it began leaves the last transform.
let mut options = serde_json::json!({ "copy": false });
if let Some(patterns) = preview.1.get("patterns") {
options["patterns"] = patterns.clone();
for key in ["patterns", "interpolate"] {
if let Some(v) = preview.1.get(key) {
options[key] = v.clone();
}
}
st.last_transform = Some(LastTransform::Matrix(vectorcraft_geom::Affine::translate(moved), options));
st.last_perspective = None;
+102 -2
View File
@@ -85,6 +85,7 @@ mod history_mem;
mod ids_without_selection;
mod inline;
mod interactivity;
mod interpolate_handles;
mod intertwine;
mod journal;
mod keyanchor;
@@ -122,6 +123,7 @@ mod paintproxy;
mod panelcmds;
mod paragraphs;
mod params;
mod params_cache;
mod path_menu_enabled;
mod pathfinder_clip;
mod pathops;
@@ -371,9 +373,12 @@ fn a_long_unknown_command_id_is_answered_at_once() {
fn action_batch_names_the_nearest_command_id() {
let mut s = session();
let e = s.execute("action.batch", &json!({"source": "dataSets", "commands": [{"command": "select.al"}]})).unwrap_err();
assert_eq!(e.to_string(), "invalid parameters for `action.batch`: commands[0]: unknown command `select.al`; did you mean `select.all`?");
assert_eq!(
e.to_string(),
"invalid parameters for `action.batch`: action step 1 (`select.al`) failed: unknown command `select.al`; did you mean `select.all`?"
);
let e = s.execute("action.batch", &json!({"source": "dataSets", "commands": [{"command": "nope"}]})).unwrap_err();
assert_eq!(e.to_string(), "invalid parameters for `action.batch`: commands[0]: unknown command `nope`");
assert_eq!(e.to_string(), "invalid parameters for `action.batch`: action step 1 (`nope`) failed: unknown command `nope`");
}
#[test]
@@ -3215,6 +3220,101 @@ fn every_command_has_unique_id_and_doc() {
assert!(command_specs().iter().all(|c| !c.params.is_empty() && !c.label.is_empty()));
}
/// Ids that name no built-in command: commands only the app runs, near misses of real ids and
/// plug-in command ids of plug-ins that are not installed.
const NOT_BUILT_IN: &[&str] =
&["", "file.save", "file.open", "edit.preferences", "select", "select.none.", "SELECT.NONE", " select.none", "plugin.nobody.cmd", "plugin."];
/// The spec a search of the built-in list in order finds for `id`.
fn first_built_in(id: &str) -> Option<&'static CommandSpec> {
command_specs().iter().find(|c| c.id == id)
}
#[test]
fn find_command_finds_the_spec_a_search_of_the_list_finds() {
let misses: Vec<String> = NOT_BUILT_IN.iter().map(|id| (*id).to_string()).chain((0..200).map(|i| format!("missing.command{i}"))).collect();
for id in command_specs().iter().map(|c| c.id.to_string()).chain(misses) {
let (found, first) = (find_command(&id), first_built_in(&id));
assert!(found.map(std::ptr::from_ref) == first.map(std::ptr::from_ref), "{id:?}");
assert_eq!(found.is_none(), NOT_BUILT_IN.contains(&id.as_str()) || id.starts_with("missing."), "{id:?}");
}
}
#[test]
fn the_command_index_keeps_the_first_spec_of_an_id() {
let base = &command_specs()[0];
let specs = [
CommandSpec { id: "test.twice", label: "First", ..*base },
CommandSpec { id: "test.once", ..*base },
CommandSpec { id: "test.twice", label: "Second", ..*base },
];
let index = crate::cmd::index_by_id(&specs);
assert_eq!(index.len(), 2);
assert!(index.get("test.twice").is_some_and(|c| std::ptr::eq(*c, &specs[0])));
assert!(index.get("test.once").is_some_and(|c| std::ptr::eq(*c, &specs[1])));
assert!(!index.contains_key("test.none"));
}
/// Times [`find_command`] against a search of the built-in list in order (the lookup before the
/// index), in one process, over every built-in id and 200 ids that name no command, and
/// `select.none` run 100,000 times on a document with one rectangle.
/// Run with `cargo test --release -p vectorcraft-engine --lib command_lookup_timing -- --ignored --nocapture`.
#[test]
#[ignore = "manual timing probe; wall-clock performance depends on machine load"]
fn command_lookup_timing() {
use std::hint::black_box;
use std::time::Instant;
let hits: Vec<&str> = command_specs().iter().map(|c| c.id).collect();
let missing: Vec<String> = (0..200 - NOT_BUILT_IN.len()).map(|i| format!("missing.command{i}")).collect();
let misses: Vec<&str> = NOT_BUILT_IN.iter().copied().chain(missing.iter().map(String::as_str)).collect();
let linear = |id: &str| first_built_in(id).or_else(|| crate::cmd::plugin::find_spec(id));
for id in hits.iter().chain(&misses) {
assert!(find_command(id).map(std::ptr::from_ref) == linear(id).map(std::ptr::from_ref), "{id:?}");
}
let per_lookup = |ids: &[&str], f: &dyn Fn(&str) -> Option<&'static CommandSpec>| {
let rounds = 50;
let start = Instant::now();
for _ in 0..rounds {
for id in ids {
black_box(f(black_box(id)));
}
}
start.elapsed().as_nanos() as f64 / (rounds * ids.len()) as f64
};
let median = |mut v: Vec<f64>| {
v.sort_by(f64::total_cmp);
v[v.len() / 2]
};
println!("{} built-in ids, {} ids that name no command", hits.len(), misses.len());
for (what, ids) in [("built-in id", &hits), ("no such command", &misses)] {
let (mut old, mut new) = (Vec::new(), Vec::new());
for run in 0..7 {
// Alternates which lookup goes first, so a change in machine load falls on both.
if run % 2 == 0 {
old.push(per_lookup(ids, &linear));
new.push(per_lookup(ids, &find_command));
} else {
new.push(per_lookup(ids, &find_command));
old.push(per_lookup(ids, &linear));
}
}
println!("{what}: search of the list {old:.0?} ns, median {:.0}; index {new:.0?} ns, median {:.0}", median(old.clone()), median(new.clone()));
}
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 200})).unwrap();
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap();
let runs: Vec<f64> = (0..7)
.map(|_| {
let start = Instant::now();
for _ in 0..100_000 {
black_box(s.execute("select.none", &json!({})).unwrap());
}
start.elapsed().as_nanos() as f64 / 100_000.0
})
.collect();
println!("select.none: {runs:.0?} ns a command, median {:.0}", median(runs.clone()));
}
#[test]
fn every_command_survives_empty_params() {
// Robustness: no command may panic on {} (with and without a selection).
+106
View File
@@ -227,6 +227,112 @@ fn stroke_options_on_a_group_with_its_own_stroke_edit_that_stroke() {
assert_eq!((st.paint, st.width), (Paint::solid(Color::BLACK), 3.0));
}
/// `brushed_strokes_profiled` reads the strokes `stroke.set` edits: a group's own stroke when it
/// has one, else its members'. It answers only while each of them draws with a brush, and not
/// while an object has no stroke row, which `stroke.set` would give a plain stroke.
#[test]
fn brushed_strokes_profiled_reads_the_strokes_stroke_set_edits() {
let mut s = session();
let (a, b) = (rect(&mut s, 100.0), rect(&mut s, 250.0));
run(&mut s, "brush.apply", json!({"ids": [a.0, b.0], "name": "3 pt. Round"}));
run(&mut s, "select.set", json!({"ids": [a.0, b.0]}));
assert_eq!(s.brushed_strokes_profiled(), Some(false), "both draw with a brush, neither has a profile");
run(&mut s, "stroke.set", json!({"ids": [b.0], "profile": "lens"}));
run(&mut s, "select.set", json!({"ids": [a.0, b.0]}));
assert_eq!(s.brushed_strokes_profiled(), Some(true), "one has a profile");
let g = NodeId(run(&mut s, "object.group", json!({"ids": [a.0, b.0]}))["id"].as_u64().unwrap());
run(&mut s, "select.set", json!({"ids": [g.0]}));
assert_eq!(s.brushed_strokes_profiled(), Some(true), "a group without its own stroke: its members'");
run(&mut s, "appearance.addStroke", json!({"ids": [g.0]}));
run(&mut s, "select.set", json!({"ids": [g.0]}));
assert_eq!(s.brushed_strokes_profiled(), None, "the group's own plain stroke takes the profile");
let c = rect(&mut s, 400.0);
run(&mut s, "appearance.removeItem", json!({"ids": [c.0], "index": 1}));
assert!(node(&s, c).appearance.stroke().is_none());
run(&mut s, "select.set", json!({"ids": [a.0, c.0]}));
assert_eq!(s.brushed_strokes_profiled(), None, "an object without a stroke row takes a plain stroke");
}
/// A compound shape's own stroke is the one `stroke.set` edits: brushed members do not count.
#[test]
fn brushed_strokes_profiled_reads_a_compound_shapes_own_stroke() {
let mut s = session();
let (a, b) = (rect(&mut s, 100.0), rect(&mut s, 120.0));
run(&mut s, "select.set", json!({"ids": [a.0, b.0]}));
let c = NodeId(run(&mut s, "object.compoundShape.make", json!({"mode": "add"}))["id"].as_u64().unwrap());
assert!(node(&s, c).appearance.stroke().is_some_and(|st| st.brush.is_none()), "the compound shape's own plain stroke");
s.edit("Brush", |d, _| {
for id in [a, b] {
if let Some(st) = d.node_mut(id).and_then(|n| n.appearance.stroke_mut()) {
st.brush = Some("3 pt. Round".into());
}
}
Ok(())
})
.unwrap();
run(&mut s, "select.set", json!({"ids": [c.0]}));
assert_eq!(s.brushed_strokes_profiled(), None);
s.edit("Brush", |d, _| {
d.node_mut(c).unwrap().appearance.stroke_mut().unwrap().brush = Some("3 pt. Round".into());
Ok(())
})
.unwrap();
run(&mut s, "select.set", json!({"ids": [c.0]}));
assert_eq!(s.brushed_strokes_profiled(), Some(false));
}
/// A targeted layer with its own plain Stroke row active: `stroke.set` edits that row, so the
/// brushed path inside the layer does not count.
#[test]
fn brushed_strokes_profiled_reads_a_targeted_layers_active_stroke_row() {
let mut s = session();
let a = rect(&mut s, 100.0);
run(&mut s, "brush.apply", json!({"ids": [a.0], "name": "3 pt. Round"}));
let layer = s.doc().unwrap().doc.layers[0].id;
run(&mut s, "layer.target", json!({"id": layer.0}));
run(&mut s, "appearance.addStroke", json!({}));
let rows = &node(&s, layer).appearance.items;
let index = rows.iter().position(|it| matches!(it, AppearanceItem::Stroke(st) if st.brush.is_none())).expect("the layer's own stroke row");
run(&mut s, "appearance.setActiveItem", json!({"index": index}));
assert_eq!(s.brushed_strokes_profiled(), None, "the layer's plain stroke takes the profile");
run(&mut s, "stroke.set", json!({"profile": "lens"}));
assert!(node(&s, layer).appearance.items.get(index).is_some_and(|it| matches!(it, AppearanceItem::Stroke(st) if st.profile.is_some())));
assert!(node(&s, a).appearance.stroke().is_some_and(|st| st.profile.is_none()), "the brushed path is left as it was");
}
/// A symbol instance selected with a brushed path takes no stroke from `stroke.set`, so it does
/// not count; the brushed path alone decides.
#[test]
fn brushed_strokes_profiled_leaves_out_symbol_instances() {
let mut s = session();
let a = rect(&mut s, 100.0);
run(&mut s, "brush.apply", json!({"ids": [a.0], "name": "3 pt. Round"}));
let r = rect(&mut s, 300.0);
run(&mut s, "select.set", json!({"ids": [r.0]}));
let inst = NodeId(run(&mut s, "symbol.new", json!({"name": "Dot"}))["id"].as_u64().unwrap());
assert!(matches!(node(&s, inst).kind, NodeKind::SymbolInstance { .. }));
run(&mut s, "select.set", json!({"ids": [a.0, inst.0]}));
assert_eq!(s.brushed_strokes_profiled(), Some(false));
}
/// With the active row a stroke of the first object that another selected object has no equal
/// row for, `stroke.set` edits that object's top stroke, so its top stroke decides.
#[test]
fn brushed_strokes_profiled_falls_back_to_the_top_stroke_where_the_active_row_has_no_match() {
let mut s = session();
let (a, b) = (rect(&mut s, 100.0), rect(&mut s, 250.0));
run(&mut s, "select.set", json!({"ids": [a.0]}));
run(&mut s, "appearance.addStroke", json!({}));
run(&mut s, "brush.apply", json!({"ids": [a.0, b.0], "name": "3 pt. Round"}));
run(&mut s, "stroke.set", json!({"ids": [b.0], "weight": 5}));
let rows = &node(&s, a).appearance.items;
let index = rows.iter().position(|it| matches!(it, AppearanceItem::Stroke(st) if st.brush.is_some())).expect("a's brushed stroke");
assert!(index >= node(&s, b).appearance.items.len() || node(&s, b).appearance.items[index].is_fill(), "{rows:?}");
run(&mut s, "select.set", json!({"ids": [a.0, b.0]}));
run(&mut s, "appearance.setActiveItem", json!({"index": index}));
assert_eq!(s.brushed_strokes_profiled(), Some(false), "b's top stroke has the brush too");
}
#[test]
fn text_items_take_item_paint() {
let mut s = session();
+17
View File
@@ -302,6 +302,23 @@ fn the_shared_settings_drive_the_export_and_arent_an_undo_step() {
assert_eq!(run(&mut s, "document.exportSettings", json!({}))["settings"]["formats"][0]["format"], "jpg");
}
/// The shared settings are not an undo step, so undo and redo of the steps before them leave them
/// as they are.
#[test]
fn undo_and_redo_keep_the_shared_settings() {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0);
run(&mut s, "assets.add", json!({"ids": [a]}));
run(&mut s, "assets.settings.set", json!({"formats": [{"format": "svg"}], "prefix": "ic_"}));
let settings = run(&mut s, "document.exportSettings", json!({}))["settings"].clone();
run(&mut s, "edit.undo", json!({}));
assert_eq!(run(&mut s, "document.exportSettings", json!({}))["settings"], settings);
run(&mut s, "assets.settings.set", json!({"formats": [{"format": "jpg"}], "prefix": ""}));
let settings = run(&mut s, "document.exportSettings", json!({}))["settings"].clone();
run(&mut s, "edit.redo", json!({}));
assert_eq!(run(&mut s, "document.exportSettings", json!({}))["settings"], settings);
}
/// An export preset sets the shared settings as the Asset Export panel applies one: its rows (or
/// mobile/density), its format settings over the saved ones, its prefix and its sub-folders.
#[test]
+331
View File
@@ -1289,6 +1289,29 @@ fn brush_freehand_continued_by_one_point_follows_keep_selected() {
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "the same brush again: no undo step");
}
/// A `brush.freehand` call that continues a path by one point with a bad `connect` is refused
/// before the path's brush changes: the brush, the selection and the undo history stay as they were.
#[test]
fn brush_freehand_continued_by_one_point_refuses_a_bad_connect() {
let mut s = session();
let r = s.execute("brush.freehand", &json!({"points": [[10, 10], [60, 40], [120, 10]], "style": "brush", "brush": "Charcoal"})).unwrap();
let p = NodeId(r["id"].as_u64().unwrap());
let a = rect(&mut s, 200.0, 200.0, 10.0, 10.0);
select(&mut s, &[a]);
let undo = undo_steps(&s);
let one = json!({"points": [[120, 10]], "extend": {"id": p.0, "end": "end"}, "brush": "Dots"});
for connect in
[json!({"id": p.0, "end": "end"}), json!({"id": a.0, "end": "middle"}), json!({"end": "end"}), json!({"id": 999_999, "end": "end"})]
{
let mut params = one.clone();
params["connect"] = connect;
assert!(s.execute("brush.freehand", &params).is_err(), "{params}");
assert_eq!(brush_of(&s, p).as_deref(), Some("Charcoal"), "{params}: the brush stays");
assert_eq!(selected(&s), [a], "{params}: the selection stays");
assert_eq!(undo_steps(&s), undo, "{params}: no undo step");
}
}
/// `brush.freehand` refuses a brush for a path with no stroke (a continued path, a redrawn one
/// and a new filled pencil path while the stroke is None) instead of reporting it painted: the
/// document, the selection and the undo history stay as they were. Without a brush the path is
@@ -1400,6 +1423,40 @@ fn paintbrush_tool_uses_the_current_brush() {
assert!(s.execute("brush.setCurrent", &json!({"name": "Nope"})).is_err());
}
/// The current brush and symbol are not undo steps, so undo and redo of other steps leave them as
/// they are. With nothing else changed outside the history, undo back to the saved document leaves
/// it saved.
#[test]
fn undo_and_redo_keep_the_current_brush_and_symbol() {
let mut s = session();
rect(&mut s, 10.0, 10.0, 20.0, 20.0);
s.execute("symbol.new", &json!({"name": "A"})).unwrap();
rect(&mut s, 40.0, 10.0, 20.0, 20.0);
s.execute("symbol.new", &json!({"name": "B"})).unwrap();
s.doc_mut().unwrap().mark_saved();
rect(&mut s, 70.0, 10.0, 20.0, 20.0);
s.execute("edit.undo", &json!({})).unwrap();
assert!(!s.doc().unwrap().is_dirty(), "back at the saved document");
s.execute("edit.redo", &json!({})).unwrap();
s.execute("brush.setCurrent", &json!({"name": "Arrow"})).unwrap();
s.execute("symbol.setCurrent", &json!({"name": "A"})).unwrap();
let current = |s: &mut Session| {
let brush = s.execute("brush.list", &json!({})).unwrap()["current"].clone();
(brush, s.execute("symbol.list", &json!({})).unwrap()["current"].clone())
};
let want = (json!("Arrow"), json!("A"));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(current(&mut s), want);
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(current(&mut s), want);
// A symbol made current between undoing and redoing its deletion is not kept as current.
s.execute("symbol.delete", &json!({"name": "B"})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
s.execute("symbol.setCurrent", &json!({"name": "B"})).unwrap();
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc.unknown.get("currentSymbol"), Some(&json!("A")));
}
/// A Size: Pressure variant of "3 pt. Round" (3 ± 3 pt).
fn pressure_round(s: &mut Session) {
let params = json!({"variation": [0, 0, 3], "modes": ["fixed", "fixed", "pressure"]});
@@ -1569,6 +1626,34 @@ fn paintbrush_records_the_pens_tilt_on_the_stroke() {
assert_eq!(back.node(pen).unwrap().appearance.stroke(), doc.node(pen).unwrap().appearance.stroke());
}
/// A Bristle path made from pen samples keeps its input when saved and uses it when exported.
#[test]
fn bristle_path_keeps_and_draws_its_pen_pose() {
let mut s = session();
let id = NodeId(
s.execute(
"brush.freehand",
&json!({"points": [[20, 60, 0.1, 10, 0, 0], [200, 60, 0.9, 35, 0, 90]], "style": "brush", "brush": "Bristle Round"}),
)
.unwrap()["id"]
.as_u64()
.unwrap(),
);
let doc: Document = (*s.doc().unwrap().doc).clone();
let st = doc.node(id).unwrap().appearance.stroke().unwrap();
assert!(st.pressure.is_some() && st.tilt.is_some() && st.bearing.is_some() && st.rotation.is_some());
let back = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap();
assert_eq!(back.node(id).unwrap().appearance.stroke(), Some(st));
let mut neutral = doc.clone();
let st = neutral.node_mut(id).unwrap().appearance.stroke_mut().unwrap();
st.pressure = None;
st.tilt = None;
st.bearing = None;
st.rotation = None;
assert_ne!(vectorcraft_svg::export(&doc, &Default::default()), vectorcraft_svg::export(&neutral, &Default::default()));
}
/// Pen pressure belongs to its path: new art, graphic styles and Brush Options' edits leave it.
#[test]
fn pressure_stays_with_its_own_path() {
@@ -1612,6 +1697,46 @@ fn brush_options_set_variation_modes() {
assert_eq!(s.execute("brush.get", &json!({"name": "Dots"})).unwrap()["modes"], modes);
}
/// The fill colors of the copies brushed path `id` draws in `doc`, as `#rrggbb`.
fn piece_fills(doc: &Document, id: NodeId) -> Vec<String> {
let pieces = vectorcraft_brush::node_pieces(doc, doc.node(id).unwrap()).expect("brushed");
pieces.iter().map(|n| n.appearance.fill_paint().color().unwrap().to_hex()).collect()
}
/// Scatter Brush Options' `hue_jitter`: shown by `brush.get`, set by `brush.options`, saved with the
/// document, and the turned colors drawn the same after Open and written by SVG export.
#[test]
fn scatter_hue_jitter_saves_and_exports() {
let mut s = session();
let r = rect(&mut s, 10.0, 200.0, 8.0, 8.0);
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
let name = s.execute("brush.new", &json!({"type": "scatter", "name": "Confetti", "ids": [r.0]})).unwrap()["name"].as_str().unwrap().to_string();
let id = line(&mut s);
select(&mut s, &[id]);
s.execute("brush.apply", &json!({ "name": name })).unwrap();
let plain = piece_fills(&s.doc().unwrap().doc, id);
assert!(plain.len() > 10 && plain.iter().all(|c| c == "#ff0000"), "{plain:?}");
assert_eq!(s.execute("brush.get", &json!({ "name": name })).unwrap()["hue_jitter"], json!(0.0), "brush.get shows the option at 0");
s.execute("brush.options", &json!({"name": name, "params": {"hue_jitter": 120}})).unwrap();
assert_eq!(s.execute("brush.get", &json!({ "name": name })).unwrap()["hue_jitter"], json!(120.0));
let doc = s.doc().unwrap().doc.clone();
let turned = piece_fills(&doc, id);
assert_eq!(turned.len(), plain.len());
let distinct: std::collections::HashSet<&String> = turned.iter().collect();
assert!(distinct.len() > 5, "{turned:?}");
// Saved and opened again, the stroke draws the same colors.
let back = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap();
assert_eq!(piece_fills(&back, id), turned);
// SVG export writes each copy's turned color.
let svg = vectorcraft_svg::export(&doc, &Default::default());
for c in &distinct {
assert!(svg.contains(&format!("fill=\"{c}\"")), "{c} missing from the SVG");
}
// Back to 0, the copies draw the art's own color.
s.execute("brush.options", &json!({"name": name, "params": {"hue_jitter": 0}})).unwrap();
assert_eq!(piece_fills(&s.doc().unwrap().doc, id), plain);
}
/// The bounds of the brush art `id`'s strokes draw.
fn brushed_bounds(s: &Session, id: NodeId) -> Rect {
let st = s.doc().unwrap();
@@ -2074,6 +2199,212 @@ fn break_link_then_update_redefines_all_instances() {
assert!((bounds(&s, other).center().x - 300.0).abs() < 1e-6);
}
/// Redefine Symbol with `keepArt: true` updates the symbol and its instances from the selection,
/// and the selected art stays ordinary art in its place, with its ids, still selected; the result
/// has no instance id. One undo step takes the definition back. Without `keepArt`, or with false,
/// the art becomes an instance.
#[test]
fn redefine_with_keep_art_leaves_the_art_as_ordinary_art() {
let mut s = session();
let (inst, name, _) = make_symbol(&mut s);
let a = rect(&mut s, 20.0, 200.0, 60.0, 30.0);
let b = rect(&mut s, 100.0, 200.0, 40.0, 50.0);
let spot = |s: &Session, id: NodeId| s.doc().unwrap().doc.position(id).map(|(p, i, _)| (p, i));
let before = (node(&s, a), node(&s, b), spot(&s, a), spot(&s, b));
let symbol_art = |s: &Session| s.doc().unwrap().doc.symbols.iter().find(|x| x.name == name).map(|x| x.art.clone()).unwrap();
let old_art = symbol_art(&s);
let steps = s.doc().unwrap().history.undo.len();
select(&mut s, &[a, b]);
let r = s.execute("symbol.update", &json!({"name": name, "keepArt": true})).unwrap();
assert_eq!(r, json!({"name": name, "id": null}));
assert_eq!((node(&s, a), node(&s, b), spot(&s, a), spot(&s, b)), before, "the art is unchanged and in its place");
assert_eq!(s.doc().unwrap().selection.objects, vec![a, b], "the art stays selected");
let instances = |s: &Session| {
let mut n = 0;
s.doc().unwrap().doc.walk(|c| n += usize::from(matches!(c.kind, NodeKind::SymbolInstance { .. })));
n
};
assert_eq!(instances(&s), 1, "no new instance");
// The instance shows the new art: the 120 × 50 pair.
let w = bounds(&s, inst);
assert!((w.width() - 120.0).abs() < 1e-6 && (w.height() - 50.0).abs() < 1e-6, "{w:?}");
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(symbol_art(&s), old_art, "undo takes the definition back");
s.execute("edit.redo", &json!({})).unwrap();
assert!((bounds(&s, inst).width() - 120.0).abs() < 1e-6, "{:?}", bounds(&s, inst));
// false, like no keepArt, makes the art an instance.
for p in [json!({"name": name, "ids": [a.0], "keepArt": false}), json!({"name": name, "ids": [b.0]})] {
let r = s.execute("symbol.update", &p).unwrap();
let id = NodeId(r["id"].as_u64().expect("an instance id"));
assert!(matches!(node(&s, id).kind, NodeKind::SymbolInstance { .. }), "{p}");
assert_eq!(s.doc().unwrap().selection.objects, vec![id], "{p}");
}
assert!(s.doc().unwrap().doc.node(a).is_none() && s.doc().unwrap().doc.node(b).is_none());
}
/// Redefine Symbol with `keepArt: true` and explicit ids keeps the named art selected only where
/// it can be selected: locked or hidden art is left out. A `keepArt` that is not true or false is
/// refused, with no change and no undo step.
#[test]
fn redefine_with_keep_art_selects_only_selectable_art_and_refuses_a_bad_switch() {
let mut s = session();
let (_, name, _) = make_symbol(&mut s);
let a = rect(&mut s, 20.0, 200.0, 60.0, 30.0);
let locked = rect(&mut s, 100.0, 200.0, 40.0, 50.0);
let hidden = rect(&mut s, 200.0, 200.0, 40.0, 50.0);
{
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
doc.node_mut(locked).unwrap().locked = true;
doc.node_mut(hidden).unwrap().visible = false;
}
for bad in [json!("true"), json!(1), json!([true])] {
let before = s.doc().unwrap().doc.clone();
let steps = s.doc().unwrap().history.undo.len();
let e = s.execute("symbol.update", &json!({"name": name, "ids": [a.0], "keepArt": bad})).unwrap_err();
assert!(e.to_string().contains("`keepArt` must be true or false"), "{bad}: {e}");
assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc), "{bad}: the document is unchanged");
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{bad}: no undo step");
}
select(&mut s, &[]);
s.execute("symbol.update", &json!({"name": name, "ids": [a.0, locked.0, hidden.0], "keepArt": true})).unwrap();
assert_eq!(s.doc().unwrap().selection.objects, vec![a], "only the selectable art is selected");
for id in [a, locked, hidden] {
assert!(matches!(node(&s, id).kind, NodeKind::Path { .. }), "{id:?} stays ordinary art");
}
}
/// The number of symbol instances in the document.
fn instance_count(s: &Session) -> usize {
let mut n = 0;
s.doc().unwrap().doc.walk(|c| n += usize::from(matches!(c.kind, NodeKind::SymbolInstance { .. })));
n
}
/// New Symbol with `keepArt: true` makes a symbol of the selection and makes it the current
/// symbol, and the selected art stays ordinary art in its place, with its ids, still selected; the
/// result has no instance id and nothing places the symbol. One undo step takes the symbol away
/// and redo makes it again. Without `keepArt`, or with false, the art becomes an instance.
#[test]
fn new_symbol_with_keep_art_leaves_the_art_as_ordinary_art() {
let mut s = session();
let a = rect(&mut s, 20.0, 200.0, 60.0, 30.0);
let b = rect(&mut s, 100.0, 200.0, 40.0, 50.0);
let spot = |s: &Session, id: NodeId| s.doc().unwrap().doc.position(id).map(|(p, i, _)| (p, i));
let before = (node(&s, a), node(&s, b), spot(&s, a), spot(&s, b));
let steps = s.doc().unwrap().history.undo.len();
select(&mut s, &[a, b]);
let r = s.execute("symbol.new", &json!({"name": "Kept", "keepArt": true})).unwrap();
assert_eq!((&r["name"], &r["id"]), (&json!("Kept"), &Value::Null), "{r}");
assert_eq!((node(&s, a), node(&s, b), spot(&s, a), spot(&s, b)), before, "the art is unchanged and in its place");
assert_eq!(s.doc().unwrap().selection.objects, vec![a, b], "the art stays selected");
assert_eq!(instance_count(&s), 0, "no instance");
let list = s.execute("symbol.list", &json!({})).unwrap();
assert_eq!((&list["current"], &list["symbols"][0]["name"], &list["symbols"][0]["instances"]), (&json!("Kept"), &json!("Kept"), &json!(0)));
// The symbol's art is the pair: an instance placed from it is 120 × 50.
let placed = NodeId(s.execute("symbol.place", &json!({"name": "Kept"})).unwrap()["id"].as_u64().unwrap());
let w = bounds(&s, placed);
assert!((w.width() - 120.0).abs() < 1e-6 && (w.height() - 50.0).abs() < 1e-6, "{w:?}");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "New Symbol is one undo step");
s.execute("edit.undo", &json!({})).unwrap();
assert!(s.doc().unwrap().doc.symbols.is_empty(), "undo takes the symbol away");
assert_eq!((node(&s, a), node(&s, b)), (before.0.clone(), before.1.clone()), "and leaves the art");
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(s.execute("symbol.list", &json!({})).unwrap()["current"], json!("Kept"), "redo");
assert_eq!(instance_count(&s), 0, "redo places no instance");
// false, like no keepArt, makes the art an instance.
for p in [json!({"name": "Plain", "ids": [a.0], "keepArt": false}), json!({"name": "Plain", "ids": [b.0]})] {
let r = s.execute("symbol.new", &p).unwrap();
let id = NodeId(r["id"].as_u64().expect("an instance id"));
assert!(matches!(node(&s, id).kind, NodeKind::SymbolInstance { .. }), "{p}");
assert_eq!(s.doc().unwrap().selection.objects, vec![id], "{p}");
}
assert!(s.doc().unwrap().doc.node(a).is_none() && s.doc().unwrap().doc.node(b).is_none());
}
/// New Symbol with `keepArt: true` and explicit ids keeps the named art selected only where it
/// can be selected: locked or hidden art is left out. A symbol instance in the art stays the
/// instance it was. A `keepArt` that is not true or false is refused, with no symbol, no change and
/// no undo step.
#[test]
fn new_symbol_with_keep_art_selects_only_selectable_art_and_refuses_a_bad_switch() {
let mut s = session();
let (inst, _, _) = make_symbol(&mut s);
let a = rect(&mut s, 20.0, 200.0, 60.0, 30.0);
let locked = rect(&mut s, 100.0, 200.0, 40.0, 50.0);
let hidden = rect(&mut s, 200.0, 200.0, 40.0, 50.0);
{
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
doc.node_mut(locked).unwrap().locked = true;
doc.node_mut(hidden).unwrap().visible = false;
}
for bad in [json!("true"), json!(1), json!([true])] {
let before = s.doc().unwrap().doc.clone();
let steps = s.doc().unwrap().history.undo.len();
let e = s.execute("symbol.new", &json!({"name": "Bad", "ids": [a.0], "keepArt": bad})).unwrap_err();
assert!(e.to_string().contains("`keepArt` must be true or false"), "{bad}: {e}");
assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc), "{bad}: the document is unchanged");
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{bad}: no undo step");
}
select(&mut s, &[]);
let symbols = s.doc().unwrap().doc.symbols.len();
let ids = [a.0, locked.0, hidden.0, inst.0];
s.execute("symbol.new", &json!({"name": "Kept", "ids": ids, "keepArt": true})).unwrap();
assert_eq!(s.doc().unwrap().doc.symbols.len(), symbols + 1);
let selected = &s.doc().unwrap().selection.objects;
assert!(selected.len() == 2 && selected.contains(&a) && selected.contains(&inst), "only the selectable art is selected: {selected:?}");
for id in [a, locked, hidden] {
assert!(matches!(node(&s, id).kind, NodeKind::Path { .. }), "{id:?} stays ordinary art");
}
assert!(matches!(node(&s, inst).kind, NodeKind::SymbolInstance { .. }), "the instance stays an instance");
assert_eq!(instance_count(&s), 1, "no new instance");
}
/// Redefine Symbol refuses art that holds an instance of the symbol it redefines, directly, in a
/// group, in an opacity mask, or through the art of another symbol it holds an instance of, and
/// then changes nothing and adds no undo step. An instance of an unrelated symbol still redefines
/// it.
#[test]
fn redefine_refuses_art_holding_an_instance_of_the_symbol() {
let mut s = session();
let (inst, name, _) = make_symbol(&mut s);
// Ring's art is an instance of Box.
let ring = NodeId(s.execute("symbol.new", &json!({"name": "Ring", "ids": [inst.0]})).unwrap()["id"].as_u64().unwrap());
let place =
|s: &mut Session, x: f64| NodeId(s.execute("symbol.place", &json!({"name": name, "x": x, "y": 200})).unwrap()["id"].as_u64().unwrap());
let direct = place(&mut s, 300.0);
let plain = rect(&mut s, 20.0, 220.0, 30.0, 30.0);
let grouped = place(&mut s, 100.0);
// A rectangle whose opacity mask is a Box instance.
let masked = rect(&mut s, 60.0, 260.0, 30.0, 30.0);
let mut mask_art = node(&s, direct);
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
mask_art.id = doc.alloc_id();
doc.node_mut(masked).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(mask_art, true)));
let cases = [
("a Box instance", vec![direct.0]),
("Ring, whose art holds Box", vec![ring.0]),
("art with a Box instance", vec![plain.0, grouped.0]),
("art masked by a Box instance", vec![masked.0]),
];
for (case, ids) in cases {
let before = s.doc().unwrap().doc.clone();
let undo = s.doc().unwrap().history.undo.len();
let e = s.execute("symbol.update", &json!({"name": name, "ids": ids})).unwrap_err();
assert!(e.to_string().contains("can't hold an instance of itself"), "{case}: {e}");
assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc), "{case}: the document is unchanged");
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "{case}: no undo step");
}
// An instance of a symbol that does not hold Box redefines it.
let dot = rect(&mut s, 200.0, 20.0, 10.0, 10.0);
let dot = NodeId(s.execute("symbol.new", &json!({"name": "Dot", "ids": [dot.0]})).unwrap()["id"].as_u64().unwrap());
let r = s.execute("symbol.update", &json!({"name": name, "ids": [dot.0]})).unwrap();
assert_eq!(r["name"], json!(name));
let art = s.doc().unwrap().doc.symbols.iter().find(|x| x.name == name).map(|x| x.art.clone()).unwrap();
assert!(matches!(&art.kind, NodeKind::SymbolInstance { symbol, .. } if symbol == "Dot"), "{}", art.kind_label());
}
/// A linked opacity mask of a 10 × 10 square at (100, 50).
fn square_mask(s: &mut Session) -> Box<vectorcraft_doc::OpacityMask> {
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
+30
View File
@@ -1083,6 +1083,36 @@ fn shape_builder_drops_a_press_held_during_a_merge() {
}
}
/// When `tool.setOption` names no tool, the option is set on the tool that was active when the
/// call arrived (the Shape Builder), even when finishing its merge replays a held Cmd press that
/// switches to the Selection tool.
#[test]
fn shape_builder_option_set_while_a_cmd_press_is_held_goes_to_the_shape_builder() {
let v = ViewInfo::default();
let mut s = session();
s.select_tool("shapeBuilder", v).unwrap();
s.set_tool_option_cmd(&json!({"key": "pickColorFrom", "value": "swatches"})).unwrap();
square_row(&mut s);
click_row(&mut s, v);
s.pointer(&PointerEvent::new(PointerKind::Down, 305.0, 10.0).with_mods(Mods { cmd: true, ..Default::default() }), v).unwrap();
assert!(s.tool_editing(), "the press is held");
let out = s.set_tool_option_cmd(&json!({"key": "pickColorFrom", "value": "artwork"})).unwrap();
assert_eq!(s.tool_id(), "selection", "the held press lent the selection tool");
assert_eq!(s.lender.as_ref().map(|t| t.id()), Some("shapeBuilder"));
assert_eq!(out["pickColorFrom"], json!("artwork"));
assert_eq!(s.lender.as_ref().map(|t| t.options()["pickColorFrom"].clone()), Some(json!("artwork")));
// Named while it waits, the Shape Builder is read where it waits, not made afresh from the
// preferences.
s.lender.as_mut().unwrap().set_option("pickColorFrom", &json!("swatches"));
let read = s.set_tool_option_cmd(&json!({"tool": "shapeBuilder"})).unwrap();
assert_eq!(read["pickColorFrom"], json!("swatches"), "read from the waiting tool");
// A value set on it counts as set on the tool chosen.
s.tool_set_since_reset = false;
s.set_tool_option_cmd(&json!({"tool": "shapeBuilder", "key": "highlightFill", "value": false})).unwrap();
assert!(s.tool_set_since_reset(), "the tool chosen was set");
assert_eq!(s.lender.as_ref().map(|t| t.options()["highlightFill"].clone()), Some(json!(false)));
}
/// A new revision of the document made outside a command while a merge is computed on another
/// thread keeps the merge when the selected art is as it was (the next poll applies it, as the
/// command computes it), and drops it when the art changed.
+44 -10
View File
@@ -1,5 +1,6 @@
//! `shape.circleThroughPoints`: a circle through three given points, or through the three anchor
//! points selected with Direct Selection, and the Ellipse tool's three Shift-clicks that run it.
//! `shape.circleThroughPoints`: a circle through two or three given points, or through the two or
//! three anchor points selected with Direct Selection, the Ellipse tool's three Shift-clicks that
//! run it, and the Circle tool.
use serde_json::{Value, json};
use vectorcraft_doc::{LiveShape, Node, NodeKind};
@@ -95,13 +96,42 @@ fn coincident_or_collinear_points_are_refused() {
assert!((r - want).abs() / want < 1e-9 && (cx - 200.0).abs() < 1e-6 && (cy - (199.99 + want)).abs() / want < 1e-9, "{out}");
}
/// Points that are not three pairs of finite numbers are an error, not a fallback.
/// Two points are the ends of a diameter: (20, 40) and (100, 100) give the circle centered at
/// (60, 70) with radius 50, through both points, in one undo step. Two points that are the same
/// are refused, and so is a circle that would reach past the canvas, from two points or from three
/// nearly on one line; nothing is drawn and no undo step is recorded.
#[test]
fn two_points_are_the_ends_of_a_diameter() {
let mut s = session();
let undo = undo_len(&s);
let out = s.execute(C, &json!({"points": [[20, 40], [100, 100]]})).unwrap();
assert_eq!((out["cx"].as_f64(), out["cy"].as_f64(), out["radius"].as_f64()), (Some(60.0), Some(70.0), Some(50.0)), "{out}");
let id = id_of(&out);
assert!(bounds_are(&s, id, vectorcraft_geom::Rect::new(10.0, 20.0, 110.0, 120.0)));
assert!(farthest_from_path(&s, id, &[Point::new(20.0, 40.0), Point::new(100.0, 100.0)]) < 50.0 * 3e-4);
assert_eq!(s.doc().unwrap().selection.objects, [id]);
assert_eq!(undo_len(&s), undo + 1);
let (undo, count) = (undo_len(&s), object_count(&s));
let e = s.execute(C, &json!({"points": [[30, 30], [30, 30]]})).unwrap_err().to_string();
assert!(e.contains("no circle passes through these points"), "{e}");
// 4,100,000 pt across, past the canvas's 4,000,000 pt from the origin; and three points 0.001 pt
// off a chord 200 pt long, whose circle has a radius of about 5,000,000 pt.
for points in [json!([[0, 0], [4_100_000, 0]]), json!([[0, 0], [200, 0], [100, 0.001]])] {
let e = s.execute(C, &json!({ "points": points })).unwrap_err().to_string();
assert!(e.contains("result would exceed the canvas"), "{points}: {e}");
}
assert_eq!((undo_len(&s), object_count(&s)), (undo, count));
}
/// Points that are not two or three pairs of finite numbers are an error, not a fallback.
#[test]
fn malformed_points_are_refused() {
let mut s = session();
let undo = undo_len(&s);
for points in [
json!([[0, 0], [10, 0]]),
json!([[0, 0]]),
json!([]),
json!([[0, 0], [10]]),
json!([[0, 0], [10, 0], [0, 10], [5, 5]]),
json!([[0, 0], [10, 0], [0]]),
json!([[0, 0], [10, 0], ["0", 10]]),
@@ -109,12 +139,12 @@ fn malformed_points_are_refused() {
json!([[0, 0], [10, 0], [0, 10, 3]]),
] {
let e = s.execute(C, &json!({ "points": points })).unwrap_err().to_string();
assert!(e.contains("`points` must be three [x, y] pairs of numbers"), "{points}: {e}");
assert!(e.contains("`points` must be two or three [x, y] pairs of numbers"), "{points}: {e}");
}
assert_eq!(undo_len(&s), undo);
}
/// With `points` left out, the three anchor points selected with Direct Selection give the
/// With `points` left out, the two or three anchor points selected with Direct Selection give the
/// circle, from one path or several; any other number of them is an error.
#[test]
fn three_direct_selected_anchor_points_give_the_circle() {
@@ -130,11 +160,15 @@ fn three_direct_selected_anchor_points_give_the_circle() {
s.execute("select.anchors", &json!({"id": other.0, "anchors": [[0, 0]], "mode": "add"})).unwrap();
let out = s.execute(C, &json!({"points": null})).unwrap();
assert_eq!((out["cx"].as_f64(), out["cy"].as_f64()), (Some(40.0), Some(30.0)), "{out}");
// Two or four anchors, or a path of four anchors selected whole.
for picked in [json!([[0, 0], [0, 1]]), json!([[0, 0], [0, 1], [0, 2], [0, 3]])] {
// Two anchors are the ends of a diameter: (0, 0) and (80, 0).
s.execute("select.anchors", &json!({"id": path.0, "anchors": [[0, 0], [0, 1]], "mode": "set"})).unwrap();
let out = s.execute(C, &json!({})).unwrap();
assert_eq!((out["cx"].as_f64(), out["cy"].as_f64(), out["radius"].as_f64()), (Some(40.0), Some(0.0), Some(40.0)), "{out}");
// One or four anchors, or a path of four anchors selected whole.
for picked in [json!([[0, 0]]), json!([[0, 0], [0, 1], [0, 2], [0, 3]])] {
s.execute("select.anchors", &json!({"id": path.0, "anchors": picked, "mode": "set"})).unwrap();
let e = s.execute(C, &json!({})).unwrap_err().to_string();
assert!(e.contains("direct-select three anchor points, or give `points`"), "{picked}: {e}");
assert!(e.contains("direct-select two or three anchor points, or give `points`"), "{picked}: {e}");
}
s.execute("select.set", &json!({"ids": [path.0]})).unwrap();
assert!(s.execute(C, &json!({})).is_err());
@@ -153,7 +187,7 @@ fn three_direct_selected_anchor_points_give_the_circle() {
s.execute("select.segments", &json!({"id": path.0, "segments": [[0, 0], [0, 1]], "mode": "set"})).unwrap();
assert_eq!(s.doc().unwrap().selection.anchors.get(&path).map(|a| a.len()), Some(3));
let e = s.execute(C, &json!({})).unwrap_err().to_string();
assert!(e.contains("direct-select three anchor points, or give `points`"), "{e}");
assert!(e.contains("direct-select two or three anchor points, or give `points`"), "{e}");
assert_eq!(undo_len(&s), undo);
}
+72
View File
@@ -594,6 +594,78 @@ fn separations_preview_compares_the_visible_plates_as_a_set() {
assert!(r["plates"].as_array().unwrap().iter().all(|p| p["visible"] == false), "{r}");
}
/// Each plate's visibility in a `view.separationsPreview` or `color.plates` reply, in plate order.
fn visible_plates(r: &Value) -> Vec<bool> {
r["plates"].as_array().unwrap().iter().map(|p| p["visible"].as_bool().unwrap()).collect()
}
/// A session whose document has the process plates and the spot plate `Brand Orange`.
fn session_with_spot_plate() -> Session {
let mut s = session();
s.execute("swatch.new", &json!({"name": "Brand Orange", "color": {"c": 0, "m": 60, "y": 100, "k": 0}, "global": true})).unwrap();
s.execute("swatch.setSpot", &json!({"name": "Brand Orange"})).unwrap();
let a = NodeId(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap());
s.execute("paint.setFill", &json!({"ids": [a.0], "swatch": "Brand Orange"})).unwrap();
s
}
/// `soloToggle` (the panel's Alt-click on a plate's eye) shows that plate alone, and every plate
/// when it already shows alone. A hidden plate, a plate among others, another solo plate and an
/// empty set of plates all give the named plate alone. It leaves the document's undo list and
/// modified state alone.
#[test]
fn separations_preview_solo_toggle_shows_every_plate_the_second_time() {
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
let _v = DefaultView::new();
let mut s = session_with_spot_plate();
let undo = s.doc().unwrap().history.undo.len();
let dirty = s.doc().unwrap().is_dirty();
let solo = |s: &mut Session, n: &str| visible_plates(&s.execute("view.separationsPreview", &json!({"soloToggle": n})).unwrap());
// Off: the preview turns on with the plate alone.
assert_eq!(solo(&mut s, "Cyan"), [true, false, false, false, false]);
assert_eq!(vectorcraft_render::proof::view().separations, Some(vec!["Cyan".to_string()]));
// The same plate again: every plate, the spot plate included, and the preview stays on.
assert_eq!(solo(&mut s, "Cyan"), [true; 5]);
assert!(vectorcraft_render::proof::view().separations.is_some(), "the preview stays on");
// A plate shown among others, then another plate while one shows alone.
assert_eq!(solo(&mut s, "Magenta"), [false, true, false, false, false]);
assert_eq!(solo(&mut s, "Cyan"), [true, false, false, false, false]);
// A hidden plate.
s.execute("view.separationsPreview", &json!({"toggle": "Black"})).unwrap();
assert_eq!(solo(&mut s, "Yellow"), [false, false, true, false, false]);
// No plate shown.
s.execute("view.separationsPreview", &json!({"plates": []})).unwrap();
assert_eq!(solo(&mut s, "Black"), [false, false, false, true, false]);
// The spot plate alone, then every plate.
assert_eq!(solo(&mut s, "Brand Orange"), [false, false, false, false, true]);
assert_eq!(solo(&mut s, "Brand Orange"), [true; 5]);
// A plate the document doesn't have is an error and leaves the view as it is.
let before = vectorcraft_render::proof::view();
assert!(s.execute("view.separationsPreview", &json!({"soloToggle": "Mauve"})).is_err());
assert_eq!(vectorcraft_render::proof::view(), before);
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step");
assert_eq!(s.doc().unwrap().is_dirty(), dirty, "not marked modified");
// `only` stays a setter: the same plate again keeps it alone.
s.execute("view.separationsPreview", &json!({"only": "Cyan"})).unwrap();
let r = s.execute("view.separationsPreview", &json!({"only": "Cyan"})).unwrap();
assert_eq!(visible_plates(&r), [true, false, false, false, false]);
}
/// A plate counts as shown alone when no other plate of the active document shows: names left in
/// the visible set by another document's plates don't count.
#[test]
fn separations_preview_solo_toggle_counts_the_active_documents_plates() {
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
let _v = DefaultView::new();
let mut s = session_with_spot_plate();
s.execute("view.separationsPreview", &json!({"plates": ["Cyan", "Brand Orange"]})).unwrap();
// A new document without the spot plate: Cyan is the only one of its plates shown.
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
assert_eq!(visible_plates(&s.execute("color.plates", &json!({})).unwrap()), [true, false, false, false]);
let r = s.execute("view.separationsPreview", &json!({"soloToggle": "Cyan"})).unwrap();
assert_eq!(visible_plates(&r), [true; 4]);
}
#[test]
fn proof_setup_simulates_tritanopia() {
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
+66 -5
View File
@@ -414,6 +414,61 @@ fn pencil_refuses_an_unknown_style_or_extend_end() {
assert!(ends.contains(&Point::new(0.0, 100.0)) && ends.contains(&Point::new(200.0, 100.0)), "continued from its start: {ends:?}");
}
/// `path.freehand` refuses a `connect` without `extend`, and checks a `connect` given with `extend`
/// before a stroke of one point returns, so a bad one is refused there too; a refused call changes
/// neither the document nor the undo history. A `connect` of null is a key left out.
#[test]
fn pencil_refuses_connect_without_extend_and_a_bad_connect_for_one_point() {
let mut s = session();
let a = line(&mut s, 100.0, 100.0, 200.0, 100.0);
let b = line(&mut s, 300.0, 200.0, 400.0, 200.0);
let closed = NodeId(s.execute("path.create", &json!({"d": "M0 500 L50 500 L50 550 Z"})).unwrap()["id"].as_u64().unwrap());
let inner = NodeId(s.execute("path.create", &json!({"d": "M600 500 L650 500"})).unwrap()["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [inner.0]})).unwrap();
let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
let stroke = json!({"points": [[200, 100], [250, 150], [300, 200]]});
for connect in [json!({"id": b.0, "end": "start"}), json!({"id": b.0, "end": "middle"}), json!({"id": b.0}), json!({})] {
refuses_with(&mut s, "path.freehand", &with(&stroke, json!({ "connect": connect })), "connect needs extend");
refuses_with(&mut s, "path.freehand", &with(&stroke, json!({"extend": null, "connect": connect})), "connect needs extend");
}
let refused = |s: &mut Session, p: &serde_json::Value| {
let before = s.doc().unwrap().doc.clone();
let undo = undo_steps(s);
assert!(s.execute("path.freehand", p).is_err(), "{p}");
assert!(s.doc().unwrap().doc == before, "{p} changed the document");
assert_eq!(undo_steps(s), undo, "{p} left an undo step");
};
refused(&mut s, &with(&stroke, json!({"connect": "b"})));
let one = json!({"points": [[200, 100]], "extend": {"id": a.0, "end": "end"}});
let end = "connect end must be \"start\" or \"end\"";
for e in [json!("middle"), json!(1), json!(null)] {
refuses_with(&mut s, "path.freehand", &with(&one, json!({"connect": {"id": b.0, "end": e}})), end);
}
refuses_with(&mut s, "path.freehand", &with(&one, json!({"connect": {"id": b.0}})), end);
refuses_with(&mut s, "path.freehand", &with(&one, json!({"connect": {"end": "end"}})), "connect needs id");
refuses_with(&mut s, "path.freehand", &with(&one, json!({"connect": {"id": "b", "end": "end"}})), "`id` must be a whole number");
let other = "connect needs a path other than the one extended";
refuses_with(&mut s, "path.freehand", &with(&one, json!({"connect": {"id": a.0, "end": "end"}})), other);
refuses_with(&mut s, "path.freehand", &with(&one, json!({"connect": {"id": closed.0, "end": "end"}})), "connect path has no open end");
for p in [
with(&one, json!({"connect": "b"})),
with(&one, json!({"connect": {"id": 999_999, "end": "end"}})),
with(&one, json!({"connect": {"id": group.0, "end": "end"}})),
] {
refused(&mut s, &p);
}
assert_eq!((paths(&s).len(), path(&s, a).anchor_count(), path(&s, b).anchor_count()), (4, 2, 2), "refused: nothing changed");
// A good `connect`, or a null one, on a stroke of one point leaves the path as it was.
let undo = undo_steps(&s);
for connect in [json!({"id": b.0, "end": "start"}), json!(null)] {
assert_eq!(s.execute("path.freehand", &with(&one, json!({ "connect": connect }))).unwrap()["id"], json!(a.0));
}
assert_eq!((path(&s, a).anchor_count(), undo_steps(&s)), (2, undo));
// Null without `extend`, `connect` is left out, and the stroke draws a new path.
s.execute("path.freehand", &with(&stroke, json!({"connect": null}))).unwrap();
assert_eq!(paths(&s).len(), 5);
}
/// With Keep selected off, a compound path whose direct-selected anchors all lie on the subpath
/// that connect joins on is no longer selected, and Delete then has nothing to delete.
#[test]
@@ -6292,14 +6347,20 @@ fn pencil_at_the_lowest_fidelity_takes_degenerate_strokes() {
}
}
/// The Pencil's Fidelity option takes 0.01, and the Smooth tool's stays at 0.05 or more.
/// The Pencil's Fidelity option takes 0.01, and the Smooth tool's 0.05 or more: a lower Fidelity is
/// an error that leaves the option as it was.
#[test]
fn pencil_option_takes_a_hundredth_and_smooth_keeps_its_floor() {
let mut s = session();
for (tool, want) in [("pencil", 0.01), ("paintbrush", 0.01), ("smooth", 0.05)] {
s.set_tool_option_cmd(&json!({"tool": tool, "values": {"fidelity": 0.001}})).unwrap();
assert_eq!(s.tool_options_of(tool)["fidelity"].as_f64(), Some(want), "{tool}");
s.set_tool_option_cmd(&json!({"tool": tool, "values": {"fidelity": 0.02}})).unwrap();
for (tool, floor) in [("pencil", 0.01), ("paintbrush", 0.01), ("smooth", 0.05)] {
let before = s.tool_options_of(tool)["fidelity"].clone();
let e = s.set_tool_option_cmd(&json!({"tool": tool, "values": {"fidelity": 0.001}})).unwrap_err();
assert_eq!(e, format!("tool `{tool}`: `fidelity` must be a number from {floor} to 100"));
assert_eq!(s.tool_options_of(tool)["fidelity"], before, "{tool}");
s.set_tool_option_cmd(&json!({"tool": tool, "values": {"fidelity": floor}})).unwrap();
assert_eq!(s.tool_options_of(tool)["fidelity"].as_f64(), Some(floor), "{tool}");
let hundredth = s.set_tool_option_cmd(&json!({"tool": tool, "values": {"fidelity": 0.02}}));
assert_eq!(hundredth.is_ok(), tool != "smooth", "{tool}");
assert_eq!(s.tool_options_of(tool)["fidelity"].as_f64(), Some(if tool == "smooth" { 0.05 } else { 0.02 }), "{tool}");
}
}
+270
View File
@@ -260,6 +260,100 @@ fn a_stroke_effect_reshapes_a_stroke_a_dynamic_instance_adds() {
assert!(b.x0 <= 31.0 && b.x1 >= 169.0, "the bounds take in the offset stroke: {b:?}");
let drawn = vectorcraft_render::drawn_bounds(&doc, doc.node(id).unwrap()).expect("the instance is drawn");
assert!(drawn.x0 <= 31.0 && drawn.x1 >= 169.0, "the drawn bounds take in the offset stroke: {drawn:?}");
assert_eq!(hit_at(&s, 30.5, vectorcraft_doc::hit::HitOptions { tol: 1.0, ..Default::default() }), Some(id), "a click on the added stroke");
}
/// What a click at (`x`, 100) with `opt` hits.
fn hit_at(s: &Session, x: f64, opt: vectorcraft_doc::hit::HitOptions) -> Option<NodeId> {
vectorcraft_doc::hit::hit_test(&s.doc().unwrap().doc, vectorcraft_geom::Point::new(x, 100.0), opt).map(|h| h.leaf)
}
/// [`instance_with_row`] of a symbol whose art is an instance of another symbol made of the square.
fn nested_instance_with_row(s: &mut Session) -> (NodeId, usize) {
square(s);
let inner = NodeId(run(s, "symbol.new", json!({"name": "Inner"}))["id"].as_u64().unwrap());
run(s, "select.set", json!({"ids": [inner.0]}));
let id = NodeId(run(s, "symbol.new", json!({"name": "Outer"}))["id"].as_u64().unwrap());
run(s, "appearance.addFill", json!({"ids": [id.0]}));
let row = node(s, id).appearance.items.len() - 1;
run(s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true}));
(id, row)
}
/// Effect › Pathfinder › Add on a group holding a symbol instance combines the art the instance
/// draws: the effects on the instance's fill and stroke reshape the result as they reshape the
/// instance, in a symbol placed inside another symbol too.
#[test]
fn pathfinder_takes_a_symbol_instance_fill_and_stroke_effects() {
for (fill, x, color) in [(true, 44, RED), (false, 40, BLUE)] {
let mut s = session();
let (id, row) = instance_with_row(&mut s, "Square", fill);
offset_row(&mut s, id, row, 10.0);
let g = NodeId(run(&mut s, "object.group", json!({"ids": [id.0]}))["id"].as_u64().unwrap());
run(&mut s, "effect.apply", json!({"ids": [g.0], "effect": "pathfinder.add"}));
let r = render(&s);
assert!(near(r.pixel(x, 100), color), "fill {fill}: the result keeps the offset: {:?}", r.pixel(x, 100));
assert!(near(r.pixel(100, 100), RED), "fill {fill}: the result keeps the art's fill: {:?}", r.pixel(100, 100));
}
// An effect of the instance's own reshapes the art as well.
let mut s = session();
let (id, row) = instance_with_row(&mut s, "Square", true);
offset_row(&mut s, id, row, 10.0);
run(&mut s, "effect.apply", json!({"ids": [id.0], "item": null, "effect": "path.offsetPath", "params": {"offset": 5}}));
assert!(near(render(&s).pixel(37, 100), RED), "both offsets grow the art on the canvas: {:?}", render(&s).pixel(37, 100));
let g = NodeId(run(&mut s, "object.group", json!({"ids": [id.0]}))["id"].as_u64().unwrap());
run(&mut s, "effect.apply", json!({"ids": [g.0], "effect": "pathfinder.add"}));
assert!(near(render(&s).pixel(37, 100), RED), "both offsets grow the result: {:?}", render(&s).pixel(37, 100));
let mut s = session();
let (id, row) = nested_instance_with_row(&mut s);
offset_row(&mut s, id, row, 10.0);
assert!(near(render(&s).pixel(44, 100), RED), "the nested art grows on the canvas: {:?}", render(&s).pixel(44, 100));
let g = NodeId(run(&mut s, "object.group", json!({"ids": [id.0]}))["id"].as_u64().unwrap());
run(&mut s, "effect.apply", json!({"ids": [g.0], "effect": "pathfinder.add"}));
assert!(near(render(&s).pixel(44, 100), RED), "the nested art grows in the result: {:?}", render(&s).pixel(44, 100));
}
/// A click where the effect on a symbol instance's fill or stroke paints its art outside the
/// instance's bounds selects the instance; a click past the drawn art, a fill with Selection by
/// Path Only and outline mode do not.
#[test]
fn a_click_where_a_symbol_instance_fill_or_stroke_effect_paints_selects_it() {
use vectorcraft_doc::hit::HitOptions;
let opt = HitOptions { tol: 1.0, ..Default::default() };
let mut s = session();
let (id, row) = instance_with_row(&mut s, "Square", true);
assert_eq!(hit_at(&s, 44.0, opt), None);
offset_row(&mut s, id, row, 10.0);
assert_eq!(hit_at(&s, 44.0, opt), Some(id), "a click on the grown fill");
assert_eq!(hit_at(&s, 100.0, opt), Some(id), "a click inside the instance");
assert_eq!(hit_at(&s, 36.0, opt), None, "a click past the grown fill");
assert_eq!(hit_at(&s, 44.0, HitOptions { path_only: true, ..opt }), None, "Selection by Path Only leaves the fill out");
assert_eq!(hit_at(&s, 44.0, HitOptions { outline: true, ..opt }), None, "outline mode draws the art as it is");
let mut s = session();
let (id, row) = instance_with_row(&mut s, "Square", false);
offset_row(&mut s, id, row, 10.0);
assert_eq!(hit_at(&s, 40.0, opt), Some(id), "a click on the moved stroke");
assert_eq!(hit_at(&s, 45.0, opt), None, "a click between the moved stroke and the fill");
assert_eq!(hit_at(&s, 40.0, HitOptions { path_only: true, ..opt }), Some(id), "Selection by Path Only takes the stroke");
let mut s = session();
let (id, row) = nested_instance_with_row(&mut s);
offset_row(&mut s, id, row, 10.0);
assert_eq!(hit_at(&s, 44.0, opt), Some(id), "a click on the grown fill of the nested art");
// A path in the art with an Offset Path of its own: both offsets grow what it draws.
let mut s = session();
let art = square(&mut s);
run(&mut s, "effect.apply", json!({"ids": [art.0], "item": null, "effect": "path.offsetPath", "params": {"offset": 5}}));
let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Offset"}))["id"].as_u64().unwrap());
run(&mut s, "appearance.addFill", json!({"ids": [id.0]}));
let row = node(&s, id).appearance.items.len() - 1;
run(&mut s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true}));
offset_row(&mut s, id, row, 10.0);
assert!(near(render(&s).pixel(37, 100), RED), "both offsets grow the art on the canvas: {:?}", render(&s).pixel(37, 100));
assert_eq!(hit_at(&s, 37.0, opt), Some(id), "a click where both offsets grow the art");
}
/// A group in the symbol's art with a fill of its own: the instance's fill effect reshapes what
@@ -284,6 +378,7 @@ fn a_fill_effect_reshapes_the_fill_of_a_group_in_the_art() {
assert!(b.x0 <= 31.0 && b.x1 >= 169.0, "the bounds take in the group's grown fill: {b:?}");
let drawn = vectorcraft_render::drawn_bounds(&doc, doc.node(id).unwrap()).expect("the instance is drawn");
assert!(drawn.x0 <= 31.0 && drawn.x1 >= 169.0, "the drawn bounds take in the group's grown fill: {drawn:?}");
assert_eq!(hit_at(&s, 35.0, vectorcraft_doc::hit::HitOptions { tol: 1.0, ..Default::default() }), Some(id), "a click on the group's grown fill");
let before = render(&s);
run(&mut s, "effect.expandAppearance", json!({}));
@@ -292,6 +387,181 @@ fn a_fill_effect_reshapes_the_fill_of_a_group_in_the_art() {
assert!(differing(&before, &after, 8) < 200, "expanding changed {} pixels", differing(&before, &after, 8));
}
/// An image whose fill Convert to Shape gives a shape, selected. The frame runs from 85 to 115;
/// the fill's shape is 9 pt larger on each side.
fn image_with_shaped_fill(s: &mut Session) -> NodeId {
let mut png = vec![];
image::RgbaImage::from_pixel(30, 30, image::Rgba([255, 0, 0, 255]))
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
.unwrap();
let r = run(s, "file.place", json!({"name": "red.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [100, 100]}));
let im = NodeId(r["ids"][0].as_u64().unwrap());
run(s, "select.set", json!({"ids": [im.0]}));
run(s, "appearance.addFill", json!({}));
run(s, "paint.setFill", json!({"color": "#0000ff", "item": 0}));
run(s, "effect.apply", json!({"effect": "convertToShape.rectangle", "item": 0}));
im
}
/// The objects a marquee from `x0` to `x1` across y = 100 touches, as the canvas shows them, in
/// outline with `outline`.
fn marquee_at(s: &Session, x0: f64, x1: f64, outline: bool) -> Vec<NodeId> {
let r = vectorcraft_geom::Rect::new(x0, 90.0, x1, 110.0);
vectorcraft_doc::hit::marquee_in_view(&s.doc().unwrap().doc, r, None, true, outline)
}
/// A marquee touches a symbol instance where the geometry effects of its fill or stroke paint its
/// art outside its box, as a click there selects it, except in outline.
#[test]
fn a_marquee_where_a_symbol_instance_fill_or_stroke_effect_paints_selects_it() {
let mut s = session();
let (id, row) = instance_with_row(&mut s, "Square", true);
assert_eq!(marquee_at(&s, 38.0, 45.0, false), []);
offset_row(&mut s, id, row, 10.0);
assert_eq!(marquee_at(&s, 38.0, 45.0, false), [id], "a marquee across the grown fill");
assert_eq!(marquee_at(&s, 30.0, 37.0, false), [], "a marquee past the grown fill");
assert_eq!(marquee_at(&s, 38.0, 45.0, true), [], "outline mode draws the art as it is");
let mut s = session();
let (id, row) = instance_with_row(&mut s, "Square", false);
offset_row(&mut s, id, row, 10.0);
assert_eq!(marquee_at(&s, 38.0, 42.0, false), [id], "a marquee across the moved stroke");
assert_eq!(marquee_at(&s, 43.0, 45.0, false), [], "a marquee between the moved stroke and the fill");
let mut s = session();
let (id, row) = nested_instance_with_row(&mut s);
offset_row(&mut s, id, row, 10.0);
assert_eq!(marquee_at(&s, 38.0, 45.0, false), [id], "a marquee across the grown fill of the nested art");
}
/// A marquee touches an image where the shape of its own fill lies outside its frame, and an
/// instance of a symbol made of that image where the instance's fill effect grows that shape, as
/// clicks there select them, except in outline.
#[test]
fn a_marquee_on_the_shape_of_an_image_fill_selects_it() {
let mut s = session();
let im = image_with_shaped_fill(&mut s);
assert_eq!(marquee_at(&s, 74.0, 79.0, false), [im], "a marquee across the fill's shape outside the frame");
assert_eq!(marquee_at(&s, 70.0, 75.0, false), [], "a marquee past the fill's shape");
assert_eq!(marquee_at(&s, 74.0, 79.0, true), [], "outline mode draws the frame");
let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Image"}))["id"].as_u64().unwrap());
run(&mut s, "appearance.addFill", json!({"ids": [id.0]}));
let row = node(&s, id).appearance.items.len() - 1;
run(&mut s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true}));
offset_row(&mut s, id, row, 10.0);
assert_eq!(marquee_at(&s, 64.0, 68.0, false), [id], "a marquee across the instance's grown fill");
assert_eq!(marquee_at(&s, 58.0, 63.0, false), [], "a marquee past the grown fill");
}
/// An image in the symbol's art whose fill Convert to Shape gives a shape: the instance's fill
/// effect grows what that fill paints, and a click there selects the instance.
#[test]
fn a_click_on_the_grown_fill_of_an_image_in_the_art_selects_the_instance() {
let mut s = session();
image_with_shaped_fill(&mut s);
let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Image"}))["id"].as_u64().unwrap());
run(&mut s, "appearance.addFill", json!({"ids": [id.0]}));
let row = node(&s, id).appearance.items.len() - 1;
run(&mut s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true}));
let opt = vectorcraft_doc::hit::HitOptions { tol: 1.0, ..Default::default() };
assert_eq!(hit_at(&s, 70.0, opt), None);
offset_row(&mut s, id, row, 10.0);
assert!(near(render(&s).pixel(70, 100), BLUE), "the image's fill grows by the offset: {:?}", render(&s).pixel(70, 100));
assert_eq!(hit_at(&s, 70.0, opt), Some(id), "a click on the image's grown fill");
assert_eq!(hit_at(&s, 60.0, opt), None, "a click past the grown fill");
}
/// A group in the symbol's art with Effect › Pathfinder › Subtract: the instance's fill effect
/// grows the result, and a click past both shapes where only the subtracted shape would grow does
/// not select the instance.
#[test]
fn a_click_on_a_shape_a_pathfinder_effect_in_the_art_subtracts_misses_the_instance() {
let mut s = session();
// The back square runs from 50 to 110 and the front one from 80 to 140; the result runs from 50 to 80.
let back = NodeId(run(&mut s, "shape.rectangle", json!({"x": 50, "y": 50, "width": 60, "height": 100}))["id"].as_u64().unwrap());
run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
run(&mut s, "paint.setStroke", json!({"color": "#0000ff"}));
run(&mut s, "stroke.set", json!({"weight": 4}));
let front = NodeId(run(&mut s, "shape.rectangle", json!({"x": 80, "y": 50, "width": 60, "height": 100}))["id"].as_u64().unwrap());
let g = NodeId(run(&mut s, "object.group", json!({"ids": [back.0, front.0]}))["id"].as_u64().unwrap());
run(&mut s, "effect.apply", json!({"ids": [g.0], "effect": "pathfinder.subtract"}));
run(&mut s, "select.set", json!({"ids": [g.0]}));
let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Subtracted"}))["id"].as_u64().unwrap());
run(&mut s, "appearance.addFill", json!({"ids": [id.0]}));
let row = node(&s, id).appearance.items.len() - 1;
run(&mut s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true}));
let opt = vectorcraft_doc::hit::HitOptions { tol: 1.0, ..Default::default() };
assert_eq!(hit_at(&s, 45.0, opt), None);
offset_row(&mut s, id, row, 10.0);
let r = render(&s);
assert!(near(r.pixel(45, 100), RED), "the result's fill grows by the offset: {:?}", r.pixel(45, 100));
assert!(near(r.pixel(145, 100), WHITE), "the subtracted shape is not drawn: {:?}", r.pixel(145, 100));
assert_eq!(hit_at(&s, 45.0, opt), Some(id), "a click on the result's grown fill");
assert_eq!(hit_at(&s, 145.0, opt), None, "a click where only the subtracted shape would grow");
}
/// A Shaper group in the symbol's art: the instance's fill effect grows the faces it shows, and a
/// click where only its original shapes would grow does not select the instance.
#[test]
fn a_click_on_a_shaper_groups_original_shapes_in_the_art_misses_the_instance() {
let mut s = session();
run(&mut s, "paint.setStroke", json!({"none": true, "ids": []}));
for x in [0, 50] {
run(&mut s, "paint.setFill", json!({"color": "#ff0000", "ids": []}));
run(&mut s, "shape.rectangle", json!({"x": x, "y": 50, "width": 100, "height": 100}));
}
// The scribble inside the overlap removes the front rectangle's face; the face left runs from 0 to 50.
let g = NodeId(run(&mut s, "shaper.scribble", json!({"points": [[65, 70], [85, 90], [65, 110], [85, 130]]}))["id"].as_u64().unwrap());
assert!(node(&s, g).extras().shaper.is_some());
run(&mut s, "select.set", json!({"ids": [g.0]}));
let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Shaped"}))["id"].as_u64().unwrap());
run(&mut s, "appearance.addFill", json!({"ids": [id.0]}));
let row = node(&s, id).appearance.items.len() - 1;
run(&mut s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true}));
let opt = vectorcraft_doc::hit::HitOptions { tol: 1.0, ..Default::default() };
assert_eq!(hit_at(&s, 57.0, opt), None);
offset_row(&mut s, id, row, 10.0);
let r = render(&s);
assert!(near(r.pixel(57, 100), RED), "the face's fill grows by the offset: {:?}", r.pixel(57, 100));
assert!(near(r.pixel(125, 100), WHITE), "the original shapes are not drawn: {:?}", r.pixel(125, 100));
assert_eq!(hit_at(&s, 57.0, opt), Some(id), "a click on the face's grown fill");
assert_eq!(hit_at(&s, 125.0, opt), None, "a click on an original shape");
}
/// A Shaper group in the symbol's art with a stroke of its own below its Contents row: the
/// instance's stroke effect moves what that stroke paints, and a click selects the instance where
/// the canvas draws the moved stroke, not inside the original shapes.
#[test]
fn a_click_on_a_shaper_group_with_a_stroke_below_its_contents_selects_the_instance_where_it_draws() {
let mut s = session();
run(&mut s, "paint.setStroke", json!({"none": true, "ids": []}));
for x in [0, 50] {
run(&mut s, "paint.setFill", json!({"color": "#ff0000", "ids": []}));
run(&mut s, "shape.rectangle", json!({"x": x, "y": 50, "width": 100, "height": 100}));
}
// The scribble removes the front rectangle's face; the group's stroke outlines both rectangles.
let g = NodeId(run(&mut s, "shaper.scribble", json!({"points": [[65, 70], [85, 90], [65, 110], [85, 130]]}))["id"].as_u64().unwrap());
run(&mut s, "appearance.addStroke", json!({"ids": [g.0]}));
let stroke = node(&s, g).appearance.items.len() - 1;
run(&mut s, "paint.setStroke", json!({"ids": [g.0], "item": stroke, "color": "#0000ff"}));
run(&mut s, "stroke.set", json!({"ids": [g.0], "item": stroke, "weight": 4}));
run(&mut s, "appearance.moveItem", json!({"ids": [g.0], "from": "contents", "to": stroke + 1}));
assert_eq!(node(&s, g).appearance.split_contents().0.len(), stroke + 1, "the group's stroke is below its Contents row");
run(&mut s, "select.set", json!({"ids": [g.0]}));
let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Shaped"}))["id"].as_u64().unwrap());
run(&mut s, "appearance.addStroke", json!({"ids": [id.0]}));
let row = node(&s, id).appearance.items.len() - 1;
run(&mut s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true}));
offset_row(&mut s, id, row, 10.0);
let r = render(&s);
let opt = vectorcraft_doc::hit::HitOptions { tol: 1.0, ..Default::default() };
assert!(near(r.pixel(160, 100), BLUE), "the group's stroke moves out by the offset: {:?}", r.pixel(160, 100));
assert!(near(r.pixel(125, 100), WHITE), "the original shapes are not drawn: {:?}", r.pixel(125, 100));
assert_eq!(hit_at(&s, 160.0, opt), Some(id), "a click on the group's moved stroke");
assert_eq!(hit_at(&s, 125.0, opt), None, "a click inside an original shape");
}
/// Of several fills, only the topmost one's effects reach the art, and only while it is visible.
#[test]
fn only_the_topmost_visible_instance_fill_reshapes_the_art() {
+239
View File
@@ -529,6 +529,245 @@ fn saved_documents_keep_inline_graphics() {
assert_eq!(t.cached_bounds, obj(&s, id).cached_bounds);
}
/// `groups` groups of `each` 5 × 5 black rectangles added to the first layer in one edit; returns
/// the ids of each group's rectangles.
fn rect_groups(s: &mut Session, groups: usize, each: usize) -> Vec<Vec<NodeId>> {
s.edit("Rectangles", |d, _| {
let look = vectorcraft_doc::Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0);
let mut ids = vec![];
let mut made = vec![];
for g in 0..groups {
let kids: Vec<Arc<Node>> = (0..each)
.map(|i| {
let r = Rect::new(i as f64 * 6.0, g as f64 * 6.0, i as f64 * 6.0 + 5.0, g as f64 * 6.0 + 5.0);
Arc::new(Node::path(d.alloc_id(), vectorcraft_geom::shapes::rectangle(r), look.clone()))
})
.collect();
ids.push(kids.iter().map(|k| k.id).collect());
made.push(Arc::new(Node::group(d.alloc_id(), kids)));
}
match Arc::make_mut(&mut d.layers[0]).children_mut() {
Some(kids) => kids.extend(made),
None => panic!("the first layer holds art"),
}
Ok(ids)
})
.unwrap()
}
/// Runs `step` on `full`, with every refresh of inline graphics taking the full pass, then on
/// `fast`; checks that both leave the same document and that each refresh returned the same changed
/// texts. Returns whether each of `fast`'s refreshes checked only the changed layer trees.
fn same_as_full_pass(full: &mut Session, fast: &mut Session, step: &dyn Fn(&mut Session)) -> Vec<bool> {
let take = || cmd::inline::PASSES.with(|p| std::mem::take(&mut *p.borrow_mut()));
take();
cmd::inline::FULL_PASS.set(true);
step(full);
cmd::inline::FULL_PASS.set(false);
let want = take();
step(fast);
let got = take();
assert_eq!(*full.doc().unwrap().doc, *fast.doc().unwrap().doc);
let ids = |passes: &[(bool, Vec<NodeId>)]| passes.iter().map(|(_, ids)| ids.clone()).collect::<Vec<_>>();
assert_eq!(ids(&got), ids(&want));
assert!(want.iter().all(|(partial, _)| !partial));
got.iter().map(|(partial, _)| *partial).collect()
}
/// After an edit, inline graphics are checked again only in the layer trees the edit changed, and
/// the document and the changed texts are those of the full pass; a change to a symbol's art, its
/// natural size or anything else a symbol is measured with checks them all.
#[test]
fn refreshing_only_changed_trees_matches_the_full_pass() {
let setup = |s: &mut Session| {
circle_symbol(s, "Tap", 10.0);
circle_symbol(s, "Dot", 6.0);
let groups = rect_groups(s, 20, 10);
let id = text(s, "Tap here");
s.execute("text.insertInline", &json!({"id": id.0, "at": 0, "symbol": "Tap"})).unwrap();
// Type showing Dot inline becomes the opacity mask of a rectangle.
let masked = s.execute("shape.rectangle", &json!({"x": 300, "y": 300, "width": 50, "height": 50})).unwrap()["id"].clone();
let mask = text(s, "Dot");
s.execute("text.insertInline", &json!({"id": mask.0, "at": 0, "symbol": "Dot"})).unwrap();
s.execute("transparency.makeOpacityMask", &json!({"ids": [masked, mask.0]})).unwrap();
(groups, id)
};
let (mut full, mut fast) = (session(), session());
let (groups, id) = setup(&mut full);
assert_eq!(setup(&mut fast), (groups.clone(), id));
let rect = groups[3][4].0;
let len = obj(&fast, id).plain_text().len();
let only_changed = |passes: &[bool]| !passes.is_empty() && passes.iter().all(|&p| p);
let all = |passes: &[bool]| !passes.is_empty() && passes.iter().all(|&p| !p);
// A rectangle beside 19 unchanged groups moves.
let passes = same_as_full_pass(&mut full, &mut fast, &|s| {
s.execute("select.set", &json!({"ids": [rect]})).unwrap();
s.execute("object.move", &json!({"dx": 5, "dy": 0})).unwrap();
});
assert!(only_changed(&passes), "{passes:?}");
// Type with an inline graphic is edited, gets a second one, and loses it again.
let passes = same_as_full_pass(&mut full, &mut fast, &|s| {
s.execute("text.editRange", &json!({"id": id.0, "start": len, "end": len, "insert": "!"})).unwrap();
s.execute("text.insertInline", &json!({"id": id.0, "at": len, "symbol": "Dot"})).unwrap();
s.execute("text.editRange", &json!({"id": id.0, "start": len, "end": len + INLINE_CHAR.len_utf8(), "insert": ""})).unwrap();
});
assert!(only_changed(&passes), "{passes:?}");
// Dot's art is redefined: the type in the opacity mask follows it.
let passes = same_as_full_pass(&mut full, &mut fast, &|s| redefine_as_wide_ellipse(s, "Dot"));
assert!(passes.contains(&false), "{passes:?}");
// Tap's natural size changes, its art unchanged.
let passes = same_as_full_pass(&mut full, &mut fast, &|s| {
s.edit("Size", |d, _| {
d.unknown.insert(vectorcraft_doc::SYMBOL_SIZES.into(), json!({ "Tap": [40.0, 20.0] }));
Ok(())
})
.unwrap();
});
assert!(all(&passes), "{passes:?}");
let (b, want) = (inline_bounds(&obj(&fast, id)), fast.doc().unwrap().doc.symbol_art_bounds("Tap"));
assert!(b.is_some() && b == want, "{b:?} {want:?}");
// 9-slice guides for Tap, its art unchanged.
let passes = same_as_full_pass(&mut full, &mut fast, &|s| {
s.execute("symbol.options", &json!({"name": "Tap", "nineSlice": true})).unwrap();
});
assert!(all(&passes), "{passes:?}");
// Symbol editing mode, entered and left, a rectangle moved inside it.
same_as_full_pass(&mut full, &mut fast, &|s| {
s.execute("symbol.edit", &json!({"name": "Dot"})).unwrap();
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 4, "height": 4})).unwrap();
s.execute("symbol.exitEditing", &json!({})).unwrap();
});
// Undo and redo, then edits after them.
same_as_full_pass(&mut full, &mut fast, &|s| {
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
s.execute("select.set", &json!({"ids": [rect]})).unwrap();
s.execute("object.move", &json!({"dx": 0, "dy": 5})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.redo", &json!({})).unwrap();
s.execute("object.move", &json!({"dx": -5, "dy": 0})).unwrap();
});
// Fonts scanned again, then another move.
same_as_full_pass(&mut full, &mut fast, &|s| {
s.execute("text.rescanFonts", &json!({})).unwrap();
s.execute("select.set", &json!({"ids": [rect]})).unwrap();
s.execute("object.move", &json!({"dx": 1, "dy": 1})).unwrap();
});
}
/// The CPU time this thread has used, from Linux's scheduler statistics; `None` elsewhere.
fn thread_cpu() -> Option<std::time::Duration> {
let stat = std::fs::read_to_string("/proc/thread-self/schedstat").ok()?;
stat.split_whitespace().next()?.parse().ok().map(std::time::Duration::from_nanos)
}
/// The time `f` takes in milliseconds: this thread's CPU time where Linux reports it, otherwise the
/// wall clock.
fn time_ms(f: impl FnOnce()) -> f64 {
let d = match thread_cpu() {
Some(before) => {
f();
thread_cpu().map_or(std::time::Duration::ZERO, |after| after.saturating_sub(before))
}
None => {
let start = std::time::Instant::now();
f();
start.elapsed()
}
};
d.as_secs_f64() * 1000.0
}
/// The median, fastest and slowest of `runs`, as text.
fn spread(runs: &mut [f64]) -> String {
runs.sort_by(f64::total_cmp);
format!("{:>9.3} ({:.3}-{:.3})", runs[runs.len() / 2], runs[0], runs[runs.len() - 1])
}
/// Timings of the refresh of inline graphics after one rectangle moves, with the full pass and with
/// only the changed layer trees checked, in documents of 5,000, 50,000 and 200,000 rectangles in 100
/// groups, with three symbols and one line of type showing one of them inline: the refresh alone,
/// on copies of the same edit, and the whole `object.move` command. 7 runs each, taking turns going
/// first. Ignored by default; it prints the median, fastest and slowest run and sets no bound on
/// them: `cargo test --release -p vectorcraft-engine --lib inline_refresh_perf -- --ignored --nocapture`.
#[test]
#[ignore = "a benchmark: run with --ignored --nocapture"]
fn inline_refresh_perf() {
const RUNS: usize = 7;
eprintln!("inline_refresh_perf: {}", if thread_cpu().is_some() { "thread CPU time" } else { "wall clock" });
eprintln!("inline_refresh_perf: {:>7} {:<14} {:>28} {:>28}", "objects", "case", "full pass ms (min-max)", "changed trees ms (min-max)");
for n in [5_000, 50_000, 200_000] {
let mut s = session();
for name in ["A", "B", "C"] {
circle_symbol(&mut s, name, 10.0);
}
let groups = rect_groups(&mut s, 100, n / 100);
let id = text(&mut s, "Type");
s.execute("text.insertInline", &json!({"id": id.0, "at": 0, "symbol": "B"})).unwrap();
let rect = groups[50][7];
s.execute("select.set", &json!({"ids": [rect.0]})).unwrap();
s.execute("object.move", &json!({"dx": 1, "dy": 0})).unwrap();
// The refresh alone, after the same move made on a copy of the resolved document.
let resolved = s.doc().unwrap().inline_resolved.clone().unwrap();
let before = resolved.0.clone();
// The rectangle and the group and layer above it become new nodes, as a move makes them.
let mut after = (*before).clone();
assert!(after.node_mut(rect).is_some());
// Each run times EACH refreshes, or EACH commands, and gives the time of one.
const EACH: usize = 20;
let (mut full, mut partial) = (vec![], vec![]);
for run in 0..RUNS {
let (mut a, mut b) = (vec![after.clone(); EACH], vec![after.clone(); EACH]);
let mut go_full = || {
cmd::inline::FULL_PASS.set(true);
full.push(
time_ms(|| {
for d in &mut a {
cmd::inline::refresh(Some(&resolved), &before, d);
}
}) / EACH as f64,
);
cmd::inline::FULL_PASS.set(false);
};
let mut go_partial = || {
partial.push(
time_ms(|| {
for d in &mut b {
cmd::inline::refresh(Some(&resolved), &before, d);
}
}) / EACH as f64,
);
};
if run % 2 == 0 {
go_full();
go_partial();
} else {
go_partial();
go_full();
}
assert_eq!(a, b);
}
eprintln!("inline_refresh_perf: {n:>7} {:<14} {:>28} {:>28}", "refresh", spread(&mut full), spread(&mut partial));
// The whole command, moving the rectangle back and forth.
let (mut full, mut partial) = (vec![], vec![]);
for run in 0..2 * RUNS {
let take_full = (run / 2) % 2 == run % 2;
cmd::inline::FULL_PASS.set(take_full);
let ms = time_ms(|| {
for i in 0..EACH {
let dx = if i % 2 == 0 { -1 } else { 1 };
s.execute("object.move", &json!({"dx": dx, "dy": 0})).unwrap();
}
}) / EACH as f64;
cmd::inline::FULL_PASS.set(false);
if take_full { full.push(ms) } else { partial.push(ms) }
}
eprintln!("inline_refresh_perf: {n:>7} {:<14} {:>28} {:>28}", "object.move", spread(&mut full), spread(&mut partial));
cmd::inline::PASSES.with(|p| p.borrow_mut().clear());
}
}
#[test]
fn create_outlines_turns_inline_graphics_into_symbol_instances() {
let mut s = session();
@@ -0,0 +1,522 @@
//! #7832: General › Interpolate Control Points When Moving Anchors (`interpolateControlPoints`).
//! With it on, a Direct Selection drag or an arrow-key nudge of selected anchors re-maps the
//! handles of each segment with one moved end, so the segment keeps its shape relative to its
//! ends. Off (the default), the handles of a moved anchor move with it and the others stay.
use serde_json::json;
use vectorcraft_geom::{Anchor, PathData, Point};
use vectorcraft_tools::{PointerEvent, PointerKind};
use super::history;
use crate::*;
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
s
}
fn interpolate(s: &mut Session, on: bool) {
s.execute("prefs.set", &json!({"key": "interpolateControlPoints", "value": on})).unwrap();
}
fn path_of(s: &Session, id: NodeId) -> PathData {
s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().clone()
}
fn anchor(s: &Session, id: NodeId, ai: usize) -> Anchor {
path_of(s, id).subpaths[0].anchors[ai]
}
fn create(s: &mut Session, anchors: serde_json::Value) -> NodeId {
NodeId(s.execute("path.create", &json!({ "anchors": anchors })).unwrap()["id"].as_u64().unwrap())
}
/// A curve from (100, 100) to (300, 100) whose handles lie on its chord.
fn curve(s: &mut Session) -> NodeId {
create(s, json!([{"x": 100, "y": 100, "out": [150, 100]}, {"x": 300, "y": 100, "in": [250, 100]}]))
}
fn select(s: &mut Session, id: NodeId, anchors: serde_json::Value) {
s.execute("select.anchors", &json!({"id": id.0, "anchors": anchors, "mode": "set"})).unwrap();
}
/// A Direct Selection click on (`x`, `y`), then a drag from there to (`to_x`, `to_y`).
fn drag(s: &mut Session, (x, y): (f64, f64), (to_x, to_y): (f64, f64)) {
let v = ViewInfo { smart_guides: false, ..ViewInfo::default() };
s.select_tool("directSelection", v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Down, x, y), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, x, y), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Down, x, y), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, (x + to_x) / 2.0, (y + to_y) / 2.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, to_x, to_y), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, to_x, to_y), v).unwrap();
}
#[test]
fn the_preference_is_off_by_default_and_the_handles_then_move_rigidly() {
let mut s = session();
assert!(!s.prefs.interpolate_control_points);
let id = curve(&mut s);
select(&mut s, id, json!([[0, 0]]));
s.execute("object.nudge", &json!({"dx": 20, "dy": 8})).unwrap();
let (a, b) = (anchor(&s, id, 0), anchor(&s, id, 1));
assert_eq!(a.p, Point::new(120.0, 108.0));
assert_eq!(a.h_out, Point::new(170.0, 108.0), "the moved anchor's handle moves with it");
assert_eq!(b.h_in, Point::new(250.0, 100.0), "the other end's handle stays");
}
#[test]
fn a_nudge_with_the_preference_on_re_maps_both_handles_of_the_segment() {
let mut s = session();
interpolate(&mut s, true);
let id = curve(&mut s);
select(&mut s, id, json!([[0, 0]]));
let before = history(&s).0;
s.execute("object.nudge", &json!({"dx": 20, "dy": 8})).unwrap();
assert_eq!(history(&s).0, before + 1, "one undo step");
let (a, b) = (anchor(&s, id, 0), anchor(&s, id, 1));
// The chord goes from (200, 0) to (180, -8): a scale by 0.9 and a turn, so the handles a
// quarter of the way from each end stay on the new chord, a quarter of the way along it.
assert_eq!(a.p, Point::new(120.0, 108.0));
assert_eq!(a.h_in, a.p, "a retracted handle stays retracted");
assert_eq!(a.h_out, Point::new(165.0, 106.0));
assert_eq!(b.p, Point::new(300.0, 100.0));
assert_eq!(b.h_in, Point::new(255.0, 102.0));
assert_eq!(b.h_out, b.p);
}
#[test]
fn a_direct_selection_drag_with_the_preference_on_re_maps_the_handles_in_one_undo_step() {
let mut s = session();
interpolate(&mut s, true);
let id = curve(&mut s);
let original = path_of(&s, id);
drag(&mut s, (100.0, 100.0), (120.0, 108.0));
let (a, b) = (anchor(&s, id, 0), anchor(&s, id, 1));
assert_eq!(a.p, Point::new(120.0, 108.0));
assert_eq!(a.h_out, Point::new(165.0, 106.0));
assert_eq!(b.h_in, Point::new(255.0, 102.0));
// One undo step puts the path back as it was before the drag.
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(path_of(&s, id), original);
}
#[test]
fn a_direct_selection_drag_with_the_preference_off_keeps_the_rigid_move() {
let mut s = session();
let id = curve(&mut s);
drag(&mut s, (100.0, 100.0), (120.0, 108.0));
let (a, b) = (anchor(&s, id, 0), anchor(&s, id, 1));
assert_eq!(a.h_out, Point::new(170.0, 108.0));
assert_eq!(b.h_in, Point::new(250.0, 100.0));
}
#[test]
fn a_segment_with_both_ends_moved_moves_rigidly() {
let mut s = session();
interpolate(&mut s, true);
let id = create(
&mut s,
json!([
{"x": 100, "y": 100, "out": [150, 60]},
{"x": 300, "y": 100, "in": [250, 60], "out": [350, 150]},
{"x": 500, "y": 100, "in": [450, 140]},
]),
);
select(&mut s, id, json!([[0, 0], [0, 1]]));
s.execute("object.nudge", &json!({"dx": 10, "dy": 5})).unwrap();
let (a, b, c) = (anchor(&s, id, 0), anchor(&s, id, 1), anchor(&s, id, 2));
assert_eq!((a.p, a.h_out), (Point::new(110.0, 105.0), Point::new(160.0, 65.0)));
assert_eq!((b.p, b.h_in), (Point::new(310.0, 105.0), Point::new(260.0, 65.0)));
// The segment to the unmoved third anchor is re-mapped: its chord goes from (200, 0) to
// (190, -5), a scale by 0.95 with a turn of -0.025 per unit.
close(b.h_out, Point::new(358.75, 151.25));
close(c.h_in, Point::new(453.5, 139.25));
assert_eq!(c.p, Point::new(500.0, 100.0));
}
fn close(p: Point, q: Point) {
assert!((p.x - q.x).abs() < 1e-9 && (p.y - q.y).abs() < 1e-9, "{p:?} is not {q:?}");
}
/// A closed square from (100, 100) to (300, 300) whose handles lie on its sides, a quarter of
/// the way along.
fn square(s: &mut Session) -> NodeId {
let anchors = json!([
{"x": 100, "y": 100, "in": [100, 150], "out": [150, 100]},
{"x": 300, "y": 100, "in": [250, 100], "out": [300, 150]},
{"x": 300, "y": 300, "in": [300, 250], "out": [250, 300]},
{"x": 100, "y": 300, "in": [150, 300], "out": [100, 250]},
]);
NodeId(s.execute("path.create", &json!({ "anchors": anchors, "closed": true })).unwrap()["id"].as_u64().unwrap())
}
#[test]
fn moving_the_first_anchor_of_a_closed_path_re_maps_the_closing_segment_too() {
let mut s = session();
interpolate(&mut s, true);
let id = square(&mut s);
select(&mut s, id, json!([[0, 0]]));
s.execute("object.nudge", &json!({"dx": 0, "dy": -200})).unwrap();
let (a, b, c, d) = (anchor(&s, id, 0), anchor(&s, id, 1), anchor(&s, id, 2), anchor(&s, id, 3));
assert_eq!(a.p, Point::new(100.0, -100.0));
// The segment to the second anchor: its chord goes from (200, 0) to (200, 200).
close(a.h_out, Point::new(150.0, -50.0));
close(b.h_in, Point::new(250.0, 50.0));
// The closing segment from the fourth anchor: its chord goes from (0, -200) to (0, -400).
close(d.h_out, Point::new(100.0, 200.0));
close(a.h_in, Point::new(100.0, 0.0));
// The segment between the third and fourth anchors is not beside the moved anchor.
assert_eq!((c.h_out, d.h_in), (Point::new(250.0, 300.0), Point::new(150.0, 300.0)));
assert_eq!((b.h_out, c.h_in), (Point::new(300.0, 150.0), Point::new(300.0, 250.0)));
}
#[test]
fn moving_the_last_anchor_of_an_open_path_re_maps_only_the_segment_before_it() {
let mut s = session();
interpolate(&mut s, true);
let id = create(
&mut s,
json!([
{"x": 100, "y": 100, "out": [150, 100]},
{"x": 300, "y": 100, "in": [250, 100], "out": [350, 50]},
{"x": 500, "y": 100, "in": [450, 100], "out": [550, 50]},
]),
);
select(&mut s, id, json!([[0, 2]]));
s.execute("object.nudge", &json!({"dx": 0, "dy": 200})).unwrap();
let (a, b, c) = (anchor(&s, id, 0), anchor(&s, id, 1), anchor(&s, id, 2));
assert_eq!(c.p, Point::new(500.0, 300.0));
// The chord from the second (corner) anchor goes from (200, 0) to (200, 200).
close(b.h_out, Point::new(400.0, 100.0));
close(c.h_in, Point::new(450.0, 250.0));
// The last anchor's own outgoing handle leads to no segment and moves with it.
assert_eq!(c.h_out, Point::new(550.0, 250.0));
assert_eq!((a.h_out, b.h_in), (Point::new(150.0, 100.0), Point::new(250.0, 100.0)));
}
#[test]
fn move_and_transform_of_anchors_re_map_the_handles_in_one_undo_step() {
for (cmd, params) in [("object.move", json!({"dx": 20, "dy": 8})), ("object.transform", json!({"matrix": [1, 0, 0, 1, 20, 8], "anchors": true}))]
{
let mut s = session();
interpolate(&mut s, true);
let id = curve(&mut s);
select(&mut s, id, json!([[0, 0]]));
let (before, original) = (history(&s).0, path_of(&s, id));
s.execute(cmd, &params).unwrap();
assert_eq!(history(&s).0, before + 1, "{cmd}: one undo step");
let (a, b) = (anchor(&s, id, 0), anchor(&s, id, 1));
assert_eq!(a.p, Point::new(120.0, 108.0), "{cmd}");
close(a.h_out, Point::new(165.0, 106.0));
close(b.h_in, Point::new(255.0, 102.0));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(path_of(&s, id), original, "{cmd}: undone");
}
}
#[test]
fn set_bounds_and_guide_move_of_anchors_follow_the_preference_and_the_param() {
for (pref, param, re_mapped) in [(false, None, false), (true, None, true), (true, Some(false), false), (false, Some(true), true)] {
for cmd in ["object.setBounds", "guide.move"] {
let mut s = session();
interpolate(&mut s, pref);
let id = curve(&mut s);
select(&mut s, id, json!([[0, 0]]));
let mut params = if cmd == "object.setBounds" {
json!({"x": 120, "y": 108})
} else {
let g = s.execute("guide.add", &json!({"vertical": true, "pos": 50})).unwrap()["index"].as_u64().unwrap();
s.execute("guide.select", &json!({"indexes": [g], "toggle": true})).unwrap();
json!({"dx": 20, "dy": 8})
};
if let Some(on) = param {
params["interpolate"] = json!(on);
}
let (before, original) = (history(&s).0, path_of(&s, id));
s.execute(cmd, &params).unwrap();
assert_eq!(history(&s).0, before + 1, "{cmd}: one undo step");
let (a, b) = (anchor(&s, id, 0), anchor(&s, id, 1));
assert_eq!(a.p, Point::new(120.0, 108.0), "{cmd}");
if re_mapped {
close(a.h_out, Point::new(165.0, 106.0));
close(b.h_in, Point::new(255.0, 102.0));
} else {
assert_eq!((a.h_out, b.h_in), (Point::new(170.0, 108.0), Point::new(250.0, 100.0)), "{cmd}, pref {pref}, param {param:?}");
}
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(path_of(&s, id), original, "{cmd}: undone");
}
}
let mut s = session();
let id = curve(&mut s);
// Both anchors, so that a new width scales them and does not only move them.
select(&mut s, id, json!([[0, 0], [0, 1]]));
s.execute("guide.add", &json!({"vertical": true, "pos": 50})).unwrap();
s.execute("guide.select", &json!({"indexes": [0], "toggle": true})).unwrap();
let original = path_of(&s, id);
for (cmd, params) in [
("object.setBounds", json!({"x": 120, "interpolate": "yes"})),
("object.setBounds", json!({"width": 50, "interpolate": 1})),
("guide.move", json!({"dx": 1, "interpolate": "yes"})),
] {
let e = s.execute(cmd, &params).unwrap_err().to_string();
assert!(e.contains("`interpolate` must be true or false"), "{cmd}: {e}");
}
assert_eq!(path_of(&s, id), original);
// With only guides selected, guide.move rejects the value too and leaves the guide.
s.execute("select.none", &json!({})).unwrap();
s.execute("guide.select", &json!({"indexes": [0]})).unwrap();
let e = s.execute("guide.move", &json!({"dx": 1, "interpolate": "yes"})).unwrap_err().to_string();
assert!(e.contains("`interpolate` must be true or false"), "guide.move: {e}");
assert_eq!(s.doc().unwrap().doc.ruler_guides()[0].pos, 50.0);
}
#[test]
fn the_interpolate_param_overrides_the_preference_and_rejects_other_values() {
for (pref, param, re_mapped) in [(true, false, false), (false, true, true)] {
let mut s = session();
interpolate(&mut s, pref);
let id = curve(&mut s);
select(&mut s, id, json!([[0, 0]]));
s.execute("path.moveAnchors", &json!({"dx": 20, "dy": 8, "interpolate": param})).unwrap();
let b = anchor(&s, id, 1);
assert_eq!(b.h_in != Point::new(250.0, 100.0), re_mapped, "pref {pref}, param {param}: {:?}", b.h_in);
}
let mut s = session();
let id = curve(&mut s);
select(&mut s, id, json!([[0, 0]]));
let original = path_of(&s, id);
for (cmd, params) in [
("path.moveAnchors", json!({"dx": 1, "dy": 0, "interpolate": "yes"})),
("object.nudge", json!({"dx": 1, "dy": 0, "interpolate": "yes"})),
("object.move", json!({"dx": 1, "dy": 0, "interpolate": "yes"})),
("object.transform", json!({"matrix": [1, 0, 0, 1, 1, 0], "anchors": true, "interpolate": 1})),
("object.transformAgain", json!({"interpolate": "yes"})),
] {
let e = s.execute(cmd, &params).unwrap_err().to_string();
assert!(e.contains("`interpolate` must be true or false"), "{cmd}: {e}");
}
assert_eq!(path_of(&s, id), original);
}
#[test]
fn a_replayed_move_re_maps_the_handles_as_it_did_whatever_the_preference_is_then() {
let mut s = session();
interpolate(&mut s, true);
let id = curve(&mut s);
select(&mut s, id, json!([[0, 0]]));
let start = s.journal.len();
s.execute("object.nudge", &json!({"dx": 20, "dy": 8})).unwrap();
let moved = path_of(&s, id);
let (cmd, params) = s.journal.since(start).last().cloned().unwrap();
assert_eq!(params["interpolate"], json!(true), "{cmd}: journaled");
// Undo, turn the preference off and play the journal entry again.
s.execute("edit.undo", &json!({})).unwrap();
interpolate(&mut s, false);
select(&mut s, id, json!([[0, 0]]));
s.replay(&cmd, &params).unwrap();
assert_eq!(path_of(&s, id), moved);
}
#[test]
fn a_saved_step_without_interpolate_moves_the_handles_rigidly_whatever_the_preference() {
// A step recorded before the preference existed has no `interpolate`; with the preference on,
// it still plays as it did when it was recorded.
for cmd in ["path.moveAnchors", "object.nudge", "object.move"] {
let mut s = session();
interpolate(&mut s, true);
let id = curve(&mut s);
select(&mut s, id, json!([[0, 0]]));
s.replay(cmd, &json!({"dx": 1, "dy": 1})).unwrap();
let (a, b) = (anchor(&s, id, 0), anchor(&s, id, 1));
assert_ne!(a.p, Point::new(100.0, 100.0), "{cmd}: the anchor moves");
assert_eq!((a.h_out.x - a.p.x, a.h_out.y - a.p.y), (50.0, 0.0), "{cmd}: the moved anchor's handle moves with it");
assert_eq!(b.h_in, Point::new(250.0, 100.0), "{cmd}: the other end's handle stays");
// Run directly, the same params follow the preference.
s.execute(cmd, &json!({"dx": 1, "dy": 1})).unwrap();
assert_ne!(anchor(&s, id, 1).h_in, Point::new(250.0, 100.0), "{cmd}: executed, the handles are re-mapped");
}
}
#[test]
fn transform_again_keeps_the_setting_its_move_used() {
let mut s = session();
interpolate(&mut s, true);
let id = curve(&mut s);
select(&mut s, id, json!([[0, 0]]));
s.execute("object.nudge", &json!({"dx": 20, "dy": 8})).unwrap();
interpolate(&mut s, false);
s.execute("object.transformAgain", &json!({})).unwrap();
let mut t = session();
interpolate(&mut t, true);
let other = curve(&mut t);
select(&mut t, other, json!([[0, 0]]));
t.execute("object.nudge", &json!({"dx": 20, "dy": 8})).unwrap();
t.execute("object.nudge", &json!({"dx": 20, "dy": 8})).unwrap();
assert_eq!(path_of(&s, id), path_of(&t, other));
}
#[test]
fn a_segment_whose_ends_are_at_the_same_place_moves_rigidly() {
let mut s = session();
interpolate(&mut s, true);
let id = create(&mut s, json!([{"x": 100, "y": 100, "out": [150, 50]}, {"x": 100, "y": 100, "in": [50, 150]}]));
select(&mut s, id, json!([[0, 0]]));
s.execute("object.nudge", &json!({"dx": 10, "dy": 0})).unwrap();
let (a, b) = (anchor(&s, id, 0), anchor(&s, id, 1));
assert_eq!((a.p, a.h_out), (Point::new(110.0, 100.0), Point::new(160.0, 50.0)));
assert_eq!((b.p, b.h_in), (Point::new(100.0, 100.0), Point::new(50.0, 150.0)));
}
#[test]
fn a_move_onto_the_other_end_moves_the_handles_rigidly() {
let mut s = session();
interpolate(&mut s, true);
let id = curve(&mut s);
select(&mut s, id, json!([[0, 0]]));
s.execute("object.nudge", &json!({"dx": 200, "dy": 0})).unwrap();
let (a, b) = (anchor(&s, id, 0), anchor(&s, id, 1));
assert_eq!((a.p, a.h_out), (Point::new(300.0, 100.0), Point::new(350.0, 100.0)));
assert_eq!(b.h_in, Point::new(250.0, 100.0));
}
#[test]
fn a_nudge_of_zero_with_the_preference_on_records_no_undo_step() {
let mut s = session();
interpolate(&mut s, true);
let id = curve(&mut s);
select(&mut s, id, json!([[0, 0]]));
let (before, original) = (history(&s), path_of(&s, id));
s.execute("object.nudge", &json!({"dx": 0, "dy": 0})).unwrap();
assert_eq!(history(&s), before);
assert_eq!(path_of(&s, id), original);
}
#[test]
fn a_smooth_anchor_keeps_its_handles_in_line() {
let mut s = session();
interpolate(&mut s, true);
let id = create(
&mut s,
json!([
{"x": 100, "y": 100, "out": [150, 100]},
{"x": 300, "y": 100, "in": [250, 100], "out": [350, 100], "smooth": true},
{"x": 500, "y": 100, "in": [450, 100]},
]),
);
select(&mut s, id, json!([[0, 0]]));
s.execute("object.nudge", &json!({"dx": 0, "dy": -100})).unwrap();
let b = anchor(&s, id, 1);
assert_eq!(b.p, Point::new(300.0, 100.0));
// The segment to the third anchor did not move, so its handle stays where it was.
assert_eq!(b.h_out, Point::new(350.0, 100.0));
// The incoming handle grows with the chord from the moved anchor (from 200 to 100√5) and
// turns back in line with the outgoing one.
assert_eq!(b.h_in.y, 100.0, "in line: {:?}", b.h_in);
assert!((300.0 - b.h_in.x - 25.0 * 5f64.sqrt()).abs() < 1e-9, "{:?}", b.h_in);
}
#[test]
fn a_moved_smooth_anchor_keeps_a_retracted_handle_exactly_retracted() {
let mut s = session();
interpolate(&mut s, true);
let id = create(
&mut s,
json!([
{"x": 0, "y": 100, "out": [50, 100]},
{"x": 200, "y": 100, "in": [200, 100], "out": [250, 150], "smooth": true},
{"x": 400, "y": 100, "in": [350, 100]},
]),
);
select(&mut s, id, json!([[0, 1]]));
s.execute("object.nudge", &json!({"dx": 20, "dy": 8.1})).unwrap();
let b = anchor(&s, id, 1);
assert_eq!(b.p, Point::new(220.0, 108.1));
// Re-mapping the retracted handle by its segment's map would leave it a rounding error away
// from the anchor, and lining the handles up would then turn the outgoing one by that error.
assert_eq!(b.h_in, b.p, "the retracted handle stays retracted");
// The chord to the third anchor goes from (200, 0) to (180, -8.1).
close(b.h_out, Point::new(267.025, 151.075));
}
#[test]
fn transform_again_repeats_a_move_with_the_handles_re_mapped() {
let twice = |again: bool| {
let mut s = session();
interpolate(&mut s, true);
let id = curve(&mut s);
select(&mut s, id, json!([[0, 0]]));
s.execute("object.nudge", &json!({"dx": 20, "dy": 8})).unwrap();
if again {
s.execute("object.transformAgain", &json!({})).unwrap();
} else {
s.execute("object.nudge", &json!({"dx": 20, "dy": 8})).unwrap();
}
path_of(&s, id)
};
let (repeated, nudged) = (twice(true), twice(false));
assert_eq!(repeated.subpaths[0].anchors[0].p, Point::new(140.0, 116.0));
assert_eq!(repeated, nudged);
}
#[test]
fn a_transform_that_scales_by_a_hair_still_scales_the_anchors() {
let mut s = session();
interpolate(&mut s, true);
let id = curve(&mut s);
select(&mut s, id, json!([[0, 0]]));
let k = 1.000_000_000_5;
s.execute("object.transform", &json!({"matrix": [k, 0, 0, 1, 0, 0], "anchors": true})).unwrap();
let a = anchor(&s, id, 0);
assert_eq!(a.p, Point::new(100.0 * k, 100.0));
assert_eq!(a.h_out, Point::new(150.0 * k, 100.0));
}
#[test]
fn a_smooth_anchor_whose_re_mapped_handles_point_the_same_way_moves_them_with_it() {
let mut s = session();
interpolate(&mut s, true);
let id = create(
&mut s,
json!([
{"x": 100, "y": 100, "out": [150, 100]},
{"x": 300, "y": 100, "in": [250, 100], "out": [350, 100], "smooth": true},
{"x": 500, "y": 100, "in": [450, 100]},
]),
);
select(&mut s, id, json!([[0, 1]]));
s.execute("object.nudge", &json!({"dx": 300, "dy": 0})).unwrap();
// Both chords re-map their handle to the left of the anchor, which has no direction between
// them: both handles move with the anchor, as with the preference off.
let b = anchor(&s, id, 1);
assert_eq!(b.p, Point::new(600.0, 100.0));
assert_eq!(b.h_out, Point::new(650.0, 100.0));
assert_eq!(b.h_in, Point::new(550.0, 100.0));
}
#[test]
fn a_smooth_anchor_between_two_re_mapped_segments_keeps_its_handles_in_line() {
let mut s = session();
interpolate(&mut s, true);
let id = create(
&mut s,
json!([
{"x": 100, "y": 100, "out": [150, 100]},
{"x": 300, "y": 100, "in": [250, 100], "out": [350, 100], "smooth": true},
{"x": 500, "y": 100, "in": [450, 100]},
]),
);
select(&mut s, id, json!([[0, 1]]));
s.execute("object.nudge", &json!({"dx": 0, "dy": -100})).unwrap();
let b = anchor(&s, id, 1);
let (v_in, v_out) = (b.h_in - b.p, b.h_out - b.p);
assert_eq!(b.p, Point::new(300.0, 0.0));
// The two chords turn by the same angle in opposite directions, so the handles point along
// the mean of the two: across, at the length each chord gives them.
assert!(v_in.cross(v_out).abs() < 1e-9, "the handles stay in line: {:?} {:?}", b.h_in, b.h_out);
assert!(v_in.dot(v_out) < 0.0, "on opposite sides of the anchor");
assert!(v_out.y.abs() < 1e-9 && v_out.x > 0.0, "{:?}", b.h_out);
assert!((v_out.hypot() - 25.0 * 5f64.sqrt()).abs() < 1e-9 && (v_in.hypot() - 25.0 * 5f64.sqrt()).abs() < 1e-9);
}
+230
View File
@@ -213,6 +213,117 @@ fn the_selection_column_selects_a_rows_art_and_shift_adds_or_removes_it() {
assert_eq!(ids_sel(&run(&mut s, "layer.target", json!({"id": layer.0}))), vec![c, a, g]);
}
/// The rows of [`column_start`]: [`tree`]'s, plus a rectangle `o` on a second layer and an empty
/// third layer `e`.
#[derive(Clone, Copy)]
struct Column {
layer: NodeId,
sub: NodeId,
a: NodeId,
g: NodeId,
b: NodeId,
c: NodeId,
o: NodeId,
e: NodeId,
}
fn column_start() -> (Session, Column) {
let mut s = session();
let (layer, sub, a, g, b, c) = tree(&mut s);
run(&mut s, "layer.setCurrent", json!({"id": layer.0}));
let other = id(&run(&mut s, "layer.new", json!({})));
let o = rect(&mut s, 200.0);
let e = id(&run(&mut s, "layer.new", json!({})));
run(&mut s, "select.none", json!({}));
let top: Vec<NodeId> = s.doc().unwrap().doc.layers.iter().map(|l| l.id).collect();
assert!(top.contains(&other) && top.contains(&e) && parent(&s, o) == Some(other), "{top:?}");
(s, Column { layer, sub, a, g, b, c, o, e })
}
type Prep = dyn Fn(&mut Session, Column);
/// A Shift-click in the selection column of `row` (whose art is `art`) after `prep` gives the
/// same selection, reply, current layer, highlighted rows and revision as removing or adding each
/// id of `art` one at a time. Returns the session the click ran in.
fn shift_column_matches_each_id(prep: &Prep, row: impl Fn(Column) -> NodeId, art: impl Fn(Column) -> Vec<NodeId>) -> (Session, Column) {
let (mut new, t) = column_start();
prep(&mut new, t);
let row = row(t);
let before = new.doc().unwrap().selection.clone();
let reply = run(&mut new, "layer.selectAll", json!({"id": row.0, "add": true}));
let (mut old, t) = column_start();
prep(&mut old, t);
let ids = art(t);
let st = old.doc().unwrap();
let all_selected = !ids.is_empty() && ids.iter().all(|i| st.selection.contains(*i));
let rows = st.layer_rows.clone();
old.select(|_, sel| {
for i in &ids {
if all_selected { sel.remove(*i) } else { sel.add(*i) }
}
})
.unwrap();
old.doc_mut().unwrap().layer_rows = rows;
let (n, o) = (new.doc().unwrap(), old.doc().unwrap());
assert_eq!(n.selection, o.selection, "row {row:?} from {before:?}");
assert_eq!(ids_sel(&reply), o.selection.objects);
assert_eq!(n.active_layer, o.active_layer);
assert_eq!(n.highlighted_rows(), o.highlighted_rows());
assert_eq!(n.revision, o.revision);
assert_eq!(undos(&new), undos(&old));
(new, t)
}
#[test]
fn a_shift_click_in_the_selection_column_matches_adding_or_removing_each_id() {
// `o` outside the layer is selected first and is the key object and the target; `a` is
// selected by one anchor, which is the key anchor.
let partly: &Prep = &|s, t| {
run(s, "layer.setCurrent", json!({"id": t.sub.0}));
let sel = &mut s.doc_mut().unwrap().selection;
sel.objects = vec![t.o, t.a];
sel.anchors.insert(t.a, [(0, 1)].into());
sel.key = Some(t.o);
sel.key_anchor = Some((t.a, (0, 1)));
sel.target = Some(t.o);
};
let layer_art = |t: Column| vec![t.c, t.a, t.g];
// Some of the layer's art is selected: the rest is added after what was selected.
let (s, t) = shift_column_matches_each_id(partly, |t| t.layer, layer_art);
let sel = &s.doc().unwrap().selection;
assert_eq!(sel.objects, vec![t.o, t.a, t.c, t.g]);
assert_eq!(sel.anchors.len(), 1, "the picked anchor stays picked");
assert!(sel.target.is_none());
// All of it is selected, `a` as the key object: it is removed, with its anchors, key and key
// anchor.
let all: &Prep = &|s, t| {
partly(s, t);
let sel = &mut s.doc_mut().unwrap().selection;
sel.objects.extend([t.c, t.g]);
sel.key = Some(t.a);
};
let (s, t) = shift_column_matches_each_id(all, |t| t.layer, layer_art);
let sel = &s.doc().unwrap().selection;
assert_eq!(sel.objects, vec![t.o]);
assert!(sel.anchors.is_empty() && sel.key.is_none() && sel.key_anchor.is_none());
// An object row, a group row and an empty layer's row.
shift_column_matches_each_id(all, |t| t.c, |t| vec![t.c]);
shift_column_matches_each_id(partly, |t| t.g, |t| vec![t.g]);
shift_column_matches_each_id(partly, |t| t.e, |_| vec![]);
// A locked sublayer's row, and rows outside and inside the isolated group.
let locked: &Prep = &|s, t| {
partly(s, t);
run(s, "layer.setProps", json!({"id": t.sub.0, "locked": true}));
};
shift_column_matches_each_id(locked, |t| t.sub, |_| vec![]);
let isolated: &Prep = &|s, t| {
partly(s, t);
s.doc_mut().unwrap().isolation = Some(t.g);
};
shift_column_matches_each_id(isolated, |t| t.c, |_| vec![]);
shift_column_matches_each_id(isolated, |t| t.b, |t| vec![t.b]);
}
fn ids_sel(v: &Value) -> Vec<NodeId> {
v["selected"].as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect()
}
@@ -481,6 +592,54 @@ fn new_layers_go_below_the_current_one_and_sublayers_under_the_contents() {
assert_eq!(children(&s, layer), vec![front, under, back]);
}
/// In Draw Behind a new layer goes directly below the current layer, at its level, in one undo
/// step; `top` and `below` keep their meaning, Draw Inside and Draw Normal keep it above, and new
/// sublayers are not affected.
#[test]
fn new_layers_go_below_the_current_one_in_draw_behind() {
let mut s = session();
let (layer, sub, a, g, _, c) = tree(&mut s);
run(&mut s, "view.drawMode", json!({"mode": "behind"}));
run(&mut s, "layer.setCurrent", json!({"id": sub.0}));
let before = undos(&s);
let n = id(&run(&mut s, "layer.new", json!({})));
assert_eq!(children(&s, layer), vec![c, n, sub], "a sublayer directly below the current sublayer");
assert_eq!(undos(&s), before + 1);
assert_eq!(s.doc().unwrap().highlighted_rows(), vec![n]);
assert_eq!(s.doc().unwrap().current_layer(), Some(n));
run(&mut s, "edit.undo", json!({}));
assert_eq!(children(&s, layer), vec![c, sub]);
// The Create New Layer button sends `top: false` for a plain click: still below.
run(&mut s, "layer.setCurrent", json!({"id": sub.0}));
let n = id(&run(&mut s, "layer.new", json!({"top": false})));
assert_eq!(children(&s, layer), vec![c, n, sub]);
run(&mut s, "edit.undo", json!({}));
// At the top level, and with options.
run(&mut s, "layer.setCurrent", json!({"id": layer.0}));
let back = id(&run(&mut s, "layer.new", json!({"name": "Back", "locked": true})));
let order = |s: &Session| s.doc().unwrap().doc.layers.iter().map(|l| l.id).collect::<Vec<_>>();
assert_eq!(order(&s), vec![back, layer]);
assert!(node(&s, back).locked);
// `top` and `below` win over the drawing mode.
let top = id(&run(&mut s, "layer.new", json!({"top": true})));
assert_eq!(order(&s), vec![back, layer, top]);
let below = id(&run(&mut s, "layer.new", json!({"below": true})));
assert_eq!(order(&s), vec![back, layer, below, top]);
assert!(s.execute("layer.new", &json!({"top": true, "below": true})).is_err());
// New sublayers still go on top of the parent's contents.
let inner = id(&run(&mut s, "layer.newSublayer", json!({"parent": sub.0})));
assert_eq!(children(&s, sub), vec![a, g, inner]);
// Draw Inside and Draw Normal put it above.
run(&mut s, "select.set", json!({"ids": [c.0]}));
for mode in ["inside", "normal"] {
run(&mut s, "view.drawMode", json!({"mode": mode}));
assert_eq!(s.draw_mode, if mode == "inside" { DrawMode::Inside } else { DrawMode::Normal });
run(&mut s, "layer.setCurrent", json!({"id": back.0}));
let n = id(&run(&mut s, "layer.new", json!({})));
assert_eq!(s.doc().unwrap().doc.layers[1].id, n, "{mode}");
}
}
#[test]
fn rows_move_above_below_and_into_layers_and_groups() {
let mut s = session();
@@ -643,6 +802,45 @@ fn alt_drag_copies_rows_and_the_selected_art_moves_between_layers() {
assert_eq!(s.doc().unwrap().selection.objects, vec![a, g], "it stays selected");
}
/// #8237: a copy may go above or below a row it copies, so a lone layer, the top layer dragged up
/// and the bottom one dragged down can be copied. A move there, or a copy inside the row, is still
/// refused.
#[test]
fn a_copy_goes_above_or_below_a_row_it_copies() {
let mut s = session();
let layers = |s: &Session| s.doc().unwrap().doc.layers.iter().map(|l| l.id).collect::<Vec<_>>();
let [only] = layers(&s)[..] else { panic!("one layer") };
for place in ["above", "below", "inside"] {
assert!(s.execute("layer.move", &json!({"ids": [only.0], "target": only.0, "place": place})).is_err(), "a move {place} itself");
}
assert!(s.execute("layer.move", &json!({"ids": [only.0], "target": only.0, "place": "inside", "copy": true})).is_err());
assert_eq!(layers(&s), vec![only], "nothing changed");
let above = ids(&run(&mut s, "layer.move", json!({"ids": [only.0], "target": only.0, "place": "above", "copy": true})));
assert_eq!(layers(&s), vec![only, above[0]], "the copy above the original");
let below = ids(&run(&mut s, "layer.move", json!({"ids": [only.0], "target": only.0, "place": "below", "copy": true})));
assert_eq!(layers(&s), vec![below[0], only, above[0]], "and one below it");
run(&mut s, "edit.undo", json!({}));
assert_eq!(layers(&s), vec![only, above[0]], "each copy is one undo step");
}
/// #8237 review: rows that hold an object can't sit beside a top-level layer, so copied beside a
/// top-level layer among them they would go inside it: a copy of that layer inside itself. Refused,
/// and nothing changes.
#[test]
fn a_copy_with_objects_beside_a_copied_top_level_layer_is_refused() {
let mut s = session();
let bottom = s.doc().unwrap().doc.layers[0].id;
let other = id(&run(&mut s, "layer.new", json!({})));
let r = rect(&mut s, 0.0);
assert_eq!(s.doc().unwrap().doc.parent_of(r), Some(other), "the rectangle is in the other layer");
let count = s.doc().unwrap().doc.node_count();
for place in ["above", "below"] {
let p = json!({"ids": [bottom.0, r.0], "target": bottom.0, "place": place, "copy": true});
assert!(s.execute("layer.move", &p).is_err(), "{place}: the layer's copy would go inside it");
}
assert_eq!(s.doc().unwrap().doc.node_count(), count, "nothing copied");
}
/// The selected art in rows dragged into a hidden layer or group is deselected, the key object
/// included. Undo puts the rows back and selects the art again.
#[test]
@@ -904,6 +1102,38 @@ fn locate_object_highlights_its_row() {
assert!(s.execute("layer.locate", &json!({})).is_err());
}
/// Locate Layer (`layersOnly`, sent while Show Layers Only is on) highlights the innermost layer
/// or sublayer holding the object, through any groups; a layer locates itself.
#[test]
fn locate_layer_highlights_the_layer_holding_the_object() {
let mut s = session();
let (layer, sub, _, g, b, c) = tree(&mut s);
run(&mut s, "select.set", json!({"ids": [b.0]}));
let r = run(&mut s, "layer.locate", json!({"layersOnly": true}));
assert_eq!(r, json!({"id": sub.0, "objectId": b.0, "ancestry": [layer.0, sub.0]}), "the group's sublayer");
assert_eq!(s.doc().unwrap().highlighted_rows(), vec![sub]);
assert_eq!(s.doc().unwrap().locate_reveal, Some(sub), "the Layers panel reveals the located row");
s.doc_mut().unwrap().locate_reveal = None;
let undo = s.doc().unwrap().history.undo.len();
run(&mut s, "layer.locate", json!({"layersOnly": true}));
assert_eq!(s.doc().unwrap().locate_reveal, Some(sub), "again for a row already highlighted");
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step");
assert_eq!(run(&mut s, "layer.locate", json!({"id": c.0, "layersOnly": true}))["id"], layer.0, "art directly in a layer");
assert_eq!(s.doc().unwrap().highlighted_rows(), vec![layer]);
let r = run(&mut s, "layer.locate", json!({"id": sub.0, "layersOnly": true}));
assert_eq!((r["id"].clone(), r["objectId"].clone()), (json!(sub.0), json!(sub.0)), "a sublayer locates itself");
// Off, the object's own row is highlighted, as before.
assert_eq!(run(&mut s, "layer.locate", json!({"id": g.0, "layersOnly": false})), json!({"id": g.0, "ancestry": [layer.0, sub.0, g.0]}));
// Bad input changes nothing.
for p in [json!({"id": b.0, "layersOnly": "yes"}), json!({"id": 999_999, "layersOnly": true})] {
assert!(s.execute("layer.locate", &p).is_err(), "{p}");
assert_eq!(s.doc().unwrap().highlighted_rows(), vec![g], "{p}");
assert_eq!(s.doc().unwrap().locate_reveal, Some(g), "{p}");
}
run(&mut s, "select.none", json!({}));
assert!(s.execute("layer.locate", &json!({"layersOnly": true})).is_err(), "nothing selected");
}
#[test]
fn the_clipping_mask_button_acts_on_the_highlighted_group() {
let mut s = session();
-28
View File
@@ -2542,34 +2542,6 @@ fn confined_screens_rows_check_the_artboard_each_file_holds() {
}
}
/// A confined caller's single-file PDF with Preserve Editing of several assets carries the first
/// asset's document alone, so only that document is checked: an image linked outside the read roots in a later asset does
/// not refuse it, and one in the first asset does.
#[test]
fn confined_single_file_pdf_checks_the_document_it_carries() {
use crate::file_access::{AutomationRoots, confine};
let away = Folder::new("single-pdf-away");
let home = Folder::new("single-pdf-home");
let photo = away.file("photo.png");
write(&photo, &png(60, 30, RED));
let mut s = session();
let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap();
let rect: vectorcraft_doc::NodeId = serde_json::from_value(r["id"].clone()).unwrap();
let placed = place(&mut s, &photo);
let mut assets = vec![];
for id in [rect, placed] {
assets.push(s.execute("assets.add", &json!({"ids": [id.0]})).unwrap()["assets"][0].as_u64().unwrap());
}
let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap();
let p = |ids: &[u64], folder: &str| json!({"assets": ids, "folder": home.file(folder), "pdfs": "single", "formats": [{"format": "pdf", "preserveEditing": true}]});
let r = confine(roots.as_ref(), || s.execute("assets.export", &p(&assets, "first-plain"))).unwrap_or_else(|e| panic!("{e}"));
assert_eq!(r["files"].as_array().map(Vec::len), Some(1), "{r}");
let reversed = [assets[1], assets[0]];
let e = confine(roots.as_ref(), || s.execute("assets.export", &p(&reversed, "first-linked"))).expect_err("first asset links outside").to_string();
assert!(e.contains("a linked image file is outside the read roots"), "{e}");
}
/// A confined caller's native outputs (a native file or template, an EPS or `.ai` file, a PDF with
/// Preserve Editing, a package's document) carry the document without the Export for Screens
/// folder when it is outside the read roots, with the other export settings and the art; the open
+8 -3
View File
@@ -1629,9 +1629,9 @@ fn cmyk_mesh(create: Value) -> (Session, NodeId) {
(s, a)
}
/// The fill colours `document.exportPdf {standard: pdfX4}` writes (`… scn` operands, and the
/// corner colours of its gradient meshes, which are patch shadings, as PDF import reads them
/// back), and its warnings.
/// The fill colours `document.exportPdf {standard: pdfX4}` writes (`… scn` and DeviceCMYK
/// `c m y k k` operands, and the corner colours of its gradient meshes, which are patch shadings,
/// as PDF import reads them back), and its warnings.
fn pdf_fill_colours(s: &mut Session) -> (Vec<Vec<f32>>, Vec<String>) {
let v = s.execute("document.exportPdf", &json!({"standard": "pdfX4", "compression": {"compressText": false}})).unwrap();
let bytes = vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap();
@@ -1646,6 +1646,11 @@ fn pdf_fill_colours(s: &mut Session) -> (Vec<Vec<f32>>, Vec<String>) {
if !nums.is_empty() {
out.push(nums.into_iter().rev().collect());
}
} else if *w == "k" {
let nums: Vec<f32> = words[..i].iter().rev().take(4).map_while(|x| x.parse().ok()).collect();
if nums.len() == 4 {
out.push(nums.into_iter().rev().collect());
}
}
}
}
+162
View File
@@ -392,6 +392,67 @@ fn an_ellipse_takes_pie_angles_and_inverts() {
assert!(s.execute("object.setLiveShape", &json!({"pieStart": "half"})).is_err());
}
/// Constrain Pie Angle (`constrainPie`): a new Pie Start or End Angle moves the other angle by as
/// much, so each selected ellipse keeps its own span, across 0° too; a whole ellipse stays whole;
/// after Invert Pie the inverted span is kept; one undo step for all of them; the angle each
/// already has records nothing; and `constrainPie` with both angles, with neither, with Invert Pie
/// or as text is an error that changes nothing.
#[test]
fn constrain_pie_keeps_each_ellipses_span() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap();
let id = |v: Value| NodeId(v["id"].as_u64().unwrap());
let [a, b, c] = [0, 100, 200].map(|y| id(s.execute("shape.ellipse", &json!({"x": 0, "y": y, "width": 200, "height": 80})).unwrap()));
run(&mut s, json!({"ids": [a.0], "pieStart": 300, "pieEnd": 60}));
run(&mut s, json!({"ids": [b.0], "pieStart": 0, "pieEnd": 90}));
let pies = |s: &Session| {
[a, b, c].map(|i| match &s.doc().unwrap().doc.node(i).unwrap().kind {
NodeKind::Path { live: Some(l), .. } => match &**l {
LiveShape::Ellipse { pie, .. } => *pie,
k => panic!("{k:?}"),
},
k => panic!("{k:?}"),
})
};
let near = |p: (f64, f64), q: (f64, f64)| (p.0 - q.0).abs() < 1e-9 && (p.1 - q.1).abs() < 1e-9;
let undo = |s: &Session| s.doc().unwrap().history.undo.len();
let n = undo(&s);
// 300° to 60° spans 120°, through 0°; 0° to 90° spans 90°; the third ellipse is whole.
run(&mut s, json!({"ids": [a.0, b.0, c.0], "pieStart": 350, "constrainPie": true}));
let [pa, pb, pc] = pies(&s);
assert!(near(pa, (350.0, 110.0)) && near(pb, (350.0, 80.0)), "{pa:?} {pb:?}");
assert!(near(pc, (350.0, 350.0)), "{pc:?}");
assert_eq!(s.doc().unwrap().doc.node(c).unwrap().path_data().unwrap().anchor_count(), 4, "the whole ellipse stays whole");
assert_eq!(undo(&s), n + 1, "one undo step");
run(&mut s, json!({"ids": [a.0, b.0], "pieEnd": 20, "constrainPie": true}));
let [pa, pb, _] = pies(&s);
assert!(near(pa, (260.0, 20.0)) && near(pb, (290.0, 20.0)), "{pa:?} {pb:?}");
let n = undo(&s);
run(&mut s, json!({"ids": [a.0, b.0], "pieEnd": 380, "constrainPie": true}));
assert_eq!(undo(&s), n, "the end each already has: no undo step");
s.execute("edit.undo", &json!({})).unwrap();
let [pa, pb, _] = pies(&s);
assert!(near(pa, (350.0, 110.0)) && near(pb, (350.0, 80.0)), "{pa:?} {pb:?}");
// Inverted, 80° to 350° spans 270°, and a linked edit keeps that.
run(&mut s, json!({"ids": [b.0], "invertPie": true}));
run(&mut s, json!({"ids": [b.0], "pieStart": 0, "constrainPie": true}));
assert!(near(pies(&s)[1], (0.0, 270.0)), "{:?}", pies(&s)[1]);
let before = (undo(&s), pies(&s));
for (p, want) in [
(json!({"ids": [b.0], "pieStart": 10, "pieEnd": 20, "constrainPie": true}), "needs one of"),
(json!({"ids": [b.0], "constrainPie": true}), "needs one of"),
(json!({"ids": [b.0], "pieStart": 10, "constrainPie": true, "invertPie": true}), "needs one of"),
(json!({"ids": [b.0], "pieStart": 10, "constrainPie": "yes"}), "`constrainPie` must be true or false"),
] {
let r = s.execute("object.setLiveShape", &p);
assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg.contains(want)), "{p}: {r:?}");
assert_eq!((undo(&s), pies(&s)), before, "{p}");
}
// Off, each angle is set on its own, as before.
run(&mut s, json!({"ids": [b.0], "pieStart": 90, "constrainPie": false}));
assert!(near(pies(&s)[1], (90.0, 270.0)), "{:?}", pies(&s)[1]);
}
/// Invert Pie and Make Sides Equal given as text or as another value that is not true or false are
/// an error naming the key: the ellipse's pie, the polygon and the undo history stay as they were.
/// True makes the change, and false and null leave the shape as it is.
@@ -524,6 +585,107 @@ fn a_polygon_takes_its_angle_radius_side_length_and_equal_sides() {
}
}
/// A live line's Line Properties: Line Length keeps its first end in place, Line Angle (degrees
/// counterclockwise, any finite value brought into 0 to 360) turns it about its midpoint, the
/// length applies before the angle, every selected line takes them in one undo step, and a value
/// that changes nothing records none.
#[test]
fn a_line_takes_its_length_and_angle() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
let line = |s: &mut Session, a: (f64, f64), b: (f64, f64)| {
NodeId(s.execute("shape.line", &json!({"x1": a.0, "y1": a.1, "x2": b.0, "y2": b.1})).unwrap()["id"].as_u64().unwrap())
};
let id = line(&mut s, (100.0, 100.0), (200.0, 100.0));
let ends = |s: &Session, id: NodeId| match &s.doc().unwrap().doc.node(id).unwrap().kind {
NodeKind::Path { live: Some(l), path, .. } => {
let LiveShape::Line { a, b } = **l else { panic!("{l:?}") };
assert_eq!(*path, l.to_path(), "the path follows the line");
(a.x, a.y, b.x, b.y)
}
k => panic!("{k:?}"),
};
let near = |got: (f64, f64, f64, f64), want: (f64, f64, f64, f64)| {
assert!([got.0 - want.0, got.1 - want.1, got.2 - want.2, got.3 - want.3].iter().all(|d| d.abs() < 1e-9), "{got:?} ≠ {want:?}")
};
let steps = |s: &Session| s.doc().unwrap().history.undo.len();
run(&mut s, json!({"lineLength": 50}));
near(ends(&s, id), (100.0, 100.0, 150.0, 100.0));
// 90° points up the page.
run(&mut s, json!({"lineAngle": 90}));
near(ends(&s, id), (125.0, 125.0, 125.0, 75.0));
let n = steps(&s);
for same in [json!({"lineAngle": 450}), json!({"lineAngle": -270}), json!({"lineLength": 50}), json!({"lineLength": 50, "lineAngle": 90})] {
run(&mut s, same.clone());
assert_eq!(steps(&s), n, "{same} records no undo step");
}
near(ends(&s, id), (125.0, 125.0, 125.0, 75.0));
run(&mut s, json!({"lineLength": 20, "lineAngle": 0}));
near(ends(&s, id), (115.0, 115.0, 135.0, 115.0));
assert_eq!(steps(&s), n + 1, "both in one step");
run(&mut s, json!({"lineAngle": 180}));
near(ends(&s, id), (135.0, 115.0, 115.0, 115.0));
run(&mut s, json!({"lineAngle": -90}));
near(ends(&s, id), (125.0, 105.0, 125.0, 125.0));
let LiveShape::Line { .. } = s.doc().unwrap().doc.node(id).unwrap().live_shape().unwrap() else { panic!("still live") };
assert_eq!(s.doc().unwrap().doc.node(id).unwrap().live_shape().unwrap().line_angle(), Some(270.0));
// Several lines: each keeps its own first end, in one undo step.
let other = line(&mut s, (0.0, 0.0), (0.0, 40.0));
let n = steps(&s);
run(&mut s, json!({"ids": [id.0, other.0], "lineLength": 10}));
near(ends(&s, id), (125.0, 105.0, 125.0, 115.0));
near(ends(&s, other), (0.0, 0.0, 0.0, 10.0));
assert_eq!(steps(&s), n + 1);
s.execute("edit.undo", &json!({})).unwrap();
near(ends(&s, id), (125.0, 105.0, 125.0, 125.0));
near(ends(&s, other), (0.0, 0.0, 0.0, 40.0));
// Bad values, and a line that would reach past the coordinate limit, change neither line.
let far = line(&mut s, (3_900_000.0, 0.0), (3_900_100.0, 0.0));
let n = steps(&s);
for bad in [
json!({"ids": [id.0], "lineLength": 0}),
json!({"ids": [id.0], "lineLength": -3}),
json!({"ids": [id.0], "lineLength": "long"}),
json!({"ids": [id.0], "lineAngle": "up"}),
json!({"ids": [id.0], "lineLength": 1e300}),
json!({"ids": [id.0, far.0], "lineLength": 200_000}),
] {
assert!(s.execute("object.setLiveShape", &bad).is_err(), "{bad}");
assert_eq!(steps(&s), n, "{bad}");
}
near(ends(&s, id), (125.0, 105.0, 125.0, 125.0));
near(ends(&s, far), (3_900_000.0, 0.0, 3_900_100.0, 0.0));
// A length past the coordinate limit is fine while both ends stay inside it.
let wide = line(&mut s, (-3_500_000.0, 0.0), (3_500_000.0, 0.0));
run(&mut s, json!({"ids": [wide.0], "lineLength": 6_000_000}));
near(ends(&s, wide), (-3_500_000.0, 0.0, 2_500_000.0, 0.0));
// A line whose ends meet reads 0°: an angle leaves it as it is, and a length points it right.
let dot = line(&mut s, (10.0, 10.0), (10.0, 10.0));
assert_eq!(s.doc().unwrap().doc.node(dot).unwrap().live_shape().unwrap().line_angle(), Some(0.0));
let n = steps(&s);
run(&mut s, json!({"lineAngle": 45}));
assert_eq!(steps(&s), n);
run(&mut s, json!({"lineLength": 30}));
near(ends(&s, dot), (10.0, 10.0, 40.0, 10.0));
// A very short length is applied.
let speck = line(&mut s, (20.0, 20.0), (20.0, 20.0));
let n = steps(&s);
run(&mut s, json!({"ids": [speck.0], "lineLength": 1e-12}));
assert_eq!(steps(&s), n + 1, "a length of 1e-12 pt is a change");
assert!(ends(&s, speck).2 > 20.0, "{:?}", ends(&s, speck));
// A length so short that the rounded ends do not move records no undo step.
let dust = line(&mut s, (20.0, 20.0), (20.0, 20.0));
let n = steps(&s);
run(&mut s, json!({"ids": [dust.0], "lineLength": 1e-20}));
assert_eq!(steps(&s), n, "a length of 1e-20 pt changes nothing");
near(ends(&s, dust), (20.0, 20.0, 20.0, 20.0));
// Other live shapes ignore the line params.
let rect = NodeId(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap());
let n = steps(&s);
run(&mut s, json!({"ids": [rect.0], "lineLength": 30, "lineAngle": 45}));
assert_eq!(steps(&s), n);
}
#[test]
fn relative_corner_rounding_keeps_fraction_on_resize() {
let (mut s, id) = session();
+69
View File
@@ -4473,6 +4473,58 @@ fn exit_isolation_leaves_a_locked_guide_path_deselected() {
assert_eq!(selected(&s), vec![g]);
}
/// Exit Isolation Mode on an isolated sublayer isolates its parent layer and selects the sublayer, one
/// layer per call, without an undo step; from the top-level layer it leaves isolation mode. `all: true`
/// leaves from any depth, a hidden parent layer is not isolated (the call leaves), and a group in a
/// sublayer still leaves in one call.
#[test]
fn exit_isolation_goes_up_one_layer_from_a_sublayer() {
let mut s = session();
let top = s.doc().unwrap().doc.layers[0].id;
let mid = id_of(&s.execute("layer.newSublayer", &json!({"parent": top.0})).unwrap());
let deep = id_of(&s.execute("layer.newSublayer", &json!({"parent": mid.0})).unwrap());
s.execute("layer.setCurrent", &json!({"id": deep.0})).unwrap();
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
let b = rect(&mut s, 20.0, 0.0, 10.0, 10.0);
let isolation = |s: &Session| s.doc().unwrap().isolation;
let exit = |s: &mut Session, p: Value| s.execute("object.exitIsolation", &p).unwrap();
s.execute("object.isolate", &json!({"id": deep.0})).unwrap();
let before = history(&s);
exit(&mut s, json!({}));
assert_eq!((isolation(&s), selected(&s)), (Some(mid), vec![deep]), "up from the deepest sublayer");
exit(&mut s, json!({}));
assert_eq!((isolation(&s), selected(&s)), (Some(top), vec![mid]), "up from the middle sublayer");
exit(&mut s, json!({}));
assert_eq!((isolation(&s), selected(&s)), (None, vec![top]), "out from the top-level layer");
assert_eq!(history(&s), before, "no undo step");
s.execute("object.isolate", &json!({"id": deep.0})).unwrap();
exit(&mut s, json!({"all": true}));
assert_eq!((isolation(&s), selected(&s)), (None, vec![deep]), "all: true");
s.execute("object.isolate", &json!({"id": deep.0})).unwrap();
exit(&mut s, json!({"all": false}));
assert_eq!(isolation(&s), Some(mid), "all: false");
for bad in [json!({"all": 1}), json!({"all": "yes"}), json!({"all": null})] {
let e = s.execute("object.exitIsolation", &bad).unwrap_err().to_string();
assert!(e.contains("`all` must be true or false"), "{bad}: {e}");
assert_eq!(isolation(&s), Some(mid), "{bad}: still isolated");
}
// A parent layer hidden while its sublayer is isolated isn't isolated: the call leaves.
s.execute("object.isolate", &json!({"id": deep.0})).unwrap();
s.execute("layer.setProps", &json!({"id": mid.0, "visible": false})).unwrap();
exit(&mut s, json!({}));
assert_eq!(isolation(&s), None, "hidden parent layer");
s.execute("layer.setProps", &json!({"id": mid.0, "visible": true})).unwrap();
sel(&mut s, &[a, b]);
let g = id_of(&s.execute("object.group", &json!({})).unwrap());
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
exit(&mut s, json!({}));
assert_eq!((isolation(&s), selected(&s)), (None, vec![g]), "a group in a sublayer");
}
/// Undo and Redo bring back a selection without the guides, ruler guides or guide paths, that
/// Lock Guides has locked since, so a move after them leaves the guides where they are.
#[test]
@@ -5689,3 +5741,20 @@ fn crop_image_trim_leaves_a_cmyk_image_alone() {
let r = s.execute("object.cropImage", &json!({"trim": true})).unwrap();
assert_eq!((r["trimmed"].as_bool(), r["width"].as_u64(), r["height"].as_u64()), (Some(false), Some(4), Some(2)), "{r}");
}
/// Lock Guides is not an undo step: it adds none, and undo and redo of the steps before it leave
/// the guides locked.
#[test]
fn lock_guides_is_not_an_undo_step() {
let mut s = session();
let g = rect(&mut s, 200.0, 0.0, 10.0, 10.0);
sel(&mut s, &[g]);
s.execute("view.guides.make", &json!({})).unwrap();
let steps = s.doc().unwrap().history.undo.len();
s.execute("view.guides.lock", &json!({"locked": true})).unwrap();
assert_eq!(s.doc().unwrap().history.undo.len(), steps);
s.execute("edit.undo", &json!({})).unwrap();
assert!(s.guides_locked());
s.execute("edit.redo", &json!({})).unwrap();
assert!(s.guides_locked());
}
+113
View File
@@ -637,6 +637,69 @@ fn an_edited_profile_starts_the_documents_of_its_category() {
let _ = std::fs::remove_dir_all(&dir);
}
/// The fill, stroke and weight of `id` in the active document.
fn look(s: &Session, id: u64) -> (vectorcraft_color::Paint, vectorcraft_color::Paint, Option<f64>) {
let n = s.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).cloned().unwrap();
(n.appearance.fill_paint(), n.appearance.stroke_paint(), n.appearance.stroke().map(|st| st.width))
}
#[test]
fn a_redefined_default_graphic_style_in_a_profile_is_the_default_fill_and_stroke() {
use vectorcraft_color::Paint;
let (mut s, dir) = with_profiles("default-style");
// The Print profile's Default Graphic Style becomes no fill and a 0.25 pt red stroke.
s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap();
s.execute("paint.setFill", &json!({"none": true})).unwrap();
s.execute("paint.setStroke", &json!({"color": "#ff0000"})).unwrap();
s.execute("stroke.set", &json!({"weight": 0.25})).unwrap();
s.execute("graphicStyle.redefine", &json!({"name": "Default Graphic Style"})).unwrap();
s.execute("document.save", &json!({})).unwrap();
let style = s.doc().unwrap().doc.graphic_styles[0].clone();
let red = style.appearance.stroke_paint();
assert!(matches!(red, Paint::Solid { .. }), "{red:?}");
assert_eq!(style.appearance.stroke().map(|st| st.width), Some(0.25), "{style:?}");
// The Mobile profile is saved as shipped.
s.execute("file.newProfiles.edit", &json!({"name": "Mobile"})).unwrap();
s.execute("document.save", &json!({})).unwrap();
s.execute("select.none", &json!({})).unwrap();
s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap();
let green = s.paint.fill.clone();
// A document from the Print profile starts with the style's fill, stroke and weight, and its art takes them.
s.execute("file.new", &json!({"profile": "Print", "colorMode": "cmyk"})).unwrap();
assert_eq!((s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width), (Paint::None, red.clone(), 0.25));
let id = s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 60, "height": 60})).unwrap()["id"].as_u64().unwrap();
assert_eq!(look(&s, id), (Paint::None, red.clone(), Some(0.25)));
// Default Fill and Stroke gives the selection and the defaults that look again, as one undo step.
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
s.execute("stroke.set", &json!({"weight": 3})).unwrap();
let steps = s.doc().unwrap().history.undo.len();
s.execute("paint.default", &json!({})).unwrap();
assert_eq!(look(&s, id), (Paint::None, red.clone(), Some(0.25)));
assert_eq!((s.paint.fill.clone(), s.paint.stroke_width), (Paint::None, 0.25));
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1);
// Nothing to change: no undo step.
let step = s.doc().unwrap().history.step();
s.execute("paint.default", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().history.step(), step);
// The new art is not linked to the style.
assert!(s.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().extras().graphic_style.is_none());
// A profile with the shipped style, here converted to CMYK, leaves the fill and stroke the user chose.
s.execute("select.none", &json!({})).unwrap();
s.execute("paint.setFill", &json!({"color": "#00ff00", "keepModel": true})).unwrap();
s.execute("file.new", &json!({"profile": "Mobile", "colorMode": "cmyk"})).unwrap();
assert_eq!(s.doc().unwrap().doc.color_mode, ColorMode::Cmyk);
assert_eq!(s.paint.fill, green);
// So does a document without a profile, and Default Fill and Stroke there gives white and 1 pt black.
s.execute("file.new", &json!({})).unwrap();
assert_eq!(s.paint.fill, green);
s.execute("paint.default", &json!({})).unwrap();
assert_eq!(s.paint, vectorcraft_tools::PaintDefaults::default());
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn the_profile_follows_the_preset_access_and_reset() {
let (mut s, dir) = with_profiles("choice");
@@ -682,6 +745,56 @@ fn the_profile_follows_the_preset_access_and_reset() {
let _ = std::fs::remove_dir_all(&dir);
}
/// The first run's style of text object `id`.
fn first_run(s: &Session, id: &Value) -> vectorcraft_doc::CharStyle {
let n = s.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id.as_u64().unwrap())).cloned().unwrap();
let vectorcraft_doc::NodeKind::Text(t) = &n.kind else { panic!("not type: {n:?}") };
t.runs[0].style.clone()
}
#[test]
fn a_profiles_normal_character_style_is_the_default_font() {
let (mut s, dir) = with_profiles("default-font");
// The Print profile's [Normal Character Style] becomes Source Serif 4 Regular at 9 pt.
s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap();
let attrs = json!({"font_family": "Source Serif 4", "font_style": "Regular", "size": 9, "charAlign": "emBoxBottom"});
s.execute("charStyle.setAttrs", &json!({"name": "[Normal Character Style]", "attrs": attrs})).unwrap();
s.execute("document.save", &json!({})).unwrap();
// New type in a document from the profile takes the font, size and Character Alignment.
s.execute("file.new", &json!({"preset": "A4"})).unwrap();
let made = s.execute("text.create", &json!({"x": 20, "y": 40, "text": "Serif"})).unwrap();
assert!(made.get("warning").is_none(), "{made}");
let st = first_run(&s, &made["id"]);
assert_eq!((st.font_family.as_str(), st.font_style.as_str(), st.size), ("Source Serif 4", "Regular", 9.0));
assert_eq!(st.char_align, vectorcraft_doc::CharAlign::EmBoxBottom);
// A font, size or Character Alignment given to the command still wins.
let made = s
.execute("text.create", &json!({"x": 20, "y": 80, "text": "Sans", "font": "Source Sans 3", "size": 14, "charAlign": "romanBaseline"}))
.unwrap();
let st = first_run(&s, &made["id"]);
assert_eq!((st.font_family.as_str(), st.size, st.char_align), ("Source Sans 3", 14.0, vectorcraft_doc::CharAlign::RomanBaseline));
// A family given alone starts in Regular, not the style's Bold, and without its axis settings.
let attrs = json!({"font_style": "Bold", "fontAxes": {"wght": 700}});
s.execute("charStyle.setAttrs", &json!({"name": "[Normal Character Style]", "attrs": attrs})).unwrap();
let made = s.execute("text.create", &json!({"x": 20, "y": 120, "text": "Inter", "font": "Inter"})).unwrap();
let st = first_run(&s, &made["id"]);
assert_eq!((st.font_family.as_str(), st.font_style.as_str()), ("Inter", "Regular"));
assert!(st.font_axes.is_empty(), "{:?}", st.font_axes);
// A font of the style that isn't available is reported, as one given to the command is.
s.execute("charStyle.setAttrs", &json!({"name": "[Normal Character Style]", "attrs": {"font_family": "No Such Family 7498"}})).unwrap();
let made = s.execute("text.create", &json!({"x": 20, "y": 160, "text": "Missing"})).unwrap();
assert!(made["warning"].as_str().is_some_and(|w| w.contains("No Such Family 7498")), "{made}");
// A document from a profile left as shipped starts type in the default font and size.
s.execute("file.new", &json!({"profile": "Web"})).unwrap();
let made = s.execute("text.create", &json!({"x": 20, "y": 40, "text": "Default"})).unwrap();
let st = first_run(&s, &made["id"]);
let default = vectorcraft_doc::CharStyle::default();
assert_eq!((st.font_family, st.size), (default.font_family, default.size));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn profile_errors_name_the_file_by_its_name_outside_the_read_roots() {
let (mut s, dir) = with_profiles("errors");
+111
View File
@@ -465,6 +465,117 @@ fn a_confined_package_refuses_a_linked_file_that_keeps_an_export_folder_outside_
assert_eq!(package(&mut s, json!({"folder": out})).unwrap()["links"], 1);
}
/// A confined request packages no linked file whose native document it can't read to check against
/// its read roots: a PDF that needs a password to open, and a native document that doesn't load,
/// even inside the roots. The package is refused before anything is written, with an error that
/// names no file or folder. A PDF without editing data is copied, and the person's package copies
/// every file.
#[test]
fn a_confined_package_refuses_a_linked_file_whose_editing_data_cannot_be_read() {
let home = Folder::new("package-unreadable-home");
let roots = crate::file_access::AutomationRoots::new(&[&home.0], &[&home.0]).unwrap().unwrap();
let out = home.file("out");
let package = |s: &mut Session, p: Value| crate::file_access::confine(Some(&roots), || s.execute("file.package", &p));
let refused = |s: &mut Session, p: Value| {
let e = package(s, p.clone()).expect_err("refused");
assert!(matches!(e, EngineError::BadParams { .. }), "{p}: {e:?}");
let e = e.to_string();
assert!(e.contains("a linked file's editing data can't be read to check it against the read roots"), "{p}: {e}");
assert!(!e.contains(home.0.to_string_lossy().as_ref()) && !e.contains("part."), "{p}: {e}");
assert!(!std::path::Path::new(&out).exists(), "{p}");
};
let mut part = session();
run(&mut part, "shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 30}));
std::fs::create_dir_all(home.0.join("art")).unwrap();
let native = home.file("art/part.vectorcraft");
let pdf = home.file("art/part.pdf");
save(&mut part, &native);
let pdf_of =
|part: &mut Session, p: Value| vectorcraft_format::base64_decode(run(part, "document.serialize", p)["dataBase64"].as_str().unwrap()).unwrap();
let editable = pdf_of(&mut part, json!({"format": "pdf"}));
let locked = pdf_of(&mut part, json!({"format": "pdf", "security": {"openPassword": "open sesame"}}));
assert!(vectorcraft_pdf::editing_with(&locked, Some("open sesame")).is_some(), "the locked PDF carries editing data");
let plain = pdf_of(&mut part, json!({"format": "pdf", "preserveEditing": false}));
let poster = |placed: &str| {
let mut s = session();
let r = run(&mut s, "file.place", json!({"path": placed, "link": true}));
assert_eq!(r["linked"], true, "{r}");
save(&mut s, &home.file("poster.vectorcraft"));
s
};
write(&pdf, &editable);
let mut s = poster(&pdf);
write(&pdf, &locked);
refused(&mut s, json!({"folder": out}));
refused(&mut s, json!({"relink": false}));
// A package prepared in the confined request and written on another thread.
let prepared = crate::file_access::confine(Some(&roots), || s.prepare_package(&json!({"folder": out}))).unwrap();
let e =
std::thread::spawn(move || prepared.write(&mut |_, _| Ok(())).map(|_| ()).map_err(|e| e.to_string())).join().unwrap().expect_err("refused");
assert!(e.contains("a linked file's editing data can't be read to check it against the read roots"), "{e}");
assert!(!std::path::Path::new(&out).exists());
assert_eq!(run(&mut s, "file.package", json!({}))["links"], 1, "the person's package");
// A PDF listing the editing file without its data (`EF` renamed, the same length).
let at = editable.windows(4).position(|w| w.starts_with(b"/EF") && !w[3].is_ascii_alphanumeric()).expect("the editing file's EF");
let mut detached = editable.clone();
detached[at..at + 3].copy_from_slice(b"/XF");
assert!(vectorcraft_pdf::editing(&detached).is_none(), "the editing data can't be resolved");
write(&pdf, &detached);
refused(&mut s, json!({"folder": out}));
refused(&mut s, json!({"relink": false}));
assert_eq!(run(&mut s, "file.package", json!({}))["links"], 1, "the person's package");
// A PDF without editing data.
write(&pdf, &plain);
assert_eq!(package(&mut s, json!({"folder": out})).unwrap()["links"], 1);
std::fs::remove_dir_all(&out).unwrap();
// A PDF whose attachments are too many to search to their end, with a readable editing file
// listed before the ones left unsearched.
let cut = attachments_cut_short(&vectorcraft_pdf::editing(&editable).unwrap().data);
assert!(vectorcraft_pdf::editing(&cut).is_some(), "the editing data is read");
write(&pdf, &cut);
refused(&mut s, json!({"folder": out}));
refused(&mut s, json!({"relink": false}));
assert_eq!(run(&mut s, "file.package", json!({}))["links"], 1, "the person's package");
// A native document that doesn't load, rewritten or copied as it is.
let mut s = poster(&native);
write(&native, b"not a document");
refused(&mut s, json!({"folder": out}));
refused(&mut s, json!({"folder": out, "relink": false}));
assert_eq!(run(&mut s, "file.package", json!({}))["links"], 1, "the person's package");
}
/// A one-page PDF carrying `native` as its editing file, listed first in an attachment name tree
/// whose second subtree has 70,000 nodes, more than are searched.
fn attachments_cut_short(native: &[u8]) -> Vec<u8> {
let name = vectorcraft_pdf::EDITING_FILE;
let mut stream = format!("<< /Length {} >>\nstream\n", native.len()).into_bytes();
stream.extend_from_slice(native);
stream.extend_from_slice(b"\nendstream");
let objects = [
b"<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles 3 0 R >> >>".to_vec(),
b"<< /Type /Pages /Kids [6 0 R] /Count 1 >>".to_vec(),
format!("<< /Kids [4 0 R << /Kids [{}] >>] >>", "<< /Names [] >> ".repeat(70_000)).into_bytes(),
format!("<< /Names [({name}) << /Type /Filespec /UF ({name}) /EF << /F 5 0 R >> >>] >>").into_bytes(),
stream,
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] >>".to_vec(),
];
let mut out = b"%PDF-1.7\n".to_vec();
let mut offsets = Vec::new();
for (i, body) in objects.iter().enumerate() {
offsets.push(out.len());
out.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes());
out.extend_from_slice(body);
out.extend_from_slice(b"\nendobj\n");
}
let xref = out.len();
out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", offsets.len() + 1).as_bytes());
for at in &offsets {
out.extend_from_slice(format!("{at:010} 00000 n \n").as_bytes());
}
out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", offsets.len() + 1).as_bytes());
out
}
/// A missing link stored as a path relative to the document names a file inside a confined
/// request's read root: the package report and Document Info give its stored path.
#[test]
+2
View File
@@ -430,6 +430,8 @@ fn set_live_shape_refuses_an_unknown_key() {
json!({"id": 3, "radius": 5}),
json!({"ids": [3], "sides": 6, "polygonAngle": 15, "polygonRadius": 20, "sideLength": null, "makeSidesEqual": true}),
json!({"pieStart": 30, "pieEnd": 90, "invertPie": true}),
json!({"pieEnd": 90, "constrainPie": true}),
json!({"ids": [3], "lineLength": 72, "lineAngle": 90}),
json!({"items": null}),
] {
assert!(check_params(ID, &ok).is_ok(), "{ok}");
+168
View File
@@ -0,0 +1,168 @@
//! The params description of each built-in command is parsed once per process; the answers read
//! from it are those of parsing it where they are used.
use std::hint::black_box;
use serde_json::{Value, json};
use crate::cmd::params::{PARSES, accepted_keys, check_keys, doc_keys, id_stands_for_ids, read_once, takes_key, uncached};
use crate::{Session, command_specs};
/// Every answer the key functions give about `doc` for command `id`, as text.
fn answers(id: &str, doc: &'static str) -> Vec<String> {
let own = doc_keys(doc).map(|p| p.keys).unwrap_or_default();
let accepted = accepted_keys(doc);
let mut out = vec![format!("{accepted:?}"), format!("{}", id_stands_for_ids(doc))];
let near = own.first().map(|k| format!("{k}q"));
for key in own.iter().copied().chain(["ids", "id", "zzz"]).chain(near.as_deref()) {
out.push(format!("{key}: {}", takes_key(doc, key)));
}
let all: serde_json::Map<String, Value> = accepted.iter().flatten().map(|k| (k.to_string(), Value::Null)).collect();
let mut cases = vec![json!({}), json!({"zzz": 1}), Value::Object(all)];
cases.extend(near.map(|k| json!({ k: 1 })));
for params in cases {
out.push(format!("{params}: {:?}", check_keys(id, doc, &params)));
}
out
}
#[test]
fn every_command_gets_the_answers_of_its_parsed_description() {
for c in command_specs() {
assert_eq!(answers(c.id, c.params), uncached(|| answers(c.id, c.params)), "{}", c.id);
}
}
#[test]
fn a_built_in_description_is_not_parsed_again() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 200, "created": null})).unwrap();
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap()["id"].as_u64().unwrap();
let run = |s: &mut Session| {
s.execute("select.set", &json!({"ids": [id]})).unwrap();
s.execute("object.move", &json!({"ids": [id], "dx": 1})).unwrap();
s.execute("object.move", &json!({"ids": [id], "dx": -1})).unwrap();
for c in command_specs() {
black_box((accepted_keys(c.params), takes_key(c.params, "ids"), takes_key(c.params, "id"), id_stands_for_ids(c.params)));
black_box(check_keys(c.id, c.params, &json!({"zzz": 1})).is_err());
}
};
run(&mut s);
PARSES.set(0);
run(&mut s);
assert_eq!(PARSES.get(), 0, "descriptions parsed again");
// Without the table each command parses its description where it is used.
uncached(|| run(&mut s));
assert!(PARSES.get() > command_specs().len());
}
/// A description that isn't a built-in command's, even with the same words (a plug-in's), is parsed
/// where it is used, and so is one that names a plug-in command, whose keys change as plug-ins are
/// installed and removed.
#[test]
fn other_descriptions_are_parsed_where_they_are_used() {
let spec = command_specs().iter().find(|c| id_stands_for_ids(c.params)).unwrap();
let copy: &'static str = String::from(spec.params).leak();
assert_eq!(answers(spec.id, copy), answers(spec.id, spec.params));
PARSES.set(0);
assert!(takes_key(copy, "ids") && id_stands_for_ids(copy));
assert!(PARSES.get() > 0);
assert!(read_once("{a, …settings as file.new}"));
assert!(!read_once("{a, …settings as plugin.some.command}"));
assert!(!read_once("{a, …the options of `plugin.some.command`}"));
}
/// This thread's CPU time in ns where Linux reports it, else the time since `start`.
fn now(start: std::time::Instant) -> (u128, bool) {
let cpu = std::fs::read_to_string("/proc/thread-self/schedstat").ok().and_then(|s| s.split_whitespace().next()?.parse().ok());
match cpu {
Some(ns) => (ns, true),
None => (start.elapsed().as_nanos(), false),
}
}
fn median(mut v: Vec<u128>) -> u128 {
v.sort_unstable();
v[v.len() / 2]
}
/// `cargo test --release -p vectorcraft-engine --lib params_cache -- --ignored --nocapture` prints
/// the time of the key questions over every built-in description and of `Session::execute` on a
/// one-object document, with descriptions parsed where they are used (`parse`) and read once
/// (`once`), alternating in one process: the median of 7 runs, in this thread's CPU time on Linux.
#[test]
#[ignore = "benchmark"]
fn bench_params_keys_once() {
let start = std::time::Instant::now();
let specs = command_specs();
let questions = || {
for c in specs {
black_box((accepted_keys(c.params), takes_key(c.params, "ids"), takes_key(c.params, "id")));
black_box((takes_key(c.params, "ids"), takes_key(c.params, "id"), id_stands_for_ids(c.params)));
}
};
let time = |f: &dyn Fn()| {
let t = now(start);
f();
(now(start).0 - t.0, t.1)
};
questions();
uncached(questions);
let (mut parse, mut once, mut cpu) = (Vec::new(), Vec::new(), true);
for _ in 0..7 {
let (p, c1) = time(&|| uncached(|| (0..200).for_each(|_| questions())));
let (o, c2) = time(&|| (0..200).for_each(|_| questions()));
parse.push(p);
once.push(o);
cpu &= c1 && c2;
}
let per = |ns: u128| ns / (200 * specs.len() as u128);
println!("clock: {}", if cpu { "thread CPU time" } else { "wall time" });
println!("key questions, ns per description: parse {} once {}", per(median(parse)), per(median(once)));
for (cmd, params) in [("select.set", "ids"), ("object.move", "move")] {
let doc = || {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 200, "created": null})).unwrap();
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap()["id"].as_u64().unwrap();
let p = if params == "ids" { json!({"ids": [id]}) } else { json!({"ids": [id], "dx": 1}) };
(s, p)
};
let run = |s: &mut Session, p: &Value| {
for _ in 0..20_000 {
black_box(s.execute(cmd, p).unwrap());
}
};
let ((mut a, pa), (mut b, pb)) = (doc(), doc());
assert_eq!(uncached(|| a.execute(cmd, &pa).unwrap()), b.execute(cmd, &pb).unwrap(), "{cmd}: both ways give the same result");
let timed = |s: &mut Session, p: &Value, cached: bool| {
let t = now(start).0;
if cached {
run(s, p)
} else {
uncached(|| run(s, p))
}
now(start).0 - t
};
let (mut parse, mut once) = (Vec::new(), Vec::new());
for i in 0..7 {
let (mut s1, p1) = doc();
let (mut s2, p2) = doc();
if i % 2 == 0 {
parse.push(timed(&mut s1, &p1, false));
once.push(timed(&mut s2, &p2, true));
} else {
once.push(timed(&mut s2, &p2, true));
parse.push(timed(&mut s1, &p1, false));
}
// Each document has a `uid` of its own.
let state = |s: &Session| {
let mut d = crate::inspect::document(s);
d.as_object_mut().unwrap().remove("uid");
d
};
assert_eq!(state(&s1), state(&s2), "{cmd}: same document");
}
let ms = |ns: u128| ns as f64 / 1e6;
println!("{cmd} x 20,000: parse {:.1} ms once {:.1} ms", ms(median(parse)), ms(median(once)));
}
}
+85
View File
@@ -312,6 +312,91 @@ fn view_options_toggle_without_undo_steps_and_survive_presets() {
assert_eq!(PerspectiveGrid::from_doc(&back), Some(g));
}
/// The view options are not undo steps, so undo and redo of other steps leave them as they are:
/// Lock Grid, Lock Station Point, Snap to Grid, Show Rulers and whether the grid shows. Undoing a
/// grid definition brings back the old grid with the current view options.
#[test]
fn undo_and_redo_keep_the_view_options() {
let mut s = session();
run(&mut s, "perspective.grid.preset", json!({"kind": 2}));
let old = grid(&s);
run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 40}));
run(&mut s, "perspective.grid.preset", json!({"kind": 1}));
let n = undo_len(&s);
for (id, on) in
[("perspective.grid.lock", true), ("perspective.grid.lockStation", true), ("perspective.grid.snap", false), ("perspective.grid.rulers", true)]
{
run(&mut s, id, json!({"on": on}));
}
run(&mut s, "perspective.grid.show", json!({"visible": false}));
assert_eq!(undo_len(&s), n);
let view = |g: &PerspectiveGrid| (g.locked, g.lock_station, g.snap, g.rulers, g.visible);
let want = (true, true, false, true, false);
assert_eq!(view(&grid(&s)), want);
// Undo the one-point preset: the two-point grid comes back with today's view options.
s.execute("edit.undo", &json!({})).unwrap();
let g = grid(&s);
assert_eq!((g.kind, g.vp_left, view(&g)), (old.kind, old.vp_left, want));
// Undo the rectangle, which left the grid alone.
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(view(&grid(&s)), want);
// An option changed now holds through the redo steps.
run(&mut s, "perspective.grid.lock", json!({"on": false}));
s.execute("edit.redo", &json!({})).unwrap();
s.execute("edit.redo", &json!({})).unwrap();
let g = grid(&s);
assert_eq!((g.kind, view(&g)), (1, (false, true, false, true, false)));
}
/// The view options set on a document whose steps hold no grid yet stay as they are when undo
/// brings back a step without one, and the active plane chosen without an undo step stays too.
#[test]
fn undo_keeps_the_view_options_of_a_grid_no_step_defined() {
let mut s = session();
run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 40}));
run(&mut s, "shape.rectangle", json!({"x": 100, "y": 10, "width": 50, "height": 40}));
assert!(!s.doc().unwrap().doc.unknown.contains_key(vectorcraft_tools::distort::perspective::DOC_KEY));
run(&mut s, "perspective.grid.show", json!({"visible": true}));
run(&mut s, "perspective.grid.lock", json!({"on": true}));
run(&mut s, "perspective.grid.snap", json!({"on": false}));
run(&mut s, "perspective.plane.set", json!({"plane": "ground"}));
let view = |g: &PerspectiveGrid| (g.visible, g.locked, g.snap, g.plane);
let want = (true, true, false, vectorcraft_tools::distort::perspective::Plane::Ground);
assert_eq!(view(&grid(&s)), want);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(view(&grid(&s)), want);
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(view(&grid(&s)), want);
}
/// A step that changed a view option itself takes it back on undo and sets it again on redo: a
/// preset shows the grid, and a grid definition can lock it.
#[test]
fn undo_takes_back_the_view_options_a_step_changed() {
let mut s = session();
run(&mut s, "perspective.grid.preset", json!({"kind": 2}));
run(&mut s, "perspective.grid.show", json!({"visible": false}));
run(&mut s, "perspective.grid.preset", json!({"kind": 1}));
assert!(grid(&s).visible);
s.execute("edit.undo", &json!({})).unwrap();
assert!(!grid(&s).visible, "the preset showed the grid");
s.execute("edit.redo", &json!({})).unwrap();
assert!(grid(&s).visible);
let cell = grid(&s).cell;
run(&mut s, "perspective.grid.set", json!({"locked": true, "cell": cell + 10.0}));
assert!(grid(&s).locked);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!((grid(&s).locked, grid(&s).cell), (false, cell));
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!((grid(&s).locked, grid(&s).cell), (true, cell + 10.0));
// An option the step left alone and changed after it stays as it is.
run(&mut s, "perspective.grid.snap", json!({"on": false}));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!((grid(&s).locked, grid(&s).snap), (false, false));
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!((grid(&s).locked, grid(&s).snap), (true, false));
}
/// Lock Grid, Lock Station Point, Snap to Grid and Show Rulers refuse an `on` given as text or as
/// another value that is not true or false: the grid and the undo history stay as they were. Null is
/// read as the key left out, so it toggles the option.
+55 -1
View File
@@ -4446,6 +4446,59 @@ fn a_cancelled_filter_run_changes_nothing() {
assert_eq!(s.doc().unwrap().doc, before);
}
/// Preferences › Plug-ins & Scratch Disks › Plug-in Instruction Budget: with Normal a light filter
/// runs out of instructions and changes nothing; with Large the same installed filter finishes, as
/// one undo step, without being installed again. The time budget, Cancel and a heavy filter's
/// larger budget stay as they are, and setting Normal again applies to the next run.
#[test]
fn the_plugin_instruction_budget_preference_sets_a_filter_run_s_instructions() {
use cmd::plugin::FilterRun;
let mut s = session();
let id = "test.engine.largebudget";
let output = json!({"objects": [{"path": triangle(), "name": "Plug-in"}]}).to_string();
// More steps than a light budget pays for, fewer than 5 times it.
install_wat(&mut s, &tpl::spinning(&tpl::manifest(id, "filter", "{}"), 20_000_000, &output));
let p = json!({"id": id, "ids": []});
let (before, undo) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len());
let e = s.execute("plugin.run", &p).unwrap_err().to_string();
assert!(e.contains("instruction budget"), "{e}");
assert_eq!((&s.doc().unwrap().doc, s.doc().unwrap().history.undo.len()), (&before, undo));
run(&mut s, "prefs.set", json!({"key": "pluginInstructionBudget", "value": "large"}));
let light = vectorcraft_plugins::Limits::default();
let large = FilterRun::prepare(&s, &p).unwrap().limits().clone();
assert_eq!(large, vectorcraft_plugins::Limits { fuel_base: vectorcraft_plugins::LARGE_FUEL, ..light.clone() });
assert_eq!((large.fuel_per_byte, large.wall_time_ms), (light.fuel_per_byte, light.wall_time_ms));
// Cancel still stops it, and it changes nothing.
let token = vectorcraft_doc::cancel::CancelToken::new();
token.cancel();
let r = vectorcraft_doc::cancel::scope(&token, None, || s.execute("plugin.run", &p));
assert!(matches!(r, Err(EngineError::Cancelled)), "{r:?}");
assert_eq!((&s.doc().unwrap().doc, s.doc().unwrap().history.undo.len()), (&before, undo));
let made = run(&mut s, "plugin.run", p.clone())["ids"].clone();
assert_eq!(made.as_array().map(Vec::len), Some(1));
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
// A heavy filter keeps its larger budget with either choice.
let heavy_id = "test.engine.largebudget.heavy";
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&heavy(heavy_id, 1)), "allowHeavy": true}));
let hp = json!({"id": heavy_id, "ids": []});
for budget in ["large", "normal"] {
run(&mut s, "prefs.set", json!({"key": "pluginInstructionBudget", "value": budget}));
let limits = FilterRun::prepare(&s, &hp).unwrap().limits().clone();
let heavy_limits = (vectorcraft_plugins::HEAVY_FUEL, vectorcraft_plugins::HEAVY_WALL_TIME_MS);
assert_eq!((limits.fuel_base, limits.wall_time_ms), heavy_limits, "{budget}");
}
// Normal again: the next run runs out of instructions.
let undo = s.doc().unwrap().history.undo.len();
let e = s.execute("plugin.run", &p).unwrap_err().to_string();
assert!(e.contains("instruction budget"), "{e}");
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
run(&mut s, "plugin.remove", json!({"id": id}));
run(&mut s, "plugin.remove", json!({"id": heavy_id}));
}
/// The manifest of a filter `id` named "Cmd Test" of `kind` with `commands` (a JSON list).
fn with_commands(id: &str, kind: &str, commands: &str) -> String {
format!(r#"{{"id":"{id}","name":"Cmd Test","version":"1","kind":"{kind}","commands":{commands}}}"#)
@@ -4511,9 +4564,10 @@ fn plugin_commands_are_registered_run_and_removed() {
install_wat(&mut s, &tpl::module(&tpl::manifest(id, "filter", "{}"), tpl::ECHO, "", 1));
assert!(listed(&s, grow).is_none() && crate::cmd::find_command(grow).is_none());
install_wat(&mut s, &grower(id));
assert!(listed(&s, grow).is_some());
assert!(listed(&s, grow).is_some() && crate::cmd::find_command(grow).is_some());
run(&mut s, "plugin.remove", json!({"id": id}));
assert!(listed(&s, grow).is_none() && listed(&s, tidy).is_none());
assert!(crate::cmd::find_command(grow).is_none() && crate::cmd::find_command(tidy).is_none());
assert!(s.execute(grow, &json!({})).is_err(), "removed, it no longer runs");
}
+49
View File
@@ -109,6 +109,23 @@ fn grid_prefs_apply_to_open_documents() {
assert_eq!((g.spacing, g.subdivisions), (36.0, 4));
}
/// The grid preferences are not an undo step in the documents they apply to, so undo and redo
/// leave the grid as the preferences set it.
#[test]
fn undo_and_redo_keep_the_grid_prefs() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap();
s.execute("prefs.set", &json!({"values": {"gridlineEvery": 36, "gridSubdivisions": 4}})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
let g = &s.doc().unwrap().doc.grid;
assert_eq!((g.spacing, g.subdivisions), (36.0, 4));
s.execute("prefs.set", &json!({"values": {"gridlineEvery": 18, "gridSubdivisions": 3}})).unwrap();
s.execute("edit.redo", &json!({})).unwrap();
let g = &s.doc().unwrap().doc.grid;
assert_eq!((g.spacing, g.subdivisions), (18.0, 3));
}
/// Guides & Grid › Gridline every and Subdivisions (#394): set with no document open, as the
/// desktop app restores them at launch, they give `file.new`'s document their grid.
#[test]
@@ -447,6 +464,38 @@ fn gpu_preference_defaults_to_automatic_and_validates() {
assert_eq!(s.prefs.gpu_preference, "automatic");
}
/// Plug-ins & Scratch Disks › Plug-in Instruction Budget: Normal by default, Large by value or
/// label, kept through a save and load, and reset with its category. Setting another value is an
/// error that changes nothing; a saved value that is missing, unknown or of another type reads as
/// Normal and leaves the other saved preferences as they are.
#[test]
fn plugin_instruction_budget_defaults_to_normal_and_validates() {
let mut s = Session::new();
assert_eq!(s.prefs.plugin_instruction_budget, PluginBudget::Normal);
assert_eq!(s.execute("prefs.get", &json!({"key": "pluginInstructionBudget"})).unwrap(), json!("normal"));
set_pref(&mut s, "pluginInstructionBudget", json!("Large"));
assert_eq!(s.prefs.plugin_instruction_budget, PluginBudget::Large);
assert_eq!(s.execute("prefs.get", &json!({"key": "pluginInstructionBudget"})).unwrap(), json!("large"));
for bad in [json!("unlimited"), json!(""), json!(5), json!(null), json!(true), json!(["large"])] {
assert!(s.execute("prefs.set", &json!({"key": "pluginInstructionBudget", "value": bad})).is_err(), "{bad}");
assert_eq!(s.prefs.plugin_instruction_budget, PluginBudget::Large, "{bad}");
}
let back: Prefs = serde_json::from_value(s.prefs.to_json()).unwrap();
assert_eq!(back.plugin_instruction_budget, PluginBudget::Large);
let other_values = [json!("unlimited"), json!(5), json!(null), json!(["large"]), json!({"large": true}), json!("LARGE")];
let saved_files = other_values.map(|v| json!({"keyboardIncrement": 4, "pluginInstructionBudget": v}));
for saved in std::iter::once(json!({"keyboardIncrement": 4})).chain(saved_files) {
let read: Prefs = serde_json::from_value(saved.clone()).unwrap();
assert_eq!((read.plugin_instruction_budget, read.keyboard_increment), (PluginBudget::Normal, 4.0), "{saved}");
}
let l = s.execute("prefs.list", &json!({})).unwrap();
let row = l.as_array().unwrap().iter().find(|e| e["key"] == "pluginInstructionBudget").unwrap().clone();
assert_eq!((row["category"].as_str(), row["section"].as_str()), (Some("Plug-ins & Scratch Disks"), Some("Plug-ins")));
assert_eq!((&row["options"], &row["value"]), (&json!(["normal", "large"]), &json!("large")));
s.execute("prefs.reset", &json!({"category": "Plug-ins & Scratch Disks"})).unwrap();
assert_eq!(s.prefs.plugin_instruction_budget, PluginBudget::Normal);
}
/// Performance › Low-Latency Drawing (#6013): off by default and for preference files written
/// before it, a boolean only, kept through a save/load round trip, listed under Performance and
/// reset with it.
+62
View File
@@ -299,6 +299,68 @@ fn redefine_shares_one_appearance() {
assert!(!Shared::ptr_eq(&node(&s, d).appearance, &nb.appearance));
}
/// Redefine with `from` gives a style another style's look: the style keeps its name, place and id,
/// its objects still linked follow, edited ones are unlinked, and `from` and its objects stay as
/// they are, in one undo step. A style replaced by itself or by a style with the same look records
/// nothing, and bad parameters are errors that change nothing.
#[test]
fn redefine_from_a_style_gives_the_style_that_look() {
let mut s = session();
let (a, b, c) = linked_three(&mut s);
let d = rect(&mut s, 300.0);
set_fill(&mut s, d, "#0000ff");
run(&mut s, "transparency.set", json!({"item": null, "opacity": 50, "blend": "multiply"}));
run(&mut s, "graphicStyle.new", json!({"name": "Blue"}));
set_fill(&mut s, c, "#00ff00");
let names = |s: &Session| s.doc().unwrap().doc.graphic_styles.iter().map(|g| g.name.clone()).collect::<Vec<_>>();
let steps = |s: &Session| s.doc().unwrap().history.undo.len();
let (old, blue, order, before) = (style(&s, "S"), style(&s, "Blue"), names(&s), steps(&s));
assert_eq!(run(&mut s, "graphicStyle.redefine", json!({"name": "S", "from": "Blue"}))["name"], "S");
assert_eq!(style(&s, "S"), GraphicStyle { name: "S".into(), id: old.id, ..blue.clone() });
assert_eq!(names(&s), order);
let blue_paint = Paint::solid(Color::from_hex("#0000ff").unwrap());
for id in [a, b] {
let n = node(&s, id);
assert_eq!((n.appearance.fill_paint(), n.opacity, n.blend), (blue_paint.clone(), 0.5, BlendMode::Multiply));
}
assert_eq!(linked(&mut s, "S"), vec![a.0, b.0]);
// The edited object keeps its look and is unlinked; Blue and its object are as they were.
assert_eq!(fill(&s, c), Paint::solid(Color::from_hex("#00ff00").unwrap()));
assert_eq!(node(&s, c).extras().graphic_style, None);
assert_eq!(style(&s, "Blue"), blue);
assert_eq!(linked(&mut s, "Blue"), vec![d.0]);
let step = s.doc().unwrap().history.undo.last().unwrap().clone();
assert_eq!((step.label.as_str(), steps(&s)), ("Redefine Graphic Style “S”", before + 1));
run(&mut s, "edit.undo", json!({}));
assert_eq!(style(&s, "S"), old);
assert_eq!((fill(&s, a), fill(&s, b)), (Paint::solid(Color::WHITE), Paint::solid(Color::WHITE)));
assert_eq!(node(&s, c).extras().graphic_style, Some(old.id));
run(&mut s, "edit.redo", json!({}));
assert_eq!(style(&s, "S").appearance, blue.appearance);
assert_eq!(linked(&mut s, "S"), vec![a.0, b.0]);
run(&mut s, "edit.undo", json!({}));
// A style replaced by itself, or by a copy with the same look, records nothing.
run(&mut s, "graphicStyle.duplicate", json!({"name": "Blue"}));
let before = steps(&s);
run(&mut s, "graphicStyle.redefine", json!({"name": "S", "from": "S"}));
run(&mut s, "graphicStyle.redefine", json!({"name": "Blue copy", "from": "Blue"}));
assert_eq!(steps(&s), before);
assert_eq!(style(&s, "S"), old);
// A style that does not exist, a `from` that is not a name, `from` with `id` and a missing `name` are errors.
for p in [
json!({"name": "S", "from": "nope"}),
json!({"name": "nope", "from": "Blue"}),
json!({"name": "S", "from": 3}),
json!({"name": "S", "from": "Blue", "id": a.0}),
json!({"from": "Blue"}),
] {
assert!(s.execute("graphicStyle.redefine", &p).is_err(), "{p}");
}
assert_eq!((steps(&s), style(&s, "S")), (before, old));
}
#[test]
fn deleting_a_style_unlinks_and_renaming_keeps_links() {
let mut s = session();
+22
View File
@@ -253,6 +253,28 @@ fn redefining_the_symbol_being_edited_leaves_symbol_editing_mode_in_the_same_ste
assert!(st.doc.symbol_edit.is_some());
}
/// Redefining the symbol being edited with `keepArt: true` also leaves symbol editing mode in the
/// same step; the art outside the editing layer stays ordinary art and stays selected, and the
/// art on the editing layer still can't redefine it.
#[test]
fn redefining_the_symbol_being_edited_with_keep_art_leaves_the_art_and_the_mode() {
let (mut s, first, second) = two_instances();
let other = id(&run(&mut s, "shape.rectangle", json!({"x": 10, "y": 200, "width": 30, "height": 30})));
let layer = NodeId(run(&mut s, "symbol.edit", json!({"id": first.0}))["layer"].as_u64().unwrap());
let e = s.execute("symbol.update", &json!({"name": "Box", "keepArt": true})).unwrap_err().to_string();
assert!(e.contains("can't hold an instance of itself"), "{e}");
let steps = s.doc().unwrap().history.undo.len();
let r = run(&mut s, "symbol.update", json!({"name": "Box", "ids": [other.0], "keepArt": true}));
assert!(r["id"].is_null(), "{r}");
let st = s.doc().unwrap();
assert!(st.doc.symbol_edit.is_none() && st.isolation.is_none() && st.doc.node(layer).is_none());
assert_eq!(st.history.undo.len(), steps + 1);
assert!(matches!(st.doc.node(other).map(|n| &n.kind), Some(NodeKind::Path { .. })), "the art stays ordinary art");
assert_eq!(st.selection.objects, vec![other], "the art stays selected");
assert!(is_instance(&s, first), "the instance editing was entered from is still an instance");
assert!(close(bounds(&s, second), Rect::new(285.0, 185.0, 315.0, 215.0)), "{:?}", bounds(&s, second));
}
#[test]
fn leaving_goes_back_to_the_isolation_before_and_undo_keeps_a_group_isolated_inside() {
let (mut s, first, _) = two_instances();
+66
View File
@@ -375,3 +375,69 @@ fn other_documents_symbols_load_and_unreadable_files_are_errors() {
let bytes = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap();
assert_eq!(vectorcraft_format::load(&bytes).unwrap().symbols.len(), 1);
}
/// `symbol.placeFromDocument` places another open document's symbol in the active document as
/// one undo step, with the symbol it nests, the pattern its art uses and its Symbol Options. A
/// second placement uses what the first added; the source document is left as it was; a symbol
/// of the active document itself is placed as it is; a closed document, a name the document does
/// not have and bad params are errors that change nothing.
#[test]
fn another_documents_symbol_is_added_and_placed_in_one_step() {
let mut s = kit();
let source = s.doc().unwrap().uid;
let source_doc = s.doc().unwrap().doc.clone();
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
let before = undo_len(&s);
let r = run(&mut s, "symbol.placeFromDocument", json!({"sourceDocument": source, "name": "Badge", "x": 30, "y": 40}));
assert_eq!(undo_len(&s), before + 1, "added and placed in one step");
assert_eq!(r["name"], "Badge");
let mut names = symbols(&s);
names.sort();
assert_eq!(names, ["Badge", "Star"], "the nested Star came along");
assert_eq!(doc(&s).symbol_registration("Badge"), SymbolRegistration(0));
let placed = NodeId(r["id"].as_u64().unwrap());
assert_eq!(s.doc().unwrap().selection.objects, [placed]);
let NodeKind::SymbolInstance { symbol, .. } = &doc(&s).node(placed).unwrap().kind else { panic!("not an instance") };
assert_eq!(symbol, "Badge");
let size = |d: &vectorcraft_doc::Document| d.unknown.get("symbolSizes").and_then(|m| m.get("Badge")).cloned();
assert!(size(doc(&s)).is_some());
assert_eq!(size(doc(&s)), size(&source_doc));
// The Dots symbol brings its pattern and swatch.
run(&mut s, "symbol.placeFromDocument", json!({"sourceDocument": source, "name": "Dots"}));
assert!(doc(&s).pattern("Dots").is_some() && doc(&s).swatch("Dots").is_some());
// Placed again, Badge is the one already added.
let count = doc(&s).symbols.len();
let r = run(&mut s, "symbol.placeFromDocument", json!({"sourceDocument": source, "name": "Badge"}));
assert_eq!((r["name"].as_str(), doc(&s).symbols.len()), (Some("Badge"), count));
run(&mut s, "edit.undo", json!({}));
run(&mut s, "edit.undo", json!({}));
run(&mut s, "edit.undo", json!({}));
assert!(symbols(&s).is_empty() && doc(&s).pattern("Dots").is_none());
// The active document's own symbol, by its uid: placed, nothing added.
run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10}));
run(&mut s, "symbol.new", json!({"name": "Star"}));
let own = s.doc().unwrap().uid;
let before = undo_len(&s);
let r = run(&mut s, "symbol.placeFromDocument", json!({"sourceDocument": own, "name": "Star", "x": 70, "y": 70}));
assert_eq!((undo_len(&s), r["name"].as_str(), symbols(&s)), (before + 1, Some("Star"), vec!["Star".to_string()]));
// Errors change nothing.
let before = (undo_len(&s), doc(&s).clone());
for p in [
json!({"sourceDocument": source, "name": "Nope"}),
json!({"sourceDocument": source}),
json!({"name": "Star"}),
json!({"sourceDocument": -1, "name": "Star"}),
json!({"sourceDocument": "1", "name": "Star"}),
json!({"sourceDocument": source, "name": "Star", "x": "10"}),
json!({"sourceDocument": u64::MAX, "name": "Star"}),
] {
assert!(s.execute("symbol.placeFromDocument", &p).is_err(), "{p}");
assert_eq!((undo_len(&s), doc(&s)), (before.0, &before.1), "{p}");
}
// The source document is left as it was, and once it is closed its symbols are gone with it.
assert!(s.set_active(0));
assert_eq!(*s.doc().unwrap().doc, *source_doc);
run(&mut s, "file.close", json!({"index": 0}));
let e = s.execute("symbol.placeFromDocument", &json!({"sourceDocument": source, "name": "Star"})).unwrap_err();
assert!(e.to_string().contains("no longer open"), "{e}");
}
+113 -1
View File
@@ -246,7 +246,12 @@ fn spiral_decay_is_normalized_for_active_and_inactive_tools_and_preferences() {
let mut s = session();
for active in [false, true] {
select(&mut s, if active { "spiral" } else { "selection" });
let options = s.set_tool_option_cmd(&json!({"tool": "spiral", "values": {"decay": 150, "segments": 4, "clockwise": false}})).unwrap();
// A decay past the 99.99 % a spiral draws is refused, and nothing changes.
let before = s.tool_options_of("spiral");
let refused = s.set_tool_option_cmd(&json!({"tool": "spiral", "values": {"decay": 150, "segments": 4, "clockwise": false}}));
assert_eq!(refused.err(), Some("tool `spiral`: `decay` must be a number from 5 to 99.99".to_string()));
assert_eq!(s.tool_options_of("spiral"), before);
let options = s.set_tool_option_cmd(&json!({"tool": "spiral", "values": {"decay": 99.99, "segments": 4, "clockwise": false}})).unwrap();
assert_eq!(options["decay"], json!(99.99));
assert_eq!(s.tool_options_of("spiral")["decay"], json!(99.99));
assert_eq!(s.prefs.tool_settings["spiral"]["decay"], json!(99.99));
@@ -387,3 +392,110 @@ fn alt_smoothing_takes_the_smooth_tools_fidelity() {
assert_eq!(s.tool_options()["fidelity"], json!(3.0), "{id}");
}
}
/// `tool.setOption` with a value of the wrong type, a number out of range, an unknown value or an
/// option the tool doesn't have is an error naming the tool and the option. Nothing is set, also
/// when another option given with it is good, and nothing is saved or recorded for undo.
#[test]
fn bad_option_values_are_errors_that_set_nothing() {
let mut s = session();
select(&mut s, "smooth");
let (options, saved, undo) = (s.tool_options(), s.prefs.tool_settings.clone(), s.doc().unwrap().history.undo.len());
let fidelity = "tool `smooth`: `fidelity` must be a number from 0.05 to 100";
for bad in [json!("abc"), json!(true), json!(-3), json!(1e9), json!(null), json!([2])] {
assert_eq!(s.set_tool_option_cmd(&json!({"key": "fidelity", "value": bad})).unwrap_err(), fidelity, "{bad}");
}
let cases = [
(json!({"key": "bogus", "value": 1}), "tool `smooth`: unknown option `bogus`"),
(json!({"tool": "pencil", "values": {"closeWithin": 5, "fidelity": "x"}}), "tool `pencil`: `fidelity` must be a number from 0.01 to 100"),
(json!({"tool": "pencil", "key": "fill", "value": "yes"}), "tool `pencil`: `fill` must be true or false"),
(json!({"tool": "blobBrush", "key": "sizeMode", "value": "huge"}), "tool `blobBrush`: `sizeMode` must be one of `fixed`, `pressure`"),
(json!({"tool": "eraser", "key": "fidelity", "value": 4}), "tool `eraser`: unknown option `fidelity`"),
(json!({"tool": "polygon", "key": "sides", "value": 2}), "tool `polygon`: `sides` must be a whole number from 3 to 1000"),
(
json!({"tool": "mirrorCut", "key": "axis", "value": "diagonal"}),
"tool `mirrorCut`: `axis` must be one of `vertical`, `horizontal`, `free`",
),
(json!({"tool": "selection", "key": "fidelity", "value": 4}), "tool `selection`: unknown option `fidelity`"),
(json!({"values": [1]}), "`values` must be an object"),
(json!({"tool": 3, "key": "fidelity", "value": 4}), "`tool` must be a tool id"),
(json!({"key": "fidelity"}), "`value` is missing for `fidelity`"),
];
for (p, want) in cases {
assert_eq!(s.set_tool_option_cmd(&p).unwrap_err(), want, "{p}");
}
assert_eq!(s.tool_options_of("pencil")["closeWithin"], session().tool_options_of("pencil")["closeWithin"]);
assert_eq!((s.tool_options(), &s.prefs.tool_settings, s.doc().unwrap().history.undo.len()), (options, &saved, undo));
// A good value after the errors is set and read back.
assert_eq!(s.set_tool_option_cmd(&json!({"key": "fidelity", "value": 9})).unwrap()["fidelity"], json!(9.0));
}
/// `tool.setOption {}` reads the options, of the active tool or of the tool named, and saves nothing.
#[test]
fn an_empty_set_option_reads_and_saves_nothing() {
let mut s = session();
select(&mut s, "smooth");
let saved = s.prefs.tool_settings.clone();
assert_eq!(s.set_tool_option_cmd(&json!({})).unwrap(), s.tool_options());
assert_eq!(s.set_tool_option_cmd(&json!({"tool": "flare"})).unwrap(), s.tool_options_of("flare"));
// No params (null) read too; params that are not an object are an error.
assert_eq!(s.set_tool_option_cmd(&serde_json::Value::Null).unwrap(), s.tool_options());
for (bad, got) in [(json!(true), "true"), (json!([]), "[]")] {
assert_eq!(s.set_tool_option_cmd(&bad).unwrap_err(), format!("the params must be an object, not {got}"));
}
assert_eq!(s.prefs.tool_settings, saved);
}
/// A Place queue with a malformed entry is an error, and the queue held stays as it was.
#[test]
fn a_malformed_place_queue_is_an_error() {
let mut s = session();
select(&mut s, "place");
let entry = json!({"params": {"svg": "<svg/>"}, "name": "a", "width": 10, "height": 10});
s.set_tool_option_cmd(&json!({"key": "queue", "value": {"entries": [entry]}})).unwrap();
let bad = json!({"params": {}, "name": "b", "width": "wide", "height": 10});
let e = s.set_tool_option_cmd(&json!({"key": "queue", "value": {"entries": [entry, bad]}})).unwrap_err();
assert!(e.starts_with("tool `place`: `queue` must be"), "{e}");
assert_eq!(s.tool_options()["names"], json!(["a"]));
assert_eq!(
s.set_tool_option_cmd(&json!({"key": "current", "value": 1})).unwrap_err(),
"tool `place`: `current` must be the index of a queued file, from 0 to 0"
);
}
/// A `current` given with a new Place queue picks among the files of that queue.
#[test]
fn a_place_queue_and_its_current_file_set_together() {
let mut s = session();
select(&mut s, "place");
let entry = |name: &str| json!({"params": {"svg": "<svg/>"}, "name": name, "width": 10, "height": 10});
let queue = json!({"entries": [entry("a"), entry("b"), entry("c")]});
let out = s.set_tool_option_cmd(&json!({"values": {"queue": queue, "current": 2}})).unwrap();
assert_eq!((out["names"].clone(), out["current"].clone()), (json!(["a", "b", "c"]), json!(2)));
let short = json!({"entries": [entry("d")]});
let e = s.set_tool_option_cmd(&json!({"values": {"queue": short, "current": 2}})).unwrap_err();
assert_eq!(e, "tool `place`: `current` must be the index of a queued file, from 0 to 0");
assert_eq!(s.tool_options()["names"], json!(["a", "b", "c"]), "a refused call keeps the queue held");
}
/// A value given with a parametric shape's new `kind` is checked against that kind's range and
/// set on it, whether the tool is chosen or not.
#[test]
fn a_parametric_shape_kind_and_its_values_set_together() {
for active in [false, true] {
let mut s = session();
if active {
select(&mut s, "parametricShape");
}
let set = |s: &mut Session, values: serde_json::Value| s.set_tool_option_cmd(&json!({"tool": "parametricShape", "values": values}));
set(&mut s, json!({"kind": "polygon"})).unwrap();
let out = set(&mut s, json!({"kind": "star", "a": 0.8})).unwrap();
assert_eq!((out["kind"].clone(), out["a"].clone()), (json!("star"), json!(0.8)), "active {active}");
set(&mut s, json!({"kind": "ring"})).unwrap();
let out = set(&mut s, json!({"kind": "star", "a": 1.0})).unwrap();
assert_eq!((out["kind"].clone(), out["a"].clone()), (json!("star"), json!(1.0)), "active {active}");
let e = set(&mut s, json!({"kind": "ring", "a": 1.0})).unwrap_err();
assert!(e.contains("`a`"), "{e}");
assert_eq!(s.tool_options_of("parametricShape")["kind"], json!("star"), "a refused call sets nothing");
}
}
+118
View File
@@ -167,6 +167,124 @@ fn adjust_adjoining_scales_the_neighbours() {
assert_eq!(points(&s, id), vec![(0.5, 4.0, 1.0)]);
}
/// A line with a discontinuous point in the middle: 1× before it, 2× after it.
fn pair_session(points: serde_json::Value) -> (Session, NodeId) {
let (mut s, id) = line_session();
s.execute("stroke.widthProfile.set", &json!({"ids": [id.0], "points": points})).unwrap();
s.doc_mut().unwrap().mark_saved();
(s, id)
}
#[test]
fn paired_set_edits_both_halves_in_one_step() {
let (mut s, id) = pair_session(json!([[0, 1, 1], [0.5, 1, 1], [0.5, 2, 2], [1, 1, 1]]));
let before = s.doc().unwrap().doc.clone();
let undo = s.doc().unwrap().history.undo.len();
let p = json!({"id": id.0, "index": 1, "t": 0.5, "left": 10, "right": 5, "outIndex": 2, "outLeft": 15, "outRight": 20});
assert_eq!(set(&mut s, p.clone()), 1);
assert_eq!(points(&s, id), vec![(0.0, 1.0, 1.0), (0.5, 2.0, 1.0), (0.5, 3.0, 4.0), (1.0, 1.0, 1.0)]);
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
let after = s.doc().unwrap().doc.clone();
// The same widths again change nothing and record no undo step.
set(&mut s, p);
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc, before);
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc, after);
}
#[test]
fn paired_set_adjusts_the_point_before_and_the_point_after_once_each() {
let (mut s, id) = pair_session(json!([[0, 1, 1], [0.5, 1, 1], [0.5, 2, 2], [1, 1, 1]]));
// The incoming half doubles and the outgoing half halves: the start doubles, the end halves.
set(
&mut s,
json!({"id": id.0, "index": 1, "t": 0.5, "left": 10, "right": 10, "outIndex": 2, "outLeft": 5, "outRight": 5, "adjustAdjoining": true}),
);
assert_eq!(points(&s, id), vec![(0.0, 2.0, 2.0), (0.5, 2.0, 2.0), (0.5, 1.0, 1.0), (1.0, 0.5, 0.5)]);
// A discontinuous point at the start has only a point after it to adjust.
let (mut s, id) = pair_session(json!([[0, 1, 1], [0, 2, 2], [1, 1, 1]]));
set(
&mut s,
json!({"id": id.0, "index": 0, "t": 0, "left": 10, "right": 10, "outIndex": 1, "outLeft": 20, "outRight": 20, "adjustAdjoining": true}),
);
assert_eq!(points(&s, id), vec![(0.0, 2.0, 2.0), (0.0, 4.0, 4.0), (1.0, 2.0, 2.0)]);
}
/// Three points each within 1e-6 of the next: the first two are the pair, and the third, though
/// within 1e-6 of the outgoing half, is the point after the pair that the outgoing half adjusts.
#[test]
fn paired_set_adjusts_the_point_after_a_chained_pair() {
let (mut s, id) = pair_session(json!([[0, 1, 1], [0.5, 1, 1], [0.50000075, 2, 2], [0.5000015, 1, 1], [1, 1, 1]]));
set(
&mut s,
json!({"id": id.0, "index": 1, "t": 0.5, "left": 5, "right": 5, "outIndex": 2, "outLeft": 5, "outRight": 5, "adjustAdjoining": true}),
);
assert_eq!(points(&s, id), vec![(0.0, 1.0, 1.0), (0.5, 1.0, 1.0), (0.50000075, 1.0, 1.0), (0.5000015, 0.5, 0.5), (1.0, 1.0, 1.0)]);
}
#[test]
fn single_width_only_leaves_one_continuous_point() {
for (single, kept) in [("incoming", (2.0, 1.0)), ("outgoing", (3.0, 4.0))] {
let (mut s, id) = pair_session(json!([[0, 1, 1], [0.5, 1, 1], [0.5, 2, 2], [1, 1, 1]]));
let before = s.doc().unwrap().doc.clone();
let undo = s.doc().unwrap().history.undo.len();
let p = json!({"id": id.0, "index": 1, "t": 0.5, "left": 10, "right": 5, "outIndex": 2, "outLeft": 15, "outRight": 20, "single": single});
assert_eq!(set(&mut s, p), 1);
assert_eq!(points(&s, id), vec![(0.0, 1.0, 1.0), (0.5, kept.0, kept.1), (1.0, 1.0, 1.0)], "{single}");
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc, before);
}
// With Adjust Adjoining, each neighbor follows the change of the half beside it.
let (mut s, id) = pair_session(json!([[0, 1, 1], [0.5, 1, 1], [0.5, 2, 2], [1, 1, 1]]));
let p = json!({"id": id.0, "index": 1, "t": 0.5, "left": 5, "right": 5, "outIndex": 2, "outLeft": 5, "outRight": 5, "single": "incoming", "adjustAdjoining": true});
set(&mut s, p);
assert_eq!(points(&s, id), vec![(0.0, 1.0, 1.0), (0.5, 1.0, 1.0), (1.0, 0.5, 0.5)]);
}
#[test]
fn paired_set_refuses_what_is_not_one_discontinuous_point() {
let (mut s, id) = pair_session(json!([[0, 1, 1], [0.25, 1, 1], [0.5, 1, 1], [0.5, 2, 2], [0.75, 3, 3], [0.75, 3, 3], [0.75, 3, 3], [1, 1, 1]]));
let before = s.doc().unwrap().doc.clone();
let undo = s.doc().unwrap().history.undo.len();
let pair = |extra: serde_json::Value| {
let mut p = json!({"id": id.0, "index": 2, "t": 0.5, "left": 5, "right": 5, "outIndex": 3, "outLeft": 5, "outRight": 5});
for (k, v) in extra.as_object().unwrap() {
if v.is_null() {
p.as_object_mut().unwrap().remove(k);
} else {
p[k] = v.clone();
}
}
p
};
for p in [
pair(json!({"index": 1, "t": 0.25, "outIndex": 2})),
pair(json!({"outIndex": 4})),
pair(json!({"index": 3, "outIndex": 2})),
pair(json!({"outIndex": 99})),
pair(json!({"outIndex": "3"})),
pair(json!({"outIndex": -1})),
pair(json!({"t": 0.6})),
pair(json!({"index": 4, "t": 0.75, "outIndex": 5})),
pair(json!({"index": null})),
pair(json!({"outLeft": null})),
pair(json!({"outRight": -1})),
pair(json!({"outLeft": 1.0e6})),
pair(json!({"single": "both"})),
pair(json!({"single": true})),
pair(json!({"outIndex": null})),
pair(json!({"outIndex": null, "outLeft": null})),
json!({"id": id.0, "index": 2, "t": 0.5, "left": 5, "right": 5, "single": "incoming"}),
] {
assert!(s.execute("stroke.widthPoint.set", &p).is_err(), "accepted {p}");
assert_eq!(s.doc().unwrap().doc, before, "{p}");
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
}
}
#[test]
fn flipping_along_swaps_the_sides_of_a_discontinuous_point() {
let (mut s, id) = line_session();
+18
View File
@@ -40,6 +40,24 @@ fn the_width_tool_edits_a_compound_paths_stroke() {
assert_eq!(s.journal.last().unwrap().1["id"], json!(c.0));
}
/// A compound path whose stroke draws with a brush: a press or a double-click on a member puts the
/// tool's reason in the status bar and leaves the stroke and the undo history as they were.
#[test]
fn the_width_tool_says_why_it_leaves_a_brushed_compound_path_alone() {
let (mut s, c, _) = compound();
s.execute("brush.apply", &json!({"ids": [c.0], "name": "3 pt. Round"})).unwrap();
let steps = s.journal.len();
let v = ViewInfo::default();
s.select_tool("width", v).unwrap();
for (kind, reason) in [(PointerKind::Down, true), (PointerKind::Drag, false), (PointerKind::Up, false), (PointerKind::DoubleClick, true)] {
let ui = s.pointer(&PointerEvent::new(kind, 200.0, 301.0), v).unwrap();
let said = ui.iter().any(|r| matches!(r, UiRequest::Status(m) if m == vectorcraft_tools::distort::KEEPS_SIZE));
assert_eq!(said, reason, "{kind:?}: {ui:?}");
}
assert_eq!(profile(&s, c), None);
assert_eq!(s.journal.len(), steps, "no command ran");
}
#[test]
fn width_point_commands_given_a_member_edit_the_compound() {
let (mut s, c, members) = compound();
+122 -5
View File
@@ -480,8 +480,8 @@ fn reflect_and_shear_tools() {
assert!((b.width() - 150.0).abs() < 1e-6, "{b:?}");
}
/// Reflect and Shear return an error for an `axis` they don't take (Reflect's names it and also
/// takes an angle): nothing moves and no undo step is recorded. A null `axis` counts as not given: Reflect
/// Reflect and Shear return an error for an `axis` they don't take, naming it (both also take an
/// angle, Shear's from -359° to 359°): nothing moves and no undo step is recorded. A null `axis` counts as not given: Reflect
/// then reflects across the vertical axis and Shear shears along the horizontal one.
#[test]
fn reflect_and_shear_reject_unknown_axes_without_changing_state() {
@@ -489,13 +489,17 @@ fn reflect_and_shear_reject_unknown_axes_without_changing_state() {
let a = rect(&mut s, 10.0, 20.0, 30.0, 10.0);
let n = undo_len(&s);
let reflect = "axis must be \"vertical\", \"horizontal\" or an angle in degrees";
let shear = "`axis` must be one of horizontal, vertical";
let shear = "axis must be \"horizontal\", \"vertical\" or an angle in degrees from -359 to 359";
for (cmd, p, msg) in [
("object.reflect", json!({"axis": "diagonal", "origin": [0, 0]}), format!("{reflect}, not `diagonal`")),
("object.reflect", json!({"axis": "45", "origin": [0, 0]}), format!("{reflect}, not `45`")),
("object.reflect", json!({"axis": true, "origin": [0, 0]}), format!("{reflect}, not `true`")),
("object.shear", json!({"angle": 30, "axis": "diagonal"}), shear.to_string()),
("object.shear", json!({"angle": 30, "axis": 90}), shear.to_string()),
("object.shear", json!({"angle": 30, "axis": "diagonal"}), format!("{shear}, not `diagonal`")),
("object.shear", json!({"angle": 30, "axis": "90"}), format!("{shear}, not `90`")),
("object.shear", json!({"angle": 30, "axis": 360}), format!("{shear}, not `360`")),
("object.shear", json!({"angle": 30, "axis": -359.5}), format!("{shear}, not `-359.5`")),
("object.shear", json!({"angle": 30, "axis": [45]}), format!("{shear}, not `[45]`")),
("object.shear", json!({"angle": 30, "axis": false}), format!("{shear}, not `false`")),
] {
let e = s.execute(cmd, &p).expect_err(&format!("{cmd} {p}"));
assert_eq!(e.to_string(), format!("invalid parameters for `{cmd}`: {msg}"));
@@ -511,6 +515,119 @@ fn reflect_and_shear_reject_unknown_axes_without_changing_state() {
assert!((b.y0 + 30.0).abs() < 1e-6 && (b.y1 + 20.0).abs() < 1e-6 && b.width() > 30.0, "along the horizontal axis: {b:?}");
}
/// Shear takes an angle from -359 to 359 degrees and shears by its tangent: 60 and -60 slant
/// opposite ways, and 120 and 300 slant as -60 does.
#[test]
fn shear_angles_slant_by_their_tangent() {
let run = 100.0 * 60f64.to_radians().tan();
for (angle, want) in [
(60.0, Rect::new(-run, 0.0, 100.0, 100.0)),
(-60.0, Rect::new(0.0, 0.0, 100.0 + run, 100.0)),
(120.0, Rect::new(0.0, 0.0, 100.0 + run, 100.0)),
(300.0, Rect::new(0.0, 0.0, 100.0 + run, 100.0)),
(-359.0, Rect::new(-100.0 * 1f64.to_radians().tan(), 0.0, 100.0, 100.0)),
] {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
s.execute("object.shear", &json!({"angle": angle, "origin": [0, 0]})).unwrap();
assert!(close(bounds(&s, a), want), "{angle}: {:?}, want {want:?}", bounds(&s, a));
}
}
/// Shear returns an error for an angle outside -359 to 359 and for ±90 and ±270, which have no
/// finite shear (within a billionth of a degree too); nothing moves and no undo step is recorded.
#[test]
fn shear_rejects_angles_with_no_shear_or_out_of_range() {
let mut s = session();
let a = rect(&mut s, 10.0, 20.0, 30.0, 10.0);
let n = undo_len(&s);
let none = |v: f64| format!("invalid parameters for `object.shear`: `angle` cannot be {v}: ±90 and ±270 degrees have no shear");
let range = |v: f64| format!("invalid parameters for `object.shear`: `angle` must be from -359 to 359 degrees, not {v}");
for (angle, msg) in [
(90.0, none(90.0)),
(-90.0, none(-90.0)),
(270.0, none(270.0)),
(-270.0, none(-270.0)),
(90.0 + 1e-12, none(90.0 + 1e-12)),
(360.0, range(360.0)),
(-359.5, range(-359.5)),
(1e300, range(1e300)),
] {
let e = s.execute("object.shear", &json!({"angle": angle})).expect_err(&angle.to_string());
assert_eq!(e.to_string(), msg);
}
assert!(s.execute("object.shear", &json!({"angle": "45"})).is_err(), "a string is not an angle");
assert!(close(bounds(&s, a), Rect::new(10.0, 20.0, 40.0, 30.0)), "nothing moved: {:?}", bounds(&s, a));
assert_eq!(undo_len(&s), n, "no undo step");
}
/// Shear by 0, 180 or -180 degrees, along either axis, has no slant: the art keeps its exact
/// coordinates and no undo step is recorded.
#[test]
fn shear_by_0_and_180_changes_nothing() {
let mut s = session();
let a = rect(&mut s, 10.0, 20.0, 30.0, 10.0);
let before = bounds(&s, a);
let n = undo_len(&s);
for angle in [180.0, -180.0, 0.0, 180.0 + 1e-12, -180.0 - 1e-12] {
for axis in ["horizontal", "vertical"] {
s.execute("object.shear", &json!({"angle": angle, "axis": axis})).unwrap();
assert_eq!(bounds(&s, a), before, "{angle} {axis}");
assert_eq!(undo_len(&s), n, "{angle} {axis}: no undo step");
}
}
}
/// Shear along an axis at an angle, counter-clockwise from horizontal on the page: each point
/// slides along the axis by the tangent of the shear angle times its distance across the axis
/// from the origin. -359° and 359° are taken, the shear is one undo step and Transform Again
/// repeats it; 0° and 90° shear as the named axes do, and a copy leaves the original in place.
#[test]
fn shear_along_an_axis_at_an_angle() {
let anchors = |s: &Session, id: NodeId| -> Vec<Point> {
s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().anchors().map(|(_, _, an)| an.p).collect()
};
// The axis's direction and the direction a quarter turn counter-clockwise from it, with y down.
let sheared = |p: Point, o: Point, axis: f64, angle: f64| {
let (a, k) = (axis.to_radians(), angle.to_radians().tan());
let (along, across) = (Vec2::new(a.cos(), -a.sin()), Vec2::new(-a.sin(), -a.cos()));
p + along * (k * (p - o).dot(across))
};
let near = |a: &[Point], b: &[Point]| a.len() == b.len() && a.iter().zip(b).all(|(p, q)| p.distance(*q) < 1e-9);
let o = Point::new(20.0, 30.0);
for (axis, angle) in [(45.0, 30.0), (-120.5, 20.0), (359.0, 30.0), (-359.0, -30.0), (30.0, 30.0)] {
let mut s = session();
let a = rect(&mut s, 100.0, 100.0, 60.0, 20.0);
let before = anchors(&s, a);
let n = undo_len(&s);
s.execute("object.shear", &json!({"angle": angle, "axis": axis, "origin": [o.x, o.y]})).unwrap();
let want: Vec<Point> = before.iter().map(|p| sheared(*p, o, axis, angle)).collect();
assert!(near(&anchors(&s, a), &want), "{axis}° {angle}°: {:?}, not {want:?}", anchors(&s, a));
assert_eq!(undo_len(&s), n + 1, "one undo step");
s.execute("object.transformAgain", &json!({})).unwrap();
let again: Vec<Point> = want.iter().map(|p| sheared(*p, o, axis, angle)).collect();
assert!(near(&anchors(&s, a), &again), "Transform Again at {axis}°: {:?}", anchors(&s, a));
}
for (named, axis) in [("horizontal", 0.0), ("vertical", 90.0), ("vertical", -270.0)] {
let mut s = session();
let a = rect(&mut s, 100.0, 100.0, 60.0, 20.0);
s.execute("object.shear", &json!({"angle": 30, "axis": named, "origin": [o.x, o.y]})).unwrap();
let by_name = anchors(&s, a);
s.execute("edit.undo", &json!({})).unwrap();
s.execute("object.shear", &json!({"angle": 30, "axis": axis, "origin": [o.x, o.y]})).unwrap();
assert!(near(&anchors(&s, a), &by_name), "{axis}° shears as {named}: {:?}, not {by_name:?}", anchors(&s, a));
}
let mut s = session();
let a = rect(&mut s, 100.0, 100.0, 60.0, 20.0);
let before = anchors(&s, a);
s.execute("object.shear", &json!({"angle": 30, "axis": 45, "origin": [o.x, o.y], "copy": true})).unwrap();
assert!(near(&anchors(&s, a), &before), "the original stays: {:?}", anchors(&s, a));
let copy = *s.doc().unwrap().selection.objects.first().unwrap();
assert_ne!(copy, a, "the copy is selected");
let want: Vec<Point> = before.iter().map(|p| sheared(*p, o, 45.0, 30.0)).collect();
assert!(near(&anchors(&s, copy), &want), "the copy is sheared: {:?}", anchors(&s, copy));
}
#[test]
fn distort_command_maps_corners() {
let mut s = session();
+45 -15
View File
@@ -1321,7 +1321,14 @@ impl Session {
/// The options of tool `id`: the active tool's, or those it would have if chosen now.
pub fn tool_options_of(&self, id: &str) -> Value {
if id == self.tool.id() { self.tool.options() } else { self.make_tool(id).options() }
if id == self.tool.id() {
self.tool.options()
} else if let Some(lender) = self.lender.as_deref().filter(|l| l.id() == id) {
// The tool that lent a selection tool for a Cmd-drag holds its options while it waits.
lender.options()
} else {
self.make_tool(id).options()
}
}
/// Set options of tool `id` (default: the active tool). Another tool's persistent options are
@@ -1333,14 +1340,22 @@ impl Session {
self.note_place_queue_roots();
}
let active = id.is_none_or(|id| id == self.tool.id());
self.tool_set_since_reset |= active;
// The tool that lent a selection tool for a Cmd-drag is the tool chosen, and active again
// when the drag ends.
let lender = id.is_some_and(|id| self.lender.as_deref().is_some_and(|l| l.id() == id));
self.tool_set_since_reset |= active || lender;
// The Place queue and a parametric shape's kind are set first: setting the queue starts
// again at its first file, and a `current` given with it is an index into it; setting the
// kind puts the shape's other numbers back to that kind's, and those given with it are its.
let first = |k: &str| k == "queue" || k == "kind";
let ordered = || values.iter().filter(|(k, _)| first(k)).chain(values.iter().filter(|(k, _)| !first(k)));
let mut other = (!active).then(|| self.make_tool(id.unwrap_or_default()));
let t = other.as_deref_mut().unwrap_or(self.tool.as_mut());
for (k, v) in values {
for (k, v) in ordered() {
t.set_option(k, v);
}
Self::store_tool_settings(&mut self.prefs, t);
let out = t.options();
let mut out = t.options();
if let Some(other) = other {
// The tool that lent a selection tool for a Cmd-drag is kept aside, not made again when
// it is back: when it is the tool set, it takes the writes too (the Rounded Rectangle's
@@ -1348,11 +1363,14 @@ impl Session {
// active tool.
if let Some(lender) = self.lender.as_deref_mut() {
if lender.id() == other.id() {
for (k, v) in values {
for (k, v) in ordered() {
lender.set_option(k, v);
}
}
Self::restore_tool_settings(&self.prefs, lender);
if lender.id() == other.id() {
out = lender.options();
}
}
// Only the stores it shares with the tool set: the active tool's own options stay as they
// are, also in the middle of a drag that Escape can cancel.
@@ -1364,21 +1382,28 @@ impl Session {
/// `tool.setOption {tool?, key?, value?, values?}` (a command of the desktop app and of the
/// headless host): set one option (`key`, `value`) or several (`values`) of `tool` (default:
/// the active tool) → its options.
/// the tool active when the call arrives, named before the edit in progress is finished) → its
/// options. With no option given, the options are read and nothing is set. Parameters that are
/// not an object are an error; none (null) read the options. Every option given is checked
/// first ([`vectorcraft_tools::Tool::check_option`]): an unknown option, a value of the wrong
/// type or a number out of range is an error that sets none of them.
pub fn set_tool_option_cmd(&mut self, p: &Value) -> std::result::Result<Value, String> {
let tool = p.get("tool").and_then(Value::as_str);
let (tool, values) = vectorcraft_tools::option_check::set_option_params(p)?;
if let Some(t) = tool
&& vectorcraft_tools::tool_info(t).is_none()
{
return Err(format!("unknown tool `{t}`"));
}
let mut values = p.get("values").and_then(Value::as_object).cloned().unwrap_or_default();
if let Some(k) = p.get("key").and_then(Value::as_str) {
values.insert(k.to_string(), p.get("value").cloned().unwrap_or(Value::Null));
// The tool is named before the edit in progress is finished: finishing it can make a held
// Cmd press, which lends a selection tool and makes that the active tool.
let id = tool.unwrap_or(self.tool.id());
let active = id == self.tool.id();
if values.is_empty() {
return Ok(self.tool_options_of(id));
}
// Every value is checked before any is set, so an invalid one changes nothing.
vectorcraft_tools::builder::check_builder_options(tool.unwrap_or(self.tool.id()), &values)?;
if tool.unwrap_or(self.tool.id()) == vectorcraft_tools::cropimage::ID {
vectorcraft_tools::builder::check_builder_options(id, &values)?;
if id == vectorcraft_tools::cropimage::ID {
use vectorcraft_tools::cropimage as crop;
// The most the selected image can be cropped to, when one is selected.
let max = self.doc().ok().and_then(|st| {
@@ -1397,7 +1422,7 @@ impl Session {
crate::file_access::check_read(path)?;
}
}
if tool.unwrap_or(self.tool_id()) == "dimension" {
if id == "dimension" {
if let Some(style) = values.get("style") {
vectorcraft_doc::dimension::DimensionOptions::from_params(style.clone())?;
}
@@ -1407,11 +1432,16 @@ impl Session {
return Err("Unknown dimension mode".into());
}
}
if active {
vectorcraft_tools::option_check::check_values(self.tool.as_ref(), &values)?;
} else {
vectorcraft_tools::option_check::check_values(self.make_tool(id).as_ref(), &values)?;
}
// The active tool's merge being computed is applied with the options it was started with.
if tool.is_none_or(|t| t == self.tool.id()) {
if active {
self.finish_tool_edit_later().map_err(|e| e.to_string())?;
}
Ok(self.set_tool_options(tool, &values))
Ok(self.set_tool_options(Some(id), &values))
}
/// Let the active tool finish work a command from outside it ended ([`vectorcraft_tools::Tool::after_command`]):