mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-30 02:07:10 +01:00
Merge main (8fcadbc3c) into fix/6983-followup-page-widths-pick-font-copy
Conflicts in docs only (status lines, changelog rows and table rows): main's entries and this branch's are both kept, each once. Main now has this branch's first File formats row fix (#868) itself. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
6eca4e8cce
155 files changed
+11749
-666
No files matched your search
@@ -32,6 +32,7 @@ pub mod expand;
|
||||
pub(crate) mod fileinfo;
|
||||
pub mod fileio;
|
||||
pub mod findfiles;
|
||||
pub mod flare;
|
||||
pub mod flatten;
|
||||
pub mod fontfiles;
|
||||
mod fonts;
|
||||
@@ -885,7 +886,8 @@ pub use compoundshape::OPEN_PATHS_ADD_NO_AREA;
|
||||
/// Pathfinder Options (`Prefs::pathfinder`).
|
||||
pub use pathops::{PATHFINDER_PRECISION_RANGE, PathfinderOptions};
|
||||
|
||||
/// The Attributes panel's state ([`Session::attributes_info`]).
|
||||
/// The Attributes panel's state ([`Session::attributes_info`]) and how many recent URLs it keeps.
|
||||
pub use attributes::RECENT_URLS;
|
||||
pub use overprint::AttributesInfo;
|
||||
|
||||
/// Object → Flatten Transparency settings (`object.flattenTransparency`).
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Smooth Bridge: two selected circles joined into one outline by two concave arcs that touch both
|
||||
//! circles, replacing the circles or added above them.
|
||||
//! circles, or three or more each joined the same way to the others within reach and united where
|
||||
//! the bridges connect, replacing the circles or added above them.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{NodeId, NodeKind};
|
||||
@@ -20,6 +21,12 @@ 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);
|
||||
/// The gap (pt) added to the smaller circle's radius to give the arcs' radius: the range.
|
||||
const GAPS: (f64, f64) = (0.0, 1000.0);
|
||||
/// How far apart (pt) the outlines of two of three or more circles may be for a bridge between
|
||||
/// them: by default, and the range.
|
||||
const REACH: f64 = 10.0;
|
||||
const REACHES: (f64, f64) = (0.0, 10000.0);
|
||||
|
||||
pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
@@ -27,16 +34,33 @@ pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
"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}",
|
||||
"{radius?: % 1..1000 (100; the radius of each bridge's two arcs as a percentage of the smaller circle's radius: larger makes a wider, gentler bridge), gap?: pt 0..1000 (instead of radius: the arcs' radius is the smaller circle's radius plus this gap, so each arc stays this gap away from a circle of the smaller circle's size about the arc's center; for equal circles this gap apart that is where a third circle this gap from both sits, as in a triangular grid, so the channels around an empty place in such a grid are one width; giving both is an error), reach?: pt 0..10000 (10; with three or more circles: how far apart two circles' outlines may be for a bridge between them, overlapping ones included; two circles are bridged at any distance), keepOriginals?: bool (false: each outline replaces its circles, painted as the topmost of them; true: it goes directly above that circle and the circles stay), ids?: [id] (default: the selection)} join circles (paths whose outline is a circle, not hidden or locked) into metaball (aka meatball) shapes. Two circles become 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. With three or more, every two circles within reach are bridged the same way, and the bridges that connect are united into one shape each (holes smaller than 1% of the smallest circle's area are filled); a pair within reach but too far apart for the radius gets no bridge, and so does one whose neck would be thinner than the precision its shape is united at, and a circle bridged to no other is left as it is. Overlapping and touching circles are joined too. One circle inside another (among three or more, any such pair within reach) is an error; so are two circles too far apart for the radius (the arcs would not reach both, or would cross), or three or more with no pair the arcs can join, which suggests a larger radius or gap when the largest one would bridge them; so are no two circles within reach, more than 2000 circles and more than 8000 bridges. One undo step; the outlines (and the circles left as they are) are selected → {ids, alone}, with {id} too for two circles",
|
||||
has_selection,
|
||||
bridge
|
||||
)]
|
||||
}
|
||||
|
||||
fn bridge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let percent = given(p, "radius", Some(RADII), C)?.unwrap_or(RADIUS);
|
||||
let percent = given(p, "radius", Some(RADII), C)?;
|
||||
let gap = given(p, "gap", Some(GAPS), C)?;
|
||||
let reach = given(p, "reach", Some(REACHES), C)?.unwrap_or(REACH);
|
||||
if percent.is_some() && gap.is_some() {
|
||||
// As the parameter check words it (`EXCLUSIVE_KEYS`), for a caller that skips that check.
|
||||
let (key, other) = ("radius", "gap");
|
||||
return Err(bad(C, format!("give `{key}` or `{other}`, not both")));
|
||||
}
|
||||
let arc = match gap {
|
||||
Some(gap) => pt::ArcRadius::Gap(gap),
|
||||
None => pt::ArcRadius::Share(percent.unwrap_or(RADIUS) / 100.0),
|
||||
};
|
||||
let keep = switch_or(p, "keepOriginals", false, C)?;
|
||||
let roots = checked_ids_or_selection(s, p, C)?;
|
||||
let mut roots = checked_ids_or_selection(s, p, C)?;
|
||||
// An id given twice is one circle.
|
||||
roots.sort_unstable();
|
||||
roots.dedup();
|
||||
if roots.len() > pt::MAX_BRIDGED_CIRCLES {
|
||||
return Err(bad(C, "select at most 2000 circles to bridge"));
|
||||
}
|
||||
let circles: Vec<(NodeId, pt::Circle)> = {
|
||||
let d = &s.doc()?.doc;
|
||||
let editable = d.editable();
|
||||
@@ -48,48 +72,93 @@ fn bridge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
})
|
||||
.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"));
|
||||
if circles.len() != roots.len() || circles.len() < 2 {
|
||||
return Err(bad(C, "select two or more circles to bridge"));
|
||||
}
|
||||
let only: Vec<pt::Circle> = circles.iter().map(|(_, c)| *c).collect();
|
||||
// Each shape: the circles it joins, in paint order, and its outline.
|
||||
let (shapes, alone): (Vec<(Vec<NodeId>, PathData)>, Vec<NodeId>) = match only.as_slice() {
|
||||
[a, b] => match pt::smooth_bridge(*a, *b, arc.between(*a, *b)) {
|
||||
Ok(sp) => (vec![(roots_of(&circles, &[0, 1]), PathData::single(sp))], vec![]),
|
||||
Err(e) => return Err(refusal(e, arc, |largest| pt::smooth_bridge(*a, *b, largest.between(*a, *b)).is_ok())),
|
||||
},
|
||||
_ => {
|
||||
let made = pt::bridge_many(&only, arc, reach).map_err(|e| match e {
|
||||
pt::ManyError::TooManyCircles => bad(C, "select at most 2000 circles to bridge"),
|
||||
pt::ManyError::TooManyBridges => bad(C, "that makes too many bridges (at most 8000): lower the reach"),
|
||||
pt::ManyError::NoneInReach => bad(C, "no two circles are within reach: raise the reach"),
|
||||
pt::ManyError::TooComplex => bad(C, "the bridged circles are too complex to unite"),
|
||||
// Under the many-circle rules: a pair the largest radius or gap bridges on its own
|
||||
// can still have a neck too thin to unite among the others.
|
||||
pt::ManyError::Pair(_, _, e) => refusal(e, arc, |largest| pt::bridges_any(&only, largest, reach)),
|
||||
pt::ManyError::Bad => bad(C, "select two or more circles to bridge"),
|
||||
})?;
|
||||
let shapes = made.joined.into_iter().map(|j| (roots_of(&circles, &j.members), j.outline)).collect();
|
||||
(shapes, roots_of(&circles, &made.alone))
|
||||
}
|
||||
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 made = s.edit(LABEL, |d, sel| {
|
||||
let mut made = Vec::with_capacity(shapes.len());
|
||||
if keep {
|
||||
// A copy of each shape's topmost circle (its appearance) with the outline as its path,
|
||||
// right above it; the circles stay as they are, live shapes included. Fresh ids
|
||||
// throughout, an opacity mask's art included.
|
||||
let tops: Vec<NodeId> = shapes.iter().filter_map(|(members, _)| members.last().copied()).collect();
|
||||
let mut beside = Beside::above(d, &tops);
|
||||
for ((_, outline), top) in shapes.into_iter().zip(tops) {
|
||||
let upper = d.node(top).cloned().ok_or(EngineError::NoNode(top))?;
|
||||
let mut n = d.reid(&upper);
|
||||
if let NodeKind::Path { path, live, .. } = &mut n.kind {
|
||||
*path = outline;
|
||||
*live = None;
|
||||
}
|
||||
made.push(n.id);
|
||||
beside.put(d, top, vec![n])?;
|
||||
}
|
||||
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;
|
||||
// Each shape's topmost circle becomes its outline (a plain path now) and the others go.
|
||||
let mut gone = vec![];
|
||||
for (members, outline) in shapes {
|
||||
let Some((&top, rest)) = members.split_last() else { continue };
|
||||
if let Some(NodeKind::Path { path, live, .. }) = d.node_mut(top).map(|n| &mut n.kind) {
|
||||
*path = outline;
|
||||
*live = None;
|
||||
}
|
||||
made.push(top);
|
||||
gone.extend_from_slice(rest);
|
||||
}
|
||||
remove_each(d, &[below])?;
|
||||
above
|
||||
};
|
||||
sel.set([id]);
|
||||
Ok(id)
|
||||
remove_each(d, &gone)?;
|
||||
}
|
||||
sel.set(made.iter().chain(&alone).copied());
|
||||
Ok(made)
|
||||
})?;
|
||||
Ok(json!({ "id": id.0 }))
|
||||
let mut out = json!({ "ids": made.iter().map(|id| id.0).collect::<Vec<_>>(), "alone": alone.iter().map(|id| id.0).collect::<Vec<_>>() });
|
||||
if let ([id], 2) = (made.as_slice(), only.len()) {
|
||||
out["id"] = json!(id.0);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The ids of `circles` at indices `at`, in paint order (the circles are listed in paint order).
|
||||
fn roots_of(circles: &[(NodeId, pt::Circle)], at: &[usize]) -> Vec<NodeId> {
|
||||
at.iter().filter_map(|&i| circles.get(i)).map(|(id, _)| *id).collect()
|
||||
}
|
||||
|
||||
/// The error for circles that arcs of `arc` can't bridge. A larger radius or gap bridges circles a
|
||||
/// smaller one cannot, so it suggests one only when `bridges` says the largest allowed would.
|
||||
fn refusal(e: pt::BridgeError, arc: pt::ArcRadius, bridges: impl FnOnce(pt::ArcRadius) -> bool) -> EngineError {
|
||||
let largest = match arc {
|
||||
pt::ArcRadius::Share(_) => pt::ArcRadius::Share(RADII.1 / 100.0),
|
||||
pt::ArcRadius::Gap(_) => pt::ArcRadius::Gap(GAPS.1),
|
||||
};
|
||||
let would = e == pt::BridgeError::TooFar && bridges(largest);
|
||||
match (e, arc, would) {
|
||||
(pt::BridgeError::Inside, ..) => bad(C, "one circle is inside the other"),
|
||||
(pt::BridgeError::TooFar, pt::ArcRadius::Share(_), true) => bad(C, "the circles are too far apart for this radius: raise the radius"),
|
||||
(pt::BridgeError::TooFar, pt::ArcRadius::Share(_), false) => bad(C, "the circles are too far apart for this radius"),
|
||||
(pt::BridgeError::TooFar, pt::ArcRadius::Gap(_), true) => bad(C, "the circles are too far apart for this gap: raise the gap"),
|
||||
(pt::BridgeError::TooFar, pt::ArcRadius::Gap(_), false) => bad(C, "the circles are too far apart for this gap"),
|
||||
(pt::BridgeError::Bad, ..) => bad(C, "select two or more circles to bridge"),
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Smooth Bridge: the outline in place of the circles or above them, one undo step, the radius,
|
||||
//! and what it refuses.
|
||||
//! Smooth Bridge: the outline in place of the circles or above them, one undo step, the radius or
|
||||
//! gap, many circles joined to their neighbors within reach, and what it refuses.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{NodeId, NodeKind};
|
||||
@@ -46,6 +46,8 @@ fn two_circles_become_one_outline_in_the_upper_ones_place() {
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
let r = s.execute(BRIDGE, &json!({})).unwrap();
|
||||
assert_eq!(r["id"], json!(b.0));
|
||||
assert_eq!(r["ids"], json!([b.0]), "the same result fields as for more circles");
|
||||
assert_eq!(r["alone"], json!([]));
|
||||
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") };
|
||||
@@ -158,9 +160,11 @@ fn far_apart_nested_and_other_objects_are_refused() {
|
||||
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}");
|
||||
for ids in [json!([a.0, square.0]), json!([a.0, oval.0]), json!([a.0]), json!([a.0, far.0, square.0])] {
|
||||
assert!(err(&mut s, json!({ "ids": ids })).contains("select two or more circles to bridge"), "{ids}");
|
||||
}
|
||||
// Three circles: each two within reach are bridged, and one inside another is refused there too.
|
||||
assert!(err(&mut s, json!({"ids": [a.0, far.0, inner.0]})).contains("one circle is inside the other"));
|
||||
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"));
|
||||
@@ -169,6 +173,174 @@ fn far_apart_nested_and_other_objects_are_refused() {
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "nothing changed, no undo step");
|
||||
}
|
||||
|
||||
/// A 3 × 3 grid of circles of radius 10, 4 apart (centers 24 apart), in rows from (100, 100).
|
||||
fn grid(s: &mut Session) -> Vec<NodeId> {
|
||||
(0..9).map(|k| circle(s, 100.0 + 24.0 * (k % 3) as f64, 100.0 + 24.0 * (k / 3) as f64, 10.0)).collect()
|
||||
}
|
||||
|
||||
fn ids(v: &Value) -> Vec<NodeId> {
|
||||
v.as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect()
|
||||
}
|
||||
|
||||
fn path(s: &Session, id: NodeId) -> vectorcraft_geom::PathData {
|
||||
s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_grid_of_circles_joins_each_to_its_neighbors_in_one_shape() {
|
||||
let mut s = session();
|
||||
let g = grid(&mut s);
|
||||
select(&mut s, &g);
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
// Reach 5: the side neighbors (4 apart) are bridged, the diagonal ones (about 13.9 apart) not.
|
||||
let r = s.execute(BRIDGE, &json!({"gap": 4, "reach": 5})).unwrap();
|
||||
assert_eq!(ids(&r["ids"]), [g[8]], "one shape, in the topmost circle's place");
|
||||
assert_eq!(ids(&r["alone"]), []);
|
||||
assert_eq!(top_level(&s), [g[8]]);
|
||||
assert_eq!(s.doc().unwrap().selection.objects.to_vec(), [g[8]]);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "one undo step");
|
||||
// Its outline and a hole in each square of four circles, which no diagonal bridge fills.
|
||||
let outline = path(&s, g[8]);
|
||||
assert_eq!(outline.subpaths.len(), 5, "{}", outline.subpaths.len());
|
||||
let inside = |p: &vectorcraft_geom::PathData, x: f64, y: f64| p.to_bezpath().winding(vectorcraft_geom::kurbo::Point::new(x, y)) != 0;
|
||||
assert!(inside(&outline, 112.0, 100.0) && inside(&outline, 100.0, 112.0) && !inside(&outline, 112.0, 112.0));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(top_level(&s), g);
|
||||
// Reach 15 takes in the diagonal neighbors, whose bridges fill the middle of each square.
|
||||
select(&mut s, &g);
|
||||
s.execute(BRIDGE, &json!({"gap": 4, "reach": 15})).unwrap();
|
||||
let outline = path(&s, g[8]);
|
||||
assert_eq!(outline.subpaths.len(), 1);
|
||||
assert!(inside(&outline, 112.0, 112.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_circle_with_no_neighbor_in_reach_stays_as_it_is() {
|
||||
let mut s = session();
|
||||
let g = grid(&mut s);
|
||||
let far = circle(&mut s, 300.0, 250.0, 10.0);
|
||||
let pair = [circle(&mut s, 300.0, 40.0, 8.0), circle(&mut s, 320.0, 40.0, 8.0)];
|
||||
let mut all = g.clone();
|
||||
all.extend([far, pair[0], pair[1]]);
|
||||
let r = s.execute(BRIDGE, &json!({"ids": all.iter().map(|i| i.0).collect::<Vec<_>>(), "reach": 5})).unwrap();
|
||||
assert_eq!(ids(&r["ids"]), [g[8], pair[1]]);
|
||||
assert_eq!(ids(&r["alone"]), [far]);
|
||||
assert_eq!(top_level(&s), [g[8], far, pair[1]]);
|
||||
assert!(matches!(&s.doc().unwrap().doc.node(far).unwrap().kind, NodeKind::Path { live: Some(_), .. }), "untouched");
|
||||
let mut selected = s.doc().unwrap().selection.objects.to_vec();
|
||||
selected.sort();
|
||||
let mut want = vec![g[8], pair[1], far];
|
||||
want.sort();
|
||||
assert_eq!(selected, want, "the shapes and the circle left alone");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keep_originals_adds_each_shape_above_its_topmost_circle() {
|
||||
let mut s = session();
|
||||
let row: Vec<NodeId> = (0..3).map(|i| circle(&mut s, 100.0 + 25.0 * i as f64, 100.0, 10.0)).collect();
|
||||
let other = [circle(&mut s, 100.0, 200.0, 10.0), circle(&mut s, 122.0, 200.0, 10.0)];
|
||||
s.execute("paint.setFill", &json!({"ids": [row[2].0], "color": "#00ff00"})).unwrap();
|
||||
let all: Vec<u64> = row.iter().chain(&other).map(|i| i.0).collect();
|
||||
let r = s.execute(BRIDGE, &json!({"ids": all, "keepOriginals": true})).unwrap();
|
||||
let made = ids(&r["ids"]);
|
||||
assert_eq!(made.len(), 2);
|
||||
assert_eq!(top_level(&s), [row[0], row[1], row[2], made[0], other[0], other[1], made[1]]);
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.node(made[0]).unwrap().appearance, d.node(row[2]).unwrap().appearance, "painted as the topmost circle");
|
||||
let b = d.node(made[0]).unwrap().path_data().unwrap().bounds().unwrap();
|
||||
assert!((b.x0 - 90.0).abs() < 1e-2 && (b.x1 - 160.0).abs() < 1e-2, "{b:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_gap_form_gives_arcs_the_smaller_radius_plus_the_gap() {
|
||||
let area_with = |p: Value| {
|
||||
let mut s = session();
|
||||
let a = circle(&mut s, 100.0, 100.0, 10.0);
|
||||
let b = circle(&mut s, 124.0, 100.0, 10.0);
|
||||
let mut p = p;
|
||||
p["ids"] = json!([a.0, b.0]);
|
||||
let id = NodeId(s.execute(BRIDGE, &p).unwrap()["id"].as_u64().unwrap());
|
||||
area(&s, id)
|
||||
};
|
||||
// Radius 10 plus a gap of 4 is 140% of 10.
|
||||
let (gap, percent) = (area_with(json!({"gap": 4})), area_with(json!({"radius": 140})));
|
||||
assert!((gap - percent).abs() < 1e-9, "{gap} {percent}");
|
||||
assert!(area_with(json!({"gap": 0})) < gap && gap < area_with(json!({"gap": 20})));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn many_circle_and_gap_refusals() {
|
||||
let mut s = session();
|
||||
let a = circle(&mut s, 50.0, 100.0, 10.0);
|
||||
let b = circle(&mut s, 250.0, 100.0, 10.0);
|
||||
let c = circle(&mut s, 330.0, 100.0, 10.0);
|
||||
let far = circle(&mut s, 380.0, 100.0, 10.0);
|
||||
let before = top_level(&s);
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
assert!(err(&mut s, json!({"ids": [a.0, b.0], "radius": 100, "gap": 4})).contains("give `radius` or `gap`, not both"));
|
||||
// Centers 200 apart: a gap of 0 does not bridge them, the largest (1000 pt) does. With centers
|
||||
// 330 apart even that one closes the neck: it stays open only below 2 × √(10² + 2 × 10 × 1010)
|
||||
// ≈ 285.
|
||||
assert!(err(&mut s, json!({"ids": [a.0, b.0], "gap": 0})).ends_with("too far apart for this gap: raise the gap"));
|
||||
assert!(err(&mut s, json!({"ids": [a.0, far.0], "gap": 0})).ends_with("the circles are too far apart for this gap"));
|
||||
assert!(err(&mut s, json!({"ids": [a.0, b.0, c.0], "reach": 5})).contains("no two circles are within reach: raise the reach"));
|
||||
// b and c are 60 apart: within a reach of 100, but too far for the default radius.
|
||||
assert!(err(&mut s, json!({"ids": [a.0, b.0, c.0], "reach": 100})).ends_with("too far apart for this radius: raise the radius"));
|
||||
assert!(err(&mut s, json!({"ids": [a.0, b.0, c.0], "reach": -1})).contains("`reach` must be from 0 to 10000"));
|
||||
assert!(err(&mut s, json!({"ids": [a.0, b.0], "gap": 1001})).contains("`gap` must be from 0 to 1000"));
|
||||
assert_eq!(top_level(&s), before);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "nothing changed, no undo step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_larger_radius_is_suggested_only_when_it_bridges_among_the_other_circles() {
|
||||
let mut s = session();
|
||||
// Centers 91.65 apart: the largest radius (1000%, 100 pt) bridges these two on their own, but
|
||||
// with a neck about 0.0007 pt wide, too thin to unite among three or more circles.
|
||||
let a = circle(&mut s, 20.0, 100.0, 10.0);
|
||||
let b = circle(&mut s, 111.65, 100.0, 10.0);
|
||||
let far = circle(&mut s, 380.0, 100.0, 10.0);
|
||||
assert!(s.execute(BRIDGE, &json!({"ids": [a.0, b.0], "radius": 1000})).is_ok());
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(err(&mut s, json!({"ids": [a.0, b.0]})).ends_with("too far apart for this radius: raise the radius"));
|
||||
for radius in [100, 1000] {
|
||||
let e = err(&mut s, json!({"ids": [a.0, b.0, far.0], "radius": radius, "reach": 100}));
|
||||
assert!(e.ends_with("the circles are too far apart for this radius"), "{e}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn too_many_circles_or_bridges_are_refused() {
|
||||
let mut s = session();
|
||||
// 130 overlapping circles in a row: 8,385 pairs within reach.
|
||||
let row: Vec<u64> = (0..130).map(|i| circle(&mut s, 20.0 + i as f64 * 0.2, 100.0, 10.0).0).collect();
|
||||
assert!(err(&mut s, json!({ "ids": row })).contains("that makes too many bridges (at most 8000): lower the reach"));
|
||||
let many: Vec<u64> = (0..2001).map(|i| circle(&mut s, 20.0 + (i % 50) as f64 * 7.0, 150.0 + (i / 50) as f64 * 3.0, 1.0).0).collect();
|
||||
assert!(err(&mut s, json!({ "ids": many })).contains("select at most 2000 circles to bridge"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_id_given_twice_is_one_circle() {
|
||||
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 r = s.execute(BRIDGE, &json!({"ids": [a.0, a.0, b.0]})).unwrap();
|
||||
assert_eq!(r["id"], json!(b.0), "two circles, bridged");
|
||||
assert_eq!(top_level(&s), [b]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn small_circles_at_the_default_reach_bridge_the_pairs_the_arcs_can_join() {
|
||||
let mut s = session();
|
||||
// Radius 3: arcs of 3 pt (100%) join a and b (2 apart) but close before reaching c (6 from b,
|
||||
// within the default reach of 10).
|
||||
let (a, b, c) = (circle(&mut s, 100.0, 100.0, 3.0), circle(&mut s, 108.0, 100.0, 3.0), circle(&mut s, 120.0, 100.0, 3.0));
|
||||
let r = s.execute(BRIDGE, &json!({"ids": [a.0, b.0, c.0]})).unwrap();
|
||||
assert_eq!(ids(&r["ids"]), [b]);
|
||||
assert_eq!(ids(&r["alone"]), [c]);
|
||||
assert_eq!(top_level(&s), [b, c]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locked_and_hidden_circles_are_not_bridged() {
|
||||
let mut s = session();
|
||||
@@ -176,9 +348,9 @@ fn locked_and_hidden_circles_are_not_bridged() {
|
||||
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"));
|
||||
assert!(err(&mut s, json!({"ids": [a.0, b.0]})).contains("select two or more 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"));
|
||||
assert!(err(&mut s, json!({"ids": [a.0, b.0]})).contains("select two or more circles to bridge"));
|
||||
}
|
||||
@@ -10,7 +10,7 @@
|
||||
mod tests;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{OrientedBox, Unit, decimal_point, finite_in_every_unit};
|
||||
use vectorcraft_doc::{OrientedBox, Unit, arithmetic_signs, decimal_point, finite_in_every_unit};
|
||||
use vectorcraft_render::effects;
|
||||
|
||||
use super::super::{CommandSpec, always, bad, cmd, has_selection};
|
||||
@@ -22,8 +22,8 @@ const SELECTION_SIZE: &str = "addon.units.selectionSize";
|
||||
const SHOWN_CHARS: usize = 64;
|
||||
/// The longest `value` or `unit` text `addon.units.convert` reads, in bytes.
|
||||
const MAX_TEXT_LEN: usize = 1024;
|
||||
/// The most `+ - * /` signs `addon.units.convert` reads in one `value`: [`Unit::parse`] takes one
|
||||
/// level of recursion per sign.
|
||||
/// The most `+ - * /` signs `addon.units.convert` reads in one `value`, a multiplication sign
|
||||
/// counted as a `*`: [`Unit::parse`] takes one level of recursion per sign.
|
||||
const MAX_OPERATORS: usize = 128;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
@@ -33,7 +33,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Convert Units",
|
||||
[],
|
||||
None,
|
||||
"{value: a length (a number, or text as a number field reads it, with a unit suffix and + - * / arithmetic: \"10mm\", \"1in/2\", \"2p6\", \"3cm*50%\"; a decimal comma reads as a point: \"0,5 mm\"; at most 1024 bytes and 128 operators), unit?: the unit of a number without a suffix (a unit's name, suffix or key: points, picas, inches, millimeters, centimeters, pixels, feetInches, meters, yards, feet, q, ha; default: points)} the length in every unit of Preferences › Units › East Asian Type, written as the number fields write it (rounded to 3 decimals in pt, px, picas, Q and Ha and to 4 in the others; pixels are points). Nothing in the document changes → {points, units: [{unit (its key), label, number (no suffix), text (with the suffix)}]}",
|
||||
"{value: a length (a number, or text as a number field reads it, with a unit suffix and + - * / arithmetic, x, X or × multiplying as * does: \"10mm\", \"1in/2\", \"2p6\", \"3cm*50%\", \"2x3 mm\"; a decimal comma reads as a point: \"0,5 mm\"; at most 1024 bytes and 128 operators, each multiplication sign counted), unit?: the unit of a number without a suffix (a unit's name, suffix or key: points, picas, inches, millimeters, centimeters, pixels, feetInches, meters, yards, feet, q, ha; default: points)} the length in every unit of Preferences › Units › East Asian Type, written as the number fields write it (rounded to 3 decimals in pt, px, picas, Q and Ha and to 4 in the others; pixels are points). Nothing in the document changes → {points, units: [{unit (its key), label, number (no suffix), text (with the suffix)}]}",
|
||||
always,
|
||||
convert
|
||||
),
|
||||
@@ -88,9 +88,9 @@ fn convert(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
/// Is `s` short enough to read: at most [`MAX_TEXT_LEN`] bytes and [`MAX_OPERATORS`] `+ - * /`
|
||||
/// signs?
|
||||
/// signs, a multiplication sign typed as `x`, `X` or `×` counted as a `*` ([`arithmetic_signs`])?
|
||||
fn readable(s: &str) -> bool {
|
||||
s.len() <= MAX_TEXT_LEN && s.chars().filter(|c| matches!(c, '+' | '-' | '*' | '/')).count() <= MAX_OPERATORS
|
||||
s.len() <= MAX_TEXT_LEN && arithmetic_signs(s) <= MAX_OPERATORS
|
||||
}
|
||||
|
||||
/// `v` as an error message shows it: text cut at [`SHOWN_CHARS`] characters with "…", as JSON,
|
||||
|
||||
@@ -76,6 +76,12 @@ fn values_read_as_number_fields_read_them() {
|
||||
assert!(near(pt(&mut s, json!({"value": "1,500+2", "unit": "mm"})), 3.5 * 72.0 / 25.4));
|
||||
// A sum of 128 signs still reads.
|
||||
assert!(near(pt(&mut s, json!({"value": format!("1{}", "+1".repeat(128))})), 129.0));
|
||||
// x, X and × multiply as * does, and each counts toward the 128 signs.
|
||||
assert!(near(pt(&mut s, json!({"value": "2x3 mm"})), 6.0 * 72.0 / 25.4));
|
||||
assert!(near(pt(&mut s, json!({"value": "10X2"})), 20.0));
|
||||
assert!(near(pt(&mut s, json!({"value": "0,5×4 in"})), 144.0));
|
||||
assert!(near(pt(&mut s, json!({"value": format!("1{}", "x1".repeat(128))})), 1.0));
|
||||
assert!(s.execute("addon.units.convert", &json!({"value": format!("1{}", "x1".repeat(129))})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -12,8 +12,9 @@ use super::overprint::{AttributesInfo, apply_overprint, edit_counted, overprint_
|
||||
use super::path::paths_in;
|
||||
use super::{CommandSpec, NodeId, Result, Session, bad, cmd, has_doc, str_param, targets};
|
||||
|
||||
/// How many URLs the Attributes panel's recent list keeps.
|
||||
const RECENT_URLS: usize = 10;
|
||||
/// How many URLs the Attributes panel's recent list keeps: the most its Panel Options lets the
|
||||
/// URL menu list.
|
||||
pub const RECENT_URLS: usize = 30;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
@@ -22,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Attributes",
|
||||
[],
|
||||
None,
|
||||
"{overprintFill?: bool, overprintStroke?: bool (aimed as object.setOverprint's fill and stroke, item? too), showCenter?: bool (the canvas shows the selected object's centre point), imageMap?: \"none\"|\"rectangle\"|\"polygon\", url?: string (\"\" removes it; SVG, PDF and .ai export link the object), note?: string, ids?|id?, item?: appearance item index|null, target?: \"object\"|\"contents\"} set the Attributes panel's values on ids or the selection, as one undo step; a URL given joins the recent URLs (attributes.info) → {changed: objects}",
|
||||
"{overprintFill?: bool, overprintStroke?: bool (aimed as object.setOverprint's fill and stroke, item? too), showCenter?: bool (the canvas shows the selected object's centre point), imageMap?: \"none\"|\"rectangle\"|\"polygon\", url?: string (\"\" removes it; SVG, PDF and .ai export link the object), note?: string, ids?|id?, item?: appearance item index|null, target?: \"object\"|\"contents\"} set the Attributes panel's values on ids or the selection, as one undo step; a URL given joins the recent URLs (attributes.info, newest first, at most 30) → {changed: objects}",
|
||||
has_doc,
|
||||
set
|
||||
),
|
||||
|
||||
@@ -12,7 +12,8 @@ use std::sync::{Arc, LazyLock};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_brush::{
|
||||
self as brush, ArtBrush, Bristle, BristleShape, Brush, BrushKind, Calligraphic, Colorization, PatternBrush, PatternFit, Scatter, Variation,
|
||||
self as brush, ArtBrush, ArtScale, Bristle, BristleShape, Brush, BrushKind, Calligraphic, Colorization, PatternBrush, PatternFit, Scatter,
|
||||
Variation,
|
||||
};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, NodeId, NodeKind, PatternDef, Symbol};
|
||||
@@ -180,6 +181,7 @@ pub const BUILTIN: &[BuiltinBrushLibrary] = &[
|
||||
BuiltinBrushLibrary { id: "energy-beams", name: "Energy Beams", make: energy_beams },
|
||||
BuiltinBrushLibrary { id: "dry-media", name: "Dry Media", make: dry_media },
|
||||
BuiltinBrushLibrary { id: "tech-circuit", name: "Tech Circuit", make: tech_circuit },
|
||||
BuiltinBrushLibrary { id: "arrows", name: "Arrows", make: arrows },
|
||||
];
|
||||
|
||||
/// Built-in library `id`, made once.
|
||||
@@ -233,6 +235,54 @@ fn art(name: &str, art: Node, colorization: Colorization) -> Brush {
|
||||
Brush { name: name.into(), kind: BrushKind::Art(ArtBrush { art, colorization, ..Default::default() }) }
|
||||
}
|
||||
|
||||
/// An Arrows brush whose art stretches only between `start` and `end` (fractions of its length).
|
||||
fn arrow_art(name: &str, art: Node, start: f64, end: f64) -> Brush {
|
||||
Brush {
|
||||
name: name.into(),
|
||||
kind: BrushKind::Art(ArtBrush {
|
||||
art,
|
||||
scale: ArtScale::BetweenGuides { start, end },
|
||||
colorization: Colorization::Tints,
|
||||
..Default::default()
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Arrows: original art brushes whose stems stretch while their heads keep their proportions.
|
||||
fn arrows() -> BrushLibrary {
|
||||
let shaft = || black(shapes::rectangle(Rect::new(0.0, -1.0, 82.0, 1.0)));
|
||||
let head = || black(polygon(&[(76.0, -7.0), (100.0, 0.0), (76.0, 7.0), (82.0, 0.0)]));
|
||||
let solid = group(vec![shaft(), head()]);
|
||||
let outline = group(vec![shaft(), black(polygon(&[(76.0, -7.0), (100.0, 0.0), (76.0, 7.0), (78.0, 4.0), (91.0, 0.0), (78.0, -4.0)]))]);
|
||||
let double = group(vec![
|
||||
black(shapes::rectangle(Rect::new(18.0, -1.0, 82.0, 1.0))),
|
||||
head(),
|
||||
black(polygon(&[(24.0, -7.0), (0.0, 0.0), (24.0, 7.0), (18.0, 0.0)])),
|
||||
]);
|
||||
let chevrons = group(vec![shaft(), head(), black(polygon(&[(53.0, -5.0), (66.0, 0.0), (53.0, 5.0), (56.0, 0.0)]))]);
|
||||
let dashed = group(
|
||||
(0..5)
|
||||
.map(|i| {
|
||||
let x = f64::from(i) * 16.0;
|
||||
black(shapes::rectangle(Rect::new(x, -1.0, x + 10.0, 1.0)))
|
||||
})
|
||||
.chain(std::iter::once(head()))
|
||||
.collect(),
|
||||
);
|
||||
built(
|
||||
"Arrows",
|
||||
Document::new(100.0, 100.0),
|
||||
vec![
|
||||
arrow_art("Solid Arrow", solid, 0.0, 0.76),
|
||||
arrow_art("Open Arrow", outline, 0.0, 0.76),
|
||||
arrow_art("Double Arrow", double, 0.24, 0.76),
|
||||
// The second chevron starts at 53 pt, so only the shaft before it stretches.
|
||||
arrow_art("Chevron Arrow", chevrons, 0.0, 0.53),
|
||||
arrow_art("Dashed Arrow", dashed, 0.0, 0.76),
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
/// Art Ribbons: art brushes, 100 pt long, drawn here; Striped Ribbon is filled with the library's
|
||||
/// own pattern, Pinstripes.
|
||||
fn art_ribbons() -> BrushLibrary {
|
||||
|
||||
+10
-144
@@ -55,7 +55,16 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
None,
|
||||
"{cx, cy, diameter=100, opacity=50 (%), brightness=30 (%), growth=20 (%), fuzziness=50 (%), rays=15, longest=300 (%), rayFuzziness=100 (%), rotation=0 (deg, turns the rays clockwise), x2?, y2? (ring end; else pathLength at direction), pathLength=300, rings=10, largest=50 (%), direction=45 (deg counter-clockwise from 3 o'clock: where the rings run from the centre), seed?, ringSeed? (whole number below 2^53: deterministically places every ring along the path, including the first for small seed values, keeping their count and sizes)} → {id}",
|
||||
has_doc,
|
||||
flare
|
||||
super::flare::flare
|
||||
),
|
||||
cmd!(
|
||||
"shape.editFlare",
|
||||
"Edit Flare",
|
||||
[],
|
||||
None,
|
||||
"{ids?|id?: flares (default: the selected flares), cx?, cy? (the center, where it is drawn now), x2?, y2? (the rings' end point, where it is drawn now; else pathLength at direction from the center, both where it is drawn now, when either is given; else where it was), diameter?, opacity?, brightness?, growth?, fuzziness?, rays?, longest?, rayFuzziness?, rotation? (deg, turns the rays clockwise), pathLength?, rings?, largest?, direction? (as shape.flare: what is left out stays as it was)} draws each flare again in its place, moved, scaled, rotated, reflected or sheared as it has been since it was drawn, as one undo step (none when nothing changes); a flare whose parts were edited, or that is locked or hidden, is not one → {ids}",
|
||||
has_doc,
|
||||
super::flare::edit_flare
|
||||
),
|
||||
cmd!(
|
||||
"shape.circleThroughPoints",
|
||||
@@ -515,149 +524,6 @@ fn star(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
add_art_turned(s, "Star", path_kind(path, None), constrained_turn(s, rot))
|
||||
}
|
||||
|
||||
/// Flare tool: a lens flare built from radial-gradient paths in Screen mode — a bright centre, a halo
|
||||
/// ring, rays of varying length and rings along the path to the end point.
|
||||
fn flare(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
use vectorcraft_color::{BlendMode, Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop, Paint};
|
||||
let c = Point::new(f64_req(p, "cx", "shape.flare")?, f64_req(p, "cy", "shape.flare")?);
|
||||
let numbers = [
|
||||
"diameter",
|
||||
"opacity",
|
||||
"brightness",
|
||||
"growth",
|
||||
"fuzziness",
|
||||
"rays",
|
||||
"longest",
|
||||
"rayFuzziness",
|
||||
"rotation",
|
||||
"rings",
|
||||
"largest",
|
||||
"x2",
|
||||
"y2",
|
||||
"direction",
|
||||
"pathLength",
|
||||
"seed",
|
||||
"ringSeed",
|
||||
];
|
||||
check_numbers(p, &numbers, "shape.flare")?;
|
||||
let pct = |k: &str, d: f64| (f64_or(p, k, d) / 100.0).clamp(0.0, 10.0);
|
||||
let r = (f64_or(p, "diameter", 100.0) / 2.0).max(0.5);
|
||||
let opacity = pct("opacity", 50.0).min(1.0) as f32;
|
||||
let brightness = pct("brightness", 30.0).min(1.0) as f32;
|
||||
let growth = pct("growth", 20.0);
|
||||
let fuzz = pct("fuzziness", 50.0).min(1.0);
|
||||
let rays = p.get("rays").and_then(Value::as_u64).unwrap_or(15).min(50) as usize;
|
||||
let longest = pct("longest", 300.0);
|
||||
let ray_fuzz = pct("rayFuzziness", 100.0).min(1.0);
|
||||
let ray_turn = f64_or(p, "rotation", 0.0).to_radians();
|
||||
let rings = p.get("rings").and_then(Value::as_u64).unwrap_or(10).min(50) as usize;
|
||||
let largest = pct("largest", 50.0);
|
||||
let end = match (p.get("x2").and_then(Value::as_f64), p.get("y2").and_then(Value::as_f64)) {
|
||||
(Some(x), Some(y)) => Point::new(x, y),
|
||||
_ => {
|
||||
let a = f64_or(p, "direction", 45.0).to_radians();
|
||||
c + vectorcraft_geom::Vec2::new(a.cos(), -a.sin()) * f64_or(p, "pathLength", 300.0)
|
||||
}
|
||||
};
|
||||
// Deterministic pseudo-random sizes (same parameters → same flare). `ringSeed` places the rings
|
||||
// along the path from a sequence of its own; their count and sizes and the other parts stay.
|
||||
let seed_of = |key: &str| match p.get(key) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(v) => v.as_u64().map(Some).ok_or_else(|| bad("shape.flare", format!("`{key}` must be a whole number of at least 0, not {v}"))),
|
||||
};
|
||||
// Xorshift64. Both streams start from a nonzero state.
|
||||
let random = |mut state: u64| {
|
||||
move || {
|
||||
state ^= state << 13;
|
||||
state ^= state >> 7;
|
||||
state ^= state << 17;
|
||||
(state >> 11) as f64 / (1u64 << 53) as f64
|
||||
}
|
||||
};
|
||||
let mut rnd = random(seed_of("seed")?.unwrap_or(0x2545_f491_4f6c_dd1d) | 1);
|
||||
// Each `ringSeed` below 2^53 (what a JSON number holds exactly) gets a state of its own.
|
||||
let ring_seed = match seed_of("ringSeed")? {
|
||||
Some(r) if r >= 1 << 53 => return Err(bad("shape.flare", format!("`ringSeed` must be below 2^53, not {r}"))),
|
||||
r => r,
|
||||
};
|
||||
let mut ring_at = ring_seed.map(|r| {
|
||||
// SplitMix64 initializes the ring-position stream.
|
||||
let mut z = r.wrapping_add(0x9e37_79b9_7f4a_7c15);
|
||||
z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
|
||||
z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
|
||||
random(z ^ (z >> 31))
|
||||
});
|
||||
let stop = |offset: f32, opacity: f32| GradientStop { opacity, ..GradientStop::new(offset, vectorcraft_color::Color::WHITE) };
|
||||
let radial = |centre: Point, radius: f64, stops: Vec<GradientStop>| {
|
||||
let mut g = GradientPaint::new(Gradient::new(GradientKind::Radial, stops));
|
||||
g.geom = Some(GradientGeom { start: centre, end: centre + vectorcraft_geom::Vec2::new(radius, 0.0), aspect: 1.0, focal: None });
|
||||
Paint::Gradient(Box::new(g))
|
||||
};
|
||||
let circle = |centre: Point, radius: f64| shapes::ellipse(Rect::from_center_size(centre, (radius * 2.0, radius * 2.0)));
|
||||
let mut parts: Vec<(&str, PathData, Paint, f32)> = vec![];
|
||||
// Halo: a soft ring just outside the centre.
|
||||
let halo_r = r * (1.0 + growth) * 1.6;
|
||||
let inner = (1.0 - fuzz as f32 * 0.6).clamp(0.05, 0.95);
|
||||
parts.push(("Halo", circle(c, halo_r), radial(c, halo_r, vec![stop(0.0, 0.0), stop(inner * 0.75, 0.0), stop(inner, 0.5), stop(1.0, 0.0)]), 1.0));
|
||||
// Rays: thin spikes of random length (Longest = % of the centre radius), fading outwards.
|
||||
// `rotation` turns them clockwise about the center.
|
||||
if rays > 0 {
|
||||
let mut bp = vectorcraft_geom::BezPath::new();
|
||||
let mut reach: f64 = 0.0;
|
||||
for i in 0..rays {
|
||||
let a = std::f64::consts::TAU * (i as f64 + rnd() * 0.6) / rays as f64 + ray_turn;
|
||||
let len = r * longest * (1.0 - ray_fuzz * 0.75 * rnd()).max(0.1);
|
||||
reach = reach.max(len);
|
||||
let w = r * 0.035;
|
||||
let dir = vectorcraft_geom::Vec2::new(a.cos(), a.sin());
|
||||
let n = vectorcraft_geom::Vec2::new(-dir.y, dir.x) * w;
|
||||
bp.move_to(c + n);
|
||||
bp.line_to(c + dir * len);
|
||||
bp.line_to(c - n);
|
||||
bp.line_to(c - dir * (w * 4.0));
|
||||
bp.close_path();
|
||||
}
|
||||
parts.push(("Rays", PathData::from_bezpath(&bp), radial(c, reach, vec![stop(0.0, 0.9), stop(0.25, 0.35), stop(1.0, 0.0)]), 1.0));
|
||||
}
|
||||
// Centre: bright core fading to transparent.
|
||||
parts.push(("Center", circle(c, r), radial(c, r, vec![stop(0.0, 1.0), stop(0.25 + brightness * 0.5, 0.6), stop(1.0, 0.0)]), opacity));
|
||||
// Rings along the path to the end point (Largest = % of the average ring size).
|
||||
for _ in 0..rings {
|
||||
let t = rnd();
|
||||
let t = ring_at.as_mut().map_or(t, |next| next());
|
||||
let at = c + (end - c) * t;
|
||||
let rr = (r * largest * (0.25 + rnd() * 0.75)).max(0.5);
|
||||
let solid = rnd() < 0.5;
|
||||
let stops = if solid {
|
||||
vec![stop(0.0, 0.25), stop(0.8, 0.2), stop(1.0, 0.0)]
|
||||
} else {
|
||||
vec![stop(0.0, 0.0), stop(0.7, 0.05), stop(0.92, 0.35), stop(1.0, 0.0)]
|
||||
};
|
||||
parts.push(("Ring", circle(at, rr), radial(at, rr, stops), 1.0));
|
||||
}
|
||||
let parent = s.doc()?.target_parent()?;
|
||||
let id = s.edit("Flare", |d, sel| {
|
||||
let children = parts
|
||||
.into_iter()
|
||||
.map(|(name, pd, paint, op)| {
|
||||
let mut n = Node::path(d.alloc_id(), pd, Appearance::basic(paint, Paint::None, 0.0));
|
||||
n.name = Some(name.into());
|
||||
n.blend = BlendMode::Screen;
|
||||
n.opacity = op;
|
||||
super::object::align_new_object(d, &mut n);
|
||||
std::sync::Arc::new(n)
|
||||
})
|
||||
.collect();
|
||||
let gid = d.alloc_id();
|
||||
let mut g = Node::group(gid, children);
|
||||
g.name = Some("Flare".into());
|
||||
d.insert(parent, usize::MAX, g)?;
|
||||
sel.set([gid]);
|
||||
Ok(gid)
|
||||
})?;
|
||||
Ok(json!({ "id": id.0 }))
|
||||
}
|
||||
|
||||
fn line(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let a = Point::new(f64_req(p, "x1", "shape.line")?, f64_req(p, "y1", "shape.line")?);
|
||||
let b = Point::new(f64_req(p, "x2", "shape.line")?, f64_req(p, "y2", "shape.line")?);
|
||||
|
||||
@@ -182,7 +182,7 @@ impl Expandable {
|
||||
n.walk(&mut |c| {
|
||||
let shape = matches!(c.kind, NodeKind::Path { .. } | NodeKind::Compound { .. });
|
||||
e.text |= matches!(c.kind, NodeKind::Text(_));
|
||||
e.live |= matches!(c.kind, NodeKind::Path { live: Some(_), .. });
|
||||
e.live |= matches!(c.kind, NodeKind::Path { live: Some(_), .. }) || c.extras().flare.is_some();
|
||||
e.effects |= !c.appearance.effects.is_empty();
|
||||
e.envelope |= matches!(c.kind, NodeKind::Envelope { .. });
|
||||
e.blends |= matches!(c.kind, NodeKind::Blend { .. });
|
||||
@@ -503,10 +503,14 @@ fn end_dimension_links(s: &mut Session, ended: &mut Vec<EndedLink>) -> Result<()
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Makes the live shapes in `n` plain paths, and the flares plain groups of their parts.
|
||||
fn drop_live(n: &mut Node) {
|
||||
if let NodeKind::Path { live, .. } = &mut n.kind {
|
||||
*live = None;
|
||||
}
|
||||
if n.extras().flare.is_some() {
|
||||
n.extras_mut().flare = None;
|
||||
}
|
||||
if let Some(ch) = n.children_mut() {
|
||||
for c in ch.iter_mut() {
|
||||
drop_live(Arc::make_mut(c));
|
||||
|
||||
@@ -297,7 +297,17 @@ pub(crate) fn write_file(path: &str, bytes: &[u8]) -> Result<()> {
|
||||
vectorcraft_doc::cancel::check()?;
|
||||
may_write(path)?;
|
||||
// Never a half-written file: see [`write_atomic`].
|
||||
write_atomic(std::path::Path::new(path), bytes).map_err(|e| EngineError::Other(format!("{path}: {e}")))
|
||||
write_atomic(std::path::Path::new(path), bytes).map_err(|e| write_error(path, e))
|
||||
}
|
||||
|
||||
/// The error writing `path` failed with: [`EngineError::Cancelled`] for work canceled before the
|
||||
/// file was put in place ([`vectorcraft_format::write_atomic_with`]), otherwise the path and the reason.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn write_error(path: &str, error: std::io::Error) -> EngineError {
|
||||
if error.get_ref().is_some_and(|e| e.is::<vectorcraft_doc::cancel::Cancelled>()) {
|
||||
return EngineError::Cancelled;
|
||||
}
|
||||
EngineError::Other(format!("{path}: {error}"))
|
||||
}
|
||||
|
||||
/// [`write_file`] with what `fill` writes into the file (a save streamed into it).
|
||||
@@ -305,7 +315,7 @@ pub(crate) fn write_file(path: &str, bytes: &[u8]) -> Result<()> {
|
||||
pub fn write_file_with(path: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>) -> Result<()> {
|
||||
vectorcraft_doc::cancel::check()?;
|
||||
may_write(path)?;
|
||||
vectorcraft_format::write_atomic_with(std::path::Path::new(path), |f| fill(f)).map_err(|e| EngineError::Other(format!("{path}: {e}")))
|
||||
vectorcraft_format::write_atomic_with(std::path::Path::new(path), |f| fill(f)).map_err(|e| write_error(path, e))
|
||||
}
|
||||
|
||||
/// The save commands' writer: preserves a filesystem location refusal as a typed error. Other
|
||||
@@ -324,8 +334,10 @@ pub fn write_save_file_with(path: &str, fill: &mut dyn FnMut(&mut dyn std::io::W
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(super) fn save_write_error(path: &str, error: std::io::Error) -> EngineError {
|
||||
let reason = format!("{path}: {error}");
|
||||
if vectorcraft_format::read_only_location(&error) { EngineError::ReadOnlyLocation(reason) } else { EngineError::Other(reason) }
|
||||
if !vectorcraft_format::read_only_location(&error) {
|
||||
return write_error(path, error);
|
||||
}
|
||||
EngineError::ReadOnlyLocation(format!("{path}: {error}"))
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
|
||||
@@ -970,7 +970,8 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option<String> {
|
||||
/// TIFF ([`vectorcraft_doc::cmyk::turned_cmyk`]). An image the decoder reads and that is stored as
|
||||
/// PNG keeps its gray or RGB samples at 8 or 16 bits, and the gray or RGB ICC profile they are in;
|
||||
/// other samples become 8-bit RGBA. A PSD/PSB composite's stored image keeps its imported
|
||||
/// clipping path ([`image_clip`]).
|
||||
/// clipping path ([`image_clip`]), and a PNG or TIFF that keeps such a path (as Unembed writes
|
||||
/// it) is read with that path.
|
||||
pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> {
|
||||
let ppi = super::ppi::resolution(bytes);
|
||||
if let Some((w, h)) = vectorcraft_doc::cmyk::oversized_tiff(bytes) {
|
||||
@@ -1147,13 +1148,15 @@ pub fn texture_image(bytes: &[u8]) -> Result<String> {
|
||||
texture.and_then(|t| t.to_stored()).ok_or_else(|| err("the image can't be read as a texture"))
|
||||
}
|
||||
|
||||
/// An image's encoded `bytes`, `width` × `height` pixels, ready to embed.
|
||||
/// An image's encoded `bytes`, `width` × `height` pixels, ready to embed, with the clipping path a
|
||||
/// PNG or TIFF made from a PSD or PSB file keeps ([`image_clip`]).
|
||||
fn stored(bytes: Vec<u8>, mime: &'static str, (width, height): (u32, u32), ppi: Option<(f64, f64)>) -> Result<RasterImage> {
|
||||
if width == 0 || height == 0 {
|
||||
return Err(err("the image is empty"));
|
||||
}
|
||||
let blob = ImageBlob::new(mime, bytes);
|
||||
Ok(RasterImage { key: blob.content_key(), blob, width, height, ppi, clip: None })
|
||||
let clip = image_clip(&blob).map(|path| (path, vectorcraft_geom::FillRule::EvenOdd));
|
||||
Ok(RasterImage { key: blob.content_key(), blob, width, height, ppi, clip })
|
||||
}
|
||||
|
||||
/// The keyword of the PNG text chunk holding the clipping path of the file a PNG was made from
|
||||
|
||||
@@ -69,7 +69,7 @@ pub(crate) const OPTIONS: &[FormatOption] = &[
|
||||
name: "bleed",
|
||||
ty: "object",
|
||||
default: "null",
|
||||
description: "{useDocument, top, bottom, left, right} in points: the page grows by the bleed (BleedBox) around its artboard (TrimBox); a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning",
|
||||
description: "{useDocument, top, bottom, left, right} in points: the page grows by the bleed (BleedBox) around its artboard (TrimBox); a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning, and so do objects that reach the trim edge on a side with a bleed but stop short of the bleed edge",
|
||||
},
|
||||
FormatOption {
|
||||
name: "output",
|
||||
@@ -128,7 +128,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export PDF",
|
||||
[],
|
||||
None,
|
||||
"{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, and with destination and an sRGB destination a gray or RGB image tagged
Line truncated
|
||||
"{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning, and so does a count of the visible objects that reach the trim edge (within 0.5 pt) on a side with a bleed but end before the bleed edge; layers that don't print are left out unless includeNonPrinting, and art and boxes are written unchanged). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in
Line truncated
|
||||
has_doc,
|
||||
export_pdf
|
||||
),
|
||||
@@ -295,6 +295,8 @@ pub(super) fn encode_art_page(cmd: &str, doc: &Document, p: &Value) -> Result<Op
|
||||
o.insert("preserveEditing".into(), json!(false));
|
||||
}
|
||||
let (bytes, mut notes) = encode(cmd, &art, &q)?;
|
||||
// The page is the art's bounds, so every object at its edge would count.
|
||||
notes.retain(|n| !is_short_of_bleed(&n.text));
|
||||
if left_out {
|
||||
notes.push(Note::setting(EDITING_NEEDS_THE_ARTBOARDS));
|
||||
}
|
||||
@@ -317,6 +319,191 @@ pub(super) fn art_page(cmd: &str, doc: &Document, p: &Value) -> Result<Option<(D
|
||||
/// ([`vectorcraft_pdf::PdfSettings::leaves_out_bleed`]).
|
||||
pub const BLEED_LEFT_OUT: &str = "the document sets a bleed that this PDF/X file leaves out: turn on Use document bleed settings";
|
||||
|
||||
/// How far, in points, an object's edge may sit inside the trim edge, or short of the bleed edge,
|
||||
/// and still count as reaching it in [`short_of_bleed`]. A side whose bleed is no larger has none.
|
||||
const EDGE_TOLERANCE: f64 = 0.5;
|
||||
|
||||
/// How many objects of `doc` reach the trim edge (an artboard's edge, within [`EDGE_TOLERANCE`]) of
|
||||
/// one of `artboards` (`None`: all of them) on a side where `bleed` (`[top, bottom, left, right]`
|
||||
/// in points) is set, but end before that side's bleed edge. The objects are the members of the
|
||||
/// visible layers and sublayers, a group counted as one, measured as [`drawn_bounds`] measures them
|
||||
/// and cut to the clipping paths of the layers they are on. Template layers, layers with an opacity
|
||||
/// mask and, unless `non_printing`, layers whose Print option is off are left out. A side whose
|
||||
/// bleed is [`EDGE_TOLERANCE`] or less counts as having none. Each object counts once.
|
||||
pub fn short_of_bleed(doc: &Document, bleed: [f64; 4], artboards: Option<&[usize]>, non_printing: bool) -> usize {
|
||||
let bleed = bleed.map(|b| if b.is_finite() && b > EDGE_TOLERANCE { b } else { 0.0 });
|
||||
if bleed.iter().all(|b| *b == 0.0) {
|
||||
return 0;
|
||||
}
|
||||
let trims: Vec<vectorcraft_geom::Rect> = match artboards {
|
||||
Some(picked) => picked.iter().filter_map(|&i| doc.artboards.get(i)).map(|a| a.rect).collect(),
|
||||
None => doc.artboards.iter().map(|a| a.rect).collect(),
|
||||
};
|
||||
let symbols = doc.symbol_boxes();
|
||||
let mut count = 0;
|
||||
// Each object with the clipping path of the layers above it.
|
||||
let mut stack: Vec<(&Node, Option<vectorcraft_geom::Rect>)> = doc.layers.iter().map(|l| (&**l, None)).collect();
|
||||
while let Some((n, clip)) = stack.pop() {
|
||||
if let NodeKind::Layer { template, printable, children, clip: clipping, .. } = &n.kind {
|
||||
// An opacity mask decides what shows, so a masked layer's art is not measured.
|
||||
if !n.visible || *template || !(*printable || non_printing) || n.opacity <= 0.0 || n.extras().mask.is_some() {
|
||||
continue;
|
||||
}
|
||||
// A clipping layer's first child clips the others, and its fills and strokes are an
|
||||
// object of their own.
|
||||
let (inner, members) = if *clipping {
|
||||
let Some(own) = clip_region(children, &symbols) else { continue };
|
||||
let inner = clip.map_or(own, |c| c.intersect(own));
|
||||
if let Some(first) = children.first()
|
||||
&& let Drawn::Bounds(b) = clip_paint_drawn(first, inner, &symbols)
|
||||
{
|
||||
let b = clip.map_or(b, |c| c.intersect(b));
|
||||
if b.area() > 0.0 && trims.iter().any(|t| stops_short(b, *t, bleed)) {
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
(Some(inner), children.get(1..).unwrap_or_default())
|
||||
} else {
|
||||
(clip, &children[..])
|
||||
};
|
||||
stack.extend(members.iter().map(|c| (&**c, inner)));
|
||||
continue;
|
||||
}
|
||||
let Drawn::Bounds(b) = drawn_bounds(n, &symbols) else { continue };
|
||||
let b = clip.map_or(b, |c| c.intersect(b));
|
||||
if b.area() > 0.0 && trims.iter().any(|t| stops_short(b, *t, bleed)) {
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
count
|
||||
}
|
||||
|
||||
/// What [`drawn_bounds`] finds an object draws.
|
||||
enum Drawn {
|
||||
/// Nothing: it is hidden, a guide, at 0% opacity, or a path that paints nothing.
|
||||
Nothing,
|
||||
/// Art within these bounds.
|
||||
Bounds(vectorcraft_geom::Rect),
|
||||
/// Art whose bounds aren't known, which is not measured: brush art paints past the visual
|
||||
/// bounds by an amount they don't give, an opacity mask hides part of what they hold, and area
|
||||
/// type and type on a path are bounded by their frame or path.
|
||||
Unknown,
|
||||
}
|
||||
|
||||
/// Whether path or compound path `n` paints: one of its fills and strokes is visible, has a paint
|
||||
/// and an opacity above 0 and, a stroke, a width above 0. Other objects count as painting.
|
||||
fn paints(n: &Node) -> bool {
|
||||
!matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })
|
||||
|| n.appearance.items.iter().any(|i| {
|
||||
i.visible() && i.opacity() > 0.0 && !i.paint().is_none() && !matches!(i, vectorcraft_doc::AppearanceItem::Stroke(s) if s.width <= 0.0)
|
||||
})
|
||||
}
|
||||
|
||||
/// What `n` draws on a page, by its visual bounds (strokes included): a group without a clipping
|
||||
/// path by the members that draw, and a clip group by the part of them inside its clipping path
|
||||
/// together with what the clipping path paints itself ([`clip_paint_drawn`]).
|
||||
/// Hidden objects, guides, objects at 0% opacity and paths that paint nothing draw nothing. Art
|
||||
/// with a brushed stroke that draws, in `n` or (outside groups) in the objects it holds, art with
|
||||
/// an opacity mask, and area type and type on a path are [`Drawn::Unknown`].
|
||||
fn drawn_bounds(n: &Node, symbols: &vectorcraft_doc::SymbolBoxes) -> Drawn {
|
||||
if !n.visible || n.is_guide() || n.opacity <= 0.0 || !paints(n) {
|
||||
return Drawn::Nothing;
|
||||
}
|
||||
// An opacity mask decides what shows of the object, and the bounds of area type and type on a
|
||||
// path are its frame or path, not its glyphs.
|
||||
let frame_bounds = matches!(&n.kind, NodeKind::Text(t) if !matches!(t.kind, vectorcraft_doc::TextKind::Point));
|
||||
if vectorcraft_brush::reach(n) > 0.0 || n.extras().mask.is_some() || frame_bounds {
|
||||
return Drawn::Unknown;
|
||||
}
|
||||
let members = |children: &[Arc<Node>]| {
|
||||
let mut out = Some(None);
|
||||
for c in children {
|
||||
out = match (out, drawn_bounds(c, symbols)) {
|
||||
(None, _) | (_, Drawn::Unknown) => None,
|
||||
(Some(acc), Drawn::Bounds(b)) => Some(vectorcraft_geom::union_opt(acc, Some(b))),
|
||||
(keep, Drawn::Nothing) => keep,
|
||||
};
|
||||
}
|
||||
out
|
||||
};
|
||||
let measured = match &n.kind {
|
||||
NodeKind::Group { clip: false, .. } => match members(n.editing_children()) {
|
||||
Some(art) => art.and_then(|_| n.visual_of_members(std::iter::once(art))),
|
||||
None => return Drawn::Unknown,
|
||||
},
|
||||
NodeKind::Group { clip: true, children } => {
|
||||
let Some(region) = clip_region(children, symbols) else { return Drawn::Nothing };
|
||||
let Some(art) = members(children.get(1..).unwrap_or_default()) else { return Drawn::Unknown };
|
||||
let art = art.map(|a| region.intersect(a)).filter(|b| b.area() > 0.0);
|
||||
match children.first().map_or(Drawn::Nothing, |first| clip_paint_drawn(first, region, symbols)) {
|
||||
Drawn::Unknown => return Drawn::Unknown,
|
||||
Drawn::Bounds(b) => vectorcraft_geom::union_opt(art, Some(b)),
|
||||
Drawn::Nothing => art,
|
||||
}
|
||||
}
|
||||
_ if vectorcraft_brush::reach_within(n) > 0.0 => return Drawn::Unknown,
|
||||
_ => n.visual_bounds_with(symbols),
|
||||
};
|
||||
measured.map_or(Drawn::Nothing, Drawn::Bounds)
|
||||
}
|
||||
|
||||
/// The region the clipping path of a clip group or clipping layer with `children` clips to: its
|
||||
/// geometric bounds, without its strokes.
|
||||
fn clip_region(children: &[Arc<Node>], symbols: &vectorcraft_doc::SymbolBoxes) -> Option<vectorcraft_geom::Rect> {
|
||||
children.first()?.geometric_bounds_with(symbols)
|
||||
}
|
||||
|
||||
/// What clipping path `clip` paints itself ([`Node::clip_paint`]): its fills inside `region`, the
|
||||
/// region it clips to, and its strokes over the clipped art, unclipped.
|
||||
fn clip_paint_drawn(clip: &Node, region: vectorcraft_geom::Rect, symbols: &vectorcraft_doc::SymbolBoxes) -> Drawn {
|
||||
let paint = clip.clip_paint();
|
||||
let mut out = None;
|
||||
for (part, clipped) in [(paint.fill, true), (paint.stroke, false)] {
|
||||
let Some(part) = part else { continue };
|
||||
match drawn_bounds(&part, symbols) {
|
||||
Drawn::Unknown => return Drawn::Unknown,
|
||||
Drawn::Nothing => {}
|
||||
Drawn::Bounds(b) => {
|
||||
let b = if clipped { region.intersect(b) } else { b };
|
||||
out = vectorcraft_geom::union_opt(out, Some(b).filter(|b| b.area() > 0.0));
|
||||
}
|
||||
}
|
||||
}
|
||||
out.map_or(Drawn::Nothing, Drawn::Bounds)
|
||||
}
|
||||
|
||||
/// Whether bounds `b` reach the trim edge `t` (within [`EDGE_TOLERANCE`] on either side of it) on a
|
||||
/// side where `bleed` (`[top, bottom, left, right]`) is above 0 and end before the bleed edge there.
|
||||
/// Document space has y down.
|
||||
fn stops_short(b: vectorcraft_geom::Rect, t: vectorcraft_geom::Rect, [top, bottom, left, right]: [f64; 4]) -> bool {
|
||||
let tol = EDGE_TOLERANCE;
|
||||
let across = b.x0 < t.x1 && b.x1 > t.x0;
|
||||
let down = b.y0 < t.y1 && b.y1 > t.y0;
|
||||
let reaches = |near: f64, far: f64, edge: f64| near <= edge + tol && far >= edge - tol;
|
||||
(across && top > 0.0 && reaches(b.y0, b.y1, t.y0) && b.y0 > t.y0 - top + tol)
|
||||
|| (across && bottom > 0.0 && reaches(-b.y1, -b.y0, -t.y1) && b.y1 < t.y1 + bottom - tol)
|
||||
|| (down && left > 0.0 && reaches(b.x0, b.x1, t.x0) && b.x0 > t.x0 - left + tol)
|
||||
|| (down && right > 0.0 && reaches(-b.x1, -b.x0, -t.x1) && b.x1 < t.x1 + right - tol)
|
||||
}
|
||||
|
||||
/// The warning for `n` objects that [`short_of_bleed`] finds; `None` for none.
|
||||
pub fn short_of_bleed_warning(n: usize) -> Option<String> {
|
||||
match n {
|
||||
0 => None,
|
||||
1 => Some(format!("1 object {SHORT_OF_BLEED_ONE}")),
|
||||
_ => Some(format!("{n} objects {SHORT_OF_BLEED_OTHER}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// The end of [`short_of_bleed_warning`] for one object and for more.
|
||||
const SHORT_OF_BLEED_ONE: &str = "reaches the trim edge but stops short of the bleed";
|
||||
const SHORT_OF_BLEED_OTHER: &str = "reach the trim edge but stop short of the bleed";
|
||||
|
||||
/// Whether `text` is a warning [`short_of_bleed_warning`] gives.
|
||||
pub fn is_short_of_bleed(text: &str) -> bool {
|
||||
text.ends_with(SHORT_OF_BLEED_ONE) || text.ends_with(SHORT_OF_BLEED_OTHER)
|
||||
}
|
||||
|
||||
/// The end of the writer's warning for a page longer than 14,400 pt written with a `UserUnit`
|
||||
/// above 1.
|
||||
const SHOWN_SMALLER: &str = "so apps that ignore UserUnit show it that many times smaller";
|
||||
@@ -340,7 +527,7 @@ pub(super) fn encode_at(cmd: &str, doc: &Document, p: &Value, modified: Option<i
|
||||
let mut notes: Vec<Note> = placed.into_iter().map(Note::loss).collect();
|
||||
// The editing data leaves out an Export for Screens folder outside the read roots.
|
||||
let native = || Ok(vectorcraft_format::save(&super::access::with_readable_settings_folder(doc), false));
|
||||
let (bytes, drawn) = encode_carrying_at(cmd, &full, p, modified, native, || Ok(None))?;
|
||||
let (bytes, drawn) = encode_carrying_at(cmd, &full, p, modified, true, native, || Ok(None))?;
|
||||
notes.extend(drawn);
|
||||
if notes.iter().any(|n| n.text.ends_with(SHOWN_SMALLER)) && options(cmd, &full, p)?.settings.standard == Standard::None {
|
||||
for n in notes.iter_mut().filter(|n| n.text.ends_with(SHOWN_SMALLER)) {
|
||||
@@ -364,7 +551,8 @@ fn overflow_warning(cmd: &str, doc: &Document, p: &Value) -> Result<Option<Strin
|
||||
|
||||
/// [`encode`] the pages of `doc`, carrying `native()` as the editing data (a `.ai` file: the
|
||||
/// native document with its save options, whose pages may be left blank), and `private()`, the
|
||||
/// editing copy of the art for other apps with what it couldn't hold, on every page.
|
||||
/// editing copy of the art for other apps with what it couldn't hold, on every page. It doesn't
|
||||
/// warn about art that stops short of the bleed ([`short_of_bleed`]), which PDF export does.
|
||||
pub(super) fn encode_carrying(
|
||||
cmd: &str,
|
||||
doc: &Document,
|
||||
@@ -372,20 +560,26 @@ pub(super) fn encode_carrying(
|
||||
native: impl FnOnce() -> Result<Vec<u8>>,
|
||||
private: impl FnOnce() -> Result<Option<(vectorcraft_pdf::PrivateData, Vec<String>)>>,
|
||||
) -> Result<(Vec<u8>, Vec<Note>)> {
|
||||
encode_carrying_at(cmd, doc, p, None, native, private)
|
||||
encode_carrying_at(cmd, doc, p, None, false, native, private)
|
||||
}
|
||||
|
||||
/// [`encode_carrying`] modified at `modified` (Unix seconds) when given, instead of the time of
|
||||
/// writing.
|
||||
/// writing, warning about art that stops short of the bleed when `bleed_check` is true.
|
||||
fn encode_carrying_at(
|
||||
cmd: &str,
|
||||
doc: &Document,
|
||||
p: &Value,
|
||||
modified: Option<i64>,
|
||||
bleed_check: bool,
|
||||
native: impl FnOnce() -> Result<Vec<u8>>,
|
||||
private: impl FnOnce() -> Result<Option<(vectorcraft_pdf::PrivateData, Vec<String>)>>,
|
||||
) -> Result<(Vec<u8>, Vec<Note>)> {
|
||||
let mut opts = options_at(cmd, doc, p, modified.or_else(vectorcraft_doc::metadata::output_time))?;
|
||||
// Measured before the pages' background colors join the art. Only art that prints counts:
|
||||
// createLayers writes non-printing layers with /PrintState /OFF, so they count only with
|
||||
// includeNonPrinting, which writes them as printing art.
|
||||
let set = &opts.settings;
|
||||
let short = if bleed_check { short_of_bleed(doc, set.bleed_of(doc), opts.artboards.as_deref(), set.include_non_printing) } else { 0 };
|
||||
// The pages' background colors, behind the art (the editing data keeps them as colors).
|
||||
let pages = opts.artboards.clone().unwrap_or_else(|| (0..doc.artboards.len()).collect());
|
||||
let filled = super::export::with_artboard_fills(doc, p, pages).map_err(|e| bad(cmd, e))?;
|
||||
@@ -401,6 +595,8 @@ fn encode_carrying_at(
|
||||
if opts.settings.leaves_out_bleed(doc) {
|
||||
notes.push(Note::loss(BLEED_LEFT_OUT));
|
||||
}
|
||||
// Art that reaches the trim edge but leaves part of the page's bleed empty.
|
||||
notes.extend(short_of_bleed_warning(short).map(Note::loss));
|
||||
if opts.settings.preserve_editing {
|
||||
if opts.artboards.as_ref().is_none_or(|v| v.iter().copied().eq(0..doc.artboards.len())) {
|
||||
opts.native = Some(native()?);
|
||||
|
||||
@@ -629,6 +629,24 @@ impl<W: std::io::Write> std::io::Write for Counted<W> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A writer that fails once the work running on this thread is canceled
|
||||
/// ([`crate::cancel::is_cancelled`]), so a streamed save stops writing into its temporary file.
|
||||
/// It sits under the stream's buffer: it is checked once per buffer written, not per write.
|
||||
struct StopsWhenCancelled<W>(W);
|
||||
|
||||
impl<W: std::io::Write> std::io::Write for StopsWhenCancelled<W> {
|
||||
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
|
||||
if crate::cancel::is_cancelled() {
|
||||
return Err(std::io::Error::other(crate::cancel::Cancelled));
|
||||
}
|
||||
self.0.write(buf)
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
self.0.flush()
|
||||
}
|
||||
}
|
||||
|
||||
/// The artboards a native or `.ai` save also writes to files of their own: with
|
||||
/// `separateArtboards`, those `range` names (default all).
|
||||
fn separate_boards(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result<Vec<usize>> {
|
||||
@@ -1026,10 +1044,15 @@ impl SaveJob {
|
||||
}
|
||||
|
||||
/// [`SaveJob::write`], once `stop` has seen the paths of every file it writes to a path, in
|
||||
/// order: when `stop` returns a value, nothing is written and that value is returned.
|
||||
/// order: when `stop` returns a value, nothing is written and that value is returned. Work
|
||||
/// canceled ([`crate::cancel`]) before the first file is written returns
|
||||
/// [`crate::EngineError::Cancelled`] and writes nothing; once the first file is written, the
|
||||
/// others are written too.
|
||||
pub fn write_unless(&self, stop: impl FnOnce(&[&str]) -> Option<Value>, mut write: impl FnMut(&str, &[u8]) -> Result<()>) -> Result<Value> {
|
||||
let (plan, doc) = (&self.plan, &*self.doc);
|
||||
crate::cancel::check()?;
|
||||
let enc = self.encode()?;
|
||||
crate::cancel::check()?;
|
||||
let extra = json!({ "format": plan.format.id, "warnings": enc.notes() });
|
||||
let Some(path) = &plan.path else {
|
||||
let mut out = write_encoded(None, &plan.name, doc, &enc, extra)?;
|
||||
@@ -1046,8 +1069,13 @@ impl SaveJob {
|
||||
if let Some(stopped) = stop(&files.iter().map(|(p, _)| p.as_str()).collect::<Vec<_>>()) {
|
||||
return Ok(stopped);
|
||||
}
|
||||
for (p, bytes) in &files {
|
||||
write(p, bytes)?;
|
||||
for (i, (p, bytes)) in files.iter().enumerate() {
|
||||
if i == 0 {
|
||||
write(p, bytes)?;
|
||||
} else {
|
||||
// Once a file is in place, a Cancel no longer stops the save: the set is written whole.
|
||||
crate::cancel::scope(&crate::cancel::CancelToken::new(), None, || write(p, bytes))?;
|
||||
}
|
||||
}
|
||||
let bytes = files.first().map_or(0, |f| f.1.len());
|
||||
let mut out = super::merge(json!({ "path": path, "bytes": bytes }), extra);
|
||||
@@ -1070,11 +1098,15 @@ impl SaveJob {
|
||||
/// [`SaveJob::write`] through `stream`, which writes the file at a path with what the filler
|
||||
/// it is given writes (atomically, as [`vectorcraft_format::write_atomic_with`]). A native
|
||||
/// file goes into it as it is encoded ([`SaveJob::streams`]), never held whole in memory;
|
||||
/// other files are encoded first, then written into it.
|
||||
/// other files are encoded first, then written into it. Work canceled ([`crate::cancel`])
|
||||
/// while the native file is encoded, or before its filler returns, returns
|
||||
/// [`crate::EngineError::Cancelled`]: the filler fails, so `stream` keeps the file as it was
|
||||
/// (the atomic writer checks once more before it puts the file in place).
|
||||
pub fn write_streamed(&self, stream: StreamWrite) -> Result<Value> {
|
||||
let (Some(path), true) = (&self.plan.path, self.streams()) else {
|
||||
return self.write(|p, b| stream(p, &mut |w| w.write_all(b)));
|
||||
};
|
||||
crate::cancel::check()?;
|
||||
let (cmd, f) = (self.plan.mode.command(), self.plan.format);
|
||||
let doc = self.doc.without_edit_modes();
|
||||
let doc = match f.id {
|
||||
@@ -1091,16 +1123,22 @@ impl SaveJob {
|
||||
let mut failed = None;
|
||||
let mut written = 0u64;
|
||||
let mut fill = |w: &mut dyn std::io::Write| {
|
||||
let mut out = Counted { inner: std::io::BufWriter::with_capacity(STREAM_BUFFER, w), n: 0 };
|
||||
let mut out = Counted { inner: std::io::BufWriter::with_capacity(STREAM_BUFFER, StopsWhenCancelled(w)), n: 0 };
|
||||
let r = super::native::encode_to(cmd, f, &doc, &self.params, &mut out);
|
||||
written = out.n;
|
||||
match r {
|
||||
let r = match r {
|
||||
Ok(()) => out.inner.flush(),
|
||||
Err(e) => {
|
||||
failed = Some(e);
|
||||
Err(std::io::Error::other("the file couldn't be encoded"))
|
||||
}
|
||||
};
|
||||
// The last check before the file is replaced: a canceled save leaves it as it was.
|
||||
if crate::cancel::is_cancelled() {
|
||||
failed = Some(crate::EngineError::Cancelled);
|
||||
return Err(std::io::Error::other(crate::cancel::Cancelled));
|
||||
}
|
||||
r
|
||||
};
|
||||
let r = stream(path, &mut fill);
|
||||
r.map_err(|e| failed.take().unwrap_or(e))?;
|
||||
|
||||
@@ -1349,10 +1349,14 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) ->
|
||||
}
|
||||
// The document a PDF row writes: with Include Bleed, the artboards as they are.
|
||||
let pdf_doc = ungrown.as_deref();
|
||||
// A PDF page of an artboard has the artboard as its trim, with or without Include Bleed. A
|
||||
// page of its art's bounds has every object at its edge: it doesn't say whether art stops
|
||||
// short of the bleed.
|
||||
let artboard_page = o.assets.is_none() && o.layers.is_none() && o.selection.is_none();
|
||||
let mut write = |doc: &Document, format: &str, options: &Value| -> Result<Vec<u8>> {
|
||||
// The steps are the files: an encoder's own steps (artboards, pages) are not reported.
|
||||
let (bytes, given) = vectorcraft_doc::cancel::quiet(|| encode_with_notes(doc, format, options))?;
|
||||
for n in given {
|
||||
for n in given.into_iter().filter(|n| artboard_page || !super::pdf::is_short_of_bleed(&n.text)) {
|
||||
add_note(&mut notes, n);
|
||||
}
|
||||
Ok(bytes)
|
||||
|
||||
@@ -935,6 +935,109 @@ fn a_save_that_fails_while_streaming_leaves_the_file_as_it_was() {
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
/// A save canceled (Background Save's Cancel) before it starts, while a native file streams into
|
||||
/// its temporary file, or after the last byte went into it, fails with `Cancelled` and leaves the
|
||||
/// file as it was, with no temporary file behind. A file encoded first is never written.
|
||||
#[test]
|
||||
fn a_canceled_save_leaves_the_file_as_it_was() {
|
||||
/// Passes every write on, and cancels the save after the first one.
|
||||
struct CancelAfterFirst<'a> {
|
||||
inner: &'a mut dyn std::io::Write,
|
||||
token: crate::cancel::CancelToken,
|
||||
}
|
||||
impl std::io::Write for CancelAfterFirst<'_> {
|
||||
fn write(&mut self, b: &[u8]) -> std::io::Result<usize> {
|
||||
let n = self.inner.write(b)?;
|
||||
self.token.cancel();
|
||||
Ok(n)
|
||||
}
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
self.inner.flush()
|
||||
}
|
||||
}
|
||||
let d = tmp_dir("stream-cancel");
|
||||
// A small document's file goes in one piece; a large one's in several.
|
||||
for count in [1, 1500] {
|
||||
let mut s = session(2000.0, 2000.0, 1);
|
||||
for i in 0..count {
|
||||
s.execute("shape.rectangle", &json!({"x": i % 100 * 20, "y": i / 100 * 20, "width": 10, "height": 10})).unwrap();
|
||||
}
|
||||
let path = d.join("a.vectorcraft").to_string_lossy().to_string();
|
||||
s.execute("file.saveCopy", &json!({"path": path})).unwrap();
|
||||
let before = std::fs::read(&path).unwrap();
|
||||
s.execute("shape.ellipse", &json!({"x": 0, "y": 0, "width": 50, "height": 50})).unwrap();
|
||||
let plan = save_plan(&s, SaveMode::Copy, &json!({"path": path})).unwrap();
|
||||
let job = save_job(&mut s, plan).unwrap();
|
||||
assert!(job.streams());
|
||||
let token = crate::cancel::CancelToken::new();
|
||||
let r = crate::cancel::scope(&token, None, || {
|
||||
job.write_streamed(&mut |p, fill| super::write_file_with(p, &mut |w| fill(&mut CancelAfterFirst { inner: w, token: token.clone() })))
|
||||
});
|
||||
assert!(matches!(r, Err(EngineError::Cancelled)), "{count}: {r:?}");
|
||||
assert_eq!(std::fs::read(&path).unwrap(), before, "{count} objects");
|
||||
assert_eq!(std::fs::read_dir(&d).unwrap().count(), 1, "no temporary file is left");
|
||||
// Canceled before it starts: the file isn't opened.
|
||||
let mut opened = false;
|
||||
let r = crate::cancel::scope(&token, None, || {
|
||||
job.write_streamed(&mut |_, _| {
|
||||
opened = true;
|
||||
Ok(())
|
||||
})
|
||||
});
|
||||
assert!(matches!(r, Err(EngineError::Cancelled)) && !opened, "{r:?}");
|
||||
}
|
||||
// A file encoded first (SVG): nothing reaches the writer.
|
||||
let mut s = session(200.0, 100.0, 1);
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap();
|
||||
let plan = save_plan(&s, SaveMode::Copy, &json!({"path": d.join("a.svg").to_string_lossy()})).unwrap();
|
||||
let job = save_job(&mut s, plan).unwrap();
|
||||
let token = crate::cancel::CancelToken::new();
|
||||
token.cancel();
|
||||
let mut writes = 0;
|
||||
let r = crate::cancel::scope(&token, None, || {
|
||||
job.write_streamed(&mut |_, _| {
|
||||
writes += 1;
|
||||
Ok(())
|
||||
})
|
||||
});
|
||||
assert!(matches!(r, Err(EngineError::Cancelled)), "{r:?}");
|
||||
let r = crate::cancel::scope(&token, None, || {
|
||||
job.write(|_, _| {
|
||||
writes += 1;
|
||||
Ok(())
|
||||
})
|
||||
});
|
||||
assert!(matches!(r, Err(EngineError::Cancelled)) && writes == 0, "{r:?}");
|
||||
assert!(!d.join("a.svg").exists());
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
/// A save that writes several files (EPS with Use Artboards) and is canceled once its first file is
|
||||
/// in place writes the others too and succeeds: the set is never left half written.
|
||||
#[test]
|
||||
fn a_save_canceled_after_its_first_file_writes_them_all() {
|
||||
let d = tmp_dir("cancel-files");
|
||||
let mut s = session(100.0, 100.0, 2);
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 30, "height": 30})).unwrap();
|
||||
let path = d.join("logo.eps").to_string_lossy().to_string();
|
||||
let plan = save_plan(&s, SaveMode::Copy, &json!({"path": path, "options": {"useArtboards": true}})).unwrap();
|
||||
let job = save_job(&mut s, plan).unwrap();
|
||||
let token = crate::cancel::CancelToken::new();
|
||||
let mut written = vec![];
|
||||
let r = crate::cancel::scope(&token, None, || {
|
||||
job.write(|p, b| {
|
||||
super::write_save_file(p, b)?;
|
||||
written.push(p.to_string());
|
||||
token.cancel();
|
||||
Ok(())
|
||||
})
|
||||
});
|
||||
assert!(r.is_ok(), "{r:?}");
|
||||
assert_eq!(written.len(), 3, "{written:?}");
|
||||
assert!(written.iter().all(|p| std::path::Path::new(p).is_file()), "{written:?}");
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
/// A save that fails leaves File Info's dates and the saved state alone; one that works stamps them.
|
||||
#[test]
|
||||
fn a_failed_save_does_not_stamp_the_documents_dates() {
|
||||
|
||||
@@ -171,6 +171,226 @@ fn a_pdfx_file_that_leaves_out_the_document_bleed_warns() {
|
||||
assert!(!left_out(&warnings), "{warnings:?}");
|
||||
}
|
||||
|
||||
/// A 200 × 100 pt document with no art, bleed `bleed` (pt).
|
||||
fn bleed_session(bleed: Value) -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
|
||||
s.execute("document.setup", &json!({ "bleed": bleed })).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// A rectangle from (x0, y0) to (x1, y1) without a stroke, on the current layer.
|
||||
fn plain_rect(s: &mut Session, [x0, y0, x1, y1]: [f64; 4]) -> Value {
|
||||
let id = s.execute("shape.rectangle", &json!({"x": x0, "y": y0, "width": x1 - x0, "height": y1 - y0})).unwrap()["id"].clone();
|
||||
s.execute("paint.setStroke", &json!({"ids": [id], "none": true})).unwrap();
|
||||
id
|
||||
}
|
||||
|
||||
/// The warnings of a PDF that carries the document's bleed that say art stops short of it.
|
||||
fn short_of_bleed(s: &mut Session) -> Vec<String> {
|
||||
let (_, warnings) = pdf(s, json!({"bleed": {"useDocument": true}}));
|
||||
warnings.into_iter().filter(|w| super::pdf::is_short_of_bleed(w)).collect()
|
||||
}
|
||||
|
||||
const MM: f64 = 72.0 / 25.4;
|
||||
|
||||
/// A bleed raised from 2 mm to 5 mm leaves a background that filled the old bleed, and a band
|
||||
/// placed against the trim edge, short of the new one: the export warns once, counting both.
|
||||
#[test]
|
||||
fn art_that_reaches_the_trim_edge_but_stops_short_of_the_bleed_warns() {
|
||||
let mut s = bleed_session(json!(2.0 * MM));
|
||||
let (b, w, h) = (2.0 * MM, 200.0, 100.0);
|
||||
plain_rect(&mut s, [-b, -b, w + b, h + b]);
|
||||
plain_rect(&mut s, [0.0, 0.0, w, 20.0]);
|
||||
// At 2 mm the background reaches the bleed; the band stops at the trim edge.
|
||||
assert_eq!(short_of_bleed(&mut s), ["1 object reaches the trim edge but stops short of the bleed"]);
|
||||
s.execute("document.setup", &json!({"bleed": 5.0 * MM})).unwrap();
|
||||
assert_eq!(short_of_bleed(&mut s), ["2 objects reach the trim edge but stop short of the bleed"]);
|
||||
// The PDF/X presets carry the document's bleed.
|
||||
let (_, warnings) = pdf(&mut s, json!({"preset": "PDF/X-4:2010"}));
|
||||
assert!(warnings.iter().any(|w| super::pdf::is_short_of_bleed(w)), "{warnings:?}");
|
||||
// A PDF/X file with a bleed on the top alone leaves out the rest of the document's bleed, and
|
||||
// the background and the band stop short at the top: the warning comes right after
|
||||
// BLEED_LEFT_OUT.
|
||||
let (_, warnings) = pdf(&mut s, json!({"standard": "pdfX4", "bleed": {"top": 9}}));
|
||||
assert_eq!(warnings.first().map(String::as_str), Some(super::pdf::BLEED_LEFT_OUT), "{warnings:?}");
|
||||
assert_eq!(warnings.get(1).map(String::as_str), Some("2 objects reach the trim edge but stop short of the bleed"), "{warnings:?}");
|
||||
// A page without the bleed (the default preset) doesn't warn, and neither does a page of the art's bounds.
|
||||
let (_, warnings) = pdf(&mut s, json!({}));
|
||||
assert!(!warnings.iter().any(|w| super::pdf::is_short_of_bleed(w)), "{warnings:?}");
|
||||
let (_, warnings) = pdf(&mut s, json!({"bleed": {"useDocument": true}, "useArtboards": false}));
|
||||
assert!(!warnings.iter().any(|w| super::pdf::is_short_of_bleed(w)), "{warnings:?}");
|
||||
// An explicit bleed counts too, and the Summary lists the warning.
|
||||
let (_, warnings) = pdf(&mut s, json!({"bleed": {"top": 9, "bottom": 9, "left": 9, "right": 9}}));
|
||||
assert!(warnings.iter().any(|w| super::pdf::is_short_of_bleed(w)), "{warnings:?}");
|
||||
let v = s.execute("document.pdfSettings", &json!({"bleed": {"useDocument": true}, "includeDocument": true})).unwrap();
|
||||
assert!(v["warnings"].as_array().unwrap().iter().any(|w| super::pdf::is_short_of_bleed(w.as_str().unwrap())), "{v}");
|
||||
// A group counts once, measured by its visible members: a hidden member that fills the bleed
|
||||
// doesn't hide a visible one at the trim edge.
|
||||
let mut s = bleed_session(json!(9));
|
||||
let fill = plain_rect(&mut s, [-9.0, -9.0, 209.0, 109.0]);
|
||||
let band = plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]);
|
||||
let side = plain_rect(&mut s, [0.0, 40.0, 20.0, 60.0]);
|
||||
s.execute("object.group", &json!({"ids": [fill, band, side]})).unwrap();
|
||||
s.execute("object.hide", &json!({"ids": [fill]})).unwrap();
|
||||
assert_eq!(short_of_bleed(&mut s), ["1 object reaches the trim edge but stops short of the bleed"]);
|
||||
// A clip group is measured by the art inside its clipping path, not by a clipping path that
|
||||
// reaches the bleed edge.
|
||||
let mut s = bleed_session(json!(9));
|
||||
let art = plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]);
|
||||
let clip = plain_rect(&mut s, [-9.0, -9.0, 209.0, 109.0]);
|
||||
s.execute("select.set", &json!({"ids": [art, clip]})).unwrap();
|
||||
s.execute("object.clippingMask.make", &json!({})).unwrap();
|
||||
assert_eq!(short_of_bleed(&mut s).len(), 1);
|
||||
// A clipping path that paints a fill reaching the trim edge counts, though the art it clips is
|
||||
// inside: in a clip group, and as an object of its own in a clipping layer.
|
||||
let mut s = bleed_session(json!(9));
|
||||
let art = plain_rect(&mut s, [20.0, 30.0, 60.0, 60.0]);
|
||||
let clip = plain_rect(&mut s, [0.0, 0.0, 200.0, 100.0]);
|
||||
s.execute("select.set", &json!({"ids": [art, clip]})).unwrap();
|
||||
s.execute("object.clippingMask.make", &json!({})).unwrap();
|
||||
assert!(short_of_bleed(&mut s).is_empty());
|
||||
s.execute("paint.setFill", &json!({"ids": [clip], "color": "#ff0000"})).unwrap();
|
||||
assert_eq!(short_of_bleed(&mut s).len(), 1);
|
||||
let mut s = bleed_session(json!(9));
|
||||
let clipping = s.execute("layer.new", &json!({})).unwrap()["id"].clone();
|
||||
plain_rect(&mut s, [20.0, 30.0, 60.0, 60.0]);
|
||||
let clip = plain_rect(&mut s, [0.0, 0.0, 200.0, 100.0]);
|
||||
s.execute("layer.clippingMask.toggle", &json!({"id": clipping})).unwrap();
|
||||
assert!(short_of_bleed(&mut s).is_empty());
|
||||
s.execute("paint.setFill", &json!({"ids": [clip], "color": "#ff0000"})).unwrap();
|
||||
assert_eq!(short_of_bleed(&mut s).len(), 1);
|
||||
// A hidden brushed member doesn't keep a group's visible art at the trim edge from counting.
|
||||
let mut s = bleed_session(json!(9));
|
||||
let brushed = plain_rect(&mut s, [-9.0, -9.0, 209.0, 109.0]);
|
||||
s.execute("brush.apply", &json!({"ids": [brushed], "name": "Charcoal"})).unwrap();
|
||||
let band = plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]);
|
||||
s.execute("object.group", &json!({"ids": [brushed, band]})).unwrap();
|
||||
s.execute("object.hide", &json!({"ids": [brushed]})).unwrap();
|
||||
assert_eq!(short_of_bleed(&mut s).len(), 1);
|
||||
// A clipping layer clips its art to the clipping path's geometry, not to the stroke around it:
|
||||
// the stroke reaches the trim edge, but the art it clips stops 5 pt inside.
|
||||
let mut s = bleed_session(json!(9));
|
||||
let clipping = s.execute("layer.new", &json!({})).unwrap()["id"].clone();
|
||||
plain_rect(&mut s, [-9.0, -9.0, 209.0, 109.0]);
|
||||
let clip = plain_rect(&mut s, [5.0, 5.0, 195.0, 95.0]);
|
||||
s.execute("layer.clippingMask.toggle", &json!({"id": clipping})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [clip], "color": "#ff0000"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"ids": [clip], "weight": 10})).unwrap();
|
||||
assert_eq!(short_of_bleed(&mut s), ["1 object reaches the trim edge but stops short of the bleed"]);
|
||||
}
|
||||
|
||||
/// No warning for art that already fills the bleed, art inside the trim, a document without a
|
||||
/// bleed, art on hidden, non-printing or template layers, a side without a bleed, area type, a
|
||||
/// masked object, or a `.ai` save.
|
||||
#[test]
|
||||
fn art_that_fills_the_bleed_or_stays_inside_does_not_warn() {
|
||||
let mut s = bleed_session(json!(9));
|
||||
plain_rect(&mut s, [-9.0, -9.0, 209.0, 109.0]);
|
||||
plain_rect(&mut s, [-20.0, 40.0, 50.0, 60.0]);
|
||||
plain_rect(&mut s, [10.0, 10.0, 190.0, 90.0]);
|
||||
assert!(short_of_bleed(&mut s).is_empty());
|
||||
// A document without a bleed has nothing to fall short of.
|
||||
let mut s = bleed_session(json!(0));
|
||||
plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]);
|
||||
assert!(short_of_bleed(&mut s).is_empty());
|
||||
// Layers that don't print.
|
||||
for props in [json!({"visible": false}), json!({"printable": false}), json!({"template": true})] {
|
||||
let mut s = bleed_session(json!(9));
|
||||
let layer = s.execute("layer.new", &json!({})).unwrap()["id"].clone();
|
||||
plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]);
|
||||
let mut p = props.clone();
|
||||
p["id"] = layer;
|
||||
s.execute("layer.setProps", &p).unwrap();
|
||||
assert!(short_of_bleed(&mut s).is_empty(), "{props}");
|
||||
}
|
||||
// A hidden object, and a group whose hidden member is the one at the trim edge.
|
||||
let mut s = bleed_session(json!(9));
|
||||
let id = plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]);
|
||||
s.execute("object.hide", &json!({"ids": [id]})).unwrap();
|
||||
assert!(short_of_bleed(&mut s).is_empty());
|
||||
let mut s = bleed_session(json!(9));
|
||||
let edge = plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]);
|
||||
let inside = plain_rect(&mut s, [10.0, 30.0, 50.0, 60.0]);
|
||||
s.execute("object.group", &json!({"ids": [edge, inside]})).unwrap();
|
||||
s.execute("object.hide", &json!({"ids": [edge]})).unwrap();
|
||||
assert!(short_of_bleed(&mut s).is_empty());
|
||||
// Art that lies in the bleed alone, away from the trim edge.
|
||||
let mut s = bleed_session(json!(9));
|
||||
plain_rect(&mut s, [20.0, -5.0, 60.0, -3.0]);
|
||||
assert!(short_of_bleed(&mut s).is_empty());
|
||||
// A guide in a group at the trim edge.
|
||||
let mut s = bleed_session(json!(9));
|
||||
let guide = plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]);
|
||||
s.execute("view.guides.make", &json!({})).unwrap();
|
||||
let inside = plain_rect(&mut s, [10.0, 30.0, 50.0, 60.0]);
|
||||
s.execute("object.group", &json!({"ids": [guide, inside]})).unwrap();
|
||||
assert!(short_of_bleed(&mut s).is_empty());
|
||||
// A brushed stroke, whose brush art can paint past its visual bounds, is not measured.
|
||||
let mut s = bleed_session(json!(9));
|
||||
let id = plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]);
|
||||
s.execute("brush.apply", &json!({"ids": [id], "name": "Charcoal"})).unwrap();
|
||||
assert!(short_of_bleed(&mut s).is_empty());
|
||||
// A path with no fill and no stroke paints nothing.
|
||||
let mut s = bleed_session(json!(9));
|
||||
let id = plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]);
|
||||
s.execute("paint.setFill", &json!({"ids": [id], "none": true})).unwrap();
|
||||
assert!(short_of_bleed(&mut s).is_empty());
|
||||
// An object at 0% opacity draws nothing.
|
||||
let mut s = bleed_session(json!(9));
|
||||
let id = plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]);
|
||||
s.execute("object.setProps", &json!({"ids": [id], "opacity": 0})).unwrap();
|
||||
assert!(short_of_bleed(&mut s).is_empty());
|
||||
// A clipping layer whose clipping path lies inside the trim draws none of its art at the edge.
|
||||
let mut s = bleed_session(json!(9));
|
||||
let clipping = s.execute("layer.new", &json!({})).unwrap()["id"].clone();
|
||||
plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]);
|
||||
plain_rect(&mut s, [10.0, 10.0, 60.0, 60.0]);
|
||||
s.execute("layer.clippingMask.toggle", &json!({"id": clipping})).unwrap();
|
||||
assert!(short_of_bleed(&mut s).is_empty());
|
||||
// A bleed on the top alone: art short at the left doesn't count, art short at the top does.
|
||||
let mut s = bleed_session(json!([9, 0, 0, 0]));
|
||||
plain_rect(&mut s, [0.0, 30.0, 40.0, 60.0]);
|
||||
assert!(short_of_bleed(&mut s).is_empty());
|
||||
plain_rect(&mut s, [60.0, 0.0, 100.0, 40.0]);
|
||||
assert_eq!(short_of_bleed(&mut s).len(), 1);
|
||||
// Area type is bounded by its frame, not its glyphs: a frame at the trim edge is not measured.
|
||||
let mut s = bleed_session(json!(9));
|
||||
s.execute("text.create", &json!({"x": 0, "y": 0, "text": "Title", "size": 12, "area": {"width": 200, "height": 40}})).unwrap();
|
||||
assert!(short_of_bleed(&mut s).is_empty());
|
||||
// An opacity mask decides what shows of the object, so a masked object is not measured.
|
||||
let mut s = bleed_session(json!(9));
|
||||
let band = plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]);
|
||||
let mask = plain_rect(&mut s, [20.0, 30.0, 60.0, 60.0]);
|
||||
s.execute("transparency.makeOpacityMask", &json!({"ids": [band, mask]})).unwrap();
|
||||
assert!(short_of_bleed(&mut s).is_empty());
|
||||
// A `.ai` save with a bleed doesn't warn: the check is PDF export's.
|
||||
let mut s = bleed_session(json!(9));
|
||||
plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]);
|
||||
assert_eq!(short_of_bleed(&mut s).len(), 1);
|
||||
let r = s.execute("document.export", &json!({"format": "ai", "bleed": {"useDocument": true}})).unwrap();
|
||||
assert!(!r["warnings"].to_string().contains("short of the bleed"), "{}", r["warnings"]);
|
||||
}
|
||||
|
||||
/// The warning changes neither the art nor the page boxes.
|
||||
#[test]
|
||||
fn the_bleed_warning_changes_no_geometry_and_no_page_box() {
|
||||
let mut s = bleed_session(json!(9));
|
||||
plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]);
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let v = s.execute("document.exportPdf", &json!({"bleed": {"useDocument": true}})).unwrap();
|
||||
assert!(v["warnings"].as_array().unwrap().iter().any(|w| super::pdf::is_short_of_bleed(w.as_str().unwrap())), "{v}");
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
let info = s.execute("document.pdfInfo", &json!({"name": "x.pdf", "dataBase64": v["dataBase64"]})).unwrap();
|
||||
let boxes = &info["pageInfo"][0]["boxes"];
|
||||
let side = |b: &Value| {
|
||||
let n: Vec<f64> = b.as_array().unwrap().iter().map(|x| x.as_f64().unwrap()).collect();
|
||||
(((n[2] - n[0]) * 100.0).round() / 100.0, ((n[3] - n[1]) * 100.0).round() / 100.0)
|
||||
};
|
||||
assert_eq!(side(&boxes["trim"]), (200.0, 100.0), "{info}");
|
||||
assert_eq!(side(&boxes["bleed"]), (218.0, 118.0), "{info}");
|
||||
}
|
||||
|
||||
/// The ink amounts (0..1) `doc` shows at `p` in its images (the topmost image there).
|
||||
fn image_inks_at(doc: &vectorcraft_doc::Document, p: vectorcraft_geom::Point) -> Option<[f32; 4]> {
|
||||
fn visit(n: &vectorcraft_doc::Node, out: &mut Vec<vectorcraft_doc::ImageObject>) {
|
||||
|
||||
@@ -602,6 +602,56 @@ fn relink_and_update_follow_the_clipping_path_of_a_linked_psd() {
|
||||
assert_eq!(clip_group(&s.doc().unwrap().doc, group), (squared, true, NodeId(image)), "links.update reads the clipping path again");
|
||||
}
|
||||
|
||||
/// Unembed keeps the clip group of the clipping path an embedded PSD file's image came with, with a
|
||||
/// path and with a folder, and so do relinking to the written file, placing it and opening it.
|
||||
#[test]
|
||||
fn unembed_keeps_the_clipping_path_of_an_embedded_psd() {
|
||||
let dir = vectorcraft_testkit::TempDir::new("psd-unembed-clip");
|
||||
// An RGB file is kept as a PNG, a CMYK one as a TIFF.
|
||||
let cmyk = psd(1, 4, (100, 50), 8, 4, &[], &triangle_resources(), &[], &raw(&[&[0; 5000], &[255; 5000], &[255; 5000], &[0; 5000]]));
|
||||
let files = [("rgb", red_psd(&triangle_resources())), ("cmyk", cmyk)];
|
||||
for ((kind, file), folder) in files.iter().flat_map(|f| [(f, false), (f, true)]) {
|
||||
let data = vectorcraft_format::base64_encode(file);
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap();
|
||||
let r = s.execute("file.place", &json!({"name": "cut.psd", "dataBase64": data, "at": [50, 25]})).unwrap();
|
||||
let (group, image) = (NodeId(r["ids"][0].as_u64().unwrap()), NodeId(r["image"].as_u64().unwrap()));
|
||||
let before = clip_group(&s.doc().unwrap().doc, group);
|
||||
// Without an extension the image is written in the format it is stored in.
|
||||
let path = if folder {
|
||||
let out = dir.join(format!("folder-{kind}"));
|
||||
std::fs::create_dir_all(&out).unwrap();
|
||||
let r = s.execute("links.unembed", &json!({"ids": [image.0], "folder": out})).unwrap();
|
||||
r["unembedded"][0]["path"].as_str().unwrap().to_string()
|
||||
} else {
|
||||
let r = s.execute("links.unembed", &json!({"id": image.0, "path": dir.join(format!("written-{kind}"))})).unwrap();
|
||||
r["path"].as_str().unwrap().to_string()
|
||||
};
|
||||
let ext = if *kind == "rgb" { ["png"].as_slice() } else { ["tif", "tiff"].as_slice() };
|
||||
assert!(ext.contains(&super::extension(&path).as_str()), "{kind}: {path}");
|
||||
for step in ["unembed", "relink"] {
|
||||
if step == "relink" {
|
||||
s.execute("links.relink", &json!({"ids": [image.0], "path": path})).unwrap();
|
||||
}
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let NodeKind::Image(im) = &d.node(image).unwrap().kind else { panic!("an image") };
|
||||
assert!(im.link.is_some(), "linked to the file written");
|
||||
assert_eq!(clip_group(d, group), before, "{kind}, {step}, folder: {folder}");
|
||||
}
|
||||
// Placing the written file gives the same clip group as placing the PSD file did.
|
||||
let r = s.execute("file.place", &json!({"path": path, "at": [50, 25]})).unwrap();
|
||||
let placed = NodeId(r["ids"][0].as_u64().unwrap());
|
||||
let (anchors, even_odd, _) = clip_group(&s.doc().unwrap().doc, placed);
|
||||
assert_eq!((anchors, even_odd), (before.0.clone(), true), "{kind}, place");
|
||||
// Opening it gives a document of the image in that clip group.
|
||||
s.execute("document.open", &json!({"path": path})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let top = d.layers[0].children().and_then(|c| c.first()).map(|c| c.id).expect("an object");
|
||||
let (anchors, even_odd, _) = clip_group(d, top);
|
||||
assert_eq!((anchors, even_odd), (before.0.clone(), true), "{kind}, open");
|
||||
}
|
||||
}
|
||||
|
||||
/// The PNG a PSD file's merged image is kept as holds the clipping path the file names, and only a
|
||||
/// text chunk within the size limit that reads as a path gives one back.
|
||||
#[test]
|
||||
|
||||
@@ -610,6 +610,35 @@ fn include_bleed_pdfx_rows_do_not_warn_about_the_bleed() {
|
||||
assert!(warned(&export(&mut s, json!({"includeBleed": true, "selection": "one", "formats": row}))));
|
||||
}
|
||||
|
||||
/// A PDF row with a bleed warns about art that reaches an artboard's edge and stops short of the
|
||||
/// bleed, with or without Include Bleed: the page's trim is the artboard either way. It doesn't
|
||||
/// warn about art that reaches the bleed, or on a page of a selection's bounds.
|
||||
#[test]
|
||||
fn pdf_rows_warn_about_art_short_of_the_bleed_on_artboard_pages_only() {
|
||||
let warned = |r: &Value| r["warnings"].as_array().unwrap().iter().any(|w| super::pdf::is_short_of_bleed(w.as_str().unwrap()));
|
||||
let row = json!([{"format": "pdf", "bleed": {"useDocument": true}}]);
|
||||
let mut s = session(1);
|
||||
s.execute("document.setup", &json!({"bleed": 6})).unwrap();
|
||||
// Against the artboard's top edge.
|
||||
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 40, "height": 10})).unwrap();
|
||||
assert!(warned(&export(&mut s, json!({"formats": row}))));
|
||||
assert!(warned(&export(&mut s, json!({"includeBleed": true, "formats": row}))));
|
||||
assert!(warned(&export(&mut s, json!({"includeBleed": true, "formats": [{"format": "pdf"}]}))), "the row takes the document's bleed");
|
||||
assert!(!warned(&export(&mut s, json!({"selection": "one", "formats": row}))));
|
||||
assert!(!warned(&export(&mut s, json!({"includeBleed": true, "selection": "one", "formats": row}))));
|
||||
// Out to the bleed edge on the top, left and right.
|
||||
let mut s = session(1);
|
||||
s.execute("document.setup", &json!({"bleed": 6})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": -6, "y": -6, "width": 52, "height": 16})).unwrap();
|
||||
assert!(!warned(&export(&mut s, json!({"formats": row}))));
|
||||
assert!(!warned(&export(&mut s, json!({"includeBleed": true, "formats": row}))));
|
||||
// Without a document bleed, a row's own bleed warns.
|
||||
let mut s = session(1);
|
||||
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 40, "height": 10})).unwrap();
|
||||
let row = json!([{"format": "pdf", "bleed": {"top": 6, "bottom": 6, "left": 6, "right": 6}}]);
|
||||
assert!(warned(&export(&mut s, json!({"includeBleed": true, "formats": row}))));
|
||||
}
|
||||
|
||||
/// Each `[x0 y0 x1 y1]` that follows `key` in a PDF's bytes, in the order the file has them, read
|
||||
/// as text without VectorCraft's PDF reader (PDF 32000-1:2008, 14.11.2, Page Boundaries).
|
||||
fn raw_boxes(pdf: &[u8], key: &str) -> Vec<[f64; 4]> {
|
||||
|
||||
@@ -437,3 +437,48 @@ fn svg_darkness_uses_rendered_shadow_in_non_srgb_working_space() {
|
||||
assert!(a.iter().zip(b).all(|(a, b)| a.abs_diff(b) <= 8), "at {x}: {a:?} vs {b:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// #864 / G11: SVG export preserves the document's physical units on the root `width`/`height` so
|
||||
/// that the unit setting survives a save/open round-trip. The engine-level test covers the full
|
||||
/// stack (file.new → document.setUnits → document.serialize → document.open).
|
||||
#[test]
|
||||
fn svg_round_trip_preserves_document_units() {
|
||||
// (unit name the engine accepts, expected unit after re-import)
|
||||
let cases: &[(&str, vectorcraft_doc::Unit)] = &[
|
||||
("millimeters", vectorcraft_doc::Unit::Millimeters),
|
||||
("centimeters", vectorcraft_doc::Unit::Centimeters),
|
||||
("inches", vectorcraft_doc::Unit::Inches),
|
||||
("picas", vectorcraft_doc::Unit::Picas),
|
||||
// Points and pixels both serialise as bare user-unit numbers, so both import as Pixels.
|
||||
("pixels", vectorcraft_doc::Unit::Pixels),
|
||||
];
|
||||
for (name, expected) in cases {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 1})).unwrap();
|
||||
s.execute("document.setUnits", &json!({"units": name})).unwrap();
|
||||
let r = s.execute("document.serialize", &json!({"format": "svg"})).unwrap();
|
||||
let svg_text = r["text"].as_str().unwrap();
|
||||
match *expected {
|
||||
vectorcraft_doc::Unit::Millimeters => assert!(svg_text.contains("mm\""), "mm suffix missing: {svg_text}"),
|
||||
vectorcraft_doc::Unit::Centimeters => assert!(svg_text.contains("cm\""), "cm suffix missing: {svg_text}"),
|
||||
vectorcraft_doc::Unit::Inches => assert!(svg_text.contains("in\""), "in suffix missing: {svg_text}"),
|
||||
vectorcraft_doc::Unit::Picas => assert!(svg_text.contains("pc\""), "pc suffix missing: {svg_text}"),
|
||||
_ => {}
|
||||
}
|
||||
let b64 = vectorcraft_format::base64_encode(svg_text.as_bytes());
|
||||
s.execute("document.open", &json!({"name": "test.svg", "dataBase64": b64})).unwrap();
|
||||
let doc_state = s.doc().unwrap();
|
||||
assert_eq!(doc_state.doc.units, *expected, "unit mismatch after round-trip for '{name}'");
|
||||
}
|
||||
|
||||
// Points serialise without suffix and re-open as Pixels (equivalent in user units).
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 1})).unwrap();
|
||||
s.execute("document.setUnits", &json!({"units": "points"})).unwrap();
|
||||
let r = s.execute("document.serialize", &json!({"format": "svg"})).unwrap();
|
||||
let svg_text = r["text"].as_str().unwrap();
|
||||
assert!(svg_text.contains("width=\"200\" height=\"100\""), "{svg_text}");
|
||||
let b64 = vectorcraft_format::base64_encode(svg_text.as_bytes());
|
||||
s.execute("document.open", &json!({"name": "test.svg", "dataBase64": b64})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.units, vectorcraft_doc::Unit::Pixels);
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
//! Flares (the Flare tool): `shape.flare` draws a group of radial-gradient paths that keeps the
|
||||
//! settings it was drawn with ([`FlareSpec`]), and `shape.editFlare` draws it again from them.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::flare::{DEFAULT_SEED, FlareSpec, json_close, part_node, parts};
|
||||
use vectorcraft_doc::{Document, Node, NodeId};
|
||||
use vectorcraft_geom::{Affine, Point, Vec2};
|
||||
|
||||
use super::{EngineError, Result, Session, bad, check_numbers, f64_or, f64_req, given_objects, number_or};
|
||||
|
||||
const C: &str = "shape.editFlare";
|
||||
|
||||
/// `shape.flare`'s settings besides the center, the rings' end point, the counts and the seed:
|
||||
/// (key, default).
|
||||
const SETTINGS: [(&str, f64); 9] = [
|
||||
("diameter", 100.0),
|
||||
("opacity", 50.0),
|
||||
("brightness", 30.0),
|
||||
("growth", 20.0),
|
||||
("fuzziness", 50.0),
|
||||
("longest", 300.0),
|
||||
("rayFuzziness", 100.0),
|
||||
("rotation", 0.0),
|
||||
("largest", 50.0),
|
||||
];
|
||||
|
||||
/// The whole number of 0 or more `p` gives for `key`, or `default`.
|
||||
fn count_or(p: &Value, key: &str, default: u64, cmd: &str) -> Result<u64> {
|
||||
let n = number_or(p, key, default as f64, cmd)?;
|
||||
if n.is_finite() && n >= 0.0 && n.fract() == 0.0 {
|
||||
Ok(n as u64)
|
||||
} else {
|
||||
Err(bad(cmd, format!("`{key}` must be a whole number of at least 0, not {n}")))
|
||||
}
|
||||
}
|
||||
|
||||
/// `end`, the rings' end point, or an error naming `x2` or `y2` when that coordinate is not a
|
||||
/// finite number (a `pathLength` so large that the end point overflows).
|
||||
fn finite_end(end: Point, cmd: &str) -> Result<Point> {
|
||||
match [("x2", end.x), ("y2", end.y)].into_iter().find(|(_, v)| !v.is_finite()) {
|
||||
None => Ok(end),
|
||||
Some((key, _)) => Err(bad(cmd, format!("{key} must be a finite coordinate"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// `shape.flare`'s params `p` with every setting given: the defaults filled in, the counts at most
|
||||
/// 50 and the rings' end point as `x2`, `y2` (from `pathLength` and `direction` when `p` gives no
|
||||
/// end point), with `ringSeed` when `p` gives one.
|
||||
fn settings_of(p: &Value, cmd: &str) -> Result<Value> {
|
||||
let c = Point::new(f64_req(p, "cx", cmd)?, f64_req(p, "cy", cmd)?);
|
||||
let mut numbers: Vec<&str> = SETTINGS.iter().map(|(key, _)| *key).collect();
|
||||
numbers.extend(["x2", "y2", "direction", "pathLength", "seed", "ringSeed"]);
|
||||
check_numbers(p, &numbers, cmd)?;
|
||||
let seed_of = |key: &str| match p.get(key) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(v) => v.as_u64().map(Some).ok_or_else(|| bad(cmd, format!("`{key}` must be a whole number of at least 0, not {v}"))),
|
||||
};
|
||||
let seed = seed_of("seed")?.unwrap_or(DEFAULT_SEED);
|
||||
// Each `ringSeed` below 2^53 (what a JSON number holds exactly) places the rings anew.
|
||||
let ring_seed = match seed_of("ringSeed")? {
|
||||
Some(r) if r >= 1 << 53 => return Err(bad(cmd, format!("`ringSeed` must be below 2^53, not {r}"))),
|
||||
r => r,
|
||||
};
|
||||
let rays = count_or(p, "rays", 15, cmd)?.min(50);
|
||||
let rings = count_or(p, "rings", 10, cmd)?.min(50);
|
||||
let end = match (p.get("x2").and_then(Value::as_f64), p.get("y2").and_then(Value::as_f64)) {
|
||||
(Some(x), Some(y)) => Point::new(x, y),
|
||||
_ => {
|
||||
let a = f64_or(p, "direction", 45.0).to_radians();
|
||||
finite_end(c + Vec2::new(a.cos(), -a.sin()) * f64_or(p, "pathLength", 300.0), cmd)?
|
||||
}
|
||||
};
|
||||
let mut v = json!({ "cx": c.x, "cy": c.y, "x2": end.x, "y2": end.y, "rays": rays, "rings": rings, "seed": seed });
|
||||
if let Some(r) = ring_seed {
|
||||
v["ringSeed"] = json!(r);
|
||||
}
|
||||
for (key, default) in SETTINGS {
|
||||
v[key] = json!(f64_or(p, key, default));
|
||||
}
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// The objects of a flare drawn with the settings `v`, transformed by `xf`. A new flare's parts
|
||||
/// (`old` None) get new ids and take the document's Align New Objects to Pixel Grid. A flare drawn
|
||||
/// again from its parts `old` keeps, for each part, the id and pixel-aligned property of the old
|
||||
/// part it replaces (the same kind of part, counted in order: the second ring replaces the second
|
||||
/// ring); a part that replaces none gets a new id and the first old part's property.
|
||||
fn part_nodes(d: &mut Document, v: &Value, xf: Affine, old: Option<&[Arc<Node>]>) -> Vec<Arc<Node>> {
|
||||
let mut seen: Vec<&str> = vec![];
|
||||
parts(v)
|
||||
.into_iter()
|
||||
.map(|part| {
|
||||
let name = part.0;
|
||||
let nth = seen.iter().filter(|n| **n == name).count();
|
||||
seen.push(name);
|
||||
let replaced = old.and_then(|old| old.iter().filter(|c| c.name.as_deref() == Some(name)).nth(nth));
|
||||
let id = replaced.map_or_else(|| d.alloc_id(), |c| c.id);
|
||||
let mut n = part_node(id, part, Affine::IDENTITY, false);
|
||||
match old {
|
||||
None => super::object::align_new_object(d, &mut n),
|
||||
Some(old) => n.extras_mut().pixel_aligned = replaced.or(old.first()).is_some_and(|c| c.extras().pixel_aligned),
|
||||
}
|
||||
if xf != Affine::IDENTITY {
|
||||
n.transform(xf, false);
|
||||
}
|
||||
Arc::new(n)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `shape.flare`: a flare group that keeps its settings.
|
||||
pub(super) fn flare(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let v = settings_of(p, "shape.flare")?;
|
||||
let parent = s.doc()?.target_parent()?;
|
||||
let id = s.edit("Flare", |d, sel| {
|
||||
let children = part_nodes(d, &v, Affine::IDENTITY, None);
|
||||
let gid = d.alloc_id();
|
||||
let mut g = Node::group(gid, children);
|
||||
g.name = Some("Flare".into());
|
||||
g.extras_mut().flare = Some(Box::new(FlareSpec::new(v)));
|
||||
d.insert(parent, usize::MAX, g)?;
|
||||
sel.set([gid]);
|
||||
Ok(gid)
|
||||
})?;
|
||||
Ok(json!({ "id": id.0 }))
|
||||
}
|
||||
|
||||
/// The settings of flare `id`: a group drawn by the Flare tool whose parts are still the ones its
|
||||
/// settings draw, in place ([`FlareSpec::draws`]). A flare whose parts were edited, distorted,
|
||||
/// removed or added to, or whose art was flattened to a line, is no longer one.
|
||||
pub fn flare_settings(d: &Document, id: NodeId) -> Option<FlareSpec> {
|
||||
let n = d.node(id)?;
|
||||
let spec = n.extras().flare.as_deref()?;
|
||||
// Settings a file holds are read as `shape.flare` reads them.
|
||||
let spec = FlareSpec { params: settings_of(&spec.params, "shape.flare").ok()?, transform: spec.transform };
|
||||
spec.draws(n).then_some(spec)
|
||||
}
|
||||
|
||||
/// The flares `shape.editFlare` changes: those `p` names, else the selected flares. Each must be a
|
||||
/// flare that can be edited.
|
||||
fn flares_to_edit(s: &Session, p: &Value) -> Result<Vec<(NodeId, FlareSpec)>> {
|
||||
let given = given_objects(s, p, C)?;
|
||||
let d = &s.doc()?.doc;
|
||||
let flare = |id: NodeId| flare_settings(d, id).filter(|_| d.is_editable(id)).map(|spec| (id, spec));
|
||||
let flares: Vec<(NodeId, FlareSpec)> = match &given {
|
||||
Some(ids) => ids.iter().map(|id| flare(*id)).collect::<Option<Vec<_>>>().unwrap_or_default(),
|
||||
None => s.doc()?.selection.objects.iter().filter_map(|id| flare(*id)).collect(),
|
||||
};
|
||||
if flares.is_empty() {
|
||||
return Err(EngineError::Other("select a flare".into()));
|
||||
}
|
||||
Ok(flares)
|
||||
}
|
||||
|
||||
/// The settings `old` changed as `p` asks (`shape.editFlare`'s params). The center and the end
|
||||
/// point `p` gives are in the document, where the flare is now drawn, which `xf` maps from where
|
||||
/// it was drawn.
|
||||
fn edited(old: &Value, p: &Value, xf: Affine) -> Result<Value> {
|
||||
let mut v = old.clone();
|
||||
let inv = xf.inverse();
|
||||
let point = |kx: &str, ky: &str| -> Result<Option<Point>> {
|
||||
if p.get(kx).is_none_or(Value::is_null) && p.get(ky).is_none_or(Value::is_null) {
|
||||
return Ok(None);
|
||||
}
|
||||
// A point that leaves the finite range where the flare was drawn is refused, not stored.
|
||||
let q = inv * Point::new(f64_req(p, kx, C)?, f64_req(p, ky, C)?);
|
||||
match [(kx, q.x), (ky, q.y)].into_iter().find(|(_, v)| !v.is_finite()) {
|
||||
None => Ok(Some(q)),
|
||||
Some((key, _)) => Err(bad(C, format!("{key} must be a finite coordinate"))),
|
||||
}
|
||||
};
|
||||
let c = point("cx", "cy")?;
|
||||
let end = point("x2", "y2")?;
|
||||
if let Some(c) = c {
|
||||
v["cx"] = json!(c.x);
|
||||
v["cy"] = json!(c.y);
|
||||
}
|
||||
let centre = Point::new(f64_or(&v, "cx", 0.0), f64_or(&v, "cy", 0.0));
|
||||
let old_end = Point::new(f64_or(&v, "x2", centre.x), f64_or(&v, "y2", centre.y));
|
||||
let end = match end {
|
||||
Some(e) => e,
|
||||
None if p.get("pathLength").is_some_and(|l| !l.is_null()) || p.get("direction").is_some_and(|a| !a.is_null()) => {
|
||||
// The path length and the direction are where the flare is drawn now; the direction is
|
||||
// measured counter-clockwise from 3 o'clock, as `shape.flare` takes it.
|
||||
let (c, e) = (xf * centre, xf * old_end);
|
||||
let d = e - c;
|
||||
let a = number_or(p, "direction", (-d.y).atan2(d.x).to_degrees(), C)?.to_radians();
|
||||
finite_end(inv * (c + Vec2::new(a.cos(), -a.sin()) * number_or(p, "pathLength", d.hypot(), C)?), C)?
|
||||
}
|
||||
// Moving the center leaves the rings' end point where it is.
|
||||
None => old_end,
|
||||
};
|
||||
v["x2"] = json!(end.x);
|
||||
v["y2"] = json!(end.y);
|
||||
for (key, _) in SETTINGS {
|
||||
if p.get(key).is_some_and(|x| !x.is_null()) {
|
||||
v[key] = json!(number_or(p, key, 0.0, C)?);
|
||||
}
|
||||
}
|
||||
for key in ["rays", "rings"] {
|
||||
if p.get(key).is_some_and(|x| !x.is_null()) {
|
||||
v[key] = json!(count_or(p, key, 0, C)?.min(50));
|
||||
}
|
||||
}
|
||||
settings_of(&v, C)
|
||||
}
|
||||
|
||||
/// `shape.editFlare`: draw the flares again with the settings `p` changes, each in its place and
|
||||
/// transformed as it has been since it was drawn, as one undo step.
|
||||
pub(super) fn edit_flare(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut numbers: Vec<&str> = SETTINGS.iter().map(|(key, _)| *key).collect();
|
||||
numbers.extend(["cx", "cy", "x2", "y2", "pathLength", "direction", "rays", "rings"]);
|
||||
check_numbers(p, &numbers, C)?;
|
||||
let flares = flares_to_edit(s, p)?;
|
||||
let mut changed: Vec<(NodeId, FlareSpec)> = vec![];
|
||||
for (id, spec) in &flares {
|
||||
let v = edited(&spec.params, p, spec.transform)?;
|
||||
if !json_close(&v, &spec.params, 1e-9) {
|
||||
changed.push((*id, FlareSpec { params: v, transform: spec.transform }));
|
||||
}
|
||||
}
|
||||
let ids: Vec<u64> = flares.iter().map(|(id, _)| id.0).collect();
|
||||
// Nothing changes: no undo step.
|
||||
if changed.is_empty() {
|
||||
return Ok(json!({ "ids": ids }));
|
||||
}
|
||||
let edited_ids: Vec<NodeId> = changed.iter().map(|(id, _)| *id).collect();
|
||||
s.edit("Edit Flare", |d, _| {
|
||||
for (id, spec) in changed {
|
||||
let old: Vec<Arc<Node>> = d.node(id).and_then(Node::children).cloned().unwrap_or_default();
|
||||
let children = part_nodes(d, &spec.params, spec.transform, Some(&old));
|
||||
let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?;
|
||||
if let Some(ch) = n.children_mut() {
|
||||
*ch = children;
|
||||
}
|
||||
n.extras_mut().flare = Some(Box::new(spec));
|
||||
}
|
||||
if !crate::sanity::objects_in_range(d, &edited_ids) {
|
||||
return Err(EngineError::Other("result would exceed the canvas (coordinates out of range)".into()));
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "ids": ids }))
|
||||
}
|
||||
@@ -108,7 +108,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Unembed",
|
||||
[],
|
||||
None,
|
||||
"{id?: an embedded image (default: the one selected), path?, ids?: [image ids] (instead of id; one id is the same as id), folder?} write the image's pixels to the file at path (PNG, JPEG, GIF or WebP as stored, other images as PNG; a path ending in .png/.jpg/.jpeg/.gif/.webp/.tif/.tiff/.bmp converts them) and link the image to it, keeping its bounds. One undo step → {id, path}; no path → {name, dataBase64} (nothing changes: there is no file to link to). With folder: write each embedded image of ids or id (default: the selected embedded images) to a new file in folder, as stored (as PNG when that format is not one of VectorCraft's raster file formats), named after the image (characters a file name can't hold become _; Image when nothing is left), with Name 2 … Name 99 when the name is taken; a file already there is never replaced. Linked images among ids are left as they are. Each image links to its file and keeps its bounds. One undo step (undo does not remove the files); when a file can't be written, the files this call wrote are removed and nothing changes → {unembedded: [{id, path}], skipped: [ids of linked images]}; id with ids, path with folder, and ids of more or fewer than one image without folder are errors",
|
||||
"{id?: an embedded image (default: the one selected), path?, ids?: [image ids] (instead of id; one id is the same as id), folder?} write the image's pixels to the file at path (PNG, JPEG, GIF or WebP as stored, other images as PNG; a path ending in .png/.jpg/.jpeg/.gif/.webp/.tif/.tiff/.bmp converts them) and link the image to it, keeping its bounds; written as stored (here and with folder), an image from a PSD or PSB file keeps the clip group of the clipping path that file names, and the file written keeps the path, so Open, Place, Relink and Update Links read the file with that clip group. One undo step → {id, path}; no path → {name, dataBase64} (nothing changes: there is no file to link to). With folder: write each embedded image of ids or id (default: the selected embedded images) to a new file in folder, as stored (as PNG when that format is not one of VectorCraft's raster file formats), named after the image (characters a file name can't hold become _; Image when nothing is left), with Name 2 … Name 99 when the name is taken; a file already there is never replaced. Linked images among ids are left as they are. Each image links to its file and keeps its bounds. One undo step (undo does not remove the files); when a file can't be written, the files this call wrote are removed and nothing changes → {unembedded: [{id, path}], skipped: [ids of linked images]}; id with ids, path with folder, and ids of more or fewer than one image without folder are errors",
|
||||
has_doc,
|
||||
unembed
|
||||
),
|
||||
@@ -634,7 +634,8 @@ pub(crate) fn readable_and_kept(blob: ImageBlob, unread: bool, linked: bool) ->
|
||||
|
||||
/// The linked image file `bytes` (read from `path`, when there is one), read with its preview: a
|
||||
/// DCS file's plates, else its image ([`super::place::dcs::raster`]); an error when its pixels
|
||||
/// can't be read ([`readable`]).
|
||||
/// can't be read ([`readable`]). A PNG or TIFF that Unembed wrote from a PSD or PSB file's image
|
||||
/// is read with the clipping path it keeps ([`fileio::raster_image`]).
|
||||
fn linked_image(bytes: &[u8], path: Option<&str>) -> Result<RasterImage> {
|
||||
let mut img = super::place::dcs::raster(bytes, path)?;
|
||||
img.blob = readable(img.blob, kept_unread(bytes), true)?;
|
||||
|
||||
@@ -214,6 +214,25 @@ fn spine_points_param(p: &Value, cmd: &str) -> Result<Vec<usize>> {
|
||||
list.iter().map(|i| i.as_u64().and_then(|i| usize::try_from(i).ok()).ok_or_else(wrong)).collect()
|
||||
}
|
||||
|
||||
/// Whether linking handle `out` of spine point `index` at `q` would leave the blend's spine as it
|
||||
/// is (false when the blend or the point is not there, for the edit to report it).
|
||||
fn spine_link_unchanged(s: &Session, p: &Value, cmd: &str, index: usize, out: bool, q: Point) -> Result<bool> {
|
||||
let id = match crate::cmd::object_param(p, "id", cmd)? {
|
||||
Some(id) => Some(id),
|
||||
None => selected_of(s, is_blend).first().copied(),
|
||||
};
|
||||
let d = &s.doc()?.doc;
|
||||
let Some(NodeKind::Blend { children, spec }) = id.and_then(|id| d.node(id)).map(|n| &n.kind) else { return Ok(false) };
|
||||
let Some((path, _)) = live::pin_spine(children, spec) else { return Ok(false) };
|
||||
Ok(path.subpaths.first().is_some_and(|sp| {
|
||||
sp.anchors.get(index).is_some_and(|a| {
|
||||
let mut linked = *a;
|
||||
linked.link_handle(out, q, sp.has_segment(index, !out));
|
||||
linked == *a
|
||||
})
|
||||
}))
|
||||
}
|
||||
|
||||
pub(super) fn spine_move_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "object.blend.spine.moveAnchor";
|
||||
let index = index_param(p, "anchor", C)?;
|
||||
@@ -225,15 +244,33 @@ pub(super) fn spine_move_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(_) => return Err(bad(C, "handle must be in or out")),
|
||||
};
|
||||
let independent = switch_or(p, "independent", false, C)?;
|
||||
let link = switch_or(p, "link", false, C)?;
|
||||
let with = spine_points_param(p, C)?;
|
||||
// Any `with`, even an empty list, asks to move points, which a handle drag doesn't.
|
||||
if handle.is_some() && p.get("with").is_some_and(|v| !v.is_null()) {
|
||||
return Err(bad(C, "`with` moves points, not a handle"));
|
||||
}
|
||||
if link && independent {
|
||||
return Err(bad(C, "`link` and `independent` cannot both be true"));
|
||||
}
|
||||
if link && handle.is_none() {
|
||||
return Err(bad(C, "`link` places a handle: give `handle`"));
|
||||
}
|
||||
if link && let Some(out) = handle {
|
||||
// A spine point the linked handles would leave as it is records no undo step.
|
||||
if spine_link_unchanged(s, p, C, index, out, q)? {
|
||||
return ok();
|
||||
}
|
||||
}
|
||||
edit_spine(s, p, C, "Reshape Spine", |sp, anchors, keys| {
|
||||
let pull_out = handle.is_some_and(|out| sp.has_segment(index, !out));
|
||||
let a = sp.anchors.get_mut(index).ok_or_else(|| bad(C, "no such spine point"))?;
|
||||
if let Some(out) = handle {
|
||||
a.set_handle(out, q, independent);
|
||||
if link {
|
||||
a.link_handle(out, q, pull_out);
|
||||
} else {
|
||||
a.set_handle(out, q, independent);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let delta = q - a.p;
|
||||
|
||||
@@ -99,7 +99,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Spine Point",
|
||||
[],
|
||||
None,
|
||||
"{id? (default: the selected blend), anchor: index, x, y, with?: [index…], handle?: in|out, independent?: bool} move a point of the blend's spine (its handles along), and the points `with` names by as much, or with `handle` place that handle's end at (x, y) (a smooth point keeps the other handle in line unless `independent`). A key object sitting on a moved point moves with it. The first edit turns the straight spine into a path",
|
||||
"{id? (default: the selected blend), anchor: index, x, y, with?: [index…], handle?: in|out, independent?: bool, link?: bool} move a point of the blend's spine (its handles along), and the points `with` names by as much, or with `handle` place that handle's end at (x, y) (a smooth point keeps the other handle in line unless `independent`; `link` makes the point smooth with the other handle in line at its own length, a retracted one pulled out to the moved handle's length where a segment leaves the point on its side; `link` needs `handle` and cannot go with `independent`). A key object sitting on a moved point moves with it. The first edit turns the straight spine into a path",
|
||||
has_doc,
|
||||
spine_move_anchor
|
||||
),
|
||||
|
||||
@@ -30,7 +30,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Attributes",
|
||||
[],
|
||||
None,
|
||||
"{ids?|id?, item?, target?: \"object\"|\"contents\"} → {ids, overprintFill, overprintStroke, showCenter, imageMap: \"none\"|\"rectangle\"|\"polygon\", url, note, fillRule: \"nonZero\"|\"evenOdd\" (of the paths and compound paths in them), reversed (their subpaths run counter-clockwise on screen: Reverse Path Direction On), recentUrls: [newest first]} the Attributes panel's values for `ids` or the selection, overprint aimed as object.setOverprint aims; a value is null where they differ (or nothing has a fill, stroke or path)",
|
||||
"{ids?|id?, item?, target?: \"object\"|\"contents\"} → {ids, overprintFill, overprintStroke, showCenter, imageMap: \"none\"|\"rectangle\"|\"polygon\", url, note, fillRule: \"nonZero\"|\"evenOdd\" (of the paths and compound paths in them), reversed (their subpaths run counter-clockwise on screen: Reverse Path Direction On), recentUrls: [newest first, at most 30]} the Attributes panel's values for `ids` or the selection, overprint aimed as object.setOverprint aims; a value is null where they differ (or nothing has a fill, stroke or path)",
|
||||
has_doc,
|
||||
|s, p| Ok(attributes(s, p)?.to_json())
|
||||
),
|
||||
|
||||
@@ -382,6 +382,7 @@ pub fn check_keys(id: &str, doc: &'static str, params: &Value) -> Result<()> {
|
||||
const EXCLUSIVE_KEYS: &[(&str, &str, &str)] = &[
|
||||
("addon.pathtools.cornerSet", "items", "ids"),
|
||||
("addon.pathtools.cornerRemove", "items", "ids"),
|
||||
("addon.pathtools.bridge", "radius", "gap"),
|
||||
("links.unembed", "id", "ids"),
|
||||
("links.unembed", "path", "folder"),
|
||||
];
|
||||
|
||||
@@ -50,7 +50,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Direction Handle",
|
||||
[],
|
||||
None,
|
||||
"{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool}",
|
||||
"{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool, link?: bool} move a direction handle; independent moves only that side and makes the anchor a corner; link makes the anchor smooth with the other handle in line at its own length (a retracted one is pulled out to the moved handle's length where a segment leaves the anchor on its side); link and independent cannot both be true; both default false",
|
||||
has_doc,
|
||||
set_handle
|
||||
),
|
||||
@@ -457,6 +457,9 @@ fn set_handle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ai = index_opt(p, "anchor", "path.setHandle")?.ok_or_else(|| bad("path.setHandle", "missing anchor"))?;
|
||||
let out = str_param(p, "which") != Some("in");
|
||||
let pos = Point::new(f64_req(p, "x", "path.setHandle")?, f64_req(p, "y", "path.setHandle")?);
|
||||
if switch_or(p, "link", false, "path.setHandle")? {
|
||||
return link_handle(s, p, id, si, ai, out, pos);
|
||||
}
|
||||
let independent = switch_or(p, "independent", false, "path.setHandle")?;
|
||||
// A handle already there, on an anchor already of the kind it would get, changes nothing and
|
||||
// records no undo step. The handle is compared directly: `set_handle` would recompute the
|
||||
@@ -476,6 +479,42 @@ fn set_handle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
ok()
|
||||
}
|
||||
|
||||
/// `path.setHandle` with `link` (the Anchor Point tool's Alt-drag on a handle): the handle goes to
|
||||
/// (x, y) and the anchor becomes smooth, its other handle turned in line at its own length. A
|
||||
/// retracted other handle is pulled out to the moved handle's length when a segment leaves the
|
||||
/// anchor on its side, and stays retracted at an open end. An anchor the edit would leave as it
|
||||
/// is records no undo step.
|
||||
fn link_handle(s: &mut Session, p: &Value, id: NodeId, si: usize, ai: usize, out: bool, pos: Point) -> Result<Value> {
|
||||
const C: &str = "path.setHandle";
|
||||
if switch_or(p, "independent", false, C)? {
|
||||
return Err(bad(C, "`link` and `independent` cannot both be true"));
|
||||
}
|
||||
if !(pos.x.abs() < 1e9 && pos.y.abs() < 1e9) {
|
||||
return Err(bad(C, "x and y must be finite"));
|
||||
}
|
||||
if s.script_running() {
|
||||
return Err(EngineError::Busy);
|
||||
}
|
||||
let unchanged = s.doc()?.doc.node(id).and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.get(si)).is_some_and(|sp| {
|
||||
sp.anchors.get(ai).is_some_and(|a| {
|
||||
let mut linked = *a;
|
||||
linked.link_handle(out, pos, sp.has_segment(ai, !out));
|
||||
linked == *a
|
||||
})
|
||||
});
|
||||
if unchanged {
|
||||
return ok();
|
||||
}
|
||||
s.edit("Reshape", |d, _| {
|
||||
let sp = path_mut(d, id)?.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such anchor".into()))?;
|
||||
let pull_out = sp.has_segment(ai, !out);
|
||||
let a = sp.anchors.get_mut(ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?;
|
||||
a.link_handle(out, pos, pull_out);
|
||||
Ok(())
|
||||
})?;
|
||||
ok()
|
||||
}
|
||||
|
||||
/// `path.moveAnchor`: one anchor to (x, y), its handles keeping their offsets (the Anchor Point
|
||||
/// tool's Shift-drag).
|
||||
fn move_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -557,6 +557,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"select.update",
|
||||
"shape.arc",
|
||||
"shape.circleThroughPoints",
|
||||
"shape.editFlare",
|
||||
"shape.ellipse",
|
||||
"shape.flare",
|
||||
"shape.line",
|
||||
|
||||
@@ -157,6 +157,8 @@ pub const PREF_SPECS: &[PrefSpec] = &[
|
||||
p!("scrubNumericFields", "General", "Options", "Scrub Numeric Fields by Dragging", bool),
|
||||
p!("trackpadRotateView", "General", "Options", "Trackpad Gesture to Rotate View", bool),
|
||||
p!("holdToolKeys", "General", "Options", "Hold a Tool Shortcut to Use the Tool Temporarily", bool),
|
||||
p!("holdShortcuts", "General", "Options", "Hold Shortcuts", bool),
|
||||
p!("keyHoldDelay", "General", "Options", "Hold Shortcut Delay", num(0.2, 1.0, "s")),
|
||||
p!("boundingBoxWhileMovingAndDrawing", "General", "Options", "Show Bounding Box While Moving and Drawing", bool),
|
||||
// Selection & Anchor Display
|
||||
p!("selectionTolerance", "Selection & Anchor Display", "Selection", "Tolerance", num(1.0, 8.0, "px")),
|
||||
|
||||
@@ -29,6 +29,7 @@ use vectorcraft_tools::{PaintDefaults, Tool};
|
||||
pub use cmd::clipboard::{Clipboard, SourceLayer};
|
||||
pub use cmd::create::constrain_click;
|
||||
pub use cmd::distortcmds::{perspective_click, width_point_pair};
|
||||
pub use cmd::flare::flare_settings;
|
||||
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;
|
||||
@@ -198,7 +199,8 @@ pub struct Session {
|
||||
/// `plugin.install` takes `grant` and `allowHeavy` from any request
|
||||
/// ([`Session::allow_plugin_grants_from_requests`]).
|
||||
plugin_grants_from_requests: bool,
|
||||
/// URLs recently given in the Attributes panel (`attributes.set {url}`), newest first; not saved.
|
||||
/// URLs recently given in the Attributes panel (`attributes.set {url}`), newest first, at most
|
||||
/// [`cmd::RECENT_URLS`]; not saved.
|
||||
pub recent_urls: Vec<String>,
|
||||
/// The saved tracing presets' revision and latest changes ([`Session::trace_presets_revision`]).
|
||||
pub(crate) trace_preset_changes: cmd::TracePresetChanges,
|
||||
@@ -417,7 +419,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, PluginBudget, Prefs};
|
||||
pub use prefs::{DrawMode, KEY_HOLD_DELAY, KEY_HOLD_DELAY_RANGE, PluginBudget, Prefs};
|
||||
pub use sanity::TOO_DEEP;
|
||||
pub(crate) use sanity::{deselect_hidden, is_guide_path};
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -97,6 +97,13 @@ pub struct Prefs {
|
||||
/// A single-key tool shortcut held down chooses its tool until the key is let go, and then the
|
||||
/// tool active before comes back; a quick press chooses the tool for good.
|
||||
pub hold_tool_keys: bool,
|
||||
/// Hold shortcuts act (Edit › Keyboard Shortcuts › Hold Shortcuts, off by default): a key with a
|
||||
/// hold shortcut runs it when held for [`Self::key_hold_delay`], and its own shortcut when let go
|
||||
/// sooner. Off, every key runs on its press and the dialog shows no Hold column.
|
||||
pub hold_shortcuts: bool,
|
||||
/// Seconds a key with a hold shortcut must stay down before the hold shortcut runs (Hold
|
||||
/// Shortcut Delay, 0.2 to 1.0). VectorCraft's own default, 0.35.
|
||||
pub key_hold_delay: f64,
|
||||
/// With View › Show Bounding Box on, the bounding box stays visible while a drag moves the
|
||||
/// selection, and the shape tools that show it draw it around the shape being drawn. Off (the
|
||||
/// default), it hides during a move and while a shape is drawn, except that a Selection tool
|
||||
@@ -420,6 +427,21 @@ pub struct Prefs {
|
||||
pub import_matches: Vec<cmd::importmatches::ImportMatch>,
|
||||
}
|
||||
|
||||
/// The default Hold Shortcut Delay, in seconds (VectorCraft's own value).
|
||||
pub const KEY_HOLD_DELAY: f64 = 0.35;
|
||||
/// The range of the Hold Shortcut Delay, in seconds.
|
||||
pub const KEY_HOLD_DELAY_RANGE: (f64, f64) = (0.2, 1.0);
|
||||
|
||||
impl Prefs {
|
||||
/// The Hold Shortcut Delay in seconds, inside its range. A restored settings file is not
|
||||
/// checked against the range, so a value outside it is brought inside, and one that is not a
|
||||
/// number gives the default.
|
||||
pub fn key_hold_delay(&self) -> f64 {
|
||||
let (min, max) = KEY_HOLD_DELAY_RANGE;
|
||||
if self.key_hold_delay.is_finite() { self.key_hold_delay.clamp(min, max) } else { KEY_HOLD_DELAY }
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Prefs {
|
||||
fn default() -> Self {
|
||||
let s = |v: &str| v.to_string();
|
||||
@@ -451,6 +473,8 @@ impl Default for Prefs {
|
||||
scrub_numeric_fields: true,
|
||||
trackpad_rotate_view: true,
|
||||
hold_tool_keys: true,
|
||||
hold_shortcuts: false,
|
||||
key_hold_delay: KEY_HOLD_DELAY,
|
||||
bounding_box_while_moving_and_drawing: false,
|
||||
paste_offset: 10.0,
|
||||
selection_tolerance: 3.0,
|
||||
|
||||
@@ -3393,6 +3393,149 @@ fn flare_rotation_turns_only_the_rays() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A flare keeps its settings: `shape.editFlare` draws it again with the settings changed, in its
|
||||
/// place and transformed as it has been since, as one undo step (none when nothing changes). A
|
||||
/// flare with a changed part, a locked one and an expanded one are not edited.
|
||||
#[test]
|
||||
fn edit_flare_draws_a_transformed_flare_again_in_its_place_in_one_undo_step() {
|
||||
let mut s = session();
|
||||
let p = json!({"cx": 200, "cy": 200, "diameter": 60, "rays": 9, "rings": 4, "x2": 400, "y2": 200, "seed": 3});
|
||||
let id = NodeId(s.execute("shape.flare", &p).unwrap()["id"].as_u64().unwrap());
|
||||
// Reflected twice, sheared and back, turned a quarter and moved: it stays a flare.
|
||||
for (c, p) in [
|
||||
("object.reflect", json!({"axis": "vertical"})),
|
||||
("object.reflect", json!({"axis": "horizontal"})),
|
||||
("object.shear", json!({"angle": 30})),
|
||||
("object.shear", json!({"angle": -30})),
|
||||
("object.rotate", json!({"angle": 90})),
|
||||
("object.move", json!({"dx": 50, "dy": 10})),
|
||||
] {
|
||||
s.execute(c, &p).unwrap();
|
||||
}
|
||||
let spec = |s: &Session| flare_settings(&s.doc().unwrap().doc, id).expect("still a flare");
|
||||
let part = |s: &Session, name: &str| {
|
||||
let g = s.doc().unwrap().doc.node(id).unwrap();
|
||||
g.children().unwrap().iter().filter(|c| c.name.as_deref() == Some(name)).map(|c| c.geometric_bounds().unwrap()).collect::<Vec<_>>()
|
||||
};
|
||||
let (c, e) = (spec(&s).center().unwrap(), spec(&s).end().unwrap());
|
||||
// The quarter turn made the rings run vertically, 200 points from the center.
|
||||
assert!((c.distance(e) - 200.0).abs() < 1e-6 && (c.x - e.x).abs() < 1e-6, "{c:?} {e:?}");
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
s.execute("shape.editFlare", &json!({"diameter": 100, "rings": 6, "rays": 0})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![id]);
|
||||
let centre = part(&s, "Center")[0];
|
||||
assert!(centre.center().distance(c) < 1e-6 && (centre.width() - 100.0).abs() < 1e-6, "{centre:?}");
|
||||
assert_eq!((part(&s, "Ring").len(), part(&s, "Rays").len()), (6, 0));
|
||||
assert!(spec(&s).end().unwrap().distance(e) < 1e-6, "the end point stays");
|
||||
// Each ring lies on the line from the center to the end point.
|
||||
assert!(part(&s, "Ring").iter().all(|r| (r.center().x - c.x).abs() < 1e-6), "{:?}", part(&s, "Ring"));
|
||||
// The center handle, where it is drawn now: the end point stays where it is.
|
||||
s.execute("shape.editFlare", &json!({"ids": [id.0], "cx": c.x + 20.0, "cy": c.y})).unwrap();
|
||||
assert!(spec(&s).center().unwrap().distance(Point::new(c.x + 20.0, c.y)) < 1e-6);
|
||||
assert!(spec(&s).end().unwrap().distance(e) < 1e-6);
|
||||
assert!(part(&s, "Center")[0].center().distance(Point::new(c.x + 20.0, c.y)) < 1e-6);
|
||||
// The end handle, then the path length and direction.
|
||||
s.execute("shape.editFlare", &json!({"x2": c.x + 20.0, "y2": c.y + 80.0})).unwrap();
|
||||
assert!(spec(&s).end().unwrap().distance(Point::new(c.x + 20.0, c.y + 80.0)) < 1e-6);
|
||||
// The path length and direction are where the flare is drawn now, though it was turned.
|
||||
s.execute("shape.editFlare", &json!({"direction": 0, "pathLength": 50})).unwrap();
|
||||
assert!(spec(&s).end().unwrap().distance(Point::new(c.x + 70.0, c.y)) < 1e-6, "{:?}", spec(&s).end());
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
// Nothing changes: no undo step.
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
s.execute("shape.editFlare", &json!({"diameter": 100})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
|
||||
// Bad values are refused.
|
||||
for bad in [json!({"rings": 2.5}), json!({"diameter": "big"}), json!({"cx": 10}), json!({"diameter": 1e20})] {
|
||||
assert!(s.execute("shape.editFlare", &bad).is_err(), "{bad}");
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(spec(&s).end().unwrap().distance(e) < 1e-6, "undo puts the end point back");
|
||||
// A changed part: no longer a flare.
|
||||
s.edit("Opacity", |d, _| {
|
||||
let ring = d.node(id).unwrap().children().unwrap().iter().find(|c| c.name.as_deref() == Some("Center")).unwrap().id;
|
||||
d.node_mut(ring).unwrap().opacity = 0.25;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(s.execute("shape.editFlare", &json!({"rings": 3})).unwrap_err().to_string(), "select a flare");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
// A locked flare.
|
||||
s.execute("object.lock", &json!({})).unwrap();
|
||||
assert!(s.execute("shape.editFlare", &json!({"ids": [id.0], "rings": 3})).is_err());
|
||||
s.execute("object.unlockAll", &json!({})).unwrap();
|
||||
// Object › Expand: a plain group that is no longer a flare.
|
||||
s.execute("object.expand", &json!({"object": true, "fill": false, "stroke": false})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.node(id).unwrap().extras().flare.is_none());
|
||||
assert!(s.execute("shape.editFlare", &json!({"rings": 3})).is_err());
|
||||
}
|
||||
|
||||
/// `shape.flare` reads whole-number counts written as floats, and refuses fractions.
|
||||
#[test]
|
||||
fn flare_counts_are_whole_numbers() {
|
||||
let mut s = session();
|
||||
let id = NodeId(s.execute("shape.flare", &json!({"cx": 100, "cy": 100, "rays": 4.0, "rings": 2})).unwrap()["id"].as_u64().unwrap());
|
||||
let g = s.doc().unwrap().doc.node(id).unwrap();
|
||||
let rays = g.children().unwrap().iter().find(|c| c.name.as_deref() == Some("Rays")).unwrap();
|
||||
assert_eq!(rays.path_data().unwrap().subpaths.len(), 4);
|
||||
assert!(s.execute("shape.flare", &json!({"cx": 100, "cy": 100, "rays": 2.5})).is_err());
|
||||
}
|
||||
|
||||
/// `shape.editFlare` on a flare scaled far down: a `pathLength`, an end point or a center that,
|
||||
/// taken back to where the flare was drawn, is not a finite number is an error, and the flare keeps
|
||||
/// its settings.
|
||||
#[test]
|
||||
fn edit_flare_end_points_that_are_not_finite_are_errors() {
|
||||
let mut s = session();
|
||||
let id = NodeId(s.execute("shape.flare", &json!({"cx": 100, "cy": 100, "rings": 2})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("object.scale", &json!({"sx": 1e-4, "sy": 1e-4})).unwrap();
|
||||
let before = flare_settings(&s.doc().unwrap().doc, id).expect("a flare");
|
||||
for (p, key) in [
|
||||
(json!({"pathLength": 1e305}), "x2"),
|
||||
(json!({"x2": 1e305, "y2": 0}), "x2"),
|
||||
(json!({"x2": 0, "y2": -1e305}), "y2"),
|
||||
(json!({"cx": 1e305, "cy": 0}), "cx"),
|
||||
] {
|
||||
let err = s.execute("shape.editFlare", &p).unwrap_err().to_string();
|
||||
assert!(err.ends_with(&format!("{key} must be a finite coordinate")), "{p}: {err}");
|
||||
assert_eq!(flare_settings(&s.doc().unwrap().doc, id).expect("still a flare"), before, "{p}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A flare drawn again keeps its parts' pixel-aligned property, whatever the document's Align New
|
||||
/// Objects to Pixel Grid is now, and a pixel-aligned flare that was moved is still a flare.
|
||||
#[test]
|
||||
fn edit_flare_keeps_its_parts_pixel_alignment() {
|
||||
let mut s = session();
|
||||
let aligned = |s: &Session, id: NodeId| -> Vec<bool> {
|
||||
s.doc().unwrap().doc.node(id).unwrap().children().unwrap().iter().map(|c| c.extras().pixel_aligned).collect()
|
||||
};
|
||||
s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": true})).unwrap();
|
||||
let on = NodeId(s.execute("shape.flare", &json!({"cx": 100.3, "cy": 200.6, "rings": 2})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("object.move", &json!({"dx": 10.25, "dy": 3.5})).unwrap();
|
||||
s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": false})).unwrap();
|
||||
let part = |s: &Session, id: NodeId, name: &str| -> NodeId {
|
||||
s.doc().unwrap().doc.node(id).unwrap().children().unwrap().iter().find(|c| c.name.as_deref() == Some(name)).unwrap().id
|
||||
};
|
||||
let centre = part(&s, on, "Center");
|
||||
s.execute("shape.editFlare", &json!({"rings": 4})).unwrap();
|
||||
assert!(aligned(&s, on).len() > 4 && aligned(&s, on).iter().all(|a| *a));
|
||||
// Each part drawn again keeps its id and its own property: without the rays, the center does
|
||||
// not take theirs.
|
||||
assert_eq!(part(&s, on, "Center"), centre);
|
||||
s.execute("object.setPixelAligned", &json!({"ids": [centre.0], "on": false})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [on.0]})).unwrap();
|
||||
s.execute("shape.editFlare", &json!({"rays": 0})).unwrap();
|
||||
let node = |s: &Session, id: NodeId| s.doc().unwrap().doc.node(id).unwrap().extras().pixel_aligned;
|
||||
assert!(!node(&s, centre) && node(&s, part(&s, on, "Halo")));
|
||||
let off = NodeId(s.execute("shape.flare", &json!({"cx": 300.3, "cy": 200.6, "rings": 2})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": true})).unwrap();
|
||||
s.execute("shape.editFlare", &json!({"rings": 4})).unwrap();
|
||||
assert!(aligned(&s, off).iter().all(|a| !*a));
|
||||
}
|
||||
|
||||
/// `shape.flare`'s `ringSeed` places the rings along the path anew and keeps their count and
|
||||
/// sizes and the other parts; the same `ringSeed` draws the same flare, neighboring ones differ,
|
||||
/// and a seed that is not a whole number of at least 0 (for `ringSeed`, below 2^53) is refused.
|
||||
@@ -3453,6 +3596,38 @@ fn flare_small_ring_seeds_spread_the_first_ring_along_the_path() {
|
||||
assert!(hi - lo > 250.0, "small seeds spread the first ring along the path: {positions:?}");
|
||||
}
|
||||
|
||||
/// A flare drawn with a small `ringSeed` and then drawn again by `shape.editFlare` keeps its first
|
||||
/// ring where `shape.flare` put it: the SplitMix64-initialized Xorshift64 stream's first value
|
||||
/// along the path, for each seed.
|
||||
#[test]
|
||||
fn edit_flare_draws_the_first_ring_of_a_small_ring_seed_where_it_was() {
|
||||
let first_t = |seed: u64| {
|
||||
let mut z = seed.wrapping_add(0x9e37_79b9_7f4a_7c15);
|
||||
z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
|
||||
z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
|
||||
let mut state = z ^ (z >> 31);
|
||||
state ^= state << 13;
|
||||
state ^= state >> 7;
|
||||
state ^= state << 17;
|
||||
(state >> 11) as f64 / (1u64 << 53) as f64
|
||||
};
|
||||
let ring_x = |s: &Session, id: NodeId| {
|
||||
let NodeKind::Group { children, .. } = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("flare is a group") };
|
||||
children.iter().find(|n| n.name.as_deref() == Some("Ring")).unwrap().geometric_bounds().unwrap().center().x
|
||||
};
|
||||
let mut s = session();
|
||||
for seed in [0, 1, 2, 5, 11] {
|
||||
let p = json!({"cx": 20, "cy": 30, "x2": 1020, "y2": 30, "rays": 0, "rings": 1, "ringSeed": seed});
|
||||
let id = NodeId(s.execute("shape.flare", &p).unwrap()["id"].as_u64().unwrap());
|
||||
let expected = 20.0 + 1000.0 * first_t(seed);
|
||||
assert!((ring_x(&s, id) - expected).abs() < 1e-6, "seed {seed}: drawn at {}, expected {expected}", ring_x(&s, id));
|
||||
s.execute("shape.editFlare", &json!({"ids": [id.0], "opacity": 80})).unwrap();
|
||||
assert!((ring_x(&s, id) - expected).abs() < 1e-6, "seed {seed}: drawn again at {}, expected {expected}", ring_x(&s, id));
|
||||
s.execute("shape.editFlare", &json!({"ids": [id.0], "opacity": 40})).unwrap();
|
||||
assert!((ring_x(&s, id) - expected).abs() < 1e-6, "seed {seed}: a second edit keeps the ring");
|
||||
}
|
||||
}
|
||||
|
||||
/// `shape.ellipse` without `anchors`, or with 4, draws the live ellipse it always drew.
|
||||
#[test]
|
||||
fn ellipse_with_four_anchors_is_the_live_ellipse() {
|
||||
|
||||
@@ -176,3 +176,61 @@ fn a_handle_already_in_place_on_a_smooth_anchor_records_no_undo_step() {
|
||||
.unwrap();
|
||||
assert_eq!(undo_steps(&s), 1);
|
||||
}
|
||||
|
||||
/// `path.setHandle` with `link` makes a corner smooth: the other handle turns in line at its own
|
||||
/// length, a retracted one is pulled out to the moved handle's length where a segment leaves the
|
||||
/// anchor on its side and stays retracted at an open end. A handle already in place on a corner
|
||||
/// still links; a request that changes nothing records no undo step; `link` that is not a boolean
|
||||
/// or goes with `independent` is refused.
|
||||
#[test]
|
||||
fn a_linked_handle_makes_the_anchor_smooth() {
|
||||
let (mut s, id) = long_path(100);
|
||||
let p = anchor(&s, id, 5).p;
|
||||
let corner = Anchor { p, h_in: p + Vec2::new(-6.0, 8.0), h_out: p + Vec2::new(3.0, 0.0), kind: AnchorKind::Corner };
|
||||
let path = Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().path_data_mut().unwrap();
|
||||
path.subpaths[0].anchors[5] = corner;
|
||||
let link = |x: f64, y: f64, ai: usize| json!({"id": id.0, "anchor": ai, "which": "out", "x": x, "y": y, "link": true});
|
||||
let near = |a: Point, b: Point| a.distance(b) < 1e-9;
|
||||
|
||||
// The out handle stays where it is; the corner becomes smooth, the in handle turned opposite it.
|
||||
s.execute("path.setHandle", &link(corner.h_out.x, corner.h_out.y, 5)).unwrap();
|
||||
assert_eq!(undo_steps(&s), 1);
|
||||
let a = anchor(&s, id, 5);
|
||||
assert_eq!((a.kind, a.h_out), (AnchorKind::Smooth, corner.h_out));
|
||||
assert!(near(a.h_in, p + Vec2::new(-10.0, 0.0)), "{a:?}");
|
||||
// Moved: the in handle keeps its length of 10.
|
||||
let to = p + Vec2::new(4.0, 3.0);
|
||||
s.execute("path.setHandle", &link(to.x, to.y, 5)).unwrap();
|
||||
assert_eq!(undo_steps(&s), 2);
|
||||
let a = anchor(&s, id, 5);
|
||||
assert!(a.kind == AnchorKind::Smooth && a.h_out == to && near(a.h_in, p + Vec2::new(-8.0, -6.0)), "{a:?}");
|
||||
// The same request again changes nothing.
|
||||
s.execute("path.setHandle", &link(to.x, to.y, 5)).unwrap();
|
||||
assert_eq!(undo_steps(&s), 2);
|
||||
|
||||
// A retracted in handle on an inner anchor is pulled out; at the open start it stays retracted.
|
||||
let q = anchor(&s, id, 7).p;
|
||||
s.execute("path.setHandle", &link(q.x, q.y + 5.0, 7)).unwrap();
|
||||
let a = anchor(&s, id, 7);
|
||||
assert!(a.kind == AnchorKind::Smooth && near(a.h_in, q + Vec2::new(0.0, -5.0)), "{a:?}");
|
||||
let q = anchor(&s, id, 0).p;
|
||||
s.execute("path.setHandle", &link(q.x, q.y + 5.0, 0)).unwrap();
|
||||
let a = anchor(&s, id, 0);
|
||||
assert!(a.kind == AnchorKind::Smooth && a.h_in == q && a.h_out == q + Vec2::new(0.0, 5.0), "{a:?}");
|
||||
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let undo = undo_steps(&s);
|
||||
for bad in [
|
||||
json!({"id": id.0, "anchor": 5, "which": "out", "x": 0, "y": 0, "link": "yes"}),
|
||||
json!({"id": id.0, "anchor": 5, "which": "out", "x": 0, "y": 0, "link": 1}),
|
||||
json!({"id": id.0, "anchor": 5, "which": "out", "x": 0, "y": 0, "link": true, "independent": true}),
|
||||
json!({"id": id.0, "anchor": 5, "which": "out", "x": 0, "y": 0, "link": true, "independent": "no"}),
|
||||
json!({"id": id.0, "anchor": 100, "which": "out", "x": 0, "y": 0, "link": true}),
|
||||
json!({"id": id.0, "anchor": 7, "which": "out", "x": 1.7e308, "y": 1.7e308, "link": true}),
|
||||
json!({"id": id.0, "anchor": 7, "which": "out", "x": 0, "y": -1e9, "link": true}),
|
||||
] {
|
||||
assert!(s.execute("path.setHandle", &bad).is_err(), "{bad}");
|
||||
}
|
||||
assert!(s.doc().unwrap().doc == before, "a refused request changed the document");
|
||||
assert_eq!(undo_steps(&s), undo);
|
||||
}
|
||||
@@ -90,6 +90,23 @@ fn values_that_differ_read_null_and_recent_urls_keep_the_newest_first() {
|
||||
assert_eq!(info(&mut s, json!({"ids": [p.0, a.0]}))["showCenter"], Value::Null);
|
||||
}
|
||||
|
||||
/// The recent URLs keep the 30 newest distinct URLs, the most the panel's URL menu can list, and
|
||||
/// a URL given again moves to the front without taking a second place.
|
||||
#[test]
|
||||
fn recent_urls_keep_the_thirty_newest() {
|
||||
let mut s = session();
|
||||
rect(&mut s, 0.0);
|
||||
for i in 0..35 {
|
||||
run(&mut s, "attributes.set", json!({"url": format!("https://example.com/{i}")}));
|
||||
}
|
||||
let want: Vec<String> = (5..35).rev().map(|i| format!("https://example.com/{i}")).collect();
|
||||
assert_eq!(info(&mut s, json!({}))["recentUrls"], json!(want));
|
||||
run(&mut s, "attributes.set", json!({"url": "https://example.com/20"}));
|
||||
let urls = info(&mut s, json!({}))["recentUrls"].as_array().unwrap().clone();
|
||||
assert_eq!((urls.len(), urls[0].as_str(), urls[1].as_str()), (30, Some("https://example.com/20"), Some("https://example.com/34")));
|
||||
assert_eq!(urls.iter().filter(|u| *u == "https://example.com/20").count(), 1);
|
||||
}
|
||||
|
||||
/// A five-pointed star drawn as one self-intersecting path (its centre is wound twice).
|
||||
fn star(s: &mut Session) -> NodeId {
|
||||
let (c, r) = (50.0f64, 45.0f64);
|
||||
|
||||
@@ -431,3 +431,35 @@ fn a_spine_segment_bends_with_perpendicular_handles() {
|
||||
use vectorcraft_geom::kurbo::ParamCurve;
|
||||
assert!(sp.segment(0).eval(0.5).distance(Point::new(55.0, 45.0)) < 1e-9, "{sp:?}");
|
||||
}
|
||||
|
||||
/// `link` with `handle` makes a spine point smooth, the other handle in line opposite the moved
|
||||
/// one, without moving the keys; the same request again records no undo step, and `link` that is
|
||||
/// not a boolean, goes with `independent` or comes without `handle` is refused.
|
||||
#[test]
|
||||
fn a_linked_spine_handle_makes_the_point_smooth() {
|
||||
let mut s = session();
|
||||
let (_, _, g) = blend(&mut s);
|
||||
s.execute("object.blend.spine.addAnchor", &json!({"x": 55, "y": 5})).unwrap();
|
||||
let undo = |s: &Session| s.doc().unwrap().history.undo.len();
|
||||
let link = json!({"anchor": 1, "handle": "out", "x": 75, "y": 25, "link": true});
|
||||
s.execute("object.blend.spine.moveAnchor", &link).unwrap();
|
||||
let a = spec(&s, g).spine.unwrap().subpaths[0].anchors[1];
|
||||
assert_eq!((a.kind, a.h_out), (vectorcraft_geom::AnchorKind::Smooth, Point::new(75.0, 25.0)));
|
||||
let (din, dout) = (a.h_in - a.p, a.h_out - a.p);
|
||||
assert!(din.hypot() > 1e-6 && (din.normalize() + dout.normalize()).hypot() < 1e-9, "{a:?}");
|
||||
let st = steps(&s, g);
|
||||
assert_eq!((center(&st[0]), center(&st[2])), (Point::new(5.0, 5.0), Point::new(105.0, 5.0)), "the keys stay put");
|
||||
let done = undo(&s);
|
||||
s.execute("object.blend.spine.moveAnchor", &link).unwrap();
|
||||
assert_eq!(undo(&s), done, "an unchanged spine recorded an undo step");
|
||||
let before = spec(&s, g);
|
||||
for bad in [
|
||||
json!({"anchor": 1, "handle": "out", "x": 75, "y": 25, "link": "yes"}),
|
||||
json!({"anchor": 1, "handle": "out", "x": 75, "y": 25, "link": true, "independent": true}),
|
||||
json!({"anchor": 1, "x": 75, "y": 25, "link": true}),
|
||||
] {
|
||||
assert!(s.execute("object.blend.spine.moveAnchor", &bad).is_err(), "{bad}");
|
||||
}
|
||||
assert_eq!(spec(&s, g), before);
|
||||
assert_eq!(undo(&s), done);
|
||||
}
|
||||
@@ -117,7 +117,8 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
|
||||
"game-trails",
|
||||
"energy-beams",
|
||||
"dry-media",
|
||||
"tech-circuit"
|
||||
"tech-circuit",
|
||||
"arrows"
|
||||
]
|
||||
);
|
||||
assert!(libs.iter().all(|l| l["category"] == "builtIn"));
|
||||
@@ -145,6 +146,12 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
|
||||
[("Chalk Grain", "art"), ("Graphite Pencil", "art"), ("Wax Crayon", "art"), ("Charcoal Dust", "art")]
|
||||
);
|
||||
assert_eq!((libs[9]["name"].as_str(), libs[9]["count"].as_u64()), (Some("Dry Media"), Some(4)));
|
||||
let arrows = run(&mut s, "brush.library", json!({"library": "Arrows"}));
|
||||
assert_eq!(
|
||||
arrows["brushes"].as_array().unwrap().iter().map(|b| (b["name"].as_str().unwrap(), b["type"].as_str().unwrap())).collect::<Vec<_>>(),
|
||||
[("Solid Arrow", "art"), ("Open Arrow", "art"), ("Double Arrow", "art"), ("Chevron Arrow", "art"), ("Dashed Arrow", "art")]
|
||||
);
|
||||
assert_eq!((libs[11]["name"].as_str(), libs[11]["count"].as_u64()), (Some("Arrows"), Some(5)));
|
||||
run(&mut s, "file.new", json!({"width": 200, "height": 200}));
|
||||
let id = run(&mut s, "shape.rectangle", json!({"x": 10, "y": 20, "width": 40, "height": 8}))["id"].as_u64().unwrap();
|
||||
let added = run(&mut s, "brush.addFromLibrary", json!({"library": "energy-beams", "name": "Laser Bolt", "apply": true, "ids": [id]}));
|
||||
@@ -162,6 +169,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
|
||||
("game-trails", "art"),
|
||||
("energy-beams", "art"),
|
||||
("dry-media", "art"),
|
||||
("arrows", "art"),
|
||||
] {
|
||||
let (_, lib) = cmd::brushlib::library(&s, id).unwrap();
|
||||
assert!(lib.len() >= 4, "{id}");
|
||||
@@ -220,6 +228,78 @@ fn black_stroke() -> vectorcraft_doc::StrokeLayer {
|
||||
vectorcraft_doc::StrokeLayer::new(vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), 1.0)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arrows_library_lists_renders_and_applies_original_brushes() {
|
||||
let mut s = session();
|
||||
let listed = run(&mut s, "brush.libraries", json!({}));
|
||||
let entry = listed["libraries"].as_array().unwrap().iter().find(|l| l["id"] == "arrows").unwrap();
|
||||
assert_eq!((entry["name"].as_str(), entry["category"].as_str(), entry["count"].as_u64()), (Some("Arrows"), Some("builtIn"), Some(5)));
|
||||
let (_, lib) = cmd::brushlib::library(&s, "Arrows").unwrap();
|
||||
assert_eq!(
|
||||
lib.brushes.iter().map(|b| (b.name.as_str(), b.kind.type_id())).collect::<Vec<_>>(),
|
||||
[("Solid Arrow", "art"), ("Open Arrow", "art"), ("Double Arrow", "art"), ("Chevron Arrow", "art"), ("Dashed Arrow", "art")]
|
||||
);
|
||||
for b in &lib.brushes {
|
||||
for length in [2.0, 200.0] {
|
||||
let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &line_to(length), &black_stroke());
|
||||
let pts = anchors(&pieces.iter().collect::<Vec<_>>());
|
||||
assert!(!pts.is_empty() && pts.iter().all(|p| p.x.is_finite() && p.y.is_finite()), "{} at {length} pt", b.name);
|
||||
}
|
||||
}
|
||||
let path = run(&mut s, "shape.line", json!({"x1": 10, "y1": 20, "x2": 210, "y2": 20}))["id"].as_u64().unwrap();
|
||||
let before = undo_len(&s);
|
||||
let added = run(&mut s, "brush.addFromLibrary", json!({"library": "arrows", "name": "Double Arrow", "apply": true, "ids": [path]}));
|
||||
assert_eq!(strs(&added["added"]), ["Double Arrow"]);
|
||||
assert_eq!(added["applied"], json!([path]));
|
||||
assert_eq!(undo_len(&s), before + 1);
|
||||
assert_eq!(doc(&s).node(NodeId(path)).unwrap().appearance.stroke().unwrap().brush.as_deref(), Some("Double Arrow"));
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert!(vectorcraft_brush::find(doc(&s), "Double Arrow").is_none());
|
||||
run(&mut s, "edit.redo", json!({}));
|
||||
assert_eq!(brush(&s, "Double Arrow"), lib.brushes[2]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_chevron_arrows_second_chevron_keeps_its_length_on_a_long_path() {
|
||||
let s = session();
|
||||
let (_, lib) = cmd::brushlib::library(&s, "Arrows").unwrap();
|
||||
let b = lib.brush("Chevron Arrow").unwrap();
|
||||
let widths = |length: f64| {
|
||||
let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &line_to(length), &black_stroke());
|
||||
let children = pieces[0].children().unwrap();
|
||||
assert_eq!(children.len(), 3, "shaft, head and second chevron");
|
||||
children[1..].iter().map(|n| n.geometric_bounds().unwrap().width()).collect::<Vec<_>>()
|
||||
};
|
||||
let short = widths(100.0);
|
||||
for (long, short) in widths(400.0).into_iter().zip(short) {
|
||||
assert!((long - short).abs() < 1e-6, "the heads keep their length: {long} on 400 pt, {short} on 100 pt");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dashed_arrow_keeps_separate_dashes_and_survives_library_save() {
|
||||
let mut s = session();
|
||||
let (_, lib) = cmd::brushlib::library(&s, "Arrows").unwrap();
|
||||
let b = lib.brush("Dashed Arrow").unwrap();
|
||||
let mut curve = line_to(40.0);
|
||||
curve.curve_to((60.0, -40.0), (140.0, 40.0), (200.0, 0.0));
|
||||
for path in [line_to(2.0), line_to(200.0), curve] {
|
||||
let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &path, &black_stroke());
|
||||
let pts = anchors(&pieces.iter().collect::<Vec<_>>());
|
||||
assert!(!pts.is_empty() && pts.iter().all(|p| p.x.is_finite() && p.y.is_finite()));
|
||||
}
|
||||
let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &line_to(200.0), &black_stroke());
|
||||
let children = pieces[0].children().unwrap();
|
||||
assert_eq!(children.len(), 6, "five separate dashes and one head");
|
||||
let bounds: Vec<_> = children.iter().map(|n| n.geometric_bounds().unwrap()).collect();
|
||||
assert!(bounds.windows(2).all(|p| p[0].x1 < p[1].x0), "the dashes and head remain separated");
|
||||
run(&mut s, "brush.addFromLibrary", json!({"library": "arrows", "name": "Dashed Arrow"}));
|
||||
let saved = run(&mut s, "brush.saveLibrary", json!({"names": ["Dashed Arrow"]}));
|
||||
let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap();
|
||||
let reopened = vectorcraft_format::load(&bytes).unwrap();
|
||||
assert_eq!(vectorcraft_brush::find(&reopened, "Dashed Arrow").unwrap(), *b);
|
||||
}
|
||||
|
||||
/// Original circuit art and repeat tiles survive adding, applying and saving a library.
|
||||
#[test]
|
||||
fn the_tech_circuit_library_constructs_adds_and_applies_each_brush() {
|
||||
|
||||
@@ -1121,6 +1121,10 @@ fn path_commands_refuse_a_param_of_the_wrong_type() {
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
let r = ids(&s.execute("object.path.offsetPath", &json!({"offset": "0.1 in", "joins": "Bevel"})).unwrap());
|
||||
assert!(close(bounds(&s, r[0]), Rect::new(92.8, 92.8, 157.2, 147.2), 1e-2), "{:?}", bounds(&s, r[0]));
|
||||
// A product with a unit, which the offset used to refuse: 0.05x2 in is 0.1 in.
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
let r = ids(&s.execute("object.path.offsetPath", &json!({"offset": "0.05x2 in", "joins": "Bevel"})).unwrap());
|
||||
assert!(close(bounds(&s, r[0]), Rect::new(92.8, 92.8, 157.2, 147.2), 1e-2), "{:?}", bounds(&s, r[0]));
|
||||
// Null switches keep Clean Up's defaults, which remove the stray point.
|
||||
let r = s.execute("object.path.cleanUp", &json!({"strayPoints": null, "unpaintedObjects": null, "emptyTextPaths": null})).unwrap();
|
||||
assert_eq!(r["removed"], 1);
|
||||
|
||||
@@ -176,3 +176,24 @@ fn a_file_over_the_limit_is_refused_before_it_is_parsed() {
|
||||
assert!(s.execute("prefs.import", &json!({"path": missing.to_string_lossy()})).is_err());
|
||||
assert_eq!(s.prefs.to_json().to_string(), before);
|
||||
}
|
||||
|
||||
/// Hold Shortcuts is off by default. The Hold Shortcut Delay takes 0.2 to 1.0 s and refuses other
|
||||
/// values; a value from a settings file outside the range is brought inside it.
|
||||
#[test]
|
||||
fn hold_shortcut_preferences() {
|
||||
let mut s = Session::new();
|
||||
assert!(!s.prefs.hold_shortcuts);
|
||||
assert_eq!(s.prefs.key_hold_delay(), 0.35);
|
||||
for ok in [0.2, 1.0] {
|
||||
s.execute("prefs.set", &json!({"key": "keyHoldDelay", "value": ok})).unwrap();
|
||||
assert_eq!(s.prefs.key_hold_delay(), ok);
|
||||
}
|
||||
for bad in [0.1, 1.5] {
|
||||
assert!(is_bad_params(s.execute("prefs.set", &json!({"key": "keyHoldDelay", "value": bad}))), "{bad}");
|
||||
}
|
||||
s.execute("prefs.set", &json!({"key": "holdShortcuts", "value": true})).unwrap();
|
||||
assert!(s.prefs.hold_shortcuts);
|
||||
let restored: Prefs = serde_json::from_value(json!({"keyHoldDelay": 5.0})).unwrap();
|
||||
assert_eq!(restored.key_hold_delay(), 1.0);
|
||||
assert!(!restored.hold_shortcuts);
|
||||
}
|
||||
@@ -1012,6 +1012,8 @@ fn structured_junk() {
|
||||
("addon.pathtools.bridge", json!({"radius": 1e-308, "keepOriginals": "x"})),
|
||||
("addon.pathtools.bridge", json!({"radius": 1000, "keepOriginals": true, "ids": [0, 1, 2, 3, u64::MAX]})),
|
||||
("addon.pathtools.bridge", json!({"radius": f64::MAX, "ids": [1, 1], "junk": [0]})),
|
||||
("addon.pathtools.bridge", json!({"gap": -1e308, "reach": f64::MAX, "ids": [0, 1, 2]})),
|
||||
("addon.pathtools.bridge", json!({"gap": 1000, "reach": 10000, "radius": null, "keepOriginals": true})),
|
||||
// Refused before anything is written: no format of that name, a time that is no time.
|
||||
("addon.document.saveTimestampedCopy", json!({"format": "png", "folder": 7})),
|
||||
("addon.document.saveTimestampedCopy", json!({"format": "svg", "time": [1e308], "folder": null})),
|
||||
|
||||
Reference in new issue
Block a user