mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-19 19:11:26 +00:00
Merge main into feat/stylus-wheel
This commit is contained in:
@@ -1365,17 +1365,19 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (fill, stroke) = (attrs.appearance.fill, attrs.appearance.stroke);
|
||||
let source_has = |kind: bool| picked.appearance.items.iter().any(|it| it.is_fill() == kind);
|
||||
let source_shows = |kind: bool| picked.appearance.items.iter().any(|it| it.is_fill() == kind && it.visible());
|
||||
// A whole pick replaces the stack: it removes the rows of a kind the source has no row of.
|
||||
let whole = fill == FillAttrs::ALL && stroke == StrokeAttrs::ALL;
|
||||
let (paints, opacities) = if append {
|
||||
let rows = (fill.color && source_shows(true), stroke.color && source_shows(false));
|
||||
(rows, rows)
|
||||
} else {
|
||||
(
|
||||
(fill.color, stroke.color || (stroke.weight && source_has(false))),
|
||||
(fill.transparency && source_has(true), stroke.transparency && source_has(false)),
|
||||
(fill.transparency && (whole || source_has(true)), stroke.transparency && (whole || source_has(false))),
|
||||
)
|
||||
};
|
||||
// A pick of some attributes edits the topmost row of its kind, which may be hidden; `append` and a whole pick write rows.
|
||||
let rows_written = append || (fill == FillAttrs::ALL && stroke == StrokeAttrs::ALL);
|
||||
let rows_written = append || whole;
|
||||
let top_shows = |id: NodeId, kind: bool| {
|
||||
let items = d.node(id).map_or(&[][..], |n| &n.appearance.items[..]);
|
||||
items.iter().rev().find(|it| it.is_fill() == kind).is_some_and(|it| it.visible())
|
||||
@@ -1389,6 +1391,9 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.collect()
|
||||
};
|
||||
let mut opacity_rows = top_opacity_changed(&before, d, &targets);
|
||||
// A written row that had paint before the pick counts too when the pick left it without paint, as in
|
||||
// `capture_series_writes`.
|
||||
opacity_rows.extend(painted_rows(&before, written(opacities)));
|
||||
opacity_rows.extend(painted_rows(d, written(opacities)));
|
||||
let mut rows = top_paint_changed(&before, d, &targets);
|
||||
rows.extend(painted_rows(d, written(paints)));
|
||||
|
||||
@@ -8,10 +8,22 @@ use super::{
|
||||
|
||||
// ---------- Smooth ----------
|
||||
|
||||
/// Refit the anchors of an open run `a[lo..=hi]` keeping its end points and outer handles.
|
||||
fn refit_run(anchors: &[Anchor], tol: f64) -> Vec<Anchor> {
|
||||
/// The spread (points) of the Gaussian the Smooth tool smooths a path along its length with before
|
||||
/// refitting it, as a share of the tool's reach: a third, so each point is averaged with the stretch
|
||||
/// of path within the reach on either side of it. VectorCraft's own value.
|
||||
const SMOOTH_SPREAD: f64 = 1.0 / 3.0;
|
||||
|
||||
/// The options the Smooth tool refits with: the path smoothed along its length by a Gaussian of
|
||||
/// spread `sigma` (none at 0), then refitted within `tol` of that and within twice the distance the
|
||||
/// smoothing moved it, keeping a corner only where the path turns back on itself.
|
||||
fn refit_options(tol: f64, sigma: f64) -> SimplifyOptions {
|
||||
SimplifyOptions { tolerance: tol, corner_angle_deg: 179.0, straight_lines: false, smooth: sigma, smooth_moved_only: true }
|
||||
}
|
||||
|
||||
/// Smooth and refit the anchors of an open run `a[lo..=hi]` keeping its end points and outer handles.
|
||||
fn refit_run(anchors: &[Anchor], tol: f64, sigma: f64) -> Vec<Anchor> {
|
||||
let piece = PathData::single(SubPath::new(anchors.to_vec(), false));
|
||||
let fitted = po::simplify_with(&piece, &SimplifyOptions { tolerance: tol, corner_angle_deg: 179.0, straight_lines: false, ..Default::default() });
|
||||
let fitted = po::simplify_with(&piece, &refit_options(tol, sigma));
|
||||
let Some(mut out) = fitted.subpaths.into_iter().next().map(|s| s.anchors).filter(|a| a.len() >= 2) else { return anchors.to_vec() };
|
||||
let (f, l) = (anchors[0], anchors[anchors.len() - 1]);
|
||||
let last = out.len() - 1;
|
||||
@@ -25,7 +37,7 @@ fn refit_run(anchors: &[Anchor], tol: f64) -> Vec<Anchor> {
|
||||
out
|
||||
}
|
||||
|
||||
fn smooth_subpath(sp: &SubPath, near: &dyn Fn(Point) -> bool, tol: f64) -> Option<SubPath> {
|
||||
fn smooth_subpath(sp: &SubPath, near: &dyn Fn(Point) -> bool, tol: f64, sigma: f64) -> Option<SubPath> {
|
||||
let n = sp.anchors.len();
|
||||
let marked: Vec<bool> = sp.anchors.iter().map(|a| near(a.p)).collect();
|
||||
if n < 3 || !marked.iter().any(|m| *m) {
|
||||
@@ -33,11 +45,8 @@ fn smooth_subpath(sp: &SubPath, near: &dyn Fn(Point) -> bool, tol: f64) -> Optio
|
||||
}
|
||||
if sp.closed {
|
||||
let Some(k) = marked.iter().position(|m| !m) else {
|
||||
// Everything is in range: smooth the whole closed path.
|
||||
let f = po::simplify_with(
|
||||
&PathData::single(sp.clone()),
|
||||
&SimplifyOptions { tolerance: tol, corner_angle_deg: 179.0, straight_lines: false, ..Default::default() },
|
||||
);
|
||||
// Everything is in range: smooth the whole closed path, across its start too.
|
||||
let f = po::simplify_with(&PathData::single(sp.clone()), &refit_options(tol, sigma));
|
||||
return f.subpaths.into_iter().next();
|
||||
};
|
||||
// Rotate so an untouched anchor comes first, duplicate it at the end and treat as open.
|
||||
@@ -48,14 +57,14 @@ fn smooth_subpath(sp: &SubPath, near: &dyn Fn(Point) -> bool, tol: f64) -> Optio
|
||||
open.anchors.push(open.anchors[0]);
|
||||
m.push(false);
|
||||
open.closed = false;
|
||||
let mut res = smooth_open(&open.anchors, &m, near, tol);
|
||||
let mut res = smooth_open(&open.anchors, &m, near, tol, sigma);
|
||||
let l = res.pop()?;
|
||||
if let Some(r0) = res.first_mut() {
|
||||
r0.h_in = l.h_in;
|
||||
}
|
||||
return Some(SubPath::new(res, true));
|
||||
}
|
||||
Some(SubPath::new(smooth_open(&sp.anchors, &marked, near, tol), false))
|
||||
Some(SubPath::new(smooth_open(&sp.anchors, &marked, near, tol, sigma), false))
|
||||
}
|
||||
|
||||
/// The segment `c`, which ends in the drag's reach (`near`) and starts outside it, split where it
|
||||
@@ -84,10 +93,11 @@ fn split_at_reach(c: CubicBez, near: &dyn Fn(Point) -> bool) -> Option<(CubicBez
|
||||
(hi > 0.02).then(|| (part(0.0..hi), part(hi..1.0)))
|
||||
}
|
||||
|
||||
/// `anchors` with each run of `marked` ones refitted, together with the stretch of the segments
|
||||
/// leading into the run that is in the drag's reach (`near`): a short drag smooths what is under
|
||||
/// it, and the rest of a long segment next to it stays as it was (#1512).
|
||||
fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool, tol: f64) -> Vec<Anchor> {
|
||||
/// `anchors` with each run of `marked` ones smoothed by a Gaussian of spread `sigma` and refitted
|
||||
/// within `tol`, together with the stretch of the segments leading into the run that is in the
|
||||
/// drag's reach (`near`): a short drag smooths what is under it, and the rest of a long segment next
|
||||
/// to it stays as it was (#1512).
|
||||
fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool, tol: f64, sigma: f64) -> Vec<Anchor> {
|
||||
let n = anchors.len();
|
||||
let mut runs = vec![];
|
||||
let mut i = 0;
|
||||
@@ -127,7 +137,7 @@ fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool
|
||||
head = Some(Anchor { h_out: far.p1, ..*outer });
|
||||
*outer = Anchor::with_handles(far.p3, far.p2, reach.p1);
|
||||
}
|
||||
let new = refit_run(&piece, tol);
|
||||
let new = refit_run(&piece, tol, sigma);
|
||||
out.splice(lo..=hi, head.into_iter().chain(new).chain(tail));
|
||||
}
|
||||
out
|
||||
@@ -138,6 +148,7 @@ pub(super) fn smooth_region(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let pts = points_param(p, "points", C)?;
|
||||
let radius = number_or(p, "radius", 12.0, C)?.max(0.0);
|
||||
let tol = number_or(p, "fidelity", 2.5, C)?.clamp(vectorcraft_tools::draw2::SMOOTH_MIN_FIDELITY, 100.0);
|
||||
let sigma = radius * SMOOTH_SPREAD;
|
||||
let st = s.doc()?;
|
||||
let near = |q: Point| dist_to_polyline(&pts, q) <= radius;
|
||||
let mut plan = vec![];
|
||||
@@ -148,7 +159,7 @@ pub(super) fn smooth_region(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let subs: Vec<SubPath> = pd
|
||||
.subpaths
|
||||
.iter()
|
||||
.map(|sp| match smooth_subpath(sp, &near, tol) {
|
||||
.map(|sp| match smooth_subpath(sp, &near, tol, sigma) {
|
||||
Some(n) if n != *sp && n.anchors.len() >= 2 => {
|
||||
changed = true;
|
||||
n
|
||||
@@ -167,9 +178,13 @@ pub(super) fn smooth_region(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Ok(json!({ "ids": [], "before": 0, "after": 0 }));
|
||||
}
|
||||
let ids: Vec<NodeId> = plan.iter().map(|(id, _)| *id).collect();
|
||||
s.edit("Smooth", |d, _| {
|
||||
s.edit("Smooth", |d, sel| {
|
||||
for (id, np) in plan {
|
||||
*path_mut(d, id)? = np;
|
||||
// The smoothed path has new anchors, so the old anchor and segment indices are
|
||||
// dropped and the path stays selected whole.
|
||||
sel.anchors.remove(&id);
|
||||
sel.segments.remove(&id);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
@@ -678,12 +678,22 @@ fn undo_group_end(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// under an interaction that would then preview on, or cancel to, the document from before (#1719).
|
||||
/// A typing session also ends in the Type tool, whose caret and marked text (IME) must follow the
|
||||
/// document. A preview that Real-time Drawing off left unapplied is applied first, as the tool's own
|
||||
/// commit applies it; when it fails, the interaction is canceled.
|
||||
/// commit applies it; when it fails, the interaction is canceled. The applied preview's warning
|
||||
/// goes to the running command's result or the tool's status messages, as the tool's own commit
|
||||
/// reports it ([`Session::note_settled_warning`]).
|
||||
pub(crate) fn settle_interaction(s: &mut Session) -> Result<()> {
|
||||
let typing = typing_in_progress(s);
|
||||
match s.unapplied_interaction_preview().filter(|_| !s.previewing) {
|
||||
Some((cmd, p)) if s.preview(&cmd, &p).is_err() => s.cancel_interaction()?,
|
||||
_ => s.commit_interaction()?,
|
||||
Some((cmd, p)) => match s.preview(&cmd, &p) {
|
||||
Ok(v) => {
|
||||
if let Some(w) = v.get("warning").and_then(Value::as_str) {
|
||||
s.note_settled_warning(w);
|
||||
}
|
||||
s.commit_interaction()?
|
||||
}
|
||||
Err(_) => s.cancel_interaction()?,
|
||||
},
|
||||
None => s.commit_interaction()?,
|
||||
}
|
||||
if typing {
|
||||
s.set_tool_option("endTyping", &Value::Bool(true));
|
||||
|
||||
@@ -135,6 +135,9 @@ fn touch(a: &Rect, b: &Rect) -> bool {
|
||||
struct Sets {
|
||||
parent: Vec<usize>,
|
||||
seeded: Vec<bool>,
|
||||
/// How many open boxes the sweep's boxes met.
|
||||
#[cfg(test)]
|
||||
meets: usize,
|
||||
}
|
||||
|
||||
impl Sets {
|
||||
@@ -180,17 +183,25 @@ impl Sets {
|
||||
/// tops that knows the lowest bottom below each of its branches, so each box meets only the open
|
||||
/// boxes it overlaps, not every open one (many objects stacked in a column, sharing their
|
||||
/// horizontal extent, would otherwise compare every pair). An open box inside a later box of
|
||||
/// its group, ending no further right, is closed early: whatever overlaps it overlaps that box.
|
||||
/// Fails only when cancelled ([`vectorcraft_doc::cancel`]).
|
||||
/// its group, ending no further right, is closed early, and a box inside an open box of its group,
|
||||
/// ending no further right, isn't opened: whatever overlaps it overlaps that box. Fails only when
|
||||
/// cancelled ([`vectorcraft_doc::cancel`]).
|
||||
pub(super) fn overlapping(bounds: &[Option<Rect>]) -> Result<Vec<Vec<usize>>, Cancelled> {
|
||||
Ok(sweep(bounds, None)?.groups())
|
||||
}
|
||||
|
||||
/// [`overlapping`]'s sweep. With `see_through`, two boxes are joined only when one of them is
|
||||
/// see-through, and an open box is closed early only inside a later see-through box.
|
||||
/// see-through, and an open box is closed early, or a box isn't opened, only inside a see-through
|
||||
/// box. The open
|
||||
/// see-through boxes and the open boxes without transparency are then in trees of their own, and
|
||||
/// a box without transparency meets only the see-through ones.
|
||||
fn sweep(bounds: &[Option<Rect>], see_through: Option<&[bool]>) -> Result<Sets, Cancelled> {
|
||||
let mut sets = Sets { parent: (0..bounds.len()).collect(), seeded: (0..bounds.len()).map(|i| see_through.is_some_and(|s| s[i])).collect() };
|
||||
let joins = |a: usize, b: usize| see_through.is_none_or(|s| s[a] || s[b]);
|
||||
let mut sets = Sets {
|
||||
parent: (0..bounds.len()).collect(),
|
||||
seeded: (0..bounds.len()).map(|i| see_through.is_some_and(|s| s[i])).collect(),
|
||||
#[cfg(test)]
|
||||
meets: 0,
|
||||
};
|
||||
let boxes: Vec<(usize, Rect)> = bounds.iter().enumerate().filter_map(|(i, b)| b.filter(finite).map(|b| (i, b))).collect();
|
||||
let n = boxes.len();
|
||||
// Each box's place in the tree: by top (then index).
|
||||
@@ -201,9 +212,11 @@ fn sweep(bounds: &[Option<Rect>], see_through: Option<&[bool]>) -> Result<Sets,
|
||||
for (pos, &k) in by_top.iter().enumerate() {
|
||||
leaf[k] = pos;
|
||||
}
|
||||
// The lowest bottom of the open boxes below each node (−∞: none open).
|
||||
// The lowest bottom of the open boxes below each node (−∞: none open), in the tree of the
|
||||
// boxes without transparency (every box without `see_through`) and the see-through boxes'.
|
||||
let size = n.next_power_of_two().max(1);
|
||||
let mut low = vec![f64::NEG_INFINITY; 2 * size];
|
||||
let mut low = [vec![f64::NEG_INFINITY; 2 * size], if see_through.is_some() { vec![f64::NEG_INFINITY; 2 * size] } else { vec![] }];
|
||||
let tree = |k: usize| usize::from(see_through.is_some_and(|s| s[boxes[k].0]));
|
||||
let set = |low: &mut [f64], pos: usize, v: f64| {
|
||||
let mut i = pos + size;
|
||||
low[i] = v;
|
||||
@@ -226,43 +239,63 @@ fn sweep(bounds: &[Option<Rect>], see_through: Option<&[bool]>) -> Result<Sets,
|
||||
while let Some(&c) = by_right.get(closing)
|
||||
&& boxes[c].1.x1 < b.x0
|
||||
{
|
||||
set(&mut low, leaf[c], f64::NEG_INFINITY);
|
||||
set(&mut low[tree(c)], leaf[c], f64::NEG_INFINITY);
|
||||
closing += 1;
|
||||
}
|
||||
// The open boxes with their top at most this bottom and their bottom at least this top.
|
||||
// The open boxes it joins with their top at most this bottom and their bottom at least
|
||||
// this top: every one, or with `see_through` the see-through ones and, for a see-through
|
||||
// box, the others too.
|
||||
let shadows = see_through.is_none_or(|s| s[boxes[k].0]);
|
||||
let looks: &[usize] = match see_through {
|
||||
None => &[0],
|
||||
Some(_) if shadows => &[0, 1],
|
||||
Some(_) => &[1],
|
||||
};
|
||||
let below = tops.partition_point(|t| *t <= b.y1);
|
||||
met.clear();
|
||||
stack.clear();
|
||||
stack.push((1, 0, size));
|
||||
while let Some((node, lo, hi)) = stack.pop() {
|
||||
work += 1;
|
||||
if work.is_multiple_of(4096) {
|
||||
vectorcraft_doc::cancel::check()?;
|
||||
for &t in looks {
|
||||
stack.clear();
|
||||
stack.push((1, 0, size));
|
||||
while let Some((node, lo, hi)) = stack.pop() {
|
||||
work += 1;
|
||||
if work.is_multiple_of(4096) {
|
||||
vectorcraft_doc::cancel::check()?;
|
||||
}
|
||||
if lo >= below || low[t][node] < b.y0 {
|
||||
continue;
|
||||
}
|
||||
if hi - lo == 1 {
|
||||
met.push(by_top[lo]);
|
||||
continue;
|
||||
}
|
||||
let mid = (lo + hi) / 2;
|
||||
stack.push((2 * node + 1, mid, hi));
|
||||
stack.push((2 * node, lo, mid));
|
||||
}
|
||||
if lo >= below || low[node] < b.y0 {
|
||||
continue;
|
||||
}
|
||||
if hi - lo == 1 {
|
||||
met.push(by_top[lo]);
|
||||
continue;
|
||||
}
|
||||
let mid = (lo + hi) / 2;
|
||||
stack.push((2 * node + 1, mid, hi));
|
||||
stack.push((2 * node, lo, mid));
|
||||
}
|
||||
#[cfg(test)]
|
||||
{
|
||||
sets.meets += met.len();
|
||||
}
|
||||
// An open box it met that holds it, ending no further right, and that joins whatever it
|
||||
// overlaps: whatever later overlaps this box overlaps that one and joins it, so this box
|
||||
// isn't opened.
|
||||
let holder = met.iter().copied().find(|&o| {
|
||||
let ob = boxes[o].1;
|
||||
see_through.is_none_or(|s| s[boxes[o].0]) && b.x1 <= ob.x1 && ob.y0 <= b.y0 && b.y1 <= ob.y1
|
||||
});
|
||||
// Whatever overlaps a box inside this one overlaps this one, and joins it when this one is
|
||||
// see-through.
|
||||
let shadows = see_through.is_none_or(|s| s[boxes[k].0]);
|
||||
for &o in &met {
|
||||
if joins(boxes[k].0, boxes[o].0) {
|
||||
sets.join(boxes[k].0, boxes[o].0);
|
||||
}
|
||||
sets.join(boxes[k].0, boxes[o].0);
|
||||
let ob = boxes[o].1;
|
||||
if shadows && ob.x1 <= b.x1 && b.y0 <= ob.y0 && ob.y1 <= b.y1 {
|
||||
set(&mut low, leaf[o], f64::NEG_INFINITY);
|
||||
if shadows && Some(o) != holder && ob.x1 <= b.x1 && b.y0 <= ob.y0 && ob.y1 <= b.y1 {
|
||||
set(&mut low[tree(o)], leaf[o], f64::NEG_INFINITY);
|
||||
}
|
||||
}
|
||||
set(&mut low, leaf[k], b.y1);
|
||||
if holder.is_none() {
|
||||
set(&mut low[tree(k)], leaf[k], b.y1);
|
||||
}
|
||||
}
|
||||
Ok(sets)
|
||||
}
|
||||
@@ -392,6 +425,11 @@ mod tests {
|
||||
|
||||
/// What [`overlapping`] gives, comparing every pair.
|
||||
fn every_pair(bounds: &[Option<Rect>]) -> Vec<Vec<usize>> {
|
||||
every_pair_joining(bounds, |_, _| true)
|
||||
}
|
||||
|
||||
/// The groups of `bounds` comparing every pair, joining overlapping pairs that `joins`.
|
||||
fn every_pair_joining(bounds: &[Option<Rect>], joins: impl Fn(usize, usize) -> bool) -> Vec<Vec<usize>> {
|
||||
let n = bounds.len();
|
||||
let mut group: Vec<usize> = (0..n).collect();
|
||||
let hit = |a: &Rect, b: &Rect| a.x0 <= b.x1 && b.x0 <= a.x1 && a.y0 <= b.y1 && b.y0 <= a.y1;
|
||||
@@ -401,6 +439,7 @@ mod tests {
|
||||
for j in 0..n {
|
||||
if let (Some(a), Some(b)) = (bounds[i], bounds[j])
|
||||
&& hit(&a, &b)
|
||||
&& joins(i, j)
|
||||
&& group[j] < group[i]
|
||||
{
|
||||
group[i] = group[j];
|
||||
@@ -464,6 +503,69 @@ mod tests {
|
||||
assert_eq!(overlapping(&odd).unwrap(), vec![vec![0, 2], vec![1]]);
|
||||
}
|
||||
|
||||
/// `n` boxes sharing their left and top edges, each inside the one before.
|
||||
fn shrinking_nest(n: usize) -> Vec<Option<Rect>> {
|
||||
(0..n).map(|i| Some(Rect::new(0.0, 0.0, 2.0 * (n - i) as f64, 2.0 * (n - i) as f64))).collect()
|
||||
}
|
||||
|
||||
/// Each box of a nest that shrinks to the right and bottom meets only the outermost box, which
|
||||
/// stays open and holds it, not every box around it.
|
||||
#[test]
|
||||
fn a_shrinking_nest_meets_only_its_outermost_box() {
|
||||
let n = 512;
|
||||
let bounds = shrinking_nest(n);
|
||||
let mut sets = sweep(&bounds, None).unwrap();
|
||||
assert_eq!(sets.meets, n - 1);
|
||||
assert_eq!(sets.groups(), every_pair(&bounds));
|
||||
assert_eq!(sets.groups(), vec![(0..n).collect::<Vec<_>>()]);
|
||||
// Equal boxes: the later one isn't opened and the earlier one stays open for the third.
|
||||
let same = [Some(Rect::new(0.0, 0.0, 10.0, 10.0)), Some(Rect::new(0.0, 0.0, 10.0, 10.0)), Some(Rect::new(9.0, 9.0, 20.0, 20.0))];
|
||||
assert_eq!(overlapping(&same).unwrap(), vec![vec![0, 1, 2]]);
|
||||
// With transparency, an opaque box isn't opened inside a see-through box, and boxes inside
|
||||
// an opaque box are opened: an opaque box that overlaps only the inner one still joins it
|
||||
// when that one is see-through.
|
||||
let see = [true, false];
|
||||
let mut sets = sweep(&bounds[..2], Some(&see)).unwrap();
|
||||
assert_eq!(sets.groups(), vec![vec![0, 1]]);
|
||||
let held = [Some(Rect::new(0.0, 0.0, 20.0, 20.0)), Some(Rect::new(0.0, 0.0, 10.0, 10.0)), Some(Rect::new(5.0, 5.0, 8.0, 8.0))];
|
||||
let mut sets = sweep(&held, Some(&[false, true, false])).unwrap();
|
||||
assert_eq!(sets.groups(), vec![vec![0, 1, 2]]);
|
||||
let mut sets = sweep(&held, Some(&[true, false, false])).unwrap();
|
||||
assert_eq!(sets.groups(), vec![vec![0, 1, 2]]);
|
||||
let mut sets = sweep(&held, Some(&[false, false, true])).unwrap();
|
||||
assert_eq!(sets.groups(), vec![vec![0, 1, 2]]);
|
||||
let mut sets = sweep(&held, Some(&[false, false, false])).unwrap();
|
||||
assert_eq!(sets.groups(), vec![vec![0], vec![1], vec![2]]);
|
||||
}
|
||||
|
||||
/// Boxes nested at shared corners and placed at random, some see-through, group with and
|
||||
/// without transparency as comparing every pair groups them.
|
||||
#[test]
|
||||
fn nested_and_scattered_boxes_group_as_comparing_every_pair() {
|
||||
let mut seed = 0x51_7cc1_b727_220au64;
|
||||
let mut next = |m: f64| {
|
||||
seed ^= seed << 13;
|
||||
seed ^= seed >> 7;
|
||||
seed ^= seed << 17;
|
||||
(seed % 1000) as f64 / 1000.0 * m
|
||||
};
|
||||
for round in 0..40 {
|
||||
let n = 6 + round * 3;
|
||||
let bounds: Vec<Option<Rect>> = (0..n)
|
||||
.map(|_| {
|
||||
// Corners on a coarse grid so that edges are often shared and boxes often nest.
|
||||
let (x, y) = ((next(6.0).floor()) * 10.0, (next(6.0).floor()) * 10.0);
|
||||
let (w, h) = ((next(5.0).floor() + 1.0) * 10.0, (next(5.0).floor() + 1.0) * 10.0);
|
||||
Some(Rect::new(x, y, x + w, y + h))
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(overlapping(&bounds).unwrap(), every_pair(&bounds), "round {round}");
|
||||
let see: Vec<bool> = (0..n).map(|_| next(1.0) < 0.3).collect();
|
||||
let mut sets = sweep(&bounds, Some(&see)).unwrap();
|
||||
assert_eq!(sets.groups(), every_pair_joining(&bounds, |i, j| see[i] || see[j]), "round {round}, with transparency");
|
||||
}
|
||||
}
|
||||
|
||||
/// A filled rectangle, unstroked.
|
||||
fn filled(id: u64, r: Rect) -> Node {
|
||||
let look = vectorcraft_doc::Appearance::basic(
|
||||
@@ -583,6 +685,62 @@ mod tests {
|
||||
assert_eq!(flatten_groups(&reach, &painted, &vec![false; n], 0.0).unwrap().len(), n);
|
||||
}
|
||||
|
||||
/// A small see-through box, then `n` opaque boxes nested around it, each inside the one
|
||||
/// before and sharing its left and top edges.
|
||||
fn nest_around_a_see_through_box(n: usize) -> (Vec<Option<Rect>>, Vec<bool>) {
|
||||
let mut bounds = vec![Some(Rect::new(0.0, 0.0, 1.0, 1.0))];
|
||||
bounds.extend((0..n).map(|i| Some(Rect::new(0.0, 0.0, 2.0 * (n - i) as f64 + 1.0, 2.0 * (n - i) as f64 + 1.0))));
|
||||
let mut see = vec![false; n + 1];
|
||||
see[0] = true;
|
||||
(bounds, see)
|
||||
}
|
||||
|
||||
/// Opaque boxes nested in each other around a see-through box each meet only the see-through
|
||||
/// box, not the open opaque boxes they can't join, and all join it.
|
||||
#[test]
|
||||
fn nested_opaque_boxes_meet_only_the_see_through_box() {
|
||||
let n = 512;
|
||||
let (bounds, see) = nest_around_a_see_through_box(n);
|
||||
let mut sets = sweep(&bounds, Some(&see)).unwrap();
|
||||
assert_eq!(sets.meets, n);
|
||||
assert_eq!(sets.groups(), vec![(0..=n).collect::<Vec<_>>()]);
|
||||
// The unfiltered sweep that runs before it meets each box once too.
|
||||
let mut sets = sweep(&bounds, None).unwrap();
|
||||
assert_eq!(sets.meets, n);
|
||||
assert_eq!(sets.groups(), vec![(0..=n).collect::<Vec<_>>()]);
|
||||
let (painted, see) = nest_around_a_see_through_box(40);
|
||||
let reach: Vec<Option<Rect>> = painted.iter().map(|b| b.map(|b| b.inflate(1.0, 1.0))).collect();
|
||||
for fringe in [0.0, 0.7] {
|
||||
let groups = flatten_groups(&reach, &painted, &see, fringe).unwrap();
|
||||
check(&reach, &painted, &see, fringe, &groups, &format!("nest, fringe {fringe}"));
|
||||
assert_eq!(groups, vec![(0..=40).collect::<Vec<_>>()]);
|
||||
}
|
||||
}
|
||||
|
||||
/// An opaque box inside a later see-through box is closed: later boxes meet the see-through
|
||||
/// box instead, and join the opaque one through it.
|
||||
#[test]
|
||||
fn a_see_through_box_closes_an_opaque_box_inside_it() {
|
||||
// An opaque box, a see-through box around it, a see-through box over both and an opaque
|
||||
// box over the first.
|
||||
let bounds = [
|
||||
Some(Rect::new(0.0, 0.0, 10.0, 10.0)),
|
||||
Some(Rect::new(0.0, 0.0, 20.0, 20.0)),
|
||||
Some(Rect::new(5.0, 5.0, 30.0, 30.0)),
|
||||
Some(Rect::new(8.0, 8.0, 12.0, 12.0)),
|
||||
];
|
||||
let see = [false, true, true, false];
|
||||
let mut sets = sweep(&bounds, Some(&see)).unwrap();
|
||||
// The second box meets the first; the third meets the second; the fourth meets the second
|
||||
// and the third.
|
||||
assert_eq!(sets.meets, 4);
|
||||
assert_eq!(sets.groups(), vec![vec![0, 1, 2, 3]]);
|
||||
// Opaque boxes alone meet nothing.
|
||||
let mut sets = sweep(&bounds, Some(&[false; 4])).unwrap();
|
||||
assert_eq!(sets.meets, 0);
|
||||
assert_eq!(sets.groups().len(), 4);
|
||||
}
|
||||
|
||||
/// An opaque box between a member and its group's top that paints over the member joins, and
|
||||
/// so on along a chain; one under the member stays, but for one within the fringe.
|
||||
#[test]
|
||||
|
||||
@@ -1034,6 +1034,85 @@ fn an_opaque_pick_replaces_the_opacity_the_series_stores() {
|
||||
assert_eq!(spec(&s, id).series_paints[0].fill_opacity, None);
|
||||
}
|
||||
|
||||
/// A column graph whose series 0 stores the 40% Multiply fill set on its first mark, and a mark of series 1 whose top fill
|
||||
/// row has no paint and is opaque and Normal: the session, the graph, series 0's marks and that source.
|
||||
fn marks_and_unpainted_source() -> (Session, NodeId, Vec<NodeId>, NodeId) {
|
||||
let (mut s, id, _, marks) = column_marks();
|
||||
let source = series(s.doc().unwrap().doc.node(id).unwrap(), 1).children().unwrap()[0].id;
|
||||
s.execute("appearance.setItem", &json!({"ids": [source.0], "index": top_row(&s, source, true), "none": true})).unwrap();
|
||||
let fill = top_row(&s, marks[0], true);
|
||||
s.execute("appearance.setItem", &json!({"ids": [marks[0].0], "index": fill, "opacity": 40, "blend": "multiply"})).unwrap();
|
||||
let kept = spec(&s, id).series_paints[0].clone();
|
||||
assert_eq!((kept.fill_opacity, kept.fill_blend), (Some(0.4), Some(BlendMode::Multiply)));
|
||||
(s, id, marks, source)
|
||||
}
|
||||
|
||||
/// An Eyedropper pick from a fill row without paint onto a mark whose fill had paint replaces the fill opacity and blend
|
||||
/// mode another mark of the series stored: the series is drawn opaque and Normal again.
|
||||
#[test]
|
||||
fn an_eyedropper_pick_that_unpaints_a_series_fill_clears_its_stored_transparency() {
|
||||
let (mut s, id, marks, source) = marks_and_unpainted_source();
|
||||
let mark = s.doc().unwrap().doc.node(marks[1]).unwrap().appearance.fill().unwrap().clone();
|
||||
assert_eq!((mark.paint.is_none(), mark.opacity, mark.blend), (false, 1.0, BlendMode::Normal), "the target's fill row");
|
||||
s.execute("appearance.copyFrom", &json!({"source": source.0, "ids": [marks[1].0]})).unwrap();
|
||||
let picked = s.doc().unwrap().doc.node(marks[1]).unwrap().appearance.fill().unwrap().clone();
|
||||
assert_eq!((picked.paint.is_none(), picked.opacity, picked.blend), (true, 1.0, BlendMode::Normal));
|
||||
let kept = spec(&s, id).series_paints[0].clone();
|
||||
assert_eq!((kept.fill_opacity, kept.fill_blend), (None, None));
|
||||
s.execute("graph.setData", &json!({"rows": [[1, 2], [3, 4]]})).unwrap();
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
let fills: Vec<_> = series(&n, 0).children().unwrap().iter().filter_map(|m| m.appearance.fill().map(|f| (f.opacity, f.blend))).collect();
|
||||
assert!(fills.iter().all(|f| *f == (1.0, BlendMode::Normal)), "{fills:?}");
|
||||
}
|
||||
|
||||
/// An Eyedropper pick from a fill row without paint onto a mark whose fill had no paint before the pick either leaves the
|
||||
/// fill opacity and blend mode another mark of the series stored.
|
||||
#[test]
|
||||
fn an_eyedropper_pick_of_an_already_unpainted_row_leaves_series_transparency() {
|
||||
let (mut s, id, marks, source) = marks_and_unpainted_source();
|
||||
s.execute("appearance.setItem", &json!({"ids": [marks[1].0], "index": top_row(&s, marks[1], true), "none": true})).unwrap();
|
||||
let kept = spec(&s, id).series_paints[0].clone();
|
||||
assert_eq!((kept.fill_opacity, kept.fill_blend), (Some(0.4), Some(BlendMode::Multiply)), "a color set to None writes no opacity");
|
||||
s.execute("appearance.copyFrom", &json!({"source": source.0, "ids": [marks[1].0]})).unwrap();
|
||||
let kept = spec(&s, id).series_paints[0].clone();
|
||||
assert_eq!((kept.fill_opacity, kept.fill_blend), (Some(0.4), Some(BlendMode::Multiply)));
|
||||
}
|
||||
|
||||
/// A whole Eyedropper pick from a source with no fill row, or no stroke row, removes that row from the mark. Where the
|
||||
/// mark's row had paint, the pick replaces the opacity and blend mode another mark of the series stored for that kind
|
||||
/// of row. Where the mark's row had no paint, the stored values stay.
|
||||
#[test]
|
||||
fn a_whole_eyedropper_pick_that_removes_a_painted_row_clears_its_stored_transparency() {
|
||||
let stored = |s: &Session, id: NodeId, fill: bool| {
|
||||
let kept = spec(s, id).series_paints[0].clone();
|
||||
if fill { (kept.fill_opacity, kept.fill_blend) } else { (kept.stroke_opacity, kept.stroke_blend) }
|
||||
};
|
||||
for (fill, painted) in [(true, true), (false, true), (false, false)] {
|
||||
let (mut s, id, _, marks) = column_marks();
|
||||
let row = top_row(&s, marks[0], fill);
|
||||
if painted {
|
||||
s.execute("appearance.setItem", &json!({"ids": [marks[1].0], "index": row, "color": "#ff0000"})).unwrap();
|
||||
}
|
||||
s.execute("appearance.setItem", &json!({"ids": [marks[0].0], "index": row, "color": "#ff0000", "opacity": 40, "blend": "multiply"})).unwrap();
|
||||
assert_eq!(stored(&s, id, fill), (Some(0.4), Some(BlendMode::Multiply)), "fill {fill}, painted {painted}");
|
||||
let source = series(s.doc().unwrap().doc.node(id).unwrap(), 1).children().unwrap()[0].id;
|
||||
s.execute("appearance.removeItem", &json!({"ids": [source.0], "index": top_row(&s, source, fill)})).unwrap();
|
||||
let was = spec(&s, id).series_paints;
|
||||
s.execute("appearance.copyFrom", &json!({"source": source.0, "ids": [marks[1].0]})).unwrap();
|
||||
let mark = s.doc().unwrap().doc.node(marks[1]).unwrap().clone();
|
||||
assert!(!mark.appearance.items.iter().any(|it| it.is_fill() == fill), "the pick removed the row: fill {fill}");
|
||||
let want = if painted { (None, None) } else { (Some(0.4), Some(BlendMode::Multiply)) };
|
||||
assert_eq!(stored(&s, id, fill), want, "fill {fill}, painted {painted}");
|
||||
if painted {
|
||||
let after = spec(&s, id).series_paints;
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(spec(&s, id).series_paints, was);
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(spec(&s, id).series_paints, after);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An appearance moved between two marks of one series leaves the series with the target's paint, not the source's
|
||||
/// empty one, and the series still shows when the graph is drawn again.
|
||||
#[test]
|
||||
@@ -1251,6 +1330,45 @@ fn a_style_that_removes_a_marks_stroke_replaces_the_kept_stroke_opacity() {
|
||||
}
|
||||
}
|
||||
|
||||
/// An Eyedropper pick from a stroke row without paint onto a marker whose stroke had paint replaces the stroke opacity and
|
||||
/// blend mode the series' Filled Lines band left, in the pick's undo step: the band's outline is drawn opaque and Normal
|
||||
/// again. A pick onto a marker whose stroke had no paint before the pick leaves them as they are.
|
||||
#[test]
|
||||
fn an_eyedropper_pick_that_unpaints_a_series_stroke_clears_its_stored_transparency() {
|
||||
for stroked in [true, false] {
|
||||
let (mut s, id, band) = band_graph();
|
||||
let parts = series_parts(&s, id, 0);
|
||||
let (marker, source) = (parts[1].id, parts[2].id);
|
||||
let st = parts[2].appearance.stroke().unwrap();
|
||||
assert_eq!((st.paint.is_none(), st.opacity, st.blend), (true, 1.0, BlendMode::Normal), "the source's stroke row");
|
||||
if stroked {
|
||||
let row = top_row(&s, marker, false);
|
||||
s.execute("appearance.setItem", &json!({"ids": [marker.0], "index": row, "color": "#ff0000"})).unwrap();
|
||||
}
|
||||
let row = top_row(&s, band, false);
|
||||
s.execute("appearance.setItem", &json!({"ids": [band.0], "index": row, "opacity": 40, "blend": "multiply"})).unwrap();
|
||||
let was = spec(&s, id).series_paints;
|
||||
assert_eq!((was[0].stroke_opacity, was[0].stroke_blend), (Some(0.4), Some(BlendMode::Multiply)));
|
||||
s.execute("appearance.copyFrom", &json!({"source": source.0, "ids": [marker.0]})).unwrap();
|
||||
let picked = s.doc().unwrap().doc.node(marker).unwrap().appearance.stroke().unwrap().clone();
|
||||
assert_eq!((picked.paint.is_none(), picked.opacity, picked.blend), (true, 1.0, BlendMode::Normal), "stroked {stroked}");
|
||||
let kept = spec(&s, id).series_paints[0].clone();
|
||||
let want = if stroked { (None, None) } else { (Some(0.4), Some(BlendMode::Multiply)) };
|
||||
assert_eq!((kept.stroke_opacity, kept.stroke_blend), want, "stroked {stroked}");
|
||||
if stroked {
|
||||
let after = spec(&s, id).series_paints;
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(spec(&s, id).series_paints, was);
|
||||
assert!(!s.doc().unwrap().doc.node(marker).unwrap().appearance.stroke_paint().is_none(), "the undo took back the pick");
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(spec(&s, id).series_paints, after);
|
||||
}
|
||||
redrawn_band(&mut s, id);
|
||||
let st = series_parts(&s, id, 0)[0].appearance.stroke().unwrap().clone();
|
||||
assert_eq!((Some(st.opacity).filter(|o| *o < 1.0), Some(st.blend).filter(|b| *b != BlendMode::Normal)), want, "stroked {stroked}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A Filled Lines band's stroke row removed with the Appearance panel or set to None with `paint.setStroke` leaves the
|
||||
/// band its color: an empty stored stroke is not a color for the band.
|
||||
#[test]
|
||||
|
||||
@@ -346,6 +346,36 @@ impl Library {
|
||||
}
|
||||
}
|
||||
|
||||
/// Name item `r` `name`, in its place in its kind's list; an item keyed by its name keeps its
|
||||
/// group under the new name (a graphic is keyed by its id, which stays).
|
||||
fn rename_item(&mut self, r: &ItemRef, name: &str) {
|
||||
fn set<'a>(mut names: impl Iterator<Item = &'a mut String>, from: &str, to: &str) {
|
||||
if let Some(n) = names.find(|n| n.as_str() == from) {
|
||||
*n = to.to_string();
|
||||
}
|
||||
}
|
||||
let from = r.item.as_str();
|
||||
match r.kind {
|
||||
ItemKind::Color => set(self.colors.iter_mut().map(|c| &mut c.name), from, name),
|
||||
ItemKind::Gradient => set(self.gradients.iter_mut().map(|g| &mut g.name), from, name),
|
||||
ItemKind::Pattern => set(self.patterns.iter_mut().map(|p| &mut p.name), from, name),
|
||||
ItemKind::CharStyle => set(self.char_styles.iter_mut().map(|t| &mut t.name), from, name),
|
||||
ItemKind::ParaStyle => set(self.para_styles.iter_mut().map(|t| &mut t.name), from, name),
|
||||
ItemKind::Graphic => {
|
||||
if let Some(g) = self.graphics.iter_mut().find(|g| g.id == from) {
|
||||
g.name = name.to_string();
|
||||
}
|
||||
return;
|
||||
}
|
||||
ItemKind::Unknown => return,
|
||||
}
|
||||
for x in self.groups.iter_mut().flat_map(|g| g.items.iter_mut()) {
|
||||
if x == r {
|
||||
x.item = name.to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Move item `r` next to `to`, an item of its kind: just before it, or just after it when
|
||||
/// `after`, in their kind's list (the order the panel shows them in).
|
||||
fn place_next_to(&mut self, r: &ItemRef, to: &ItemRef, after: bool) {
|
||||
@@ -683,7 +713,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Use Library Item",
|
||||
[],
|
||||
None,
|
||||
"{library?, kind, item: name (graphic: id or name), center?: [x, y] (graphic; default: the first artboard's centre), to?: fill|stroke (colors, gradients, patterns; default: the kind's), recorded?: the item as it was when used (recorded in the journal so a replay matches)} graphic: place a copy centred on `center`, its resources pasted along, selected, one undo step; colors and gradients: paint the selection (and the defaults) as paint.setFill/paint.setStroke, a gradient fitting each object; a spot color links to the document's spot swatch of its ink's name, added when the document has none of that colour (a name taken by another colour gets a number), one undo step; patterns: add the pattern and its swatch to the document (a name the document gives another pattern gets a number; the same pattern is reused) and paint the selection (and the defaults) with it, one undo step; charStyle/paraStyle: add the style to the document (a name taken by different attributes gets a number) and apply it to the selected text, one undo step → {kind, ids?, style?}",
|
||||
"{library?, kind, item: name (graphic: id or name), center?: [x, y] (graphic; default: the first artboard's centre), to?: fill|stroke (colors, gradients, patterns; default: the kind's), recorded?: the item as it was when used (recorded in the journal so a replay matches)} graphic: place a copy centred on `center`, its resources pasted along, selected, one undo step; colors and gradients: paint the selection (and the defaults) as paint.setFill/paint.setStroke, a gradient fitting each object; a spot color links to the document's spot swatch of its ink's name, added when the document has none of that colour (a name taken by another colour gets a number), one undo step; patterns: add the pattern and its swatch to the document (a name the document gives another pattern gets a number; the same pattern is reused) and paint the selection (and the defaults) with it, one undo step; charStyle/paraStyle: add the style to the document (a name taken by different attributes gets a number; a character style's color linked to a swatch that isn't a global or spot swatch of the document keeps the color it shows, unlinked) and apply it to the selected text, one undo step → {kind, ids?, style?}",
|
||||
has_doc,
|
||||
use_item
|
||||
),
|
||||
@@ -696,6 +726,24 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
always,
|
||||
remove_item
|
||||
),
|
||||
cmd!(
|
||||
"library.renameItem",
|
||||
"Rename Library Item",
|
||||
[],
|
||||
None,
|
||||
"{library?, kind, item: name (graphic: id or name), name: string (trimmed; 1 to 256 characters)} rename an item; it keeps its place and its group; another item of its kind with that name is an error, and its own name changes nothing; not undoable → {library, kind, item: its key now (graphic: its id), name}",
|
||||
always,
|
||||
rename_item
|
||||
),
|
||||
cmd!(
|
||||
"library.addToCharacterStyles",
|
||||
"Add to Character Styles",
|
||||
[],
|
||||
None,
|
||||
"{library?, item: a character style's name, recorded?: the style as it was when added (recorded in the journal so a replay matches)} add a library character style to the document's character styles without applying it (no text needs to be selected): a document style of that name with the same attributes is reused, a name taken by different attributes gets a number; a color linked to a swatch that isn't a global or spot swatch of the document keeps the color it shows, unlinked; a new style is one undo step, a reused one none → {style: its name in the document, existing: bool}",
|
||||
has_doc,
|
||||
add_to_char_styles
|
||||
),
|
||||
cmd!(
|
||||
"library.createGroup",
|
||||
"New Library Group",
|
||||
@@ -1231,8 +1279,13 @@ fn use_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Kind::CharStyle | Kind::ParaStyle => {
|
||||
let para = kind == Kind::ParaStyle;
|
||||
let name = data.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()).unwrap_or("Style").to_string();
|
||||
let attrs = data.get("attrs").and_then(Value::as_object).cloned().unwrap_or_default();
|
||||
let mut attrs = data.get("attrs").and_then(Value::as_object).cloned().unwrap_or_default();
|
||||
let doc = &s.doc()?.doc;
|
||||
if !para {
|
||||
unlink_missing_swatches(doc, &mut attrs);
|
||||
}
|
||||
// Compared in the form the document stores them in.
|
||||
let attrs = super::textstyles::stored_style_attrs(doc, para, &attrs).unwrap_or(attrs);
|
||||
// The document's style of that name when it is the same; else a new one.
|
||||
let same = super::textstyles::style_attrs(doc, para, &name).is_some_and(|a| a == attrs);
|
||||
let style = if same { name } else { unique(&name, |n| super::textstyles::style_attrs(doc, para, n).is_some()) };
|
||||
@@ -1361,6 +1414,109 @@ fn remove_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
ok()
|
||||
}
|
||||
|
||||
fn rename_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "library.renameItem";
|
||||
let (id, kind, item) = item_param(s, p, C)?;
|
||||
let name = match p.get("name") {
|
||||
None | Some(Value::Null) => return Err(bad(C, "missing `name`")),
|
||||
Some(Value::String(n)) => n.trim().to_string(),
|
||||
Some(_) => return Err(bad(C, "`name` must be a string")),
|
||||
};
|
||||
if name.is_empty() {
|
||||
return Err(bad(C, "missing `name`"));
|
||||
}
|
||||
if name.chars().count() > MAX_NAME {
|
||||
let (label, max) = ("`name`", MAX_NAME);
|
||||
return Err(bad(C, format!("{label} must be at most {max} characters")));
|
||||
}
|
||||
let lib = s.libraries.get(&id).ok_or_else(|| bad(C, format!("no library `{id}`")))?;
|
||||
let r = lib.item_ref(kind.item_kind(), item).ok_or_else(|| bad(C, format!("the library has no item `{item}`")))?;
|
||||
// The item's name now, and whether another item of its kind has the new one.
|
||||
let mut same = false;
|
||||
let mut taken = false;
|
||||
for (_, key, shown) in lib.items().filter(|(k, ..)| *k == r.kind) {
|
||||
if key == r.item {
|
||||
same = shown == name;
|
||||
} else if shown == name {
|
||||
taken = true;
|
||||
}
|
||||
}
|
||||
let key = if r.kind == ItemKind::Graphic { r.item.clone() } else { name.clone() };
|
||||
let out = json!({ "library": id, "kind": str_param(p, "kind"), "item": key, "name": name });
|
||||
if same {
|
||||
return Ok(out);
|
||||
}
|
||||
if taken {
|
||||
return Err(bad(C, format!("the library has another item of that kind named `{name}`")));
|
||||
}
|
||||
s.libraries.change(&id, |lib| {
|
||||
lib.rename_item(&r, &name);
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn add_to_char_styles(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "library.addToCharacterStyles";
|
||||
// A replay (the journal) carries what the style was, so it doesn't depend on the library.
|
||||
let data = match p.get("recorded").cloned() {
|
||||
Some(r) => r,
|
||||
None => {
|
||||
let id = library_id(s, p, C)?;
|
||||
let item = str_param(p, "item").ok_or_else(|| bad(C, "missing `item`"))?;
|
||||
let lib = s.libraries.get(&id).ok_or_else(|| bad(C, format!("no library `{id}`")))?;
|
||||
let t = lib.char_styles.iter().find(|t| t.name == item).ok_or_else(|| bad(C, format!("the library has no item `{item}`")))?;
|
||||
let data = json!({ "name": t.name, "attrs": t.attrs });
|
||||
s.note_journal("recorded", data.clone());
|
||||
data
|
||||
}
|
||||
};
|
||||
let name = data.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()).unwrap_or("Style").to_string();
|
||||
let mut attrs = data.get("attrs").and_then(Value::as_object).cloned().ok_or_else(|| bad(C, "the library item is damaged"))?;
|
||||
let doc = &s.doc()?.doc;
|
||||
unlink_missing_swatches(doc, &mut attrs);
|
||||
// Compared in the form the document stores them in.
|
||||
let attrs = super::textstyles::stored_style_attrs(doc, false, &attrs).unwrap_or(attrs);
|
||||
// The document's style of that name when it is the same; else a new one, which isn't applied.
|
||||
if super::textstyles::style_attrs(doc, false, &name).is_some_and(|a| a == attrs) {
|
||||
return Ok(json!({ "style": name, "existing": true }));
|
||||
}
|
||||
let style = unique(&name, |n| super::textstyles::style_attrs(doc, false, n).is_some());
|
||||
s.execute("charStyle.new", &json!({ "name": style, "attrs": attrs }))?;
|
||||
Ok(json!({ "style": style, "existing": false }))
|
||||
}
|
||||
|
||||
/// Unlink a library character style's `fill` and `stroke` colors (solid, and each gradient stop)
|
||||
/// from swatches that are not global or spot swatches of `doc`: an unlinked color keeps the color
|
||||
/// it shows at full tint, as [`clean_gradient`] keeps a library gradient's stops. A link to a
|
||||
/// global or spot swatch `doc` has stays, and takes that swatch's color.
|
||||
fn unlink_missing_swatches(doc: &vectorcraft_doc::Document, attrs: &mut Map<String, Value>) {
|
||||
let keep = |name: &str| doc.global_color(name).is_some();
|
||||
for key in ["fill", "stroke"] {
|
||||
let Some(mut paint) = attrs.get(key).and_then(|v| serde_json::from_value::<Paint>(v.clone()).ok()) else { continue };
|
||||
let mut changed = false;
|
||||
let mut unlink = |swatch: &mut Option<String>, tint: &mut f32| {
|
||||
if swatch.as_deref().is_some_and(|n| !keep(n)) {
|
||||
*swatch = None;
|
||||
*tint = 1.0;
|
||||
changed = true;
|
||||
}
|
||||
};
|
||||
match &mut paint {
|
||||
Paint::Solid { swatch, tint, .. } => unlink(swatch, tint),
|
||||
Paint::Gradient(g) => {
|
||||
for st in &mut g.gradient.stops {
|
||||
unlink(&mut st.swatch, &mut st.tint);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if changed && let Ok(v) = serde_json::to_value(&paint) {
|
||||
attrs.insert(key.to_string(), v);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `p`'s `name`, trimmed and clipped, else `default`.
|
||||
fn name_param(p: &Value, default: &str) -> String {
|
||||
let mut name = str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()).unwrap_or(default).to_string();
|
||||
|
||||
@@ -172,7 +172,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Make with Top Object",
|
||||
["Object", "Envelope Distort"],
|
||||
Some("Cmd+Alt+C"),
|
||||
"{ids?} the topmost selected path becomes the envelope of the others: its outline splits into four sides at its corners, and each piece of a side takes a share of the content in proportion to its control polygon's length (type maps from its glyph outline bounds) → {id}",
|
||||
"{ids?} the topmost selected path becomes the envelope of the others: its outline splits into four sides at its corners, and each piece of a side takes a share of the content in proportion to its control polygon's length, and a side whose pieces are all one curve split at anchors follows that curve's parameter (type maps from its glyph outline bounds) → {id}",
|
||||
has_multi,
|
||||
env_make_top
|
||||
),
|
||||
|
||||
@@ -1228,7 +1228,7 @@ fn simplify(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(l) => po::simplify_level_tolerance(l),
|
||||
None => given_tolerance.unwrap_or(1.0),
|
||||
};
|
||||
let opts = po::SimplifyOptions { tolerance: tolerance.clamp(1e-4, 1e4), corner_angle_deg: corner_angle, straight_lines, smooth: 0.0 };
|
||||
let opts = po::SimplifyOptions { tolerance: tolerance.clamp(1e-4, 1e4), corner_angle_deg: corner_angle, straight_lines, ..Default::default() };
|
||||
// A path with segments direct-selected simplifies only their runs, and keeps those runs (and the
|
||||
// other anchors it had selected) direct-selected.
|
||||
let roots = selected_roots(s)?;
|
||||
|
||||
+123
-31
@@ -672,13 +672,53 @@ fn takes_over(s: &Session, plugin: &Plugin) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// Tests: runs once in the next `plugin.install` on this thread after its checks and before it
|
||||
/// installs, as another session changing the plug-ins in between would.
|
||||
pub(crate) static BEFORE_INSTALL: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) };
|
||||
/// Tests: runs once in the next `plugin.install` on this thread right after it reads the grant
|
||||
/// held for the id.
|
||||
pub(crate) static AFTER_GRANT_READ: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) };
|
||||
/// Tests: runs once in the next `plugin.install` on this thread after it installs and before it
|
||||
/// writes the store.
|
||||
pub(crate) static BEFORE_STORE: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) };
|
||||
/// Tests: runs once on this thread when [`hold_plugin_changes`] finds the lock held and waits.
|
||||
pub(crate) static WHILE_WAITING: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// Held by `plugin.install` from its first read of the grant until the store holds what it
|
||||
/// installed, and throughout by `plugin.remove`, by loads of the stored plug-ins
|
||||
/// ([`Session::load_stored_plugins`]) and by loads of a plug-ins folder: these run one after the
|
||||
/// other across sessions.
|
||||
static PLUGIN_CHANGES: Mutex<()> = Mutex::new(());
|
||||
|
||||
/// Takes [`PLUGIN_CHANGES`], waiting while another session holds it.
|
||||
pub(crate) fn hold_plugin_changes() -> std::sync::MutexGuard<'static, ()> {
|
||||
match PLUGIN_CHANGES.try_lock() {
|
||||
Ok(held) => held,
|
||||
Err(std::sync::TryLockError::Poisoned(e)) => e.into_inner(),
|
||||
Err(std::sync::TryLockError::WouldBlock) => {
|
||||
#[cfg(test)]
|
||||
if let Some(waiting) = WHILE_WAITING.take() {
|
||||
waiting();
|
||||
}
|
||||
PLUGIN_CHANGES.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `plugin.install`: loads and checks the module, refuses `grant` and `allowHeavy` that neither an
|
||||
/// [`InstallApproval`] for this module nor the session allows, one that asks for a heavy budget
|
||||
/// unless `allowHeavy` says a person agreed, one that lists permissions no person has granted this
|
||||
/// very module unless `grant` lists them all, one that would take another module's place
|
||||
/// ([`takes_over`]) unless `replace` is true, and one whose SHA-256 isn't the `hash` given; records
|
||||
/// the grant with the module's hash, keeps it for the next start and installs it → its
|
||||
/// `plugin.list` entry. A module that lists no permissions ends any grant held for its id.
|
||||
/// ([`takes_over`]) unless `replace` is true, and one whose SHA-256 isn't the `hash` given. It then
|
||||
/// checks the plug-in installed under the id and its grant again while it records the grant with
|
||||
/// the module's hash and installs it ([`registry::install_checked`]), and only then keeps both for
|
||||
/// the next start → its `plugin.list` entry. A refused install changes neither the plug-in store
|
||||
/// nor the plug-ins and grants of the process. A module that lists no permissions ends any grant
|
||||
/// held for its id. A `plugin.remove` in another session waits until the install has written the
|
||||
/// store.
|
||||
fn install(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "plugin.install";
|
||||
// One use: spent whatever this install does.
|
||||
@@ -696,21 +736,36 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
{
|
||||
return Err(bad(C, "the module doesn't have the SHA-256 `hash` gives: nothing was installed"));
|
||||
}
|
||||
if replace == Some(false) && registry::get(plugin.id()).is_some() {
|
||||
return Err(bad(C, format!("a plug-in with id {:?} is already installed", plugin.id())));
|
||||
// A removal in another session waits until the store holds what this install wrote.
|
||||
let _held = hold_plugin_changes();
|
||||
// The grant the checks below count on, the approval included. The install checks it again,
|
||||
// with the plug-in installed under the id, before anything is stored: another session may
|
||||
// change either in between.
|
||||
let seen_grant = registry::granted(plugin.id());
|
||||
#[cfg(test)]
|
||||
if let Some(between) = AFTER_GRANT_READ.take() {
|
||||
between();
|
||||
}
|
||||
// Another module under the id gets the settings and cache kept for it: whoever installs it asks
|
||||
// the user first.
|
||||
if replace != Some(true) && takes_over(s, &plugin) {
|
||||
let installed_already = || bad(C, format!("a plug-in with id {:?} is already installed", plugin.id()));
|
||||
let taken_over = || {
|
||||
let name = permissions::display_text(&plugin.manifest().name, permissions::MAX_SHOWN_NAME);
|
||||
return Err(bad(
|
||||
bad(
|
||||
C,
|
||||
format!(
|
||||
"“{name}” is another module than the plug-in with id {:?} and would get the settings and cache kept for it: install it with `replace: true` once the user agrees",
|
||||
plugin.id()
|
||||
),
|
||||
));
|
||||
)
|
||||
};
|
||||
if replace == Some(false) && registry::get(plugin.id()).is_some() {
|
||||
return Err(installed_already());
|
||||
}
|
||||
// Another module under the id gets the settings and cache kept for it: whoever installs it asks
|
||||
// the user first.
|
||||
if replace != Some(true) && takes_over(s, &plugin) {
|
||||
return Err(taken_over());
|
||||
}
|
||||
let (installed_already, taken_over) = (installed_already(), taken_over());
|
||||
// `grant` and `allowHeavy` say that a person agreed, and a request alone can't say that.
|
||||
let approval = approval.filter(|a| a.covers(&plugin));
|
||||
if !s.plugin_grants_from_requests && ((grant.is_some() && approval.is_none()) || (allow_heavy && !approval.is_some_and(|a| a.heavy))) {
|
||||
@@ -744,15 +799,55 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// this very module already covers all of them.
|
||||
let m = plugin.manifest();
|
||||
let wanted = m.permissions();
|
||||
if !s.plugin_approved(&plugin) && !grant.as_ref().is_some_and(|g| wanted.iter().all(|w| g.contains(w))) {
|
||||
let needs_approval = || {
|
||||
let name = permissions::display_text(&m.name, permissions::MAX_SHOWN_NAME);
|
||||
let asked = permissions::names(&wanted).join(", ");
|
||||
return Err(bad(
|
||||
bad(
|
||||
C,
|
||||
format!(
|
||||
"“{name}” asks for the permissions {asked}: a person has to approve them in the desktop app, or pass `grant` in a session started with --allow-plugin-grants"
|
||||
),
|
||||
));
|
||||
)
|
||||
};
|
||||
let granted_here = grant.as_ref().is_some_and(|g| wanted.iter().all(|w| g.contains(w)));
|
||||
// Without a plug-in store, the grant read above approves the module or doesn't.
|
||||
let approved = match s.plugin_dir {
|
||||
None => !m.asks_permissions() || seen_grant.as_ref().is_some_and(|g| g.covers(&m.id, plugin.hash(), &wanted)),
|
||||
Some(_) => s.plugin_approved(&plugin),
|
||||
};
|
||||
if !approved && !granted_here {
|
||||
return Err(needs_approval());
|
||||
}
|
||||
let needs_approval = needs_approval();
|
||||
let (id, hash, asks) = (m.id.clone(), plugin.hash().to_string(), m.asks_permissions());
|
||||
let g = Grant { id: id.clone(), hash: hash.clone(), permissions: wanted };
|
||||
let update = if asks { registry::GrantUpdate::Record(GrantToken::after_engine_approval(g.clone())) } else { registry::GrantUpdate::Revoke };
|
||||
// Another module installed under the id since the checks above takes the place they found free,
|
||||
// or held by these bytes. A grant that changed since no longer approves what they approved,
|
||||
// unless `grant` approves this module by itself or the new grant covers it.
|
||||
let check = |installed: Option<&Plugin>, held: Option<&Grant>| {
|
||||
if let Some(installed) = installed {
|
||||
match replace {
|
||||
Some(false) => return Err(installed_already),
|
||||
None if installed.hash() != hash => return Err(taken_over),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if asks && !granted_here && held != seen_grant.as_ref() && !held.is_some_and(|h| h.covers(&id, &hash, &g.permissions)) {
|
||||
return Err(needs_approval);
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
#[cfg(test)]
|
||||
if let Some(between) = BEFORE_INSTALL.take() {
|
||||
between();
|
||||
}
|
||||
// The plug-in gets the settings and cache kept for its id. A module without permissions takes
|
||||
// the id over, so nothing the user approved for the id applies any more.
|
||||
let installed = registry::install_checked(plugin, update, check, || s.attach_plugin_storage(&id), err)?;
|
||||
#[cfg(test)]
|
||||
if let Some(between) = BEFORE_STORE.take() {
|
||||
between();
|
||||
}
|
||||
// Installed plug-ins stay installed after a restart (#2541). The module is written first and its
|
||||
// grant only once it is there; when the grant can't be written, the store gets the module it
|
||||
@@ -760,18 +855,14 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// which the grant doesn't cover. A write that reports a failure may still have put the old
|
||||
// module back, so the store is read again to tell which module it holds. A stored module that
|
||||
// can't be read back isn't replaced by one that needs a grant.
|
||||
let previous = s.stored_plugin_bytes(plugin.id());
|
||||
let mut stored = (previous.is_ok() || !m.asks_permissions()) && s.store_plugin(plugin.id(), &bytes);
|
||||
let holds_new = |s: &Session| s.stored_plugin_bytes(plugin.id()).is_ok_and(|held| held.as_deref() == Some(&bytes[..]));
|
||||
if m.asks_permissions() {
|
||||
let g = Grant { id: m.id.clone(), hash: plugin.hash().to_string(), permissions: wanted };
|
||||
registry::grant(GrantToken::after_engine_approval(g.clone()));
|
||||
if stored && !s.store_grant(&m.id, Some(g)) {
|
||||
stored = !s.put_back_plugin(plugin.id(), previous.ok().flatten().as_deref()) && holds_new(s);
|
||||
let previous = s.stored_plugin_bytes(&id);
|
||||
let mut stored = (previous.is_ok() || !asks) && s.store_plugin(&id, &bytes);
|
||||
let holds_new = |s: &Session| s.stored_plugin_bytes(&id).is_ok_and(|held| held.as_deref() == Some(&bytes[..]));
|
||||
if asks {
|
||||
if stored && !s.store_grant(&id, Some(g)) {
|
||||
stored = !s.put_back_plugin(&id, previous.ok().flatten().as_deref()) && holds_new(s);
|
||||
}
|
||||
} else {
|
||||
// This module takes the id over, so nothing the user approved for the id applies any more.
|
||||
registry::revoke(&m.id);
|
||||
// When the write failed, the old stored module stays in the folder and needs its grant at
|
||||
// the next launch. A grant that can't be removed still approves the old bytes, so the store
|
||||
// gets the module it held back. When that module can't be read or written back, or there
|
||||
@@ -780,23 +871,21 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// approves nothing, and the new module stays; one that can't be opened or read may approve
|
||||
// the old bytes once it reads again.
|
||||
let writes = s.grant_writes();
|
||||
if stored && !s.store_grant(&m.id, None) && s.holds_plugin_grant(&m.id) {
|
||||
let back = previous.as_ref().is_ok_and(|held| s.put_back_plugin(plugin.id(), held.as_deref()));
|
||||
if stored && !s.store_grant(&id, None) && s.holds_plugin_grant(&id) {
|
||||
let back = previous.as_ref().is_ok_and(|held| s.put_back_plugin(&id, held.as_deref()));
|
||||
stored = !back && holds_new(s);
|
||||
if !back || matches!(previous, Ok(None)) {
|
||||
s.ignore_stored_grant(&m.id, writes);
|
||||
s.ignore_stored_grant(&id, writes);
|
||||
}
|
||||
}
|
||||
}
|
||||
// It gets the settings and cache kept for its id.
|
||||
s.attach_plugin_storage(plugin.id());
|
||||
// Installing a disabled plug-in again (an updated version) turns it on for the next launch too,
|
||||
// also when it is disabled by its stored file alone (it stopped a launch while loading). When
|
||||
// the new version could not replace the stored file, the old one stays disabled.
|
||||
let file = s.stored_plugin_file(plugin.id());
|
||||
let file = s.stored_plugin_file(&id);
|
||||
let mut changed = false;
|
||||
if file.is_none() || stored {
|
||||
changed = safe_mode::set_enabled(&safe_mode::Item::of(&plugin), true);
|
||||
changed = safe_mode::set_enabled(&safe_mode::Item::of(&installed), true);
|
||||
if let Some(file) = file {
|
||||
changed |= safe_mode::set_enabled(&safe_mode::Item::file(file), true);
|
||||
}
|
||||
@@ -804,7 +893,6 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if changed {
|
||||
s.store_disabled_plugins();
|
||||
}
|
||||
let installed = registry::install(plugin).map_err(err)?;
|
||||
let mut v = describe_installed(&installed);
|
||||
if !unknown.is_empty() {
|
||||
v["unknownCommands"] = json!(unknown);
|
||||
@@ -904,6 +992,8 @@ fn load_folder(s: &Session, folder: &str) -> Value {
|
||||
None if crate::file_access::current().is_none() => Ok(()),
|
||||
None => Err(format!("automation path rejected: {} isn't valid text", f.display())),
|
||||
};
|
||||
// A `plugin.install` in another session finishes writing the store first.
|
||||
let _held = hold_plugin_changes();
|
||||
match registry::load_folder_where(std::path::Path::new(folder), allow, s.plugin_folder_approver()) {
|
||||
Ok(r) => {
|
||||
for id in &r.loaded {
|
||||
@@ -1074,6 +1164,8 @@ fn info(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = str_param(p, "id").ok_or_else(|| bad("plugin.remove", "missing `id`"))?;
|
||||
// An install in another session finishes its store writes first.
|
||||
let _held = hold_plugin_changes();
|
||||
let installed = registry::get(id).is_some();
|
||||
// Settings and cache the store keeps for an id that isn't installed are deleted too.
|
||||
let stored = !installed && vectorcraft_plugins::manifest::valid_id(id) && s.has_plugin_storage(id);
|
||||
|
||||
@@ -478,6 +478,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"recolor.pickTheme",
|
||||
"recolor.randomize",
|
||||
"recolor.reduce",
|
||||
"recolor.weigh",
|
||||
"select.add",
|
||||
"select.all",
|
||||
"select.allOnArtboard",
|
||||
|
||||
@@ -7,7 +7,9 @@
|
||||
use std::collections::{BTreeSet, HashMap};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::recolor::{ColorKey, GlobalAdjust, Method, Preserve, Rng, RowMap, cluster, same_ink};
|
||||
use vectorcraft_color::recolor::{
|
||||
ColorKey, GlobalAdjust, Method, Preserve, Rng, RowMap, WeighUnit, cluster, row_shares, same_ink, weigh as weigh_rows,
|
||||
};
|
||||
use vectorcraft_color::{Color, Paint, Swatch};
|
||||
use vectorcraft_doc::swatches::{node_colors, node_paints, override_paints};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
|
||||
@@ -63,6 +65,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
pick_theme
|
||||
),
|
||||
cmd!(
|
||||
query "recolor.weigh",
|
||||
"Prominent Colors",
|
||||
[],
|
||||
None,
|
||||
"{map: rows [{from, to, …}] or {current: new} as recolor.apply, weights?: [numbers ≥ 0, one per row; an excluded row's is ignored, and at least one other must be above 0], ids?: as recolor.colors} → {map: the rows as given, each with its current colours (from) moved as below, shares: [one per row: its percent of the uses (recolor.colors' count) of the current colours of the rows that aren't excluded; 0 for an excluded row]} for Recolor Artwork's Prominent Colors (VectorCraft's own rule): without weights the rows stay as they are. With weights, current colours move one at a time between the rows that aren't excluded and have a new colour (to), while a move brings each row's share of the uses nearer its share of the weights, first the colour nearest in Lab to the first colour of the row it goes to compared with the row it leaves; a row's first colour stays in it, the tints of one global swatch in a row move together, a colour that another row with a new colour lists first stays where it is, the other rows with a new colour drop their entries for a colour that moves, and a use counts for the row recolor.apply recolors it with (rows with a new colour first, an exact colour before a hex one, the first row that lists it), else for the first other row that isn't excluded and lists it. The colours that can move are compared with the rows at most 50,000,000 times in all, and when they times the rows that aren't excluded pass that, none move. Changes nothing",
|
||||
has_doc,
|
||||
weigh
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -1062,6 +1073,181 @@ fn colors(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "colors": v }))
|
||||
}
|
||||
|
||||
/// `recolor.weigh`'s rows as given, each with `from` as a list (a `{current: new}` map gives a
|
||||
/// row per entry). The rows have already been read by [`parse_rows`].
|
||||
fn given_rows(p: &Value) -> Vec<Value> {
|
||||
match p.get("map") {
|
||||
Some(Value::Array(rows)) => rows
|
||||
.iter()
|
||||
.map(|r| {
|
||||
let mut r = r.clone();
|
||||
if let Some(f) = r.get("from").filter(|f| !f.is_array()).cloned() {
|
||||
r["from"] = json!([f]);
|
||||
}
|
||||
r
|
||||
})
|
||||
.collect(),
|
||||
Some(Value::Object(m)) => m.iter().map(|(k, v)| json!({"from": [k], "to": v})).collect(),
|
||||
_ => vec![],
|
||||
}
|
||||
}
|
||||
|
||||
fn weigh(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "recolor.weigh";
|
||||
let rows = parse_rows(p, C)?;
|
||||
let weights = match p.get("weights") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(Value::Array(a)) if a.len() == rows.len() => Some(
|
||||
a.iter()
|
||||
.map(|v| {
|
||||
v.as_f64()
|
||||
.filter(|x| x.is_finite() && *x >= 0.0)
|
||||
.ok_or_else(|| bad(C, format!("each weight must be a number of 0 or more (got {v})")))
|
||||
})
|
||||
.collect::<Result<Vec<f64>>>()?,
|
||||
),
|
||||
Some(v) => return Err(bad(C, format!("`weights` must be a list of {} numbers, one per row (got {v})", rows.len()))),
|
||||
};
|
||||
let active: Vec<usize> = (0..rows.len()).filter(|&i| !rows[i].exclude).collect();
|
||||
if let Some(w) = &weights
|
||||
&& !active.is_empty()
|
||||
&& !active.iter().any(|&i| w[i] > 0.0)
|
||||
{
|
||||
return Err(bad(C, "at least one row that isn't excluded needs a weight above 0"));
|
||||
}
|
||||
let (ids, only) = scope_ids(s, p, C)?;
|
||||
let st = s.doc()?;
|
||||
let mut used: Vec<Option<Used>> = used_colors(&st.doc, &ids, only.as_ref()).into_iter().map(Some).collect();
|
||||
let mut by_key: HashMap<ColorKey, usize> = HashMap::new();
|
||||
let mut by_hex: HashMap<String, Vec<usize>> = HashMap::new();
|
||||
for (i, u) in used.iter().enumerate().filter_map(|(i, u)| Some((i, u.as_ref()?))) {
|
||||
by_key.insert(ColorKey::of(&u.color), i);
|
||||
by_hex.entry(u.color.to_hex()).or_default().push(i);
|
||||
}
|
||||
// Each current colour's uses and global swatch. A use counts where recolor.apply recolors it:
|
||||
// rows with a new colour first, exact colours before hex colours, the first row that lists it;
|
||||
// then the other rows that aren't excluded, in the same way. `owner` holds the row and entry that took each colour,
|
||||
// and `shadows` the entries of rows with a new colour whose colours other entries took.
|
||||
let mut owner: Vec<Option<(usize, usize)>> = vec![None; used.len()];
|
||||
let mut shadows: Vec<(usize, usize, Vec<usize>)> = vec![];
|
||||
let mut found: Vec<Vec<(usize, Option<String>)>> = rows.iter().map(|r| vec![(0, None); r.from.len()]).collect();
|
||||
for recolors in [true, false] {
|
||||
for hex in [false, true] {
|
||||
for (r, row) in rows.iter().enumerate().filter(|(_, r)| !r.exclude && r.new_color().is_some() == recolors) {
|
||||
for (e, m) in row.from.iter().enumerate().filter(|(_, m)| matches!(m, Match::Hex(_)) == hex) {
|
||||
let hits: Vec<usize> = match m {
|
||||
Match::Key(k) => by_key.get(k).copied().into_iter().collect(),
|
||||
Match::Hex(h) => by_hex.get(h).cloned().unwrap_or_default(),
|
||||
};
|
||||
let (mut uses, mut link, mut took, mut taken) = (0, None, false, vec![]);
|
||||
for i in hits {
|
||||
match used[i].take() {
|
||||
Some(u) => {
|
||||
uses += u.count;
|
||||
link = link.or(u.swatch);
|
||||
took = true;
|
||||
owner[i] = Some((r, e));
|
||||
}
|
||||
None => taken.push(i),
|
||||
}
|
||||
}
|
||||
found[r][e] = (uses, link);
|
||||
if recolors && !took && !taken.is_empty() {
|
||||
shadows.push((r, e, taken));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// The units that move: in each row that isn't excluded, the colours linked to one global
|
||||
// swatch go together, each other colour on its own, and the unit of the first colour stays.
|
||||
let (mut units, mut members): (Vec<WeighUnit>, Vec<(usize, Vec<usize>)>) = (vec![], vec![]);
|
||||
let mut unit_of: HashMap<(usize, usize), usize> = HashMap::new();
|
||||
for (n, &r) in active.iter().enumerate() {
|
||||
let mut groups: Vec<(Option<&String>, Vec<usize>, usize)> = vec![];
|
||||
let mut by_link: HashMap<&String, usize> = HashMap::new();
|
||||
for (e, (uses, link)) in found[r].iter().enumerate() {
|
||||
let g = match link {
|
||||
Some(l) => *by_link.entry(l).or_insert_with(|| {
|
||||
groups.push((Some(l), vec![], 0));
|
||||
groups.len() - 1
|
||||
}),
|
||||
None => {
|
||||
groups.push((None, vec![], 0));
|
||||
groups.len() - 1
|
||||
}
|
||||
};
|
||||
groups[g].1.push(e);
|
||||
groups[g].2 += uses;
|
||||
}
|
||||
for (k, (_, entries, uses)) in groups.into_iter().enumerate() {
|
||||
for &e in &entries {
|
||||
unit_of.insert((r, e), units.len());
|
||||
}
|
||||
units.push(WeighUnit { color: rows[r].from[entries[0]].color(), uses: uses as f64, row: n, fixed: k == 0 });
|
||||
members.push((r, entries));
|
||||
}
|
||||
}
|
||||
// recolor.apply matches a colour to the first row with a new colour that lists it. A colour
|
||||
// that another such row's first colour also lists stays where it is; another row's other
|
||||
// entries for a colour that moves are dropped from that row below.
|
||||
let owners = |taken: &[usize]| -> Vec<usize> { taken.iter().filter_map(|&i| unit_of.get(&owner[i]?).copied()).collect() };
|
||||
for (_, _, taken) in shadows.iter().filter(|(_, e, _)| *e == 0) {
|
||||
for u in owners(taken) {
|
||||
units[u].fixed = true;
|
||||
}
|
||||
}
|
||||
if let Some(w) = &weights {
|
||||
// Only rows with a new colour recolor what they hold, so only they give and take colours.
|
||||
let movers: Vec<usize> = (0..active.len()).filter(|&n| rows[active[n]].new_color().is_some()).collect();
|
||||
let anchors: Vec<Color> =
|
||||
movers.iter().map(|&n| rows[active[n]].from.first().map(Match::color).or(rows[active[n]].to).unwrap_or_default()).collect();
|
||||
let mut mover_of = vec![None; active.len()];
|
||||
for (m, &n) in movers.iter().enumerate() {
|
||||
mover_of[n] = Some(m);
|
||||
}
|
||||
let at: Vec<Option<usize>> = units.iter().map(|u| mover_of[u.row]).collect();
|
||||
let sub: Vec<WeighUnit> = units.iter().zip(&at).filter_map(|(u, m)| Some(WeighUnit { row: (*m)?, ..*u })).collect();
|
||||
let to = weigh_rows(&sub, &anchors, &movers.iter().map(|&n| w[active[n]]).collect::<Vec<_>>());
|
||||
for ((u, _), m) in units.iter_mut().zip(&at).filter(|(_, m)| m.is_some()).zip(to) {
|
||||
u.row = movers[m];
|
||||
}
|
||||
}
|
||||
let mut out = given_rows(p);
|
||||
if weights.is_some() {
|
||||
// Each row's colours: those that stayed, in their order, then those that came to it.
|
||||
// A row's entry for a colour that moved to another row would take it back, so it goes.
|
||||
let moved = |u: usize| active[units[u].row] != members[u].0;
|
||||
let dropped: std::collections::HashSet<(usize, usize)> =
|
||||
shadows.iter().filter(|(_, e, taken)| *e != 0 && owners(taken).into_iter().any(moved)).map(|(r, e, _)| (*r, *e)).collect();
|
||||
let old: Vec<Vec<Value>> = out.iter().map(|r| r["from"].as_array().cloned().unwrap_or_default()).collect();
|
||||
let mut stayed: Vec<Vec<usize>> = active.iter().map(|_| vec![]).collect();
|
||||
let mut came: Vec<Vec<Value>> = active.iter().map(|_| vec![]).collect();
|
||||
for (u, (r, entries)) in units.iter().zip(&members) {
|
||||
let kept = entries.iter().copied().filter(|&e| !dropped.contains(&(*r, e)));
|
||||
if active[u.row] == *r {
|
||||
stayed[u.row].extend(kept);
|
||||
} else {
|
||||
came[u.row].extend(kept.filter_map(|e| old[*r].get(e).cloned()));
|
||||
}
|
||||
}
|
||||
for (n, &r) in active.iter().enumerate() {
|
||||
stayed[n].sort_unstable();
|
||||
let mut from: Vec<Value> = stayed[n].iter().filter_map(|&e| old[r].get(e).cloned()).collect();
|
||||
from.append(&mut came[n]);
|
||||
if let Some(row) = out.get_mut(r) {
|
||||
row["from"] = Value::Array(from);
|
||||
}
|
||||
}
|
||||
}
|
||||
let shares = row_shares(&units, active.len());
|
||||
let mut all = vec![0.0; rows.len()];
|
||||
for (n, &r) in active.iter().enumerate() {
|
||||
all[r] = shares[n];
|
||||
}
|
||||
Ok(json!({"map": out, "shares": all}))
|
||||
}
|
||||
|
||||
/// The `method` parameter (`default` without one, or for null). A `method` that is not a string,
|
||||
/// such as `5`, names no method.
|
||||
fn method_param(p: &Value, cmd: &str, default: Method) -> Result<Method> {
|
||||
|
||||
@@ -506,6 +506,13 @@ pub(crate) fn style_attrs(d: &Document, para: bool, name: &str) -> Option<Map<St
|
||||
if para { Kind::Para } else { Kind::Char }.attrs(d, name)
|
||||
}
|
||||
|
||||
/// `attrs` in the form `charStyle.new` (`para`: `paraStyle.new`) stores them in `d`, or `None`
|
||||
/// when they don't pass its checks.
|
||||
pub(crate) fn stored_style_attrs(d: &Document, para: bool, attrs: &Map<String, Value>) -> Option<Map<String, Value>> {
|
||||
let kind = if para { Kind::Para } else { Kind::Char };
|
||||
attrs_param(d, &json!({ "attrs": attrs }), kind, "new", None).ok().flatten()
|
||||
}
|
||||
|
||||
/// The name `charStyle.new` (`para`: `paraStyle.new`) gives a style when it is given none: the
|
||||
/// first "Character Style N" ("Paragraph Style N") that no character style (paragraph style) of the
|
||||
/// document has.
|
||||
|
||||
@@ -135,6 +135,7 @@ pub(crate) fn reflow(before: &Document, doc: &mut Document) {
|
||||
let mut story: Vec<TextRun> = vec![];
|
||||
let mut sources: Vec<TextObject> = vec![];
|
||||
let mut later_wins = vec![];
|
||||
let mut earlier_wins = vec![];
|
||||
let mut live = vec![];
|
||||
for id in &thread {
|
||||
match (text_of(doc, *id), text_of(before, *id)) {
|
||||
@@ -143,6 +144,9 @@ pub(crate) fn reflow(before: &Document, doc: &mut Document) {
|
||||
// A frame whose first paragraph was just restyled gives the paragraph it
|
||||
// shares with the frame before it that style.
|
||||
later_wins.push(old.is_some_and(|o| o.para_at(0) != t.para_at(0)));
|
||||
// A frame whose last paragraph was just restyled keeps that style in the
|
||||
// paragraph it shares with the frame after it, even when it is empty.
|
||||
earlier_wins.push(old.is_some_and(|o| o.para_at(o.paragraph_count() - 1) != t.para_at(t.paragraph_count() - 1)));
|
||||
sources.push(t.clone());
|
||||
live.push(*id);
|
||||
}
|
||||
@@ -151,6 +155,7 @@ pub(crate) fn reflow(before: &Document, doc: &mut Document) {
|
||||
(None, Some(old)) => {
|
||||
story.extend(old.runs.iter().cloned());
|
||||
later_wins.push(false);
|
||||
earlier_wins.push(false);
|
||||
sources.push(old.clone());
|
||||
}
|
||||
(None, None) => {}
|
||||
@@ -160,7 +165,7 @@ pub(crate) fn reflow(before: &Document, doc: &mut Document) {
|
||||
continue;
|
||||
}
|
||||
let source_refs: Vec<&TextObject> = sources.iter().collect();
|
||||
let paras = vectorcraft_text::thread::story_paras(&source_refs, &later_wins);
|
||||
let paras = vectorcraft_text::thread::story_paras_restyled(&source_refs, &later_wins, &earlier_wins);
|
||||
vectorcraft_text::edit::normalize(&mut story);
|
||||
if live.len() >= 2 {
|
||||
// Threaded frames keep their size: Auto Size is off for them (as in Illustrator).
|
||||
|
||||
@@ -60,6 +60,130 @@ fn a_restyled_empty_frame_keeps_its_style_before_an_unedited_empty_frame() {
|
||||
assert_eq!([hyphenates(a, 0), hyphenates(a, 1), hyphenates(b, 0), hyphenates(c, 0)], [false, true, true, true]);
|
||||
}
|
||||
|
||||
/// Every paragraph's left indent in frame `id`.
|
||||
fn left_indents(s: &Session, id: u64) -> Vec<f64> {
|
||||
match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind {
|
||||
NodeKind::Text(t) => t.paragraph_styles().iter().map(|p| p.left_indent).collect(),
|
||||
_ => panic!("not text"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Area type `height` high holding `text`, threaded into `empties` empty rectangles after it.
|
||||
fn tail_thread(text: &str, height: f64, empties: usize) -> (Session, Vec<u64>) {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 300})).unwrap();
|
||||
let a = new_id(s.execute("text.create", &json!({"x": 10, "y": 10, "text": text, "area": {"width": 150, "height": height}})).unwrap());
|
||||
let mut ids = vec![a];
|
||||
for k in 0..empties {
|
||||
let x = 200.0 * (k + 1) as f64;
|
||||
ids.push(new_id(s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 150, "height": 60})).unwrap()));
|
||||
}
|
||||
s.execute("select.set", &json!({"ids": ids})).unwrap();
|
||||
s.execute("text.thread.create", &json!({})).unwrap();
|
||||
(s, ids)
|
||||
}
|
||||
|
||||
/// Restyling a frame's empty last paragraph (after its final paragraph break) gives that
|
||||
/// paragraph the style in the next frame as well, instead of the next frame's old style.
|
||||
#[test]
|
||||
fn editing_a_frames_empty_last_paragraph_survives_thread_reflow() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 300})).unwrap();
|
||||
let a =
|
||||
s.execute("text.create", &json!({"x": 10, "y": 10, "text": "a\n", "area": {"width": 150, "height": 60}})).unwrap()["id"].as_u64().unwrap();
|
||||
let b = s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 150, "height": 60})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
|
||||
s.execute("text.thread.create", &json!({})).unwrap();
|
||||
assert_eq!([text(&s, a), text(&s, b)], ["a\n", ""]);
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
s.execute("text.setFormat", &json!({"ids": [a], "start": 2, "end": 2, "leftIndent": 30})).unwrap();
|
||||
assert_eq!((left_indents(&s, a), left_indents(&s, b)), (vec![0.0, 30.0], vec![30.0]));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1);
|
||||
// The same format again changes nothing and records no undo step.
|
||||
s.execute("text.setFormat", &json!({"ids": [a], "start": 2, "end": 2, "leftIndent": 30})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!((left_indents(&s, a), left_indents(&s, b)), (vec![0.0, 0.0], vec![0.0]));
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!((left_indents(&s, a), left_indents(&s, b)), (vec![0.0, 30.0], vec![30.0]));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
|
||||
// A format of the whole frame changes its last paragraph as well.
|
||||
s.execute("text.setFormat", &json!({"ids": [a], "leftIndent": 20})).unwrap();
|
||||
assert_eq!((left_indents(&s, a), left_indents(&s, b)), (vec![20.0, 20.0], vec![20.0]));
|
||||
// Both frames formatted in one command agree.
|
||||
s.execute("text.setFormat", &json!({"ids": [a, b], "leftIndent": 40})).unwrap();
|
||||
assert_eq!((left_indents(&s, a), left_indents(&s, b)), (vec![40.0, 40.0], vec![40.0]));
|
||||
}
|
||||
|
||||
/// The restyled empty last paragraph keeps its style when the next frame holds text that
|
||||
/// continues it, and across an unedited empty frame; a later restyle of a later frame still wins.
|
||||
#[test]
|
||||
fn a_restyled_empty_last_paragraph_keeps_its_style_against_later_frames() {
|
||||
// One line high: the text added to the next frame stays there.
|
||||
let (mut s, ids) = tail_thread("a\n", 20.0, 1);
|
||||
let (a, b) = (ids[0], ids[1]);
|
||||
s.execute("text.editRange", &json!({"id": b, "start": 0, "end": 0, "insert": "def"})).unwrap();
|
||||
assert_eq!([text(&s, a), text(&s, b)], ["a\n", "def"]);
|
||||
s.execute("text.setFormat", &json!({"ids": [a], "start": 2, "end": 2, "leftIndent": 30})).unwrap();
|
||||
assert_eq!([text(&s, a), text(&s, b)], ["a\n", "def"]);
|
||||
assert_eq!((left_indents(&s, a), left_indents(&s, b)), (vec![0.0, 30.0], vec![30.0]));
|
||||
|
||||
let (mut s, ids) = tail_thread("a\n", 60.0, 2);
|
||||
s.execute("text.setFormat", &json!({"ids": [ids[0]], "start": 2, "end": 2, "leftIndent": 30})).unwrap();
|
||||
assert_eq!(ids.iter().map(|id| left_indents(&s, *id)).collect::<Vec<_>>(), [vec![0.0, 30.0], vec![30.0], vec![30.0]]);
|
||||
s.execute("text.setFormat", &json!({"ids": [ids[2]], "leftIndent": 10})).unwrap();
|
||||
assert_eq!(ids.iter().map(|id| left_indents(&s, *id)).collect::<Vec<_>>(), [vec![0.0, 10.0], vec![10.0], vec![10.0]]);
|
||||
}
|
||||
|
||||
/// The restyled last paragraph keeps its style with type on a path on either side of the boundary.
|
||||
#[test]
|
||||
fn a_restyled_empty_last_paragraph_flows_onto_type_on_a_path() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 300})).unwrap();
|
||||
let a = new_id(s.execute("text.create", &json!({"x": 10, "y": 10, "text": "a\n", "area": {"width": 150, "height": 60}})).unwrap());
|
||||
let on_path = type_on_a_line(&mut s);
|
||||
s.execute("text.thread.add", &json!({"from": a, "to": on_path})).unwrap();
|
||||
assert_eq!([text(&s, a), text(&s, on_path)], ["a\n", ""]);
|
||||
s.execute("text.setFormat", &json!({"ids": [a], "start": 2, "end": 2, "leftIndent": 30})).unwrap();
|
||||
assert_eq!((left_indents(&s, a), left_indents(&s, on_path)), (vec![0.0, 30.0], vec![30.0]));
|
||||
|
||||
// Type on a path before area type.
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 300})).unwrap();
|
||||
let on_path = type_on_a_line(&mut s);
|
||||
s.execute("text.editRange", &json!({"id": on_path, "start": 0, "end": 0, "insert": "a\n"})).unwrap();
|
||||
let b = new_id(s.execute("shape.rectangle", &json!({"x": 400, "y": 10, "width": 150, "height": 60})).unwrap());
|
||||
s.execute("text.thread.add", &json!({"from": on_path, "to": b})).unwrap();
|
||||
assert_eq!([text(&s, on_path), text(&s, b)], ["a\n", ""]);
|
||||
s.execute("text.setFormat", &json!({"ids": [on_path], "start": 2, "end": 2, "leftIndent": 30})).unwrap();
|
||||
assert_eq!((left_indents(&s, on_path), left_indents(&s, b)), (vec![0.0, 30.0], vec![30.0]));
|
||||
}
|
||||
|
||||
/// A restyled empty last paragraph in a numbered list is counted once, and the next frame's
|
||||
/// first paragraph does not continue the paragraph before the break.
|
||||
#[test]
|
||||
fn a_restyled_empty_last_list_paragraph_keeps_the_counts() {
|
||||
let (mut s, ids) = tail_thread("One\nTwo\n", 60.0, 1);
|
||||
let (a, b) = (ids[0], ids[1]);
|
||||
s.execute("text.setFormat", &json!({"ids": [a, b], "list": "number"})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"ids": [a], "start": 8, "end": 8, "leftIndent": 30})).unwrap();
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let frame = |id| match &doc.node(NodeId(id)).unwrap().kind {
|
||||
NodeKind::Text(t) => (**t).clone(),
|
||||
_ => panic!("not text"),
|
||||
};
|
||||
let (ta, tb) = (frame(a), frame(b));
|
||||
let shown = [ta.plain_text(), tb.plain_text()].concat();
|
||||
assert_eq!(shown, "One\nTwo\n");
|
||||
let split = ta.paragraph_count() - 1;
|
||||
assert_eq!(ta.para_at(split).left_indent, 30.0, "{:?}", [ta.plain_text(), tb.plain_text()]);
|
||||
assert_eq!(tb.para_at(0).left_indent, 30.0);
|
||||
assert!(tb.para_at(0).list.is_some());
|
||||
assert_eq!(tb.list_count as usize, split, "the paragraphs before the shared one are counted once");
|
||||
assert_eq!(tb.first_para_continues, !ta.plain_text().ends_with('\n'));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thread_flows_reflows_on_edit_and_survives_delete() {
|
||||
let (mut s, a, b) = setup();
|
||||
|
||||
@@ -286,6 +286,9 @@ pub struct Session {
|
||||
/// While the active tool's actions run: their commands aren't "a command from outside the
|
||||
/// tool" ([`Session::after_command`]).
|
||||
pub(crate) in_tool_actions: bool,
|
||||
/// The warnings of the previews that settling an interaction applied, while a top-level command
|
||||
/// or the tool's actions collect them ([`Session::collect_settled_warnings`]).
|
||||
settled_warnings: Option<Vec<String>>,
|
||||
/// While [`Session::preview`] runs its command: its edits are the interaction's own.
|
||||
previewing: bool,
|
||||
/// The images Remove Background decoded during the interaction's preview steps, emptied when
|
||||
|
||||
@@ -321,7 +321,8 @@ impl Files {
|
||||
std::env::var("JSINCLUDE").map(|v| v.split(';').map(str::trim).filter(|p| !p.is_empty()).map(PathBuf::from).collect()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The file being run now, as `$.fileName` gives it (empty for a script given as text).
|
||||
/// The file being run now: the script, or the file `$.evalFile` is running (empty for a script
|
||||
/// given as text). `$.fileName` gives it to code that `eval` or `Function` compiled.
|
||||
pub(crate) fn file_name(&self) -> String {
|
||||
self.frames.last().map(|f| f.shown.to_string()).unwrap_or_default()
|
||||
}
|
||||
|
||||
@@ -822,6 +822,29 @@ impl Host {
|
||||
}
|
||||
}
|
||||
|
||||
/// `$.fileName` read by the code at `site`: the file that code is in, by the source map of the
|
||||
/// source it came from (this run's script, a file `$.evalFile` gave, or code an earlier run of
|
||||
/// the named engine compiled), so a function keeps the file it was defined in. Code from a file
|
||||
/// `#include` inserted is in that file. A script given as text has no name, and neither has
|
||||
/// code whose map the named engine no longer keeps. Code that `eval` or `Function` compiled has
|
||||
/// no map, and is given the file being run now.
|
||||
fn file_name_at(&self, site: vectorcraft_js::CallSite) -> String {
|
||||
let name = |m: &include::SourceMap| m.locate(site.line, site.column).1.to_string();
|
||||
let tag = site.source;
|
||||
if tag == vectorcraft_js::UNKNOWN_SOURCE {
|
||||
return self.files.borrow().file_name();
|
||||
}
|
||||
let script = self.script_tag.get();
|
||||
match tag.checked_sub(script).filter(|_| script != vectorcraft_js::UNKNOWN_SOURCE) {
|
||||
Some(0) => name(&self.script_map.borrow()),
|
||||
Some(n) => self.eval_maps.borrow().get(n as usize - 1).map(name).unwrap_or_default(),
|
||||
None => {
|
||||
let kept = self.kept_maps.as_ref().map(|k| k.borrow());
|
||||
kept.as_ref().and_then(|k| k.get(tag)).map(|k| name(&k.map)).unwrap_or_default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds a line to the run's console and, during a slice, to the session's.
|
||||
fn line(&self, entry: console::Entry, cut: bool) {
|
||||
let line = console::ConsoleLine { run: self.run, name: self.name.clone(), entry };
|
||||
@@ -1254,9 +1277,9 @@ fn each_line(text: &str, mut done: impl FnMut(String, bool)) {
|
||||
|
||||
/// The `$` object: `$.write(...values)` writes the values to the Script Console as `String(value)`
|
||||
/// gives them, one after another, and `$.writeln(...values)` does the same and ends the line.
|
||||
/// `$.evalFile(path[, timeout])` runs a file and gives its last value, `$.fileName` is the file
|
||||
/// being run and `$.includePath` the `#includepath` list. Its other members are
|
||||
/// [`dollar::members`].
|
||||
/// `$.evalFile(path[, timeout])` runs a file and gives its last value, `$.fileName` is the file the
|
||||
/// code reading it is in ([`Host::file_name_at`]) and `$.includePath` the `#includepath` list. Its
|
||||
/// other members are [`dollar::members`].
|
||||
fn dollar_object(link: &Link, info: dollar::RunInfo, localization: &Rc<vectorcraft_js::Localization>) -> Vec<(String, HostItem)> {
|
||||
let writer = |end: bool| {
|
||||
let l = link.clone();
|
||||
@@ -1278,6 +1301,15 @@ fn dollar_object(link: &Link, info: dollar::RunInfo, localization: &Rc<vectorcra
|
||||
Ok(Data::String(text))
|
||||
}))
|
||||
};
|
||||
let file_name = {
|
||||
let l = link.clone();
|
||||
HostItem::SiteGetter(Rc::new(move |site| {
|
||||
let h = current(&l)?;
|
||||
let text = h.file_name_at(site);
|
||||
h.charge_call(text.len() as u64 + 2)?;
|
||||
Ok(Data::String(text))
|
||||
}))
|
||||
};
|
||||
let eval_file = {
|
||||
let (l, end, strict) = (link.clone(), link.clone(), link.clone());
|
||||
HostItem::Evaluator {
|
||||
@@ -1294,7 +1326,7 @@ fn dollar_object(link: &Link, info: dollar::RunInfo, localization: &Rc<vectorcra
|
||||
("write".into(), writer(false)),
|
||||
("writeln".into(), writer(true)),
|
||||
("evalFile".into(), eval_file),
|
||||
("fileName".into(), getter(include::Files::file_name)),
|
||||
("fileName".into(), file_name),
|
||||
("includePath".into(), getter(include::Files::include_path)),
|
||||
];
|
||||
items.extend(dollar::members(link, info, localization));
|
||||
|
||||
@@ -116,6 +116,7 @@ impl Session {
|
||||
screens_hand_off: None,
|
||||
recovery: Default::default(),
|
||||
in_tool_actions: false,
|
||||
settled_warnings: None,
|
||||
previewing: false,
|
||||
decoded_images: Default::default(),
|
||||
envelope_defaults: None,
|
||||
|
||||
@@ -234,6 +234,27 @@ impl Session {
|
||||
self.active().and_then(|d| d.interaction.as_ref().filter(|it| std::sync::Arc::ptr_eq(&it.doc, &d.doc)).and_then(|it| it.preview.clone()))
|
||||
}
|
||||
|
||||
/// Keep `warning`, from a preview that settling an interaction applied, for whatever collects
|
||||
/// such warnings now ([`Session::collect_settled_warnings`]). Nothing keeps it when nothing
|
||||
/// collects, so it is never reported with a later, unrelated command.
|
||||
pub(crate) fn note_settled_warning(&mut self, warning: &str) {
|
||||
if let Some(kept) = &mut self.settled_warnings
|
||||
&& !kept.iter().any(|w| w == warning)
|
||||
{
|
||||
kept.push(warning.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
/// Run `f`, and → its result with the warnings of the previews that settling an interaction
|
||||
/// applied while it ran ([`Session::note_settled_warning`]). Warnings an outer `f` collects are
|
||||
/// kept for it.
|
||||
pub(crate) fn collect_settled_warnings<R>(&mut self, f: impl FnOnce(&mut Self) -> R) -> (R, Vec<String>) {
|
||||
let outer = self.settled_warnings.replace(Vec::new());
|
||||
let r = f(self);
|
||||
let settled = std::mem::replace(&mut self.settled_warnings, outer).unwrap_or_default();
|
||||
(r, settled)
|
||||
}
|
||||
|
||||
pub fn begin_interaction(&mut self, label: &str) -> Result<()> {
|
||||
if self.script_running() {
|
||||
return Err(EngineError::Busy);
|
||||
|
||||
@@ -3,6 +3,27 @@ use super::{
|
||||
strip_replay_only, waits_for_tool_edit,
|
||||
};
|
||||
|
||||
/// A command's result `r` with the warnings of the previews that settling an interaction applied
|
||||
/// before it ran: `previewWarning` holds them, and `warning` too when the command gives none of its
|
||||
/// own, so the status bar shows the command's own warning when there is one. A null result becomes
|
||||
/// an object holding them; any other result that isn't an object is returned as it is.
|
||||
fn with_settled_warnings(mut r: Value, settled: &[String]) -> Value {
|
||||
if settled.is_empty() {
|
||||
return r;
|
||||
}
|
||||
if r.is_null() {
|
||||
r = Value::Object(serde_json::Map::new());
|
||||
}
|
||||
if let Value::Object(m) = &mut r {
|
||||
let w = Value::String(settled.join("; "));
|
||||
if m.get("warning").is_none_or(Value::is_null) {
|
||||
m.insert("warning".into(), w.clone());
|
||||
}
|
||||
m.insert("previewWarning".into(), w);
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// `spec`'s `enabled` with `ids` selected instead of the selection, which is then put back.
|
||||
fn enabled_with_selection(&mut self, spec: &CommandSpec, ids: Vec<NodeId>) -> std::result::Result<(), String> {
|
||||
@@ -54,7 +75,14 @@ impl Session {
|
||||
self.finish_tool_edit_later()?;
|
||||
}
|
||||
let outer = std::mem::replace(&mut self.reading, !spec.journal || JOURNALED_READS.contains(&id));
|
||||
let r = self.execute_spec(spec, id, params);
|
||||
// A preview that a top-level command applied first (a drag with Real-time Drawing off, kept
|
||||
// before Undo) reports its warning in the command's result.
|
||||
let r = if self.depth == 0 {
|
||||
let (r, settled) = self.collect_settled_warnings(|s| s.execute_spec(spec, id, params));
|
||||
r.map(|v| with_settled_warnings(v, &settled))
|
||||
} else {
|
||||
self.execute_spec(spec, id, params)
|
||||
};
|
||||
self.reading = outer;
|
||||
r
|
||||
}
|
||||
@@ -364,3 +392,25 @@ impl Session {
|
||||
r
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::json;
|
||||
|
||||
use super::with_settled_warnings;
|
||||
|
||||
/// The command's own warning stays the one the status bar shows, and the settled preview's is
|
||||
/// kept beside it; a null result holds the preview's; other results are left as they are.
|
||||
#[test]
|
||||
fn settled_warnings_join_the_result() {
|
||||
let settled = ["a".to_string(), "b".to_string()];
|
||||
assert_eq!(
|
||||
with_settled_warnings(json!({"ran": 1, "warning": "own"}), &settled),
|
||||
json!({"ran": 1, "warning": "own", "previewWarning": "a; b"})
|
||||
);
|
||||
assert_eq!(with_settled_warnings(json!({"warning": null}), &settled), json!({"warning": "a; b", "previewWarning": "a; b"}));
|
||||
assert_eq!(with_settled_warnings(json!(null), &settled[..1]), json!({"warning": "a", "previewWarning": "a"}));
|
||||
assert_eq!(with_settled_warnings(json!([1]), &settled), json!([1]));
|
||||
assert_eq!(with_settled_warnings(json!({"ran": 1}), &[]), json!({"ran": 1}));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -421,6 +421,8 @@ impl Session {
|
||||
if safe_mode::active() {
|
||||
return;
|
||||
}
|
||||
// A `plugin.install` in another session writes the store before this reads it.
|
||||
let _held = crate::cmd::plugin::hold_plugin_changes();
|
||||
let grants = self.counted_grants(&dir);
|
||||
let limits = vectorcraft_plugins::Limits::default();
|
||||
let mut left = MAX_PLUGIN_STORE;
|
||||
|
||||
@@ -1367,6 +1367,28 @@ fn smooth_tool_reduces_jagged_path() {
|
||||
assert_eq!(p.subpaths[0].anchors[0].p, Point::new(100.0, 200.0));
|
||||
}
|
||||
|
||||
/// Smoothing a path with direct-selected anchors leaves the path selected whole: the selection no
|
||||
/// longer names anchors by indices into the anchors the smooth replaced. A selected path the drag
|
||||
/// does not reach keeps its anchors selected, and undo brings the old selection back.
|
||||
#[test]
|
||||
fn smoothing_a_path_drops_its_direct_selected_anchors() {
|
||||
let mut s = session();
|
||||
let anchors: Vec<_> = (0..=40).map(|i| json!({"x": 100.0 + i as f64 * 5.0, "y": 200.0 + if i % 2 == 0 { 0.0 } else { 1.5 }})).collect();
|
||||
let r = s.execute("path.create", &json!({"anchors": anchors})).unwrap();
|
||||
let id = NodeId(r["id"].as_u64().unwrap());
|
||||
let other = line(&mut s, 100.0, 500.0, 300.0, 500.0);
|
||||
s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 38]], "mode": "set"})).unwrap();
|
||||
s.execute("select.anchors", &json!({"id": other.0, "anchors": [[0, 1]], "mode": "add"})).unwrap();
|
||||
drag(&mut s, "smooth", &[(90.0, 200.0), (200.0, 200.0), (310.0, 200.0)], Mods::default());
|
||||
assert!(path(&s, id).anchor_count() < 20, "the path is smoothed");
|
||||
let sel = s.doc().unwrap().selection.clone();
|
||||
assert!(sel.contains(id) && sel.contains(other), "{sel:?}");
|
||||
assert!(!sel.anchors.contains_key(&id) && !sel.segments.contains_key(&id), "{sel:?}");
|
||||
assert_eq!(sel.anchors.get(&other), Some(&[(0, 1)].into()), "the path out of reach keeps its anchor");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().selection.anchors.get(&id), Some(&[(0, 38)].into()));
|
||||
}
|
||||
|
||||
/// #1512: a short drag over a small bump smooths the stretch of path under it. The long straight
|
||||
/// sides next to the bump stay straight lines from their far ends, which keep their place.
|
||||
#[test]
|
||||
@@ -1390,6 +1412,169 @@ fn a_short_smooth_drag_leaves_the_rest_of_long_segments_alone() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A selected path through `anchors` (x, y, and the in and out handles when given).
|
||||
fn smooth_test_path(s: &mut Session, anchors: &[serde_json::Value], closed: bool) -> NodeId {
|
||||
let r = s.execute("path.create", &json!({"anchors": anchors, "closed": closed})).unwrap();
|
||||
let id = NodeId(r["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
id
|
||||
}
|
||||
|
||||
/// `path.smoothRegion` along `drag` with the Smooth tool's reach (12 pt at 100%) and default Fidelity.
|
||||
fn smooth_pass(s: &mut Session, drag: &[Point]) {
|
||||
let pts: Vec<_> = drag.iter().map(|p| json!([p.x, p.y])).collect();
|
||||
s.execute("path.smoothRegion", &json!({"points": pts, "radius": 12, "fidelity": 2.5})).unwrap();
|
||||
}
|
||||
|
||||
/// Points 1/32 of a segment apart along every segment of `p`.
|
||||
fn smooth_test_samples(p: &PathData) -> Vec<Point> {
|
||||
use kurbo::ParamCurve;
|
||||
let mut v = vec![];
|
||||
for sp in &p.subpaths {
|
||||
for i in 0..sp.segment_count() {
|
||||
let c = sp.segment(i);
|
||||
v.extend((0..32).map(|k| c.eval(f64::from(k) / 32.0)));
|
||||
}
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// How much `p` turns along its length, in radians: a wobbly path turns much more than a smooth one.
|
||||
fn total_turning(p: &PathData) -> f64 {
|
||||
let pts = smooth_test_samples(p);
|
||||
pts.windows(3)
|
||||
.map(|w| (w[1] - w[0], w[2] - w[1]))
|
||||
.filter(|(u, v)| u.hypot() > 1e-9 && v.hypot() > 1e-9)
|
||||
.map(|(u, v)| u.cross(v).atan2(u.dot(v)).abs())
|
||||
.sum()
|
||||
}
|
||||
|
||||
/// Deterministic noise in -1..1.
|
||||
fn smooth_noise(seed: &mut u64) -> f64 {
|
||||
*seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
|
||||
(*seed >> 11) as f64 / (1u64 << 53) as f64 * 2.0 - 1.0
|
||||
}
|
||||
|
||||
/// A drag along y = `y` from x = `x0` to `x1`, one point every 5 pt.
|
||||
fn smooth_drag_along(y: f64, x0: f64, x1: f64) -> Vec<Point> {
|
||||
let n = ((x1 - x0) / 5.0).ceil() as usize;
|
||||
(0..=n).map(|i| Point::new(x0 + (x1 - x0) * i as f64 / n as f64, y)).collect()
|
||||
}
|
||||
|
||||
/// Each drag of the Smooth tool smooths the path under it, and a second drag over the same place
|
||||
/// smooths it further, as the help page describes
|
||||
/// (https://helpx.adobe.com/illustrator/using/tool-techniques/smooth-tool.html): a curve that wobbles
|
||||
/// 4 pt either side of its line every 12 pt, with an anchor at each crest, wobbles less after each drag.
|
||||
#[test]
|
||||
fn each_smooth_drag_smooths_a_wobble_larger_than_fidelity_further() {
|
||||
let mut s = session();
|
||||
let anchors: Vec<_> = (0..=20)
|
||||
.map(|k| {
|
||||
let (x, y) = (100.0 + 12.0 * f64::from(k), if k % 2 == 0 { 196.0 } else { 204.0 });
|
||||
json!({"x": x, "y": y, "in": [x - 4.4, y], "out": [x + 4.4, y]})
|
||||
})
|
||||
.collect();
|
||||
let id = smooth_test_path(&mut s, &anchors, false);
|
||||
let drag = smooth_drag_along(200.0, 90.0, 350.0);
|
||||
let wobble =
|
||||
|p: &PathData| smooth_test_samples(p).iter().filter(|q| (130.0..=310.0).contains(&q.x)).map(|q| (q.y - 200.0).abs()).fold(0.0, f64::max);
|
||||
let mut before = path(&s, id);
|
||||
for pass in 1..=2 {
|
||||
smooth_pass(&mut s, &drag);
|
||||
let after = path(&s, id);
|
||||
assert_ne!(after, before, "pass {pass} changes the path");
|
||||
let (t0, t1) = (total_turning(&before), total_turning(&after));
|
||||
assert!(t1 < 0.9 * t0, "pass {pass}: turning {t0} -> {t1}");
|
||||
let (w0, w1) = (wobble(&before), wobble(&after));
|
||||
assert!(w1 < 0.8 * w0, "pass {pass}: wobble {w0} -> {w1}");
|
||||
let (a, b) = (before.subpaths[0].anchors[0].p, after.subpaths[0].anchors[0].p);
|
||||
assert_eq!(a, b, "pass {pass}: the path keeps its start");
|
||||
before = after;
|
||||
}
|
||||
}
|
||||
|
||||
/// Smoothing a line with up to 1 pt of noise again and again, over all of it or over its middle,
|
||||
/// keeps it close to the line under the noise: each refit stays near the path it smooths.
|
||||
#[test]
|
||||
fn repeated_smooth_drags_stay_close_to_the_line_under_the_noise() {
|
||||
let off = |p: &PathData| {
|
||||
let d: Vec<f64> = smooth_test_samples(p).iter().map(|q| (q.y - 200.0).abs()).collect();
|
||||
(d.iter().sum::<f64>() / d.len() as f64, d.iter().copied().fold(0.0, f64::max))
|
||||
};
|
||||
for (x0, x1) in [(90.0, 410.0), (150.0, 350.0)] {
|
||||
let mut s = session();
|
||||
let mut seed = 7u64;
|
||||
let anchors: Vec<_> = (0..=60).map(|i| json!({"x": 100.0 + 5.0 * f64::from(i), "y": 200.0 + smooth_noise(&mut seed)})).collect();
|
||||
let id = smooth_test_path(&mut s, &anchors, false);
|
||||
let drag = smooth_drag_along(200.0, x0, x1);
|
||||
let (mean0, _) = off(&path(&s, id));
|
||||
for pass in 1..=5 {
|
||||
smooth_pass(&mut s, &drag);
|
||||
let (mean, max) = off(&path(&s, id));
|
||||
assert!(
|
||||
mean <= 1.1 * mean0 && max <= 1.5,
|
||||
"drag {x0}-{x1}, pass {pass}: {mean} on average and {max} at most from the line, {mean0} before"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A drag over the whole of a noisy closed path leaves no corner where the path starts.
|
||||
#[test]
|
||||
fn smoothing_a_whole_closed_path_leaves_no_kink_at_its_start() {
|
||||
let mut s = session();
|
||||
let mut seed = 5u64;
|
||||
let (c, r) = (Point::new(300.0, 300.0), 80.0);
|
||||
let anchors: Vec<_> = (0..64)
|
||||
.map(|i| {
|
||||
let a = f64::from(i) / 64.0 * std::f64::consts::TAU;
|
||||
let rr = r + 2.5 * smooth_noise(&mut seed);
|
||||
json!({"x": c.x + rr * a.cos(), "y": c.y + rr * a.sin()})
|
||||
})
|
||||
.collect();
|
||||
let id = smooth_test_path(&mut s, &anchors, true);
|
||||
let ring: Vec<Point> = (0..=128).map(|i| f64::from(i) / 128.0 * std::f64::consts::TAU).map(|a| c + r * kurbo::Vec2::from_angle(a)).collect();
|
||||
smooth_pass(&mut s, &ring);
|
||||
let p = path(&s, id);
|
||||
let sp = &p.subpaths[0];
|
||||
assert!(sp.closed && sp.anchors.len() < 64, "{} anchors", sp.anchors.len());
|
||||
let (last, first) = (sp.segment(sp.segment_count() - 1), sp.segment(0));
|
||||
let tin = if last.p3.distance(last.p2) > 1e-9 { last.p3 - last.p2 } else { last.p3 - last.p1 };
|
||||
let tout = if first.p1.distance(first.p0) > 1e-9 { first.p1 - first.p0 } else { first.p2 - first.p0 };
|
||||
let kink = tin.cross(tout).atan2(tin.dot(tout)).abs().to_degrees();
|
||||
assert!(kink <= 1.0, "a {kink}° corner at the start");
|
||||
}
|
||||
|
||||
/// A drag over the whole of a closed path smooths a bump at its first anchor as much as the same
|
||||
/// bump on the far side of it.
|
||||
#[test]
|
||||
fn smoothing_a_whole_closed_path_smooths_a_bump_at_its_start() {
|
||||
let mut s = session();
|
||||
let (c, r) = (Point::new(300.0, 300.0), 80.0);
|
||||
let anchors: Vec<_> = (0..64)
|
||||
.map(|i| {
|
||||
let a = f64::from(i) / 64.0 * std::f64::consts::TAU;
|
||||
let rr = if i % 32 == 0 { r + 6.0 } else { r };
|
||||
json!({"x": c.x + rr * a.cos(), "y": c.y + rr * a.sin()})
|
||||
})
|
||||
.collect();
|
||||
let id = smooth_test_path(&mut s, &anchors, true);
|
||||
let ring: Vec<Point> = (0..=128).map(|i| f64::from(i) / 128.0 * std::f64::consts::TAU).map(|a| c + r * kurbo::Vec2::from_angle(a)).collect();
|
||||
// A Fidelity of 0.5 pt, so the refit follows the smoothed path closely on both sides.
|
||||
let pts: Vec<_> = ring.iter().map(|p| json!([p.x, p.y])).collect();
|
||||
s.execute("path.smoothRegion", &json!({"points": pts, "radius": 12, "fidelity": 0.5})).unwrap();
|
||||
let p = path(&s, id);
|
||||
use std::f64::consts::{PI, TAU};
|
||||
// How far the path rises above the circle within 0.3 radians of the angle `near`.
|
||||
let bump = |near: f64| {
|
||||
let off = |q: &Point| (((q.y - c.y).atan2(q.x - c.x) - near + PI).rem_euclid(TAU) - PI).abs();
|
||||
smooth_test_samples(&p).iter().filter(|q| off(q) < 0.3).map(|q| q.distance(c) - r).fold(0.0, f64::max)
|
||||
};
|
||||
let (start, far) = (bump(0.0), bump(PI));
|
||||
assert!(far < 5.0, "the far bump stays {far} pt high");
|
||||
assert!(start <= far + 0.5, "the bump at the start stays {start} pt high, the far one {far} pt");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn join_tool_joins_two_lines() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -535,9 +535,9 @@ fn expanded_art_keeps_the_random_transforms_the_canvas_drew() {
|
||||
}
|
||||
|
||||
/// The reply lists each object whose appearance expanded once, by the id it has in the document,
|
||||
/// starting with the selected object. In "group copies" the two copies of the square share an id
|
||||
/// until Expand Appearance gives them ids of their own, and the reply names the group, then each
|
||||
/// copy by its new id.
|
||||
/// starting with the selected object. In "group copies" the group's art holds the square with its
|
||||
/// stroke's effect applied, so the reply names the group alone; the two copies of the square share
|
||||
/// ids until Expand Appearance gives every object in them an id of its own.
|
||||
#[test]
|
||||
fn the_reply_names_each_expanded_copy_by_its_own_id() {
|
||||
for case in RANDOM_CASES {
|
||||
@@ -551,8 +551,17 @@ fn the_reply_names_each_expanded_copy_by_its_own_id() {
|
||||
assert!(ids.iter().all(|&i| s.doc().unwrap().doc.node(NodeId(i)).is_some()), "{case}: {ids:?}");
|
||||
if case == "group copies" {
|
||||
let art = node(&s, id);
|
||||
let copies: Vec<u64> = art.children().unwrap()[0].children().unwrap().iter().map(|c| c.id.0).collect();
|
||||
assert_eq!(ids, [vec![id.0], copies].concat(), "{case}");
|
||||
assert_eq!(ids, [id.0], "{case}");
|
||||
let copies = art.children().unwrap();
|
||||
assert_eq!(copies.len(), 2, "{case}");
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let mut repeated = vec![];
|
||||
art.walk(&mut |n| {
|
||||
if !seen.insert(n.id) {
|
||||
repeated.push(n.id);
|
||||
}
|
||||
});
|
||||
assert!(repeated.is_empty(), "{case}: {repeated:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -635,6 +635,210 @@ fn a_library_style_named_with_spaces_comes_in_trimmed() {
|
||||
assert_eq!((text.runs[0].style.size, text.runs[0].style.style_name.as_deref()), (31.0, Some("Body")));
|
||||
}
|
||||
|
||||
/// The size of the first run of text object `id`.
|
||||
fn run_size(s: &Session, id: &Value) -> f64 {
|
||||
match &s.doc().unwrap().doc.node(NodeId(id.as_u64().unwrap())).unwrap().kind {
|
||||
vectorcraft_doc::NodeKind::Text(t) => t.runs[0].style.size,
|
||||
_ => 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Add to Character Styles puts a library character style into the document's character styles
|
||||
/// without applying it, with or without type selected, in one undo step; the same style there is
|
||||
/// reused without a step, and a name taken by other attributes gets a number. A bad call changes
|
||||
/// nothing.
|
||||
#[test]
|
||||
fn a_library_character_style_is_added_to_the_document_without_applying_it() {
|
||||
let mut s = session();
|
||||
let data = json!({"name": "Kept", "charStyles": [{"name": "Headline", "attrs": {"size": 31.0}}, {"name": "Broken", "attrs": {"size": "big"}}]});
|
||||
let lib = run(&mut s, "library.import", json!({"data": data.to_string()}))["id"].as_str().unwrap().to_string();
|
||||
let styles = |s: &Session| s.doc().unwrap().doc.char_styles.iter().map(|c| c.name.clone()).collect::<Vec<_>>();
|
||||
let undo = |s: &Session| s.doc().unwrap().history.undo.len();
|
||||
// Nothing selected.
|
||||
let before = undo(&s);
|
||||
let r = run(&mut s, "library.addToCharacterStyles", json!({"library": lib, "item": "Headline"}));
|
||||
assert_eq!((r["style"].as_str(), r["existing"].as_bool()), (Some("Headline"), Some(false)));
|
||||
assert_eq!(styles(&s), ["Headline"]);
|
||||
assert_eq!(undo(&s), before + 1, "one undo step");
|
||||
let attrs = &s.doc().unwrap().doc.char_styles[0].attrs;
|
||||
assert_eq!(attrs.get("size"), Some(&json!(31.0)));
|
||||
// Selected type keeps its look.
|
||||
let t = run(&mut s, "text.create", json!({"x": 10, "y": 50, "text": "Body", "size": 9}))["id"].clone();
|
||||
run(&mut s, "select.set", json!({"ids": [t]}));
|
||||
let before = undo(&s);
|
||||
let r = run(&mut s, "library.addToCharacterStyles", json!({"library": lib, "item": "Headline"}));
|
||||
assert_eq!((r["style"].as_str(), r["existing"].as_bool()), (Some("Headline"), Some(true)));
|
||||
assert_eq!((undo(&s), run_size(&s, &t), styles(&s).len()), (before, 9.0, 1), "reused: no step, the type unchanged");
|
||||
// Another style of that name: numbered, still not applied.
|
||||
run(&mut s, "charStyle.setAttrs", json!({"name": "Headline", "attrs": {"size": 5}}));
|
||||
let r = run(&mut s, "library.addToCharacterStyles", json!({"library": lib, "item": "Headline"}));
|
||||
assert_eq!((r["style"].as_str(), r["existing"].as_bool()), (Some("Headline 2"), Some(false)));
|
||||
assert_eq!(run_size(&s, &t), 9.0);
|
||||
let vectorcraft_doc::NodeKind::Text(text) = &s.doc().unwrap().doc.node(NodeId(t.as_u64().unwrap())).unwrap().kind else { panic!("not text") };
|
||||
assert_eq!(text.runs[0].style.style_name, None, "no style applied");
|
||||
// Undo takes the added style back alone.
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(styles(&s), ["Headline"]);
|
||||
// Bad calls: nothing changes.
|
||||
let before = (undo(&s), styles(&s));
|
||||
for bad in [
|
||||
json!({"library": lib}),
|
||||
json!({"library": lib, "item": 3}),
|
||||
json!({"library": lib, "item": "Nope"}),
|
||||
json!({"library": "Nope", "item": "Headline"}),
|
||||
json!({"library": lib, "item": "Broken"}),
|
||||
json!({"recorded": {"name": "X", "attrs": "damaged"}}),
|
||||
] {
|
||||
assert!(s.execute("library.addToCharacterStyles", &bad).is_err(), "{bad}");
|
||||
assert_eq!((undo(&s), styles(&s)), before, "{bad}");
|
||||
}
|
||||
// Without a document it isn't available.
|
||||
run(&mut s, "file.close", json!({}));
|
||||
assert!(s.active().is_none());
|
||||
assert!(s.execute("library.addToCharacterStyles", &json!({"library": lib, "item": "Headline"})).is_err());
|
||||
}
|
||||
|
||||
/// A library character style whose fill links to a swatch the document lacks is added and applied
|
||||
/// with the color it shows, unlinked at full tint; a global swatch of that name in the document
|
||||
/// keeps the link and gives its color.
|
||||
#[test]
|
||||
fn a_library_character_style_linked_to_a_missing_swatch_is_added_unlinked() {
|
||||
let base = vectorcraft_color::Color::rgb(0.2, 0.4, 0.6);
|
||||
let shown = base.tinted(0.5);
|
||||
let linked = vectorcraft_color::Paint::Solid { color: shown, swatch: Some("Brand".into()), tint: 0.5 };
|
||||
let data = json!({"name": "Kept", "charStyles": [{"name": "Accent", "attrs": {"size": 20.0, "fill": linked}}]});
|
||||
let mut s = session();
|
||||
let lib = run(&mut s, "library.import", json!({"data": data.to_string()}))["id"].as_str().unwrap().to_string();
|
||||
let fill = |s: &Session, name: &str| {
|
||||
let st = s.doc().unwrap().doc.char_styles.iter().find(|c| c.name == name).map(|c| c.attrs.clone()).unwrap();
|
||||
serde_json::from_value::<vectorcraft_color::Paint>(st["fill"].clone()).unwrap()
|
||||
};
|
||||
run(&mut s, "library.addToCharacterStyles", json!({"library": lib, "item": "Accent"}));
|
||||
assert_eq!(fill(&s, "Accent"), vectorcraft_color::Paint::Solid { color: shown, swatch: None, tint: 1.0 });
|
||||
// Apply as well, on selected type.
|
||||
let t = run(&mut s, "text.create", json!({"x": 10, "y": 50, "text": "Body", "size": 9}))["id"].clone();
|
||||
run(&mut s, "select.set", json!({"ids": [t]}));
|
||||
let r = run(&mut s, "library.use", json!({"library": lib, "kind": "charStyle", "item": "Accent"}));
|
||||
assert_eq!(r["style"], "Accent", "the added style is reused");
|
||||
assert_eq!(run_size(&s, &t), 20.0);
|
||||
// A document with a global swatch of that name keeps the link.
|
||||
run(&mut s, "file.new", json!({"width": 200, "height": 200}));
|
||||
let other = vectorcraft_color::Color::rgb(0.8, 0.1, 0.1);
|
||||
run(&mut s, "swatch.new", json!({"name": "Brand", "color": other, "global": true}));
|
||||
run(&mut s, "library.addToCharacterStyles", json!({"library": lib, "item": "Accent"}));
|
||||
let vectorcraft_color::Paint::Solid { swatch, tint, .. } = fill(&s, "Accent") else { panic!("not a solid fill") };
|
||||
assert_eq!((swatch.as_deref(), tint), (Some("Brand"), 0.5));
|
||||
// The style with the document's swatch color is the same style: added again, it is reused.
|
||||
let r = run(&mut s, "library.addToCharacterStyles", json!({"library": lib, "item": "Accent"}));
|
||||
assert_eq!((r["style"].as_str(), r["existing"].as_bool()), (Some("Accent"), Some(true)));
|
||||
}
|
||||
|
||||
/// A library style is compared with the document's in the form the document stores it in, so a
|
||||
/// style whose file writes a size as a whole number is reused, by Add to Character Styles and by a
|
||||
/// click alike.
|
||||
#[test]
|
||||
fn a_library_style_is_reused_whatever_form_its_file_writes_it_in() {
|
||||
let data = json!({"name": "Kept", "charStyles": [{"name": "Whole", "attrs": {"size": 31}}], "paraStyles": [{"name": "Para", "attrs": {"left_indent": 4}}]});
|
||||
let mut s = session();
|
||||
let lib = run(&mut s, "library.import", json!({"data": data.to_string()}))["id"].as_str().unwrap().to_string();
|
||||
run(&mut s, "library.addToCharacterStyles", json!({"library": lib, "item": "Whole"}));
|
||||
let r = run(&mut s, "library.addToCharacterStyles", json!({"library": lib, "item": "Whole"}));
|
||||
assert_eq!((r["style"].as_str(), r["existing"].as_bool()), (Some("Whole"), Some(true)));
|
||||
let t = run(&mut s, "text.create", json!({"x": 10, "y": 50, "text": "Body", "size": 9}))["id"].clone();
|
||||
run(&mut s, "select.set", json!({"ids": [t]}));
|
||||
for (kind, item) in [("charStyle", "Whole"), ("paraStyle", "Para"), ("paraStyle", "Para")] {
|
||||
assert_eq!(run(&mut s, "library.use", json!({"library": lib, "kind": kind, "item": item}))["style"], item);
|
||||
}
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!((d.char_styles.len(), d.para_styles.iter().filter(|p| p.name.starts_with("Para")).count()), (1, 1));
|
||||
}
|
||||
|
||||
/// Rename gives a library item a new name, trimmed, in its place and its group; a character style
|
||||
/// keeps its attributes, a graphic its id. Another item of its kind with that name, an empty or
|
||||
/// too long name, a name that isn't text and an unknown item or library are errors that change
|
||||
/// nothing; a name with path characters is a name like any other; the item's own name writes
|
||||
/// nothing; and the document's history is not touched.
|
||||
#[test]
|
||||
fn library_items_are_renamed_in_place() {
|
||||
let (mut s, g, c, st) = brand();
|
||||
let t = run(&mut s, "text.create", json!({"x": 10, "y": 120, "text": "Body", "size": 9}))["id"].clone();
|
||||
run(&mut s, "select.set", json!({"ids": [t]}));
|
||||
let other = run(&mut s, "library.add", json!({"kind": "charStyle", "name": "Body"}))["name"].as_str().unwrap().to_string();
|
||||
run(&mut s, "library.createGroup", json!({"name": "Brand", "items": [{"kind": "charStyle", "item": st}, {"kind": "fillColor", "item": c}]}));
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let attrs = run(&mut s, "library.get", json!({}))["charStyles"][0]["attrs"].clone();
|
||||
let r = run(&mut s, "library.renameItem", json!({"kind": "charStyle", "item": st, "name": " Title "}));
|
||||
assert_eq!((r["item"].as_str(), r["name"].as_str()), (Some("Title"), Some("Title")));
|
||||
let got = run(&mut s, "library.get", json!({}));
|
||||
assert_eq!(got["charStyles"][0], json!({"name": "Title", "attrs": attrs}), "first still, the attributes kept");
|
||||
assert_eq!(got["charStyles"][1]["name"], other.as_str());
|
||||
assert_eq!(groups(&mut s), [("Brand".into(), refs(&[("charStyle", "Title"), ("color", &c)]))]);
|
||||
// A colour keeps its group under its new name; a graphic keeps its id.
|
||||
run(&mut s, "library.renameItem", json!({"kind": "strokeColor", "item": c, "name": "Navy"}));
|
||||
assert_eq!(groups(&mut s), [("Brand".into(), refs(&[("charStyle", "Title"), ("color", "Navy")]))]);
|
||||
let r = run(&mut s, "library.renameItem", json!({"kind": "graphic", "item": "Logo", "name": "Mark"}));
|
||||
assert_eq!(r["item"], g.as_str());
|
||||
let graphic = run(&mut s, "library.get", json!({}))["graphics"][0].clone();
|
||||
assert_eq!((graphic["id"].as_str(), graphic["name"].as_str()), (Some(g.as_str()), Some("Mark")));
|
||||
// Path characters are kept.
|
||||
run(&mut s, "library.renameItem", json!({"kind": "charStyle", "item": "Title", "name": "a/b\\c:d"}));
|
||||
assert_eq!(style_order_of(&mut s)[0], "a/b\\c:d");
|
||||
// Errors change nothing.
|
||||
let before = run(&mut s, "library.get", json!({}));
|
||||
let long = "x".repeat(257);
|
||||
for bad in [
|
||||
json!({"kind": "charStyle", "item": "a/b\\c:d", "name": other}),
|
||||
json!({"kind": "charStyle", "item": "a/b\\c:d", "name": " "}),
|
||||
json!({"kind": "charStyle", "item": "a/b\\c:d", "name": long}),
|
||||
json!({"kind": "charStyle", "item": "a/b\\c:d", "name": 5}),
|
||||
json!({"kind": "charStyle", "item": "a/b\\c:d"}),
|
||||
json!({"kind": "charStyle", "item": "Nope", "name": "X"}),
|
||||
json!({"kind": "paraStyle", "item": "a/b\\c:d", "name": "X"}),
|
||||
json!({"kind": "brush", "item": "a/b\\c:d", "name": "X"}),
|
||||
json!({"library": "Nope", "kind": "charStyle", "item": "a/b\\c:d", "name": "X"}),
|
||||
] {
|
||||
assert!(s.execute("library.renameItem", &bad).is_err(), "{bad}");
|
||||
assert_eq!(run(&mut s, "library.get", json!({})), before, "{bad}");
|
||||
}
|
||||
// A style of another kind may have the name, and 256 characters are allowed.
|
||||
run(&mut s, "library.renameItem", json!({"kind": "charStyle", "item": "a/b\\c:d", "name": "Navy"}));
|
||||
run(&mut s, "library.renameItem", json!({"kind": "charStyle", "item": "Navy", "name": "y".repeat(256)}));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no document undo step");
|
||||
}
|
||||
|
||||
/// The current library's character style names, in order.
|
||||
fn style_order_of(s: &mut Session) -> Vec<String> {
|
||||
order(s, "charStyles", "name")
|
||||
}
|
||||
|
||||
/// A rename is kept in the library's file; renaming an item to its own name writes nothing; and a
|
||||
/// rename whose file can't be written is taken back.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_library_item_rename_is_saved_or_taken_back() {
|
||||
let dir = vectorcraft_testkit::temp_dir("library-rename-item");
|
||||
let folder = dir.to_string_lossy().to_string();
|
||||
let mut s = session();
|
||||
s.libraries.set_dir(Some(folder.clone()));
|
||||
let lib = run(&mut s, "library.create", json!({"name": "Kept"}))["id"].as_str().unwrap().to_string();
|
||||
let t = run(&mut s, "text.create", json!({"x": 10, "y": 50, "text": "Body", "size": 12}))["id"].clone();
|
||||
run(&mut s, "select.set", json!({"ids": [t]}));
|
||||
run(&mut s, "library.add", json!({"kind": "charStyle", "name": "Body"}));
|
||||
run(&mut s, "library.renameItem", json!({"kind": "charStyle", "item": "Body", "name": "Text"}));
|
||||
let mut t2 = session();
|
||||
t2.libraries.set_dir(Some(folder.clone()));
|
||||
assert_eq!(style_order_of(&mut t2), ["Text"], "kept in the file");
|
||||
// The file can't be written (a folder stands where it goes): its own name still succeeds, as
|
||||
// it writes nothing; a new name fails and is taken back.
|
||||
let file = dir.join(format!("{lib}.vclibrary"));
|
||||
std::fs::remove_file(&file).unwrap();
|
||||
std::fs::create_dir(&file).unwrap();
|
||||
run(&mut s, "library.renameItem", json!({"kind": "charStyle", "item": "Text", "name": " Text "}));
|
||||
assert!(s.execute("library.renameItem", &json!({"kind": "charStyle", "item": "Text", "name": "Copy"})).is_err());
|
||||
assert_eq!(style_order_of(&mut s), ["Text"], "taken back");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn libraries_are_kept_in_files_across_sessions() {
|
||||
|
||||
@@ -643,6 +643,32 @@ fn envelope_top_object_shares_a_side_by_control_polygon_length() {
|
||||
assert!(near(Point::new(500.0, 200.0)) < 0.5, "the middle of the bottom: {pts:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn envelope_top_object_keeps_its_look_when_anchors_are_added() {
|
||||
// Add Anchor Points splits each segment of the top object in two without changing its shape.
|
||||
// The top curve's parameter runs fast at its start, so its halves have control polygons of
|
||||
// different lengths; the envelope still bends the two rectangles as the unsplit curve does.
|
||||
let made = |add_anchors: bool| {
|
||||
let mut s = session();
|
||||
let left = rect(&mut s, 100.0, 100.0, 100.0, 100.0);
|
||||
let right = rect(&mut s, 200.0, 100.0, 100.0, 100.0);
|
||||
let d = "M400 100 C520 40 590 70 600 100 L600 200 L400 200 Z";
|
||||
let t = id_of(&s.execute("path.create", &json!({ "d": d })).unwrap());
|
||||
if add_anchors {
|
||||
sel(&mut s, &[t]);
|
||||
s.execute("object.path.addAnchorPoints", &json!({})).unwrap();
|
||||
assert_eq!(node(&s, t).path_data().map(|p| p.anchor_count()), Some(8));
|
||||
}
|
||||
sel(&mut s, &[left, right, t]);
|
||||
let e = id_of(&s.execute("object.envelope.makeWithTopObject", &json!({})).unwrap());
|
||||
all_anchors(&live::expand_live(&node(&s, e)))
|
||||
};
|
||||
let (plain, split) = (made(false), made(true));
|
||||
assert_eq!(plain.len(), split.len());
|
||||
let off = plain.iter().zip(&split).map(|(p, q)| p.distance(*q)).fold(0.0, f64::max);
|
||||
assert!(off < 1e-6, "the art moves by up to {off} pt");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn envelope_release_and_expand() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -257,6 +257,25 @@ fn shadows_under_a_groups_or_an_objects_transform_expand_appearance_as_the_canva
|
||||
}
|
||||
}
|
||||
|
||||
/// A group's Transform effect runs after its member's own Offset Path in Expand Appearance as on
|
||||
/// the canvas: the 100 pt square offset to 120 pt and scaled by half expands 60 pt wide.
|
||||
#[test]
|
||||
fn a_groups_effects_after_its_members_own_expand_as_the_canvas_draws_them() {
|
||||
let mut s = session();
|
||||
run(&mut s, "shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 100}));
|
||||
run(&mut s, "effect.apply", json!({"effect": "path.offsetPath", "params": {"offset": 10}}));
|
||||
run(&mut s, "object.group", json!({}));
|
||||
run(&mut s, "effect.apply", json!({"effect": "distort.transform", "params": {"scaleH": 50, "scaleV": 50}}));
|
||||
let before = render(&s);
|
||||
run(&mut s, "effect.expandAppearance", json!({}));
|
||||
let after = render(&s);
|
||||
let diff = differing(&before, &after, 64);
|
||||
assert_eq!(diff, 0, "{diff} pixels differ");
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let w = doc.node(doc.layers[0].id).and_then(|l| l.geometric_bounds()).unwrap().width();
|
||||
assert!((w - 60.0).abs() < 1e-6, "{w}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_placed_gradient_moved_by_a_warp_expands_as_the_canvas_draws_it() {
|
||||
// The object's own effect, and the fill's (the first appearance item).
|
||||
|
||||
@@ -2820,6 +2820,188 @@ fn a_failed_store_write_keeps_the_stored_module_with_its_grant() {
|
||||
vectorcraft_plugins::registry::revoke(id);
|
||||
}
|
||||
|
||||
/// An install refused because another session revoked the grant its checks relied on writes
|
||||
/// nothing: a store that kept the grant and lost the module gets no module back, its grants stay as
|
||||
/// they were, and the plug-in installed with the id and the other session's revoke stand. `grant`
|
||||
/// approves the module by itself.
|
||||
#[test]
|
||||
fn a_grant_revoked_while_installing_leaves_the_store_as_it_was() {
|
||||
use vectorcraft_plugins::permissions::sha256_hex;
|
||||
use vectorcraft_plugins::registry;
|
||||
let folder = crate::tests_links::Folder::new("plugin-store-revoked-while-installing");
|
||||
let id = "test.engine.permissions.revokedwhileinstalling";
|
||||
let bytes = asking(id, r#"["doc.read"]"#, &json!({"objects": []}));
|
||||
let data = vectorcraft_format::base64_encode(&bytes);
|
||||
let mut s = session();
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]}));
|
||||
let grants = folder.0.join("grants.json");
|
||||
let recorded = std::fs::read(&grants).unwrap();
|
||||
let module = std::path::PathBuf::from(s.stored_plugin_file(id).unwrap());
|
||||
std::fs::remove_file(&module).unwrap();
|
||||
|
||||
crate::cmd::plugin::BEFORE_INSTALL.set(Some(Box::new(move || {
|
||||
registry::revoke(id);
|
||||
})));
|
||||
let e = s.execute("plugin.install", &json!({"dataBase64": data})).unwrap_err().to_string();
|
||||
assert!(e.contains("asks for the permissions doc.read"), "{e}");
|
||||
assert!(!module.exists(), "no module is stored");
|
||||
assert_eq!(std::fs::read(&grants).unwrap(), recorded, "the grants stay as they were");
|
||||
assert!(registry::granted(id).is_none(), "the other session's revoke stands");
|
||||
assert_eq!(registry::get(id).map(|p| p.hash().to_string()), Some(sha256_hex(&bytes)), "the installed plug-in stays");
|
||||
|
||||
crate::cmd::plugin::BEFORE_INSTALL.set(Some(Box::new(move || {
|
||||
registry::revoke(id);
|
||||
})));
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]}));
|
||||
assert_eq!(std::fs::read(&module).unwrap(), bytes, "a module `grant` approves is stored");
|
||||
assert!(registry::granted(id).is_some_and(|g| g.hash == sha256_hex(&bytes)));
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
}
|
||||
|
||||
/// A plug-in another session installs with the id while a module is checked takes the place the
|
||||
/// checks found free. Without `replace`, or with `replace: false`, the install is refused, writes no
|
||||
/// module and leaves that plug-in installed; with `replace: true` the module takes its place.
|
||||
#[test]
|
||||
fn a_plug_in_installed_while_installing_needs_replace() {
|
||||
use vectorcraft_plugins::permissions::sha256_hex;
|
||||
use vectorcraft_plugins::registry;
|
||||
let folder = crate::tests_links::Folder::new("plugin-store-installed-while-installing");
|
||||
let id = "test.engine.installedwhileinstalling";
|
||||
let ours = asking(id, "[]", &json!({"objects": []}));
|
||||
let theirs = asking(id, "[]", &json!({"objects": [], "documentData": null}));
|
||||
let data = vectorcraft_format::base64_encode(&ours);
|
||||
let mut s = session();
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
let module = std::path::PathBuf::from(s.stored_plugin_file(id).unwrap());
|
||||
let installed = || registry::get(id).map(|p| p.hash().to_string());
|
||||
let meanwhile = |theirs: Vec<u8>| -> Option<Box<dyn FnOnce()>> {
|
||||
Some(Box::new(move || {
|
||||
registry::install_bytes(&theirs).unwrap();
|
||||
}))
|
||||
};
|
||||
|
||||
for (replace, why) in [(Value::Null, "is another module than"), (json!(false), "is already installed")] {
|
||||
crate::cmd::plugin::BEFORE_INSTALL.set(meanwhile(theirs.clone()));
|
||||
let e = s.execute("plugin.install", &json!({"dataBase64": data, "replace": replace})).unwrap_err().to_string();
|
||||
assert!(e.contains(why), "{replace}: {e}");
|
||||
assert!(!module.exists(), "{replace}: no module is stored");
|
||||
assert_eq!(installed(), Some(sha256_hex(&theirs)), "{replace}: the other plug-in stays installed");
|
||||
registry::remove(id);
|
||||
}
|
||||
|
||||
crate::cmd::plugin::BEFORE_INSTALL.set(meanwhile(theirs));
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": data, "replace": true}));
|
||||
assert_eq!(std::fs::read(&module).unwrap(), ours);
|
||||
assert_eq!(installed(), Some(sha256_hex(&ours)));
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
}
|
||||
|
||||
/// Without a plug-in store, the install's approval comes from the grant it read first, the one it
|
||||
/// checks again before it installs: a grant another session records after that read approves
|
||||
/// nothing, so a revoke that follows it can't be undone by the install recording it again.
|
||||
#[test]
|
||||
fn a_grant_recorded_and_revoked_while_installing_approves_nothing() {
|
||||
use vectorcraft_plugins::permissions::{Grant, GrantToken, Permission, sha256_hex};
|
||||
use vectorcraft_plugins::registry;
|
||||
let id = "test.engine.permissions.recordedwhileinstalling";
|
||||
let bytes = asking(id, r#"["doc.read"]"#, &json!({"objects": []}));
|
||||
let data = vectorcraft_format::base64_encode(&bytes);
|
||||
let mut s = session();
|
||||
let g = Grant { id: id.into(), hash: sha256_hex(&bytes), permissions: vec![Permission::DocRead] };
|
||||
crate::cmd::plugin::AFTER_GRANT_READ.set(Some(Box::new(move || {
|
||||
registry::grant(GrantToken::after_engine_approval(g));
|
||||
})));
|
||||
let e = s.execute("plugin.install", &json!({"dataBase64": data})).unwrap_err().to_string();
|
||||
assert!(e.contains("asks for the permissions doc.read"), "{e}");
|
||||
assert!(registry::get(id).is_none(), "nothing is installed");
|
||||
registry::revoke(id);
|
||||
}
|
||||
|
||||
/// A `plugin.remove` in another session while a module is installed waits until the install has
|
||||
/// written the store, then removes the module, its grant and the plug-in: nothing of it stays in
|
||||
/// the store for the next launch.
|
||||
#[test]
|
||||
fn a_removal_while_installing_leaves_nothing_in_the_store() {
|
||||
use vectorcraft_plugins::registry;
|
||||
let folder = crate::tests_links::Folder::new("plugin-store-removed-while-installing");
|
||||
let id = "test.engine.permissions.removedwhileinstalling";
|
||||
let bytes = asking(id, r#"["doc.read"]"#, &json!({"objects": []}));
|
||||
let data = vectorcraft_format::base64_encode(&bytes);
|
||||
let mut s = session();
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
let module = std::path::PathBuf::from(s.stored_plugin_file(id).unwrap());
|
||||
let grants = folder.0.join("grants.json");
|
||||
|
||||
let (said, heard) = std::sync::mpsc::channel::<&'static str>();
|
||||
let (handed, remover) = std::sync::mpsc::channel();
|
||||
let dir = folder.0.clone();
|
||||
crate::cmd::plugin::BEFORE_STORE.set(Some(Box::new(move || {
|
||||
let thread = std::thread::spawn(move || {
|
||||
let tell = said.clone();
|
||||
crate::cmd::plugin::WHILE_WAITING.set(Some(Box::new(move || {
|
||||
let _ = tell.send("waiting");
|
||||
})));
|
||||
let mut other = session();
|
||||
other.attach_plugin_store(dir);
|
||||
let removed = other.execute("plugin.remove", &json!({"id": id})).map(|_| ()).map_err(|e| e.to_string());
|
||||
let _ = said.send("removed");
|
||||
removed
|
||||
});
|
||||
// The removal has finished, or waits for this install.
|
||||
let first = heard.recv().unwrap_or("gone");
|
||||
let _ = handed.send((first, thread));
|
||||
})));
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]}));
|
||||
let (first, thread) = remover.recv().unwrap();
|
||||
assert_eq!(thread.join().unwrap(), Ok(()));
|
||||
assert!(registry::get(id).is_none() && registry::granted(id).is_none(), "the plug-in and its grant are gone");
|
||||
assert!(!module.exists(), "no module stays in the store");
|
||||
assert!(!std::fs::read_to_string(&grants).is_ok_and(|g| g.contains(id)), "no grant stays in the store");
|
||||
assert_eq!(first, "waiting", "the removal waits for the install");
|
||||
}
|
||||
|
||||
/// Another session that attaches the plug-in store while a new version is installed loads the
|
||||
/// stored plug-ins once the install has written the store: the version that runs is the one the
|
||||
/// store keeps for the next launch.
|
||||
#[test]
|
||||
fn a_store_loaded_while_installing_loads_the_new_version() {
|
||||
use vectorcraft_plugins::permissions::sha256_hex;
|
||||
use vectorcraft_plugins::registry;
|
||||
let folder = crate::tests_links::Folder::new("plugin-store-loaded-while-installing");
|
||||
let id = "test.engine.permissions.loadedwhileinstalling";
|
||||
let old = asking(id, r#"["doc.read"]"#, &json!({"objects": []}));
|
||||
let new = asking(id, r#"["doc.read"]"#, &json!({"objects": [], "documentData": null}));
|
||||
let mut s = session();
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&old), "grant": ["doc.read"]}));
|
||||
|
||||
let (said, heard) = std::sync::mpsc::channel::<&'static str>();
|
||||
let (handed, loader) = std::sync::mpsc::channel();
|
||||
let dir = folder.0.clone();
|
||||
crate::cmd::plugin::BEFORE_STORE.set(Some(Box::new(move || {
|
||||
let thread = std::thread::spawn(move || {
|
||||
let tell = said.clone();
|
||||
crate::cmd::plugin::WHILE_WAITING.set(Some(Box::new(move || {
|
||||
let _ = tell.send("waiting");
|
||||
})));
|
||||
session().attach_plugin_store(dir);
|
||||
let _ = said.send("loaded");
|
||||
});
|
||||
// The load has finished, or waits for this install.
|
||||
let first = heard.recv().unwrap_or("gone");
|
||||
let _ = handed.send((first, thread));
|
||||
})));
|
||||
let data = vectorcraft_format::base64_encode(&new);
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"], "replace": true}));
|
||||
let (first, thread) = loader.recv().unwrap();
|
||||
thread.join().unwrap();
|
||||
assert_eq!(registry::get(id).map(|p| p.hash().to_string()), Some(sha256_hex(&new)), "the new version runs");
|
||||
assert_eq!(std::fs::read(s.stored_plugin_file(id).unwrap()).unwrap(), new, "the store keeps the new version");
|
||||
assert_eq!(first, "waiting", "the load waits for the install");
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
}
|
||||
|
||||
/// Runs the test `name` of this module again in a process of its own → whether this is that
|
||||
/// process. The list of disabled plug-ins is kept for the whole process, and the other tests here
|
||||
/// read it again each time they attach a plug-in store.
|
||||
|
||||
@@ -2473,6 +2473,65 @@ fn deferred_commit_forwards_preview_warnings() {
|
||||
assert!(ui.iter().any(|r| matches!(r, UiRequest::Status(m) if m.contains("type"))), "{ui:?}");
|
||||
}
|
||||
|
||||
/// A session with a rectangle selected, and type too with `with_type`, tool `tool` chosen,
|
||||
/// Real-time Drawing off, and an interaction labeled `label` whose deferred Bloat preview warns
|
||||
/// that type is skipped when type is selected.
|
||||
fn deferred_bloat(label: &str, with_type: bool, tool: &str) -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
let rect = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 200, "height": 200})).unwrap();
|
||||
let text = s.execute("text.create", &json!({"x": 300, "y": 200, "text": "Hi"})).unwrap();
|
||||
let ids = if with_type { json!([rect["id"], text["id"]]) } else { json!([rect["id"]]) };
|
||||
s.execute("select.set", &json!({ "ids": ids })).unwrap();
|
||||
s.select_tool(tool, ViewInfo::default()).unwrap();
|
||||
set_pref(&mut s, "realTimeDrawing", json!(false));
|
||||
s.begin_interaction(label).unwrap();
|
||||
let p = json!({"tool": "bloat", "points": [[290.0, 200.0]], "width": 200.0, "height": 200.0});
|
||||
s.doc_mut().unwrap().interaction.as_mut().unwrap().preview = Some(("object.liquify".into(), p));
|
||||
s
|
||||
}
|
||||
|
||||
/// A command that applies a deferred preview before it runs (Undo, Clear History) reports the
|
||||
/// preview's warning in its result, as the tool's own commit reports it; the preview is its own
|
||||
/// step, which Undo takes back. A preview without a warning adds none.
|
||||
#[test]
|
||||
fn settling_a_deferred_preview_keeps_its_warning() {
|
||||
let mut s = deferred_bloat("Bloat", true, "selection");
|
||||
let before = s.doc().unwrap().history.undo.len();
|
||||
let r = s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(r["undone"], "Bloat", "{r}");
|
||||
assert!(r["warning"].as_str().is_some_and(|w| w.contains("type")), "{r}");
|
||||
assert_eq!(r["previewWarning"], r["warning"], "{r}");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), before, "the preview was a step of its own, and Undo took it back");
|
||||
let r = s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert!(r.get("warning").is_none() && r.get("previewWarning").is_none(), "nothing was settled: {r}");
|
||||
|
||||
let mut s = deferred_bloat("Bloat", true, "selection");
|
||||
let r = s.execute("edit.clearHistory", &json!({})).unwrap();
|
||||
assert!(r["warning"].as_str().is_some_and(|w| w.contains("type")), "{r}");
|
||||
|
||||
let mut s = deferred_bloat("Bloat", false, "selection");
|
||||
let r = s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(r, json!({"undone": "Bloat"}));
|
||||
}
|
||||
|
||||
/// Typing kept as its own step when a tool's drag begins, or when a Cmd press lends the Selection
|
||||
/// tool, shows its applied preview's warning in the status bar.
|
||||
#[test]
|
||||
fn settling_typing_for_a_tool_shows_its_preview_warning() {
|
||||
use vectorcraft_tools::{Action, Mods};
|
||||
let warned = |ui: &[UiRequest]| ui.iter().any(|r| matches!(r, UiRequest::Status(m) if m.contains("type")));
|
||||
let mut s = deferred_bloat("Typing", true, "selection");
|
||||
let ui = s.apply_actions(vec![Action::Begin("Move".into())]).unwrap();
|
||||
assert!(warned(&ui), "{ui:?}");
|
||||
|
||||
let mut s = deferred_bloat("Typing", true, "rectangle");
|
||||
let cmd = Mods { cmd: true, ..Default::default() };
|
||||
let ui = s.pointer(&PointerEvent::new(PointerKind::Down, 50.0, 380.0).with_mods(cmd), ViewInfo::default()).unwrap();
|
||||
assert!(warned(&ui), "{ui:?}");
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 50.0, 380.0).with_mods(cmd), ViewInfo::default()).unwrap();
|
||||
}
|
||||
|
||||
/// File Handling › Use Low Resolution Proxy for Linked EPS (#394): off by default; toggling it does
|
||||
/// not replace full-resolution pixels already in the document.
|
||||
#[test]
|
||||
|
||||
@@ -1348,3 +1348,159 @@ fn theme_picker_refuses_bad_params() {
|
||||
assert!(e.contains(msg), "{p}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
const RED: &str = "rgb 255 0 0";
|
||||
const PURPLE: &str = "rgb 128 0 204";
|
||||
const BLUE: &str = "rgb 0 0 255";
|
||||
|
||||
/// Two red rectangles, a purple one and a blue one, selected.
|
||||
fn prominent_art(s: &mut Session) -> [NodeId; 4] {
|
||||
let ids = [rect(s, json!("#ff0000")), rect(s, json!("#ff0000")), rect(s, json!("#8000cc")), rect(s, json!("#0000ff"))];
|
||||
select_all(s);
|
||||
ids
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn weigh_gives_each_rows_share_of_the_uses() {
|
||||
let mut s = session();
|
||||
prominent_art(&mut s);
|
||||
let map = json!([{"from": [RED, PURPLE], "to": "#00ff00"}, {"from": BLUE, "to": null, "tint": 50}]);
|
||||
let r = run(&mut s, "recolor.weigh", json!({"map": map}));
|
||||
assert_eq!(r["shares"], json!([75.0, 25.0]));
|
||||
assert_eq!(
|
||||
r["map"],
|
||||
json!([{"from": [RED, PURPLE], "to": "#00ff00"}, {"from": [BLUE], "to": null, "tint": 50}]),
|
||||
"rows as given, from as a list"
|
||||
);
|
||||
// An excluded row has no share, and the others share the uses.
|
||||
let excl = json!([{"from": [RED, PURPLE], "to": null}, {"from": [BLUE], "to": null, "exclude": true}]);
|
||||
assert_eq!(run(&mut s, "recolor.weigh", json!({"map": excl}))["shares"], json!([100.0, 0.0]));
|
||||
// An excluded row before another that lists the same colour doesn't take its uses.
|
||||
let first = json!([{"from": [RED], "exclude": true}, {"from": [RED]}, {"from": [BLUE, PURPLE]}]);
|
||||
assert_eq!(run(&mut s, "recolor.weigh", json!({"map": first}))["shares"], json!([0.0, 50.0, 50.0]));
|
||||
// A current colour that no art uses counts nothing, and a use counts for the first row only.
|
||||
let twice = json!({"map": [{"from": [RED, "#123456"]}, {"from": [RED, PURPLE, BLUE]}]});
|
||||
assert_eq!(run(&mut s, "recolor.weigh", twice)["shares"], json!([50.0, 50.0]));
|
||||
// As recolor.apply matches them: an exact colour before a hex one, a row with a new colour first.
|
||||
let exact = json!({"map": [{"from": ["#ff0000", PURPLE], "to": "#00ff00"}, {"from": [RED, BLUE], "to": "#ffff00"}]});
|
||||
assert_eq!(run(&mut s, "recolor.weigh", exact)["shares"], json!([25.0, 75.0]));
|
||||
let recolored = json!({"map": [{"from": [RED, PURPLE]}, {"from": [RED, BLUE], "to": "#ffff00"}]});
|
||||
assert_eq!(run(&mut s, "recolor.weigh", recolored)["shares"], json!([25.0, 75.0]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn weigh_moves_colors_to_the_rows_weights_and_changes_nothing() {
|
||||
let mut s = session();
|
||||
let [_, _, purple, blue] = prominent_art(&mut s);
|
||||
let map = json!([{"from": [RED, PURPLE], "to": "#00ff00"}, {"from": [BLUE], "to": "#ffff00"}]);
|
||||
let r = run(&mut s, "recolor.weigh", json!({"map": map, "weights": [1, 1]}));
|
||||
assert_eq!(r["map"], json!([{"from": [RED], "to": "#00ff00"}, {"from": [BLUE, PURPLE], "to": "#ffff00"}]));
|
||||
assert_eq!(r["shares"], json!([50.0, 50.0]));
|
||||
assert_eq!(fill(&s, purple).to_hex(), "#8000cc", "a query leaves the art alone");
|
||||
// Recoloring with the weighed rows gives the moved colour its new row's colour.
|
||||
select_all(&mut s);
|
||||
run(&mut s, "recolor.apply", json!({"map": r["map"]}));
|
||||
assert_eq!(fill(&s, purple).to_hex(), "#ffff00");
|
||||
assert_eq!(fill(&s, blue).to_hex(), "#ffff00");
|
||||
// A row's first colour stays, however small its weight.
|
||||
let mut s = session();
|
||||
prominent_art(&mut s);
|
||||
let r = run(&mut s, "recolor.weigh", json!({"map": map, "weights": [0, 1]}));
|
||||
assert_eq!(r["map"][0]["from"], json!([RED]));
|
||||
assert_eq!(r["shares"], json!([50.0, 50.0]));
|
||||
// Excluded rows keep their colours and take none; their weights are ignored.
|
||||
let three =
|
||||
json!([{"from": [RED, PURPLE], "to": "#000000"}, {"from": [BLUE], "to": "#000000", "exclude": true}, {"from": ["#00ff00"], "to": "#000000"}]);
|
||||
let r = run(&mut s, "recolor.weigh", json!({"map": three, "weights": [1, 50, 1]}));
|
||||
assert_eq!(r["map"][1]["from"], json!([BLUE]));
|
||||
assert_eq!(r["map"][2]["from"], json!(["#00ff00", PURPLE]));
|
||||
// A row without a new colour recolors nothing, so it neither gives nor takes colours.
|
||||
let keep = json!([{"from": [RED, PURPLE], "to": "#000000"}, {"from": [BLUE]}, {"from": ["#00ff00"], "to": "#000000"}]);
|
||||
let r = run(&mut s, "recolor.weigh", json!({"map": keep, "weights": [0, 1, 1]}));
|
||||
assert_eq!(r["map"][1]["from"], json!([BLUE]));
|
||||
assert_eq!(r["map"][2]["from"], json!(["#00ff00", PURPLE]));
|
||||
}
|
||||
|
||||
/// A colour that two rows list moves only where recolor.apply recolors it with the row it moved
|
||||
/// to, so the shares describe the recolor.
|
||||
#[test]
|
||||
fn weigh_keeps_a_moved_color_from_rows_that_also_list_it() {
|
||||
const GREEN: &str = "rgb 0 255 0";
|
||||
let mut s = session();
|
||||
let [_, _, purple, _] = prominent_art(&mut s);
|
||||
rect(&mut s, json!("#00ff00"));
|
||||
select_all(&mut s);
|
||||
// The purple moves from the first row to the third; the second row's entry for it goes.
|
||||
let map = json!([{"from": [RED, PURPLE], "to": "#000000"}, {"from": [BLUE, PURPLE], "to": "#ffffff"}, {"from": [GREEN], "to": "#ffff00"}]);
|
||||
let r = run(&mut s, "recolor.weigh", json!({"map": map, "weights": [2, 1, 2]}));
|
||||
assert_eq!(r["map"][0]["from"], json!([RED]));
|
||||
assert_eq!(r["map"][1]["from"], json!([BLUE]));
|
||||
assert_eq!(r["map"][2]["from"], json!([GREEN, PURPLE]));
|
||||
assert_eq!(r["shares"], json!([40.0, 20.0, 40.0]));
|
||||
run(&mut s, "recolor.apply", json!({"map": r["map"], "method": "exact"}));
|
||||
assert_eq!(fill(&s, purple).to_hex(), "#ffff00", "the purple takes the row it moved to");
|
||||
// A colour that another row lists first stays: that row would take it back.
|
||||
let mut s = session();
|
||||
let [_, _, purple, _] = prominent_art(&mut s);
|
||||
rect(&mut s, json!("#00ff00"));
|
||||
select_all(&mut s);
|
||||
let map = json!([{"from": [RED, PURPLE], "to": "#000000"}, {"from": [PURPLE, BLUE], "to": "#ffffff"}, {"from": [GREEN], "to": "#ffff00"}]);
|
||||
let r = run(&mut s, "recolor.weigh", json!({"map": map, "weights": [2, 1, 2]}));
|
||||
assert_eq!(r["map"][0]["from"], json!([RED, PURPLE]));
|
||||
assert_eq!(r["map"][1]["from"], json!([PURPLE, BLUE]));
|
||||
assert_eq!(r["shares"], json!([60.0, 20.0, 20.0]));
|
||||
run(&mut s, "recolor.apply", json!({"map": r["map"], "method": "exact"}));
|
||||
assert_eq!(fill(&s, purple).to_hex(), "#000000", "the purple keeps the first row's colour");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn weigh_moves_the_tints_of_a_global_swatch_together() {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.new", json!({"name": "Brand", "color": {"c": 0, "m": 80, "y": 90, "k": 0}, "global": true}));
|
||||
rect(&mut s, json!("#ff0000"));
|
||||
let full = rect(&mut s, json!("#00ff00"));
|
||||
let tint = rect(&mut s, json!("#00ff00"));
|
||||
rect(&mut s, json!("#0000ff"));
|
||||
run(&mut s, "paint.setFill", json!({"ids": [full.0], "swatch": "Brand"}));
|
||||
run(&mut s, "paint.setFill", json!({"ids": [tint.0], "swatch": "Brand", "tint": 50}));
|
||||
select_all(&mut s);
|
||||
let brand: Vec<Value> = run(&mut s, "recolor.colors", json!({}))["colors"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter(|c| c["swatch"] == "Brand")
|
||||
.map(|c| c["key"].clone())
|
||||
.collect();
|
||||
assert_eq!(brand.len(), 2);
|
||||
let map = json!([{"from": [RED, brand[0], brand[1]], "to": "#000000"}, {"from": [BLUE], "to": "#ffffff"}]);
|
||||
// Even weights would take one tint alone, which would split the swatch: nothing moves.
|
||||
let r = run(&mut s, "recolor.weigh", json!({"map": map, "weights": [1, 1]}));
|
||||
assert_eq!(r["map"][1]["from"], json!([BLUE]));
|
||||
// The swatch's two colours move to the blue row as one.
|
||||
let r = run(&mut s, "recolor.weigh", json!({"map": map, "weights": [1, 3]}));
|
||||
assert_eq!(r["map"][1]["from"], json!([BLUE, brand[0], brand[1]]));
|
||||
assert_eq!(r["shares"], json!([25.0, 75.0]));
|
||||
// Colours that stay keep their order, a swatch's colours with another between them included.
|
||||
let split = json!([{"from": [brand[0], RED, brand[1]], "to": "#000000"}, {"from": [BLUE], "to": "#ffffff"}]);
|
||||
let r = run(&mut s, "recolor.weigh", json!({"map": split, "weights": [3, 1]}));
|
||||
assert_eq!(r["map"][0]["from"], json!([brand[0], RED, brand[1]]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn weigh_refuses_bad_weights() {
|
||||
let mut s = session();
|
||||
prominent_art(&mut s);
|
||||
let map = json!([{"from": [RED]}, {"from": [BLUE], "exclude": true}]);
|
||||
for (p, msg) in [
|
||||
(json!({"map": map, "weights": [1]}), "`weights` must be a list of 2 numbers, one per row"),
|
||||
(json!({"map": map, "weights": "1, 1"}), "`weights` must be a list of 2 numbers"),
|
||||
(json!({"map": map, "weights": [1, -1]}), "each weight must be a number of 0 or more (got -1)"),
|
||||
(json!({"map": map, "weights": [1, "2"]}), "each weight must be a number of 0 or more"),
|
||||
(json!({"map": map, "weights": [0, 5]}), "at least one row that isn't excluded needs a weight above 0"),
|
||||
(json!({"weights": [1, 1]}), "missing `map`"),
|
||||
(json!({"map": [{"to": "#ff0000"}]}), "each row needs `from`"),
|
||||
] {
|
||||
let e = s.execute("recolor.weigh", &p).unwrap_err().to_string();
|
||||
assert!(e.contains(msg), "{p}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -202,6 +202,52 @@ fn an_error_in_code_an_earlier_run_kept_is_at_that_runs_file_and_line() {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// `$.fileName` in code an earlier run of a named engine kept names the file that code is in: that
|
||||
/// run's script, a file it included or a file `$.evalFile` gave, not the file of the run that calls
|
||||
/// it. Code from a script given as text, and code whose place the engine no longer keeps, has no
|
||||
/// name; a dropped engine takes its functions with it.
|
||||
#[test]
|
||||
fn a_kept_function_reads_the_file_name_of_the_file_it_is_in() {
|
||||
let base: PathBuf = std::env::temp_dir().join(format!("vc-script-engines-file-name-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
for dir in ["a", "b"] {
|
||||
std::fs::create_dir_all(base.join(dir)).unwrap();
|
||||
}
|
||||
std::fs::write(base.join("a/inc.jsxinc"), "function fromInclude() { return $.fileName; }").unwrap();
|
||||
std::fs::write(base.join("a/ev.jsxinc"), "\nfunction fromEval() { return $.fileName; }").unwrap();
|
||||
let def = base.join("a/def.jsx");
|
||||
std::fs::write(&def, "#targetengine e\nfunction where() { return $.fileName; }\n#include \"inc.jsxinc\"\n$.evalFile('ev.jsxinc');").unwrap();
|
||||
let caller = base.join("b/caller.jsx");
|
||||
let call = |s: &mut Session, text: &str| -> Vec<String> {
|
||||
std::fs::write(&caller, text).unwrap();
|
||||
let r = s.execute("script.run", &json!({"path": caller.to_string_lossy()})).unwrap();
|
||||
r["log"][0].as_array().unwrap().iter().map(|v| v.as_str().unwrap().replace('\\', "/")).collect()
|
||||
};
|
||||
let mut s = Session::new();
|
||||
s.execute("script.run", &json!({"path": def.to_string_lossy()})).unwrap();
|
||||
let from_file = call(&mut s, "#targetengine e\nvc.log([where(), fromInclude(), fromEval(), $.fileName]);");
|
||||
let from_text = log(&mut s, "#targetengine e\nvc.log([where(), $.fileName, eval('where()'), eval('$.fileName')]);");
|
||||
run(&mut s, "#targetengine e\nfunction fromText() { return $.fileName; }").unwrap();
|
||||
let text_kept = call(&mut s, "#targetengine e\nvc.log([fromText(), $.fileName]);");
|
||||
// Each run's own place takes the room of the ones before, so def.jsx's places go.
|
||||
TEST_KEPT_MAP_BYTES.with(|b| b.set(Some(300)));
|
||||
for _ in 0..20 {
|
||||
run(&mut s, "#targetengine e\nvar x = 1;").unwrap();
|
||||
}
|
||||
let evicted = call(&mut s, "#targetengine e\nvc.log([where(), fromEval(), $.fileName]);");
|
||||
TEST_KEPT_MAP_BYTES.with(|b| b.set(None));
|
||||
s.execute("script.engine.drop", &json!({"name": "e"})).unwrap();
|
||||
let dropped = log(&mut s, "#targetengine e\nvc.log(typeof where);");
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
let ends = |names: &[String], ends: &[&str]| names.len() == ends.len() && names.iter().zip(ends).all(|(n, e)| n.ends_with(e));
|
||||
assert!(ends(&from_file, &["a/def.jsx", "a/inc.jsxinc", "a/ev.jsxinc", "b/caller.jsx"]), "{from_file:?}");
|
||||
let shown: Vec<String> = from_text[0].as_array().unwrap().iter().map(|v| v.as_str().unwrap().replace('\\', "/")).collect();
|
||||
assert!(ends(&shown, &["a/def.jsx", "", "a/def.jsx", ""]) && shown[1].is_empty() && shown[3].is_empty(), "{shown:?}");
|
||||
assert!(text_kept[0].is_empty() && text_kept[1].ends_with("b/caller.jsx"), "{text_kept:?}");
|
||||
assert!(evicted[0].is_empty() && evicted[1].is_empty() && evicted[2].ends_with("b/caller.jsx"), "{evicted:?}");
|
||||
assert_eq!(dropped, json!(["undefined"]));
|
||||
}
|
||||
|
||||
/// A named engine keeps the places of its earlier runs' code within its budget, the oldest going
|
||||
/// first, and the code still runs once its place is gone.
|
||||
#[test]
|
||||
|
||||
@@ -374,6 +374,48 @@ fn script_eval_file_returns_last_value_and_shares_globals() {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// `$.fileName` names the file the code reading it is in: a function `$.evalFile` gave names its
|
||||
/// file after the file has returned, through nested files, and code an included file inserted names
|
||||
/// that file. Code that `eval` compiled names the file being run.
|
||||
#[test]
|
||||
fn script_file_name_names_the_file_of_the_code_that_reads_it() {
|
||||
let base = folder("filename");
|
||||
write(&base.join("main/inc.jsxinc"), "function fromInclude() { return $.fileName; }\nvar includedTop = $.fileName;");
|
||||
write(
|
||||
&base.join("main/sub/outer.jsx"),
|
||||
"function fromOuter() { return $.fileName; }\nvar before = $.fileName;\n$.evalFile('inner.jsx');\nvar after = $.fileName;\nfromInner();",
|
||||
);
|
||||
write(&base.join("main/sub/inner.jsx"), "function fromInner() { return $.fileName; }\n$.fileName;");
|
||||
let r = run(
|
||||
&base,
|
||||
"#include \"inc.jsxinc\"\nvar nested = $.evalFile('sub/outer.jsx');\n\
|
||||
vc.log([fromInclude(), includedTop, before, after, nested, fromOuter(), fromInner(), $.fileName, eval('$.fileName')]);",
|
||||
)
|
||||
.unwrap();
|
||||
let names: Vec<String> = r["log"][0].as_array().unwrap().iter().map(|v| v.as_str().unwrap().replace('\\', "/")).collect();
|
||||
let ends = [
|
||||
"main/inc.jsxinc",
|
||||
"main/inc.jsxinc",
|
||||
"sub/outer.jsx",
|
||||
"sub/outer.jsx",
|
||||
"sub/inner.jsx",
|
||||
"sub/outer.jsx",
|
||||
"sub/inner.jsx",
|
||||
"main/main.jsx",
|
||||
"main/main.jsx",
|
||||
];
|
||||
assert_eq!(names.len(), ends.len(), "{names:?}");
|
||||
for (name, end) in names.iter().zip(ends) {
|
||||
assert!(name.ends_with(end), "{name} ends with {end}: {names:?}");
|
||||
}
|
||||
// A script given as text has no name, and neither have the functions it defines.
|
||||
let r = Session::new()
|
||||
.execute("script.run", &json!({"source": "function f() { return $.fileName; }\nvc.log([f(), $.fileName]);", "name": "t.js"}))
|
||||
.unwrap();
|
||||
assert_eq!(r["log"], json!([["", ""]]));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_eval_file_outside_scope_refused() {
|
||||
let base = folder("evaloutside");
|
||||
|
||||
@@ -75,6 +75,15 @@ fn nine_slice_guide_preview(cmd: &str, p: &Value) -> bool {
|
||||
&& p.as_object().is_some_and(|m| m.contains_key("nineSliceGuides") && m.keys().all(|k| k == "name" || k == "nineSliceGuides"))
|
||||
}
|
||||
|
||||
/// `ui` with a status message first for each of `warnings` (which came before its requests) that it
|
||||
/// doesn't already show.
|
||||
fn with_status(mut ui: Vec<UiRequest>, warnings: Vec<String>) -> Vec<UiRequest> {
|
||||
let new: Vec<UiRequest> =
|
||||
warnings.into_iter().filter(|w| !ui.iter().any(|r| matches!(r, UiRequest::Status(s) if s == w))).map(UiRequest::Status).collect();
|
||||
ui.splice(0..0, new);
|
||||
ui
|
||||
}
|
||||
|
||||
/// Requests from tools that only the frontend can fulfil.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum UiRequest {
|
||||
@@ -227,24 +236,28 @@ impl Session {
|
||||
|
||||
/// A press with Cmd held (Ctrl elsewhere) and any other tool than a selection tool: the
|
||||
/// selection tool [`Self::lent_tool`] takes the gesture, pressing without Cmd (a plain click,
|
||||
/// not Select Behind). The tool lent to stays as it was, unaware, until the release.
|
||||
fn lend_selection_tool(&mut self, ev: &PointerEvent) -> PointerEvent {
|
||||
/// not Select Behind). The tool lent to stays as it was, unaware, until the release. → the event
|
||||
/// for the tool, and the warnings of a preview that keeping the typing applied.
|
||||
fn lend_selection_tool(&mut self, ev: &PointerEvent) -> Result<(PointerEvent, Vec<String>)> {
|
||||
if ev.kind != PointerKind::Down || !ev.mods.cmd || self.lender.is_some() {
|
||||
return *ev;
|
||||
return Ok((*ev, vec![]));
|
||||
}
|
||||
let Some(id) = self.lent_tool(self.tool.id(), &ev.mods) else { return *ev };
|
||||
let Some(id) = self.lent_tool(self.tool.id(), &ev.mods) else { return Ok((*ev, vec![])) };
|
||||
// Typing in progress is kept as its own step first: the lent tool's drag previews from the
|
||||
// document its interaction started from, which would drop the typing (#1881).
|
||||
// document its interaction started from, which would drop the typing (#1881). When it
|
||||
// can't be kept, the press is not lent.
|
||||
let mut settled = vec![];
|
||||
if crate::cmd::typing_in_progress(self) {
|
||||
// Fails only without a document, and then there is no typing to keep.
|
||||
let _ = crate::cmd::settle_interaction(self);
|
||||
let (r, warnings) = self.collect_settled_warnings(crate::cmd::settle_interaction);
|
||||
r?;
|
||||
settled = warnings;
|
||||
}
|
||||
// The Selection and Group Selection tools act on the instance whole.
|
||||
self.select_whole_instance(id);
|
||||
let lent = self.make_tool(id);
|
||||
self.selection_at_lend = self.active().map(|d| (d.uid, d.selection.clone()));
|
||||
self.lender = Some(std::mem::replace(&mut self.tool, lent));
|
||||
PointerEvent { mods: Mods { cmd: false, ..ev.mods }, ..*ev }
|
||||
Ok((PointerEvent { mods: Mods { cmd: false, ..ev.mods }, ..*ev }, settled))
|
||||
}
|
||||
|
||||
/// The lent selection tool's gesture is over: the tool it was lent to is back as it was (the
|
||||
@@ -659,7 +672,8 @@ impl Session {
|
||||
}
|
||||
self.leave_draw_inside(ev, view)?;
|
||||
self.tell_tool_history_moved();
|
||||
let ev = &self.lend_selection_tool(ev);
|
||||
let (ev, settled) = self.lend_selection_tool(ev)?;
|
||||
let ev = &ev;
|
||||
let lent = self.lender.is_some();
|
||||
let mut acts = self.with_tool_cx(view, |t, cx| t.pointer(cx, ev));
|
||||
if !keep {
|
||||
@@ -670,7 +684,7 @@ impl Session {
|
||||
if keep && ev.kind == PointerKind::Up {
|
||||
self.keep_tool_settings();
|
||||
}
|
||||
self.apply_actions(acts)
|
||||
self.apply_actions(acts).map(|ui| with_status(ui, settled))
|
||||
});
|
||||
// The tool's own edits do not move the history for it. A selection tool that Cmd lends
|
||||
// edits for the lender, which hears of the edit at its next event.
|
||||
@@ -1375,7 +1389,14 @@ impl Session {
|
||||
/// Apply tool actions. Errors from previews are reported but keep the interaction alive.
|
||||
pub fn apply_actions(&mut self, acts: Vec<Action>) -> Result<Vec<UiRequest>> {
|
||||
let outer = std::mem::replace(&mut self.in_tool_actions, true);
|
||||
let r = self.apply_tool_actions(acts);
|
||||
// A preview that settling applied (typing kept as its own step before a drag begins) shows
|
||||
// its warning in the status bar, as the tool's own commit shows its preview's.
|
||||
let r = if !outer && self.depth == 0 {
|
||||
let (r, settled) = self.collect_settled_warnings(|s| s.apply_tool_actions(acts));
|
||||
r.map(|ui| with_status(ui, settled))
|
||||
} else {
|
||||
self.apply_tool_actions(acts)
|
||||
};
|
||||
self.in_tool_actions = outer;
|
||||
if !outer && self.depth == 0 {
|
||||
self.trim_histories();
|
||||
|
||||
Reference in New Issue
Block a user