Merge main into feat/plugin-api-importer-output-kinds

This commit is contained in:
dotCooCoo committed 2026-11-25 14:51:05 -08:00
commit af7ee2fdca
390 files changed
+24406 -2126

No files matched your search

+10 -4
View File
@@ -1687,6 +1687,8 @@ fn move_item(s: &mut Session, p: &Value) -> Result<Value> {
let from = index_param(p, "from", C)?;
let contents = p.get("contents").map(|_| index_param(p, "contents", C)).transpose()?;
let mut landed = to;
let active = s.active_appearance_item.as_ref().and_then(|a| a.objects.first().copied());
let mut active_landed = None;
// When every object's stack comes out as it was, the document and its undo history stay as they
// are.
let before = s.doc()?.doc.clone();
@@ -1694,6 +1696,9 @@ fn move_item(s: &mut Session, p: &Value) -> Result<Value> {
for id in &ids {
let Some(n) = d.node_mut(*id) else { continue };
landed = n.appearance.move_item(from, to).ok_or_else(|| bad(C, format!("no item at index {from}")))?;
if active == Some(*id) {
active_landed = Some(landed);
}
if let Some(k) = contents.filter(|_| n.contents_label().is_some()) {
n.appearance.set_contents_at(k);
}
@@ -1703,13 +1708,14 @@ fn move_item(s: &mut Session, p: &Value) -> Result<Value> {
let labels = super::graph::capture_label_changes(&before, d, &ids, true, None);
Ok(count_changed(d, &before, &ids) + usize::from(kept || painted || labels))
})?;
// The moved row stays the active one; the rows it passed shift by one.
// Track the row in its own object's stack, since other stacks may clamp to a different index.
let at = active_landed.unwrap_or(landed);
s.remap_appearance_item(&ids, |a| {
Some(if a == from {
landed
} else if from < a && a <= landed {
at
} else if from < a && a <= at {
a - 1
} else if landed <= a && a < from {
} else if at <= a && a < from {
a + 1
} else {
a
+6 -4
View File
@@ -88,11 +88,13 @@ fn recipe(s: &Session, p: &Value) -> Result<Dimension> {
}
let a = if source.is_none() || p.get("a").is_some() { point(p, "a")? } else { Point::ZERO };
let b = if source.is_none() || p.get("b").is_some() { point(p, "b")? } else { Point::new(1.0, 0.0) };
let vertex = if mode == DimensionMode::Angular && (source.is_none() || matches!(source, Some(DimensionSource::Points { .. }))) {
point(p, "vertex")?
} else {
Point::ZERO
// Resolution supplies a linked vertex. An explicit coordinate is still checked when given.
let read_vertex = match &source {
None => true,
Some(DimensionSource::Points { vertex, .. }) => vertex.is_none() || p.get("vertex").is_some(),
_ => false,
};
let vertex = if mode == DimensionMode::Angular && read_vertex { point(p, "vertex")? } else { Point::ZERO };
let orientation = orientation(p, mode)?.unwrap_or_default();
let mut d = Dimension {
mode,
+19 -1
View File
@@ -131,8 +131,10 @@ fn apply(s: &mut DocSetup, units: &mut vectorcraft_doc::Unit, k: &str, v: &Value
let (name, _, quotes) = LANGUAGES.iter().find(|(n, _, _)| n.eq_ignore_ascii_case(l)).ok_or_else(|| {
bad(C, format!("unknown language `{l}` (one of {})", LANGUAGES.iter().map(|(n, _, _)| *n).collect::<Vec<_>>().join(", ")))
})?;
if !s.language.eq_ignore_ascii_case(name) {
s.quotes = *quotes;
}
s.language = name.to_string();
s.quotes = *quotes;
}
"quotes" => s.quotes = quotes_param(v, s.quotes)?,
"typographersQuotes" => s.typographers_quotes = flag(k, v)?,
@@ -311,3 +313,19 @@ fn restamp_scripts(d: &mut Document) {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn setup_round_trip_preserves_custom_quotes() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
s.execute(C, &json!({"quotes": {"double": "«»", "single": "‹›"}})).unwrap();
let mut fields = s.execute(C, &json!({})).unwrap();
fields["bleed"] = json!(4);
let reply = s.execute(C, &fields).unwrap();
assert_eq!(reply["quotes"], fields["quotes"]);
}
}
+1 -1
View File
@@ -12,7 +12,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Pencil",
[],
None,
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation,wheel]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise, 0..360: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation. An airbrush pen's finger wheel 0..1: the stroke keeps it for brushes with Stylus Wheel variation, a point without one half way; null for what a point lacks. A pressure, tilt, rotation or wheel outside its range, or a point array of more than seven numbers, is an error), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\" (default) | \"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end?: \"end\" (default) | \"start\"}, connect?: {id, end: \"start\"|\"end\"} (only with extend), redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it. Any other style, extend end or connect end, connect without extend, and a connect that names no other path with an open end are errors, a stroke of one point included, and nothing changes",
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation,wheel]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise, 0..360: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation. An airbrush pen's finger wheel 0..1: the stroke keeps it for brushes with Stylus Wheel variation, a point without one half way; null for what a point lacks. A pressure, tilt, rotation or wheel outside its range, or a point array of more than seven numbers, is an error), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\" (default) | \"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), leaveSelection?: bool (false; true with keepSelected false: a new path leaves the selection as it is, as the Pencil previews a stroke that redraws a path), extend?: {id, end?: \"end\" (default) | \"start\"}, connect?: {id, end: \"start\"|\"end\"} (only with extend), redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the way round a closed one that leaves the bigger shape; on an open one the way the stroke runs along it at each end decides: it replaces the part it runs along where it starts and joins the part it runs into where it lands, so it replaces the part between, keeps it and closes the path along the stroke, or, when its ends disagree, ends where it is lifted; an end that leaves or meets the path squarely follows the other end, and when both do it closes only if it goes round both pieces beyond), the stroke's ends bent smoothly onto the path; a stroke that starts on it and returns to the same point adds a loop there, and one lifted farther than `within` from it takes the path with it: a closed subpath opens where the stroke starts, an open one is cut there and drops the part the stroke heads along, and the path ends where the stroke does. Any other style, extend end or connect end, connect without extend, and a connect that names no other path with an open end are errors, a stroke of one point included, and nothing changes",
has_doc,
freehand
),
+380 -32
View File
@@ -74,13 +74,329 @@ fn stroke_subpath(pts: &[Point], tol: Option<f64>, closed: bool) -> SubPath {
}
}
/// Pencil's Edit Selected Paths in the middle of a path: a stroke from one point of a subpath of
/// `pd` to another, each within `within` of it, replaces the section between them (the shorter
/// way round a closed subpath) with the stroke fitted at `tol` (with no `tol`, unfitted). The
/// subpath's index and its new shape; None when the stroke doesn't start and end on the same
/// subpath, or meets it once.
/// The anchor of `sp` at the point of it nearest to `q`: the one there, else a new one, and
/// whether it was added.
fn anchor_at(sp: &mut SubPath, q: Point) -> Option<(usize, bool)> {
let (_, seg, t, _, _) = PathData::single(sp.clone()).nearest(q)?;
let n = sp.anchors.len();
if n == 0 {
return None;
}
Some(if t <= 1e-6 {
(seg % n, false)
} else if t >= 1.0 - 1e-6 {
((seg + 1) % n, false)
} else {
(sp.insert_anchor(seg, t), true)
})
}
/// The direction `sp` leaves anchor `k` going forward (towards the next anchor).
fn forward_at(sp: &SubPath, k: usize) -> Option<kurbo::Vec2> {
let a = sp.anchors.get(k)?;
let n = sp.anchors.len();
let next = if sp.closed || k + 1 < n { sp.anchors.get((k + 1) % n) } else { None };
let toward = if a.h_out != a.p {
a.h_out
} else if let Some(b) = next {
if b.h_in != b.p { b.h_in } else { b.p }
} else {
// The last anchor of an open subpath: forward goes on the way it arrived.
let prev = sp.anchors.get(k.checked_sub(1)?)?;
return Some(a.p - if a.h_in != a.p { a.h_in } else { prev.p });
};
let v = toward - a.p;
(v.hypot() > 1e-9).then_some(v)
}
/// The direction stroke `pts` leaves its first point: towards its first point farther than
/// `reach` from it, or its last point.
fn heading(pts: &[Point], reach: f64) -> Option<kurbo::Vec2> {
let (&p0, rest) = pts.split_first()?;
let to = rest.iter().find(|q| q.distance(p0) > reach).or(rest.last())?;
let v = *to - p0;
(v.hypot() > 1e-9).then_some(v)
}
/// `stroke` (its first point moved onto anchor `a` of the path it leaves) fitted at `tol`: its
/// anchors, the first of which is at `a`.
fn fit_from(a: Point, pts: &[Point], tol: Option<f64>, reach: f64) -> Vec<Anchor> {
let mut stroke = pts.to_vec();
bend_ends(&mut stroke, Some(a), None, reach);
stroke_subpath(&stroke, tol, false).anchors.into_vec()
}
/// Bend the ends of `stroke` onto `a` (its start) and `b` (its end): each end moves all the way
/// and the stroke behind it less and less, to not at all `reach` along it (Edit selected paths
/// within), so a stroke that starts or ends near the path joins it smoothly instead of with a
/// straight piece. A stroke shorter than `reach` bends over its own length, so each end still
/// lands on its target and the other end's bend doesn't move it off.
fn bend_ends(stroke: &mut [Point], a: Option<Point>, b: Option<Point>, reach: f64) {
let (Some(&first), Some(&last)) = (stroke.first(), stroke.last()) else { return };
// How far along the stroke each point lies, measured before anything moves.
let mut along = Vec::with_capacity(stroke.len());
let mut total = 0.0;
let mut prev = first;
for p in stroke.iter() {
total += prev.distance(*p);
prev = *p;
along.push(total);
}
let reach = reach.min(total);
if !reach.is_finite() || reach <= 0.0 {
// No length to bend over: only the ends move.
if let (Some(a), Some(p)) = (a, stroke.first_mut()) {
*p = a;
}
if let (Some(b), Some(p)) = (b, stroke.last_mut()) {
*p = b;
}
return;
}
let weight = |d: f64| (1.0 - d / reach).max(0.0);
let (shift_a, shift_b) = (a.map(|a| a - first), b.map(|b| b - last));
for (p, &d) in stroke.iter_mut().zip(&along) {
if let Some(s) = shift_a {
*p += s * weight(d);
}
if let Some(s) = shift_b {
*p += s * weight(total - d);
}
}
}
/// Pencil's Edit Selected Paths for a stroke that starts on a subpath of `pd` (within `within` of
/// it) and ends away from it (#2850 follow-up): the path follows the stroke and ends where the
/// stroke does. A closed subpath opens where the stroke starts and keeps its whole outline, run
/// so that it arrives there heading the stroke's way. An open subpath is cut there and keeps the
/// part behind the stroke: the part the stroke heads along is dropped. The subpath's index and its
/// new shape; None when the stroke doesn't start on `pd`. `runs_up`, when given, says which part of
/// an open subpath the stroke heads along: the part towards its last anchor when true.
fn redraw_extend(pd: &PathData, pts: &[Point], tol: Option<f64>, within: f64, runs_up: Option<bool>) -> Option<(usize, SubPath)> {
let first = *pts.first()?;
let (si, _, _, _, d) = pd.nearest(first)?;
if d > within || pts.len() < 2 {
return None;
}
let mut sp = pd.subpaths.get(si)?.clone();
if sp.anchors.len() < 2 {
return None;
}
let (mut k, _) = anchor_at(&mut sp, first)?;
let last = sp.anchors.len() - 1;
// Run the subpath so the stroke goes on from `k` forward; the result runs the subpath's own way
// again below, so a shape's holes stay holes under the non-zero fill rule. A closed subpath
// arrives at `k` heading the stroke's way. An open one drops the part the stroke heads along;
// one it leaves nearly square to it (more than 70° from its direction) drops its shorter
// part, never most of the path. From one of its ends it drops nothing.
let dir = heading(pts, within.max(tol.unwrap_or(0.0) * 2.0))?;
let cos = forward_at(&sp, k).map_or(0.0, |f| f.dot(dir) / (f.hypot() * dir.hypot()).max(1e-12));
let flipped = if sp.closed {
cos < 0.0
} else if k == 0 || k == last {
k == 0
} else if let Some(up) = runs_up {
!up
} else if cos.abs() >= 0.34 {
cos < 0.0
} else {
let len = |i: usize, j: usize| (i..j).map(|s| kurbo::ParamCurveArclen::arclen(&sp.segment(s), 0.01)).sum::<f64>();
len(0, k) < len(k, last)
};
if flipped {
sp.reverse();
k = sp.anchors.len().checked_sub(1 + k)?;
}
let at = *sp.anchors.get(k)?;
let mut anchors: Vec<Anchor> = if sp.closed {
// From `k` all the way round back to `k`: the shape opens there.
let mut v: Vec<Anchor> = sp.anchors.get_range(k..)?.into_iter().chain(sp.anchors.get_range(..k)?).collect();
if let Some(a0) = v.first_mut() {
*a0 = Anchor::with_handles(a0.p, a0.p, a0.h_out);
}
v.push(at);
v
} else {
sp.anchors.get_range(..=k)?
};
let fit = fit_from(at.p, pts, tol, within);
let (f0, rest) = fit.split_first()?;
if let Some(a) = anchors.last_mut() {
*a = Anchor::with_handles(a.p, a.h_in, f0.h_out);
}
anchors.extend_from_slice(rest);
let mut out = SubPath::new(anchors, false);
if flipped {
out.reverse();
}
Some((si, out))
}
/// A stroke that leaves anchor `k` of `sp` and comes back to it: the stroke is inserted there as a
/// loop out of the path (#2850 follow-up).
fn redraw_loop(mut sp: SubPath, k: usize, pts: &[Point], tol: Option<f64>, within: f64) -> Option<SubPath> {
let at = *sp.anchors.get(k)?;
let mut stroke = pts.to_vec();
bend_ends(&mut stroke, Some(at.p), Some(at.p), within);
let fit = stroke_subpath(&stroke, tol, false).anchors.into_vec();
let (Some(f0), Some(fl)) = (fit.first().copied(), fit.last().copied()) else { return None };
if fit.len() < 3 {
return None;
}
let inner = fit.get(1..fit.len() - 1)?;
let mut anchors = sp.anchors.get_range(..k)?;
anchors.push(Anchor::with_handles(at.p, at.h_in, f0.h_out));
anchors.extend_from_slice(inner);
anchors.push(Anchor::with_handles(at.p, fl.h_in, at.h_out));
anchors.extend_from_slice(&sp.anchors.get_range(k + 1..)?);
sp.anchors = anchors.into();
Some(sp)
}
/// The area closed subpath `sp` would have with `stroke` (running from anchor `start` to anchor
/// `end`) in place of its run from `start` forward to `end`.
fn redrawn_area(sp: &SubPath, start: usize, end: usize, stroke: impl Iterator<Item = Point>) -> f64 {
use kurbo::ParamCurveArea;
let n = sp.anchors.len();
let (Some(from), Some(to)) = (sp.anchors.get(start), sp.anchors.get(end)) else { return 0.0 };
let mut area: f64 = (0..(start + n - end) % n).map(|k| sp.segment((end + k) % n).signed_area()).sum();
let mut at = from.p;
for q in stroke.chain([to.p]) {
area += kurbo::Line::new(at, q).signed_area();
at = q;
}
area.abs()
}
/// Which way a stroke runs along open subpath `sp` where it meets it: `stroke` starts at that end
/// of the stroke. It runs along when its first `within` of length stays within `within` of the
/// path and moves along the path more than away from it: Some(true) towards the subpath's last
/// anchor. None when it goes straight off (or onto) the path.
fn run_along(sp: &SubPath, mut stroke: impl Iterator<Item = Point>, within: f64) -> Option<bool> {
let one = PathData::single(sp.clone());
let p0 = stroke.next()?;
// The point `within` along the stroke, or its other end when it is shorter.
let (mut prev, mut len, mut q) = (p0, 0.0, p0);
for p in stroke {
let step = prev.distance(p);
if len + step >= within && step > 0.0 {
q = prev.lerp(p, (within - len) / step);
break;
}
len += step;
prev = p;
q = p;
}
let (_, s0, t0, on0, _) = one.nearest(p0)?;
let (_, s1, t1, on1, away) = one.nearest(q)?;
if away > within || on0.distance(on1) <= away {
return None;
}
Some(s1 as f64 + t1 > s0 as f64 + t0)
}
/// What a stroke from anchor `from` to anchor `to` of open subpath `sp` does to it.
enum OpenRedraw {
/// Replaces the part between and leaves the path open.
Replace,
/// Keeps the part between, drops the pieces beyond and closes the path with the stroke.
Close,
/// Drops the part it starts along (towards the last anchor when true) and ends where it does.
Extend(bool),
}
/// Pencil's Edit Selected Paths on an open subpath: what a stroke from anchor `from` to anchor `to`
/// of `sp` does, from the way it runs along the path at each end ([`run_along`]; `before` is the
/// subpath before the anchors at `from` and `to` were added). Where it starts, it replaces the part
/// it runs along; where it lands, it joins the part it runs into and the part behind goes. An end
/// that goes straight off or onto the path follows the other end. When both do, it closes only if
/// the shape it makes with the part between goes round both pieces beyond ([`goes_round`]). When
/// the two ends disagree, the start decides and the stroke's end stays where it is lifted.
fn open_redraw(before: &SubPath, sp: &SubPath, from: usize, to: usize, pts: &[Point], within: f64) -> OpenRedraw {
let up = to > from;
// Each end runs towards the last anchor (true) or the first. Running towards the other end
// of the stroke at the start, or on away from it where it lands, replaces the part between;
// the other way keeps the part between and closes the path.
let at_start = run_along(before, pts.iter().copied(), within);
let at_end = run_along(before, pts.iter().rev().copied(), within).map(|back| !back);
match (at_start, at_end) {
(Some(s), Some(e)) if s != e => OpenRedraw::Extend(s),
(Some(r), _) | (None, Some(r)) => {
if r == up {
OpenRedraw::Replace
} else {
OpenRedraw::Close
}
}
(None, None) => {
if goes_round(sp, from, to, pts) {
OpenRedraw::Close
} else {
OpenRedraw::Replace
}
}
}
}
/// Does the shape that stroke `pts` (from anchor `from` to anchor `to` of open subpath `sp`) makes
/// with the part of `sp` between them go round both pieces of `sp` beyond them? A piece counts as
/// inside when more of it lies inside than outside; a piece of no length counts as inside.
fn goes_round(sp: &SubPath, from: usize, to: usize, pts: &[Point]) -> bool {
use kurbo::{ParamCurve, Shape};
let (lo, hi) = (from.min(to), from.max(to));
let Some(middle) = sp.anchors.get_range(lo..=hi) else { return false };
let mut shape = PathData::single(SubPath::new(middle, false)).to_bezpath();
// The stroke runs from `hi` back to `lo` to close the shape.
let back: Vec<Point> = if from == lo { pts.iter().rev().copied().collect() } else { pts.to_vec() };
for p in back {
shape.line_to(p);
}
shape.close_path();
let inside = |segs: std::ops::Range<usize>| {
let (mut yes, mut no) = (0, 0);
for k in segs {
let seg = sp.segment(k);
for t in [0.25, 0.5, 0.75] {
if shape.winding(seg.eval(t)) != 0 { yes += 1 } else { no += 1 }
}
}
yes >= no
};
inside(0..lo) && inside(hi..sp.anchors.len().saturating_sub(1))
}
/// Closes open subpath `sp` with stroke `pts`, which runs from anchor `from` to anchor `to`: the
/// anchors between them stay, the pieces beyond go, and the stroke, its ends bent onto those
/// anchors ([`bend_ends`] over `within`), runs from one back to the other.
fn redraw_across_gap(sp: &SubPath, from: usize, to: usize, pts: &[Point], tol: Option<f64>, within: f64) -> Option<SubPath> {
let (lo, hi) = (from.min(to), from.max(to));
let (a_lo, a_hi) = (*sp.anchors.get(lo)?, *sp.anchors.get(hi)?);
let mut stroke = pts.to_vec();
if from == lo {
stroke.reverse();
}
bend_ends(&mut stroke, Some(a_hi.p), Some(a_lo.p), within);
let fit = stroke_subpath(&stroke, tol, false).anchors.into_vec();
let (Some(f0), Some(fl)) = (fit.first().copied(), fit.last().copied()) else { return None };
let mut anchors = sp.anchors.get_range(lo..=hi)?;
if let Some(a) = anchors.first_mut() {
*a = Anchor::with_handles(a.p, fl.h_in, a.h_out);
}
if let Some(a) = anchors.last_mut() {
*a = Anchor::with_handles(a.p, a.h_in, f0.h_out);
}
anchors.extend_from_slice(fit.get(1..fit.len().saturating_sub(1)).unwrap_or_default());
Some(SubPath::new(anchors, true))
}
/// Pencil's Edit Selected Paths in the middle of a path: a stroke that starts and ends within
/// `within` of a subpath of `pd` replaces the section between with the stroke fitted at `tol` (with
/// no `tol`, unfitted), its ends bent onto the path ([`bend_ends`]). On a closed subpath that is the
/// way round that leaves the bigger shape. On an open one the way the stroke runs along the path
/// at its ends decides ([`open_redraw`]): it replaces the part between, keeps the part between and
/// closes the path, or ends where it is lifted. The subpath's index and its new shape; None when
/// the stroke doesn't start and end on the same subpath.
fn redraw_section(pd: &PathData, pts: &[Point], tol: Option<f64>, within: f64) -> Option<(usize, SubPath)> {
use kurbo::ParamCurveArclen;
let (first, last) = (*pts.first()?, *pts.last()?);
let (si, _, _, _, d_a) = pd.nearest(first)?;
let (sj, _, _, _, d_b) = pd.nearest(last)?;
@@ -91,35 +407,35 @@ fn redraw_section(pd: &PathData, pts: &[Point], tol: Option<f64>, within: f64) -
if sp.anchors.len() < 2 {
return None;
}
// The anchor nearest to `q`: the one there, else a new one, and whether it was added. Each
// point is looked up on the subpath as it is by then: splitting a straight segment makes two
// new ones, which a `t` along the old one doesn't measure.
let place = |sp: &mut SubPath, q: Point| {
let (_, seg, t, _, _) = PathData::single(sp.clone()).nearest(q)?;
let n = sp.anchors.len();
Some(if t <= 1e-6 {
(seg % n, false)
} else if t >= 1.0 - 1e-6 {
((seg + 1) % n, false)
} else {
(sp.insert_anchor(seg, t), true)
})
};
let (mut from, _) = place(&mut sp, first)?;
let (to, added) = place(&mut sp, last)?;
let before = sp.clone();
// Each point is looked up on the subpath as it is by then: splitting a straight segment makes
// two new ones, which a `t` along the old one doesn't measure.
let (mut from, _) = anchor_at(&mut sp, first)?;
let (to, added) = anchor_at(&mut sp, last)?;
if added && to <= from {
from += 1;
}
if from == to {
return None;
// The stroke starts and ends on the same point: it is a loop out of the path there.
return redraw_loop(sp, from, pts, tol, within).map(|sp| (si, sp));
}
if !sp.closed {
match open_redraw(&before, &sp, from, to, pts, within) {
OpenRedraw::Replace => {}
OpenRedraw::Close => return redraw_across_gap(&sp, from, to, pts, tol, within).map(|sp| (si, sp)),
OpenRedraw::Extend(up) => return redraw_extend(pd, pts, tol, within, Some(up)),
}
}
let n = sp.anchors.len();
// The length of the run of segments from anchor i forward to anchor j.
let run = |i: usize, j: usize| (0..(j + n - i) % n).map(|k| sp.segment((i + k) % n).arclen(0.01)).sum::<f64>();
// The stroke goes from `start` to `end` and replaces the run between them; `kept` runs from
// `end` round to `start`, then the stroke's inner anchors follow.
let (start, end, reversed) = if sp.closed {
if run(from, to) <= run(to, from) { (from, to, false) } else { (to, from, true) }
// The bigger of the two shapes the stroke could make stays: carving across a shape replaces
// the part it cuts off, drawing round outside it the part it goes round. Picking the side
// nearer the stroke instead threw away a thin shape under a tall arch over its long side.
let forward = redrawn_area(&sp, from, to, pts.iter().copied());
let backward = redrawn_area(&sp, to, from, pts.iter().rev().copied());
if forward >= backward { (from, to, false) } else { (to, from, true) }
} else if from < to {
(from, to, false)
} else {
@@ -129,10 +445,8 @@ fn redraw_section(pd: &PathData, pts: &[Point], tol: Option<f64>, within: f64) -
if reversed {
stroke.reverse();
}
let (Some(s0), Some(s1)) = (stroke.first_mut(), sp.anchors.get(start)) else { return None };
*s0 = s1.p;
let (Some(e0), Some(e1)) = (stroke.last_mut(), sp.anchors.get(end)) else { return None };
*e0 = e1.p;
let (Some(s1), Some(e1)) = (sp.anchors.get(start), sp.anchors.get(end)) else { return None };
bend_ends(&mut stroke, Some(s1.p), Some(e1.p), within);
let fit = stroke_subpath(&stroke, tol, false).anchors.into_vec();
let (Some(f0), Some(f1)) = (fit.first().copied(), fit.last().copied()) else { return None };
let inner = fit.get(1..fit.len().saturating_sub(1)).unwrap_or_default();
@@ -212,6 +526,9 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s
// The undo step's name: a stroke painted with a brush is a Paintbrush stroke, whatever its style.
let label = if brush || brush_name.is_some() { "Paintbrush" } else { "Pencil" };
let keep_selected = switch_or(p, "keepSelected", true, C)?;
// The Pencil's preview of a stroke that redraws a path draws it as a new path but leaves the
// selection as it is: the path being redrawn stays selected until the release redraws it.
let leave_selection = switch_or(p, "leaveSelection", false, C)?;
let filled = switch_or(p, "fill", false, C)?;
let extend = p.get("extend").filter(|v| !v.is_null());
if extend.is_none() && p.get("connect").is_some_and(|v| !v.is_null()) {
@@ -416,7 +733,9 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s
// shortcut: a stroke's pressure, tilt, bearing and rotation profiles are left as they
// were, measured along the old path; fit them to the new length if strokes drawn with a
// pen get redrawn.
if let Some((si, sp)) = redraw_section(&pd, &pts, fit_tol, within) {
// A stroke that ends back on the path redraws the section between; one that ends away from
// it takes the path with it (it is where the pen is lifted that decides).
if let Some((si, sp)) = redraw_section(&pd, &pts, fit_tol, within).or_else(|| redraw_extend(&pd, &pts, fit_tol, within, None)) {
// A member path of a compound path is redrawn in it: the compound path is what is
// selected, and what a brush paints.
let whole = brush_target(&s.doc()?.doc, id);
@@ -461,7 +780,7 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s
}
}
let out = insert_look(s, label, path_kind(PathData::single(sp)), look, None, keep_selected)?;
if !keep_selected {
if !keep_selected && !leave_selection {
// A new stroke with Keep selected off leaves nothing selected: Illustrator starts the stroke
// by dropping the earlier selection, it does not keep it (#5752).
s.select(|_, sel| sel.clear())?;
@@ -628,3 +947,32 @@ pub(super) fn blob(s: &mut Session, p: &Value) -> Result<Value> {
})?;
Ok(json!({ "id": keep.0 }))
}
#[cfg(test)]
mod bend_tests {
use super::*;
/// The ends move onto their targets, the stroke behind them less and less, and nothing farther
/// along than `reach`.
#[test]
fn bend_ends_moves_the_ends_and_fades_out_along_the_reach() {
let mut pts: Vec<Point> = (0..=10).map(|i| Point::new(f64::from(i) * 10.0, 0.0)).collect();
bend_ends(&mut pts, Some(Point::new(0.0, 8.0)), Some(Point::new(100.0, -8.0)), 40.0);
assert_eq!(pts[0], Point::new(0.0, 8.0));
assert_eq!(pts[10], Point::new(100.0, -8.0));
assert!((pts[2].y - 8.0 * 0.5).abs() < 1e-9, "halfway along the reach, half the shift: {:?}", pts[2]);
assert!((pts[8].y + 8.0 * 0.5).abs() < 1e-9, "{:?}", pts[8]);
assert_eq!(pts[5], Point::new(50.0, 0.0), "the middle doesn't move");
}
/// A stroke shorter than `reach` still has both ends on their targets: bending one end onto
/// its target doesn't pull the other end off its own.
#[test]
fn bend_ends_keeps_both_ends_on_target_for_a_short_stroke() {
let mut pts = vec![Point::new(40.0, -12.0), Point::new(44.0, -12.0), Point::new(48.0, -12.0)];
bend_ends(&mut pts, Some(Point::new(40.0, 0.0)), Some(Point::new(48.0, 0.0)), 16.0);
assert_eq!(pts[0], Point::new(40.0, 0.0), "{pts:?}");
assert_eq!(pts[2], Point::new(48.0, 0.0), "{pts:?}");
assert_eq!(pts[1], Point::new(44.0, 0.0), "halfway, half of each end's shift: {pts:?}");
}
}
+4 -1
View File
@@ -695,6 +695,7 @@ fn undo_group_end(s: &mut Session, p: &Value) -> Result<Value> {
/// 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<()> {
s.put_back_interaction();
let typing = typing_in_progress(s);
match s.unapplied_interaction_preview().filter(|_| !s.previewing) {
Some((cmd, p)) => match s.preview(&cmd, &p) {
@@ -894,8 +895,10 @@ fn clear_history(s: &mut Session, _: &Value) -> Result<Value> {
fn new_document_from_state(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "edit.newDocumentFromState";
let created = date_param(p, "created", C)?;
// The row as the panel lists it now, with a drag in progress on show: keeping it below
// changes the rows.
s.put_back_interaction();
let st = s.doc()?;
// The row as the panel lists it now: keeping an edit in progress below changes the rows.
let chosen = match super::index_opt(p, "index", C)? {
None => None,
Some(row) => {
+1 -1
View File
@@ -33,7 +33,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export EPS",
[],
None,
"{path?, level?: 2|3 (default; PostScript language level: 3 writes smooth gradients and masks transparent image pixels out, 2 steps gradients and writes those pixels white), previewFormat?: none|tiffBw|tiffColor (default: a TIFF preview other apps show), transparentPreview?: true (else on white), overprints?: preserve (default)|discard, flattenerPreset?: \"medium\" (default; high, low or a saved preset: flattener.presets.list), flattener?: {the options of object.flattenTransparency over the preset}, embedFonts?: true (type is always written as outlines, so no fonts are needed), includeLinkedFiles?: false (the embedded document keeps linked images whole, not just their previews), thumbnails?: true (a PNG thumbnail in the file), cmykPostScript?: true (RGB documents written in CMYK), compatibleGradients?: false (stepped gradients at level 3 too), selectedOnly?: false, useArtboards?: true (one file per chosen artboard, artboards?/range?, {stem}_{artboard}.eps, the bounding box the artboard; with two or more, also the central file {stem}.eps first: the whole document, the bounding box the visible art; none when no art shows) | false (one file, the bounding box the visible art, y up from the first artboard's bottom-left corner, even when artboards are named; the default when none are named), format?: \"eps\", artboard?: i | artboards?: [i…] | range?: \"1-3, 5\" (the artboards written; naming them without useArtboards works as useArtboards: true)} → {path, bytes, warnings, files?}; no path → {dataBase64, …}. Transparency is flattened with the preset (EPS has none); the native document rides along in comments, for reopening the file as it was. Same as document.export {format: eps}. A key EPS doesn't take, and an unknown key inside flattener, are refused",
"{path?, level?: 2|3 (default; PostScript language level: 3 writes smooth gradients and masks transparent image pixels out, 2 steps gradients and writes those pixels white), previewFormat?: none|tiffBw|tiffColor (default: a TIFF preview other apps show), transparentPreview?: true (else on white), overprints?: preserve (default; paper white fills and strokes knock out with document.setup discardWhiteOverprint; white linked to a spot swatch that has a color, at a tint above 0%, still overprints)|discard, flattenerPreset?: \"medium\" (default; high, low or a saved preset: flattener.presets.list), flattener?: {the options of object.flattenTransparency over the preset}, embedFonts?: true (type is always written as outlines, so no fonts are needed), includeLinkedFiles?: false (the embedded document keeps linked images whole, not just their previews), thumbnails?: true (a PNG thumbnail in the file), cmykPostScript?: true (RGB documents written in CMYK), compatibleGradients?: false (stepped gradients at level 3 too), selectedOnly?: false, useArtboards?: true (one file per chosen artboard, artboards?/range?, {stem}_{artboard}.eps, the bounding box the artboard; with two or more, also the central file {stem}.eps first: the whole document, the bounding box the visible art; none when no art shows) | false (one file, the bounding box the visible art, y up from the first artboard's bottom-left corner, even when artboards are named; the default when none are named), format?: \"eps\", artboard?: i | artboards?: [i…] | range?: \"1-3, 5\" (the artboards written; naming them without useArtboards works as useArtboards: true)} → {path, bytes, warnings, files?}; no path → {dataBase64, …}. Transparency is flattened with the preset (EPS has none); the native document rides along in comments, for reopening the file as it was. Same as document.export {format: eps}. A key EPS doesn't take, and an unknown key inside flattener, are refused",
has_doc,
export_eps
)]
+7
View File
@@ -849,6 +849,13 @@ impl ReadFile {
r
}
/// Is part of the read still to do ([`Self::finish_read`]): the policies and the color mode of a
/// file that stopped for its profile question, or the linked files and the type of an answered
/// one?
pub fn read_left(&self) -> bool {
self.rest.is_some() || self.links_left.is_some()
}
/// The rest of [`read_for_open_asking`], once: the color management policies with the profile
/// answer (or as the policy says without one), the color mode `colorMode` asks for, the linked
/// files and the type. The app runs it off the UI thread once the question is answered.
+2 -1
View File
@@ -159,7 +159,8 @@ impl LoadOptions {
trust_editing_data,
embedded_fonts,
legacy_names,
native: true,
// The command's opt-out also skips the embedded VectorCraft document.
native: editing_data,
link_pages,
})
}
+18
View File
@@ -212,11 +212,29 @@ fn flattening_cropped_art_keeps_the_art_under_its_hidden_part() {
fn overprints_are_kept_or_discarded() {
let mut s = session(100.0, 100.0, 1);
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 30, "height": 30})).unwrap()["id"].as_u64().unwrap();
s.execute("paint.setFill", &json!({"ids": [id], "color": {"c": 100, "m": 0, "y": 0, "k": 0}})).unwrap();
s.execute("attributes.set", &json!({"ids": [id], "overprintFill": true})).unwrap();
let kept = postscript(&b64(&s.execute("document.exportEps", &json!({"previewFormat": "none"})).unwrap()));
assert!(kept.contains("true op\n"), "{kept}");
let dropped = postscript(&b64(&s.execute("document.exportEps", &json!({"previewFormat": "none", "overprints": "discard"})).unwrap()));
assert!(!dropped.contains("true op"));
// A white fill or stroke that overprints knocks out with Discard White Overprint (on by
// default), and overprints without it, as in PDF export.
let white = json!({"c": 0, "m": 0, "y": 0, "k": 0});
let filled = [json!({"ids": [id], "color": white}), json!({"ids": [id], "none": true})];
let stroked = [json!({"ids": [id], "none": true}), json!({"ids": [id], "color": white})];
for (i, [fill, stroke]) in [filled, stroked].iter().enumerate() {
s.execute("paint.setFill", fill).unwrap();
s.execute("paint.setStroke", stroke).unwrap();
s.execute("attributes.set", &json!({"ids": [id], "overprintFill": i == 0, "overprintStroke": i == 1})).unwrap();
s.execute("document.setup", &json!({"discardWhiteOverprint": true})).unwrap();
let knocked_out = postscript(&b64(&s.execute("document.exportEps", &json!({"previewFormat": "none"})).unwrap()));
assert!(!knocked_out.contains("true op"), "{i}: {knocked_out}");
s.execute("document.setup", &json!({"discardWhiteOverprint": false})).unwrap();
let overprinted = postscript(&b64(&s.execute("document.exportEps", &json!({"previewFormat": "none"})).unwrap()));
assert!(overprinted.contains("true op\n"), "{i}: {overprinted}");
}
}
#[test]
@@ -53,6 +53,27 @@ fn a_pdf_saved_with_preserve_editing_reopens_as_the_same_document() {
assert!(vectorcraft_pdf::editing(&b64(&v)).is_some_and(|e| e.intact));
}
#[test]
fn opening_a_preserve_editing_pdf_without_editing_data_imports_its_pages() {
let mut s = rich();
assert!(!s.doc().unwrap().doc.symbols.is_empty());
let exported = s.execute("document.exportPdf", &json!({"preserveEditing": true})).unwrap();
let reopened = s
.execute(
"document.open",
&json!({
"name": "rich.pdf",
"dataBase64": exported["dataBase64"],
"cropTo": "media",
"editingData": false,
}),
)
.unwrap();
assert_eq!(reopened["restored"], false, "{reopened}");
assert!(s.doc().unwrap().doc.symbols.is_empty(), "the PDF page has no native symbol definitions");
}
#[test]
fn pages_changed_elsewhere_open_as_artwork_with_a_warning() {
let mut s = rich();
+1 -1
View File
@@ -156,7 +156,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Artboard Options…",
["Window", "Artboards"],
None,
"{index | artboards: [{index, name?, color?, guideLabel?, locked?, showCenterMark?, showCrossHairs?, showVideoSafeAreas?, videoRulerPixelAspectRatio?, x?, y?, width?, height?}…] (several artboards in one undo step, each with its own fields; the art inside each before any of them changes goes with it, and an object inside several goes with the first listed that moves or scales its art), name?, color?: color (\"#rrggbb\", {c,m,y,k}, … as the paint commands take, #rrggbbaa and #rgba refused: the background color the canvas draws the artboard's paper in, multiplied with the Simulate Colored Paper color while that is on; exports and print leave it out) | null (no background color), guideLabel?: name | \"#rrggbb\" | null (the guide label: the canvas draws the artboard's own guides (guide.add with artboard) in this color instead of the guide color preference, selected ones still in the selection color; a layer color's name spelled exactly as Layer Options lists it (\"Light Blue\", \"Red\", …) or #rrggbb; null for none, which new artboards and older files have; screen-only, so exports and print leave it out; it can change on a locked artboard; an invalid value anywhere in the list changes nothing), locked?: bool (the Artboards panel's lock column: a locked artboard keeps its rectangle (a new x, y, width or height is an error unless locked is false), can't be moved, deleted or cut, and Rearrange and Fit to Artwork Bounds leave it as it is; the art on it (each object of a layer or sublayer whose bounds with strokes overlap it, a group as one object) acts as locked art until it is unlocked: clicks, marquees, select.set, select.all and the tools pass over it (art drawn or pasted onto it stays selected and editable until a selection leaves it out or it is moved off the locked artboards), it is deselected, and when another artboard moves or scales it stays unless lockedAndHidden), showCenterMark?: bool (Artboard Options' Show Center Mark: the canvas draws a mark at the artboard's center), showCrossHairs?: bool (Show Cross Hairs: the canvas draws a line from the middle of each side through the center), showVideoSafeAreas?: bool (Show Video Safe Areas: the canvas draws the action-safe area 3.5% and the title-safe area 5% in from each edge, as EBU R 95 sets them; the three are screen-only, as the artboard's edges are: exports and print leave them out), videoRulerPixelAspectRatio?: number 0.1–10 (Video Ruler Pixel Aspect Ratio: the width of one video pixel over its height, which View › Rulers › Show Video Rulers counts the artboard in; default 1, square pixels), x?, y?, width?, height?, moveArt?: bool (default false; a position-only change moves the contained art with its artboard), scaleArt?: bool (Scale Artwork with Artboard: resized, the artboard takes the art fully inside it (locked and hidden art only with lockedAndHidden?: bool, default prefs moveLockedWithArtboard) and its guides from its old rectangle onto the new one, each side by its own ratio; strokes/corners/patterns as object.scale), strokes?: bool, corners?: bool, patterns?: bool (the three as object.scale, for art that moves or scales with the artboard), lockedAndHidden?: bool (locked and hidden art moves along; default: the preference; recorded in the journal so a replay matches)} → null, or with scaleArt {scaled: the art scaled}; no undo step when nothing changes",
"{index | artboards: [{index, name?, color?, guideLabel?, locked?, showCenterMark?, showCrossHairs?, showVideoSafeAreas?, videoRulerPixelAspectRatio?, x?, y?, width?, height?}…] (several artboards in one undo step, each with its own fields; the art inside each before any of them changes goes with it, and an object inside several goes with the first listed that moves or scales its art), name?, color?: color (\"#rrggbb\", {c,m,y,k}, … as the paint commands take, #rrggbbaa and #rgba refused: the background color the canvas draws the artboard's paper in, multiplied with the Simulate Colored Paper color while that is on. Supported artboard exports and printing include it by default. This includes raster exports with `selectedOnly: true` when the output area is an artboard. Set `includeArtboardFill: false` on the export or print command to omit it. Exports cropped to selection bounds, artwork bounds, or an explicit raster region leave it out, as do formats that do not support artboard fills) | null (no background color), guideLabel?: name | \"#rrggbb\" | null (the guide label: the canvas draws the artboard's own guides (guide.add with artboard) in this color instead of the guide color preference, selected ones still in the selection color; a layer color's name spelled exactly as Layer Options lists it (\"Light Blue\", \"Red\", …) or #rrggbb; null for none, which new artboards and older files have; screen-only, so exports and print leave it out; it can change on a locked artboard; an invalid value anywhere in the list changes nothing), locked?: bool (the Artboards panel's lock column: a locked artboard keeps its rectangle (a new x, y, width or height is an error unless locked is false), can't be moved, deleted or cut, and Rearrange and Fit to Artwork Bounds leave it as it is; the art on it (each object of a layer or sublayer whose bounds with strokes overlap it, a group as one object) acts as locked art until it is unlocked: clicks, marquees, select.set, select.all and the tools pass over it (art drawn or pasted onto it stays selected and editable until a selection leaves it out or it is moved off the locked artboards), it is deselected, and when another artboard moves or scales it stays unless lockedAndHidden), showCenterMark?: bool (Artboard Options' Show Center Mark: the canvas draws a mark at the artboard's center), showCrossHairs?: bool (Show Cross Hairs: the canvas draws a line from the middle of each side through the center), showVideoSafeAreas?: bool (Show Video Safe Areas: the canvas draws the action-safe area 3.5% and the title-safe area 5% in from each edge, as EBU R 95 sets them; the three are screen-only, as the artboard's edges are: exports and print leave them out), videoRulerPixelAspectRatio?: number 0.1–10 (Video Ruler Pixel Aspect Ratio: the width of one video pixel over its height, which View › Rulers › Show Video Rulers counts the artboard in; default 1, square pixels), x?, y?, width?, height?, moveArt?: bool (default false; a position-only change moves the contained art with its artboard), scaleArt?: bool (Scale Artwork with Artboard: resized, the artboard takes the art fully inside it (locked and hidden art only with lockedAndHidden?: bool, default prefs moveLockedWithArtboard) and its guides from its old rectangle onto the new one, each side by its own ratio; strokes/corners/patterns as object.scale), strokes?: bool, corners?: bool, patterns?: bool (the three as object.scale, for art that moves or scales with the artboard), lockedAndHidden?: bool (locked and hidden art moves along; default: the preference; recorded in the journal so a replay matches)} → null, or with scaleArt {scaled: the art scaled}; no undo step when nothing changes",
has_doc,
artboard_set
),
+1 -1
View File
@@ -79,7 +79,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Nudge",
[],
None,
"{dx: -1|0|1, dy: -1|0|1, big?: bool (×10), copy?: bool, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move), interpolate?: bool (as path.moveAnchors's; default: prefs interpolateControlPoints)} arrow-key nudge by the keyboard increment (the selected anchors, else objects, along the x and y axes turned by the constrainAngle preference; else ruler guides, along the page axes)",
"{dx: -1|0|1, dy: -1|0|1, big?: bool (×10), copy?: bool, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move), interpolate?: bool (as path.moveAnchors's; default: prefs interpolateControlPoints)} arrow-key nudge by the keyboard increment (the selected anchors (a selected curved segment bends instead: its anchors stay and its handles keep their directions while its middle moves by the step), else objects, along the x and y axes turned by the constrainAngle preference; else ruler guides, along the page axes)",
has_selection_or_guides,
nudge
),
+4 -1
View File
@@ -347,7 +347,10 @@ pub(super) fn nudge(s: &mut Session, p: &Value) -> Result<Value> {
if dx == 0.0 && dy == 0.0 {
return ok();
}
return crate::cmd::path::move_anchors(s, &json!({ "dx": dx, "dy": dy, "patterns": p.get("patterns"), "interpolate": p.get("interpolate") }));
return crate::cmd::path::nudge_anchors(
s,
&json!({ "dx": dx, "dy": dy, "patterns": p.get("patterns"), "interpolate": p.get("interpolate") }),
);
}
if objects && s.doc()?.selection.is_empty() {
let copy = bool_or(p, "copy", false);
+105 -48
View File
@@ -4,7 +4,7 @@ use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_doc::{AnchorRef, Document, Node, NodeId, NodeKind, Scaling, Selection};
use vectorcraft_doc::{AnchorRef, Document, Node, NodeId, NodeKind, Scaling, SegmentRef, Selection};
use vectorcraft_geom::{Anchor, AnchorKind, Anchors, PathData, Point, SubPath, Vec2};
use super::create::anchor_from_json;
@@ -140,7 +140,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add Anchor Point",
[],
None,
"{id, subpath?, segment, t: 0..1} add an anchor at t on the segment → {anchor}; the direct-selected anchors and selected segments keep the same points (a selected segment it splits stays selected as its two halves), and a path that isn't selected becomes the selection with the new anchor direct-selected",
"{id, subpath?, segment, t: 0..1, selectAnchor?: bool (the path becomes the selection with only the new anchor direct-selected, also when it is selected)} add an anchor at t on the segment → {anchor}; the direct-selected anchors and selected segments keep the same points (a selected segment it splits stays selected as its two halves), and a path that isn't selected becomes the selection with the new anchor direct-selected",
has_doc,
insert_anchor
),
@@ -244,19 +244,48 @@ fn close(s: &mut Session, p: &Value) -> Result<Value> {
}
pub(crate) fn move_anchors(s: &mut Session, p: &Value) -> Result<Value> {
let d = Vec2::new(number_or(p, "dx", 0.0, "path.moveAnchors")?, number_or(p, "dy", 0.0, "path.moveAnchors")?);
check_switches(p, &["patterns", "interpolate"], "path.moveAnchors")?;
move_selected(s, p, false)
}
/// The arrow keys with direct-selected anchors or segments: as `path.moveAnchors`, except that a
/// selected curved segment bends ([`SubPath::nudge_segment`]).
pub(crate) fn nudge_anchors(s: &mut Session, p: &Value) -> Result<Value> {
move_selected(s, p, true)
}
/// Move the selection by `(dx, dy)`: its direct-selected anchors with their handles, and the
/// objects selected whole. With `bend`, each selected curved segment bends instead and its anchors
/// stay, except an anchor that also ends a selected straight segment, which moves with it.
fn move_selected(s: &mut Session, p: &Value, bend: bool) -> Result<Value> {
const C: &str = "path.moveAnchors";
let d = Vec2::new(number_or(p, "dx", 0.0, C)?, number_or(p, "dy", 0.0, C)?);
check_switches(p, &["patterns", "interpolate"], C)?;
// An object selected in a symbol instance's art stays where the symbol puts it.
super::edit::refuse_symbol_part(s)?;
let st = s.doc()?;
let mut sel = st.selection.clone();
let (held, bends) = if bend { held_segments(&st.doc, &mut sel, d) } else { (false, vec![]) };
// Segments that hold their anchors and don't bend, with nothing else to move, change nothing.
if held && bends.is_empty() && sel.whole().is_empty() && sel.guides.is_empty() && sel.anchors.values().all(BTreeSet::is_empty) {
return ok();
}
// Objects selected whole move as objects, and their pattern tiles move with them when
// `patterns` (default: General › Transform Pattern Tiles) is on.
let whole = s.doc()?.selection.whole();
let sc = Scaling { patterns: super::object::transform_patterns(s, p, &whole)?, ..Scaling::default() };
let interpolate = interpolates_handles(s, p, "path.moveAnchors")?;
transform_anchors(s, "Move", vectorcraft_geom::Affine::translate(d), sc, interpolate)?;
// Transform Again repeats a move that moved something; a drag records it when it commits.
let sc = Scaling { patterns: super::object::transform_patterns(s, p, &sel.whole())?, ..Scaling::default() };
let interpolate = interpolates_handles(s, p, C)?;
s.edit(if bends.is_empty() { "Move" } else { "Reshape" }, |doc, _| {
transform_selected(doc, &sel, vectorcraft_geom::Affine::translate(d), sc, interpolate)?;
for &(id, si, seg) in &bends {
if let Some(sp) = path_mut(doc, id)?.subpaths.get_mut(si) {
sp.nudge_segment(seg, d);
}
}
Ok(())
})?;
// Transform Again repeats a move that moved something; a drag records it when it commits. A
// move that held segments' anchors is not one move of the selection.
let st = s.doc_mut()?;
if st.interaction.is_none() && (d.x != 0.0 || d.y != 0.0) {
if !held && st.interaction.is_none() && (d.x != 0.0 || d.y != 0.0) {
let options = json!({ "copy": false, "patterns": sc.patterns, "interpolate": interpolate });
st.last_transform = Some(crate::LastTransform::Matrix(vectorcraft_geom::Affine::translate(d), options));
st.last_perspective = None;
@@ -264,6 +293,29 @@ pub(crate) fn move_anchors(s: &mut Session, p: &Value) -> Result<Value> {
ok()
}
/// Take the anchors of `sel`'s selected curved segments out of its `anchors`, except those that
/// also end a selected straight segment, and list the segments that a bend by `d` changes. Also
/// whether any curved segment is selected.
fn held_segments(doc: &Document, sel: &mut Selection, d: Vec2) -> (bool, Vec<(NodeId, usize, usize)>) {
let (mut held, mut bends) = (false, vec![]);
for (&id, refs) in &sel.segments {
let (Some(path), Some(set)) = (doc.node(id).and_then(Node::path_data), sel.anchors.get_mut(&id)) else { continue };
let ends = |(si, seg): SegmentRef| path.subpaths.get(si).map(|sp| [(si, seg), (si, (seg + 1) % sp.anchors.len())]);
let curved = |&(si, seg): &SegmentRef| path.subpaths.get(si).is_some_and(|sp| seg < sp.segment_count() && !sp.segment_is_line(seg));
let moved: BTreeSet<AnchorRef> = refs.iter().filter(|r| !curved(r)).filter_map(|&r| ends(r)).flatten().collect();
for &(si, seg) in refs.iter().filter(|r| curved(r)) {
held = true;
for end in ends((si, seg)).into_iter().flatten().filter(|e| !moved.contains(e)) {
set.remove(&end);
}
if path.subpaths.get(si).is_some_and(|sp| sp.nudged_handles(seg, d).is_some()) {
bends.push((id, si, seg));
}
}
}
(held, bends)
}
/// Interpolate Control Points: does a move of direct-selected anchors re-map the handles of the
/// segments beside them (`interpolate` param, else General › Interpolate Control Points When
/// Moving Anchors)? Noted in the journal, so a replay re-maps them alike whatever the preference
@@ -276,56 +328,59 @@ pub(crate) fn interpolates_handles(s: &mut Session, p: &Value, cmd: &str) -> Res
Ok(on)
}
/// [`transform_selected`] on the active document's selection, as one undo step `label`.
pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_geom::Affine, sc: Scaling, interpolate: bool) -> Result<()> {
let sel = s.doc()?.selection.clone();
s.edit(label, |doc, _| transform_selected(doc, &sel, xf, sc, interpolate))
}
/// Apply `xf` to the direct-selected anchors, their handles with them, and (with `sc`) to the
/// objects selected whole (those with no entry in the selection's `anchors`). An object inside
/// objects selected whole (those with no entry in `sel`'s `anchors`). An object inside
/// another selected object, such as a path in a selected group, moves once, with that object.
/// When `xf` is a move and `interpolate` is on, the handles of each segment with one moved end
/// are re-mapped ([`move_interpolating_handles`]).
pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_geom::Affine, sc: Scaling, interpolate: bool) -> Result<()> {
let sel = s.doc()?.selection.clone();
let ids = super::edit::outermost(&s.doc()?.doc, sel.objects.clone());
fn transform_selected(doc: &mut Document, sel: &Selection, xf: vectorcraft_geom::Affine, sc: Scaling, interpolate: bool) -> Result<()> {
let ids = super::edit::outermost(doc, sel.objects.clone());
let c = xf.as_coeffs();
let is_translation = (c[0] - 1.0).abs() < 1e-9 && c[1].abs() < 1e-9 && c[2].abs() < 1e-9 && (c[3] - 1.0).abs() < 1e-9;
let delta = vectorcraft_geom::Vec2::new(c[4], c[5]);
s.edit(label, |doc, _| {
for id in &ids {
match sel.anchors.get(id) {
Some(set) => {
let path = path_mut(doc, *id)?;
// Only an exact move takes the interpolating path: a near-identity scale or
// turn still transforms the anchors as asked.
if interpolate && c[..4] == [1.0, 0.0, 0.0, 1.0] {
move_interpolating_handles(path, set, delta);
} else {
for &(si, ai) in set {
if let Some(a) = path.anchor_mut(si, ai) {
*a = a.transform(xf);
}
for id in &ids {
match sel.anchors.get(id) {
Some(set) => {
let path = path_mut(doc, *id)?;
// Only an exact move takes the interpolating path: a near-identity scale or
// turn still transforms the anchors as asked.
if interpolate && c[..4] == [1.0, 0.0, 0.0, 1.0] {
move_interpolating_handles(path, set, delta);
} else {
for &(si, ai) in set {
if let Some(a) = path.anchor_mut(si, ai) {
*a = a.transform(xf);
}
}
// A pixel-aligned path, or the pixel-aligned compound path that holds it, snaps
// to the pixel grid again after its anchors move.
let top = compound_or_self(doc, *id);
if let Some(n) = doc.node_mut(top) {
super::object::snap_if_aligned(n);
}
}
None => {
if let Some(n) = doc.node_mut(*id) {
n.transform(xf, sc);
super::object::keep_pixel_aligned(n, sc);
}
super::object::keep_compound_aligned(doc, *id, sc);
// A pixel-aligned path, or the pixel-aligned compound path that holds it, snaps
// to the pixel grid again after its anchors move.
let top = compound_or_self(doc, *id);
if let Some(n) = doc.node_mut(top) {
super::object::snap_if_aligned(n);
}
}
}
if is_translation && (delta.x != 0.0 || delta.y != 0.0) {
for &i in &sel.guides {
doc.edit_ruler_guide(i, |g| *g = g.moved(delta));
None => {
if let Some(n) = doc.node_mut(*id) {
n.transform(xf, sc);
super::object::keep_pixel_aligned(n, sc);
}
super::object::keep_compound_aligned(doc, *id, sc);
}
}
Ok(())
})
}
if is_translation && (delta.x != 0.0 || delta.y != 0.0) {
for &i in &sel.guides {
doc.edit_ruler_guide(i, |g| *g = g.moved(delta));
}
}
Ok(())
}
/// Move the anchors `set` of `path` by `d`, their handles with them, then re-map the two handles
@@ -2155,6 +2210,7 @@ fn insert_anchor(s: &mut Session, p: &Value) -> Result<Value> {
let si = usize_opt(p, "subpath", "path.insertAnchor")?.unwrap_or(0);
let seg = index_opt(p, "segment", "path.insertAnchor")?.ok_or_else(|| bad("path.insertAnchor", "missing segment"))?;
let t = number_or(p, "t", 0.5, "path.insertAnchor")?.clamp(0.0, 1.0);
let select_anchor = switch_or(p, "selectAnchor", false, "path.insertAnchor")?;
let idx = s.edit("Add Anchor Point", |d, sel| {
let path = path_mut(d, id)?;
let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?;
@@ -2164,8 +2220,9 @@ fn insert_anchor(s: &mut Session, p: &Value) -> Result<Value> {
let idx = sp.insert_anchor(seg, t);
renumber_after_insert(sel, id, si, idx);
// A path that wasn't selected becomes the selection, its new anchor direct-selected, so
// the point added shows and can be edited at once (#4237).
if !sel.contains(id) {
// the point added shows and can be edited at once (#4237). `selectAnchor` does the same
// for a path that is selected.
if select_anchor || !sel.contains(id) {
sel.clear();
sel.add(id);
sel.anchors.entry(id).or_default().insert((si, idx));
+322 -53
View File
@@ -43,6 +43,11 @@
//! A filter whose manifest lists `inputs` (plug-in API level 2) is also given the selected type,
//! images or symbol instances of those kinds, to read only: its output must return each of them
//! unchanged ([`objects::decode_output_with`]).
//!
//! A filter, or a live effect's command, whose manifest lists `context` (plug-in API level 3) is
//! also given the parts of the active document it names in `_context.document`, whether or not
//! anything is selected: the settings, artboards, layers and swatches, as plain values
//! ([`context`]).
use std::collections::HashMap;
use std::sync::{Arc, Mutex, RwLock};
@@ -52,10 +57,13 @@ use vectorcraft_doc::{Document, Effect, Node};
use vectorcraft_plugins::{Budget, Command, Kind, Plugin, effect, export, objects, registry, safe_mode};
use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, cmd, has_doc, ids_param, str_param, switch_or};
use crate::store::StoreTurn;
use crate::store::{PluginLoad, StoreTurn};
use vectorcraft_plugins::permissions::{self, Grant, GrantToken, Permission};
mod context;
pub use context::{CONTEXT_FUEL_PER_ITEM, MAX_CONTEXT_BYTES, MAX_CONTEXT_ITEMS};
/// What a plug-in error looks like to the user. A run the caller cancelled changed nothing.
fn err(e: vectorcraft_plugins::Error) -> EngineError {
match e {
@@ -105,6 +113,9 @@ pub fn describe(p: &Plugin) -> Value {
if !m.output_kinds.is_empty() {
v["outputKinds"] = json!(m.output_kinds);
}
if !m.context.is_empty() {
v["context"] = json!(m.context);
}
if m.paint_output {
v["paintOutput"] = json!(true);
}
@@ -257,15 +268,25 @@ impl FilterRun {
params["_context"]["mode"] = json!("command");
params["_context"]["command"] = json!(cmd.id);
}
// The parts of the document its manifest asks for (`context`), selection or not. Each row
// costs the run [`context::CONTEXT_FUEL_PER_ITEM`] instructions.
let sections = m.context_sections();
let mut charged = 0;
if !sections.is_empty() && may.contains(&Permission::DocRead) {
let given = context::document_context(st, &sections, c)?;
params["_context"]["document"] = given.value;
charged = (given.items as u64).saturating_mul(context::CONTEXT_FUEL_PER_ITEM);
}
let params = serde_json::to_vec(&params).map_err(|e| bad(c, e.to_string()))?;
// The input and the parameters may use half the plug-in's memory together.
let capacity = (plugin.limits().max_memory_bytes / 2).min(i32::MAX as usize).saturating_sub(params.len());
let (input, read_only) = objects::encode_input_with(&st.doc, &inputs, &kinds, capacity).map_err(err)?;
let document = (st.uid, st.revision);
let limits = match s.prefs.plugin_instruction_budget {
let mut limits = match s.prefs.plugin_instruction_budget {
crate::PluginBudget::Normal => plugin.limits().clone(),
crate::PluginBudget::Large => plugin.large_limits(),
};
limits.fuel_base = limits.fuel_base.saturating_sub(charged);
Ok(FilterRun { plugin, command, input, params, inputs, read_only, parent, document, limits })
}
@@ -299,11 +320,17 @@ impl FilterRun {
}
/// The limits it runs under: the plug-in's, with the Plug-in Instruction Budget in force when
/// it was made.
/// it was made, less what its document context costs.
pub fn limits(&self) -> &vectorcraft_plugins::Limits {
&self.limits
}
/// The parameters it hands the plug-in, `_context` included.
#[cfg(test)]
pub(crate) fn params_json(&self) -> Value {
serde_json::from_slice(&self.params).unwrap_or(Value::Null)
}
/// Does the plug-in call commands (its manifest's `commandAllowlist`)? Then it runs only in the
/// session ([`FilterRun::run_with_calls`]).
pub fn calls(&self) -> bool {
@@ -1013,12 +1040,16 @@ thread_local! {
pub(crate) static BEFORE_GRANT_STORED: 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) };
/// Tests: runs once in the next `plugin.reload` on this thread after its load started and before
/// it installs, as another session loading a folder in between would.
pub(crate) static BEFORE_RELOAD_INSTALLS: 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.
/// installed, throughout by `plugin.remove`, and while the loads of the stored plug-ins
/// ([`Session::load_stored_plugins`]) and of a plug-ins folder install what they loaded: these run
/// one after the other across sessions. It is not held while the modules load, so a session's
/// plug-in commands don't wait for another session's loads.
static PLUGIN_CHANGES: Mutex<()> = Mutex::new(());
/// Takes [`PLUGIN_CHANGES`], waiting while another session holds it.
@@ -1036,6 +1067,21 @@ pub(crate) fn hold_plugin_changes() -> std::sync::MutexGuard<'static, ()> {
}
}
/// Takes [`PLUGIN_CHANGES`] when no other session holds it, without waiting.
pub(crate) fn try_hold_plugin_changes() -> Option<std::sync::MutexGuard<'static, ()>> {
match PLUGIN_CHANGES.try_lock() {
Ok(held) => Some(held),
Err(std::sync::TryLockError::Poisoned(e)) => Some(e.into_inner()),
Err(std::sync::TryLockError::WouldBlock) => None,
}
}
/// Tests: whether [`PLUGIN_CHANGES`] could be taken now.
#[cfg(test)]
pub(crate) fn plugin_changes_free() -> bool {
!matches!(PLUGIN_CHANGES.try_lock(), Err(std::sync::TryLockError::WouldBlock))
}
/// `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
@@ -1285,31 +1331,61 @@ fn load_path(_: &str) -> Result<(Plugin, Vec<u8>)> {
Err(EngineError::Other("installing from a path is not available on the web; pass the module as `dataBase64`".into()))
}
/// The plug-in folder last loaded, the plug-in store whose grants it was loaded with, and what
/// happened.
static FOLDER: Mutex<Option<(String, Option<std::path::PathBuf>, Value)>> = Mutex::new(None);
/// The plug-in folder last loaded, the plug-in store whose grants it was loaded with, what
/// happened, the load whose report it is ([`FOLDER_LOADS`]), and whether a file failed because no
/// loader thread was left to load it ([`vectorcraft_plugins::loader::NO_THREAD`]), so that the next
/// [`sync_prefs`] loads the folder again.
type FolderRecord = (String, Option<std::path::PathBuf>, Value, u64, bool);
/// The [`FolderRecord`] of the plug-in folder last loaded.
static FOLDER: Mutex<Option<FolderRecord>> = Mutex::new(None);
/// The number of the last folder load [`sync_prefs`] or `plugin.reload` started. [`sync_prefs`]
/// keeps it in [`FOLDER`] while its load runs, so only that load replaces or clears the record, and
/// a `plugin.reload` keeps its report only when no load started after it.
static FOLDER_LOADS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
/// Loads the Additional Plug-ins Folder preference (`*.wasm`) when it is set and it, or the
/// session's plug-in store, has changed since the last load. Runs whenever preferences are applied
/// (startup, `prefs.set`). Native only.
pub(crate) fn sync_prefs(s: &Session) {
let folder = s.prefs.plugins_folder.trim();
/// (startup, `prefs.set`). With [`Session::load_plugins_in_background`] on, it returns while the
/// modules load, and `plugin.list` reports the folder as loading until they are installed. Off, it
/// returns once the folder's plug-ins are installed, also while another session is still loading
/// the same folder. Native only.
pub(crate) fn sync_prefs(s: &mut Session) {
let folder = s.prefs.plugins_folder.trim().to_string();
// In Safe Mode nothing loads, and the folder is loaded once it ends ([`load_prefs_folder`]).
if folder.is_empty() || safe_mode::active() {
return;
}
let mut last = FOLDER.lock().unwrap_or_else(|e| e.into_inner());
if last.as_ref().is_some_and(|(f, store, _)| f == folder && *store == s.plugin_dir) {
// This session's own load of the folder, still running, is waited for unless loads go on in the
// background.
if s.plugin_loads.iter().any(|l| matches!(l, PluginLoad::Folder(f) if f.loads(&folder, &s.plugin_dir))) {
if !s.plugin_loads_in_background {
s.finish_plugin_loads();
}
return;
}
*last = Some((folder.to_string(), s.plugin_dir.clone(), load_folder(s, folder)));
let token = {
let mut last = FOLDER.lock().unwrap_or_else(|e| e.into_inner());
// A folder another session is still loading is loaded here too: that load may end with its
// session, and this one returns once its own plug-ins are installed.
// A load in which a file found no thread to load it is tried again.
if last.as_ref().is_some_and(|(f, store, r, _, retry)| *f == folder && *store == s.plugin_dir && r["loading"] != true && !retry) {
return;
}
let token = FOLDER_LOADS.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
*last = Some((folder.clone(), s.plugin_dir.clone(), json!({"folder": folder, "loading": true}), token, false));
token
};
let load = start_folder(s, &folder, Some(token));
s.queue_plugin_load(PluginLoad::Folder(load));
}
/// The Additional Plug-ins Folder preference was cleared from `old`: when `old` is the folder last
/// loaded, it is forgotten, so setting the preference to it again loads it again.
pub(crate) fn forget_prefs_folder(old: &str) {
let mut last = FOLDER.lock().unwrap_or_else(|e| e.into_inner());
if last.as_ref().is_some_and(|(f, _, _)| f == old.trim()) {
if last.as_ref().is_some_and(|(f, _, _, _, _)| f == old.trim()) {
*last = None;
}
}
@@ -1329,42 +1405,232 @@ pub fn load_prefs_folder(s: &mut Session) {
sync_prefs(s);
}
/// Loads the plug-ins in `folder`, those that list permissions only when `s` has them granted
/// ([`Session::plugin_approved`], with the store's grants read once) → its report; saves the
/// disabled list when loading changed it.
/// The modules of a folder loading ([`registry::FolderLoad`]); the web build has none.
#[cfg(not(target_arch = "wasm32"))]
fn load_folder(s: &Session, folder: &str) -> Value {
if let Err(e) = crate::file_access::check_read(folder) {
return json!({"folder": folder, "error": e});
}
// A file in it may be a link to one elsewhere.
let allow = |f: &std::path::Path| match f.to_str() {
Some(f) => crate::file_access::check_read(f),
// A lossy name would check another file than the one loaded.
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 or process finishes writing the store first. When the
// store can't be locked, the folder still loads, and the store isn't written.
let _held = hold_plugin_changes();
let turn = s.plugin_store_turn().unwrap_or_else(|_| StoreTurn::unheld());
match registry::load_folder_where(std::path::Path::new(folder), allow, s.plugin_folder_approver()) {
Ok(r) => {
for id in &r.loaded {
s.attach_plugin_storage(&turn, id);
}
if r.disabled_changed {
s.store_disabled_plugins_in(&turn);
}
json!({"folder": folder, "loaded": r.loaded, "failed": r.failed.iter().map(|(f, e)| json!({"file": f, "error": e})).collect::<Vec<_>>(), "leftOut": r.left_out})
type FolderModules = registry::FolderLoad;
#[cfg(target_arch = "wasm32")]
type FolderModules = std::convert::Infallible;
/// A load of the plug-ins in a folder ([`start_folder`]), which [`install_folder`] installs as the
/// modules load and [`end_folder`] ends.
pub(crate) struct FolderPending {
folder: String,
/// The plug-in store whose grants it loads with.
store: Option<std::path::PathBuf>,
/// The load's number in [`FOLDER`] when [`end_folder`] keeps its report as the folder last
/// loaded ([`sync_prefs`]).
record: Option<u64>,
/// A `plugin.reload`'s load: [`end_folder`] keeps its report as the folder last loaded unless a
/// load started after it.
reload: bool,
/// The modules loading, or the report of a folder that can't be loaded; `None` once ended.
load: Option<std::result::Result<FolderModules, Value>>,
/// Whether the modules not installed yet were dropped ([`FolderPending::cancel`]).
canceled: bool,
}
impl FolderPending {
/// Whether every module has been installed or reported.
pub(crate) fn done(&self) -> bool {
match &self.load {
#[cfg(not(target_arch = "wasm32"))]
Some(Ok(load)) => load.done(),
#[cfg(target_arch = "wasm32")]
Some(Ok(never)) => match *never {},
Some(Err(_)) | None => true,
}
Err(e) => json!({"folder": folder, "error": e.to_string()}),
}
/// Starts the modules loading, unless they started already.
pub(crate) fn start(&mut self) {
#[cfg(not(target_arch = "wasm32"))]
if let Some(Ok(load)) = &mut self.load {
load.start();
}
}
/// The installs and removals its modules are checked against (`None`: the folder couldn't be
/// listed, or the load ended).
pub(crate) fn changes(&self) -> Option<&registry::LoadChanges> {
match &self.load {
#[cfg(not(target_arch = "wasm32"))]
Some(Ok(load)) => Some(load.changes()),
#[cfg(target_arch = "wasm32")]
Some(Ok(never)) => match *never {},
Some(Err(_)) | None => None,
}
}
/// [`FolderPending::changes`], to adopt an earlier load's.
pub(crate) fn changes_mut(&mut self) -> Option<&mut registry::LoadChanges> {
match &mut self.load {
#[cfg(not(target_arch = "wasm32"))]
Some(Ok(load)) => Some(load.changes_mut()),
#[cfg(target_arch = "wasm32")]
Some(Ok(never)) => match *never {},
Some(Err(_)) | None => None,
}
}
/// Whether something can be installed or reported now, without waiting.
pub(crate) fn ready(&mut self) -> bool {
match &mut self.load {
#[cfg(not(target_arch = "wasm32"))]
Some(Ok(load)) => load.ready(),
#[cfg(target_arch = "wasm32")]
Some(Ok(never)) => match *never {},
Some(Err(_)) | None => true,
}
}
/// Waits until the next module in file-name order has loaded or failed.
pub(crate) fn wait(&mut self) {
#[cfg(not(target_arch = "wasm32"))]
if let Some(Ok(load)) = &mut self.load {
load.wait();
}
}
/// Drops the modules not installed yet, leaving it [`FolderPending::done`]; [`end_folder`]
/// then keeps no report as the folder last loaded.
pub(crate) fn cancel(&mut self) {
#[cfg(not(target_arch = "wasm32"))]
if let Some(Ok(load)) = &mut self.load {
load.cancel();
}
self.canceled = true;
}
/// Whether it is a load of `folder` with the plug-in store `store`.
pub(crate) fn loads(&self, folder: &str, store: &Option<std::path::PathBuf>) -> bool {
self.folder == folder && self.store == *store
}
}
impl Drop for FolderPending {
/// A load dropped before it ended (its session closed) leaves no folder reported as loading, so
/// the next session that applies the preference loads it.
fn drop(&mut self) {
if let Some(token) = self.record.filter(|_| self.load.is_some()) {
let mut last = FOLDER.lock().unwrap_or_else(|e| e.into_inner());
if last.as_ref().is_some_and(|(_, _, _, t, _)| *t == token) {
*last = None;
}
}
}
}
/// Starts loading the plug-ins in `folder` on worker threads ([`registry::FolderLoad`]); `record`:
/// the load's number in [`FOLDER`], whose record [`end_folder`] replaces with the report.
#[cfg(not(target_arch = "wasm32"))]
fn start_folder(s: &Session, folder: &str, record: Option<u64>) -> FolderPending {
let pending =
|load| FolderPending { folder: folder.to_string(), store: s.plugin_dir.clone(), record, reload: false, load: Some(load), canceled: false };
if let Err(e) = crate::file_access::check_read(folder) {
return pending(Err(json!({"folder": folder, "error": e})));
}
// A file in it may be a link to one elsewhere. Each file is checked again on its worker
// thread, in the scope in force here (the automation roots and the script gate), as the
// folder itself was.
let scope = crate::file_access::ScopeHandle::capture_now();
let allow = move |f: &std::path::Path| {
scope.clone().run(|| match f.to_str() {
Some(f) => crate::file_access::check_read(f),
// A lossy name would check another file than the one loaded.
None if crate::file_access::current().is_none() => Ok(()),
None => Err(format!("automation path rejected: {} isn't valid text", f.display())),
})
};
// The modules start loading once the loads queued before them are done.
pending(registry::FolderLoad::list(std::path::Path::new(folder), allow).map_err(|e| json!({"folder": folder, "error": e.to_string()})))
}
#[cfg(target_arch = "wasm32")]
fn load_folder(_: &Session, folder: &str) -> Value {
json!({"folder": folder, "error": "plug-in folders are not available on the web"})
fn start_folder(s: &Session, folder: &str, record: Option<u64>) -> FolderPending {
let load = Err(json!({"folder": folder, "error": "plug-in folders are not available on the web"}));
FolderPending { folder: folder.to_string(), store: s.plugin_dir.clone(), record, reload: false, load: Some(load), canceled: false }
}
/// Installs what `load` has loaded so far, in file-name order up to the first module still
/// loading, without waiting: those that list permissions only when `s` has them granted
/// ([`Session::plugin_approved`], with the store's grants read once). Runs while
/// [`hold_plugin_changes`] and `turn` are held, so a `plugin.install` in another session or process
/// finishes writing the store first; when the store can't be locked, the folder still installs,
/// and the store isn't written.
pub(crate) fn install_folder(s: &mut Session, load: &mut FolderPending, turn: &StoreTurn) {
#[cfg(not(target_arch = "wasm32"))]
if let Some(Ok(load)) = &mut load.load
&& !load.done()
{
for id in load.install_ready(s.plugin_folder_approver()) {
s.attach_plugin_storage(turn, &id);
}
// A disabled plug-in's file matched by its id is saved in the same turn.
if load.disabled_changed() && s.store_disabled_plugins_in(turn) {
load.disabled_saved();
}
}
#[cfg(target_arch = "wasm32")]
let _ = (s, load, turn);
}
/// Ends `load` once [`FolderPending::done`], while [`hold_plugin_changes`] and `turn` are held, so
/// the grants of ids whose module lists no permissions are forgotten while no `plugin.install` can
/// record one for another module → its report; saves the disabled list when loading changed it.
pub(crate) fn end_folder(s: &mut Session, mut load: FolderPending, turn: &StoreTurn) -> Value {
let (report, retry) = match load.load.take() {
#[cfg(not(target_arch = "wasm32"))]
Some(Ok(modules)) => {
let r = modules.finish();
if r.disabled_changed {
s.store_disabled_plugins_in(turn);
}
let failed = r.failed.iter().map(|(f, e)| json!({"file": f, "error": e})).collect::<Vec<_>>();
(json!({"folder": load.folder, "loaded": r.loaded, "failed": failed, "leftOut": r.left_out}), r.no_thread)
}
#[cfg(target_arch = "wasm32")]
Some(Ok(never)) => match never {},
Some(Err(report)) => (report, false),
None => (Value::Null, false),
};
if let Some(token) = load.record {
let mut last = FOLDER.lock().unwrap_or_else(|e| e.into_inner());
// A later load, or a `plugin.reload`, replaced it meanwhile. A canceled load leaves no
// folder reported, so the next session that applies the preference loads it. A
// `plugin.reload`'s report replaces the record unless a load started after it, or the
// folder couldn't be loaded.
let current = if load.reload {
FOLDER_LOADS.load(std::sync::atomic::Ordering::Relaxed) == token && report.get("error").is_none()
} else {
last.as_ref().is_some_and(|(_, _, _, t, _)| *t == token)
};
if current {
*last = if load.canceled { None } else { Some((load.folder.clone(), load.store.clone(), report.clone(), token, retry)) };
}
}
report
}
/// Loads the plug-ins in `folder` and installs them, waiting for every module → the report, which is
/// kept as the folder last loaded unless a load started after this one.
fn load_folder_now(s: &mut Session, folder: &str) -> Value {
let token = FOLDER_LOADS.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
let mut load = start_folder(s, folder, Some(token));
load.reload = true;
#[cfg(test)]
if let Some(between) = BEFORE_RELOAD_INSTALLS.take() {
between();
}
s.finish_plugin_load(PluginLoad::Folder(load))
}
/// Tests: the next [`sync_prefs`] treats the folder last loaded as one in which a file found no
/// loader thread to load it.
#[cfg(test)]
pub(crate) fn folder_found_no_thread() {
if let Some(record) = FOLDER.lock().unwrap_or_else(|e| e.into_inner()).as_mut() {
record.4 = true;
}
}
fn reload(s: &mut Session, p: &Value) -> Result<Value> {
@@ -1376,11 +1642,12 @@ fn reload(s: &mut Session, p: &Value) -> Result<Value> {
if folder.is_empty() {
return Err(bad(C, "no folder: pass `path` or set Preferences › Plug-ins & Scratch Disks › Additional Plug-ins Folder"));
}
let report = load_folder(s, &folder);
// Loads started earlier install first, so this one's plug-ins replace theirs.
s.finish_plugin_loads();
let report = load_folder_now(s, &folder);
if let Some(e) = report.get("error").and_then(Value::as_str) {
return Err(EngineError::Other(e.to_string()));
}
*FOLDER.lock().unwrap_or_else(|e| e.into_inner()) = Some((folder, s.plugin_dir.clone(), report.clone()));
Ok(report)
}
@@ -1429,7 +1696,7 @@ fn shown_report(mut report: Value) -> Value {
}
fn list(_: &mut Session, _: &Value) -> Result<Value> {
let folder = FOLDER.lock().unwrap_or_else(|e| e.into_inner()).as_ref().map(|(_, _, r)| shown_report(r.clone()));
let folder = FOLDER.lock().unwrap_or_else(|e| e.into_inner()).as_ref().map(|(_, _, r, _, _)| shown_report(r.clone()));
let disabled: Vec<Value> = safe_mode::disabled().iter().map(shown_item).collect();
Ok(
json!({"plugins": registry::list().iter().map(|p| describe_installed(p)).collect::<Vec<_>>(), "folder": folder, "safeMode": safe_mode::active(), "disabled": disabled}),
@@ -1437,13 +1704,15 @@ fn list(_: &mut Session, _: &Value) -> Result<Value> {
}
/// `plugin.safeMode`: whether Safe Mode is on and why, the plug-ins disabled for the next launch,
/// and the plug-in the last launch was loading when it stopped while the user hasn't chosen yet.
/// and the plug-ins the last launch was loading when it stopped while the user hasn't chosen yet.
fn safe_mode_state(_: &mut Session, _: &Value) -> Result<Value> {
let pending: Vec<Value> = safe_mode::previous().iter().map(shown_item).collect();
Ok(json!({
"active": safe_mode::active(),
"source": safe_mode::source().map(safe_mode::Source::name),
"disabled": safe_mode::disabled().iter().map(shown_item).collect::<Vec<_>>(),
"pendingItem": safe_mode::previous().map(|i| shown_item(&i)),
"pendingItem": pending.first(),
"pendingItems": pending,
}))
}
@@ -1582,7 +1851,7 @@ pub fn specs() -> Vec<CommandSpec> {
"List Plug-ins",
[],
None,
"{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's or importer's format id, plugin.<id>, for document.export or document.open's importer, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 or 2), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.<id>.<command id>, which runs it), label, params (doc), paramsSchema, menu?: {path: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}",
"{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's or importer's format id, plugin.<id>, for document.export or document.open's importer, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), context?: [\"settings\"|\"artboards\"|\"layers\"|\"swatches\"] (the parts of the active document a filter's runs and its or a live effect's commands are given in _context.document, with or without a selection, see docs/plugins.md), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1, 2 or 3), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.<id>.<command id>, which runs it), label, params (doc), paramsSchema, menu?: {path: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}",
always,
list
),
@@ -1654,7 +1923,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Safe Mode",
[],
None,
"{} → {active: bool (no plug-in loads or runs: plugin.install, .run, .reload and exporters fail, live effects draw their object's geometry unchanged and the objects keep their effects), source: \"flag\" (started with --safe-mode) | \"startup\" (the user chose Safe Mode, or hasn't chosen yet, after a launch that stopped while a plug-in was loading) | null, disabled: [{id, file, name, label}] (turned off for the next launch; id is null for one known only by its file; under automation read roots, a file outside them is named by its file name here and in pendingItem, and plugin.setEnabled takes that name), pendingItem: {id, file, name, label} | null (the plug-in the last launch was loading when it stopped, until the user chooses; it may not be what stopped it)}. Safe Mode is chosen at launch, never by a command",
"{} → {active: bool (no plug-in loads or runs: plugin.install, .run, .reload and exporters fail, live effects draw their object's geometry unchanged and the objects keep their effects), source: \"flag\" (started with --safe-mode) | \"startup\" (the user chose Safe Mode, or hasn't chosen yet, after a launch that stopped while a plug-in was loading) | null, disabled: [{id, file, name, label}] (turned off for the next launch; id is null for one known only by its file; under automation read roots, a file outside them is named by its file name here and in pendingItem, and plugin.setEnabled takes that name), pendingItem: {id, file, name, label} | null (the first of pendingItems), pendingItems: [{id, file, name, label}] (the plug-ins the last launch was loading when it stopped, oldest first, until the user chooses; any of them, or none, may be what stopped it)}. Safe Mode is chosen at launch, never by a command",
always,
safe_mode_state
),
+147
View File
@@ -0,0 +1,147 @@
//! A plug-in run's document context (`_context.document`): the parts of the active document its
//! manifest's `context` asks for ([`ContextSection`]), read when the run is prepared, with or
//! without a selection. It holds plain values only: names, flags, rectangles and colors, never an
//! object, a file path or a link target.
use serde_json::{Value, json};
use vectorcraft_doc::{ColorMode, LayerColor, Node, NodeKind};
use vectorcraft_plugins::ContextSection;
use super::super::{Result, bad};
use crate::DocState;
/// Most rows (artboards, layers and sublayers, and swatches together) a document context holds.
pub const MAX_CONTEXT_ITEMS: usize = 10_000;
/// Most bytes the rows of a document context take as JSON.
pub const MAX_CONTEXT_BYTES: usize = 4 * 1024 * 1024;
/// Instructions each row costs: they come off the run's instruction budget.
pub const CONTEXT_FUEL_PER_ITEM: u64 = 1_000;
/// A document context, and the rows it holds.
pub(super) struct DocumentContext {
pub value: Value,
pub items: usize,
}
/// The document context of `sections` for a run of command `c` on `st`: `{revision}` and a key
/// for each section asked for. A document with more than [`MAX_CONTEXT_ITEMS`] rows in them, or
/// rows of more than [`MAX_CONTEXT_BYTES`], is an error, before any row is made in the first case.
pub(super) fn document_context(st: &DocState, sections: &[ContextSection], c: &str) -> Result<DocumentContext> {
let d = &st.doc;
let layers = if sections.contains(&ContextSection::Layers) { layer_rows(d) } else { Vec::new() };
let swatches = || super::super::swatch::listed_swatches(d, true, d.swatch_groups.iter().collect());
let mut items = 0;
for s in sections {
items += match s {
ContextSection::Settings => 0,
ContextSection::Artboards => d.artboards.len(),
ContextSection::Layers => layers.len(),
ContextSection::Swatches => swatches().count(),
};
}
let too_large = || {
bad(
c,
format!(
"the document information the plug-in asks for is too large to hand over: at most {MAX_CONTEXT_ITEMS} artboards, layers and swatches in {MAX_CONTEXT_BYTES} bytes"
),
)
};
if items > MAX_CONTEXT_ITEMS {
return Err(too_large());
}
let mut bytes = 0usize;
let mut row = |v: Value| -> Result<Value> {
bytes = bytes.saturating_add(serde_json::to_vec(&v).map_or(usize::MAX, |b| b.len() + 1));
if bytes > MAX_CONTEXT_BYTES { Err(too_large()) } else { Ok(v) }
};
let active = active_artboard(st);
let mut out = json!({"revision": st.revision});
for s in sections {
let value = match s {
ContextSection::Settings => {
let board = active.and_then(|i| d.artboards.get(i));
row(json!({
"name": st.title(),
"colorMode": match d.color_mode {
ColorMode::Rgb => "rgb",
ColorMode::Cmyk => "cmyk",
},
"units": d.units.label(),
"width": board.map(|a| a.rect.width()),
"height": board.map(|a| a.rect.height()),
"bleed": d.setup.bleed,
"rasterEffectsPpi": d.raster_ppi(),
"activeArtboard": board.map(|a| a.id),
}))?
}
ContextSection::Artboards => {
let rows = d.artboards.iter().enumerate().map(|(i, a)| {
let r = a.rect;
row(json!({"id": a.id, "index": i, "name": a.name, "rect": [r.x0, r.y0, r.x1, r.y1], "active": active == Some(i)}))
});
Value::Array(rows.collect::<Result<_>>()?)
}
ContextSection::Layers => {
let rows = layers.iter().map(|l| {
let n = l.node;
row(json!({
"id": n.id.0, "parentId": l.parent, "depth": l.depth, "name": n.display_name(),
"visible": n.visible, "locked": n.locked, "template": l.template, "color": l.color.label_text(),
"sublayers": l.sublayers, "current": st.active_layer == Some(n.id),
}))
});
Value::Array(rows.collect::<Result<_>>()?)
}
ContextSection::Swatches => {
let rows = swatches().map(|(w, g)| row(super::super::swatch::swatch_json(w, g)));
Value::Array(rows.collect::<Result<_>>()?)
}
};
out[s.name()] = value;
}
Ok(DocumentContext { value: out, items })
}
/// Is `n` a layer or sublayer?
fn is_layer(n: &Node) -> bool {
matches!(n.kind, NodeKind::Layer { .. })
}
/// A layer or sublayer, where it is in the layer tree, and what its row reports besides the
/// node's own name and flags.
struct LayerRow<'a> {
node: &'a Node,
/// Its parent layer's id; `None` for a top-level layer.
parent: Option<u64>,
/// 0 for a top-level layer, 1 for its sublayers, and so on.
depth: usize,
color: LayerColor,
template: bool,
/// The sublayers it holds directly.
sublayers: usize,
}
/// Every layer and sublayer of `d`, depth first in document order (bottom first within each
/// parent). The walk keeps its own stack, so deep nesting can't overflow the thread's.
fn layer_rows(d: &vectorcraft_doc::Document) -> Vec<LayerRow<'_>> {
let mut out = Vec::new();
let mut stack: Vec<(&Node, Option<u64>, usize)> = d.layers.iter().rev().map(|l| (l.as_ref(), None, 0)).collect();
while let Some((node, parent, depth)) = stack.pop() {
let NodeKind::Layer { color, template, children, .. } = &node.kind else { continue };
let sublayers = children.iter().filter(|c| is_layer(c)).count();
stack.extend(children.iter().rev().filter(|c| is_layer(c)).map(|c| (c.as_ref(), Some(node.id.0), depth + 1)));
out.push(LayerRow { node, parent, depth, color: *color, template: *template, sublayers });
}
out
}
/// The index of the view's active artboard ([`DocState::active_artboard`]): when the document no
/// longer has it, the artboard the document opened on, else the first; `None` with no artboards.
fn active_artboard(st: &DocState) -> Option<usize> {
let d = &st.doc;
let at = |id: Option<u32>| id.and_then(|id| d.artboards.iter().position(|a| a.id == id));
at(st.active_artboard).or_else(|| at(d.opened_artboard)).or((!d.artboards.is_empty()).then_some(0))
}
+1
View File
@@ -141,6 +141,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[
p!("disableAutoAddDelete", "General", "Options", "Disable Auto Add/Delete", bool),
p!("interpolateControlPoints", "General", "Options", "Interpolate Control Points When Moving Anchors", bool),
p!("deleteKeepsPathsJoined", "General", "Options", "Delete Removes Anchor Points and Keeps Paths Joined", bool),
p!("doubleClickAddsAnchorPoints", "General", "Options", "Double-Click Adds Anchor Points", bool),
p!("usePreciseCursors", "General", "Options", "Use Precise Cursors", bool),
p!("showToolTips", "General", "Options", "Show Tool Tips", bool),
p!("showToolCards", "General", "Options", "Show Tool Cards", bool),
+5
View File
@@ -472,6 +472,11 @@ impl RecoveryStore for FolderStore {
Self::create_area(dir)?;
Self::own_area(dir)?;
}
// A read refuses a link (`read`), and a write must too: the atomic writer replaces the
// target of a link, which would put the copy over a file outside the store.
if std::fs::symlink_metadata(&f).is_ok_and(|m| m.file_type().is_symlink()) {
return Err(format!("{}: not a plain file", f.display()));
}
vectorcraft_format::write_atomic(&f, bytes).map_err(|e| Self::file_error(&f, &e))
}
fn remove(&self, name: &str) -> std::result::Result<(), String> {
+18 -8
View File
@@ -1012,18 +1012,28 @@ fn swatch_list(s: &mut Session, p: &Value) -> Result<Value> {
Some(g) => vec![d.swatch_groups.iter().find(|x| x.name == g).ok_or_else(|| bad("swatch.list", format!("no colour group `{g}`")))?],
None => d.swatch_groups.iter().collect(),
};
// The built-in Registration swatch lists after None, as the panel shows it.
let none = d.swatches.iter().take_while(|w| w.paint.is_none()).count();
let (specials, rest) = d.swatches.split_at(none);
let all = specials.iter().chain([vectorcraft_color::swatch::registration()]).chain(rest);
let ungrouped = all.filter(|_| only.is_none()).map(|w| swatch_json(w, None));
let grouped = groups.iter().flat_map(|g| g.swatches.iter().map(|w| swatch_json(w, Some(&g.name))));
let swatches: Vec<Value> = ungrouped.chain(grouped).collect();
let swatches: Vec<Value> = listed_swatches(d, only.is_none(), groups.clone()).map(|(w, g)| swatch_json(w, g)).collect();
let groups: Vec<Value> =
groups.iter().map(|g| json!({"name": g.name, "swatches": g.swatches.iter().map(|w| &w.name).collect::<Vec<_>>()})).collect();
Ok(json!({"swatches": swatches, "groups": groups}))
}
/// The swatches `swatch.list` lists, in its order, each with the name of the colour group it is
/// in: with `ungrouped`, the swatches outside groups (the built-in Registration swatch after None,
/// as the panel shows it), then those of `groups`.
pub(super) fn listed_swatches<'a>(
d: &'a Document,
ungrouped: bool,
groups: Vec<&'a SwatchGroup>,
) -> impl Iterator<Item = (&'a Swatch, Option<&'a str>)> + 'a {
let none = d.swatches.iter().take_while(|w| w.paint.is_none()).count();
let (specials, rest) = d.swatches.split_at(none);
let all = specials.iter().chain([vectorcraft_color::swatch::registration()]).chain(rest);
let ungrouped = all.filter(move |_| ungrouped).map(|w| (w, None));
let grouped = groups.into_iter().flat_map(|g| g.swatches.iter().map(move |w| (w, Some(g.name.as_str()))));
ungrouped.chain(grouped)
}
fn swatch_sort(s: &mut Session, _: &Value) -> Result<Value> {
s.edit("Sort Swatches", |d, _| {
// [None] and other bracketed specials stay first, like the reference app.
@@ -1252,7 +1262,7 @@ fn swatch_rename_group(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(C, format!("a swatch or color group named `{name}` already exists")));
}
// A drag still in progress is a step of its own, so canceling or undoing it leaves the rename.
if !s.previewing && s.batch_stash.is_none() && s.in_interaction() {
if !s.previewing && s.batch_stash.is_none() && (s.in_interaction() || s.holds_interaction()) {
super::settle_interaction(s)?;
}
s.edit("Color Group Options", |d, _| {
+7 -2
View File
@@ -340,11 +340,16 @@ pub struct ColorTable {
type Shift = ([u8; 3], [u8; 3]);
/// The most colours a colour table list holds.
const MAX_TABLE: usize = 256;
pub const MAX_TABLE: usize = 256;
/// The error for a deletion that would leave the color table no color for the pixels.
pub const KEEP_ONE: &str = "colorTable.deleted: at least one color has to stay in the color table";
/// The error for a colour table list `what` (`colorTable.<what>`) with more than [`MAX_TABLE`] colours.
pub fn too_many(what: &str) -> String {
format!("colorTable.{what}: at most {MAX_TABLE} colours")
}
impl ColorTable {
/// Whether the table is a Custom one: a color was deleted or the palette is fixed.
pub fn is_custom(&self) -> bool {
@@ -353,7 +358,7 @@ impl ColorTable {
fn colors(list: &[String], what: &str) -> std::result::Result<Vec<[u8; 3]>, String> {
if list.len() > MAX_TABLE {
return Err(format!("colorTable.{what}: at most {MAX_TABLE} colours"));
return Err(too_many(what));
}
list.iter().map(|h| Self::rgb(h).ok_or_else(|| format!("colorTable.{what}: `{h}` is not a colour such as \"#ff8800\""))).collect()
}