mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-27 16:59:43 +01:00
Merge main into feat/retype-installed-fonts
This commit is contained in:
commit
bf782369fc
568 files changed
+37351
-3478
No files matched your search
@@ -846,8 +846,9 @@ pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000;
|
||||
pub(crate) use addons::{DecodedImages, refresh_color_masks};
|
||||
/// Packaging Tools' blanks and the objects their print leaves out, for the Fold Preview window.
|
||||
pub use addons::{fold_source, print_hidden};
|
||||
/// Document Info's category titles and the Objects category's count labels.
|
||||
pub use docinfo::{CATEGORIES, OBJECT_LABELS};
|
||||
/// Document Info's category titles, the Objects category's count labels, and how its image rows
|
||||
/// write a resolution and a number of bytes.
|
||||
pub use docinfo::{CATEGORIES, OBJECT_LABELS, byte_size, ppi_number};
|
||||
pub use docmenu::guide_indexes;
|
||||
pub(crate) use edit::{Unrecorded, settle_interaction, typing_in_progress};
|
||||
pub(crate) use object::bounds_rewrite;
|
||||
|
||||
@@ -52,7 +52,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Print Ink Fixes",
|
||||
["Object", "Plug-ins", "Color Effects"],
|
||||
None,
|
||||
"{scope?: \"selection\" (the selection, or `ids`; by default, the document while nothing is selected) | \"document\" (every layer), inkLimit?: total ink % 1..400 (0 or left out: off), excludePureBlack?: true (black-only and grey colours keep their ink), removeWhiteOverprint?: false (white fills and strokes, and colorized images with a white color, stop overprinting), overprintBlack?: black % 1..100 (black-only and grey fills and strokes this dark or darker overprint, as edit.colors.overprintBlack; 0 or left out: off), textOnly?: false (Overprint Black on type only), fill?: true, stroke?: true, ids?: [id…]} prepare a CMYK document's inks for print as one undo step: CMYK colours (solid, gradient stops, gradient meshes) with more total ink than inkLimit are scaled down to it (colours of spot swatches and Registration stay), white overprint is removed and black overprint set. Refused in RGB documents (File › Document Color Mode › CMYK Color first). On a path directly in a graph series, the graph also stores a paint the ink limit changes on the topmost visible fill or stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, inkLimited: paints and meshes scaled, whiteOverprintRemoved: objects, blackOverprinted: objects}",
|
||||
"{scope?: \"selection\" (the selection, or `ids`; by default, the document while nothing is selected) | \"document\" (every layer), inkLimit?: total ink % 1..400 (0 or left out: off), excludePureBlack?: true (black-only and grey colours keep their ink), removeWhiteOverprint?: false (white fills and strokes, and colorized images with a white color, stop overprinting; a white linked to a spot swatch at a tint above 0% is an ink and keeps it), overprintBlack?: black % 1..100 (black-only and grey fills and strokes this dark or darker overprint, as edit.colors.overprintBlack; 0 or left out: off), textOnly?: false (Overprint Black on type only), fill?: true, stroke?: true, ids?: [id…]} prepare a CMYK document's inks for print as one undo step: CMYK colours (solid, gradient stops, gradient meshes) with more total ink than inkLimit are scaled down to it (colours of spot swatches and Registration stay), white overprint is removed and black overprint set. Refused in RGB documents (File › Document Color Mode › CMYK Color first). On a path directly in a graph series, the graph also stores a paint the ink limit changes on the topmost visible fill or stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, inkLimited: paints and meshes scaled, whiteOverprintRemoved: objects, blackOverprinted: objects}",
|
||||
has_doc,
|
||||
print_fixes::run
|
||||
),
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
//! Print Ink Fixes (`addon.color.printFixes`, Object › Plug-ins › Color Effects › Print Ink
|
||||
//! Fixes…): a CMYK document's inks made ready for print in one undo step. Colours with more total
|
||||
//! ink than the limit are scaled down to it, white fills and strokes stop overprinting, and black
|
||||
//! ink than the limit are scaled down to it, paper white fills and strokes stop overprinting, and black
|
||||
//! ones start to, as Edit › Edit Colors › Overprint Black sets it.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::Color;
|
||||
use vectorcraft_color::swatch::REGISTRATION;
|
||||
use vectorcraft_doc::overprint::{OverprintBlack, is_white};
|
||||
use vectorcraft_doc::overprint::{OverprintBlack, is_paper_white};
|
||||
use vectorcraft_doc::{ColorMode, Node, NodeKind};
|
||||
|
||||
use super::super::super::colorcmds::{Recolor, Scope, keeping_series_paint};
|
||||
@@ -78,8 +79,9 @@ impl Fixes {
|
||||
}
|
||||
|
||||
/// Remove white overprint from `n`'s own fills and strokes and its characters': true when
|
||||
/// that changed anything.
|
||||
fn unset_white(&self, n: &mut Node) -> bool {
|
||||
/// that changed anything. A white linked to one of the spot inks `inks` is an ink and keeps
|
||||
/// overprinting ([`is_paper_white`]).
|
||||
fn unset_white(&self, n: &mut Node, inks: &BTreeSet<String>) -> bool {
|
||||
let mut changed = false;
|
||||
let mut off = |aimed: bool, white: bool, flag: &mut bool| {
|
||||
if aimed && white && *flag {
|
||||
@@ -89,31 +91,32 @@ impl Fixes {
|
||||
};
|
||||
for it in &mut n.appearance.items {
|
||||
let aimed = if it.is_fill() { self.fill } else { self.stroke };
|
||||
let white = is_white(it.paint());
|
||||
let white = is_paper_white(it.paint(), inks);
|
||||
off(aimed, white, it.overprint_mut());
|
||||
}
|
||||
if let NodeKind::Text(t) = &mut n.kind {
|
||||
for r in &mut t.runs {
|
||||
off(self.fill, is_white(&r.style.fill), &mut r.style.overprint_fill);
|
||||
off(self.stroke, is_white(&r.style.stroke), &mut r.style.overprint_stroke);
|
||||
off(self.fill, is_paper_white(&r.style.fill, inks), &mut r.style.overprint_fill);
|
||||
off(self.stroke, is_paper_white(&r.style.stroke, inks), &mut r.style.overprint_stroke);
|
||||
}
|
||||
}
|
||||
// A colorized image's color is its fill.
|
||||
if n.colorize_overprints() {
|
||||
let white = n.extras().colorize.as_deref().is_some_and(is_white);
|
||||
let white = n.extras().colorize.as_deref().is_some_and(|p| is_paper_white(p, inks));
|
||||
off(self.fill, white, &mut n.extras_mut().colorize_overprint);
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// The overprint fixes on `n` and everything inside it: (objects whose white overprint was
|
||||
/// removed, objects set to overprint black).
|
||||
fn overprint(&self, n: &mut Node, black: &OverprintBlack, spots: &[String]) -> (usize, usize) {
|
||||
let white = usize::from(self.remove_white_overprint && self.unset_white(n));
|
||||
/// removed, objects set to overprint black). `spots`: the document's spot swatch names; `inks`:
|
||||
/// those that linked colors print as ([`vectorcraft_doc::Document::spot_ink_names`]).
|
||||
fn overprint(&self, n: &mut Node, black: &OverprintBlack, spots: &[String], inks: &BTreeSet<String>) -> (usize, usize) {
|
||||
let white = usize::from(self.remove_white_overprint && self.unset_white(n, inks));
|
||||
let blacks = self.overprint_black > 0.0 && (!self.text_only || matches!(n.kind, NodeKind::Text(_)));
|
||||
let mut counts = (white, usize::from(blacks && black.apply(n, spots)));
|
||||
for c in n.children_mut().into_iter().flatten().filter(|c| !c.is_ruler_guide()) {
|
||||
let (w, b) = self.overprint(Arc::make_mut(c), black, spots);
|
||||
let (w, b) = self.overprint(Arc::make_mut(c), black, spots, inks);
|
||||
counts = (counts.0 + w, counts.1 + b);
|
||||
}
|
||||
counts
|
||||
@@ -159,10 +162,10 @@ pub(super) fn run(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if !fixes.remove_white_overprint && fixes.overprint_black <= 0.0 {
|
||||
return Ok(ink);
|
||||
}
|
||||
let spots = d.spot_names();
|
||||
let (spots, inks) = (d.spot_names(), d.spot_ink_names());
|
||||
for id in &ids {
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
let (w, b) = fixes.overprint(n, &black, &spots);
|
||||
let (w, b) = fixes.overprint(n, &black, &spots, &inks);
|
||||
(white, blacks) = (white + w, blacks + b);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -101,6 +101,20 @@ fn white_overprint_goes_and_black_overprint_comes_at_the_threshold() {
|
||||
assert_eq!(s.execute(C, &json!({"overprintBlack": 90, "fill": false})).unwrap()["changed"], 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_white_spot_ink_keeps_its_overprint() {
|
||||
let white = cmyk(0.0, 0.0, 0.0, 0.0);
|
||||
let (mut s, ids) = doc(&[(white.clone(), true), (white.clone(), true)]);
|
||||
s.execute("swatch.new", &json!({"name": "Opaque White", "color": white, "spot": true})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [ids[1].0]})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"swatch": "Opaque White"})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert!(fill(&s, ids[1]).1, "the swatch keeps the overprint");
|
||||
let v = s.execute(C, &json!({"removeWhiteOverprint": true})).unwrap();
|
||||
assert_eq!(v["whiteOverprintRemoved"], 1, "{v}");
|
||||
assert_eq!([fill(&s, ids[0]).1, fill(&s, ids[1]).1], [false, true], "paper white stops; the spot white is an ink");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_requests_and_rgb_documents_are_refused() {
|
||||
let (mut s, ids) = doc(&[(cmyk(100.0, 100.0, 100.0, 100.0), true)]);
|
||||
|
||||
@@ -4,8 +4,8 @@
|
||||
//! ([`corners`]), the Parametric Shape Tool's shapes ([`shape`]), the Shared Edge Merge Tool's
|
||||
//! merges with Keep Shared Points Together ([`shared_edge`]), Divide into Dashes, Expand Dashes
|
||||
//! into Paths, Trim at Crossings ([`trim`]), Smooth Bridge ([`bridge`]), Common Tangents
|
||||
//! ([`tangents`]), Tangent Circle ([`tangent_circle`]) and Add Bounding Rectangle and Add
|
||||
//! Bounding Circle ([`bounding`]).
|
||||
//! ([`tangents`]), Tangent Circle ([`tangent_circle`]), Add Bounding Rectangle and Add
|
||||
//! Bounding Circle ([`bounding`]) and Add Inscribed Circle ([`inscribed`]).
|
||||
//! Its tools, panels and submenu (Object › Plug-ins › Path Precision Tools) are the tools crate's
|
||||
//! and the UI's.
|
||||
|
||||
@@ -14,6 +14,7 @@ mod bridge;
|
||||
mod corners;
|
||||
#[cfg(test)]
|
||||
mod effect_tests;
|
||||
mod inscribed;
|
||||
mod shape;
|
||||
mod shared_edge;
|
||||
mod tangent_circle;
|
||||
@@ -190,6 +191,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
v.extend(tangent_circle::specs());
|
||||
v.extend(tangents::specs());
|
||||
v.extend(bounding::specs());
|
||||
v.extend(inscribed::specs());
|
||||
v
|
||||
}
|
||||
|
||||
|
||||
@@ -49,7 +49,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
|
||||
/// Enabled with a selection that is not an object of a symbol instance's art, which
|
||||
/// [`selected_roots_to_transform`] refuses.
|
||||
fn whole_objects(s: &Session) -> std::result::Result<(), String> {
|
||||
pub(super) fn whole_objects(s: &Session) -> std::result::Result<(), String> {
|
||||
has_selection(s)?;
|
||||
no_symbol_part(s)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
//! Add Inscribed Circle: the largest live circle inside each selected closed path or compound
|
||||
//! path. The circle is the pathops crate's
|
||||
//! ([`inscribed_circle`](vectorcraft_pathops::addons::pathtools::inscribed_circle)).
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, LiveShape, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{Affine, FillRule, PathData};
|
||||
use vectorcraft_pathops::addons::pathtools::{self as pt, InscribedError};
|
||||
|
||||
use super::super::super::edit::selected_roots_to_transform;
|
||||
use super::super::super::{CommandSpec, bad, cmd};
|
||||
use super::bounding::whole_objects;
|
||||
use crate::{Result, Session};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
/// The command.
|
||||
pub(crate) const COMMAND: &str = "addon.pathtools.inscribedCircle";
|
||||
/// The undo step's name.
|
||||
const LABEL: &str = "Add Inscribed Circle";
|
||||
/// How far a live circle's four curves reach past a true circle, as a share of its radius: at
|
||||
/// most 0.0273%, about 20° from each axis.
|
||||
const CIRCLE_BULGE: f64 = 3e-4;
|
||||
|
||||
pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"addon.pathtools.inscribedCircle",
|
||||
"Add Inscribed Circle",
|
||||
["Object", "Plug-ins", "Path Precision Tools"],
|
||||
None,
|
||||
"{} draw the largest live circle inside each selected closed path or compound path (a path of a compound path selected on its own counts as a path): the circle lies in the area the path fills under its fill rule, so holes and the overlaps of crossing subpaths count as the fill shows them, and before it is drawn its radius is within 0.02 pt of the largest (when the filled area's box is at least 10 pt across on its narrower side; for a smaller one, within a five-hundredth of that side; a curve whose control polygon is longer than 4096² times the flattening tolerance, half the search's precision (83,886 pt at 0.005 pt), is flattened more coarsely, and the circle can be smaller by as much; a curved hole narrower than the flattening tolerance can also make it smaller; a shape that flattening would close up or move off its curves is flattened finer, down to 1/65,536 of the tolerance). The drawn circle's four curves reach up to 0.03% of its radius past a true circle, so it is drawn 0.03% smaller and stays inside where it touches. Holes and gaps narrower than 1e-6 pt close up, and edges can move by as much, as in the other path operations. Strokes and effects are left out. The circles get the current paint and go on top of the current layer or of the isolated group, as other new art; inside an isolated compound path they join it and take its appearance; they are selected; one undo step. It is an error, with the document unchanged, when a selected object is not a closed path or compound path (\"object N is not a closed path or compound path\"; an open path has no inside), when it fills no area (\"object N fills no area\"), and when its outline has more than 262,144 anchors (in subpaths of two or more) or more than 262,144 straight pieces once flattened, or the searches of the selected objects together measure more than 134,217,728 distances from a point to an edge, or one search keeps more than 1,048,576 cells waiting, or the shape is so thin for its length that it flattens to no area even at the finest tolerance (\"object N is too complex to measure\") → {id: the first circle, ids}",
|
||||
whole_objects,
|
||||
inscribed_circle
|
||||
)]
|
||||
}
|
||||
|
||||
/// The outline of path or compound path `id` and its fill rule; `None` for anything else, an open
|
||||
/// path, or a compound path with an open member.
|
||||
fn outline(d: &Document, id: NodeId) -> Option<(PathData, FillRule)> {
|
||||
let n = d.node(id)?;
|
||||
let (paths, rule): (Vec<&PathData>, FillRule) = match &n.kind {
|
||||
NodeKind::Path { path, rule, .. } => (vec![path], *rule),
|
||||
NodeKind::Compound { children, rule } => (children.iter().filter_map(|c| c.path_data()).collect(), *rule),
|
||||
_ => return None,
|
||||
};
|
||||
let subpaths: Vec<_> = paths.iter().flat_map(|p| p.subpaths.iter()).filter(|sp| !sp.anchors.is_empty()).collect();
|
||||
if subpaths.is_empty() || subpaths.iter().any(|sp| !sp.closed) {
|
||||
return None;
|
||||
}
|
||||
Some((PathData::new(subpaths.into_iter().cloned().collect()), rule))
|
||||
}
|
||||
|
||||
fn inscribed_circle(s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
// The roots leave out selected layers, which are not paths either.
|
||||
let st = s.doc()?;
|
||||
if let Some(layer) = st.selection.objects.iter().find(|id| st.doc.node(**id).is_some_and(Node::is_layer)) {
|
||||
return Err(bad(COMMAND, format!("object {} is not a closed path or compound path", layer.0)));
|
||||
}
|
||||
let roots = selected_roots_to_transform(s)?;
|
||||
let d = &s.doc()?.doc;
|
||||
let mut circles = vec![];
|
||||
// The searches share one work limit, so the command stays bounded however many objects are
|
||||
// selected.
|
||||
let mut work = pt::MAX_INSCRIBED_WORK;
|
||||
for id in roots {
|
||||
let value = id.0;
|
||||
let Some((path, rule)) = outline(d, id) else {
|
||||
return Err(bad(COMMAND, format!("object {value} is not a closed path or compound path")));
|
||||
};
|
||||
let c = pt::inscribed_circle_within(&path, rule, &mut work).map_err(|e| match e {
|
||||
InscribedError::NoArea => bad(COMMAND, format!("object {value} fills no area")),
|
||||
InscribedError::TooComplex => bad(COMMAND, format!("object {value} is too complex to measure")),
|
||||
})?;
|
||||
circles.push(c);
|
||||
}
|
||||
// Path art: inside an isolated compound path, the circles join it, as Tangent Circle's do.
|
||||
let parent = s.doc()?.target_parent_for_path()?;
|
||||
let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width);
|
||||
let ids = s.edit(LABEL, |d, sel| {
|
||||
let mut ids = vec![];
|
||||
for c in &circles {
|
||||
// Smaller by the curves' bulge, so the drawn circle stays inside where it touches.
|
||||
let (r, at) = (c.radius / (1.0 + CIRCLE_BULGE), c.center);
|
||||
let live = LiveShape::Ellipse { w: 2.0 * r, h: 2.0 * r, pie: (0.0, 360.0), xf: Affine::translate((at.x - r, at.y - r)) };
|
||||
let kind = NodeKind::Path { path: live.to_path(), rule: FillRule::NonZero, live: Some(Box::new(live)), clipping: false, guide: false };
|
||||
let mut n = Node::new(d.alloc_id(), kind);
|
||||
look.apply(d, &mut n);
|
||||
ids.push(n.id);
|
||||
d.insert(parent, usize::MAX, n)?;
|
||||
}
|
||||
sel.set(ids.iter().copied());
|
||||
Ok(ids)
|
||||
})?;
|
||||
let first = ids.first().map_or(0, |id| id.0);
|
||||
Ok(json!({ "id": first, "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() }))
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
//! Add Inscribed Circle: the largest circle in a square, a concave shape and a ring compound path
|
||||
//! under its fill rule, one circle per object as one undo step, the drawn circle inside where its
|
||||
//! curves bulge, and the errors that leave the document as it was.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{LiveShape, NodeId, NodeKind};
|
||||
use vectorcraft_geom::Point;
|
||||
|
||||
use super::COMMAND;
|
||||
use crate::Session;
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn id_of(v: &Value) -> NodeId {
|
||||
NodeId(v["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
fn ids_of(v: &Value) -> Vec<NodeId> {
|
||||
v["ids"].as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect()
|
||||
}
|
||||
|
||||
fn select(s: &mut Session, ids: &[NodeId]) {
|
||||
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
|
||||
}
|
||||
|
||||
fn undo_len(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
fn object_count(s: &Session) -> usize {
|
||||
let mut n = 0;
|
||||
s.doc().unwrap().doc.walk(|_| n += 1);
|
||||
n
|
||||
}
|
||||
|
||||
/// The center and radius of the live circle `id`.
|
||||
fn circle(s: &Session, id: NodeId) -> (Point, f64) {
|
||||
match &s.doc().unwrap().doc.node(id).unwrap().kind {
|
||||
NodeKind::Path { live: Some(live), .. } => match live.as_ref() {
|
||||
LiveShape::Ellipse { w, h, xf, .. } => {
|
||||
assert!((w - h).abs() < 1e-9, "a circle, not an ellipse");
|
||||
(*xf * Point::new(w / 2.0, h / 2.0), w / 2.0)
|
||||
}
|
||||
other => panic!("not a live ellipse: {other:?}"),
|
||||
},
|
||||
other => panic!("not a live shape: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The smallest drawn radius for a largest circle of radius `largest`: smaller by the curves'
|
||||
/// bulge, and by the search's 0.02 pt.
|
||||
fn least(largest: f64) -> f64 {
|
||||
largest / (1.0 + super::CIRCLE_BULGE) - 0.02
|
||||
}
|
||||
|
||||
/// The command on the selection fails with a message holding `want`, and the document is as it was.
|
||||
fn refused(s: &mut Session, want: &str) {
|
||||
let (undo, objects) = (undo_len(s), object_count(s));
|
||||
let e = s.execute(COMMAND, &json!({})).unwrap_err().to_string();
|
||||
assert!(e.contains(want), "{e}");
|
||||
assert_eq!((undo_len(s), object_count(s)), (undo, objects));
|
||||
}
|
||||
|
||||
/// The circle in a square sits at its center and touches its sides, gets the current paint, goes
|
||||
/// on top of the layer and is selected; one undo removes it.
|
||||
#[test]
|
||||
fn a_square_gets_the_circle_that_touches_its_sides() {
|
||||
let mut s = session();
|
||||
let sq = id_of(&s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap());
|
||||
let (undo, objects) = (undo_len(&s), object_count(&s));
|
||||
let out = s.execute(COMMAND, &json!({})).unwrap();
|
||||
let id = id_of(&out);
|
||||
let (center, r) = circle(&s, id);
|
||||
assert!((center - Point::new(150.0, 150.0)).hypot() < 0.02 && r <= 50.0 + 1e-6 && r > least(50.0), "{center:?} {r}");
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![id]);
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let parent = d.parent_of(sq).unwrap();
|
||||
assert_eq!(d.parent_of(id), Some(parent));
|
||||
assert_eq!(d.node(parent).unwrap().children().unwrap().last().map(|n| n.id), Some(id), "on top of the layer");
|
||||
// The current paint, as the rectangle drawn before got it.
|
||||
let (n, r) = (d.node(id).unwrap(), d.node(sq).unwrap());
|
||||
assert_eq!((n.appearance.fill_paint(), n.appearance.stroke_paint()), (r.appearance.fill_paint(), r.appearance.stroke_paint()));
|
||||
assert_eq!(undo_len(&s), undo + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(object_count(&s), objects);
|
||||
}
|
||||
|
||||
/// The circle in an L sits in its corner, inside the shape, where the box's center is outside.
|
||||
#[test]
|
||||
fn a_concave_shape_gets_the_circle_in_its_corner() {
|
||||
let mut s = session();
|
||||
let anchors = [(0, 0), (100, 0), (100, 30), (30, 30), (30, 100), (0, 100)].map(|(x, y)| json!({"x": x, "y": y}));
|
||||
s.execute("path.create", &json!({"anchors": anchors, "closed": true})).unwrap();
|
||||
let id = id_of(&s.execute(COMMAND, &json!({})).unwrap());
|
||||
let (center, r) = circle(&s, id);
|
||||
let largest = 30.0 * std::f64::consts::SQRT_2 / (1.0 + std::f64::consts::SQRT_2);
|
||||
assert!(r <= largest + 1e-6 && r > least(largest), "{r}");
|
||||
assert!(center.x < 30.0 && center.y < 30.0, "{center:?}");
|
||||
}
|
||||
|
||||
/// A compound path of two concentric circles: under even-odd the inner one is a hole, and the
|
||||
/// circle lies in the ring beside it. Under nonzero it is a hole while the two circles turn
|
||||
/// opposite ways, and with both turning the same way the circle fills the outer one.
|
||||
#[test]
|
||||
fn a_ring_compound_path_gets_a_circle_by_its_fill_rule() {
|
||||
let mut s = session();
|
||||
let outer = id_of(&s.execute("shape.ellipse", &json!({"x": 100, "y": 100, "width": 200, "height": 200})).unwrap());
|
||||
let inner = id_of(&s.execute("shape.ellipse", &json!({"x": 160, "y": 160, "width": 80, "height": 80})).unwrap());
|
||||
select(&mut s, &[outer, inner]);
|
||||
let compound = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap());
|
||||
let ring = Point::new(200.0, 200.0);
|
||||
let cases = [("evenOdd", false, 70.0, 30.0), ("nonZero", false, 70.0, 30.0), ("nonZero", true, 0.0, 100.0), ("evenOdd", true, 70.0, 30.0)];
|
||||
for (rule, same_way, around, largest) in cases {
|
||||
select(&mut s, &[compound]);
|
||||
let both = s.doc().unwrap().doc.node(compound).unwrap().children().unwrap().iter().map(|n| n.id.0).collect::<Vec<_>>();
|
||||
s.execute("path.reverse", &json!({"ids": both, "reversed": true})).unwrap();
|
||||
if !same_way {
|
||||
s.execute("path.reverse", &json!({"ids": [both[1]], "reversed": false})).unwrap();
|
||||
}
|
||||
s.execute("path.setFillRule", &json!({"rule": rule, "ids": [compound.0]})).unwrap();
|
||||
select(&mut s, &[compound]);
|
||||
let id = id_of(&s.execute(COMMAND, &json!({})).unwrap());
|
||||
let (center, r) = circle(&s, id);
|
||||
assert!(r > least(largest) && r < largest + 0.0003 * 140.0, "{rule} {same_way}: {r}");
|
||||
assert!(((center - ring).hypot() - around).abs() < 0.1, "{rule} {same_way}: {center:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Each selected path gets its own circle, all as one undo step; a path of a compound path
|
||||
/// selected on its own gets a circle of its own outline.
|
||||
#[test]
|
||||
fn each_selected_path_gets_a_circle_in_one_step() {
|
||||
let mut s = session();
|
||||
let a = id_of(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 40, "height": 40})).unwrap());
|
||||
let b = id_of(&s.execute("shape.rectangle", &json!({"x": 100, "y": 0, "width": 40, "height": 80})).unwrap());
|
||||
select(&mut s, &[a, b]);
|
||||
let undo = undo_len(&s);
|
||||
let ids = ids_of(&s.execute(COMMAND, &json!({})).unwrap());
|
||||
assert_eq!(ids.len(), 2);
|
||||
assert_eq!(undo_len(&s), undo + 1);
|
||||
let centers: Vec<Point> = ids.iter().map(|id| circle(&s, *id).0).collect();
|
||||
assert!(centers.iter().any(|c| c.x < 40.0) && centers.iter().any(|c| c.x > 100.0), "{centers:?}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
select(&mut s, &[a, b]);
|
||||
let compound = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap());
|
||||
let member = s.doc().unwrap().doc.node(compound).unwrap().children().unwrap()[0].id;
|
||||
select(&mut s, &[member]);
|
||||
let id = id_of(&s.execute(COMMAND, &json!({})).unwrap());
|
||||
let r = circle(&s, id).1;
|
||||
assert!(r <= 20.0 + 1e-6 && r > least(20.0), "the member's own square: {r}");
|
||||
// Inside the isolated compound path, the circle joins it.
|
||||
s.execute("object.isolate", &json!({"id": compound.0})).unwrap();
|
||||
select(&mut s, &[member]);
|
||||
let id = id_of(&s.execute(COMMAND, &json!({})).unwrap());
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(id), Some(compound));
|
||||
}
|
||||
|
||||
/// The drawn circle stays inside a large square turned so that it touches the square's sides
|
||||
/// where its curves bulge most past a true circle, about 20° from each axis.
|
||||
#[test]
|
||||
fn the_drawn_circle_stays_inside_where_its_curves_bulge() {
|
||||
let mut s = session();
|
||||
let (center, half) = (Point::new(1200.0, 1200.0), 1000.0);
|
||||
for degrees in [15.0_f64, 19.4, 25.0] {
|
||||
let (sin, cos) = degrees.to_radians().sin_cos();
|
||||
let corner = |u: f64, v: f64| json!({"x": center.x + u * cos - v * sin, "y": center.y + u * sin + v * cos});
|
||||
let anchors = [(-half, -half), (half, -half), (half, half), (-half, half)].map(|(u, v)| corner(u, v));
|
||||
s.execute("path.create", &json!({"anchors": anchors, "closed": true})).unwrap();
|
||||
let id = id_of(&s.execute(COMMAND, &json!({})).unwrap());
|
||||
let NodeKind::Path { path, .. } = &s.doc().unwrap().doc.node(id).unwrap().kind else {
|
||||
panic!("not a path");
|
||||
};
|
||||
for seg in path.to_bezpath().segments() {
|
||||
for i in 0..=200 {
|
||||
let p = vectorcraft_geom::ParamCurve::eval(&seg, f64::from(i) / 200.0) - center;
|
||||
let (u, v) = (p.x * cos + p.y * sin, -p.x * sin + p.y * cos);
|
||||
assert!(u.abs().max(v.abs()) <= half, "{degrees}°: ({u}, {v}) is outside the square");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An open path, an object that is not a path or compound path, a path that fills no area and an
|
||||
/// empty selection are errors, and nothing is drawn.
|
||||
#[test]
|
||||
fn open_paths_other_objects_and_no_selection_are_refused() {
|
||||
let mut s = session();
|
||||
assert!(s.execute(COMMAND, &json!({})).is_err(), "nothing selected");
|
||||
let open = id_of(&s.execute("path.create", &json!({"anchors": [{"x": 0, "y": 0}, {"x": 80, "y": 0}, {"x": 0, "y": 60}]})).unwrap());
|
||||
select(&mut s, &[open]);
|
||||
refused(&mut s, "is not a closed path or compound path");
|
||||
let sq = id_of(&s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap());
|
||||
select(&mut s, &[sq]);
|
||||
let group = id_of(&s.execute("object.group", &json!({})).unwrap());
|
||||
select(&mut s, &[group]);
|
||||
refused(&mut s, "is not a closed path or compound path");
|
||||
// One refused object leaves the other selected objects without a circle too.
|
||||
select(&mut s, &[group, open]);
|
||||
refused(&mut s, "is not a closed path or compound path");
|
||||
let flat = [(0, 300), (100, 300), (50, 300)].map(|(x, y)| json!({"x": x, "y": y}));
|
||||
let flat = id_of(&s.execute("path.create", &json!({"anchors": flat, "closed": true})).unwrap());
|
||||
select(&mut s, &[flat]);
|
||||
refused(&mut s, "fills no area");
|
||||
// A selected layer is refused too, alone or with a path.
|
||||
let mut layer = None;
|
||||
s.doc().unwrap().doc.walk(|n| {
|
||||
if n.is_layer() {
|
||||
layer.get_or_insert(n.id);
|
||||
}
|
||||
});
|
||||
let layer = layer.unwrap();
|
||||
let path = id_of(&s.execute("shape.rectangle", &json!({"x": 200, "y": 100, "width": 50, "height": 50})).unwrap());
|
||||
for ids in [vec![layer], vec![layer, path]] {
|
||||
select(&mut s, &ids);
|
||||
refused(&mut s, "is not a closed path or compound path");
|
||||
}
|
||||
}
|
||||
@@ -1198,6 +1198,24 @@ pub(crate) fn capture_series_paint_writes(
|
||||
super::graph::capture_series_top_paints(d, &rows)
|
||||
}
|
||||
|
||||
/// Store on the graph the opacity and blend mode of each row an edit wrote (`written`: an object with the index of the
|
||||
/// row) on the series marks among them, when that row is the topmost visible one of its kind, also when the mark
|
||||
/// already showed that opacity: it replaces the opacity another mark of the series left on the graph. When the edit
|
||||
/// reaches several marks of one series, the frontmost one sets what the graph stores. Returns whether the stored
|
||||
/// opacity or blend mode changed.
|
||||
pub(crate) fn capture_series_opacity_writes(d: &mut vectorcraft_doc::Document, written: &[(NodeId, usize)]) -> bool {
|
||||
let ids: Vec<NodeId> = written.iter().map(|(id, _)| *id).collect();
|
||||
// A later mark's capture replaces an earlier one's: take them in paint order.
|
||||
let rows: Vec<(NodeId, bool)> = series_children_in_paint_order(d, &ids)
|
||||
.into_iter()
|
||||
.flat_map(|id| {
|
||||
let shown = written.iter().filter(move |(w, _)| *w == id).filter_map(|(_, at)| Some((id, top_row_kind(&d.node(id)?.appearance, *at)?)));
|
||||
shown.collect::<Vec<_>>()
|
||||
})
|
||||
.collect();
|
||||
super::graph::capture_series_opacity(d, &rows)
|
||||
}
|
||||
|
||||
/// The kind of the row at `at` (fill `true`, stroke `false`) when it is the topmost visible row of that kind in `ap`.
|
||||
fn top_row_kind(ap: &Appearance, at: usize) -> Option<bool> {
|
||||
let fill = ap.items.get(at)?.is_fill();
|
||||
@@ -1669,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();
|
||||
@@ -1676,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);
|
||||
}
|
||||
@@ -1685,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
|
||||
|
||||
@@ -14,13 +14,14 @@
|
||||
//! the document's Spot Colors option says. Pasting back into the document the objects came from
|
||||
//! uses its resources as they are now.
|
||||
|
||||
use std::cell::OnceCell;
|
||||
use std::cell::{Cell, OnceCell};
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_brush::Brush;
|
||||
use vectorcraft_color::{Color, Paint, Swatch};
|
||||
use vectorcraft_doc::pattern::pattern_paint;
|
||||
use vectorcraft_doc::text::{KINSOKU_NAME_MAX, KINSOKU_SETS_MAX};
|
||||
use vectorcraft_doc::{
|
||||
Appearance, AppearanceItem, Document, Effect, GraphDesign, GraphicStyle, Kinsoku, KinsokuSet, Node, NodeKind, PatternDef, Symbol,
|
||||
@@ -610,6 +611,9 @@ pub(crate) enum SwatchChoice {
|
||||
pub(crate) struct SwatchChoices {
|
||||
all: SwatchChoice,
|
||||
by_name: BTreeMap<String, SwatchChoice>,
|
||||
/// Names a swatch or pattern that comes in under a numbered name skips, each with the swatch
|
||||
/// it is reserved for, which still comes in under it when the document does not use it.
|
||||
reserved: Arc<BTreeMap<String, Swatch>>,
|
||||
}
|
||||
|
||||
impl SwatchChoices {
|
||||
@@ -621,16 +625,22 @@ impl SwatchChoices {
|
||||
};
|
||||
match p.get("swatchConflict") {
|
||||
None | Some(Value::Null) => Ok(Self::default()),
|
||||
Some(Value::Object(m)) => {
|
||||
Ok(Self { all: SwatchChoice::Merge, by_name: m.iter().map(|(k, v)| Ok((k.clone(), one(v)?))).collect::<Result<_>>()? })
|
||||
}
|
||||
Some(v) => Ok(Self { all: one(v)?, by_name: BTreeMap::new() }),
|
||||
Some(Value::Object(m)) => Ok(Self {
|
||||
all: SwatchChoice::Merge,
|
||||
by_name: m.iter().map(|(k, v)| Ok((k.clone(), one(v)?))).collect::<Result<_>>()?,
|
||||
reserved: Arc::default(),
|
||||
}),
|
||||
Some(v) => Ok(Self { all: one(v)?, ..Self::default() }),
|
||||
}
|
||||
}
|
||||
/// Add for every conflict: each pasted swatch whose name the document gives another color
|
||||
/// comes in renamed.
|
||||
pub(crate) fn add_all() -> Self {
|
||||
Self { all: SwatchChoice::Add, by_name: BTreeMap::new() }
|
||||
Self { all: SwatchChoice::Add, ..Self::default() }
|
||||
}
|
||||
/// These choices, with numbered names skipping the names of `names` ([`SwatchChoices::reserved`]).
|
||||
pub(crate) fn reserving(self, names: &Arc<BTreeMap<String, Swatch>>) -> Self {
|
||||
Self { reserved: Arc::clone(names), ..self }
|
||||
}
|
||||
fn of(&self, name: &str) -> SwatchChoice {
|
||||
self.by_name.get(name).copied().unwrap_or(self.all)
|
||||
@@ -1154,6 +1164,9 @@ pub(crate) struct Imported {
|
||||
pub added_designs: BTreeSet<String>,
|
||||
/// The global and spot colors that took the document's color (merged).
|
||||
merged_swatches: BTreeSet<String>,
|
||||
/// Whether a name [`SwatchChoices::reserving`] reserves changed the name a swatch or pattern
|
||||
/// came in under.
|
||||
pub reserved_named: bool,
|
||||
}
|
||||
|
||||
impl Imported {
|
||||
@@ -1425,9 +1438,39 @@ impl Clipboard {
|
||||
let bare = |p: &PatternDef| PatternDef { name: String::new(), art: vec![], ..p.clone() };
|
||||
let same = |n: &str| !fresh && d.pattern(n).is_some_and(|x| bare(x) == bare(def) && same_art(&out.relink, &x.art, &def.art));
|
||||
let p = existing(&def.name, d.patterns.iter().map(|p| p.name.as_str()), same_doc, same).unwrap_or_else(|| {
|
||||
// Its swatch comes along under the same name.
|
||||
let name = unique_name(&def.name, |n| d.pattern(n).is_some() || d.swatch_name_taken(n));
|
||||
// Its swatch comes along under the same name, which skips the reserved swatch
|
||||
// names too, except its own name when that is reserved for a swatch of it.
|
||||
let skipped = Cell::new(false);
|
||||
let ours = |w: &Swatch| matches!(&w.paint, Paint::Pattern { pattern, .. } if *pattern == def.name);
|
||||
let name = unique_name(&def.name, |n| {
|
||||
let used = d.pattern(n).is_some() || d.swatch_name_taken(n);
|
||||
let held = !used && choices.reserved.get(n).is_some_and(|w| n != def.name || !ours(w));
|
||||
skipped.set(skipped.get() || held);
|
||||
used || held
|
||||
});
|
||||
out.reserved_named |= skipped.get();
|
||||
add_pattern(d, PatternDef { name: name.clone(), ..def.clone() });
|
||||
// The name is left to a swatch it is reserved for that places the pattern
|
||||
// otherwise; the swatch the pattern comes with gets another.
|
||||
let placed = choices.reserved.get(&name).is_some_and(|w| ours(w) && w.paint != pattern_paint(&def.name));
|
||||
if placed && d.swatches.last().is_some_and(|w| w.name == name) {
|
||||
let other = unique_name(&name, |n| n == name || d.swatch_name_taken(n) || choices.reserved.contains_key(n));
|
||||
if let Some(w) = d.swatches.last_mut() {
|
||||
w.name = other;
|
||||
}
|
||||
}
|
||||
// A pattern that comes in under another name than the one reserved for its
|
||||
// swatch, because a pattern has that name, keeps that name for its swatch
|
||||
// when no swatch or color group uses it.
|
||||
let own = name != def.name
|
||||
&& !d.swatch_name_taken(&def.name)
|
||||
&& choices.reserved.get(&def.name).is_some_and(|w| w.paint == pattern_paint(&def.name));
|
||||
if own && d.swatches.last().is_some_and(|w| w.name == name) {
|
||||
if let Some(w) = d.swatches.last_mut() {
|
||||
w.name = def.name.clone();
|
||||
}
|
||||
out.reserved_named = true;
|
||||
}
|
||||
Placed::added(&def.name, name)
|
||||
});
|
||||
added_patterns.extend(p.new_name(&def.name));
|
||||
@@ -1660,7 +1703,9 @@ impl Clipboard {
|
||||
out.merged_swatches.insert(w.name.clone());
|
||||
Placed::Existing
|
||||
} else {
|
||||
add_swatch(d, w, same_doc)
|
||||
let (p, reserved_named) = add_swatch(d, w, w, same_doc, &choices.reserved, &out.relink);
|
||||
out.reserved_named |= reserved_named;
|
||||
p
|
||||
};
|
||||
out.placed(Res::Swatch, &w.name, &p);
|
||||
}
|
||||
@@ -1675,7 +1720,8 @@ impl Clipboard {
|
||||
for def in self.swatches.iter().filter(|w| !is_base(w) && used.carries(w)) {
|
||||
let mut w = def.clone();
|
||||
out.relink.paint(&mut w.paint);
|
||||
let p = add_swatch(d, &w, same_doc);
|
||||
let (p, reserved_named) = add_swatch(d, &w, def, same_doc, &choices.reserved, &out.relink);
|
||||
out.reserved_named |= reserved_named;
|
||||
out.placed(Res::Swatch, &def.name, &p);
|
||||
}
|
||||
}
|
||||
@@ -1877,13 +1923,62 @@ pub(crate) fn import_graph_designs(src: &Document, d: &mut Document, names: &[St
|
||||
clip.import_used(d, &used, &SwatchChoices::default(), false)
|
||||
}
|
||||
|
||||
/// Whether `name` ends in a space and a number, as a numbered copy's name ("Ink 2") does.
|
||||
pub(crate) fn numbered_name(name: &str) -> bool {
|
||||
name.rsplit_once(' ').is_some_and(|(_, k)| !k.is_empty() && k.bytes().all(|b| b.is_ascii_digit()))
|
||||
}
|
||||
|
||||
/// Swatch `w` in `d` ([`existing`]), else added under a free name (swatches and colour groups
|
||||
/// share one namespace).
|
||||
fn add_swatch(d: &mut Document, w: &Swatch, same_doc: bool) -> Placed {
|
||||
/// share one namespace) → where it went, and whether `reserved` changed its name. `source` is the
|
||||
/// pasted swatch `w` stands for, before its links were relinked. A numbered name skips the names
|
||||
/// in `reserved`. A numbered name in `reserved` ("Ink 2") that `d` does not use is kept for the
|
||||
/// swatch it is reserved for: that swatch comes in under it, not as a numbered copy of it that `d`
|
||||
/// has, and another swatch of that name gets a number. A numbered copy in `d` whose name is
|
||||
/// reserved for another swatch, and that is that swatch with its links as `relink` gives them, is
|
||||
/// left to it, whether or not the import brings that swatch.
|
||||
fn add_swatch(d: &mut Document, w: &Swatch, source: &Swatch, same_doc: bool, reserved: &BTreeMap<String, Swatch>, relink: &Relink) -> (Placed, bool) {
|
||||
let same = |n: &str| d.swatch(n).is_some_and(|t| *t == Swatch { name: n.to_string(), ..w.clone() });
|
||||
existing(&w.name, d.swatches_iter().map(|t| t.name.as_str()), same_doc, same).unwrap_or_else(|| {
|
||||
let name = d.free_swatch_name(&w.name);
|
||||
d.swatches.push(Swatch { name: name.clone(), ..w.clone() });
|
||||
Placed::added(&w.name, name)
|
||||
})
|
||||
let kept = (!same_doc && numbered_name(&w.name) && !d.swatch_name_taken(&w.name)).then(|| reserved.get(&w.name)).flatten();
|
||||
let (owns, held) = (kept.is_some_and(|o| o == source), kept.is_some_and(|o| o != source));
|
||||
let is_owner = |t: &Swatch, o: &Swatch| {
|
||||
let mut o = o.clone();
|
||||
relink.paint(&mut o.paint);
|
||||
*t == o
|
||||
};
|
||||
let theirs =
|
||||
|n: &str| n != w.name && copy_of(&w.name, n) && reserved.get(n).is_some_and(|o| o != source && d.swatch(n).is_some_and(|t| is_owner(t, o)));
|
||||
let names = || d.swatches_iter().map(|t| t.name.as_str());
|
||||
let excluded = Cell::new(false);
|
||||
let found = existing(
|
||||
&w.name,
|
||||
names().filter(|n| {
|
||||
let t = theirs(n);
|
||||
excluded.set(excluded.get() || t);
|
||||
!t
|
||||
}),
|
||||
same_doc,
|
||||
same,
|
||||
);
|
||||
let reused = |p: &Option<Placed>| match p {
|
||||
Some(Placed::Reused(n)) => Some(n.clone()),
|
||||
_ => None,
|
||||
};
|
||||
let passed_over = excluded.get() && reused(&found) != reused(&existing(&w.name, names(), same_doc, same));
|
||||
let over_copy = match found {
|
||||
Some(p) if !owns => return (p, passed_over),
|
||||
found => found.is_some(),
|
||||
};
|
||||
let mut skipped = held;
|
||||
let name = if d.swatch_name_taken(&w.name) || held {
|
||||
let mut free = |n: &String| {
|
||||
let taken = d.swatch_name_taken(n);
|
||||
skipped |= !taken && reserved.contains_key(n);
|
||||
!taken && !reserved.contains_key(n)
|
||||
};
|
||||
(2..).map(|i| format!("{} {i}", w.name)).find(&mut free).unwrap_or_else(|| d.free_swatch_name(&w.name))
|
||||
} else {
|
||||
w.name.clone()
|
||||
};
|
||||
d.swatches.push(Swatch { name: name.clone(), ..w.clone() });
|
||||
(Placed::added(&w.name, name), over_copy || skipped || passed_over)
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -18,7 +18,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Document Info",
|
||||
["Window", "Document Info"],
|
||||
None,
|
||||
"{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document: {…, units (English), unitId: the units' Preferences › Units id (points, millimeters, feetInches, …), rasterEffectsPpi, transparency: {gridSize: small|medium|large, gridColors: [#rrggbb, #rrggbb], gridColorsName (a preset's name or Custom), simulatePaper, flattenerPreset} (File › Document Setup's transparency settings, which the document category lists), selectedArtboards: [{index, name, width, height, x, y}] (while the Artboard tool is the current tool, the artboards it has selected, in the document's units, x and y those of the top-left corner from the ruler origin of its active artboard, which the document category lists after the artboards; else empty)}, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts (the type in opacity masks and in the art of symbols and patterns included; with selectionOnly: the selected type's), fontUses: [{font, type: truetype|opentype|unknown, uses}] (each font of fonts, in order: truetype or opentype by the outlines (glyf, or CFF or CFF2) of the face its type is drawn in, unknown for a font not installed in the family and style it names; uses: the text objects set in it, each once however many of its runs use the font, the type in a mask or in a symbol's or pattern's art once however many objects show it; the fonts category's rows give them as `TrueType; 2 uses`), fontDetails: [{font, match: exact|style|missingWithFallback|missing, family, style, file, embedding: allowed|editing|previewPrint|forbidden|null}] (each font of fonts, in order: how it was found, the face shown (null when none), that face's file name (null for a built-in face) and what its license allows), images, imageObjects: [{name, width, height, linked, file}] (the image objects in the order Linked Images and Embedded Images list them; file: what a linked image's row shows, null for an embedded one), swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the brushes the art's drawn strokes use, each once; with selectionOnly: those the selected objects' strokes use), brushes: [{name, type: calligraphic|scatter|art|pattern|bristle|null}] (those brushes with their types; null: not in the Brushes panel), panelBrushNames (the Brushes panel's brushes), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient that color a part of it above opacity 0 (a stop at opacity 0 counts only where it mixes with a stop above opacity 0 over a stretch of some width), at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, fills and strokes at an opacity of 0, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients, kinds}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else its kind's name, such as Linear gradient; kinds gives each one's kind, linear|radial|conic|diamond|freeform, when it is named by its kind, else null; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}. An image linked to a file outside the automation read roots has link null, and its Linked Images row names the file alone. brushNames, brushes, spotObjects, patternObjects and gradientObjects leave out hidden objects, objects at an opacity of 0 and the objects inside a hidden group or layer or one at an opacity of 0 (with selectionOnly too), their characters' paints and colorized images included; objects still counts them as paths, groups and the other kinds",
|
||||
"{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document: {…, units (English), unitId: the units' Preferences › Units id (points, millimeters, feetInches, …), rasterEffectsPpi, transparency: {gridSize: small|medium|large, gridColors: [#rrggbb, #rrggbb], gridColorsName (a preset's name or Custom), simulatePaper, flattenerPreset} (File › Document Setup's transparency settings, which the document category lists), selectedArtboards: [{index, name, width, height, x, y}] (while the Artboard tool is the current tool, the artboards it has selected, in the document's units, x and y those of the top-left corner from the ruler origin of its active artboard, which the document category lists after the artboards; else empty)}, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts (the type in opacity masks and in the art of symbols and patterns included; with selectionOnly: the selected type's), fontUses: [{font, type: truetype|opentype|unknown, uses}] (each font of fonts, in order: truetype or opentype by the outlines (glyf, or CFF or CFF2) of the face its type is drawn in, unknown for a font not installed in the family and style it names; uses: the text objects set in it, each once however many of its runs use the font, the type in a mask or in a symbol's or pattern's art once however many objects show it; the fonts category's rows give them as `TrueType; 2 uses`), fontDetails: [{font, match: exact|style|missingWithFallback|missing, family, style, file, embedding: allowed|editing|previewPrint|forbidden|null}] (each font of fonts, in order: how it was found, the face shown (null when none), that face's file name (null for a built-in face) and what its license allows), images, imageObjects: [{name, width, height, linked, file, format, effectivePpi, memoryBytes, storedBytes}] (the image objects in the order Linked Images and Embedded Images list them; file: what a linked image's row shows, null for an embedded one; format: a linked image's file format by its extension, else the format of the pixels the document holds, null when unknown; effectivePpi: [x, y] pixels per inch at the size it is placed at, a distorted image measured at its middle, null when it has no area; memoryBytes: for an embedded image width × height × 4, the bytes of the 8-bit RGBA pixels it is drawn from, else null; storedBytes: for an embedded image the bytes of the encoded image the document holds, else null; a Linked Images row gives the format, the size, the resolution and the file (`PNG; 1200 × 800 px; 150 ppi — /art/photo.png`), an Embedded Images row the format, the size and the memory (`PNG; 1200 × 800 px; estimated memory 3.7 MiB`)), swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the brushes the art's drawn strokes use, each once; with selectionOnly: those the selected objects' strokes use), brushes: [{name, type: calligraphic|scatter|art|pattern|bristle|null}] (those brushes with their types; null: not in the Brushes panel), panelBrushNames (the Brushes panel's brushes), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient that color a part of it above opacity 0 (a stop at opacity 0 counts only where it mixes with a stop above opacity 0 over a stretch of some width), at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, fills and strokes at an opacity of 0, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients, kinds}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else its kind's name, such as Linear gradient; kinds gives each one's kind, linear|radial|conic|diamond|freef
Line truncated
|
||||
has_doc,
|
||||
info
|
||||
),
|
||||
@@ -183,8 +183,126 @@ fn count_fonts(fonts: &mut BTreeMap<super::fonts::UsedFont, usize>, t: &vectorcr
|
||||
}
|
||||
}
|
||||
|
||||
/// An image object as Document Info lists it: (name, width, height, linked file).
|
||||
type ImageRow = (String, u32, u32, Option<String>);
|
||||
/// An image object as Linked Images or Embedded Images lists it.
|
||||
struct ImageRow {
|
||||
name: String,
|
||||
width: u32,
|
||||
height: u32,
|
||||
/// What a linked image's row names: its file's path, or the file's name alone when the request
|
||||
/// may not read it. `None` for an embedded image.
|
||||
file: Option<String>,
|
||||
/// The image's format ([`image_format`]); `None` when it is not known.
|
||||
format: Option<&'static str>,
|
||||
/// The pixels per inch across and down at the size the image is placed at; `None` when its
|
||||
/// transform flattens it.
|
||||
ppi: Option<[f64; 2]>,
|
||||
/// For an embedded image, the bytes its pixels take when drawn (8-bit RGBA: width × height × 4).
|
||||
memory: Option<u64>,
|
||||
/// For an embedded image, the bytes of the encoded image the document holds.
|
||||
stored: Option<u64>,
|
||||
}
|
||||
|
||||
impl ImageRow {
|
||||
/// Image object `n` (image `im`) of `d`, `file` the row value of its link.
|
||||
fn of(d: &Document, n: &Node, im: &vectorcraft_doc::ImageObject, file: Option<String>) -> Self {
|
||||
let name = im.link.as_ref().map_or_else(|| n.display_name(), |l| l.name().to_string());
|
||||
// A distorted image is measured at its middle, as `image.info` measures it.
|
||||
let xf = vectorcraft_doc::image_quad::nearest_affine(n).unwrap_or(im.xf);
|
||||
let ppi = super::place::effective_ppi(xf);
|
||||
// An image with no pixels across or down has no area, and so does one whose transform lays
|
||||
// both pixel axes on one line. The determinant is compared with the product of the two
|
||||
// axes' lengths, at any scale.
|
||||
let [xx, xy, yx, yy, ..] = xf.as_coeffs();
|
||||
let has_area = im.width > 0 && im.height > 0 && xf.determinant().abs() > 1e-9 * xx.hypot(xy) * yx.hypot(yy);
|
||||
let embedded = im.link.is_none();
|
||||
let memory = || u64::from(im.width).checked_mul(u64::from(im.height))?.checked_mul(4);
|
||||
Self {
|
||||
name,
|
||||
width: im.width,
|
||||
height: im.height,
|
||||
file,
|
||||
format: image_format(d, im),
|
||||
ppi: (has_area && ppi.iter().all(|v| *v > 0.0 && v.is_finite())).then_some(ppi),
|
||||
memory: if embedded { memory() } else { None },
|
||||
stored: if embedded { d.images.get(&im.key).map(|b| b.bytes.len() as u64) } else { None },
|
||||
}
|
||||
}
|
||||
|
||||
/// The row's value: the format, the size in pixels, and for a linked image its resolution and
|
||||
/// file, for an embedded one the memory its pixels take.
|
||||
fn value(&self) -> String {
|
||||
let format = self.format.unwrap_or("Unknown format");
|
||||
let size = format!("{} × {} px", self.width, self.height);
|
||||
match &self.file {
|
||||
Some(file) => {
|
||||
let ppi = match self.ppi {
|
||||
Some([x, y]) if ppi_number(x) == ppi_number(y) => format!("{} ppi", ppi_number(x)),
|
||||
Some([x, y]) => format!("{} × {} ppi", ppi_number(x), ppi_number(y)),
|
||||
None => "resolution unavailable".into(),
|
||||
};
|
||||
format!("{format}; {size}; {ppi} — {file}")
|
||||
}
|
||||
None => {
|
||||
let memory = self.memory.map_or_else(|| "memory unavailable".to_string(), |b| format!("estimated memory {}", byte_size(b)));
|
||||
format!("{format}; {size}; {memory}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The row's `imageObjects` entry.
|
||||
fn entry(&self) -> Value {
|
||||
json!({
|
||||
"name": self.name,
|
||||
"width": self.width,
|
||||
"height": self.height,
|
||||
"linked": self.file.is_some(),
|
||||
"file": self.file,
|
||||
"format": self.format,
|
||||
"effectivePpi": self.ppi,
|
||||
"memoryBytes": self.memory,
|
||||
"storedBytes": self.stored,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The format of image `im` of `d`, as the Links panel names it: for a linked image its file's, by
|
||||
/// its extension (DCS for a separated one), else the type of the pixels the document holds for it;
|
||||
/// `None` when neither names a known format.
|
||||
fn image_format(d: &Document, im: &vectorcraft_doc::ImageObject) -> Option<&'static str> {
|
||||
use super::fileio;
|
||||
if im.link.is_some() && d.images.get(&im.key).is_some_and(vectorcraft_doc::ImageBlob::is_separated) {
|
||||
return Some("DCS");
|
||||
}
|
||||
im.link
|
||||
.as_ref()
|
||||
.and_then(|l| fileio::format_for_name(l.name()).or_else(|| fileio::readable_format_for_name(l.name())))
|
||||
.or_else(|| d.images.get(&im.key).and_then(|b| fileio::FORMATS.iter().find(|f| f.raster && f.mime == b.mime)))
|
||||
.map(|f| f.label)
|
||||
}
|
||||
|
||||
/// A resolution as Document Info shows it: rounded to a tenth (below 1, to a hundredth), without a
|
||||
/// trailing `.0`.
|
||||
pub fn ppi_number(ppi: f64) -> String {
|
||||
let k = if ppi.abs() < 1.0 { 100.0 } else { 10.0 };
|
||||
format!("{}", (ppi * k).round() / k)
|
||||
}
|
||||
|
||||
/// A number of bytes as Document Info shows it: in B below 1 KiB, else in KiB, MiB or GiB rounded
|
||||
/// to a tenth.
|
||||
pub fn byte_size(bytes: u64) -> String {
|
||||
const UNITS: [&str; 3] = ["KiB", "MiB", "GiB"];
|
||||
if bytes < 1024 {
|
||||
return format!("{bytes} B");
|
||||
}
|
||||
let mut v = bytes as f64 / 1024.0;
|
||||
let mut unit = 0;
|
||||
// 1023.96 KiB is shown as 1 MiB rather than as 1024 KiB.
|
||||
while v >= 1023.95 && unit + 1 < UNITS.len() {
|
||||
v /= 1024.0;
|
||||
unit += 1;
|
||||
}
|
||||
format!("{} {}", (v * 10.0).round() / 10.0, UNITS[unit])
|
||||
}
|
||||
|
||||
/// A Repeat object as Document Info lists it: its `repeatObjects` entry, and its row, which gives
|
||||
/// its name and then its kind with the number of instances it draws (for a grid, its rows and
|
||||
@@ -337,11 +455,9 @@ fn sections(
|
||||
"symbols" => names("symbols"),
|
||||
"fonts" => fonts.to_vec(),
|
||||
"fontDetails" => font_details.to_vec(),
|
||||
"linkedImages" => {
|
||||
images.iter().filter_map(|(name, w, h, link)| Some((name.clone(), format!("{w} × {h} px — {}", link.as_ref()?)))).collect()
|
||||
}
|
||||
"linkedImages" => images.iter().filter(|i| i.file.is_some()).map(|i| (i.name.clone(), i.value())).collect(),
|
||||
"repeats" => repeats.to_vec(),
|
||||
_ => images.iter().filter(|i| i.3.is_none()).map(|(name, w, h, _)| (name.clone(), format!("{w} × {h} px"))).collect(),
|
||||
_ => images.iter().filter(|i| i.file.is_none()).map(|i| (i.name.clone(), i.value())).collect(),
|
||||
};
|
||||
Section { id, title, rows }
|
||||
})
|
||||
@@ -753,8 +869,8 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
im.key.clone(),
|
||||
json!({ "width": im.width, "height": im.height, "linked": im.link.is_some(), "link": link.and_then(|(l, ok)| ok.then_some(&l.path)) }),
|
||||
);
|
||||
let name = im.link.as_ref().map_or_else(|| n.display_name(), |l| l.name().to_string());
|
||||
image_rows.push((name, im.width, im.height, link.map(|(l, ok)| if ok { l.path.clone() } else { l.name().to_string() })));
|
||||
let file = link.map(|(l, ok)| if ok { l.path.clone() } else { l.name().to_string() });
|
||||
image_rows.push(ImageRow::of(d, n, im, file));
|
||||
Some("images")
|
||||
}
|
||||
NodeKind::SymbolInstance { symbol, .. } => {
|
||||
@@ -835,13 +951,8 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let font_names: Vec<String> = fonts.keys().map(super::fonts::font_label).collect();
|
||||
let (font_uses, font_use_rows): (Vec<Value>, Vec<(String, String)>) = fonts.iter().map(|(f, n)| font_use(f, *n)).unzip();
|
||||
let (font_entries, font_rows): (Vec<Value>, Vec<(String, String)>) = fonts.keys().map(font_detail).unzip();
|
||||
// The image objects in walk order, as Linked Images and Embedded Images list them: `file` is a
|
||||
// linked image's row value (its path, or its file name alone when the request may not read it),
|
||||
// and null for an embedded one.
|
||||
let image_objects: Vec<Value> = image_rows
|
||||
.iter()
|
||||
.map(|(name, w, h, file)| json!({ "name": name, "width": w, "height": h, "linked": file.is_some(), "file": file }))
|
||||
.collect();
|
||||
// The image objects in walk order, as Linked Images and Embedded Images list them.
|
||||
let image_objects: Vec<Value> = image_rows.iter().map(ImageRow::entry).collect();
|
||||
// Each brush the art uses with its type, found by name in the Brushes panel as the renderer finds it (the first of two
|
||||
// brushes with one name); a brush the panel does not hold draws as a plain stroke and has no type. A row names the type
|
||||
// as the New Brush dialog does (`Art Brush`), and the panel translates these values when it shows them.
|
||||
@@ -2246,11 +2357,156 @@ mod tests {
|
||||
assert_eq!(objects.len(), 2, "{objects:?}");
|
||||
for (o, r) in objects.iter().zip(&embedded) {
|
||||
assert_eq!((o["linked"].clone(), o["file"].clone(), o["name"].clone()), (json!(false), Value::Null, r[0].clone()), "{o}");
|
||||
assert_eq!(r[1], format!("{} × {} px", o["width"], o["height"]));
|
||||
let memory = byte_size(o["memoryBytes"].as_u64().unwrap());
|
||||
assert_eq!(r[1], format!("{}; {} × {} px; estimated memory {memory}", o["format"].as_str().unwrap(), o["width"], o["height"]));
|
||||
}
|
||||
assert!(section("linkedImages").is_empty());
|
||||
}
|
||||
|
||||
/// An image object to place: (key, MIME type, linked path, width, height, transform).
|
||||
type Placed<'a> = (&'a str, &'a str, Option<&'a str>, u32, u32, Affine);
|
||||
|
||||
/// Image objects `images` placed in a new document, with a blob of `100 + n` bytes of type
|
||||
/// `mime` for each new key; their ids in order.
|
||||
fn images_in(s: &mut Session, images: &[Placed]) -> Vec<NodeId> {
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
s.edit("Place", |d, _| {
|
||||
let mut ids = vec![];
|
||||
for (n, (key, mime, link, width, height, xf)) in images.iter().enumerate() {
|
||||
if !d.images.contains_key(*key) {
|
||||
d.images.insert((*key).into(), vectorcraft_doc::ImageBlob::new(*mime, vec![0; 100 + n]));
|
||||
}
|
||||
let id = d.alloc_id();
|
||||
let im = vectorcraft_doc::ImageObject {
|
||||
key: (*key).into(),
|
||||
width: *width,
|
||||
height: *height,
|
||||
xf: *xf,
|
||||
link: link.map(vectorcraft_doc::LinkInfo::new),
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
};
|
||||
d.insert(d.default_layer(), usize::MAX, Node::new(id, NodeKind::Image(Box::new(im))))?;
|
||||
ids.push(id);
|
||||
}
|
||||
Ok(ids)
|
||||
})
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// Linked Images gives each linked image's format, size in pixels, resolution at the size it is
|
||||
/// placed at and file, and Embedded Images each embedded image's format, size and the memory
|
||||
/// its pixels take; `imageObjects` gives the same facts with the bytes the document holds for an
|
||||
/// embedded image, the text report writes the same rows, and Selection Only lists the selected
|
||||
/// images alone.
|
||||
#[test]
|
||||
fn image_rows_give_format_resolution_and_memory() {
|
||||
let mut s = Session::new();
|
||||
let half = Affine::scale(0.5);
|
||||
let ids = images_in(
|
||||
&mut s,
|
||||
&[
|
||||
("a", "image/png", None, 1200, 800, half),
|
||||
("b", "image/jpeg", None, 10, 10, half),
|
||||
("c", "image/x-unheard-of", None, 3, 2, half),
|
||||
("a", "image/png", Some("/art/photo.png"), 1200, 800, Affine::scale(0.48)),
|
||||
("a", "image/png", Some("/art/photo.png"), 1200, 800, Affine::scale(0.24)),
|
||||
("a", "image/png", Some("/art/wide.png"), 1200, 800, Affine::scale_non_uniform(0.5, 1.0)),
|
||||
("a", "image/png", Some("/art/scan.tif"), 1200, 800, half),
|
||||
("a", "image/png", Some("/art/flat.png"), 1200, 800, Affine::scale_non_uniform(0.5, 0.0)),
|
||||
// Both pixel axes on one line: neither has length 0, but the image has no area.
|
||||
("a", "image/png", Some("/art/line.png"), 1200, 800, Affine::new([0.5, 0.5, 1.0, 1.0, 0.0, 0.0])),
|
||||
("c", "image/x-unheard-of", Some("/art/odd.qqq"), 3, 2, half),
|
||||
],
|
||||
);
|
||||
let i = s.execute("document.info", &json!({})).unwrap();
|
||||
let rows = |i: &Value, id: &str| -> Vec<(String, String)> {
|
||||
let section = i["sections"].as_array().unwrap().iter().find(|s| s["id"] == id).unwrap().clone();
|
||||
section["rows"].as_array().unwrap().iter().map(|r| (r[0].as_str().unwrap().into(), r[1].as_str().unwrap().into())).collect()
|
||||
};
|
||||
let embedded = rows(&i, "embeddedImages");
|
||||
let values: Vec<&str> = embedded.iter().map(|(_, v)| v.as_str()).collect();
|
||||
assert_eq!(
|
||||
values,
|
||||
[
|
||||
"PNG; 1200 × 800 px; estimated memory 3.7 MiB",
|
||||
"JPEG; 10 × 10 px; estimated memory 400 B",
|
||||
"Unknown format; 3 × 2 px; estimated memory 24 B"
|
||||
]
|
||||
);
|
||||
let linked = rows(&i, "linkedImages");
|
||||
assert_eq!(
|
||||
linked,
|
||||
[
|
||||
("photo.png", "PNG; 1200 × 800 px; 150 ppi — /art/photo.png"),
|
||||
("photo.png", "PNG; 1200 × 800 px; 300 ppi — /art/photo.png"),
|
||||
("wide.png", "PNG; 1200 × 800 px; 144 × 72 ppi — /art/wide.png"),
|
||||
("scan.tif", "TIFF; 1200 × 800 px; 144 ppi — /art/scan.tif"),
|
||||
("flat.png", "PNG; 1200 × 800 px; resolution unavailable — /art/flat.png"),
|
||||
("line.png", "PNG; 1200 × 800 px; resolution unavailable — /art/line.png"),
|
||||
("odd.qqq", "Unknown format; 3 × 2 px; 144 ppi — /art/odd.qqq"),
|
||||
]
|
||||
.map(|(a, b)| (a.to_string(), b.to_string()))
|
||||
);
|
||||
let objects = i["imageObjects"].as_array().unwrap();
|
||||
assert_eq!(objects.len(), 10);
|
||||
assert_eq!(
|
||||
(objects[0]["format"].clone(), objects[0]["effectivePpi"].clone(), objects[0]["memoryBytes"].clone(), objects[0]["storedBytes"].clone()),
|
||||
(json!("PNG"), json!([144.0, 144.0]), json!(1200 * 800 * 4), json!(100))
|
||||
);
|
||||
assert_eq!((objects[1]["format"].clone(), objects[1]["storedBytes"].clone()), (json!("JPEG"), json!(101)));
|
||||
assert_eq!(objects[2]["format"], Value::Null);
|
||||
// A linked image gives no memory and no stored bytes: the document holds only its preview.
|
||||
assert_eq!((objects[3]["memoryBytes"].clone(), objects[3]["storedBytes"].clone()), (Value::Null, Value::Null));
|
||||
let ppi = |o: &Value| -> Vec<f64> { o["effectivePpi"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect() };
|
||||
assert!(ppi(&objects[3]).iter().all(|v| (v - 150.0).abs() < 1e-9), "{}", objects[3]);
|
||||
assert_eq!(ppi(&objects[5]), [144.0, 72.0]);
|
||||
assert_eq!((objects[7]["effectivePpi"].clone(), objects[8]["effectivePpi"].clone()), (Value::Null, Value::Null));
|
||||
let text = s.execute("document.info", &json!({"format": "text"})).unwrap()["text"].as_str().unwrap().to_string();
|
||||
assert!(text.contains("\nphoto.png: PNG; 1200 × 800 px; 150 ppi — /art/photo.png\n"), "{text}");
|
||||
assert!(text.contains(": JPEG; 10 × 10 px; estimated memory 400 B\n"), "{text}");
|
||||
// Selection Only lists the selected images alone, with the same rows.
|
||||
s.execute("select.set", &json!({"ids": [ids[1].0, ids[5].0]})).unwrap();
|
||||
let selected = s.execute("document.info", &json!({"selectionOnly": true})).unwrap();
|
||||
assert_eq!(rows(&selected, "embeddedImages").iter().map(|(_, v)| v.as_str()).collect::<Vec<_>>(), [values[1]]);
|
||||
assert_eq!(rows(&selected, "linkedImages"), [linked[2].clone()]);
|
||||
}
|
||||
|
||||
/// An image placed at a very small size still has an area, so its row gives a resolution.
|
||||
#[test]
|
||||
fn a_tiny_placement_still_gives_a_resolution() {
|
||||
let mut s = Session::new();
|
||||
images_in(&mut s, &[("a", "image/png", Some("/art/huge.png"), 100_000, 100_000, Affine::scale(1e-7))]);
|
||||
let i = s.execute("document.info", &json!({})).unwrap();
|
||||
let ppi = i["imageObjects"][0]["effectivePpi"].as_array().map(|v| v.iter().map(|v| v.as_f64().unwrap_or(0.0)).collect::<Vec<_>>());
|
||||
let ppi = ppi.unwrap_or_default();
|
||||
assert!(ppi.len() == 2 && ppi.iter().all(|v| (v / 7.2e8 - 1.0).abs() < 1e-9), "{}", i["imageObjects"][0]);
|
||||
}
|
||||
|
||||
/// An image with no pixels across or down has no area, so its row gives no resolution whatever
|
||||
/// its transform.
|
||||
#[test]
|
||||
fn a_zero_pixel_image_has_no_resolution() {
|
||||
let mut s = Session::new();
|
||||
let half = Affine::scale(0.5);
|
||||
images_in(&mut s, &[("a", "image/png", Some("/art/none.png"), 0, 800, half), ("a", "image/png", Some("/art/flat.png"), 1200, 0, half)]);
|
||||
let i = s.execute("document.info", &json!({})).unwrap();
|
||||
let objects = i["imageObjects"].as_array().cloned().unwrap_or_default();
|
||||
assert_eq!(objects.iter().map(|o| o["effectivePpi"].clone()).collect::<Vec<_>>(), [Value::Null, Value::Null], "{objects:?}");
|
||||
let text = s.execute("document.info", &json!({"format": "text"})).unwrap()["text"].as_str().unwrap_or_default().to_string();
|
||||
assert!(text.contains("none.png: PNG; 0 × 800 px; resolution unavailable — /art/none.png\n"), "{text}");
|
||||
assert!(text.contains("flat.png: PNG; 1200 × 0 px; resolution unavailable — /art/flat.png\n"), "{text}");
|
||||
}
|
||||
|
||||
/// A number of bytes reads in B below 1 KiB, else in KiB, MiB or GiB to a tenth, and a
|
||||
/// resolution to a tenth without a trailing `.0`.
|
||||
#[test]
|
||||
fn byte_sizes_and_resolutions_read_to_a_tenth() {
|
||||
let shown = [0, 1023, 1024, 1536, 1024 * 1024 - 1, 3_840_000, 5 << 30, u64::MAX].map(byte_size);
|
||||
assert_eq!(shown, ["0 B", "1023 B", "1 KiB", "1.5 KiB", "1 MiB", "3.7 MiB", "5 GiB", "17179869184 GiB"]);
|
||||
assert_eq!([150.0, 72.0 / 0.48, 205.714, 0.04, 0.001].map(ppi_number), ["150", "150", "205.7", "0.04", "0"]);
|
||||
}
|
||||
|
||||
/// A `gradientObjects` entry's `kinds` gives the kind of each gradient listed by its kind
|
||||
/// rather than by a swatch, and null for a swatch's name, even one that reads like a kind and
|
||||
/// one an object's gradient of that kind shares; a type object's characters count as its own.
|
||||
|
||||
@@ -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"]);
|
||||
}
|
||||
}
|
||||
@@ -31,6 +31,7 @@ mod freehand;
|
||||
mod quickpen;
|
||||
mod smooth;
|
||||
|
||||
pub(super) use anchors::{following_anchors, remove_anchors_of};
|
||||
pub use commands::specs;
|
||||
pub(super) use common::{center_strokes, ids_json, replace_with_pieces, usize_opt};
|
||||
pub(super) use cut::{components, erase_outline};
|
||||
|
||||
@@ -166,7 +166,7 @@ pub(super) fn remove_anchors(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
/// end. Indexes are those after the removal, without the subpaths left with fewer than two anchors.
|
||||
/// `removed` is in ascending order without repeats, as a selection holds it, and each subpath reads
|
||||
/// only its own pairs.
|
||||
fn following_anchors(shape: &[(usize, bool)], removed: &[(usize, usize)]) -> BTreeSet<(usize, usize)> {
|
||||
pub(in crate::cmd) fn following_anchors(shape: &[(usize, bool)], removed: &[(usize, usize)]) -> BTreeSet<(usize, usize)> {
|
||||
let mut next = BTreeSet::new();
|
||||
let mut kept = 0;
|
||||
let mut rest = removed;
|
||||
@@ -202,7 +202,7 @@ fn following_anchors(shape: &[(usize, bool)], removed: &[(usize, usize)]) -> BTr
|
||||
/// ([`vectorcraft_tools::draw2::curvature_remove`]). A subpath left with one anchor is removed,
|
||||
/// and a path left with no subpath is removed through `emptied`; the caller then takes it out of
|
||||
/// the selection. True when the path went.
|
||||
fn remove_anchors_of(
|
||||
pub(in crate::cmd) fn remove_anchors_of(
|
||||
d: &mut Document,
|
||||
sel: &mut Selection,
|
||||
emptied: &mut Beside,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::anchors::{convert_anchor, curvature, curvature_edit, remove_anchor, remove_anchors, reshape_segment};
|
||||
use super::cut::{erase_region, erase_segments, knife, split};
|
||||
use super::freehand::{blob, freehand};
|
||||
use super::quickpen::quick_pen;
|
||||
use super::quickpen::{quick_pen, quick_pen_length};
|
||||
use super::smooth::{join_scrub, smooth_region};
|
||||
use super::{CommandSpec, cmd, has_anchors, has_doc, has_selection};
|
||||
|
||||
@@ -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
|
||||
),
|
||||
@@ -43,6 +43,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
quick_pen
|
||||
),
|
||||
cmd!(
|
||||
"path.quickPenLength",
|
||||
"Quick Pen",
|
||||
[],
|
||||
None,
|
||||
"{id, subpath?: index (0), end?: \"end\" (default)|\"start\", length: pt} make the line or arc at that end of the open subpath `length` long, as dragging the Quick Pen tool's length handle does: a line keeps its other point and its direction; an arc (the segments before the end that lie on one circle and turn the same way) keeps its other point, its circle and the way it turns, with a sweep of at most 359°. length runs from 0.001 to 1000000 pt for a line, and to 359° of the circle for an arc. A length the piece already has changes nothing; otherwise the path is selected, as one undo step → {id, kind: \"line\"|\"arc\", length}. An end that is neither straight nor a circular arc, a closed subpath, a locked or hidden path, a length outside the range and a result that would reach past the canvas are errors",
|
||||
has_doc,
|
||||
quick_pen_length
|
||||
),
|
||||
cmd!(
|
||||
"path.removeAnchor",
|
||||
"Delete Anchor Point",
|
||||
|
||||
@@ -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:?}");
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,12 @@
|
||||
//! The Quick Pen tool's command (`path.quickPen`): a path of straight lines and circular arcs.
|
||||
//! The Quick Pen tool's commands: `path.quickPen` draws a path of straight lines and circular arcs,
|
||||
//! and `path.quickPenLength` makes the line or arc at an end of a path longer or shorter.
|
||||
|
||||
use vectorcraft_tools::quickpen::length as qpl;
|
||||
use vectorcraft_tools::quickpen::{self as qp, Piece, Stroke};
|
||||
|
||||
use super::common::{path_kind, path_mut, point_entry, usize_opt, within_input_bound};
|
||||
use super::{Color, Paint, PathData, Result, Session, SubPath, Value, add_look, bad, json, number_or, object_param, switch_or};
|
||||
use crate::cmd::f64_req;
|
||||
|
||||
const C: &str = "path.quickPen";
|
||||
/// The most pieces one request takes.
|
||||
@@ -94,3 +97,58 @@ pub(super) fn quick_pen(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
})?;
|
||||
Ok(json!({ "id": id.0 }))
|
||||
}
|
||||
|
||||
const L: &str = "path.quickPenLength";
|
||||
|
||||
/// `path.quickPenLength`: the line or arc at an end of an open subpath made `length` long.
|
||||
pub(super) fn quick_pen_length(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let Some(id) = object_param(p, "id", L)? else { return Err(bad(L, "missing `id`")) };
|
||||
let si = usize_opt(p, "subpath", L)?.unwrap_or(0);
|
||||
let at_start = match p.get("end") {
|
||||
None | Some(Value::Null) => false,
|
||||
Some(v) => match v.as_str() {
|
||||
Some("end") => false,
|
||||
Some("start") => true,
|
||||
_ => {
|
||||
let key = "end";
|
||||
return Err(bad(L, format!("`{key}` must be one of {}", ["start", "end"].join(", "))));
|
||||
}
|
||||
},
|
||||
};
|
||||
let length = f64_req(p, "length", L)?;
|
||||
let d = &s.doc()?.doc;
|
||||
let path = d.node(id).and_then(|n| n.path_data()).ok_or_else(|| bad(L, "`id` is not a path"))?;
|
||||
if !d.is_editable(id) {
|
||||
return Err(bad(L, "the path is locked or hidden"));
|
||||
}
|
||||
let sp = path.subpaths.get(si).ok_or_else(|| bad(L, "no such subpath"))?;
|
||||
if sp.closed {
|
||||
return Err(bad(L, "the subpath is closed"));
|
||||
}
|
||||
let piece = qpl::end_piece(sp, at_start).ok_or_else(|| bad(L, "the end is not a straight line or a circular arc"))?;
|
||||
let (key, lo, hi) = ("length", qpl::MIN_LENGTH, piece.max_length());
|
||||
if !(lo..=hi).contains(&length) {
|
||||
// An arc's limit, 359° of its circle, is given to the thousandth of a point, rounded down.
|
||||
let hi = (hi * 1000.0).floor() / 1000.0;
|
||||
return Err(bad(L, format!("`{key}` must be from {lo} to {hi}")));
|
||||
}
|
||||
let out = qpl::with_length(sp, at_start, length).ok_or_else(|| bad(L, "the end is not a straight line or a circular arc"))?;
|
||||
if !qp::on_canvas(&out) {
|
||||
return Err(bad(L, "result would exceed the canvas (coordinates out of range)"));
|
||||
}
|
||||
let kind = match piece.shape {
|
||||
qpl::EndShape::Line => "line",
|
||||
qpl::EndShape::Arc { .. } => "arc",
|
||||
};
|
||||
if (length - piece.length).abs() <= 1e-9 * length.max(1.0) {
|
||||
return Ok(json!({ "id": id.0, "kind": kind, "length": piece.length }));
|
||||
}
|
||||
let top = super::super::path::compound_or_self(d, id);
|
||||
s.edit("Quick Pen", |d, sel| {
|
||||
let slot = path_mut(d, id)?.subpaths.get_mut(si).ok_or_else(|| crate::EngineError::Other("no such subpath".into()))?;
|
||||
*slot = out;
|
||||
sel.set([top]);
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "id": id.0, "kind": kind, "length": length }))
|
||||
}
|
||||
@@ -225,7 +225,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Clear",
|
||||
["Edit"],
|
||||
Some("Delete"),
|
||||
"{ids?, guides?: bool (with ids: also delete the selected ruler guides)} delete the objects `ids`, else the selection (fully selected objects and direct-selected anchors together, else ruler guides; a compound-path member selected on its own is deleted alone, and a compound left with no members goes too); without ids, refused while an object of a symbol instance's art is selected",
|
||||
"{ids?, guides?: bool (with ids: also delete the selected ruler guides), keepJoined?: bool (without ids: the direct-selected anchors of a path with no selected segment are removed as path.removeAnchors removes them, without opening the path, and the next anchor along is selected (the one before at an open path's end); default: prefs deleteKeepsPathsJoined)} delete the objects `ids`, else the selection (fully selected objects and direct-selected anchors together, else ruler guides; a compound-path member selected on its own is deleted alone, and a compound left with no members goes too); without ids, refused while an object of a symbol instance's art is selected",
|
||||
has_selection_or_guides,
|
||||
clear
|
||||
),
|
||||
@@ -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) => {
|
||||
@@ -1221,6 +1224,7 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
|
||||
|
||||
fn clear(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let guides = switch_or(p, "guides", false, "edit.clear")?;
|
||||
switch_or(p, "keepJoined", false, "edit.clear")?;
|
||||
let explicit = if p.get("ids").is_some() { Some(checked_ids_param(s, p, "ids", "edit.clear")?) } else { None };
|
||||
// An object of a symbol instance's art can't be removed from the instance alone.
|
||||
if explicit.is_none() && s.doc()?.selection.symbol_part.is_some() {
|
||||
@@ -1228,7 +1232,8 @@ fn clear(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
// Direct-selected anchors or segments: remove those, and any objects selected whole with them.
|
||||
if explicit.is_none() && (!s.doc()?.selection.anchors.is_empty() || !s.doc()?.selection.segments.is_empty()) {
|
||||
return super::path::delete_anchors(s, p);
|
||||
let keep_joined = keeps_paths_joined(s, p)?;
|
||||
return super::path::delete_anchors_joined(s, p, keep_joined);
|
||||
}
|
||||
// Selected ruler guides (selected on their own).
|
||||
if explicit.is_none() && s.doc()?.selection.is_empty() {
|
||||
@@ -1275,6 +1280,17 @@ fn clear(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
ok()
|
||||
}
|
||||
|
||||
/// Does Clear remove direct-selected anchors without opening their paths (`keepJoined` param, else
|
||||
/// General › Delete Removes Anchor Points and Keeps Paths Joined)? Noted in the journal, so a
|
||||
/// replay removes them the same way whatever the preference is at the time. A saved step without `keepJoined`
|
||||
/// was recorded before the preference existed, so it opens the paths as it did then.
|
||||
fn keeps_paths_joined(s: &mut Session, p: &Value) -> Result<bool> {
|
||||
let default = s.prefs.delete_keeps_paths_joined && !s.replaying();
|
||||
let on = switch_or(p, "keepJoined", default, "edit.clear")?;
|
||||
s.note_journal("keepJoined", json!(on));
|
||||
Ok(on)
|
||||
}
|
||||
|
||||
/// Document ids scope node ids: two tabs may contain objects with the same node id.
|
||||
fn drop_selection(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "edit.dropSelection";
|
||||
|
||||
@@ -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
|
||||
)]
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -128,7 +128,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export PDF",
|
||||
[],
|
||||
None,
|
||||
"{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning, and so does a count of the visible objects that reach the trim edge (within 0.5 pt) on a side with a bleed but end before the bleed edge; layers that don't print are left out unless includeNonPrinting, and art and boxes are written unchanged). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in
Line truncated
|
||||
"{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning, and so does a count of the visible objects that reach the trim edge (within 0.5 pt) on a side with a bleed but end before the bleed edge; layers that don't print are left out unless includeNonPrinting, and art and boxes are written unchanged). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in
Line truncated
|
||||
has_doc,
|
||||
export_pdf
|
||||
),
|
||||
|
||||
@@ -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,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -333,6 +333,66 @@ fn an_item_opacity_on_a_series_mark_survives_regeneration() {
|
||||
assert_eq!((kept.fill_opacity, kept.stroke_opacity), (Some(0.4), None));
|
||||
}
|
||||
|
||||
/// `paint.setFill {opacity}` and `paint.setStroke {opacity}` on one series mark are kept by the graph as the transparency
|
||||
/// commands' item opacity is: every path of that series has them after the graph is drawn again.
|
||||
#[test]
|
||||
fn a_paint_opacity_on_a_series_mark_survives_regeneration() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let bar = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].id;
|
||||
s.execute("paint.setFill", &json!({"ids": [bar.0], "opacity": 40})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [bar.0], "color": "#ff0000", "opacity": 60})).unwrap();
|
||||
let kept = spec(&s, id).series_paints[0].clone();
|
||||
assert_eq!((kept.fill_opacity, kept.stroke_opacity), (Some(0.4), Some(0.6)));
|
||||
s.execute("graph.setData", &json!({"rows": [[1, 2], [3, 4]]})).unwrap();
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
let marks = series(&n, 0).children().unwrap().to_vec();
|
||||
let opacities: Vec<(f32, f32)> = marks.iter().map(|m| (m.appearance.fill().unwrap().opacity, m.appearance.stroke().unwrap().opacity)).collect();
|
||||
assert!(opacities.iter().all(|o| *o == (0.4, 0.6)), "{opacities:?}");
|
||||
}
|
||||
|
||||
/// `paint.setFill {opacity}` and `paint.setStroke {opacity}` with the opacity a mark already shows replace the opacity
|
||||
/// another mark of the series left on the graph, as an explicit 100% does.
|
||||
#[test]
|
||||
fn a_paint_opacity_a_series_mark_already_shows_replaces_the_kept_opacity() {
|
||||
let (mut s, id, _, marks) = column_marks();
|
||||
s.execute("paint.setFill", &json!({"ids": [marks[0].0], "opacity": 40})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [marks[0].0], "opacity": 60})).unwrap();
|
||||
let kept = spec(&s, id).series_paints[0].clone();
|
||||
assert_eq!((kept.fill_opacity, kept.stroke_opacity), (Some(0.4), Some(0.6)));
|
||||
// The second mark is opaque already: its row comes out as it was.
|
||||
s.execute("paint.setFill", &json!({"ids": [marks[1].0], "color": "#ff0000", "opacity": 100})).unwrap();
|
||||
let kept = spec(&s, id).series_paints[0].clone();
|
||||
assert_eq!((kept.fill_opacity, kept.stroke_opacity), (None, Some(0.6)));
|
||||
s.execute("paint.setStroke", &json!({"ids": [marks[1].0], "opacity": 100})).unwrap();
|
||||
let kept = spec(&s, id).series_paints[0].clone();
|
||||
assert_eq!((kept.fill_opacity, kept.stroke_opacity), (None, None));
|
||||
s.execute("graph.setData", &json!({"rows": [[1, 2], [3, 4]]})).unwrap();
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
let opacities: Vec<(f32, f32)> =
|
||||
series(&n, 0).children().unwrap().iter().map(|m| (m.appearance.fill().unwrap().opacity, m.appearance.stroke().unwrap().opacity)).collect();
|
||||
assert!(opacities.iter().all(|o| *o == (1.0, 1.0)), "{opacities:?}");
|
||||
}
|
||||
|
||||
/// The same for a graph's axis lines: a stroke opacity set on an opaque line replaces the one its kind keeps from another
|
||||
/// line.
|
||||
#[test]
|
||||
fn a_stroke_opacity_an_axis_line_already_shows_replaces_the_kept_opacity() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let lines = line_nodes(&s, id);
|
||||
s.execute("paint.setStroke", &json!({"ids": [lines[0].id.0], "opacity": 40})).unwrap();
|
||||
let kept = |s: &Session| spec(s, id).label_styles.axis_rows.and_then(|r| r.paint.stroke_opacity);
|
||||
assert_eq!(kept(&s), Some(0.4));
|
||||
s.execute("paint.setStroke", &json!({"ids": [lines[1].id.0], "opacity": 100})).unwrap();
|
||||
assert_eq!(kept(&s), None);
|
||||
s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap();
|
||||
let opacities: Vec<f32> = line_nodes(&s, id).iter().map(|n| n.appearance.stroke().map_or(1.0, |st| st.opacity)).collect();
|
||||
assert!(opacities.iter().all(|o| *o == 1.0), "{opacities:?}");
|
||||
}
|
||||
|
||||
/// Clear Appearance and Reduce to Basic Appearance on a series mark take its fill and stroke opacity away, and the
|
||||
/// graph keeps none, so the series stays opaque when it is drawn again.
|
||||
#[test]
|
||||
@@ -1424,6 +1484,27 @@ fn paint_targets_leave_a_graph_designs_copy_out() {
|
||||
assert_eq!(super::paint_targets(d, &[copy, art, mark]), [mark]);
|
||||
}
|
||||
|
||||
/// The fill opacity the proxies show leaves out the art of a column or marker design in a series, which
|
||||
/// `paint.setFill {opacity}` leaves out too: with only that art selected there is none, also with a row of the art
|
||||
/// active, and with a mark selected after it the mark's.
|
||||
#[test]
|
||||
fn proxy_opacity_leaves_a_graph_designs_art_out() {
|
||||
let (mut s, _, _, art, mark) = design_art();
|
||||
let (mut m, _, marker_art) = marker_design_art();
|
||||
for (s, art) in [(&mut s, art), (&mut m, marker_art)] {
|
||||
s.execute("select.set", &json!({"ids": [art.0]})).unwrap();
|
||||
assert_eq!(s.proxy_opacity(false), None);
|
||||
assert!(s.execute("paint.setFill", &json!({"opacity": 50})).is_err());
|
||||
let fill = top_row(s, art, true);
|
||||
s.execute("appearance.setActiveItem", &json!({"index": fill})).unwrap();
|
||||
assert_eq!(s.proxy_opacity(false), None, "with the art's fill row active");
|
||||
assert!(s.execute("paint.setFill", &json!({"opacity": 50})).is_err());
|
||||
}
|
||||
s.execute("paint.setFill", &json!({"ids": [mark.0], "opacity": 40})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [art.0, mark.0]})).unwrap();
|
||||
assert!((s.proxy_opacity(false).unwrap() - 0.4).abs() < 1e-6, "the mark's fill opacity");
|
||||
}
|
||||
|
||||
/// The art of a marker design in series 1 of a line graph: the design's copy and a path inside it.
|
||||
fn marker_design_art() -> (Session, NodeId, NodeId) {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -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
|
||||
),
|
||||
|
||||
@@ -1360,7 +1360,7 @@ fn use_pattern(s: &mut Session, data: &Value, stroke: bool, only: bool) -> Resul
|
||||
// or spot color the pattern's art links to keeps the library's color, as Add to Swatches brings
|
||||
// a library pattern's colors.
|
||||
let current = s.doc()?.doc.clone();
|
||||
let (choices, probe, imported) = super::patternlib::probe_import(¤t, &doc, &name, &clip)?;
|
||||
let (choices, probe, imported) = super::patternlib::probe_import(¤t, &doc, &name, &clip, &Default::default())?;
|
||||
drop(current);
|
||||
let target = super::patternlib::imported_name(&imported, &name);
|
||||
let paint = vectorcraft_doc::pattern::pattern_paint(&target);
|
||||
|
||||
@@ -187,7 +187,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Rearrange All Artboards…",
|
||||
["Object", "Artboards"],
|
||||
None,
|
||||
"{layout?: gridByRow|gridByColumn|row|column (gridByRow; byColumn?: true is gridByColumn), order?: leftToRight|rightToLeft (leftToRight: right-to-left mirrors the order along the rows), columns?: n (2; the rows for gridByColumn; row and column ignore it), spacing?: pt (20), moveArtwork?: true (each object of a layer or sublayer moves with the artboard its center is on; locked and hidden art, and art on a locked artboard, only with lockedAndHidden), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), lockedAndHidden?: bool (default: prefs moveLockedWithArtboard), byColumn?: bool (an older way to ask for layout gridByColumn)} lay the artboards out in their order, the grid's top-left at the first artboard's; a locked artboard stays where it is → {artboards, rows, columns}",
|
||||
"{layout?: gridByRow|gridByColumn|row|column (gridByRow; byColumn?: true is gridByColumn), order?: leftToRight|rightToLeft (leftToRight: right-to-left mirrors the order along the rows), columns?: n (2; the rows for gridByColumn; row and column ignore it), spacing?: pt (20), moveArtwork?: true (each object of a layer or sublayer moves with the artboard its center is on; locked and hidden art, and art on a locked artboard, only with lockedAndHidden), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), lockedAndHidden?: bool (default: prefs moveLockedWithArtboard), byColumn?: bool (an older way to ask for layout gridByColumn), indices?: [n] (lay out only these artboards, in document order; the others and their art and guides stay where they are), at?: [x, y] (the grid's top-left)} lay the artboards out in their order, the grid's top-left at `at`, else at the first artboard's laid out; a locked artboard stays where it is and keeps its place in the grid → {artboards, rows, columns; with indices also indices and moved, the count of artboards that moved}",
|
||||
has_doc,
|
||||
rearrange_artboards
|
||||
),
|
||||
@@ -1718,32 +1718,48 @@ fn rearrange_artboards(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(_) => return Err(bad(CMD, "order must be leftToRight or rightToLeft")),
|
||||
};
|
||||
let count = s.doc()?.doc.artboards.len();
|
||||
let n_ab = count.max(1);
|
||||
// Columns of a grid by row, rows of a grid by column.
|
||||
let lines = whole_or(p, "columns", 2, CMD)?.clamp(1, n_ab as u64) as usize;
|
||||
let (rows, cols) = match layout {
|
||||
L::GridByRow => (n_ab.div_ceil(lines), lines),
|
||||
L::GridByColumn => (lines, n_ab.div_ceil(lines)),
|
||||
L::Row => (1, n_ab),
|
||||
L::Column => (n_ab, 1),
|
||||
// `indices` lays out only those artboards, in document order; left out, every artboard.
|
||||
let picked: Option<Vec<usize>> = match p.get("indices") {
|
||||
Some(v) => Some(super::panelcmds::listed_artboards(&s.doc()?.doc, v, "indices", CMD)?),
|
||||
None => None,
|
||||
};
|
||||
let at = match p.get("at") {
|
||||
Some(v) => Some(super::finite_numbers::<2>(v).map(|[x, y]| Point::new(x, y)).ok_or_else(|| bad(CMD, "`at` must be [x, y]"))?),
|
||||
None => None,
|
||||
};
|
||||
// Columns of a grid by row, rows of a grid by column.
|
||||
let lines = whole_or(p, "columns", 2, CMD)?;
|
||||
check_numbers(p, &["spacing"], CMD)?;
|
||||
let spacing = f64_or(p, "spacing", 20.0).clamp(-1.0e5, 1.0e5);
|
||||
let move_art = switch_or(p, "moveArtwork", true, CMD)?;
|
||||
check_switches(p, &["patterns"], CMD)?;
|
||||
let locked_and_hidden = super::panelcmds::locked_and_hidden(s, p, move_art, CMD)?;
|
||||
let d = &s.doc()?.doc;
|
||||
let rects: Vec<Rect> = d.artboards.iter().map(|a| a.rect).collect();
|
||||
let laid: Vec<usize> = picked.clone().unwrap_or_else(|| (0..count).collect());
|
||||
let rects: Vec<Rect> = laid.iter().filter_map(|i| d.artboards.get(*i)).map(|a| a.rect).collect();
|
||||
let sizes: Vec<(f64, f64)> = rects.iter().map(|r| (r.width(), r.height())).collect();
|
||||
let first = rects.first().map_or(Point::ZERO, |r| r.origin());
|
||||
let origins = super::newdoc::grid_origins_rc(&sizes, first, (rows, cols), spacing, layout == L::GridByColumn, rtl);
|
||||
// A locked artboard stays where it is, and keeps its place in the grid.
|
||||
let deltas: Vec<Vec2> =
|
||||
rects.iter().zip(origins).zip(&d.artboards).map(|((r, o), a)| if a.locked { Vec2::ZERO } else { o - r.origin() }).collect();
|
||||
// The grid's top-left: `at`, else the first artboard laid out's.
|
||||
let origin = at.unwrap_or_else(|| rects.first().map_or(Point::ZERO, |r| r.origin()));
|
||||
let (origins, rows, cols) = super::newdoc::rearrange_grid(&sizes, origin, layout, lines, spacing, rtl);
|
||||
// A locked artboard stays where it is, and keeps its place in the grid; an artboard not laid
|
||||
// out stays where it is.
|
||||
let mut deltas = vec![Vec2::ZERO; count];
|
||||
for ((i, r), o) in laid.iter().zip(&rects).zip(origins) {
|
||||
if let Some(dl) = deltas.get_mut(*i)
|
||||
&& !d.artboards.get(*i).is_some_and(|a| a.locked)
|
||||
{
|
||||
*dl = o - r.origin();
|
||||
}
|
||||
}
|
||||
let moved = deltas.iter().filter(|dl| dl.x.abs() > 1e-9 || dl.y.abs() > 1e-9).count();
|
||||
let result = match &picked {
|
||||
Some(indices) => json!({ "artboards": count, "indices": indices, "moved": moved, "rows": rows, "columns": cols }),
|
||||
None => json!({ "artboards": count, "rows": rows, "columns": cols }),
|
||||
};
|
||||
// When no artboard moves more than 1e-9 pt on either axis, or there is none, the document and
|
||||
// its undo history stay as they are.
|
||||
if deltas.iter().all(|dl| dl.x.abs() <= 1e-9 && dl.y.abs() <= 1e-9) {
|
||||
return Ok(json!({ "artboards": count, "rows": rows, "columns": cols }));
|
||||
if moved == 0 {
|
||||
return Ok(result);
|
||||
}
|
||||
// With moveArtwork, each top-level object (a child of a layer or sublayer) moves with the
|
||||
// artboard its center is on, with symbol instances measured by their art as
|
||||
@@ -1791,5 +1807,5 @@ fn rearrange_artboards(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "artboards": count, "rows": rows, "columns": cols }))
|
||||
Ok(result)
|
||||
}
|
||||
@@ -601,6 +601,30 @@ pub(crate) fn grid_origins_rc(
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Rearrange Artboards' grid for artboards of `sizes`, in their order, its top-left at `origin`:
|
||||
/// `lines` is the column count of a grid by row and the row count of a grid by column (kept to 1
|
||||
/// to the artboard count), and `rtl` puts the first column at the right. Returns each artboard's
|
||||
/// top-left corner and the grid's rows and columns.
|
||||
pub fn rearrange_grid(
|
||||
sizes: &[(f64, f64)],
|
||||
origin: Point,
|
||||
layout: ArtboardLayout,
|
||||
lines: u64,
|
||||
spacing: f64,
|
||||
rtl: bool,
|
||||
) -> (Vec<Point>, usize, usize) {
|
||||
let n = sizes.len().max(1);
|
||||
let lines = usize::try_from(lines).unwrap_or(usize::MAX).clamp(1, n);
|
||||
let (rows, cols) = match layout {
|
||||
ArtboardLayout::GridByRow => (n.div_ceil(lines), lines),
|
||||
ArtboardLayout::GridByColumn => (lines, n.div_ceil(lines)),
|
||||
ArtboardLayout::Row => (1, n),
|
||||
ArtboardLayout::Column => (n, 1),
|
||||
};
|
||||
let origins = grid_origins_rc(sizes, origin, (rows, cols), spacing, layout == ArtboardLayout::GridByColumn, rtl);
|
||||
(origins, rows, cols)
|
||||
}
|
||||
|
||||
/// The built-in presets: (category, presets as (name, width, height, units)), with the category's
|
||||
/// colour mode and raster effects resolution. Sizes in `units` (converted to points on use).
|
||||
type Category = (&'static str, ColorMode, f64, &'static [(&'static str, f64, f64, Unit)]);
|
||||
|
||||
@@ -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
|
||||
),
|
||||
|
||||
@@ -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);
|
||||
|
||||
+290
-97
@@ -27,7 +27,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Fill",
|
||||
[],
|
||||
None,
|
||||
"{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), ids?|id?, defaultsOnly?: bool, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a Live Paint group among the targets (or inside one) takes the fill on its faces only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did; on a graph's axis line, tick mark or radar ring, its rows for every line of its kind. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given, only the default changes (the color the bucket paints with) and the selection keeps its paint; `defaultsOnly` with ids, id or item is refused, and the journal records a change the bucket made this way with `defaultsOnly: true`, so a replay with another tool active changes the default too → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}",
|
||||
"{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), opacity?: 0..100 (a percentage, as transparency.set's; the opacity of that fill item on each target, in the undo step of the paint, or alone without color, none, swatch or gradient, when it changes neither the defaults nor the recent colors (with New Art Has Basic Appearance off, the next shape copies the first selected object's appearance after any command, its opacity included); with no paint or a solid color, the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso take it themselves, and with another paint the fill item takes it; with no paint, a target without that fill item is left as it is (a paint given with the opacity creates the item, which then takes it, except for the color a grayscale or 1-bit image is drawn in, which creates none), and an opacity that no target takes is an error that also leaves the paint undone; type characters have no opacity of their own, so an opacity that only characters would take is an error, and so are one with nothing selected and no ids and one for an object selected in a symbol instance), ids?|id?, defaultsOnly?: bool, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids, id or item are given), the paint goes to those characters only; without `item`, a Live Paint group among the targets (or inside one) takes the fill on its faces only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row o
Line truncated
|
||||
has_doc,
|
||||
|s, p| set_paint(s, p, true)
|
||||
),
|
||||
@@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Stroke",
|
||||
[],
|
||||
None,
|
||||
"{…as paint.setFill, item?: the stroke item to set, aligned?: bool (as paint.setFill)} same as paint.setFill, for the stroke; without `item`, a Live Paint group among the targets (or inside one) takes the stroke on its edges only; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's stroke changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint and weight of the topmost visible stroke when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, as paint.setFill",
|
||||
"{…as paint.setFill, item?: the stroke item to set, aligned?: bool (as paint.setFill), opacity?: 0..100 (the opacity of that stroke item, as paint.setFill's for the fill item)} same as paint.setFill, for the stroke; without `item`, a Live Paint group among the targets (or inside one) takes the stroke on its edges only; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's stroke changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint and weight of the topmost visible stroke when the command wrote that row or changed it, and its opacity when `opacity` changed it (exceptions: docs/mcp.md); on a graph label, as paint.setFill",
|
||||
has_doc,
|
||||
|s, p| { set_paint(s, p, false) }
|
||||
),
|
||||
@@ -161,7 +161,7 @@ pub fn proxy_specs() -> Vec<CommandSpec> {
|
||||
"Fill and Stroke",
|
||||
[],
|
||||
None,
|
||||
"{} → {fill, stroke: the paints the Fill/Stroke proxies show (the Appearance panel's active item for the proxy of its kind, else the first selected object's, a group's first painted object's, a Live Paint group's first face's fill and first edge's stroke, type: its first run's; else the defaults for new art; when that object is a gradient mesh with points picked by the Mesh tool, Direct Selection or the Lasso and no fill item is active, the fill is its first picked point's color), fillActive, fillMixed, strokeMixed: the selected objects' (or a selected group's contents') fills (strokes) differ, a Live Paint group counting with its faces' fills and its edges' strokes, shown as a \"?\" proxy (a gradient mesh with points picked counts with their colors)}",
|
||||
"{} → {fill, stroke: the paints the Fill/Stroke proxies show (the Appearance panel's active item for the proxy of its kind, else the first selected object's, a group's first painted object's, a Live Paint group's first face's fill and first edge's stroke, type: its first run's; else the defaults for new art; when that object is a gradient mesh with points picked by the Mesh tool, Direct Selection or the Lasso and no fill item is active, the fill is its first picked point's color), fillActive, fillMixed, strokeMixed: the selected objects' (or a selected group's contents') fills (strokes) differ, a Live Paint group counting with its faces' fills and its edges' strokes, shown as a \"?\" proxy (a gradient mesh with points picked counts with their colors), fillOpacity, strokeOpacity: 0..100, the opacity of the fill item that paint.setFill {opacity} sets (the stroke item that paint.setStroke {opacity} sets), from the first selected object (or painted object in a selected group; a selected path of a compound path stands for its compound, and a Live Paint group for its faces' fills and its edges' strokes) that has one (a gradient mesh's first picked point's), or null with nothing selected (the defaults for new art), for an object selected in a symbol instance, while the Live Paint Bucket is the active tool, while the Type tool has characters selected, and when only type characters or objects without that item are selected}",
|
||||
always,
|
||||
proxies
|
||||
),
|
||||
@@ -239,6 +239,80 @@ impl Session {
|
||||
None
|
||||
}
|
||||
|
||||
/// The opacity (0..1) of the fill that `paint.setFill {opacity}` sets (or of the stroke that
|
||||
/// `paint.setStroke {opacity}` sets): the item's, or for a gradient mesh with points picked the
|
||||
/// first picked point's. The rows the command would edit are read in order (a group without an
|
||||
/// active Appearance row stands for its contents), and the first that exists answers. `None`
|
||||
/// with nothing selected, for an object selected in a symbol instance, while the Live Paint
|
||||
/// Bucket is the active tool (or another tool works for it, [`Session::bucket_paints`]), while
|
||||
/// the Type tool has characters selected, and when only type
|
||||
/// characters, objects without that item or the art of graph designs in a graph series are
|
||||
/// selected.
|
||||
pub fn proxy_opacity(&self, stroke: bool) -> Option<f32> {
|
||||
let st = self.active()?;
|
||||
// The Live Paint Bucket takes a fill or stroke chosen as the color it paints with, and the
|
||||
// selection keeps its own (for_bucket).
|
||||
if st.selection.symbol_part.is_some() || self.bucket_paints() {
|
||||
return None;
|
||||
}
|
||||
// The command would give the opacity to the characters, which have none of their own.
|
||||
if super::textedit::selected_range(self).is_some_and(|(_, a, b)| a != b) {
|
||||
return None;
|
||||
}
|
||||
let item = self.appearance_item();
|
||||
let of = |n: &Node, item: Option<usize>| -> Option<f32> {
|
||||
if item.is_none() && matches!(n.kind, NodeKind::Text(_)) {
|
||||
return None;
|
||||
}
|
||||
if !stroke
|
||||
&& item.is_none()
|
||||
&& let NodeKind::Mesh(m) = &n.kind
|
||||
&& let Some((_, points)) = picked_mesh_points(self, &[n.id]).first()
|
||||
{
|
||||
return points.first().and_then(|i| m.points.get(*i)).map(|q| q.opacity);
|
||||
}
|
||||
if stroke { n.appearance.stroke_at(item).map(|s| s.opacity) } else { n.appearance.fill_at(item).map(|f| f.opacity) }
|
||||
};
|
||||
let subjects = st.selection.subjects();
|
||||
// The command leaves out the art of a graph design in a series, which the graph draws again
|
||||
// from the design, and a series group stands for the paths directly in it
|
||||
// (graph::paint_targets).
|
||||
let editable = |id: &&NodeId| !super::graph::is_design_art(&st.doc, **id);
|
||||
// As the command picks its rows (ItemTarget::of_kind): the active item when it is a row of
|
||||
// this kind in the first selected object's stack, read in the stacks the command edits;
|
||||
// else the topmost one of the painted leaves of the selected objects (a group's
|
||||
// contents; for a targeted layer, its editable art, ItemTarget::targets). A row of a
|
||||
// graph design's art selected first stands for nothing (item_target_at).
|
||||
let first = subjects.first().filter(editable).and_then(|id| st.doc.node(*id));
|
||||
let active = item.filter(|i| first.and_then(|n| n.appearance.items.get(*i)).is_some_and(|it| it.is_fill() == !stroke));
|
||||
if let Some(index) = active {
|
||||
// The objects whose own stacks the command edits (appearance_targets: a selected
|
||||
// compound-path member stands for its compound, and an object inside another selected
|
||||
// one is left out), with the one whose stack the row belongs to first.
|
||||
// Each target reads the row the command edits there (ItemTarget::per_target and
|
||||
// ItemTarget::resolve): the row equal to the active one, else its topmost of the kind.
|
||||
let row = ItemTarget::Item { index, explicit: false, aligned: true };
|
||||
let mut roots = super::appearance::appearance_targets(self, &Value::Null).ok()?;
|
||||
let anchor = row.anchor(self, &roots);
|
||||
if let Some(head) = roots.get_mut(..=anchor) {
|
||||
head.rotate_right(1);
|
||||
}
|
||||
let targets: Vec<NodeId> = super::graph::series_group_marks_where(&st.doc, &roots, |n| n.extras().series_index.is_some())
|
||||
.into_iter()
|
||||
.filter(|id| editable(&id))
|
||||
.collect();
|
||||
return targets.iter().zip(row.per_target(self, &targets)).find_map(|(id, at)| {
|
||||
let n = st.doc.node(*id)?;
|
||||
of(n, at?.resolve(&n.appearance, !stroke, "paint.proxies").ok()?)
|
||||
});
|
||||
}
|
||||
// A Live Paint group stands for its faces in a fill edit and for its edges in a stroke edit
|
||||
// (ItemTarget::targets_for).
|
||||
let leaves = super::leaf_targets(self, &st.selection.objects).ok()?;
|
||||
let skipped = live_paint_parts_skipped(&st.doc, &st.selection.objects, !stroke);
|
||||
leaves.iter().filter(editable).filter(|id| !skipped.contains(*id)).filter_map(|id| st.doc.node(*id)).find_map(|n| of(n, None))
|
||||
}
|
||||
|
||||
pub(crate) fn remember_paint_now(&mut self, p: &Paint) {
|
||||
match p {
|
||||
Paint::Solid { color, .. } => {
|
||||
@@ -483,7 +557,12 @@ impl Session {
|
||||
fn proxies(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let (fill, stroke) = s.proxy_paints();
|
||||
let (fill_mixed, stroke_mixed) = s.proxy_mixed();
|
||||
Ok(json!({"fill": fill, "stroke": stroke, "fillActive": s.fill_active, "fillMixed": fill_mixed, "strokeMixed": stroke_mixed}))
|
||||
// As transparency.info answers an opacity: a percentage to two places.
|
||||
let percent = |o: Option<f32>| o.map(|o| (f64::from(o) * 10_000.0).round() / 100.0);
|
||||
Ok(json!({
|
||||
"fill": fill, "stroke": stroke, "fillActive": s.fill_active, "fillMixed": fill_mixed, "strokeMixed": stroke_mixed,
|
||||
"fillOpacity": percent(s.proxy_opacity(false)), "strokeOpacity": percent(s.proxy_opacity(true)),
|
||||
}))
|
||||
}
|
||||
|
||||
/// `stroke` param, defaulting to the proxy that is in front.
|
||||
@@ -602,13 +681,36 @@ fn set_paint(s: &mut Session, p: &Value, fill: bool) -> Result<Value> {
|
||||
return Err(bad(cmd, "`tint` goes with a global or spot `swatch`"));
|
||||
}
|
||||
check_keep_model(p, cmd)?;
|
||||
let paint = paint_from(s, p)?.ok_or_else(|| bad(cmd, "give color, none, swatch or gradient"))?;
|
||||
let opacity = opacity_param(p, cmd)?;
|
||||
let paint = paint_from(s, p)?;
|
||||
// A `swatch` that is no name gives no paint, and does not turn the request into an opacity alone.
|
||||
let swatch_not_a_name = p.get("swatch").is_some_and(|v| !v.is_null() && !v.is_string());
|
||||
if paint.is_none() && (opacity.is_none() || swatch_not_a_name) {
|
||||
return Err(bad(cmd, "give color, none, swatch, gradient or opacity"));
|
||||
}
|
||||
// As `paint.editGradient`: a `dither` given applies to gradient fills only. A gradient swatch
|
||||
// (named) keeps its own dither; `"swatch": null` names none.
|
||||
if !fill && matches!(&paint, Paint::Gradient(g) if g.gradient.dither) && p.get("swatch").and_then(Value::as_str).is_none() {
|
||||
if !fill && matches!(&paint, Some(Paint::Gradient(g)) if g.gradient.dither) && p.get("swatch").and_then(Value::as_str).is_none() {
|
||||
return Err(bad(cmd, "`dither` applies to gradient fills (paint.setFill)"));
|
||||
}
|
||||
apply_paint(s, p, paint, fill)
|
||||
apply_paint_opacity(s, p, paint, opacity, fill)
|
||||
}
|
||||
|
||||
/// The `opacity` param of `paint.setFill` and `paint.setStroke` (a percentage) as 0..1; `None`
|
||||
/// when it is left out or null.
|
||||
fn opacity_param(p: &Value, cmd: &str) -> Result<Option<f32>> {
|
||||
match p.get("opacity") {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(v) => match v.as_f64() {
|
||||
Some(o) if (0.0..=100.0).contains(&o) => Ok(Some((o / 100.0) as f32)),
|
||||
_ => Err(bad(cmd, "`opacity` must be a number from 0 to 100")),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// The error for an `opacity` that would go to type characters, which have no opacity of their own.
|
||||
fn characters_have_no_opacity(cmd: &str) -> EngineError {
|
||||
bad(cmd, "type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke")
|
||||
}
|
||||
|
||||
/// [`apply_paint`] on the proxy named by `stroke` (default: the active one), focusing it.
|
||||
@@ -621,17 +723,31 @@ fn apply_to_proxy(s: &mut Session, p: &Value, paint: Paint, cmd: &str) -> Result
|
||||
/// `paint.setFill`) and of the defaults for new art, focus its proxy unless `focus` is false, and
|
||||
/// remember the paint. Replies `{objects}`: how many objects took the paint.
|
||||
pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool) -> Result<Value> {
|
||||
apply_paint_opacity(s, p, Some(paint), None, fill)
|
||||
}
|
||||
|
||||
/// [`apply_paint`] with `paint` optional, which also sets the `opacity` (0..1) of the fill (or
|
||||
/// stroke) item each target takes it on, in the same undo step: the picked gradient mesh points'
|
||||
/// own opacity for a fill (with no paint or a solid color), nothing on a target without that item.
|
||||
/// The opacity alone changes neither the defaults for new art nor the remembered colors; with New
|
||||
/// Art Has Basic Appearance off, new art copies the first selected object's appearance after any
|
||||
/// command, its opacity included. An opacity that would go only to type
|
||||
/// characters, to an object selected in a symbol instance, or to no target at all is an error.
|
||||
fn apply_paint_opacity(s: &mut Session, p: &Value, paint: Option<Paint>, opacity: Option<f32>, fill: bool) -> Result<Value> {
|
||||
let cmd = if fill { "paint.setFill" } else { "paint.setStroke" };
|
||||
let bucket = bucket_color_params(s, p, cmd)?;
|
||||
let p = bucket.as_ref().unwrap_or(p);
|
||||
let focus = switch_or(p, "focus", true, cmd)?;
|
||||
let span = spans_targets(p, &paint).map_err(|e| bad(cmd, e))?;
|
||||
// Characters selected with the Type tool take the paint, not the whole type object (#1063).
|
||||
if p.get("ids").is_none()
|
||||
// An opacity alone places no gradient, so `span` may only be "object" with it.
|
||||
let span = spans_targets(p, paint.as_ref().unwrap_or(&Paint::None)).map_err(|e| bad(cmd, e))?;
|
||||
// Characters selected with the Type tool take the paint, not the whole type object (#1063). A
|
||||
// null `ids` or `id` names no object, as `given_nodes` reads it.
|
||||
if ["ids", "id"].iter().all(|k| p.get(k).is_none_or(Value::is_null))
|
||||
&& p.get("item").is_none()
|
||||
&& let Some((id, a, b)) = super::textedit::editing_range(s)?
|
||||
&& a != b
|
||||
{
|
||||
let (Some(paint), None) = (paint, opacity) else { return Err(characters_have_no_opacity(cmd)) };
|
||||
// After Select All in threaded text, every frame's text takes it.
|
||||
let story = super::textedit::editing_story(s);
|
||||
let ranges: Vec<(NodeId, usize, usize)> =
|
||||
@@ -684,6 +800,9 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool)
|
||||
// An object of a dynamic symbol instance's art selected with Direct Selection: that object's
|
||||
// fill or stroke changes for this instance only (solid, none, gradient or pattern).
|
||||
if let Some((id, path)) = selected_part_target(s, p, cmd)? {
|
||||
let Some(paint) = paint.filter(|_| opacity.is_none()) else {
|
||||
return Err(bad(cmd, "an object selected in a symbol instance has no fill or stroke opacity of its own"));
|
||||
};
|
||||
super::brushsym::edit_part(s, id, &path, if fill { "Fill Color" } else { "Stroke Color" }, |o| {
|
||||
if fill {
|
||||
o.fill = Some(paint.clone());
|
||||
@@ -702,36 +821,146 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool)
|
||||
let item = item_target(s, p, cmd)?.of_kind(s, fill);
|
||||
let selected = item.targets_for(s, p, fill)?;
|
||||
let ids = super::graph::paint_targets(&s.doc()?.doc, &selected);
|
||||
// An opacity has nothing to go to without targets; with a paint, the defaults then stay too.
|
||||
if opacity.is_some() && ids.is_empty() {
|
||||
return Err(bad(cmd, "select objects or give ids"));
|
||||
}
|
||||
let of = super::appearance::reference_of(s, p, item, cmd)?;
|
||||
let paint = if span {
|
||||
// With a design's art, the gradient spans only the objects with a row equal to the art's, which take it. Each
|
||||
// object's box is that of the row it edits.
|
||||
let d = &s.doc()?.doc;
|
||||
let mut spanned = Vec::with_capacity(ids.len());
|
||||
for (id, it) in ids.iter().zip(item.per_target_of(s, of, &ids)) {
|
||||
let (Some(it), Some(n)) = (it, d.node(*id)) else { continue };
|
||||
spanned.push((*id, it.resolve(&n.appearance, fill, cmd)?));
|
||||
let paint = match paint {
|
||||
Some(paint) if span => {
|
||||
// With a design's art, the gradient spans only the objects with a row equal to the art's, which take it. Each
|
||||
// object's box is that of the row it edits.
|
||||
let d = &s.doc()?.doc;
|
||||
let mut spanned = Vec::with_capacity(ids.len());
|
||||
for (id, it) in ids.iter().zip(item.per_target_of(s, of, &ids)) {
|
||||
let (Some(it), Some(n)) = (it, d.node(*id)) else { continue };
|
||||
spanned.push((*id, it.resolve(&n.appearance, fill, cmd)?));
|
||||
}
|
||||
Some(placed_across(d, &spanned, paint, p, fill))
|
||||
}
|
||||
placed_across(d, &spanned, paint, p, fill)
|
||||
} else {
|
||||
paint
|
||||
paint => paint,
|
||||
};
|
||||
// The gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso: a solid
|
||||
// fill recolors just those points of their meshes (the proxies show them: `fill_mesh_points`).
|
||||
let mesh_points = if fill && matches!(paint, Paint::Solid { .. }) { picked_mesh_points(s, &ids) } else { vec![] };
|
||||
// fill recolors just those points of their meshes (the proxies show them: `fill_mesh_points`),
|
||||
// and a fill opacity fades just them.
|
||||
let mesh_points = if fill && matches!(paint, Some(Paint::Solid { .. }) | None) { picked_mesh_points(s, &ids) } else { vec![] };
|
||||
// Without `item`, unless the Appearance panel's active fill item takes the paint.
|
||||
let colorized = if fill && p.get("item").is_none() && item == ItemTarget::Top {
|
||||
colorized_images(&s.doc()?.doc, &ids, &paint).map_err(|e| bad(cmd, e))?
|
||||
} else {
|
||||
vec![]
|
||||
let colorized = match &paint {
|
||||
Some(paint) if fill && p.get("item").is_none() && item == ItemTarget::Top => {
|
||||
colorized_images(&s.doc()?.doc, &ids, paint).map_err(|e| bad(cmd, e))?
|
||||
}
|
||||
_ => vec![],
|
||||
};
|
||||
let label = match paint {
|
||||
None => "Opacity",
|
||||
Some(_) if fill => "Fill Color",
|
||||
Some(_) => "Stroke Color",
|
||||
};
|
||||
let label = if fill { "Fill Color" } else { "Stroke Color" };
|
||||
// Each object whose appearance took the paint, with the row it went to, for the paint a graph stores for its series
|
||||
// (a series mark is a path, so it always has a row here).
|
||||
let written = std::cell::RefCell::new(Vec::new());
|
||||
// The type objects whose characters took the paint (no row targeted): only those change what a graph's labels keep
|
||||
// for their characters; a row edit is kept with the label's rows.
|
||||
let characters = std::cell::RefCell::new(Vec::new());
|
||||
// The targets that took the opacity, and whether one would have given it to its characters.
|
||||
let (took_opacity, characters_skipped) = (std::cell::RefCell::new(std::collections::BTreeSet::new()), std::cell::Cell::new(false));
|
||||
// The row each target took the opacity on, for what a graph keeps.
|
||||
let opacity_written = std::cell::RefCell::new(Vec::new());
|
||||
let paint_one = |n: &mut Node, index: Option<usize>, paint: &Paint| -> Result<()> {
|
||||
if index.is_none() && matches!(n.kind, NodeKind::Text(_)) {
|
||||
characters.borrow_mut().push(n.id);
|
||||
}
|
||||
if index.is_none() && colorized.contains(&n.id) {
|
||||
let colorize = paint.color().map(|_| Box::new(paint.clone()));
|
||||
// Without a color the image has nothing to overprint, and a later color starts
|
||||
// knocking out.
|
||||
if colorize.is_none() {
|
||||
n.extras_mut().colorize_overprint = false;
|
||||
}
|
||||
n.extras_mut().colorize = colorize;
|
||||
return Ok(());
|
||||
}
|
||||
if index.is_none()
|
||||
&& let Paint::Solid { color, .. } = paint
|
||||
&& let Some((_, points)) = mesh_points.iter().find(|(id, _)| *id == n.id)
|
||||
&& let NodeKind::Mesh(m) = &mut n.kind
|
||||
{
|
||||
for i in points {
|
||||
if let Some(q) = m.points.get_mut(*i) {
|
||||
q.color = *color;
|
||||
}
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
if index.is_none()
|
||||
&& let NodeKind::Text(t) = &mut n.kind
|
||||
{
|
||||
let (xf, lb) = (t.xf, t.local_bounds());
|
||||
for r in &mut t.runs {
|
||||
if !fill && !paint.is_none() {
|
||||
run_stroke_weight(&mut r.style);
|
||||
}
|
||||
let (cur, b) = run_paint_mut(r, !fill, lb);
|
||||
*cur = place_run_paint(paint, p, xf, b);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
// A missing top fill or stroke is created first: a new stroke's weight sizes the box its
|
||||
// gradient fits.
|
||||
if n.appearance.paint_at(index, fill).is_none() {
|
||||
n.appearance.set_paint_at(index, fill, Paint::None);
|
||||
}
|
||||
if !fill {
|
||||
restore_unpainted_stroke(&mut n.appearance, index, paint);
|
||||
}
|
||||
let new_paint = keep_pattern_xf(paint, p, n.appearance.paint_at(index, fill));
|
||||
let placed = place_paint(&new_paint, p, item_paint_bounds(n, index, fill));
|
||||
n.appearance.set_paint_at(index, fill, placed);
|
||||
if !fill
|
||||
&& paint.is_none()
|
||||
&& let Some(stroke) = n.appearance.stroke_at_mut(index)
|
||||
{
|
||||
// A stroke without paint has no weight; painting it again restores the 1 pt default.
|
||||
stroke.width = 0.0;
|
||||
}
|
||||
if !fill {
|
||||
super::object::snap_if_aligned(n);
|
||||
}
|
||||
let at = match index {
|
||||
Some(_) => n.appearance.item_of_kind(index, fill),
|
||||
None => n.appearance.items.iter().rposition(|it| it.is_fill() == fill),
|
||||
};
|
||||
written.borrow_mut().extend(at.map(|at| (n.id, at)));
|
||||
Ok(())
|
||||
};
|
||||
// The opacity goes to what the paint went to: the picked mesh points, else the fill or stroke
|
||||
// item. Characters, and targets without that item, are left as they are.
|
||||
let opacity_one = |n: &mut Node, index: Option<usize>, o: f32| {
|
||||
if index.is_none() && matches!(n.kind, NodeKind::Text(_)) {
|
||||
characters_skipped.set(true);
|
||||
return;
|
||||
}
|
||||
if index.is_none()
|
||||
&& let Some((_, points)) = mesh_points.iter().find(|(id, _)| *id == n.id)
|
||||
&& let NodeKind::Mesh(m) = &mut n.kind
|
||||
{
|
||||
for i in points {
|
||||
if let Some(q) = m.points.get_mut(*i) {
|
||||
q.opacity = o;
|
||||
took_opacity.borrow_mut().insert(n.id);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
let item =
|
||||
if fill { n.appearance.fill_at_mut(index).map(|f| &mut f.opacity) } else { n.appearance.stroke_at_mut(index).map(|s| &mut s.opacity) };
|
||||
if let Some(item) = item {
|
||||
*item = o;
|
||||
took_opacity.borrow_mut().insert(n.id);
|
||||
let at = index.or_else(|| n.appearance.items.iter().rposition(|it| it.is_fill() == fill));
|
||||
opacity_written.borrow_mut().extend(at.map(|at| (n.id, at)));
|
||||
}
|
||||
};
|
||||
// The objects counted: with a design's art, those with a row equal to the art's.
|
||||
let ids = edit_items_then(
|
||||
s,
|
||||
@@ -742,96 +971,60 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool)
|
||||
label,
|
||||
fill,
|
||||
|n, index| {
|
||||
if index.is_none() && matches!(n.kind, NodeKind::Text(_)) {
|
||||
characters.borrow_mut().push(n.id);
|
||||
if let Some(paint) = &paint {
|
||||
paint_one(n, index, paint)?;
|
||||
}
|
||||
if index.is_none() && colorized.contains(&n.id) {
|
||||
let colorize = paint.color().map(|_| Box::new(paint.clone()));
|
||||
// Without a color the image has nothing to overprint, and a later color starts
|
||||
// knocking out.
|
||||
if colorize.is_none() {
|
||||
n.extras_mut().colorize_overprint = false;
|
||||
}
|
||||
n.extras_mut().colorize = colorize;
|
||||
return Ok(());
|
||||
if let Some(o) = opacity {
|
||||
opacity_one(n, index, o);
|
||||
}
|
||||
if index.is_none()
|
||||
&& let Paint::Solid { color, .. } = &paint
|
||||
&& let Some((_, points)) = mesh_points.iter().find(|(id, _)| *id == n.id)
|
||||
&& let NodeKind::Mesh(m) = &mut n.kind
|
||||
{
|
||||
for i in points {
|
||||
if let Some(q) = m.points.get_mut(*i) {
|
||||
q.color = *color;
|
||||
}
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
if index.is_none()
|
||||
&& let NodeKind::Text(t) = &mut n.kind
|
||||
{
|
||||
let (xf, lb) = (t.xf, t.local_bounds());
|
||||
for r in &mut t.runs {
|
||||
if !fill && !paint.is_none() {
|
||||
run_stroke_weight(&mut r.style);
|
||||
}
|
||||
let (cur, b) = run_paint_mut(r, !fill, lb);
|
||||
*cur = place_run_paint(&paint, p, xf, b);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
// A missing top fill or stroke is created first: a new stroke's weight sizes the box its
|
||||
// gradient fits.
|
||||
if n.appearance.paint_at(index, fill).is_none() {
|
||||
n.appearance.set_paint_at(index, fill, Paint::None);
|
||||
}
|
||||
if !fill {
|
||||
restore_unpainted_stroke(&mut n.appearance, index, &paint);
|
||||
}
|
||||
let new_paint = keep_pattern_xf(&paint, p, n.appearance.paint_at(index, fill));
|
||||
let placed = place_paint(&new_paint, p, item_paint_bounds(n, index, fill));
|
||||
n.appearance.set_paint_at(index, fill, placed);
|
||||
if !fill
|
||||
&& paint.is_none()
|
||||
&& let Some(stroke) = n.appearance.stroke_at_mut(index)
|
||||
{
|
||||
// A stroke without paint has no weight; painting it again restores the 1 pt default.
|
||||
stroke.width = 0.0;
|
||||
}
|
||||
if !fill {
|
||||
super::object::snap_if_aligned(n);
|
||||
}
|
||||
let at = match index {
|
||||
Some(_) => n.appearance.item_of_kind(index, fill),
|
||||
None => n.appearance.items.iter().rposition(|it| it.is_fill() == fill),
|
||||
};
|
||||
written.borrow_mut().extend(at.map(|at| (n.id, at)));
|
||||
Ok(())
|
||||
},
|
||||
|before, d, changed| {
|
||||
// An opacity that no target took is an error, which also takes back the paint given with it.
|
||||
if opacity.is_some() && took_opacity.borrow().is_empty() {
|
||||
if characters_skipped.get() {
|
||||
return Err(characters_have_no_opacity(cmd));
|
||||
}
|
||||
return Err(bad(cmd, "no target has that fill or stroke to take the opacity"));
|
||||
}
|
||||
// A graph keeps the opacity of a series mark's topmost visible fill and stroke for the whole series, and of a
|
||||
// graph line's, also when the object already showed it.
|
||||
let kept = opacity.is_some() && {
|
||||
let rows = opacity_written.borrow();
|
||||
let on = super::graph::RowWrites { opacity: true, ..super::graph::RowWrites::NONE };
|
||||
let (on_fill, on_stroke) = if fill { (on, super::graph::RowWrites::NONE) } else { (super::graph::RowWrites::NONE, on) };
|
||||
let marks = super::appearance::capture_series_changes(before, d, changed);
|
||||
let written = super::appearance::capture_series_opacity_writes(d, &rows);
|
||||
marks | written | super::graph::capture_line_row_writes(d, &rows, on_fill, on_stroke)
|
||||
};
|
||||
let Some(paint) = &paint else { return Ok(kept) };
|
||||
let series = super::appearance::capture_series_paint_writes(before, d, changed, &written.borrow());
|
||||
// A graph line keeps the paint written to it, also when it already showed it.
|
||||
let lines = super::graph::capture_line_paint_writes(d, &written.borrow());
|
||||
let labels = super::graph::capture_label_styles(d, &characters.borrow(), &|st| {
|
||||
if fill {
|
||||
st.fill = unplaced(&paint);
|
||||
st.fill = unplaced(paint);
|
||||
} else {
|
||||
if !paint.is_none() {
|
||||
run_stroke_weight(st);
|
||||
}
|
||||
st.stroke = unplaced(&paint);
|
||||
st.stroke = unplaced(paint);
|
||||
}
|
||||
});
|
||||
Ok(series || lines || labels)
|
||||
Ok(series || lines || labels || kept)
|
||||
},
|
||||
)?;
|
||||
// Rejected edits leave the next shape's appearance and active proxy untouched.
|
||||
paint_new_art(s, &paint, fill);
|
||||
if focus {
|
||||
s.fill_active = fill;
|
||||
}
|
||||
s.remember_paint(&paint);
|
||||
Ok(json!({"objects": ids.iter().collect::<std::collections::BTreeSet<_>>().len()}))
|
||||
// Rejected edits leave the next shape's appearance and active proxy untouched.
|
||||
if let Some(paint) = &paint {
|
||||
paint_new_art(s, paint, fill);
|
||||
s.remember_paint(paint);
|
||||
}
|
||||
// An opacity alone counts only the targets that took it.
|
||||
let objects = if paint.is_none() { took_opacity.borrow().len() } else { ids.iter().collect::<std::collections::BTreeSet<_>>().len() };
|
||||
Ok(json!({"objects": objects}))
|
||||
}
|
||||
|
||||
/// Does `p` name no `ids`, `id` or `item`?
|
||||
|
||||
+140
-49
@@ -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;
|
||||
@@ -122,7 +122,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Delete Anchor Points",
|
||||
[],
|
||||
None,
|
||||
"{} delete the direct-selected anchors and their segments, opening closed paths there, and delete objects selected whole alongside them; what remains of a path stays selected, so a second Delete removes it (the Delete key)",
|
||||
"{} delete the direct-selected anchors and their segments, opening closed paths there, and delete objects selected whole alongside them; what remains of a path stays selected, so a second Delete removes it (the Delete key, unless the deleteKeepsPathsJoined preference is on)",
|
||||
has_anchors,
|
||||
delete_anchors
|
||||
),
|
||||
@@ -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
|
||||
@@ -1652,6 +1707,17 @@ fn convert_anchors(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// Layers are retained, and an object removed with a selected ancestor is not removed twice.
|
||||
/// Returns JSON `null` on success; selection is replaced by the surviving object IDs.
|
||||
pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
delete_anchors_joined(s, p, false)
|
||||
}
|
||||
|
||||
/// [`delete_anchors`], and with `keep_joined` (General › Delete Removes Anchor Points and Keeps
|
||||
/// Paths Joined) a path with direct-selected anchors and no selected segment loses those anchors
|
||||
/// as Remove Anchor Points takes them, without opening it, and stays selected with the next
|
||||
/// anchor along (the one before at an open subpath's end), so the next Delete goes on along the
|
||||
/// path. When no subpath it changed keeps two anchors, the path stays selected whole, as Remove
|
||||
/// Anchor Points leaves it. Paths with a selected segment are cut there, as without `keep_joined`
|
||||
/// (their selected anchors stay in the path), and objects selected whole are deleted, in the same undo step.
|
||||
pub(crate) fn delete_anchors_joined(s: &mut Session, p: &Value, keep_joined: bool) -> Result<Value> {
|
||||
// `guides: true` (Cut, #3226): the selected ruler guides go in the same undo step.
|
||||
let with_guides = switch_or(p, "guides", false, "path.deleteAnchors")?;
|
||||
let st = s.doc()?;
|
||||
@@ -1681,6 +1747,7 @@ pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
d.remove_many(&whole_ids)?;
|
||||
}
|
||||
let mut survivors = vec![];
|
||||
let mut following = vec![];
|
||||
let remaining: Vec<NodeId> = sel.keys().copied().filter(|id| d.node(*id).is_some()).collect();
|
||||
let mut emptied = Beside::replacing(d, &remaining);
|
||||
for (id, set) in &sel {
|
||||
@@ -1688,6 +1755,23 @@ pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if d.node(*id).is_none() {
|
||||
continue;
|
||||
}
|
||||
if keep_joined
|
||||
&& !set.is_empty()
|
||||
&& !segments.contains_key(id)
|
||||
&& let Some(path) = d.node(*id).and_then(|n| match &n.kind {
|
||||
NodeKind::Path { path, .. } => Some(path),
|
||||
_ => None,
|
||||
})
|
||||
{
|
||||
let shape: Vec<(usize, bool)> = path.subpaths.iter().map(|sp| (sp.anchors.len(), sp.closed)).collect();
|
||||
let anchors: Vec<(usize, usize)> = set.iter().copied().collect();
|
||||
let next = super::draw2::following_anchors(&shape, &anchors);
|
||||
if !super::draw2::remove_anchors_of(d, selection, &mut emptied, *id, anchors, false)? {
|
||||
survivors.push(*id);
|
||||
following.push((*id, next));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let original = deletion_source(d, *id)?;
|
||||
let subpaths: Vec<SubPath> = {
|
||||
let path = path_mut(d, *id)?;
|
||||
@@ -1731,6 +1815,11 @@ pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
selection.set(survivors);
|
||||
for (id, next) in following {
|
||||
if !next.is_empty() {
|
||||
selection.anchors.insert(id, next);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
ok()
|
||||
@@ -2121,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()))?;
|
||||
@@ -2130,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));
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
//! document holding its patterns, drawn here from plain shapes ([`PATTERN_LIBRARIES`]).
|
||||
//! `swatch.library.add` copies a pattern into the document with its swatch.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::{Arc, LazyLock};
|
||||
|
||||
use vectorcraft_color::{Color, Paint, Swatch, SwatchLibrary};
|
||||
@@ -15,6 +16,10 @@ use super::clipboard::Clipboard;
|
||||
use super::clipboard::resources::{Imported, SwatchChoices};
|
||||
use super::swatchlib::LibraryInfo;
|
||||
|
||||
/// Names that swatches and patterns coming in under a numbered name skip, each with the library
|
||||
/// swatch it is reserved for ([`SwatchChoices::reserving`]).
|
||||
pub(crate) type Reserved = Arc<BTreeMap<String, Swatch>>;
|
||||
|
||||
/// A built-in pattern library: a stable id, its menu name and the function that adds its patterns.
|
||||
pub struct BuiltinPatternLibrary {
|
||||
pub id: &'static str,
|
||||
@@ -96,17 +101,18 @@ pub(crate) type SwatchNames = Vec<(String, String)>;
|
||||
/// A global or spot color whose name `d` gives another color comes in under a free name, as Add
|
||||
/// to Swatches adds such a color, so that the pattern keeps the library's colors. Those colors
|
||||
/// merge instead when that reuses a pattern of `d` that keeping them would add again
|
||||
/// ([`probe_import`]).
|
||||
pub(crate) fn import(d: &mut Document, lib: &Document, name: &str) -> Result<(String, SwatchNames, SwatchNames)> {
|
||||
/// ([`probe_import`]). A swatch that comes in under a numbered name skips the names in
|
||||
/// `reserved`.
|
||||
pub(crate) fn import(d: &mut Document, lib: &Document, name: &str, reserved: &Reserved) -> Result<(String, SwatchNames, SwatchNames)> {
|
||||
let gathered = gather(lib, name);
|
||||
let had: std::collections::HashSet<String> = d.swatches_iter().map(|w| w.name.clone()).collect();
|
||||
// Without a color to merge or a pattern to reuse, the document is not copied.
|
||||
let imported = if !gathered.swatches.is_empty() && has_candidate(d, lib, name) {
|
||||
let (_, probed, imported) = probe_import(d, lib, name, &gathered)?;
|
||||
let (_, probed, imported) = probe_import(d, lib, name, &gathered, reserved)?;
|
||||
*d = probed;
|
||||
imported
|
||||
} else {
|
||||
gathered.import_into(d, &SwatchChoices::add_all(), false)?
|
||||
gathered.import_into(d, &SwatchChoices::add_all().reserving(reserved), false)?
|
||||
};
|
||||
let from = |to: &str| {
|
||||
let renamed = imported.renamed.iter().find(|r| r["kind"] == "swatch" && r["to"] == to).and_then(|r| r["from"].as_str());
|
||||
@@ -138,9 +144,11 @@ pub(crate) fn brought_names(lib: &Document, name: &str) -> std::collections::Has
|
||||
gather(lib, name).swatches.into_iter().map(|w| w.name).collect()
|
||||
}
|
||||
|
||||
/// The names in `lib` of pattern `name` and of the patterns its art brings.
|
||||
pub(crate) fn brought_patterns(lib: &Document, name: &str) -> std::collections::HashSet<String> {
|
||||
gather(lib, name).patterns.into_iter().map(|p| p.name).collect()
|
||||
/// The names in `lib` of the swatches and patterns that pattern `name` of `lib` brings, itself
|
||||
/// included.
|
||||
pub(crate) fn brought_resource_names(lib: &Document, name: &str) -> std::collections::HashSet<String> {
|
||||
let gathered = gather(lib, name);
|
||||
gathered.swatches.into_iter().map(|w| w.name).chain(gathered.patterns.into_iter().map(|p| p.name)).collect()
|
||||
}
|
||||
|
||||
/// The name pattern `name` has in the document `imported` went into.
|
||||
@@ -154,8 +162,8 @@ pub(crate) fn imported_name(imported: &Imported, name: &str) -> String {
|
||||
/// name than its own, as [`import`] lists them. A pattern whose art uses no other resource is
|
||||
/// compared as [`existing_pattern`] does. One whose art uses other resources, such as a pattern it
|
||||
/// is painted with, is imported into a copy of `d` as [`probe_import`] does, so that those
|
||||
/// resources are compared too.
|
||||
pub(crate) fn present_pattern(d: &Document, lib: &Document, name: &str) -> Option<(String, SwatchNames)> {
|
||||
/// resources are compared too, with numbered names skipping `reserved`.
|
||||
pub(crate) fn present_pattern(d: &Document, lib: &Document, name: &str, reserved: &Reserved) -> Option<(String, SwatchNames)> {
|
||||
let gathered = gather(lib, name);
|
||||
let only_pattern = gathered.patterns.len() == 1
|
||||
&& gathered.symbols.is_empty()
|
||||
@@ -173,7 +181,7 @@ pub(crate) fn present_pattern(d: &Document, lib: &Document, name: &str) -> Optio
|
||||
if !has_candidate(d, lib, name) {
|
||||
return None;
|
||||
}
|
||||
let (_, _, imported) = probe_import(d, lib, name, &gathered).ok()?;
|
||||
let (_, _, imported) = probe_import(d, lib, name, &gathered, reserved).ok()?;
|
||||
if imported.added != 0 {
|
||||
return None;
|
||||
}
|
||||
@@ -203,19 +211,73 @@ pub(crate) fn has_candidate(d: &Document, lib: &Document, name: &str) -> bool {
|
||||
/// another color comes in under a free name (Add). Those colors merge instead when Add would add
|
||||
/// the pattern again while merging reuses a pattern of `d`: such a pattern has its art linked to
|
||||
/// the document's own colors of those names, as pasting with Merge, or adding it from a library
|
||||
/// before, leaves it.
|
||||
pub(crate) fn probe_import(d: &Document, lib: &Document, name: &str, gathered: &Clipboard) -> Result<(SwatchChoices, Document, Imported)> {
|
||||
/// before, leaves it. A swatch or pattern that comes in under a numbered name skips the names in
|
||||
/// `reserved` ([`SwatchChoices::reserving`]). When that changed a name and the pattern would come
|
||||
/// in again, or would be reused only by merging colors, an import that does not skip them is used
|
||||
/// if it reuses a pattern of `d` (one pasted there), without merging in the second case, and uses
|
||||
/// none of those names that `d` does not use, other than for the swatch a name is reserved for.
|
||||
pub(crate) fn probe_import(
|
||||
d: &Document,
|
||||
lib: &Document,
|
||||
name: &str,
|
||||
gathered: &Clipboard,
|
||||
reserved: &Reserved,
|
||||
) -> Result<(SwatchChoices, Document, Imported)> {
|
||||
let reused = |i: &Imported| d.pattern(&imported_name(i, name)).is_some();
|
||||
let mut with_add = d.clone();
|
||||
let added = gathered.import_into(&mut with_add, &SwatchChoices::add_all(), false)?;
|
||||
if !reused(&added) && added.renamed.iter().any(|r| r["kind"] == "swatch") && has_candidate(d, lib, name) {
|
||||
let mut merged = d.clone();
|
||||
let found = gathered.import_into(&mut merged, &SwatchChoices::default(), false)?;
|
||||
if reused(&found) {
|
||||
return Ok((SwatchChoices::default(), merged, found));
|
||||
let found = probe_skipping(d, lib, name, gathered, reserved)?;
|
||||
// A reuse that merges colors gives the pattern the document's colors, so one that keeps the
|
||||
// library's is tried too.
|
||||
let merged = |i: &Imported| reused(i) && i.merged != 0;
|
||||
if found.2.reserved_named && (!reused(&found.2) || merged(&found.2)) && has_candidate(d, lib, name) {
|
||||
let pasted = probe_skipping(d, lib, name, gathered, &Reserved::default())?;
|
||||
let better = !reused(&found.2) || !merged(&pasted.2);
|
||||
if reused(&pasted.2) && better && !takes_reserved(d, &pasted.1, &pasted.2, gathered, reserved) {
|
||||
return Ok(pasted);
|
||||
}
|
||||
}
|
||||
Ok((SwatchChoices::add_all(), with_add, added))
|
||||
Ok(found)
|
||||
}
|
||||
|
||||
/// Whether `probed`, the import of `gathered` into a copy of `d` that `imported` describes, gives a
|
||||
/// name in `reserved` that `d` does not use to a pattern, or to a swatch other than the one the name
|
||||
/// is reserved for coming in under its own name.
|
||||
fn takes_reserved(d: &Document, probed: &Document, imported: &Imported, gathered: &Clipboard, reserved: &Reserved) -> bool {
|
||||
let had: std::collections::HashSet<&str> =
|
||||
d.swatches_iter().map(|w| w.name.as_str()).chain(d.swatch_groups.iter().map(|g| g.name.as_str())).collect();
|
||||
let renamed_to = |n: &str| imported.renamed.iter().any(|r| r["kind"] == "swatch" && r["to"] == n && r["from"] != n);
|
||||
let owner_only = |n: &str, owner: &Swatch| gathered.swatches.iter().filter(|w| w.name == n).all(|w| w == owner);
|
||||
let swatch = probed
|
||||
.swatches_iter()
|
||||
.map(|w| w.name.as_str())
|
||||
.filter(|n| !had.contains(n))
|
||||
.any(|n| reserved.get(n).is_some_and(|owner| !owner_only(n, owner) || renamed_to(n)));
|
||||
let patterns: std::collections::HashSet<&str> = d.patterns.iter().map(|p| p.name.as_str()).collect();
|
||||
swatch || probed.patterns.iter().any(|p| !patterns.contains(p.name.as_str()) && reserved.contains_key(&p.name))
|
||||
}
|
||||
|
||||
/// [`probe_import`] with numbered names skipping `reserved`.
|
||||
fn probe_skipping(
|
||||
d: &Document,
|
||||
lib: &Document,
|
||||
name: &str,
|
||||
gathered: &Clipboard,
|
||||
reserved: &Reserved,
|
||||
) -> Result<(SwatchChoices, Document, Imported)> {
|
||||
let reused = |i: &Imported| d.pattern(&imported_name(i, name)).is_some();
|
||||
let (add, merge) = (SwatchChoices::add_all().reserving(reserved), SwatchChoices::default().reserving(reserved));
|
||||
let mut with_add = d.clone();
|
||||
let mut added = gathered.import_into(&mut with_add, &add, false)?;
|
||||
if !reused(&added) && added.renamed.iter().any(|r| r["kind"] == "swatch") && has_candidate(d, lib, name) {
|
||||
let mut merged = d.clone();
|
||||
let mut found = gathered.import_into(&mut merged, &merge, false)?;
|
||||
// Whether a reservation changed a name counts for either import.
|
||||
found.reserved_named |= added.reserved_named;
|
||||
if reused(&found) {
|
||||
return Ok((merge, merged, found));
|
||||
}
|
||||
added.reserved_named |= found.reserved_named;
|
||||
}
|
||||
Ok((add, with_add, added))
|
||||
}
|
||||
|
||||
/// The pattern of `d` that is pattern `name` of library `lib`: the same tile options and art under
|
||||
|
||||
+607
-60
@@ -43,7 +43,13 @@
|
||||
//! 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};
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
@@ -51,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 {
|
||||
@@ -101,6 +110,9 @@ pub fn describe(p: &Plugin) -> Value {
|
||||
if !m.inputs.is_empty() {
|
||||
v["inputs"] = json!(m.inputs);
|
||||
}
|
||||
if !m.context.is_empty() {
|
||||
v["context"] = json!(m.context);
|
||||
}
|
||||
if m.paint_output {
|
||||
v["paintOutput"] = json!(true);
|
||||
}
|
||||
@@ -113,8 +125,19 @@ pub fn describe(p: &Plugin) -> Value {
|
||||
.iter()
|
||||
.map(|c| {
|
||||
let run = m.for_command(c);
|
||||
json!({"id": c.id, "command": command_id(&m.id, &c.id), "label": c.shown_label(), "params": run.params_doc(),
|
||||
"paramsSchema": serde_json::to_value(&run).ok().and_then(|v| v.get("params").cloned())})
|
||||
let mut entry = json!({"id": c.id, "command": command_id(&m.id, &c.id), "label": c.shown_label(), "params": run.params_doc(),
|
||||
"paramsSchema": serde_json::to_value(&run).ok().and_then(|v| v.get("params").cloned())});
|
||||
if let Some(place) = &c.place {
|
||||
let mut menu = json!({"path": place.path});
|
||||
if let Some(after) = &place.after {
|
||||
menu["after"] = json!(permissions::display_text(after, permissions::MAX_SHOWN_NAME));
|
||||
}
|
||||
if placed_menu(p, c).is_none() {
|
||||
menu["placed"] = json!(false);
|
||||
}
|
||||
entry["menu"] = menu;
|
||||
}
|
||||
entry
|
||||
})
|
||||
.collect();
|
||||
v["commands"] = json!(commands);
|
||||
@@ -242,15 +265,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, §ions, c)?;
|
||||
params["_context"]["document"] = given.value;
|
||||
charged = (given.items as u64).saturating_mul(context::CONTEXT_FUEL_PER_ITEM);
|
||||
}
|
||||
let params = serde_json::to_vec(¶ms).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 })
|
||||
}
|
||||
|
||||
@@ -284,11 +317,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 {
|
||||
@@ -497,15 +536,278 @@ pub fn find_spec(id: &str) -> Option<&'static CommandSpec> {
|
||||
command_specs().into_iter().find(|c| c.id == id)
|
||||
}
|
||||
|
||||
/// The letters and digits of `label`, lowercased. Two labels with the same key read alike in a menu
|
||||
/// (`Paste (in Place)` and `Paste in Place`).
|
||||
fn label_key(label: &str) -> String {
|
||||
label.chars().filter(|ch| ch.is_alphanumeric()).flat_map(char::to_lowercase).collect()
|
||||
}
|
||||
|
||||
/// The labels of engine commands whose menu item switches to the label of [`other_state`] (the
|
||||
/// desktop app's dynamic labels).
|
||||
pub const SWITCHING_LABELS: &[&str] = &[
|
||||
"Preview",
|
||||
"Outline",
|
||||
"Show Rulers",
|
||||
"Change to Global Rulers",
|
||||
"Show Transparency Grid",
|
||||
"Lock Guides",
|
||||
"Hide Slices",
|
||||
"Show Print Tiling",
|
||||
"Lock Grid",
|
||||
"Edit Envelope",
|
||||
"Edit Contents",
|
||||
"Start Global Edit",
|
||||
];
|
||||
|
||||
/// The label of `label`'s other state, for a menu item that switches between two labels: `Show
|
||||
/// Edges` for `Hide Edges`, `Unlock Guides` for `Lock Guides`, `Stop Global Edit` for `Start Global
|
||||
/// Edit`, and the reverse.
|
||||
pub fn other_state(label: &str) -> Option<String> {
|
||||
const PAIRS: &[(&str, &str)] = &[
|
||||
("Preview", "Outline"),
|
||||
("Change to Global Rulers", "Change to Artboard Rulers"),
|
||||
("Edit Envelope", "Edit Contents"),
|
||||
("Start Global Edit", "Stop Global Edit"),
|
||||
];
|
||||
let paired = |&(a, b): &(&'static str, &'static str)| {
|
||||
if label == a {
|
||||
Some(b)
|
||||
} else if label == b {
|
||||
Some(a)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
};
|
||||
if let Some(other) = PAIRS.iter().find_map(paired) {
|
||||
return Some(other.to_string());
|
||||
}
|
||||
[("Hide ", "Show "), ("Show ", "Hide "), ("Lock ", "Unlock "), ("Unlock ", "Lock ")]
|
||||
.iter()
|
||||
.find_map(|(from, to)| label.strip_prefix(from).map(|rest| format!("{to}{rest}")))
|
||||
}
|
||||
|
||||
/// The menu that plug-in `p`'s command `c` is listed in when its manifest's `menu` places it in
|
||||
/// another menu: that menu's path, or `None` when `c` stays in its plug-in's submenu. It stays
|
||||
/// there when its menu label ([`Command::menu_label`]) has the same letters and digits, ignoring
|
||||
/// case, as an engine command listed in that menu (either label of one of [`SWITCHING_LABELS`]),
|
||||
/// an item of [`DESKTOP_MENU_ITEMS`] there, or a command that a plug-in with a lower id, or an
|
||||
/// earlier command of `p`, places in that menu. The result is the same with and without the
|
||||
/// desktop app. Results for installed plug-ins are kept until the registry changes.
|
||||
pub fn placed_menu(p: &Plugin, c: &Command) -> Option<&'static [&'static str]> {
|
||||
type Placed = HashMap<String, Option<&'static [&'static str]>>;
|
||||
static PLACED: Mutex<Option<(u64, Placed)>> = Mutex::new(None);
|
||||
c.place.as_ref()?;
|
||||
let m = p.manifest();
|
||||
// Read before the registry, so a result found while the registry changes is kept under the
|
||||
// revision before the change.
|
||||
let revision = registry::revision();
|
||||
// `plugin.inspect` describes a module that is not installed, or not yet in place of the
|
||||
// installed one: never kept.
|
||||
if !registry::get(&m.id).is_some_and(|q| std::ptr::eq(&*q, p)) {
|
||||
return find_place(p, c);
|
||||
}
|
||||
let id = command_id(&m.id, &c.id);
|
||||
if let Ok(placed) = PLACED.lock()
|
||||
&& let Some((at, known)) = placed.as_ref()
|
||||
&& *at == revision
|
||||
&& let Some(found) = known.get(&id)
|
||||
{
|
||||
return *found;
|
||||
}
|
||||
let found = find_place(p, c);
|
||||
if let Ok(mut placed) = PLACED.lock() {
|
||||
let (at, known) = placed.get_or_insert_with(|| (revision, HashMap::new()));
|
||||
if *at != revision {
|
||||
*at = revision;
|
||||
known.clear();
|
||||
}
|
||||
known.insert(id, found);
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// [`placed_menu`], found again.
|
||||
fn find_place(p: &Plugin, c: &Command) -> Option<&'static [&'static str]> {
|
||||
let place = c.place.as_ref()?;
|
||||
let m = p.manifest();
|
||||
let key = label_key(&c.menu_label(&m.name));
|
||||
let reads_like =
|
||||
|label: &str| label_key(label) == key || SWITCHING_LABELS.contains(&label) && other_state(label).is_some_and(|o| label_key(&o) == key);
|
||||
if super::command_specs().iter().any(|s| s.menu == place.path && reads_like(s.label))
|
||||
|| DESKTOP_MENU_ITEMS.iter().any(|(path, label)| *path == place.path && label_key(label) == key)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let taken = |name: &str, d: &Command| d.place.as_ref().is_some_and(|e| e.path == place.path) && label_key(&d.menu_label(name)) == key;
|
||||
// The registry lists plug-ins in id order. `p` itself may not be installed yet (`plugin.inspect`),
|
||||
// or be replacing the installed module of its id, so its own commands come from `m`.
|
||||
for q in registry::list() {
|
||||
let qm = q.manifest();
|
||||
if qm.id >= m.id {
|
||||
break;
|
||||
}
|
||||
if qm.commands.iter().any(|d| taken(&qm.name, d)) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
for d in &m.commands {
|
||||
if d.id == c.id {
|
||||
return Some(place.path);
|
||||
}
|
||||
if taken(&m.name, d) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
Some(place.path)
|
||||
}
|
||||
|
||||
/// The labels of the desktop app's own items (not engine commands) in the menus of
|
||||
/// [`vectorcraft_plugins::manifest::MENU_PLACES`], with both labels of an item that switches
|
||||
/// between two. [`placed_menu`] reads them, so its result is the same with and without the desktop
|
||||
/// app.
|
||||
pub const DESKTOP_MENU_ITEMS: &[(&[&str], &str)] = &[
|
||||
(&["Edit"], "Spelling"),
|
||||
(&["Edit"], "Edit Custom Dictionary…"),
|
||||
(&["Edit"], "Edit Colors"),
|
||||
(&["Edit"], "Edit Original"),
|
||||
(&["Edit"], "Transparency Flattener Presets…"),
|
||||
(&["Edit"], "Print Presets…"),
|
||||
(&["Edit"], "PDF Presets…"),
|
||||
(&["Edit"], "Tracing Presets…"),
|
||||
(&["Edit"], "Perspective Grid Presets…"),
|
||||
(&["Edit"], "Refresh Monitor Profile"),
|
||||
(&["Edit"], "Keyboard Shortcuts…"),
|
||||
(&["Edit"], "Preferences…"),
|
||||
(&["Edit", "Edit Colors"], "Recolor with Preset"),
|
||||
(&["Object"], "Transform"),
|
||||
(&["Object"], "Arrange"),
|
||||
(&["Object"], "Align"),
|
||||
(&["Object"], "Distribute"),
|
||||
(&["Object"], "Lock"),
|
||||
(&["Object"], "Hide"),
|
||||
(&["Object"], "Slice"),
|
||||
(&["Object"], "Path"),
|
||||
(&["Object"], "Shape"),
|
||||
(&["Object"], "Pattern"),
|
||||
(&["Object"], "Repeat"),
|
||||
(&["Object"], "Intertwine"),
|
||||
(&["Object"], "Objects on Path"),
|
||||
(&["Object"], "Blend"),
|
||||
(&["Object"], "Envelope Distort"),
|
||||
(&["Object"], "Perspective"),
|
||||
(&["Object"], "Live Paint"),
|
||||
(&["Object"], "Image Trace"),
|
||||
(&["Object"], "Text Wrap"),
|
||||
(&["Object"], "Clipping Mask"),
|
||||
(&["Object"], "Compound Path"),
|
||||
(&["Object"], "Artboards"),
|
||||
(&["Object"], "Graph"),
|
||||
(&["Object"], "Collect for Export"),
|
||||
(&["Object"], "Plug-ins"),
|
||||
(&["Type"], "Font"),
|
||||
(&["Type"], "Recent Fonts"),
|
||||
(&["Type"], "Size"),
|
||||
(&["Type"], "Bold"),
|
||||
(&["Type"], "Italic"),
|
||||
(&["Type"], "Glyphs"),
|
||||
(&["Type"], "Insert Special Character"),
|
||||
(&["Type"], "Insert Whitespace Character"),
|
||||
(&["Type"], "Insert Break Character"),
|
||||
(&["Type"], "Type on a Path"),
|
||||
(&["Type"], "Dynamic Text Presets"),
|
||||
(&["Type"], "Threaded Text"),
|
||||
(&["Type"], "Find Font…"),
|
||||
(&["Type"], "Change Case"),
|
||||
(&["Type"], "Bullets and Numbering"),
|
||||
(&["Type"], "Show Hidden Characters"),
|
||||
(&["Type"], "Hide Hidden Characters"),
|
||||
(&["Type"], "Type Orientation"),
|
||||
(&["Select"], "Same"),
|
||||
(&["Select"], "Object"),
|
||||
(&["Select"], "Saved Selection"),
|
||||
(&["Effect"], "Apply Last Effect"),
|
||||
(&["Effect"], "Last Effect…"),
|
||||
(&["Effect"], "3D and Materials"),
|
||||
(&["Effect"], "Color Adjustments"),
|
||||
(&["Effect"], "Color Effects"),
|
||||
(&["Effect"], "Convert to Shape"),
|
||||
(&["Effect"], "Crop Marks"),
|
||||
(&["Effect"], "Distort & Transform"),
|
||||
(&["Effect"], "Path"),
|
||||
(&["Effect"], "Path Effects"),
|
||||
(&["Effect"], "Pathfinder"),
|
||||
(&["Effect"], "Rasterize…"),
|
||||
(&["Effect"], "Stylize"),
|
||||
(&["Effect"], "SVG Filters"),
|
||||
(&["Effect"], "Warp"),
|
||||
(&["Effect"], "Effect Gallery…"),
|
||||
(&["Effect"], "Artistic"),
|
||||
(&["Effect"], "Blur"),
|
||||
(&["Effect"], "Brush Strokes"),
|
||||
(&["Effect"], "Distort"),
|
||||
(&["Effect"], "Pixelate"),
|
||||
(&["Effect"], "Sharpen"),
|
||||
(&["Effect"], "Sketch"),
|
||||
(&["Effect"], "Texture"),
|
||||
(&["Effect"], "Video"),
|
||||
(&["Effect"], "Plug-ins"),
|
||||
(&["View"], "Outline"),
|
||||
(&["View"], "Preview"),
|
||||
(&["View"], "Pixel Preview"),
|
||||
(&["View"], "Trim View"),
|
||||
(&["View"], "Presentation Mode"),
|
||||
(&["View"], "Screen Mode"),
|
||||
(&["View"], "Proof Setup"),
|
||||
(&["View"], "Zoom In"),
|
||||
(&["View"], "Zoom Out"),
|
||||
(&["View"], "Fit Artboard in Window"),
|
||||
(&["View"], "Fit All in Window"),
|
||||
(&["View"], "Actual Size"),
|
||||
(&["View"], "Rotate View"),
|
||||
(&["View"], "Rotate View to Selection"),
|
||||
(&["View"], "Reset Rotate View"),
|
||||
(&["View"], "Hide Edges"),
|
||||
(&["View"], "Show Edges"),
|
||||
(&["View"], "Hide Artboards"),
|
||||
(&["View"], "Show Artboards"),
|
||||
(&["View"], "Hide Template"),
|
||||
(&["View"], "Show Template"),
|
||||
(&["View"], "Rulers"),
|
||||
(&["View"], "Hide Bounding Box"),
|
||||
(&["View"], "Show Bounding Box"),
|
||||
(&["View"], "Hide Text Threads"),
|
||||
(&["View"], "Show Text Threads"),
|
||||
(&["View"], "Hide Gradient Annotator"),
|
||||
(&["View"], "Show Gradient Annotator"),
|
||||
(&["View"], "Hide Corner Widget"),
|
||||
(&["View"], "Show Corner Widget"),
|
||||
(&["View"], "Show Live Paint Gaps"),
|
||||
(&["View"], "Hide Live Paint Gaps"),
|
||||
(&["View"], "Guides"),
|
||||
(&["View"], "Smart Guides"),
|
||||
(&["View"], "Perspective Grid"),
|
||||
(&["View"], "Show Grid"),
|
||||
(&["View"], "Hide Grid"),
|
||||
(&["View"], "Snap to Grid"),
|
||||
(&["View"], "Snap to Pixel"),
|
||||
(&["View"], "Snap to Point"),
|
||||
(&["View"], "Snap to Glyph"),
|
||||
(&["View"], "Saved View"),
|
||||
];
|
||||
|
||||
/// The command spec of plug-in `p`'s command `c`: its id, its label as menus show it (escaped and
|
||||
/// capped), its menu (Object › Plug-ins › the plug-in's name, or Effect › Plug-ins › it for a live
|
||||
/// effect: never a menu the manifest names) and its params description.
|
||||
/// capped, and followed by the plug-in's name when it is listed in another menu), its menu
|
||||
/// ([`placed_menu`], else Object › Plug-ins › the plug-in's name, or Effect › Plug-ins › it for a
|
||||
/// live effect) and its params description.
|
||||
fn spec_of(p: &Plugin, c: &Command) -> &'static CommandSpec {
|
||||
let m = p.manifest();
|
||||
let id = command_id(&m.id, &c.id);
|
||||
let label = c.shown_label();
|
||||
let placed = placed_menu(p, c);
|
||||
let label = if placed.is_some() { c.menu_label(&m.name) } else { c.shown_label() };
|
||||
let top = if m.kind == Kind::Effect { "Effect" } else { "Object" };
|
||||
let name = permissions::display_text(m.name.trim(), permissions::MAX_SHOWN_NAME);
|
||||
let submenu = [top, "Plug-ins", name.as_str()];
|
||||
let path: &[&str] = placed.unwrap_or(&submenu);
|
||||
let mut fields =
|
||||
String::from("ids?: [object id] (left out or null: the selection), params?: {…} (its parameters; or give them as top-level keys)");
|
||||
let doc = m.for_command(c).params_doc();
|
||||
@@ -518,11 +820,14 @@ fn spec_of(p: &Plugin, c: &Command) -> &'static CommandSpec {
|
||||
m.id, c.id
|
||||
);
|
||||
let mut made = MADE.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let same = |s: &&&'static CommandSpec| s.id == id && s.label == label && s.menu == [top, "Plug-ins", name.as_str()] && s.params == params;
|
||||
let same = |s: &&&'static CommandSpec| s.id == id && s.label == label && s.menu == path && s.params == params;
|
||||
if let Some(s) = made.iter().find(same) {
|
||||
return s;
|
||||
}
|
||||
let menu: &'static [&'static str] = Box::leak(vec![top, "Plug-ins", registry::intern(&name)].into_boxed_slice());
|
||||
let menu: &'static [&'static str] = match placed {
|
||||
Some(path) => path,
|
||||
None => Box::leak(vec![top, "Plug-ins", registry::intern(&name)].into_boxed_slice()),
|
||||
};
|
||||
let spec: &'static CommandSpec = Box::leak(Box::new(CommandSpec {
|
||||
id: registry::intern(&id),
|
||||
label: registry::intern(&label),
|
||||
@@ -732,12 +1037,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.
|
||||
@@ -755,6 +1064,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
|
||||
@@ -1004,31 +1328,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;
|
||||
}
|
||||
}
|
||||
@@ -1048,42 +1402,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<®istry::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> {
|
||||
@@ -1095,11 +1639,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)
|
||||
}
|
||||
|
||||
@@ -1148,7 +1693,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}),
|
||||
@@ -1156,13 +1701,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,
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -1301,7 +1848,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}] (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
|
||||
),
|
||||
@@ -1373,7 +1920,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
|
||||
),
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
@@ -60,6 +60,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"addon.pathtools.erase",
|
||||
"addon.pathtools.expandDashes",
|
||||
"addon.pathtools.extend",
|
||||
"addon.pathtools.inscribedCircle",
|
||||
"addon.pathtools.inspect",
|
||||
"addon.pathtools.mergeEdge",
|
||||
"addon.pathtools.removeKeepShape",
|
||||
@@ -466,6 +467,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"path.moveAnchor",
|
||||
"path.moveAnchors",
|
||||
"path.quickPen",
|
||||
"path.quickPenLength",
|
||||
"path.rectCut",
|
||||
"path.removeAnchor",
|
||||
"path.removeAnchors",
|
||||
|
||||
@@ -140,6 +140,8 @@ pub const PREF_SPECS: &[PrefSpec] = &[
|
||||
p!("pasteOffset", "General", "", "Paste Offset", len(0.0, 1296.0, General)),
|
||||
p!("disableAutoAddDelete", "General", "Options", "Disable Auto Add/Delete", bool),
|
||||
p!("interpolateControlPoints", "General", "Options", "Interpolate Control Points When Moving Anchors", bool),
|
||||
p!("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),
|
||||
|
||||
@@ -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> {
|
||||
|
||||
@@ -95,7 +95,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"List Script File Permissions",
|
||||
[],
|
||||
None,
|
||||
"{} the file access people allowed scripts with Always in a file dialog, kept in Script Grants.json next to the settings: each for one script file with one text and the files it includes (their SHA-256), so a changed or moved script, or a changed included file, has none, and with the SHA-256 of each source the run that kept it evaluated (files $.evalFile ran, strings given to eval and Function; at most 256), so a run loses it before it evaluates other code, or when its named engine holds code the grant was not kept for; at most 4096 → {grants: [{script: the script file's path, sha256, code: [SHA-256 of each evaluated source, of its UTF-16 code units in little-endian order], path: the file or folder allowed, write: it may be written, folder: the grant is a folder's, with everything in it (a file's grant is its own path only)}], file: the grants file's path | null (a session without a settings folder, and the web)}",
|
||||
"{} the file access people allowed scripts with Always in a file dialog, kept in Script Grants.json next to the settings: each for one script file with one text and the files it includes (their SHA-256), so a changed or moved script, or a changed included file, has none, and with the SHA-256 of each source the run that kept it evaluated (files $.evalFile ran, strings given to eval and Function; at most 256), so a run loses it before it evaluates other code, or when its named engine holds code the grant was not kept for; at most 4096 → {grants: [{script: the script file's path, sha256, code: [SHA-256 of each evaluated source, of its UTF-16 code units in little-endian order], path: the file or folder allowed, write: it may be written, folder: the grant is a folder's, with everything in it (a file's grant is its own path only)}], file: the grants file's path | null (a session without a settings folder, and the web)}; a missing grants file lists none, and one that is there but cannot be read, is too large, is not a grants file of this version or holds no list of grants, or whose lock cannot be taken, is an error (a grant in it that is not well formed is left out)",
|
||||
always,
|
||||
grants
|
||||
),
|
||||
@@ -369,7 +369,8 @@ fn grants(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let Some(dir) = s.script_data_dir() else { return Ok(json!({"grants": [], "file": null})) };
|
||||
let file = dir.with_file_name(script::files::GRANTS_FILE);
|
||||
// A script or a granted path outside the automation read roots is named by its file name alone.
|
||||
let mut grants = script::files::stored_grants(dir);
|
||||
let mut grants =
|
||||
script::files::stored_grants(dir).map_err(|e| EngineError::Other(format!("the script file permissions could not be read: {e}")))?;
|
||||
for g in &mut grants {
|
||||
for key in ["script", "path"] {
|
||||
if let Some(name) = g[key].as_str().and_then(hidden_name) {
|
||||
|
||||
@@ -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, _| {
|
||||
|
||||
@@ -17,6 +17,7 @@ use vectorcraft_color::swatch::REGISTRATION;
|
||||
use vectorcraft_color::{Paint, Swatch, SwatchGroup, SwatchLibrary, default_swatches};
|
||||
use vectorcraft_doc::pattern::pattern_paint;
|
||||
|
||||
use super::clipboard::resources::numbered_name;
|
||||
use super::fileio::{create_dir, extension, read_file, read_file_head, write_file, write_new_file};
|
||||
use super::menucmds::squash;
|
||||
use super::package::free_name;
|
||||
@@ -49,7 +50,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add to Swatches",
|
||||
["Window", "Swatch Libraries"],
|
||||
None,
|
||||
"{library: id or name, names?: [swatch or colour group names in the library] (default: all of it; a group comes as a colour group, a single swatch ungrouped), apply?: \"fill\"|\"stroke\" (also apply the first one to the selection and the defaults, as paint.setFill / paint.setStroke), focus?: true (with apply: false keeps the active proxy), defaultsOnly?: bool (with apply: apply it to the defaults only, as paint.setFill does; the journal records it for swatches applied while the Live Paint Bucket is the active tool)} copy library swatches into the document as one undo step. A swatch the document already has (same name and paint, and for a color the same process, global or spot kind, or a numbered copy of that name with the same color when the name has another color there) isn't added again; a name taken by another swatch gets a number (\"Clay 1 2\"); a tint or gradient whose global or spot color comes in under a numbered name, or is in the document as such a numbered copy, links to that copy; a global or spot color it links to that the document lacks comes in with it. A pattern swatch brings its pattern, as pasting art painted with it does: the same pattern the document has is used, also when its art links to the document's own color of a name, and a name another pattern or swatch has gets a number; a global or spot color its art links to whose name the document gives another color comes in numbered, skipping the names of the library's other swatches, and the pattern links to it → {library, added: [names in the document, the colors patterns, tints and gradients brought included], existing: [names already there], applied?: name}",
|
||||
"{library: id or name, names?: [swatch or colour group names in the library] (default: all of it; a group comes as a colour group, a single swatch ungrouped), apply?: \"fill\"|\"stroke\" (also apply the first one to the selection and the defaults, as paint.setFill / paint.setStroke), focus?: true (with apply: false keeps the active proxy), defaultsOnly?: bool (with apply: apply it to the defaults only, as paint.setFill does; the journal records it for swatches applied while the Live Paint Bucket is the active tool)} copy library swatches into the document as one undo step. A swatch the document already has (same name and paint, and for a color the same process, global or spot kind, or a numbered copy of that name with the same color when the name has another color there) isn't added again; a name taken by another swatch gets a number (\"Clay 1 2\"); a tint or gradient whose global or spot color comes in under a numbered name, or is in the document as such a numbered copy, links to that copy; a global or spot color it links to that the document lacks comes in with it. A pattern swatch brings its pattern, as pasting art painted with it does: the same pattern the document has is used, also when its art links to the document's own color of a name, and a name another pattern or swatch has gets a number; a global or spot color its art links to whose name the document gives another color comes in numbered, skipping the names of the library's other swatches, and the pattern links to it, not to a numbered copy that is the library's other swatch of that name; a swatch of a numbered library name that the art brings, such as a tint \"Ink 2\" or a pattern's swatch when its pattern comes in under another name, keeps that name when the document does not use it, and a pattern swatch or a pattern the art is painted with that comes in numbered skips the library's other names too → {library, added: [names in the document, the colors patterns, tints and gradients brought included], existing: [names already there], applied?: name}",
|
||||
has_doc,
|
||||
add
|
||||
),
|
||||
@@ -1029,55 +1030,27 @@ fn free_copy_in(taken: &mut HashSet<String>, base: &str, reserved: impl Fn(&str)
|
||||
name
|
||||
}
|
||||
|
||||
/// [`patternlib::import`] of pattern `pattern` of `src` into `d`, keeping the library's numbered
|
||||
/// swatch names (the keys of `names`, such as "Ink 2") that `d` does not use for the library's own
|
||||
/// swatches of those names, so that a color the art brings under a numbered name does not take one
|
||||
/// of them. While the import runs, a placeholder swatch holds each such name the art does not
|
||||
/// bring, and a copy of the library's color holds each one the art brings, which the art then
|
||||
/// takes. The placeholders are removed before it returns, and so is a copy the art did not take;
|
||||
/// a copy the art took is listed with the colors the import brought. Names of the patterns the
|
||||
/// import brings are not held.
|
||||
fn import_holding(
|
||||
d: &mut vectorcraft_doc::Document,
|
||||
src: &vectorcraft_doc::Document,
|
||||
pattern: &str,
|
||||
names: &HashMap<&str, &Swatch>,
|
||||
) -> Result<(String, patternlib::SwatchNames, patternlib::SwatchNames)> {
|
||||
let numbered = |n: &str| n.rsplit_once(' ').is_some_and(|(_, k)| !k.is_empty() && k.bytes().all(|b| b.is_ascii_digit()));
|
||||
let taken = taken_names(d);
|
||||
let mut free: Vec<&str> = names.keys().copied().filter(|n| numbered(n) && !taken.contains(*n)).collect();
|
||||
free.sort_unstable();
|
||||
let (mut held, mut copies): (Vec<Swatch>, Vec<Swatch>) = (vec![], vec![]);
|
||||
if !free.is_empty() {
|
||||
let brings = patternlib::brought_names(src, pattern);
|
||||
let patterns = patternlib::brought_patterns(src, pattern);
|
||||
for n in free.into_iter().filter(|n| !patterns.contains(*n)) {
|
||||
if !brings.contains(n) {
|
||||
held.push(Swatch { name: n.to_string(), paint: Paint::None, global: false, spot: false });
|
||||
} else if let Some(w) = names.get(n).filter(|w| w.paint.color().is_some() && linked_names(&w.paint).is_empty()) {
|
||||
copies.push((*w).clone());
|
||||
}
|
||||
/// The name of the document's swatch for library pattern swatch `w`, whose pattern came in as
|
||||
/// `target`, the import having made swatch `made` for it (removed again). A numbered name skips
|
||||
/// the names of the library's other swatches (`lib_by_name`), as for a color; so does a swatch
|
||||
/// named after its pattern when the pattern's name is one of them. The swatch takes the library
|
||||
/// swatch's numbered name when it is free and the library has no other swatch of that name, and leaves a
|
||||
/// numbered name the library gives an earlier swatch to that one.
|
||||
fn pattern_swatch_name(w: &Swatch, target: &str, made: Option<String>, taken: &mut HashSet<String>, lib_by_name: &HashMap<&str, &Swatch>) -> String {
|
||||
let reserved = |n: &str| lib_by_name.contains_key(n);
|
||||
let owns = lib_by_name.get(w.name.as_str()).is_some_and(|o| *o == w);
|
||||
let named_after = matches!(&w.paint, Paint::Pattern { pattern, .. } if *pattern == w.name);
|
||||
match made {
|
||||
_ if named_after && owns && numbered_name(&w.name) && !taken.contains(&w.name) => w.name.clone(),
|
||||
_ if !owns && numbered_name(&w.name) && !taken.contains(&w.name) => {
|
||||
let mut held = taken.clone();
|
||||
held.insert(w.name.clone());
|
||||
free_copy_in(&mut held, &w.name, reserved)
|
||||
}
|
||||
Some(made) if named_after => made,
|
||||
None if named_after && (target == w.name || !reserved(target)) => free_copy_in(taken, target, reserved),
|
||||
_ => free_copy_in(taken, &w.name, reserved),
|
||||
}
|
||||
let start = d.swatches.len();
|
||||
d.swatches.extend(held.iter().chain(&copies).cloned());
|
||||
let imported = patternlib::import(d, src, pattern);
|
||||
let used = |n: &str| {
|
||||
imported
|
||||
.as_ref()
|
||||
.is_ok_and(|(_, colors, took)| !colors.iter().any(|(from, _)| from == n) && !took.iter().any(|(from, to)| from == n && to != n))
|
||||
};
|
||||
let used: HashSet<String> = copies.iter().map(|w| w.name.clone()).filter(|n| used(n)).collect();
|
||||
let mut i = 0;
|
||||
d.swatches.retain(|w| {
|
||||
i += 1;
|
||||
let ours = held.iter().chain(&copies).any(|h| h.name == w.name && h.paint == w.paint);
|
||||
!(i > start && ours && !used.contains(&w.name))
|
||||
});
|
||||
let (target, mut colors, mut took) = imported?;
|
||||
took.retain(|(from, _)| !used.contains(from));
|
||||
colors.extend(copies.into_iter().map(|w| w.name).filter(|n| used.contains(n)).map(|n| (n.clone(), n)));
|
||||
Ok((target, colors, took))
|
||||
}
|
||||
|
||||
/// Link the swatches of `d` that `pending` names (document name, library swatch) to their colors
|
||||
@@ -1202,6 +1175,25 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
for w in lib.swatches.iter().chain(lib.groups.iter().flat_map(|g| &g.swatches)) {
|
||||
lib_by_name.entry(w.name.as_str()).or_insert(w);
|
||||
}
|
||||
// A swatch a pattern's art brings under a numbered name skips the library's numbered names,
|
||||
// which a later add looks up as those swatches'. Only the names a picked pattern's swatches and
|
||||
// patterns can come in under, their own or one numbered after them, are needed.
|
||||
let mut brings_names: HashSet<String> = HashSet::new();
|
||||
if let Some(src) = patterns.as_ref().filter(|_| lib_by_name.keys().any(|n| numbered_name(n))) {
|
||||
let picked_patterns: BTreeSet<&str> = picked
|
||||
.iter()
|
||||
.filter_map(|(_, w)| match &w.paint {
|
||||
Paint::Pattern { pattern, .. } => Some(pattern.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
for pattern in picked_patterns {
|
||||
brings_names.extend(patternlib::brought_resource_names(src, pattern));
|
||||
}
|
||||
}
|
||||
let can_take = |n: &str| brings_names.contains(n) || n.rsplit_once(' ').is_some_and(|(base, _)| brings_names.contains(base));
|
||||
let lib_names: patternlib::Reserved =
|
||||
Arc::new(lib_by_name.iter().filter(|(n, _)| numbered_name(n) && can_take(n)).map(|(n, w)| (n.to_string(), (*w).clone())).collect());
|
||||
let group_names: HashSet<&str> = d.swatch_groups.iter().map(|g| g.name.as_str()).collect();
|
||||
// A color whose name the document gives another color, or a color group, is the numbered copy
|
||||
// of it that an earlier add or a pattern's art brought in, when that copy is the same color. A
|
||||
@@ -1233,7 +1225,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(src) = &patterns {
|
||||
for (_, w) in &picked {
|
||||
let Paint::Pattern { pattern, .. } = &w.paint else { continue };
|
||||
present.entry(pattern.as_str()).or_insert_with(|| patternlib::present_pattern(d, src, pattern));
|
||||
present.entry(pattern.as_str()).or_insert_with(|| patternlib::present_pattern(d, src, pattern, &lib_names));
|
||||
}
|
||||
}
|
||||
// Whether the document's swatch `x` of the name of library swatch `w` is `w` with its colors
|
||||
@@ -1438,7 +1430,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut learned = vec![];
|
||||
if pending.iter().any(|(_, w)| linked_names(&w.paint).iter().any(waited)) {
|
||||
let mut probe = d.clone();
|
||||
let (_, colors, took) = import_holding(&mut probe, src, pattern, &lib_by_name)?;
|
||||
let (_, colors, took) = patternlib::import(&mut probe, src, pattern, &lib_names)?;
|
||||
for (from, to) in colors_of(&probe, &colors, &took) {
|
||||
if let std::collections::hash_map::Entry::Vacant(e) = links.entry(from.clone()) {
|
||||
e.insert(to);
|
||||
@@ -1448,7 +1440,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let settled = settle(d, &mut pending, &links);
|
||||
let had = taken_names(d);
|
||||
let (target, colors, took) = import_holding(d, src, pattern, &lib_by_name)?;
|
||||
let (target, colors, took) = patternlib::import(d, src, pattern, &lib_names)?;
|
||||
// Those colors are the ones the library's tints of them link to, unless the
|
||||
// document already has one for them. A name the copy gave that the import
|
||||
// into the document did not give is replaced, and the tints linked to it are
|
||||
@@ -1483,11 +1475,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
d.swatches.retain(|x| x.name != *made);
|
||||
}
|
||||
taken = taken_names(d);
|
||||
let name = match made {
|
||||
Some(made) if w.name == *pattern => made,
|
||||
None if w.name == *pattern => d.free_swatch_name(&target),
|
||||
_ => free_in(&mut taken, &w.name),
|
||||
};
|
||||
let name = pattern_swatch_name(w, &target, made, &mut taken, &lib_by_name);
|
||||
taken.insert(name.clone());
|
||||
// The library swatch's placement of its pattern is kept.
|
||||
let paint = match &w.paint {
|
||||
|
||||
@@ -1895,14 +1895,21 @@ enum Step {
|
||||
/// The Type tool's selected text while it edits (its typing session ends first: one undo step,
|
||||
/// with typing that Real-time Drawing off left unapplied applied first).
|
||||
pub(crate) fn editing_range(s: &mut Session) -> Result<Option<(NodeId, usize, usize)>> {
|
||||
let o = s.tool_options();
|
||||
let Some(id) = o.get("editing").and_then(Value::as_u64).map(NodeId) else { return Ok(None) };
|
||||
let Some(range) = selected_range(s) else { return Ok(None) };
|
||||
if super::edit::typing_in_progress(s) {
|
||||
s.set_tool_option("commitTyping", &Value::Bool(true));
|
||||
super::edit::settle_interaction(s)?;
|
||||
}
|
||||
Ok(Some(range))
|
||||
}
|
||||
|
||||
/// The Type tool's selected text while it edits, as [`editing_range`] reads it, with its typing
|
||||
/// session left running.
|
||||
pub(crate) fn selected_range(s: &Session) -> Option<(NodeId, usize, usize)> {
|
||||
let o = s.tool_options();
|
||||
let id = o.get("editing").and_then(Value::as_u64).map(NodeId)?;
|
||||
let at = |k: &str| byte_param(&o, k).unwrap_or(0);
|
||||
Ok(Some((id, at("start"), at("end"))))
|
||||
Some((id, at("start"), at("end")))
|
||||
}
|
||||
|
||||
/// The frames of the story whose whole text the Type tool has selected after Select All in a
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
|
||||
@@ -125,6 +125,14 @@ pub fn waits_for_tool_edit(id: &str) -> bool {
|
||||
find_command(id).is_some_and(|spec| spec.journal || WAIT_FOR_TOOL_EDIT.contains(&id))
|
||||
}
|
||||
|
||||
/// Does command `id` first install the plug-ins still loading on other threads
|
||||
/// ([`crate::Session::finish_plugin_loads`])? Plug-in commands do, a plug-in's own commands
|
||||
/// included, and so does every command that waits for a tool edit ([`waits_for_tool_edit`]);
|
||||
/// queries that only read, and view commands, go ahead while the plug-ins load.
|
||||
pub fn waits_for_plugin_loads(id: &str) -> bool {
|
||||
id.starts_with(vectorcraft_plugins::PREFIX) || waits_for_tool_edit(id)
|
||||
}
|
||||
|
||||
/// Journaled commands that write a file and change nothing in the document: with an object of a
|
||||
/// dynamic symbol instance's art selected, they read the instance as queries do
|
||||
/// ([`crate::Session::execute`]).
|
||||
|
||||
@@ -227,6 +227,14 @@ fn with_gate_reads_exempt<T>(exempt: bool, f: impl FnOnce() -> T) -> T {
|
||||
f()
|
||||
}
|
||||
|
||||
/// `scope`, or for a thread without one, the `process` roots in force now (none: unconfined).
|
||||
fn resolved(scope: Option<Scope>, process: Option<&Arc<AutomationRoots>>) -> Scope {
|
||||
scope.unwrap_or_else(|| match process {
|
||||
Some(r) => Scope::Confined(r.clone()),
|
||||
None => Scope::Unconfined,
|
||||
})
|
||||
}
|
||||
|
||||
/// This thread's scope, with the gate of the script command it runs, to carry to work it hands to
|
||||
/// another thread ([`ScopeHandle::run`]).
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -238,6 +246,15 @@ impl ScopeHandle {
|
||||
Self(SCOPE.with(|s| s.borrow().clone()), GATE.with(|g| g.borrow().clone()), GATE_READS_EXEMPT.with(std::cell::Cell::get))
|
||||
}
|
||||
|
||||
/// [`ScopeHandle::capture`], except that a thread with no scope of its own takes the process's
|
||||
/// roots as they are now ([`confine_process`]): work captured before the process is confined
|
||||
/// stays unconfined on the thread that runs it, as it would have been had it run on the calling
|
||||
/// thread at once.
|
||||
pub fn capture_now() -> Self {
|
||||
let scope = resolved(SCOPE.with(|s| s.borrow().clone()), PROCESS.get());
|
||||
Self(Some(scope), GATE.with(|g| g.borrow().clone()), GATE_READS_EXEMPT.with(std::cell::Cell::get))
|
||||
}
|
||||
|
||||
/// Run `f` in the captured scope.
|
||||
pub fn run<T>(self, f: impl FnOnce() -> T) -> T {
|
||||
let Self(scope, gate, exempt) = self;
|
||||
@@ -1327,6 +1344,24 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// Work captured with [`ScopeHandle::capture_now`] before the process is confined stays
|
||||
/// unconfined when it runs after; work captured with [`ScopeHandle::capture`] is confined then.
|
||||
#[test]
|
||||
fn a_scope_captured_now_stays_unconfined_after_the_process_is_confined() {
|
||||
if !crate::tests::in_own_process("file_access::tests::a_scope_captured_now_stays_unconfined_after_the_process_is_confined") {
|
||||
return;
|
||||
}
|
||||
let (base, roots) = folders("captured-process");
|
||||
let outside = s(base.join("outside/secret.svg"));
|
||||
let (now, plain) = std::thread::spawn(|| (ScopeHandle::capture_now(), ScopeHandle::capture())).join().unwrap();
|
||||
assert!(confine_process(roots));
|
||||
assert_eq!(now.run(|| check_read(&outside)), Ok(()), "captured now, before the process was confined");
|
||||
assert!(plain.run(|| check_read(&outside)).is_err(), "captured plainly, run after the process was confined");
|
||||
let later = std::thread::spawn(ScopeHandle::capture_now).join().unwrap();
|
||||
assert!(later.run(|| check_read(&outside)).is_err(), "captured now, after the process was confined");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn device_names() {
|
||||
for d in ["CON", "nul", "Com1", "LPT9.txt", "aux.svg", "NUL ", "COM¹", "Lpt²", "lpt³.txt"] {
|
||||
|
||||
@@ -8,6 +8,10 @@ pub struct Interaction {
|
||||
/// The selection the previews start from (shared, so a preview frame copies nothing).
|
||||
pub selection: Arc<Selection>,
|
||||
pub preview: Option<(String, Value)>,
|
||||
/// The active tool began it (a drag): a command from outside the tool runs as a step of its
|
||||
/// own under it ([`crate::Session::outside_interaction`]). A dialog or a panel that begins an
|
||||
/// interaction runs its commands inside it.
|
||||
pub(crate) tool: bool,
|
||||
/// A replaced or canceled preview restores these new-art paints from before the interaction.
|
||||
pub(crate) paint: vectorcraft_tools::PaintDefaults,
|
||||
/// A preview of the interaction gave `defaultsOnly: true`: every later preview and a cancel put
|
||||
@@ -41,6 +45,61 @@ pub struct Interaction {
|
||||
pub keep_on_switch: bool,
|
||||
}
|
||||
|
||||
/// An interaction that a command from outside the tool set aside while it runs
|
||||
/// ([`crate::Session::outside_interaction`]).
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct HeldInteraction {
|
||||
/// The [`crate::DocState::uid`] of the interaction's document.
|
||||
pub(crate) uid: u64,
|
||||
pub(crate) interaction: Interaction,
|
||||
/// The document and the selection on show when the command began, when a preview had changed
|
||||
/// them from the interaction's snapshot.
|
||||
pub(crate) shown: Option<(Arc<Document>, Selection)>,
|
||||
/// The document's current layer, highlighted Layers panel rows, highlighted variable and
|
||||
/// isolation when the command began; a cancel puts back the ones it changed as it left them.
|
||||
pub(crate) state: ViewState,
|
||||
/// The new-art paints when the command began: a change the command makes to them stays when
|
||||
/// the interaction's next preview or a cancel puts back the paints it began with.
|
||||
pub(crate) paint: vectorcraft_tools::PaintDefaults,
|
||||
}
|
||||
|
||||
/// The per-document state an interaction puts back when it is canceled, besides the document and
|
||||
/// the selection.
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub(crate) struct ViewState {
|
||||
pub(crate) active_layer: Option<NodeId>,
|
||||
pub(crate) layer_rows: Vec<NodeId>,
|
||||
pub(crate) variables_highlight: Option<String>,
|
||||
pub(crate) isolation: Option<NodeId>,
|
||||
}
|
||||
|
||||
impl ViewState {
|
||||
pub(crate) fn of(st: &crate::DocState) -> Self {
|
||||
ViewState {
|
||||
active_layer: st.active_layer,
|
||||
layer_rows: st.layer_rows.clone(),
|
||||
variables_highlight: st.variables_highlight.clone(),
|
||||
isolation: st.isolation,
|
||||
}
|
||||
}
|
||||
|
||||
/// Give `it` the parts of `now` that differ from `self`, the state before a command.
|
||||
pub(crate) fn rebase(&self, now: ViewState, it: &mut Interaction) {
|
||||
if now.active_layer != self.active_layer {
|
||||
it.active_layer = now.active_layer;
|
||||
}
|
||||
if now.layer_rows != self.layer_rows {
|
||||
it.layer_rows = now.layer_rows;
|
||||
}
|
||||
if now.variables_highlight != self.variables_highlight {
|
||||
it.variables_highlight = now.variables_highlight;
|
||||
}
|
||||
if now.isolation != self.isolation {
|
||||
it.isolation = now.isolation;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What Object → Transform → Transform Again (⌘D) repeats ([`SessionState::last_transform`]).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum LastTransform {
|
||||
|
||||
@@ -107,6 +107,19 @@ pub struct Session {
|
||||
/// The selection tool chosen last (Selection, Direct Selection or Group Selection): the one Cmd
|
||||
/// lends the other tools. None until one is chosen.
|
||||
pub(crate) last_selection_tool: Option<&'static str>,
|
||||
/// Direct Selection or Group Selection, whichever was chosen last: the one Cmd lends the
|
||||
/// Selection tool. None until one is chosen.
|
||||
pub(crate) last_part_selection_tool: Option<&'static str>,
|
||||
/// The selection tool Cmd lent the last press, which also takes the double-click or
|
||||
/// triple-click that follows it, with the uid of the document and the id of the tool it was
|
||||
/// lent from: a follow-up in another document, after a tool switch (also one back to the same
|
||||
/// tool) or after the tool starts afresh is not lent. None when the press was not lent.
|
||||
pub(crate) press_lent: Option<(Option<u64>, &'static str, &'static str)>,
|
||||
/// The selection tool a Cmd press would borrow at the pointer, as [`Session::hover_tool_at`]
|
||||
/// or [`Session::cursor`] last found it with Cmd held (None inside when it found none), with
|
||||
/// the document state, active tool and keys it was found for. None when it was last asked
|
||||
/// without Cmd.
|
||||
pub(crate) hover_lent: Option<(tooling::HoverKey, Option<&'static str>)>,
|
||||
pub(crate) last_view: ViewInfo,
|
||||
/// The selection tools' measurements for the active document as it is: a pointer move or a
|
||||
/// cursor asked for again over an unchanged document and selection measures nothing again.
|
||||
@@ -190,6 +203,11 @@ pub struct Session {
|
||||
/// Where the plug-ins `plugin.install` installs are kept; `None`: only for the process
|
||||
/// ([`Session::attach_plugin_store`]).
|
||||
plugin_dir: Option<std::path::PathBuf>,
|
||||
/// Plug-in loads running on worker threads, oldest first ([`Session::poll_plugin_loads`]).
|
||||
plugin_loads: std::collections::VecDeque<store::PluginLoad>,
|
||||
/// Whether the loads of the stored plug-ins and of the plug-ins folder go on after the call
|
||||
/// that starts them ([`Session::load_plugins_in_background`]).
|
||||
plugin_loads_in_background: bool,
|
||||
/// The Scripts folder, whose scripts File › Scripts lists; `None`: no folder
|
||||
/// ([`Session::attach_scripts_dir`]).
|
||||
scripts_dir: Option<std::path::PathBuf>,
|
||||
@@ -328,6 +346,9 @@ pub struct Session {
|
||||
/// The warnings of the previews that settling an interaction applied, while a top-level command
|
||||
/// or the tool's actions collect them ([`Session::collect_settled_warnings`]).
|
||||
settled_warnings: Option<Vec<String>>,
|
||||
/// The interaction a command from outside the tool set aside while it runs
|
||||
/// ([`Session::outside_interaction`]).
|
||||
held_interaction: Option<HeldInteraction>,
|
||||
/// While [`Session::preview`] runs its command: its edits are the interaction's own.
|
||||
previewing: bool,
|
||||
/// The images Remove Background decoded during the interaction's preview steps, emptied when
|
||||
@@ -440,13 +461,13 @@ mod session;
|
||||
pub(crate) use command_sets::SELECTS_GIVEN_IDS;
|
||||
#[cfg(test)]
|
||||
use command_sets::given_ids;
|
||||
pub use command_sets::{DRAWS_SHAPE, FIT_ACTIVE_ARTBOARD, ON_ACTIVE_ARTBOARD, waits_for_tool_edit};
|
||||
pub use command_sets::{DRAWS_SHAPE, FIT_ACTIVE_ARTBOARD, ON_ACTIVE_ARTBOARD, waits_for_plugin_loads, waits_for_tool_edit};
|
||||
pub use doc_state::{DocState, LayersReveal, OpenRows, RecalledSelection};
|
||||
pub use error::{EngineError, READ_ONLY_LOCATION, Result, SCRIPT_BUSY};
|
||||
#[cfg(test)]
|
||||
use history::history_budget_for;
|
||||
pub use history::{History, HistoryEntry, NamedStep, default_history_budget};
|
||||
pub(crate) use interaction::PreviewCopies;
|
||||
pub(crate) use interaction::{HeldInteraction, PreviewCopies};
|
||||
pub use interaction::{Interaction, LastTransform, UndoGroup, UndoScope};
|
||||
pub use prefs::{DrawMode, KEY_HOLD_DELAY, KEY_HOLD_DELAY_RANGE, PluginBudget, Prefs};
|
||||
pub use sanity::TOO_DEEP;
|
||||
|
||||
@@ -55,6 +55,15 @@ pub struct Prefs {
|
||||
/// re-mapped by the turn, scale and move that take its old ends to its new ends. Off (the
|
||||
/// default), the handles of a moved anchor move with it and the other handles stay.
|
||||
pub interpolate_control_points: bool,
|
||||
/// General › Delete Removes Anchor Points and Keeps Paths Joined: the default of the
|
||||
/// `keepJoined` param of `edit.clear` (the Delete and Backspace keys and Edit › Clear). On,
|
||||
/// Clear removes the direct-selected anchors of a path as Remove Anchor Points does, refitting
|
||||
/// the curve around each one, instead of deleting them with their segments. Off (the default),
|
||||
/// Clear opens the path there.
|
||||
pub delete_keeps_paths_joined: bool,
|
||||
/// General › Double-Click Adds Anchor Points: on, a plain double-click on a path segment with
|
||||
/// Direct Selection adds an anchor there. Off (the default), the double-click adds nothing.
|
||||
pub double_click_adds_anchor_points: bool,
|
||||
pub use_precise_cursors: bool,
|
||||
pub show_tool_tips: bool,
|
||||
/// General › Show Tool Cards: with tool tips on, a tool button's tool tip is a card with what the
|
||||
@@ -479,6 +488,8 @@ impl Default for Prefs {
|
||||
corner_radius: 12.0,
|
||||
disable_auto_add_delete: false,
|
||||
interpolate_control_points: false,
|
||||
delete_keeps_paths_joined: false,
|
||||
double_click_adds_anchor_points: false,
|
||||
use_precise_cursors: false,
|
||||
show_tool_tips: true,
|
||||
show_tool_cards: false,
|
||||
|
||||
@@ -923,8 +923,15 @@ fn read_head(real: &Path, max: usize) -> std::io::Result<Vec<u8>> {
|
||||
/// that is not well formed is left out. It is read under [`lock_store`]'s lock, so it is read
|
||||
/// between two changes, and none are read when the lock cannot be taken.
|
||||
fn read_store(store: &Path) -> Vec<serde_json::Value> {
|
||||
let Ok(_lock) = lock_store(store) else { return Vec::new() };
|
||||
load_store(store, false).unwrap_or_default()
|
||||
list_store(store).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The grants [`read_store`] reads; none when the grants file is missing, and `Err` when the lock
|
||||
/// cannot be taken or the file is there but cannot be read, is too large, is not a grants file of
|
||||
/// this version or holds no list of grants.
|
||||
fn list_store(store: &Path) -> std::io::Result<Vec<serde_json::Value>> {
|
||||
let _lock = lock_store(store)?;
|
||||
load_store(store, false)
|
||||
}
|
||||
|
||||
/// The grants the grants file at `store` holds, to change and write back; none when it is missing,
|
||||
@@ -940,7 +947,8 @@ fn try_read_store(store: &Path) -> std::io::Result<Vec<serde_json::Value>> {
|
||||
fn load_store(store: &Path, strict: bool) -> std::io::Result<Vec<serde_json::Value>> {
|
||||
let bytes = match read_head(store, MAX_STORE_BYTES) {
|
||||
Ok(bytes) => bytes,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
|
||||
// A link whose target is missing is there but cannot be read.
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound && std::fs::symlink_metadata(store).is_err() => return Ok(Vec::new()),
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
if bytes.len() > MAX_STORE_BYTES {
|
||||
@@ -958,14 +966,14 @@ fn load_store(store: &Path, strict: bool) -> std::io::Result<Vec<serde_json::Val
|
||||
&& g["write"].is_boolean()
|
||||
&& g["folder"].is_boolean()
|
||||
};
|
||||
let grants = v["grants"].as_array().ok_or_else(|| std::io::Error::other("the grants file holds no list of grants"))?;
|
||||
if strict {
|
||||
let grants = v["grants"].as_array().ok_or_else(|| std::io::Error::other("the grants file holds no list of grants"))?;
|
||||
if grants.len() > MAX_STORED_GRANTS || !grants.iter().all(valid) {
|
||||
return Err(std::io::Error::other("the grants file holds a grant that cannot be read"));
|
||||
}
|
||||
return Ok(grants.clone());
|
||||
}
|
||||
Ok(v["grants"].as_array().map(|a| a.iter().filter(|g| valid(g)).take(MAX_STORED_GRANTS).cloned().collect()).unwrap_or_default())
|
||||
Ok(grants.iter().filter(|g| valid(g)).take(MAX_STORED_GRANTS).cloned().collect())
|
||||
}
|
||||
|
||||
/// The number in the name of the next file [`write_store`] writes before it takes the grants file's
|
||||
@@ -1065,9 +1073,9 @@ fn lock_store(_: &Path) -> std::io::Result<std::fs::File> {
|
||||
}
|
||||
|
||||
/// The grants the grants file beside the data folder `data_dir` keeps: each script, the SHA-256 of
|
||||
/// its text, the path and whether it may be written (`script.grants`).
|
||||
pub(crate) fn stored_grants(data_dir: &Path) -> Vec<serde_json::Value> {
|
||||
read_store(&data_dir.with_file_name(GRANTS_FILE))
|
||||
/// its text, the path and whether it may be written (`script.grants`); as [`list_store`] reads them.
|
||||
pub(crate) fn stored_grants(data_dir: &Path) -> std::io::Result<Vec<serde_json::Value>> {
|
||||
list_store(&data_dir.with_file_name(GRANTS_FILE))
|
||||
}
|
||||
|
||||
/// Removes from the grants file beside `data_dir` the grants of the script `script` and of the path
|
||||
|
||||
@@ -326,7 +326,7 @@ impl Files {
|
||||
|
||||
/// The options a file of this run is parsed with, preprocessor lines aside.
|
||||
pub(crate) fn options(&self) -> Options {
|
||||
Options { max_source_units: MAX_TOTAL_BYTES, es2015: self.es2015, ..Options::default() }
|
||||
Options { max_source_units: MAX_TOTAL_BYTES, es2015: self.es2015, e4x: true, ..Options::default() }
|
||||
}
|
||||
|
||||
/// The `JSINCLUDE` folders of this process: absolute folders separated by `;`.
|
||||
|
||||
@@ -2009,7 +2009,7 @@ impl Session {
|
||||
// A `.js` script reads ECMAScript 2015; `eval`, `Function`, includes and `$.evalFile` read
|
||||
// code the way the script does.
|
||||
let es2015 = include::es2015_script(request.file.as_deref());
|
||||
let options = Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), es2015, ..Options::default() };
|
||||
let options = Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), es2015, e4x: true, ..Options::default() };
|
||||
let strict = options.strict;
|
||||
// A kept engine reads each run's code the way that run's script does.
|
||||
let mut realm = match realm {
|
||||
|
||||
@@ -69,6 +69,9 @@ impl Session {
|
||||
selection_at_lend: None,
|
||||
lent_selection: None,
|
||||
last_selection_tool: None,
|
||||
last_part_selection_tool: None,
|
||||
press_lent: None,
|
||||
hover_lent: None,
|
||||
last_view: ViewInfo::default(),
|
||||
preview_memo: Default::default(),
|
||||
depth: 0,
|
||||
@@ -103,6 +106,8 @@ impl Session {
|
||||
profile_dir: None,
|
||||
color_settings_file: None,
|
||||
plugin_dir: None,
|
||||
plugin_loads: Default::default(),
|
||||
plugin_loads_in_background: false,
|
||||
scripts_dir: None,
|
||||
metadata_templates_dir: None,
|
||||
new_doc_profile_dir: None,
|
||||
@@ -139,6 +144,7 @@ impl Session {
|
||||
recovery: Default::default(),
|
||||
in_tool_actions: false,
|
||||
settled_warnings: None,
|
||||
held_interaction: None,
|
||||
previewing: false,
|
||||
decoded_images: Default::default(),
|
||||
envelope_defaults: None,
|
||||
@@ -212,6 +218,7 @@ impl Session {
|
||||
return;
|
||||
}
|
||||
self.press_type_selection = None;
|
||||
self.press_lent = None;
|
||||
let view = self.last_view;
|
||||
// The edit the tool computes on another thread and the input held for it belong to the
|
||||
// document being left. The switch goes on whatever they did, as for the deactivation.
|
||||
|
||||
@@ -287,6 +287,190 @@ impl Session {
|
||||
(r, settled)
|
||||
}
|
||||
|
||||
/// Run `f`, the top-level command `id` with `params` from outside the tool (a panel, a menu
|
||||
/// item, an automation client), with the active document's tool drag set aside: the command
|
||||
/// runs on the document the drag started from and records its own undo step and journal entry.
|
||||
/// The drag then starts from what the command left, and its preview is applied again, so the
|
||||
/// next preview, the commit and a cancel keep the command's edit, and Undo takes back the drag's
|
||||
/// step before the command's. While the command runs, [`Session::in_interaction`] is false, so
|
||||
/// it updates Recent Colors and converts or remaps the new-art paints at once, as it does with
|
||||
/// no drag in progress.
|
||||
///
|
||||
/// The interaction stays as it is, and the command runs inside it, for an interaction a dialog
|
||||
/// or a panel began (it builds its preview from commands), for typing in progress
|
||||
/// ([`Session::edit`] keeps it as a step of its own), for the Quick Pen (an edit made outside
|
||||
/// it ends the path it draws), and for a copy made with `object.transform` during a drag that
|
||||
/// copies (it copies the document as the drag's move left it). A command that settles,
|
||||
/// commits or cancels the interaction, or that hands the active tool actions to apply, gets it
|
||||
/// back first ([`Session::put_back_interaction`]), as it found it.
|
||||
pub(crate) fn outside_interaction(&mut self, id: &str, params: &Value, f: impl FnOnce(&mut Self) -> Result<Value>) -> Result<Value> {
|
||||
if cmd::typing_in_progress(self) || self.tool_id() == vectorcraft_tools::quickpen::ID {
|
||||
return f(self);
|
||||
}
|
||||
let Some(st) = self.active_mut() else { return f(self) };
|
||||
let Some(it) = st.interaction.as_ref().filter(|it| it.tool) else { return f(self) };
|
||||
// A drag that copies: its latest preview, applied or held back by Real-time Drawing off, copies.
|
||||
let copying = it.preview.as_ref().is_some_and(|(c, p)| c == "object.transform" && p.get("copy").and_then(Value::as_bool) == Some(true));
|
||||
if copying && id == "object.transform" && params.get("copy").and_then(Value::as_bool) == Some(true) {
|
||||
return f(self);
|
||||
}
|
||||
let Some(interaction) = st.interaction.take() else { return f(self) };
|
||||
// The document and selection on show, when a preview changed them.
|
||||
let previewed = !Arc::ptr_eq(&st.doc, &interaction.doc) || st.selection != *interaction.selection;
|
||||
let shown = previewed.then(|| (st.doc.clone(), st.selection.clone()));
|
||||
if previewed {
|
||||
st.doc = interaction.doc.clone();
|
||||
st.selection.clone_from(&interaction.selection);
|
||||
st.revision += 1;
|
||||
cmd::globaledit::follow_history(st);
|
||||
}
|
||||
let (uid, state) = (st.uid, crate::interaction::ViewState::of(st));
|
||||
let paint = self.paint.clone();
|
||||
self.held_interaction = Some(crate::HeldInteraction { uid, interaction, shown, state, paint });
|
||||
if previewed {
|
||||
self.sync_front_profiles();
|
||||
}
|
||||
let r = f(self);
|
||||
self.put_back_interaction();
|
||||
r
|
||||
}
|
||||
|
||||
/// Put back the interaction [`Session::outside_interaction`] set aside. When the command left
|
||||
/// the document and the selection as it found them, the preview on show before it is on show
|
||||
/// again. Otherwise the interaction starts from the document the command left and from its
|
||||
/// own selection, without the objects the command removed, hid or locked, and the preview that Real-time
|
||||
/// Drawing showed is applied to it again. The warning or the error of that preview goes to
|
||||
/// the command's result ([`Session::note_settled_warning`]); a preview that fails leaves the
|
||||
/// interaction with nothing to commit. An interaction whose document the command closed ends,
|
||||
/// and so does one with anchors or segments selected on a path the command changed in more
|
||||
/// than a move. A document
|
||||
/// the command left an interaction of its own on keeps that one.
|
||||
pub(crate) fn put_back_interaction(&mut self) {
|
||||
let Some(crate::HeldInteraction { uid, interaction: mut it, shown, state, paint }) = self.held_interaction.take() else { return };
|
||||
// A selection command loaded the paints of the selection it made into the fill and stroke
|
||||
// proxies. The drag goes on with its own selection, so they show its paints again.
|
||||
if self.paint != paint
|
||||
&& let Some(st) = self.active_mut().filter(|d| d.uid == uid && d.interaction.is_none())
|
||||
{
|
||||
let own = drag_selection(&it.selection, &st.doc);
|
||||
if st.selection != own {
|
||||
let made = std::mem::replace(&mut st.selection, own);
|
||||
self.inherit_new_art();
|
||||
self.load_selection_paints();
|
||||
if let Some(st) = self.active_mut() {
|
||||
st.selection = made;
|
||||
}
|
||||
}
|
||||
}
|
||||
// A change the command made to the new-art paints stays when the next preview or a cancel
|
||||
// puts back the paints the interaction began with (the Live Paint Bucket's colors); the
|
||||
// parts it left alone keep the interaction's. The pattern lists every field, so a field
|
||||
// added to `PaintDefaults` does not compile until it is handled here.
|
||||
let vectorcraft_tools::PaintDefaults { fill, stroke, stroke_width, appearance, opacity, blend, style, inherited } = &self.paint;
|
||||
let start = &mut it.paint;
|
||||
if *fill != paint.fill {
|
||||
start.fill.clone_from(fill);
|
||||
}
|
||||
if *stroke != paint.stroke {
|
||||
start.stroke.clone_from(stroke);
|
||||
}
|
||||
if *stroke_width != paint.stroke_width {
|
||||
start.stroke_width = *stroke_width;
|
||||
}
|
||||
if *appearance != paint.appearance {
|
||||
start.appearance.clone_from(appearance);
|
||||
}
|
||||
if *opacity != paint.opacity {
|
||||
start.opacity = *opacity;
|
||||
}
|
||||
if *blend != paint.blend {
|
||||
start.blend = *blend;
|
||||
}
|
||||
if *style != paint.style {
|
||||
start.style.clone_from(style);
|
||||
}
|
||||
if *inherited != paint.inherited {
|
||||
start.inherited = *inherited;
|
||||
}
|
||||
let active = self.active().is_some_and(|d| d.uid == uid);
|
||||
let Some(st) = self.docs.iter_mut().find(|d| d.uid == uid) else { return };
|
||||
if st.interaction.is_some() {
|
||||
return;
|
||||
}
|
||||
// A change the command made to the current layer, the highlighted rows or variable, or
|
||||
// isolation stays when the interaction is canceled.
|
||||
state.rebase(crate::interaction::ViewState::of(st), &mut it);
|
||||
let previewed = shown.is_some();
|
||||
if Arc::ptr_eq(&st.doc, &it.doc) && st.selection == *it.selection {
|
||||
if let Some((doc, selection)) = shown {
|
||||
st.doc = doc;
|
||||
st.selection = selection;
|
||||
st.revision += 1;
|
||||
cmd::globaledit::follow_history(st);
|
||||
}
|
||||
st.interaction = Some(it);
|
||||
if previewed {
|
||||
self.sync_front_profiles();
|
||||
}
|
||||
return;
|
||||
}
|
||||
// The drag's anchors and segments are numbered in the paths it began on. When the command
|
||||
// changed one of those paths in more than a move, the numbers can name other points, and
|
||||
// the drag ends without a step.
|
||||
if renumbered(&it.selection, &it.doc, &st.doc) {
|
||||
self.clear_deferred_overlay_cache();
|
||||
return;
|
||||
}
|
||||
let began = std::mem::replace(&mut it.doc, st.doc.clone());
|
||||
// The drag acts on the objects it began with: a selection the command made (a paste, a
|
||||
// duplicate, Select All) does not change what the drag moves.
|
||||
it.selection = Arc::new(drag_selection(&it.selection, &st.doc));
|
||||
// The journal holds the selection the command left. The drag's own selection is journaled
|
||||
// after it, so the drag and the commands after it replay on the objects they act on.
|
||||
let reselect = (active && st.selection != *it.selection)
|
||||
.then(|| selection_steps(&it.selection, &st.selection, &st.doc, st.active_layer, &st.highlighted_rows()));
|
||||
// The objects the drag's preview names leave out those the command removed, hid or locked.
|
||||
// A preview left naming none has nothing to apply, and the drag records no step.
|
||||
if it.preview.as_mut().is_some_and(|(_, p)| !drag_targets(p, &began, &st.doc)) {
|
||||
it.preview = None;
|
||||
}
|
||||
it.copies = None;
|
||||
it.move_box = std::sync::OnceLock::new();
|
||||
// With Real-time Drawing off the preview waits for the commit, as it did before the command.
|
||||
let again = it.preview.clone().filter(|_| previewed && active);
|
||||
// Without a preview to apply, the drag's own selection is on show, as a preview would leave
|
||||
// it before it acts.
|
||||
if again.is_none() && st.selection != *it.selection {
|
||||
st.selection.clone_from(&it.selection);
|
||||
st.revision += 1;
|
||||
}
|
||||
st.interaction = Some(it);
|
||||
if let Some(steps) = reselect {
|
||||
let (from, grouped) = (self.journal.len(), self.undo_group_docs());
|
||||
for step in steps {
|
||||
self.journal.push(step);
|
||||
}
|
||||
self.journal_in_undo_groups(Some(uid), &grouped, from);
|
||||
}
|
||||
self.clear_deferred_overlay_cache();
|
||||
if let Some((cmd, p)) = again {
|
||||
match self.preview(&cmd, &p) {
|
||||
Ok(v) => {
|
||||
if let Some(w) = v.get("warning").and_then(Value::as_str) {
|
||||
self.note_settled_warning(w);
|
||||
}
|
||||
}
|
||||
Err(e) => self.note_settled_warning(&e.to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// While a command from outside the tool runs: the interaction it set aside
|
||||
/// ([`Session::outside_interaction`]).
|
||||
pub(crate) fn holds_interaction(&self) -> bool {
|
||||
self.held_interaction.is_some()
|
||||
}
|
||||
|
||||
/// [`Session::begin_interaction`] for a dialog or a panel that starts a preview → the warnings
|
||||
/// of the preview that keeping typing in progress applied, for its status bar.
|
||||
pub fn begin_interaction_warned(&mut self, label: &str) -> Result<Vec<String>> {
|
||||
@@ -311,6 +495,8 @@ impl Session {
|
||||
if label != "Typing" && cmd::typing_in_progress(self) {
|
||||
cmd::settle_interaction(self)?;
|
||||
}
|
||||
// A command from outside the tool that begins an interaction during a drag joins the drag's.
|
||||
self.put_back_interaction();
|
||||
// An edit the tool computes on another thread (a Shape Builder merge) is applied first too,
|
||||
// so the snapshot the interaction previews from and goes back to holds it.
|
||||
if !self.in_interaction() {
|
||||
@@ -327,6 +513,7 @@ impl Session {
|
||||
doc: st.doc.clone(),
|
||||
selection: Arc::new(st.selection.clone()),
|
||||
preview: None,
|
||||
tool: false,
|
||||
paint,
|
||||
used_defaults_only: false,
|
||||
preview_paint: None,
|
||||
@@ -347,6 +534,7 @@ impl Session {
|
||||
|
||||
/// Re-apply `cmd` on top of the interaction snapshot (replacing the previous preview).
|
||||
pub fn preview(&mut self, cmd: &str, params: &Value) -> Result<Value> {
|
||||
self.put_back_interaction();
|
||||
if self.script_running() {
|
||||
return Err(EngineError::Busy);
|
||||
}
|
||||
@@ -438,6 +626,7 @@ impl Session {
|
||||
fn commit_interaction_unwatched(&mut self) -> Result<()> {
|
||||
self.clear_deferred_overlay_cache();
|
||||
self.decoded_images.empty();
|
||||
self.put_back_interaction();
|
||||
if let Some(paint) = self.active().and_then(|st| st.interaction.as_ref()).and_then(|it| it.preview_paint.clone()) {
|
||||
self.paint = paint;
|
||||
}
|
||||
@@ -527,6 +716,7 @@ impl Session {
|
||||
}
|
||||
|
||||
pub fn cancel_interaction(&mut self) -> Result<()> {
|
||||
self.put_back_interaction();
|
||||
self.clear_deferred_overlay_cache();
|
||||
self.decoded_images.empty();
|
||||
self.pending_paint = None;
|
||||
@@ -567,3 +757,163 @@ impl Session {
|
||||
self.active().is_some_and(|d| d.interaction.is_some())
|
||||
}
|
||||
}
|
||||
|
||||
/// The selection a drag began with, without the objects that a command run during it removed,
|
||||
/// hid or locked in `doc`.
|
||||
fn drag_selection(began: &Selection, doc: &Document) -> Selection {
|
||||
let mut selection = began.clone();
|
||||
selection.prune(doc);
|
||||
let editable = doc.editable();
|
||||
let held: Vec<_> = selection.objects.iter().copied().filter(|&id| !editable(id)).collect();
|
||||
selection.remove_all(held);
|
||||
selection
|
||||
}
|
||||
|
||||
/// Take out of the `ids` of a drag's preview `params` the objects that a command run during the
|
||||
/// drag removed from `doc`, or hid or locked there while they were editable in `began` → false
|
||||
/// when the preview named objects and none of them is left.
|
||||
fn drag_targets(params: &mut Value, began: &Document, doc: &Document) -> bool {
|
||||
let Some(ids) = params.get_mut("ids").and_then(Value::as_array_mut) else { return true };
|
||||
if ids.is_empty() {
|
||||
return true;
|
||||
}
|
||||
let (was, now) = (began.editable(), doc.editable());
|
||||
ids.retain(|v| v.as_u64().map(vectorcraft_doc::NodeId).is_none_or(|id| doc.node(id).is_some() && (now(id) || !was(id))));
|
||||
!ids.is_empty()
|
||||
}
|
||||
|
||||
/// Whether a path with anchors or segments in `selection` is other in `doc` than in `began`, the
|
||||
/// document a drag began from, in more than a move: its anchors added, removed, put in another
|
||||
/// order (Reverse Path Direction) or reshaped, or a subpath opened or closed. A path the command
|
||||
/// moved as a whole keeps its numbers.
|
||||
fn renumbered(selection: &Selection, began: &Document, doc: &Document) -> bool {
|
||||
fn path(d: &Document, id: vectorcraft_doc::NodeId) -> Option<&[vectorcraft_geom::SubPath]> {
|
||||
d.node(id).and_then(|n| n.path_data()).map(|p| p.subpaths.as_slice())
|
||||
}
|
||||
selection.anchors.keys().chain(selection.segments.keys()).any(|&id| match (path(began, id), path(doc, id)) {
|
||||
(Some(was), Some(now)) => !moved_whole(was, now),
|
||||
(was, now) => was.is_some() != now.is_some(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the subpaths `now` are the subpaths `was` moved by one offset: the same number of each,
|
||||
/// each opened or closed as before, every anchor of the same kind, and every anchor and handle
|
||||
/// offset alike.
|
||||
fn moved_whole(was: &[vectorcraft_geom::SubPath], now: &[vectorcraft_geom::SubPath]) -> bool {
|
||||
if was.len() != now.len() || was.iter().zip(now).any(|(a, b)| a.closed != b.closed || a.anchors.len() != b.anchors.len()) {
|
||||
return false;
|
||||
}
|
||||
let mut pairs = was.iter().zip(now).flat_map(|(a, b)| a.anchors.iter().zip(b.anchors.iter()));
|
||||
let Some((a0, b0)) = pairs.next() else { return true };
|
||||
let (dx, dy) = (b0.p.x - a0.p.x, b0.p.y - a0.p.y);
|
||||
let alike = |a: vectorcraft_geom::Point, b: vectorcraft_geom::Point| {
|
||||
(b.x - a.x - dx).abs() <= vectorcraft_geom::EPS && (b.y - a.y - dy).abs() <= vectorcraft_geom::EPS
|
||||
};
|
||||
std::iter::once((a0, b0)).chain(pairs).all(|(a, b)| a.kind == b.kind && alike(a.p, b.p) && alike(a.h_in, b.h_in) && alike(a.h_out, b.h_out))
|
||||
}
|
||||
|
||||
/// The journal entries that select `selection` again in `doc` after `made`, the selection a
|
||||
/// command left with `layer` current and `rows` highlighted in the Layers panel ([`object_steps`]).
|
||||
/// When selecting the objects would make another layer current, `layer.setCurrent` makes `layer`
|
||||
/// current again, as the drag leaves it, and `layer.highlight` gives back the highlighted rows.
|
||||
fn selection_steps(
|
||||
selection: &Selection,
|
||||
made: &Selection,
|
||||
doc: &Document,
|
||||
layer: Option<vectorcraft_doc::NodeId>,
|
||||
rows: &[vectorcraft_doc::NodeId],
|
||||
) -> Vec<(String, Value)> {
|
||||
let mut steps = object_steps(selection, doc);
|
||||
// `layer.target` on a layer makes it current; any other change to the selected objects makes
|
||||
// the layer of the last selected object current.
|
||||
let targeted = steps.first().is_some_and(|(id, _)| id == "layer.target");
|
||||
let selects = match selection.target.filter(|t| targeted && doc.node(*t).is_some_and(|n| n.is_layer())) {
|
||||
Some(t) => Some(t),
|
||||
None if selection.objects != made.objects => {
|
||||
selection.objects.last().and_then(|id| doc.layer_containing(*id)).filter(|l| doc.is_editable(*l))
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
if let Some(layer) = layer.filter(|l| selects.is_some_and(|s| s != *l)) {
|
||||
steps.push(("layer.setCurrent".into(), serde_json::json!({ "id": layer.0 })));
|
||||
// `layer.setCurrent` highlights the layer's row. `layer.highlight` sets the rows the command
|
||||
// left instead; it keeps `layer` current while the last of them is on `layer`, or none is left.
|
||||
if rows != [layer] && rows.last().is_none_or(|r| doc.layer_containing(*r) == Some(layer)) {
|
||||
let ids: Vec<u64> = rows.iter().map(|r| r.0).collect();
|
||||
steps.push(("layer.highlight".into(), serde_json::json!({ "ids": ids, "mode": "set" })));
|
||||
}
|
||||
}
|
||||
steps
|
||||
}
|
||||
|
||||
/// The journal entries that select `selection` in `doc`: the selections made on their own (its
|
||||
/// slices with `object.slice.select`, its target with `layer.target`, its symbol part with
|
||||
/// `symbol.instance.selectPart`, its Objects on Path member with
|
||||
/// `object.objectsOnPath.selectMember`), or its objects in their order (`select.set`), the anchors
|
||||
/// left out on paths that are not selected whole (`select.anchorsMany`), the anchors of paths with
|
||||
/// every anchor selected (`select.anchors`) and its segments (`select.segments`); after its objects
|
||||
/// or its target, its ruler guides (`guide.select`) and its key object, key guide or key anchor
|
||||
/// (`select.key`).
|
||||
fn object_steps(selection: &Selection, doc: &Document) -> Vec<(String, Value)> {
|
||||
use serde_json::json;
|
||||
if !selection.slices.is_empty() {
|
||||
let slices: Vec<u64> = selection.slices.iter().map(|id| id.0).collect();
|
||||
return vec![("object.slice.select".into(), json!({ "slices": slices }))];
|
||||
}
|
||||
// A target is selected again only while targeting it selects the same objects: when a command
|
||||
// added art to a targeted layer, `select.set` selects the drag's objects.
|
||||
let targets = |t: vectorcraft_doc::NodeId| match doc.node(t) {
|
||||
Some(n) if n.is_layer() => n.layer_art(true) == selection.objects,
|
||||
_ => selection.objects == [t],
|
||||
};
|
||||
let json_refs = |refs: &mut dyn Iterator<Item = &(usize, usize)>| Value::Array(refs.map(|&(a, b)| json!([a, b])).collect());
|
||||
// A targeted object keeps the ruler guides and the key selected beside it.
|
||||
let mut steps = if let Some(t) = selection.target.filter(|&t| targets(t)) {
|
||||
vec![("layer.target".to_string(), json!({ "id": t.0 }))]
|
||||
} else if let Some(part) = &selection.symbol_part {
|
||||
return vec![("symbol.instance.selectPart".into(), json!({ "id": part.instance.0, "path": part.path }))];
|
||||
} else if let Some(member) = selection.on_path_member {
|
||||
return vec![("object.objectsOnPath.selectMember".into(), json!({ "member": member.0 }))];
|
||||
} else {
|
||||
let ids: Vec<u64> = selection.objects.iter().map(|id| id.0).collect();
|
||||
let mut steps = vec![("select.set".to_string(), json!({ "ids": ids }))];
|
||||
// `select.set` selects each path whole: subtracting the anchors that are not selected leaves
|
||||
// the ones that are, and keeps the order of the objects. A path with every anchor selected
|
||||
// as anchors gets them back with `select.anchors`, which keeps them all as anchors.
|
||||
let mut every = Vec::new();
|
||||
let partial: Vec<Value> = selection
|
||||
.objects
|
||||
.iter()
|
||||
.filter_map(|id| {
|
||||
let refs = selection.anchors.get(id)?;
|
||||
let path = doc.node(*id)?.path_data()?;
|
||||
let out: Vec<(usize, usize)> = path.anchors().map(|(s, i, _)| (s, i)).filter(|r| !refs.contains(r)).collect();
|
||||
if out.is_empty() {
|
||||
every.push(("select.anchors".to_string(), json!({ "id": id.0, "anchors": json_refs(&mut refs.iter()), "mode": "add" })));
|
||||
return None;
|
||||
}
|
||||
Some(json!({ "id": id.0, "anchors": json_refs(&mut out.iter()) }))
|
||||
})
|
||||
.collect();
|
||||
if !partial.is_empty() {
|
||||
steps.push(("select.anchorsMany".into(), json!({ "items": partial, "mode": "subtract" })));
|
||||
}
|
||||
steps.extend(every);
|
||||
for (id, refs) in &selection.segments {
|
||||
steps.push(("select.segments".into(), json!({ "id": id.0, "segments": json_refs(&mut refs.iter()), "mode": "add" })));
|
||||
}
|
||||
steps
|
||||
};
|
||||
if !selection.guides.is_empty() {
|
||||
let indexes = cmd::guide_indexes(doc, &selection.guides);
|
||||
steps.push(("guide.select".into(), json!({ "indexes": indexes, "toggle": true })));
|
||||
}
|
||||
if let Some((id, (s, i))) = selection.key_anchor {
|
||||
steps.push(("select.key".into(), json!({ "id": id.0, "anchor": [s, i] })));
|
||||
} else if let Some(g) = selection.key_guide.and_then(|g| cmd::guide_indexes(doc, &[g]).first().copied()) {
|
||||
steps.push(("select.key".into(), json!({ "guide": g })));
|
||||
} else if let Some(key) = selection.key {
|
||||
steps.push(("select.key".into(), json!({ "id": key.0 })));
|
||||
}
|
||||
steps
|
||||
}
|
||||
@@ -59,6 +59,13 @@ impl Session {
|
||||
|
||||
/// Execute a command by id. This is THE entry point for every frontend.
|
||||
pub fn execute(&mut self, id: &str, params: &Value) -> Result<Value> {
|
||||
// Plug-ins still loading on other threads ([`Session::load_plugins_in_background`]) are
|
||||
// installed before a plug-in command, its own commands included, and before a command that
|
||||
// may edit, as they would have been before the window showed; a step of a batch waits for
|
||||
// the plug-ins an earlier step started loading.
|
||||
if self.plugins_loading() && crate::waits_for_plugin_loads(id) {
|
||||
self.finish_plugin_loads();
|
||||
}
|
||||
self.revealing(|s| s.execute_unwatched(id, params))
|
||||
}
|
||||
|
||||
@@ -99,10 +106,17 @@ impl Session {
|
||||
self.finish_tool_edit_later()?;
|
||||
}
|
||||
let outer = std::mem::replace(&mut self.reading, !spec.journal || JOURNALED_READS.contains(&id));
|
||||
// A command from outside the tool, while the tool's drag is in progress, is a step of its
|
||||
// own before the drag's ([`Session::outside_interaction`]). Find Objects with `select` is
|
||||
// journaled (`Session::journal_query`), so it is one too.
|
||||
let find_selects = id == "document.find" && params.get("select").and_then(Value::as_bool) == Some(true);
|
||||
let outside = (spec.journal || find_selects) && !self.previewing && !self.in_tool_actions;
|
||||
// A preview that a top-level command applied first (a drag with Real-time Drawing off, kept
|
||||
// before Undo) reports its warning in the command's result.
|
||||
let r = if self.depth == 0 {
|
||||
let (r, settled) = self.collect_settled_warnings(|s| s.execute_spec(spec, id, params));
|
||||
let (r, settled) = self.collect_settled_warnings(|s| {
|
||||
if outside { s.outside_interaction(id, params, |s| s.execute_spec(spec, id, params)) } else { s.execute_spec(spec, id, params) }
|
||||
});
|
||||
r.map(|v| with_settled_warnings(v, &settled))
|
||||
} else {
|
||||
self.execute_spec(spec, id, params)
|
||||
|
||||
+650
-67
@@ -35,14 +35,16 @@
|
||||
//! The files are untrusted input like any other: sizes and counts are capped, a file that does not
|
||||
//! parse is skipped with a log record, and every write is atomic.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::collections::{BTreeMap, BTreeSet, VecDeque};
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex, MutexGuard};
|
||||
use std::time::SystemTime;
|
||||
|
||||
use serde_json::Value;
|
||||
use vectorcraft_pdf::{APP, PdfPreset, builtin_preset};
|
||||
use vectorcraft_plugins::loader::{Job, Loads};
|
||||
use vectorcraft_plugins::permissions::GrantToken;
|
||||
use vectorcraft_plugins::safe_mode;
|
||||
use vectorcraft_plugins::storage::{self, Meter, Storage, StorageError};
|
||||
@@ -170,6 +172,29 @@ fn list_files(dir: &Path, ext: &str) -> Vec<PathBuf> {
|
||||
files
|
||||
}
|
||||
|
||||
/// [`list_files`], each file with its stamp ([`file_stamp`]) from the same look at it.
|
||||
fn list_stamped_files(dir: &Path, ext: &str) -> Vec<(PathBuf, (u64, SystemTime))> {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else { return vec![] };
|
||||
let mut files: Vec<_> = entries
|
||||
.filter_map(Result::ok)
|
||||
.map(|e| e.path())
|
||||
.filter(|p| p.extension().is_some_and(|e| e.eq_ignore_ascii_case(ext)))
|
||||
.filter_map(|p| {
|
||||
let m = std::fs::metadata(&p).ok().filter(std::fs::Metadata::is_file)?;
|
||||
match m.modified() {
|
||||
Ok(t) => Some((p, (m.len(), t))),
|
||||
Err(e) => {
|
||||
log::warn!("skipping the stored plug-in {}: {e}", p.display());
|
||||
None
|
||||
}
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
files.sort_by_key(|(p, _)| p.file_name().map(|n| n.to_string_lossy().to_lowercase()));
|
||||
files.truncate(MAX_STORE_FILES);
|
||||
files
|
||||
}
|
||||
|
||||
/// The content of `path` when it is at most `max` bytes; the file is never read past `max`.
|
||||
pub(crate) fn read_capped(path: &Path, max: u64) -> Result<Vec<u8>, String> {
|
||||
let bytes = read_past_cap(path, max).map_err(|e| e.to_string())?;
|
||||
@@ -187,11 +212,243 @@ fn read_past_cap(path: &Path, max: u64) -> std::io::Result<Vec<u8>> {
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
/// Plug-ins loading on worker threads, which [`Session::poll_plugin_loads`] and
|
||||
/// [`Session::finish_plugin_loads`] install.
|
||||
pub(crate) enum PluginLoad {
|
||||
/// The plug-in store's ([`Session::load_stored_plugins`]).
|
||||
Stored(StoredLoad),
|
||||
/// The Additional Plug-ins Folder's ([`crate::cmd::plugin::sync_prefs`]).
|
||||
Folder(crate::cmd::plugin::FolderPending),
|
||||
}
|
||||
|
||||
impl PluginLoad {
|
||||
/// Starts the modules loading, unless they started already.
|
||||
fn start(&mut self) {
|
||||
match self {
|
||||
PluginLoad::Stored(load) => load.loads.begin(),
|
||||
PluginLoad::Folder(load) => load.start(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The installs and removals it checks its modules against (`None`: a folder that couldn't be
|
||||
/// listed, or one ended already).
|
||||
fn changes(&self) -> Option<&vectorcraft_plugins::registry::LoadChanges> {
|
||||
match self {
|
||||
PluginLoad::Stored(load) => Some(&load.changes),
|
||||
PluginLoad::Folder(load) => load.changes(),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`PluginLoad::changes`], to adopt an earlier load's.
|
||||
fn changes_mut(&mut self) -> Option<&mut vectorcraft_plugins::registry::LoadChanges> {
|
||||
match self {
|
||||
PluginLoad::Stored(load) => Some(&mut load.changes),
|
||||
PluginLoad::Folder(load) => load.changes_mut(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether every module has been installed or skipped.
|
||||
fn done(&self) -> bool {
|
||||
match self {
|
||||
PluginLoad::Stored(load) => load.next == load.files.len() && load.rest.is_empty(),
|
||||
PluginLoad::Folder(load) => load.done(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether something can be installed or ended now, without waiting.
|
||||
pub(crate) fn ready(&mut self) -> bool {
|
||||
match self {
|
||||
PluginLoad::Stored(load) => load.next == load.files.len() || !load.loaded.is_empty() || load.loads.next_ready(),
|
||||
PluginLoad::Folder(load) => load.ready(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Waits until [`PluginLoad::ready`], starting the modules loading first ([`PluginLoad::start`]).
|
||||
fn wait(&mut self) {
|
||||
self.start();
|
||||
match self {
|
||||
PluginLoad::Stored(load) if load.loaded.is_empty() && load.next < load.files.len() => load.loads.wait_next(),
|
||||
PluginLoad::Stored(_) => {}
|
||||
PluginLoad::Folder(load) => load.wait(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Drops the modules not installed yet ([`Session::cancel_plugin_loads`]), leaving it
|
||||
/// [`PluginLoad::done`] with what it installed.
|
||||
fn cancel(&mut self) {
|
||||
match self {
|
||||
PluginLoad::Stored(load) => {
|
||||
load.loads = Loads::deferred(Vec::new());
|
||||
load.loaded.clear();
|
||||
load.next = load.files.len();
|
||||
load.rest.clear();
|
||||
}
|
||||
PluginLoad::Folder(load) => load.cancel(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether installing it takes the plug-in store's own turn, making the store folder (a
|
||||
/// folder's plug-ins keep their settings and cache there), rather than one that goes ahead
|
||||
/// without a store folder.
|
||||
fn creates_store(&self) -> bool {
|
||||
matches!(self, PluginLoad::Folder(_))
|
||||
}
|
||||
}
|
||||
|
||||
/// A stored plug-in file, with its stamp when it was listed ([`file_stamp`]; `None`: it couldn't be
|
||||
/// read).
|
||||
type StoredFile = (PathBuf, Option<FileStamp>);
|
||||
|
||||
/// The stored plug-ins loading from the plug-in store `dir`.
|
||||
pub(crate) struct StoredLoad {
|
||||
dir: PathBuf,
|
||||
/// The files listed, in file-name order.
|
||||
files: Vec<StoredFile>,
|
||||
loads: Loads<StoredRead>,
|
||||
/// Outcomes taken from `loads` and not installed yet, in order.
|
||||
loaded: VecDeque<vectorcraft_plugins::Result<StoredRead>>,
|
||||
/// The next file to install.
|
||||
next: usize,
|
||||
/// The store's grants this load removed, by id, because the module stored for the id lists no
|
||||
/// permissions: a later file holding a module with that id that the grant covers still loads,
|
||||
/// and the grant goes back to the store.
|
||||
retired: BTreeMap<String, vectorcraft_plugins::permissions::Grant>,
|
||||
/// Installs and removals elsewhere since the store was listed, which a module loaded before
|
||||
/// them doesn't undo.
|
||||
changes: vectorcraft_plugins::registry::LoadChanges,
|
||||
/// The files listed after `files`, in file-name order, with their stamps from when the store was
|
||||
/// listed, that wait for `files` to load because what is left of [`MAX_PLUGIN_STORE`] may not
|
||||
/// cover them until the reads that fail give back what they didn't read
|
||||
/// ([`list_stored_plugins`]).
|
||||
rest: VecDeque<StoredFile>,
|
||||
/// What is left of [`MAX_PLUGIN_STORE`]: the listed length of each file in `files` is taken
|
||||
/// from it, and what a failed read didn't read of it is given back.
|
||||
left: u64,
|
||||
}
|
||||
|
||||
/// What a stored plug-in's load read of its file, at most its listed length, and the module.
|
||||
pub(crate) struct StoredRead {
|
||||
read: u64,
|
||||
plugin: vectorcraft_plugins::Result<vectorcraft_plugins::Plugin>,
|
||||
}
|
||||
|
||||
/// Tests: what runs before a stored module is read, given its path.
|
||||
#[cfg(test)]
|
||||
type StoredHook = Arc<dyn Fn(&Path) + Send + Sync>;
|
||||
|
||||
/// Tests: runs on the worker thread before the stored module at the path it is given is read.
|
||||
#[cfg(test)]
|
||||
pub(crate) static BEFORE_STORED_LOAD: Mutex<Option<StoredHook>> = Mutex::new(None);
|
||||
|
||||
#[cfg(test)]
|
||||
fn before_stored_load(path: &Path) {
|
||||
let hook = BEFORE_STORED_LOAD.lock().unwrap_or_else(|e| e.into_inner()).clone();
|
||||
if let Some(hook) = hook {
|
||||
hook(path);
|
||||
}
|
||||
}
|
||||
|
||||
/// Tests: runs on the worker thread once the stored module at the path it is given has loaded, and
|
||||
/// before its file is read again to check that it still holds the module.
|
||||
#[cfg(test)]
|
||||
pub(crate) static AFTER_STORED_LOAD: Mutex<Option<StoredHook>> = Mutex::new(None);
|
||||
|
||||
#[cfg(test)]
|
||||
fn after_stored_load(path: &Path) {
|
||||
let hook = AFTER_STORED_LOAD.lock().unwrap_or_else(|e| e.into_inner()).clone();
|
||||
if let Some(hook) = hook {
|
||||
hook(path);
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a stored plug-in whose file changed between its listing and its install is skipped.
|
||||
const CHANGED_WHILE_LOADING: &str = "it changed or went away while it loaded";
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// Tests: the stored plug-in bytes a store listed on this thread may read ([`MAX_PLUGIN_STORE`]).
|
||||
pub(crate) static PLUGIN_STORE_BUDGET: std::cell::Cell<u64> = const { std::cell::Cell::new(MAX_PLUGIN_STORE) };
|
||||
}
|
||||
|
||||
/// The stored plug-in bytes one store's load reads, all files together ([`MAX_PLUGIN_STORE`]).
|
||||
#[cfg(not(test))]
|
||||
fn plugin_store_budget() -> u64 {
|
||||
MAX_PLUGIN_STORE
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn plugin_store_budget() -> u64 {
|
||||
PLUGIN_STORE_BUDGET.with(std::cell::Cell::get)
|
||||
}
|
||||
|
||||
/// What a file over its cap is told (a detail after the file's name, in the log or an error).
|
||||
fn too_large(max: u64) -> String {
|
||||
format!("larger than {max} bytes")
|
||||
}
|
||||
|
||||
/// Takes the stored plug-in files at the front of `rest`, in order, each one's listed length taken
|
||||
/// from `left` → those files, and the jobs that load them, each reading no more than that length.
|
||||
/// It stops at the first file that `left` doesn't cover but would if files taken before it failed to
|
||||
/// read and gave back what they took; that file and the ones after it stay in `rest`. A file that
|
||||
/// `left` wouldn't cover even then is skipped with a log record, and once nothing can be given back
|
||||
/// to a used-up `left` the rest are, as when the files were read one after the other.
|
||||
fn list_stored_plugins(rest: &mut VecDeque<StoredFile>, left: &mut u64) -> (Vec<StoredFile>, Vec<Job<StoredRead>>) {
|
||||
let limits = vectorcraft_plugins::Limits::default();
|
||||
let mut files = Vec::new();
|
||||
let mut jobs = Vec::new();
|
||||
// What the files taken so far took of `left`.
|
||||
let mut taken = 0;
|
||||
while let Some((path, stamp)) = rest.pop_front() {
|
||||
let len = stamp.flatten().map_or(0, |(len, _)| len);
|
||||
let most = *left + taken;
|
||||
if most == 0 {
|
||||
log::warn!("skipping the other stored plug-ins: they hold more than {MAX_PLUGIN_STORE} bytes together");
|
||||
rest.clear();
|
||||
break;
|
||||
}
|
||||
if len > most {
|
||||
log::warn!("skipping the stored plug-in {}: {}", path.display(), too_large(most));
|
||||
continue;
|
||||
}
|
||||
// An empty file too waits once `left` is used up.
|
||||
if len > *left || *left == 0 {
|
||||
rest.push_front((path, stamp));
|
||||
break;
|
||||
}
|
||||
*left -= len;
|
||||
taken += len;
|
||||
let item = safe_mode::Item::file(path.display().to_string());
|
||||
let (read, limits) = (path.clone(), limits.clone());
|
||||
jobs.push(Job::new(Some(item), move || {
|
||||
#[cfg(test)]
|
||||
before_stored_load(&read);
|
||||
let mut bytes = vec![];
|
||||
let got = std::fs::File::open(&read).and_then(|f| f.take(len + 1).read_to_end(&mut bytes));
|
||||
let plugin = match got {
|
||||
Err(e) => Err(vectorcraft_plugins::Error::Io(e.to_string())),
|
||||
Ok(_) if bytes.len() as u64 > len => Err(vectorcraft_plugins::Error::Io(too_large(len))),
|
||||
Ok(_) => vectorcraft_plugins::Plugin::load(&bytes, limits),
|
||||
};
|
||||
#[cfg(test)]
|
||||
after_stored_load(&read);
|
||||
// A file replaced while its module loaded, by one that kept its length and modified time,
|
||||
// is told apart by its content: it is read again here, within the load's deadline. The
|
||||
// install then skips a file whose stamp changed since.
|
||||
let plugin = plugin.and_then(|p| {
|
||||
if std::fs::File::open(&read).is_ok_and(|f| holds(f, &bytes)) {
|
||||
Ok(p)
|
||||
} else {
|
||||
Err(vectorcraft_plugins::Error::Io(CHANGED_WHILE_LOADING.into()))
|
||||
}
|
||||
});
|
||||
// A read that failed part way read what `bytes` holds.
|
||||
Ok(StoredRead { read: (bytes.len() as u64).min(len), plugin })
|
||||
}));
|
||||
files.push((path, stamp));
|
||||
}
|
||||
(files, jobs)
|
||||
}
|
||||
|
||||
/// Whether `old` holds exactly `bytes`. It is read no further than one byte past their length, so a
|
||||
/// large file is not read into memory.
|
||||
pub(crate) fn holds(old: impl Read, bytes: &[u8]) -> bool {
|
||||
@@ -230,8 +487,7 @@ fn write_atomic(_: &Path, _: &[u8]) -> std::io::Result<()> {
|
||||
/// replaced or removed, so that every window locks the same file.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn lock_store(dir: &Path) -> std::io::Result<std::fs::File> {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
let file = std::fs::File::options().create(true).truncate(false).read(true).write(true).open(dir.join(DISABLED_LOCK))?;
|
||||
let file = open_store_lock(dir)?;
|
||||
match file.try_lock() {
|
||||
Ok(()) => return Ok(file),
|
||||
Err(std::fs::TryLockError::WouldBlock) => {}
|
||||
@@ -245,6 +501,30 @@ fn lock_store(dir: &Path) -> std::io::Result<std::fs::File> {
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
/// [`DISABLED_LOCK`] in `dir`, opened (and made, with the folder) but not locked.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn open_store_lock(dir: &Path) -> std::io::Result<std::fs::File> {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
std::fs::File::options().create(true).truncate(false).read(true).write(true).open(dir.join(DISABLED_LOCK))
|
||||
}
|
||||
|
||||
/// [`lock_store`] without waiting: `None` while another window or process holds the lock.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn try_lock_store(dir: &Path) -> std::io::Result<Option<std::fs::File>> {
|
||||
let file = open_store_lock(dir)?;
|
||||
match file.try_lock() {
|
||||
Ok(()) => Ok(Some(file)),
|
||||
Err(std::fs::TryLockError::WouldBlock) => Ok(None),
|
||||
Err(std::fs::TryLockError::Error(e)) => Err(e),
|
||||
}
|
||||
}
|
||||
|
||||
/// The browser has no folders to keep anything in.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn try_lock_store(_: &Path) -> std::io::Result<Option<std::fs::File>> {
|
||||
Err(std::io::Error::new(std::io::ErrorKind::Unsupported, "no file system"))
|
||||
}
|
||||
|
||||
/// The browser has no folders to keep anything in.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn lock_store(_: &Path) -> std::io::Result<std::fs::File> {
|
||||
@@ -445,78 +725,188 @@ impl Session {
|
||||
}
|
||||
|
||||
/// Keep the plug-ins this session installs in `dir`, take the disabled plug-ins saved there
|
||||
/// ([`DISABLED_FILE`]), and install the stored ones ([`Session::load_stored_plugins`]).
|
||||
/// ([`DISABLED_FILE`]), and install the stored ones ([`Session::load_stored_plugins`]). Loads
|
||||
/// still running from an earlier call are finished first.
|
||||
pub fn attach_plugin_store(&mut self, dir: PathBuf) {
|
||||
let path = dir.join(DISABLED_FILE);
|
||||
self.finish_plugin_loads();
|
||||
self.plugin_dir = Some(dir);
|
||||
// A `plugin.install` in another session or process writes the store before this reads it.
|
||||
let _held = crate::cmd::plugin::hold_plugin_changes();
|
||||
let turn = self.plugin_store_turn_for_load();
|
||||
let disabled = read_capped(&path, safe_mode::MAX_DISABLED_FILE_BYTES).map(|b| safe_mode::parse_disabled_file(&b)).unwrap_or_default();
|
||||
safe_mode::set_disabled(disabled);
|
||||
self.load_stored_plugins_in(&turn);
|
||||
self.start_stored_plugins(true);
|
||||
}
|
||||
|
||||
/// Install the plug-ins kept in the plug-in folder: none in Safe Mode, and none the user
|
||||
/// disabled (matched by file name, which is made from the id). The launch marker names each
|
||||
/// file while it loads. A module that doesn't load, and one that lists permissions the grants
|
||||
/// there don't grant that very module ([`grant_covers`]), is skipped with a log record, and
|
||||
/// stays in the folder with its grant. A grant for an id whose stored module lists no
|
||||
/// permissions is forgotten; one that can't be removed from the grants file doesn't count for
|
||||
/// any session in the process attached to the folder until the file can be written for the id
|
||||
/// ([`Session::ignore_stored_grant`]). The folder is read and changed in one turn on it
|
||||
/// ([`Session::plugin_store_turn_for_load`]).
|
||||
/// disabled (matched by file name, which is made from the id). The modules load on worker
|
||||
/// threads ([`vectorcraft_plugins::loader`]) and install in file-name order, whatever order
|
||||
/// their loads finish in; the launch marker names each file while it loads. A module that
|
||||
/// doesn't load (its load panicked or didn't finish in time included), one that changed or
|
||||
/// went away while it loaded, and one that lists permissions the grants there don't grant that
|
||||
/// very module ([`grant_covers`]), is skipped with a log record, and stays in the folder with
|
||||
/// its grant. A grant for an id whose stored module lists no permissions is forgotten; one that
|
||||
/// can't be removed from the grants file doesn't count for any session in the process attached
|
||||
/// to the folder until the file can be written for the id ([`Session::ignore_stored_grant`]).
|
||||
/// The folder is listed, and what loaded is installed and the folder changed, in turns on it
|
||||
/// ([`Session::plugin_store_turn_for_load`]); the modules load between them. With
|
||||
/// [`Session::load_plugins_in_background`] on, this returns while the modules load.
|
||||
pub fn load_stored_plugins(&mut self) {
|
||||
if self.plugin_dir.is_none() || safe_mode::active() {
|
||||
return;
|
||||
}
|
||||
// A `plugin.install` in another session or process writes the store before this reads it.
|
||||
let _held = crate::cmd::plugin::hold_plugin_changes();
|
||||
let turn = self.plugin_store_turn_for_load();
|
||||
self.load_stored_plugins_in(&turn);
|
||||
self.start_stored_plugins(false);
|
||||
}
|
||||
|
||||
/// [`Session::load_stored_plugins`] in `turn`, while [`crate::cmd::plugin::hold_plugin_changes`]
|
||||
/// is held.
|
||||
fn load_stored_plugins_in(&mut self, turn: &StoreTurn) {
|
||||
/// [`Session::load_stored_plugins`]; `disabled`: first take the disabled plug-ins saved in the
|
||||
/// folder ([`DISABLED_FILE`]).
|
||||
fn start_stored_plugins(&mut self, disabled: bool) {
|
||||
let Some(dir) = self.plugin_dir.clone() else { return };
|
||||
// A `plugin.install` in another session or process writes the store before this lists it.
|
||||
let held = crate::cmd::plugin::hold_plugin_changes();
|
||||
let turn = self.plugin_store_turn_for_load();
|
||||
if disabled {
|
||||
let path = dir.join(DISABLED_FILE);
|
||||
let saved = read_capped(&path, safe_mode::MAX_DISABLED_FILE_BYTES).map(|b| safe_mode::parse_disabled_file(&b)).unwrap_or_default();
|
||||
safe_mode::set_disabled(saved);
|
||||
}
|
||||
if safe_mode::active() {
|
||||
return;
|
||||
}
|
||||
let grants = self.counted_grants(&dir);
|
||||
let limits = vectorcraft_plugins::Limits::default();
|
||||
let mut left = MAX_PLUGIN_STORE;
|
||||
let mut asks_nothing = BTreeSet::new();
|
||||
for path in list_files(&dir, PLUGIN_EXT) {
|
||||
if left == 0 {
|
||||
log::warn!("skipping the other stored plug-ins: they hold more than {MAX_PLUGIN_STORE} bytes together");
|
||||
break;
|
||||
}
|
||||
let module = vectorcraft_plugins::Limits::default().max_module_bytes as u64;
|
||||
let mut rest = VecDeque::new();
|
||||
let disabled: BTreeSet<String> = safe_mode::skipped_ids().iter().map(|id| file_stem(id)).collect();
|
||||
for (path, stamp) in list_stamped_files(&dir, PLUGIN_EXT) {
|
||||
let item = safe_mode::Item::file(path.display().to_string());
|
||||
let stem = path.file_stem().map(|s| s.to_string_lossy().to_string());
|
||||
let by_id = safe_mode::skipped_ids().iter().any(|id| stem.as_deref() == Some(file_stem(id).as_str()));
|
||||
let by_id = path.file_stem().is_some_and(|s| disabled.contains(s.to_string_lossy().as_ref()));
|
||||
if safe_mode::skipped(&item) || by_id {
|
||||
log::info!("skipping the stored plug-in {}: disabled", path.display());
|
||||
} else if stamp.0 > module {
|
||||
log::warn!("skipping the stored plug-in {}: {}", path.display(), too_large(module));
|
||||
} else {
|
||||
rest.push_back((path, Some(Some(stamp))));
|
||||
}
|
||||
}
|
||||
let mut left = plugin_store_budget();
|
||||
let (files, jobs) = list_stored_plugins(&mut rest, &mut left);
|
||||
// A change made after the listing, while `held` no longer stops one, is made elsewhere.
|
||||
let mut changes = vectorcraft_plugins::registry::LoadChanges::default();
|
||||
changes.start();
|
||||
// The modules load after the turn, once the loads queued before them are done.
|
||||
drop((turn, held));
|
||||
let load =
|
||||
StoredLoad { dir, files, loads: Loads::deferred(jobs), loaded: VecDeque::new(), next: 0, retired: BTreeMap::new(), changes, rest, left };
|
||||
self.queue_plugin_load(PluginLoad::Stored(load));
|
||||
}
|
||||
|
||||
/// Installs what the stored plug-ins' `load` has loaded so far, in file-name order up to the
|
||||
/// first module still loading, without waiting ([`Session::load_stored_plugins`]), while
|
||||
/// [`crate::cmd::plugin::hold_plugin_changes`] and `turn` are held.
|
||||
fn install_stored_plugins(&mut self, load: &mut StoredLoad, turn: &StoreTurn) {
|
||||
if load.next == load.files.len() && !load.rest.is_empty() {
|
||||
// Every file listed so far is installed or skipped, and the reads that failed gave
|
||||
// back their length: the files waiting for them are listed now.
|
||||
let (files, jobs) = list_stored_plugins(&mut load.rest, &mut load.left);
|
||||
load.files = files;
|
||||
load.next = 0;
|
||||
load.loads = Loads::start(jobs);
|
||||
return;
|
||||
}
|
||||
load.loaded.extend(load.loads.ready());
|
||||
if load.loaded.is_empty() {
|
||||
return;
|
||||
}
|
||||
let dir = load.dir.clone();
|
||||
// The grants file is read once for this turn. `written` holds whether it names each id
|
||||
// whose grant this turn removed or put back.
|
||||
let file = read_grants(&dir);
|
||||
let mut grants = self.counted(
|
||||
&dir,
|
||||
match &file {
|
||||
Ok(file) => file.grants.clone(),
|
||||
Err(e) => {
|
||||
log::warn!("skipping the stored plug-in grants {}: {}", dir.join(GRANTS_FILE).display(), e.why);
|
||||
BTreeMap::new()
|
||||
}
|
||||
},
|
||||
);
|
||||
let mut written: BTreeMap<String, bool> = BTreeMap::new();
|
||||
let named = |written: &BTreeMap<String, bool>, id: &str| {
|
||||
written.get(id).copied().unwrap_or_else(|| match &file {
|
||||
Ok(file) => file.names(id),
|
||||
Err(e) => e.unread,
|
||||
})
|
||||
};
|
||||
while let (Some(loaded), Some((path, stamp))) = (load.loaded.pop_front(), load.files.get(load.next)) {
|
||||
load.next += 1;
|
||||
load.loads.release(1);
|
||||
// What a read that failed didn't read takes nothing from the total. A load that panicked
|
||||
// or passed its deadline gives nothing back.
|
||||
let loaded = loaded.and_then(|r| {
|
||||
load.left += stamp.flatten().map_or(0, |(len, _)| len).saturating_sub(r.read);
|
||||
r.plugin
|
||||
});
|
||||
// The worker read the file again once its module loaded ([`list_stored_plugins`]); one
|
||||
// whose stamp changed since then is skipped too.
|
||||
if file_stamp(path).ok() != *stamp {
|
||||
log::warn!("skipping the stored plug-in {}: {CHANGED_WHILE_LOADING}", path.display());
|
||||
continue;
|
||||
}
|
||||
let token = safe_mode::loading(&item);
|
||||
let loaded = read_capped(&path, (limits.max_module_bytes as u64).min(left)).and_then(|bytes| {
|
||||
left -= bytes.len() as u64;
|
||||
vectorcraft_plugins::Plugin::load(&bytes, limits.clone()).map_err(|e| e.to_string())
|
||||
});
|
||||
safe_mode::loaded(token);
|
||||
match loaded {
|
||||
Ok(plugin) if load.changes.superseded(plugin.id()) => {
|
||||
log::warn!("skipping the stored plug-in {}: {}", path.display(), vectorcraft_plugins::registry::SUPERSEDED);
|
||||
}
|
||||
// Only this store's grants count: one given elsewhere in the process doesn't let a
|
||||
// module stored here load.
|
||||
Ok(plugin) if plugin.manifest().asks_permissions() => {
|
||||
let m = plugin.manifest();
|
||||
match grants.get(&m.id).filter(|g| grant_covers(g, &plugin)) {
|
||||
let stored = grants.get(&m.id).filter(|g| grant_covers(g, &plugin)).cloned();
|
||||
// A grant given for the id since this load removed one, in another window or
|
||||
// process, is kept.
|
||||
let back = (!grants.contains_key(&m.id) && !named(&written, &m.id))
|
||||
.then(|| load.retired.get(&m.id).filter(|g| grant_covers(g, &plugin)).cloned())
|
||||
.flatten();
|
||||
match stored.or(back.clone()) {
|
||||
Some(g) => {
|
||||
asks_nothing.remove(&m.id);
|
||||
vectorcraft_plugins::registry::grant(GrantToken::from_engine_grants_file(g.clone()));
|
||||
vectorcraft_plugins::registry::set_storage(&m.id, plugin_storage(Some(&dir), &m.id, turn));
|
||||
if let Err(e) = vectorcraft_plugins::registry::install(plugin.with_source(path.display().to_string())) {
|
||||
log::warn!("skipping the stored plug-in {}: {e}", path.display());
|
||||
// A grant this load removed for an earlier file with the id goes back. When
|
||||
// it can't be written back, the module isn't installed: the store doesn't
|
||||
// grant it, so it wouldn't load at the next launch either.
|
||||
if back.is_some() {
|
||||
if !self.store_grant_in(turn, &m.id, Some(g.clone())) {
|
||||
log::warn!("skipping the stored plug-in {}: couldn't put back its grant", path.display());
|
||||
continue;
|
||||
}
|
||||
load.retired.remove(&m.id);
|
||||
written.insert(m.id.clone(), true);
|
||||
grants.insert(m.id.clone(), g.clone());
|
||||
}
|
||||
let id = m.id.clone();
|
||||
let token = GrantToken::from_engine_grants_file(g.clone());
|
||||
// The storage is made before the plug-ins are held: making it reads the store.
|
||||
let storage = plugin_storage(Some(&dir), &id, turn);
|
||||
let attach = || vectorcraft_plugins::registry::set_storage(&id, storage);
|
||||
// The id is checked for a change elsewhere again while the plug-ins are held.
|
||||
let installed = match vectorcraft_plugins::registry::install_for_load(
|
||||
plugin.with_source(path.display().to_string()),
|
||||
&load.changes,
|
||||
Some(token),
|
||||
attach,
|
||||
) {
|
||||
Ok(Some(p)) => {
|
||||
load.changes.installed(&p);
|
||||
true
|
||||
}
|
||||
Ok(None) => {
|
||||
log::warn!("skipping the stored plug-in {}: {}", path.display(), vectorcraft_plugins::registry::SUPERSEDED);
|
||||
false
|
||||
}
|
||||
Err(e) => {
|
||||
log::warn!("skipping the stored plug-in {}: {e}", path.display());
|
||||
false
|
||||
}
|
||||
};
|
||||
// A grant put back for a module that didn't install is removed again, so the
|
||||
// store doesn't grant those bytes at the next launch.
|
||||
if back.is_some() && !installed {
|
||||
if self.store_grant_in(turn, &id, None) {
|
||||
written.insert(id.clone(), false);
|
||||
grants.remove(&id);
|
||||
load.retired.insert(id, g);
|
||||
} else {
|
||||
log::warn!("couldn't remove the grant put back for the stored plug-in {}", path.display());
|
||||
}
|
||||
}
|
||||
}
|
||||
None => {
|
||||
@@ -525,29 +915,213 @@ impl Session {
|
||||
}
|
||||
}
|
||||
Ok(plugin) => {
|
||||
asks_nothing.insert(plugin.id().to_string());
|
||||
vectorcraft_plugins::registry::set_storage(plugin.id(), plugin_storage(Some(&dir), plugin.id(), turn));
|
||||
if let Err(e) = vectorcraft_plugins::registry::install(plugin.with_source(path.display().to_string())) {
|
||||
log::warn!("skipping the stored plug-in {}: {e}", path.display());
|
||||
let id = plugin.id().to_string();
|
||||
// The storage is made before the plug-ins are held: making it reads the store.
|
||||
let storage = plugin_storage(Some(&dir), &id, turn);
|
||||
let attach = || vectorcraft_plugins::registry::set_storage(&id, storage);
|
||||
// The id is checked for a change elsewhere again while the plug-ins are held.
|
||||
let p = match vectorcraft_plugins::registry::install_for_load(
|
||||
plugin.with_source(path.display().to_string()),
|
||||
&load.changes,
|
||||
None,
|
||||
attach,
|
||||
) {
|
||||
Ok(Some(p)) => p,
|
||||
Ok(None) => {
|
||||
log::warn!("skipping the stored plug-in {}: {}", path.display(), vectorcraft_plugins::registry::SUPERSEDED);
|
||||
continue;
|
||||
}
|
||||
Err(e) => {
|
||||
log::warn!("skipping the stored plug-in {}: {e}", path.display());
|
||||
continue;
|
||||
}
|
||||
};
|
||||
load.changes.installed(&p);
|
||||
// In the same turn: the grants for the id stop counting, the process's and the
|
||||
// store's, so no session sees the earlier module as approved. A module installed
|
||||
// in its place meanwhile keeps the process's grant recorded for it.
|
||||
vectorcraft_plugins::registry::revoke_if_installed(&id, p.serial());
|
||||
if let Some(g) = grants.remove(&id) {
|
||||
load.retired.insert(id.clone(), g);
|
||||
}
|
||||
if named(&written, &id) {
|
||||
let writes = self.grant_writes();
|
||||
if self.store_grant_in(turn, &id, None) {
|
||||
written.insert(id.clone(), false);
|
||||
} else if self.holds_plugin_grant(&id) {
|
||||
self.ignore_stored_grant(&id, writes);
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => log::warn!("skipping the stored plug-in {}: {e}", path.display()),
|
||||
}
|
||||
}
|
||||
let kept = read_grants(&dir);
|
||||
for id in &asks_nothing {
|
||||
vectorcraft_plugins::registry::revoke(id);
|
||||
let named = match &kept {
|
||||
Ok(file) => file.names(id),
|
||||
Err(e) => e.unread,
|
||||
}
|
||||
|
||||
/// Whether the loads of the stored plug-ins and of the Additional Plug-ins Folder go on after
|
||||
/// the call that starts them ([`Session::attach_plugin_store`], [`Session::load_stored_plugins`],
|
||||
/// preferences that set the folder): the app turns it on for its launch so that its window
|
||||
/// shows while they load, installs what loaded with [`Session::poll_plugin_loads`] as its
|
||||
/// frames go by, and turns it off once the launch's loads have started. Off (the default),
|
||||
/// those calls return once what loaded is installed, the loads still running from before
|
||||
/// included.
|
||||
pub fn load_plugins_in_background(&mut self, on: bool) {
|
||||
self.plugin_loads_in_background = on;
|
||||
}
|
||||
|
||||
/// Installs what the plug-in loads have loaded so far, in the order the loads started and each
|
||||
/// load's file-name order, up to the first module still loading, without waiting → whether
|
||||
/// some are still loading. A load starts once the loads before it are done. When another
|
||||
/// session or process is changing the plug-ins or the store, nothing installs until a later
|
||||
/// call.
|
||||
pub fn poll_plugin_loads(&mut self) -> bool {
|
||||
while let Some(mut next) = self.plugin_loads.pop_front() {
|
||||
next.start();
|
||||
if !next.ready() {
|
||||
self.plugin_loads.push_front(next);
|
||||
return true;
|
||||
}
|
||||
let Some((held, turn)) = self.plugin_install_turn_now(next.creates_store()) else {
|
||||
self.plugin_loads.push_front(next);
|
||||
return true;
|
||||
};
|
||||
if named {
|
||||
let writes = self.grant_writes();
|
||||
if !self.store_grant_in(turn, id, None) && self.holds_plugin_grant(id) {
|
||||
self.ignore_stored_grant(id, writes);
|
||||
self.install_plugin_load(&mut next, &turn);
|
||||
if !next.done() {
|
||||
self.plugin_loads.push_front(next);
|
||||
return true;
|
||||
}
|
||||
self.end_plugin_load(next, &turn);
|
||||
drop((turn, held));
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Waits for every plug-in load still running and installs what they loaded, in the order the
|
||||
/// loads started. Plug-in commands, and commands that may edit, call it first
|
||||
/// ([`Session::execute`]).
|
||||
pub fn finish_plugin_loads(&mut self) {
|
||||
while let Some(next) = self.plugin_loads.pop_front() {
|
||||
self.finish_plugin_load(next);
|
||||
}
|
||||
}
|
||||
|
||||
/// Ends the plug-in loads still running without installing more of what they load: the app
|
||||
/// calls it as it quits. Modules not started are dropped, and the ones running are given until
|
||||
/// their deadline, so the launch marker is not left naming a plug-in that was loading. Each load
|
||||
/// then ends as one that finished does for what it installed; a folder's end saves the disabled
|
||||
/// list only when the store's turn can be taken without waiting.
|
||||
pub fn cancel_plugin_loads(&mut self) {
|
||||
while let Some(mut load) = self.plugin_loads.pop_front() {
|
||||
load.cancel();
|
||||
// A stored load's grants were settled as each module installed: its end writes nothing.
|
||||
if !load.creates_store() {
|
||||
self.end_plugin_load(load, &StoreTurn::unheld());
|
||||
continue;
|
||||
}
|
||||
// Another session changing the plug-ins isn't waited for either: the folder's load then
|
||||
// ends without the store's turn, so the grants of what it installed are still forgotten
|
||||
// and the store isn't written.
|
||||
let Some(held) = crate::cmd::plugin::try_hold_plugin_changes() else {
|
||||
self.end_plugin_load(load, &StoreTurn::unheld());
|
||||
continue;
|
||||
};
|
||||
// A store another window or process is using isn't waited for: the turn then isn't
|
||||
// held, and the folder's end writes nothing to the store.
|
||||
let turn = match self.plugin_dir.as_deref().map(try_lock_store) {
|
||||
Some(Ok(Some(file))) => StoreTurn { lock: Some(file) },
|
||||
_ => StoreTurn::unheld(),
|
||||
};
|
||||
self.end_plugin_load(load, &turn);
|
||||
drop((turn, held));
|
||||
}
|
||||
}
|
||||
|
||||
/// Waits for `load`'s modules and installs them as they load, in turns on the store, then
|
||||
/// ends it → its report (a folder's; `null` for the stored plug-ins).
|
||||
pub(crate) fn finish_plugin_load(&mut self, mut load: PluginLoad) -> Value {
|
||||
load.start();
|
||||
loop {
|
||||
load.wait();
|
||||
let held = crate::cmd::plugin::hold_plugin_changes();
|
||||
let turn = self.plugin_install_turn(load.creates_store());
|
||||
self.install_plugin_load(&mut load, &turn);
|
||||
if load.done() {
|
||||
let report = self.end_plugin_load(load, &turn);
|
||||
drop((turn, held));
|
||||
return report;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A turn on the store for installing what a load loaded, taken after
|
||||
/// [`crate::cmd::plugin::hold_plugin_changes`]: the folder's own turn
|
||||
/// ([`Session::plugin_store_turn`]) when `create`, else one that goes ahead without a store
|
||||
/// folder ([`Session::plugin_store_turn_for_load`]). One that can't be locked goes ahead
|
||||
/// unheld.
|
||||
fn plugin_install_turn(&self, create: bool) -> StoreTurn {
|
||||
if create { self.plugin_store_turn().unwrap_or_else(|_| StoreTurn::unheld()) } else { self.plugin_store_turn_for_load() }
|
||||
}
|
||||
|
||||
/// [`crate::cmd::plugin::hold_plugin_changes`] and [`Session::plugin_install_turn`] without
|
||||
/// waiting: `None` while another session holds the one or another window or process the other.
|
||||
fn plugin_install_turn_now(&self, create: bool) -> Option<(MutexGuard<'static, ()>, StoreTurn)> {
|
||||
let held = crate::cmd::plugin::try_hold_plugin_changes()?;
|
||||
let turn = match self.plugin_dir.as_deref() {
|
||||
Some(dir) if create || dir.is_dir() => match try_lock_store(dir) {
|
||||
Ok(Some(file)) => StoreTurn { lock: Some(file) },
|
||||
Ok(None) => return None,
|
||||
Err(e) => {
|
||||
log::warn!("can't lock {}: {e}", dir.join(DISABLED_LOCK).display());
|
||||
StoreTurn::unheld()
|
||||
}
|
||||
},
|
||||
_ => StoreTurn::unheld(),
|
||||
};
|
||||
Some((held, turn))
|
||||
}
|
||||
|
||||
/// Whether plug-ins are still loading on worker threads ([`Session::load_plugins_in_background`]).
|
||||
pub fn plugins_loading(&self) -> bool {
|
||||
!self.plugin_loads.is_empty()
|
||||
}
|
||||
|
||||
/// Keeps `load` to install after the loads started before it; without
|
||||
/// [`Session::load_plugins_in_background`], waits for them all and installs what they loaded.
|
||||
pub(crate) fn queue_plugin_load(&mut self, load: PluginLoad) {
|
||||
self.plugin_loads.push_back(load);
|
||||
// The first load starts now; one queued after it starts once those before it are done.
|
||||
if let [only] = self.plugin_loads.make_contiguous() {
|
||||
only.start();
|
||||
}
|
||||
if !self.plugin_loads_in_background {
|
||||
self.finish_plugin_loads();
|
||||
}
|
||||
}
|
||||
|
||||
/// Installs what `load` has loaded so far, without waiting, in `turn`.
|
||||
fn install_plugin_load(&mut self, load: &mut PluginLoad, turn: &StoreTurn) {
|
||||
match load {
|
||||
PluginLoad::Stored(load) => self.install_stored_plugins(load, turn),
|
||||
PluginLoad::Folder(load) => crate::cmd::plugin::install_folder(self, load, turn),
|
||||
}
|
||||
}
|
||||
|
||||
/// Ends `load` once [`PluginLoad::done`], in `turn` → its report (a folder's).
|
||||
fn end_plugin_load(&mut self, load: PluginLoad, turn: &StoreTurn) -> Value {
|
||||
// The loads queued after it count what it installed as their own: one of theirs replaces
|
||||
// it, as it would have with the loads run one after the other.
|
||||
if let Some(ended) = load.changes() {
|
||||
for later in &mut self.plugin_loads {
|
||||
if let Some(changes) = later.changes_mut() {
|
||||
changes.adopt(ended);
|
||||
}
|
||||
}
|
||||
}
|
||||
match load {
|
||||
// A stored load's grants were settled as each module installed.
|
||||
PluginLoad::Stored(_) => Value::Null,
|
||||
PluginLoad::Folder(load) => crate::cmd::plugin::end_folder(self, load, turn),
|
||||
}
|
||||
}
|
||||
|
||||
/// Take a turn on the attached plug-in store ([`StoreTurn`]), waiting while another window or
|
||||
@@ -659,8 +1233,17 @@ impl Session {
|
||||
/// doesn't count for that folder ([`Session::ignore_stored_grant`]). The folder's key is worked
|
||||
/// out on each call, so a path whose link now leads elsewhere is matched with where it leads.
|
||||
fn counted_grants(&self, dir: &Path) -> BTreeMap<String, vectorcraft_plugins::permissions::Grant> {
|
||||
self.counted(dir, stored_grants(dir))
|
||||
}
|
||||
|
||||
/// `grants`, read from the plug-in store `dir`, without those the process doesn't count for
|
||||
/// that folder ([`Session::counted_grants`]).
|
||||
fn counted(
|
||||
&self,
|
||||
dir: &Path,
|
||||
mut grants: BTreeMap<String, vectorcraft_plugins::permissions::Grant>,
|
||||
) -> BTreeMap<String, vectorcraft_plugins::permissions::Grant> {
|
||||
let key = plugin_store_key(dir);
|
||||
let mut grants = stored_grants(dir);
|
||||
let shared = IGNORED_PLUGIN_GRANTS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
for (_, id) in shared.ignored.range((key.clone(), String::new())..).take_while(|(folder, _)| *folder == key) {
|
||||
grants.remove(id);
|
||||
|
||||
@@ -49,10 +49,12 @@ mod curvature_circle;
|
||||
mod cut;
|
||||
mod dashalign;
|
||||
mod dcs;
|
||||
mod delete_keeps_joined;
|
||||
mod distort;
|
||||
mod docsetup;
|
||||
mod document_close;
|
||||
mod document_move;
|
||||
mod double_click_adds_anchor;
|
||||
mod draw2;
|
||||
mod dynamic_symbols;
|
||||
mod dynamic_text;
|
||||
@@ -87,6 +89,7 @@ mod history_document;
|
||||
mod history_mem;
|
||||
mod ids_without_selection;
|
||||
mod inline;
|
||||
mod interaction_commands;
|
||||
mod interactivity;
|
||||
mod interpolate_handles;
|
||||
mod intertwine;
|
||||
@@ -123,6 +126,7 @@ mod outlineobject;
|
||||
pub(super) mod outlinestroke;
|
||||
mod overprint;
|
||||
mod package;
|
||||
mod paintopacity;
|
||||
mod paintproxy;
|
||||
mod panelcmds;
|
||||
mod paragraphs;
|
||||
@@ -178,6 +182,7 @@ mod script_include;
|
||||
mod script_io;
|
||||
mod script_run;
|
||||
mod scripts;
|
||||
mod segment_nudge;
|
||||
mod select_effects;
|
||||
mod select_ids_first;
|
||||
mod shaper;
|
||||
|
||||
@@ -145,6 +145,23 @@ fn item_rows_follow_remove_and_move() {
|
||||
assert_eq!(s.appearance_item(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moving_a_single_row_keeps_the_active_objects_landing() {
|
||||
let mut s = session();
|
||||
let short = rect(&mut s, 50.0);
|
||||
let long = rect(&mut s, 200.0);
|
||||
run(&mut s, "appearance.addFill", json!({}));
|
||||
run(&mut s, "select.set", json!({"ids": [short.0, long.0]}));
|
||||
run(&mut s, "appearance.setActiveItem", json!({"index": 0}));
|
||||
|
||||
let moved = run(&mut s, "appearance.moveItem", json!({"ids": [short.0, long.0], "from": 0, "to": 2}));
|
||||
|
||||
assert_eq!(moved["index"], 2, "the command still reports the last target's landing");
|
||||
assert!(matches!(node(&s, short).appearance.items[1], AppearanceItem::Fill(_)));
|
||||
assert!(matches!(node(&s, long).appearance.items[0], AppearanceItem::Stroke(_)));
|
||||
assert_eq!(s.appearance_item(), Some(1), "the active row follows its own object's landing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transparency_goes_to_the_targeted_item() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -1357,7 +1357,10 @@ fn brush_freehand_refuses_unknown_keys() {
|
||||
let spec = crate::cmd::find_command("brush.freehand").unwrap();
|
||||
let mut keys = crate::cmd::params::accepted_keys(spec.params).expect("the description names every key");
|
||||
keys.sort_unstable();
|
||||
assert_eq!(keys, ["brush", "closed", "connect", "extend", "fidelity", "fill", "fit", "keepSelected", "points", "redraw", "style"]);
|
||||
assert_eq!(
|
||||
keys,
|
||||
["brush", "closed", "connect", "extend", "fidelity", "fill", "fit", "keepSelected", "leaveSelection", "points", "redraw", "style"]
|
||||
);
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
select(&mut s, &[a]);
|
||||
|
||||
@@ -776,6 +776,15 @@ fn overprint_black_and_print_fixes_reach_a_colorized_images_color() {
|
||||
let v = s.execute("addon.color.printFixes", &json!({"removeWhiteOverprint": true})).unwrap();
|
||||
assert_eq!(v["whiteOverprintRemoved"], 1, "{v}");
|
||||
assert!(!overprints(&s), "white knocks out again");
|
||||
// A white spot ink is an ink: Remove White Overprint leaves its overprint.
|
||||
s.execute("swatch.new", &json!({"name": "Opaque White", "color": {"c": 0, "m": 0, "y": 0, "k": 0}, "spot": true})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"swatch": "Opaque White"})).unwrap();
|
||||
s.execute("object.setOverprint", &json!({"fill": true})).unwrap();
|
||||
assert!(overprints(&s), "the spot white overprints");
|
||||
let v = s.execute("addon.color.printFixes", &json!({"removeWhiteOverprint": true})).unwrap();
|
||||
assert_eq!(v["whiteOverprintRemoved"], 0, "{v}");
|
||||
assert!(overprints(&s), "the spot white keeps overprinting");
|
||||
}
|
||||
|
||||
/// A flattening for a file that writes colorized images in their ink (EPS) keeps the image, and
|
||||
|
||||
@@ -0,0 +1,227 @@
|
||||
//! General › Delete Removes Anchor Points and Keeps Paths Joined (`deleteKeepsPathsJoined`). With
|
||||
//! it on, Delete (`edit.clear`) removes the direct-selected anchors of a path as Remove Anchor
|
||||
//! Points does, without opening the path. Off (the default), Delete removes them with their
|
||||
//! segments.
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_geom::{PathData, Point};
|
||||
|
||||
use super::history;
|
||||
use crate::*;
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn keep_joined(s: &mut Session, on: bool) {
|
||||
s.execute("prefs.set", &json!({"key": "deleteKeepsPathsJoined", "value": on})).unwrap();
|
||||
}
|
||||
|
||||
fn path_of(s: &Session, id: NodeId) -> Option<PathData> {
|
||||
s.doc().unwrap().doc.node(id).and_then(|n| n.path_data().cloned())
|
||||
}
|
||||
|
||||
fn points(s: &Session, id: NodeId) -> Vec<Point> {
|
||||
path_of(s, id).unwrap().subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p)).collect()
|
||||
}
|
||||
|
||||
fn create(s: &mut Session, anchors: serde_json::Value, closed: bool) -> NodeId {
|
||||
NodeId(s.execute("path.create", &json!({ "anchors": anchors, "closed": closed })).unwrap()["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
fn square(s: &mut Session, x: f64) -> NodeId {
|
||||
create(s, json!([{"x": x, "y": 100}, {"x": x + 100.0, "y": 100}, {"x": x + 100.0, "y": 200}, {"x": x, "y": 200}]), true)
|
||||
}
|
||||
|
||||
fn line(s: &mut Session, y: f64) -> NodeId {
|
||||
create(s, json!([{"x": 100, "y": y}, {"x": 150, "y": y - 20.0}, {"x": 200, "y": y}, {"x": 250, "y": y + 20.0}, {"x": 300, "y": y}]), false)
|
||||
}
|
||||
|
||||
fn select(s: &mut Session, id: NodeId, anchors: serde_json::Value, mode: &str) {
|
||||
s.execute("select.anchors", &json!({"id": id.0, "anchors": anchors, "mode": mode})).unwrap();
|
||||
}
|
||||
|
||||
fn objects(s: &Session) -> usize {
|
||||
s.doc().unwrap().doc.layers.iter().map(|l| l.children().map_or(0, |c| c.len())).sum()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn off_by_default_delete_opens_a_closed_path() {
|
||||
let mut s = session();
|
||||
assert!(!s.prefs.delete_keeps_paths_joined);
|
||||
let id = square(&mut s, 100.0);
|
||||
select(&mut s, id, json!([[0, 1]]), "set");
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
let path = path_of(&s, id).unwrap();
|
||||
assert!(!path.subpaths[0].closed, "the path opens where the anchor was");
|
||||
assert_eq!(path.subpaths[0].anchors.len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_the_preference_on_delete_keeps_a_closed_path_closed_and_selects_the_next_anchor() {
|
||||
let mut s = session();
|
||||
keep_joined(&mut s, true);
|
||||
let id = square(&mut s, 100.0);
|
||||
select(&mut s, id, json!([[0, 1]]), "set");
|
||||
let before = history(&s).0;
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
assert_eq!(history(&s).0, before + 1, "one undo step");
|
||||
let path = path_of(&s, id).unwrap();
|
||||
assert_eq!(path.subpaths.len(), 1);
|
||||
assert!(path.subpaths[0].closed, "the path stays closed");
|
||||
assert!(!points(&s, id).contains(&Point::new(200.0, 100.0)), "the selected anchor is gone");
|
||||
let st = s.doc().unwrap();
|
||||
assert_eq!(st.selection.objects, vec![id], "the path stays selected");
|
||||
assert_eq!(st.selection.anchors[&id], [(0, 1)].into(), "the anchor after the removed one is selected");
|
||||
// A second Delete goes on along the path.
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
assert_eq!(points(&s, id), vec![Point::new(100.0, 100.0), Point::new(100.0, 200.0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_open_path_loses_an_end_anchor_and_an_interior_anchor_without_splitting() {
|
||||
let mut s = session();
|
||||
keep_joined(&mut s, true);
|
||||
let id = line(&mut s, 300.0);
|
||||
select(&mut s, id, json!([[0, 0], [0, 2]]), "set");
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
let path = path_of(&s, id).unwrap();
|
||||
assert_eq!(path.subpaths.len(), 1, "one piece");
|
||||
assert!(!path.subpaths[0].closed);
|
||||
assert_eq!(
|
||||
points(&s, id),
|
||||
vec![Point::new(150.0, 280.0), Point::new(250.0, 320.0), Point::new(300.0, 300.0)],
|
||||
"the path is shorter at its start"
|
||||
);
|
||||
assert_eq!(objects(&s), 1, "no new object");
|
||||
assert_eq!(s.doc().unwrap().selection.anchors[&id], [(0, 1)].into(), "the anchor after the last removed one is selected");
|
||||
// Removing the last anchor of an open path selects the one before it.
|
||||
select(&mut s, id, json!([[0, 2]]), "set");
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
assert_eq!(points(&s, id), vec![Point::new(150.0, 280.0), Point::new(250.0, 320.0)], "the path is shorter at its end");
|
||||
assert_eq!(s.doc().unwrap().selection.anchors[&id], [(0, 1)].into(), "the new end anchor is selected");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_subpath_left_with_one_anchor_goes_and_the_path_stays_selected_whole() {
|
||||
let mut s = session();
|
||||
keep_joined(&mut s, true);
|
||||
let id = square(&mut s, 100.0);
|
||||
let sq = json!({"closed": true, "anchors": [{"x": 100, "y": 100}, {"x": 200, "y": 100}, {"x": 200, "y": 200}, {"x": 100, "y": 200}]});
|
||||
let pair = json!({"closed": false, "anchors": [{"x": 300, "y": 100}, {"x": 400, "y": 100}]});
|
||||
s.execute("path.setAnchors", &json!({"id": id.0, "subpaths": [sq, pair]})).unwrap();
|
||||
select(&mut s, id, json!([[1, 0]]), "set");
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
let path = path_of(&s, id).unwrap();
|
||||
assert_eq!(path.subpaths.len(), 1, "the subpath left with one anchor goes");
|
||||
assert!(path.subpaths[0].closed && path.subpaths[0].anchors.len() == 4, "the other subpath is untouched");
|
||||
let st = s.doc().unwrap();
|
||||
assert_eq!(st.selection.objects, vec![id], "the path stays selected");
|
||||
assert!(st.selection.anchors.get(&id).is_none_or(|a| a.is_empty()), "no anchor is left to go on from");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_path_left_with_fewer_than_two_anchors_is_deleted() {
|
||||
let mut s = session();
|
||||
keep_joined(&mut s, true);
|
||||
let id = create(&mut s, json!([{"x": 100, "y": 100}, {"x": 200, "y": 100}]), false);
|
||||
let other = square(&mut s, 400.0);
|
||||
select(&mut s, id, json!([[0, 1]]), "set");
|
||||
select(&mut s, other, json!([[0, 0]]), "add");
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
assert!(path_of(&s, id).is_none(), "a single anchor is no path");
|
||||
assert!(path_of(&s, other).unwrap().subpaths[0].closed, "the other path keeps its other anchors joined");
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![other]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn several_paths_and_an_object_selected_whole_change_in_one_undo_step() {
|
||||
let mut s = session();
|
||||
keep_joined(&mut s, true);
|
||||
let (a, b, whole) = (square(&mut s, 100.0), line(&mut s, 400.0), square(&mut s, 500.0));
|
||||
select(&mut s, a, json!([[0, 0]]), "set");
|
||||
select(&mut s, b, json!([[0, 1], [0, 3]]), "add");
|
||||
s.execute("select.add", &json!({"ids": [whole.0]})).unwrap();
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
let before = history(&s).0;
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
assert_eq!(history(&s).0, before + 1, "one undo step");
|
||||
assert!(path_of(&s, whole).is_none(), "the object selected whole is deleted");
|
||||
assert!(path_of(&s, a).unwrap().subpaths[0].closed);
|
||||
assert_eq!(path_of(&s, a).unwrap().subpaths[0].anchors.len(), 3);
|
||||
assert_eq!(points(&s, b), vec![Point::new(100.0, 400.0), Point::new(200.0, 400.0), Point::new(300.0, 400.0)]);
|
||||
let st = s.doc().unwrap();
|
||||
assert!(st.selection.anchors.contains_key(&a) && st.selection.anchors.contains_key(&b), "both paths keep an anchor selected");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc, doc, "Undo restores every path");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_compound_path_keeps_its_members_and_loses_one_left_with_no_segment() {
|
||||
let mut s = session();
|
||||
keep_joined(&mut s, true);
|
||||
let (outer, inner) = (square(&mut s, 100.0), create(&mut s, json!([{"x": 130, "y": 150}, {"x": 170, "y": 150}]), false));
|
||||
s.execute("select.set", &json!({"ids": [outer.0, inner.0]})).unwrap();
|
||||
let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
select(&mut s, outer, json!([[0, 2]]), "set");
|
||||
select(&mut s, inner, json!([[0, 0]]), "add");
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(d.node(inner).is_none(), "the member left with one anchor goes");
|
||||
assert_eq!(d.parent_of(outer), Some(compound), "the other member stays in the compound path");
|
||||
assert!(path_of(&s, outer).unwrap().subpaths[0].closed);
|
||||
assert_eq!(path_of(&s, outer).unwrap().subpaths[0].anchors.len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selected_segment_is_still_cut() {
|
||||
let mut s = session();
|
||||
keep_joined(&mut s, true);
|
||||
let id = square(&mut s, 100.0);
|
||||
s.execute("select.segments", &json!({"id": id.0, "segments": [[0, 0]]})).unwrap();
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
let path = path_of(&s, id).unwrap();
|
||||
assert!(!path.subpaths[0].closed, "the segment's connection is removed");
|
||||
assert_eq!(path.subpaths[0].anchors.len(), 4, "every anchor stays");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_keep_joined_param_overrides_the_preference_and_must_be_a_boolean() {
|
||||
let mut s = session();
|
||||
let id = square(&mut s, 100.0);
|
||||
select(&mut s, id, json!([[0, 1]]), "set");
|
||||
assert!(s.execute("edit.clear", &json!({"keepJoined": "yes"})).is_err());
|
||||
assert_eq!(path_of(&s, id).unwrap().subpaths[0].anchors.len(), 4, "a refused call changes nothing");
|
||||
s.execute("edit.clear", &json!({"keepJoined": true})).unwrap();
|
||||
assert!(path_of(&s, id).unwrap().subpaths[0].closed);
|
||||
keep_joined(&mut s, true);
|
||||
s.execute("edit.clear", &json!({"keepJoined": false})).unwrap();
|
||||
assert!(!path_of(&s, id).unwrap().subpaths[0].closed, "false opens the path with the preference on");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_replay_removes_anchors_as_the_recorded_step_did() {
|
||||
let mut s = session();
|
||||
keep_joined(&mut s, true);
|
||||
let id = square(&mut s, 100.0);
|
||||
select(&mut s, id, json!([[0, 1]]), "set");
|
||||
let start = s.journal.len();
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
let removed = path_of(&s, id);
|
||||
assert!(removed.as_ref().is_some_and(|p| p.subpaths[0].closed), "the path stays closed");
|
||||
let (cmd, params) = s.journal.since(start).last().cloned().unwrap();
|
||||
assert_eq!(params["keepJoined"], json!(true), "{cmd}: journaled");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
keep_joined(&mut s, false);
|
||||
select(&mut s, id, json!([[0, 1]]), "set");
|
||||
s.replay(&cmd, ¶ms).unwrap();
|
||||
assert_eq!(path_of(&s, id), removed);
|
||||
// A step saved before the preference existed has no `keepJoined` and still opens the path.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
keep_joined(&mut s, true);
|
||||
select(&mut s, id, json!([[0, 1]]), "set");
|
||||
s.replay("edit.clear", &json!({})).unwrap();
|
||||
assert!(!path_of(&s, id).unwrap().subpaths[0].closed);
|
||||
}
|
||||
@@ -482,6 +482,13 @@ fn discard_white_overprint_keeps_white_overprints_in_overprint_preview() {
|
||||
s.execute("document.setup", &json!({"discardWhiteOverprint": false})).unwrap();
|
||||
let [r, g, b, _] = centre(&s);
|
||||
assert!(r > 200 && g < 60 && b < 60, "a white overprint vanishes: {:?}", [r, g, b]);
|
||||
// A white spot ink is an ink: it overprints with the option on too.
|
||||
s.execute("document.setup", &json!({"discardWhiteOverprint": true})).unwrap();
|
||||
s.execute("swatch.new", &json!({"name": "Opaque White", "color": {"c": 0, "m": 0, "y": 0, "k": 0}, "spot": true})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [white]})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"swatch": "Opaque White"})).unwrap();
|
||||
let [r, g, b, _] = centre(&s);
|
||||
assert!(r > 200 && g < 60 && b < 60, "the spot white overprints: {:?}", [r, g, b]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
//! General › Double-Click Adds Anchor Points (`doubleClickAddsAnchorPoints`). With it on, a
|
||||
//! Direct Selection double-click on a path segment adds an anchor there. Off (the default), the
|
||||
//! double-click adds nothing.
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_geom::kurbo::ParamCurveNearest;
|
||||
use vectorcraft_geom::{ParamCurve, PathData, Point};
|
||||
use vectorcraft_tools::{PointerEvent, PointerKind};
|
||||
|
||||
use super::history;
|
||||
use crate::*;
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn set_pref(s: &mut Session, key: &str, on: bool) {
|
||||
s.execute("prefs.set", &json!({"key": key, "value": on})).unwrap();
|
||||
}
|
||||
|
||||
fn path_of(s: &Session, id: NodeId) -> Option<PathData> {
|
||||
s.doc().unwrap().doc.node(id).and_then(|n| n.path_data().cloned())
|
||||
}
|
||||
|
||||
fn points(s: &Session, id: NodeId) -> Vec<Point> {
|
||||
path_of(s, id).unwrap().subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p)).collect()
|
||||
}
|
||||
|
||||
/// Two clicks and the double-click that follows them, with Direct Selection, at `at`. On a segment
|
||||
/// the clicks select it, so the double-click finds its path selected.
|
||||
fn double_click(s: &mut Session, at: Point) {
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool("directSelection", v).unwrap();
|
||||
for kind in [PointerKind::Down, PointerKind::Up, PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick] {
|
||||
s.pointer(&PointerEvent::new(kind, at.x, at.y), v).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
/// An open curve from (100, 300) to (300, 300) whose middle, at t = 0.5, is (200, 225).
|
||||
fn arch(s: &mut Session) -> NodeId {
|
||||
let anchors = json!([{"x": 100, "y": 300, "out": [100, 200]}, {"x": 300, "y": 300, "in": [300, 200]}]);
|
||||
NodeId(s.execute("path.create", &json!({ "anchors": anchors, "closed": false })).unwrap()["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn off_by_default() {
|
||||
let s = session();
|
||||
assert!(!s.prefs.double_click_adds_anchor_points);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_the_preference_on_a_double_click_on_a_segment_adds_an_anchor_in_one_undo_step() {
|
||||
// The clicks before the double-click select the segment either way; an unselected path at the
|
||||
// double-click is covered by the tools crate's tests.
|
||||
for selected in [true, false] {
|
||||
let mut s = session();
|
||||
set_pref(&mut s, "doubleClickAddsAnchorPoints", true);
|
||||
let id = arch(&mut s);
|
||||
if !selected {
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
}
|
||||
let curve = path_of(&s, id).unwrap().subpaths[0].segment(0);
|
||||
let before = history(&s).0;
|
||||
double_click(&mut s, Point::new(200.0, 225.0));
|
||||
assert_eq!(history(&s).0, before + 1, "one undo step (selected before the clicks: {selected})");
|
||||
assert_eq!(points(&s, id).len(), 3, "an anchor is added (selected before the clicks: {selected})");
|
||||
assert!(points(&s, id)[1].distance(Point::new(200.0, 225.0)) < 0.5, "at the clicked point: {:?}", points(&s, id));
|
||||
let halves = path_of(&s, id).unwrap().subpaths[0].clone();
|
||||
for seg in 0..2 {
|
||||
for t in [0.25, 0.5, 0.75] {
|
||||
let q = ParamCurve::eval(&halves.segment(seg), t);
|
||||
let d = ParamCurveNearest::nearest(&curve, q, 1e-9).distance_sq;
|
||||
assert!(d < 1e-6, "the curve keeps its shape at {q:?}");
|
||||
}
|
||||
}
|
||||
let st = s.doc().unwrap();
|
||||
assert_eq!(st.selection.objects, vec![id]);
|
||||
assert_eq!(st.selection.anchors.get(&id), Some(&[(0, 1)].into()), "only the new anchor is selected (selected before the clicks: {selected})");
|
||||
assert!(st.selection.segments.get(&id).is_none_or(|s| s.is_empty()), "no segment stays selected");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(points(&s, id).len(), 2, "undo removes it");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_the_preference_off_a_double_click_on_a_segment_adds_nothing() {
|
||||
let mut s = session();
|
||||
let id = arch(&mut s);
|
||||
let before = history(&s).0;
|
||||
double_click(&mut s, Point::new(200.0, 225.0));
|
||||
assert_eq!(history(&s).0, before);
|
||||
assert_eq!(points(&s, id).len(), 2);
|
||||
}
|
||||
|
||||
/// The two General preferences are separate: Delete Removes Anchor Points and Keeps Paths Joined
|
||||
/// does not turn on the double-click, and the double-click preference does not change Delete.
|
||||
#[test]
|
||||
fn the_double_click_and_delete_preferences_are_separate() {
|
||||
let mut s = session();
|
||||
set_pref(&mut s, "deleteKeepsPathsJoined", true);
|
||||
let id = arch(&mut s);
|
||||
let before = history(&s).0;
|
||||
double_click(&mut s, Point::new(200.0, 225.0));
|
||||
assert_eq!(history(&s).0, before, "deleteKeepsPathsJoined alone adds no anchor");
|
||||
assert_eq!(points(&s, id).len(), 2);
|
||||
|
||||
let mut s = session();
|
||||
set_pref(&mut s, "doubleClickAddsAnchorPoints", true);
|
||||
let anchors = json!([{"x": 100, "y": 100}, {"x": 200, "y": 100}, {"x": 200, "y": 200}, {"x": 100, "y": 200}]);
|
||||
let id = NodeId(s.execute("path.create", &json!({ "anchors": anchors, "closed": true })).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 1]], "mode": "set"})).unwrap();
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
assert!(!path_of(&s, id).unwrap().subpaths[0].closed, "Delete still opens the path");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_select_anchor_param_must_be_a_boolean() {
|
||||
let mut s = session();
|
||||
let id = arch(&mut s);
|
||||
assert!(s.execute("path.insertAnchor", &json!({"id": id.0, "segment": 0, "selectAnchor": "yes"})).is_err());
|
||||
assert_eq!(points(&s, id).len(), 2, "a refused call changes nothing");
|
||||
}
|
||||
@@ -198,6 +198,12 @@ fn near(a: Point, b: Point) -> bool {
|
||||
a.distance(b) < 1e-6
|
||||
}
|
||||
|
||||
/// Whether open subpath `sp`'s two ends are at `a` and `b`, in either order (within `tol`).
|
||||
fn ends_at(sp: &vectorcraft_geom::SubPath, a: Point, b: Point, tol: f64) -> bool {
|
||||
let (Some(f), Some(l)) = (sp.anchors.first(), sp.anchors.last()) else { return false };
|
||||
(f.p.distance(a) < tol && l.p.distance(b) < tol) || (f.p.distance(b) < tol && l.p.distance(a) < tol)
|
||||
}
|
||||
|
||||
fn area(pd: &PathData) -> f64 {
|
||||
vectorcraft_pathops::area(pd, FillRule::NonZero)
|
||||
}
|
||||
@@ -519,7 +525,8 @@ fn pencil_redraws_the_section_of_a_selected_path_between_its_ends() {
|
||||
}
|
||||
|
||||
/// On a closed path the stroke replaces the shorter way between where it starts and ends, and the
|
||||
/// path stays closed; a stroke that doesn't end on the path draws a new one.
|
||||
/// path stays closed; a stroke that doesn't end on the path opens it where the stroke starts and
|
||||
/// ends where the stroke does (no new path).
|
||||
#[test]
|
||||
fn pencil_redraws_the_shorter_way_round_a_closed_path() {
|
||||
let mut s = session();
|
||||
@@ -536,11 +543,12 @@ fn pencil_redraws_the_shorter_way_round_a_closed_path() {
|
||||
}
|
||||
let top = kurbo::Shape::bounding_box(&path(&s, id).to_bezpath()).y0;
|
||||
assert!(top < -20.0, "the dip: top {top}");
|
||||
// Not ending on the path: a new path, the rectangle as it was.
|
||||
let before = path(&s, id);
|
||||
// Not ending on the path: the rectangle opens at (50, 100) and follows the stroke out.
|
||||
s.execute("path.freehand", &json!({"points": [[50, 100], [80, 150], [120, 160]], "redraw": {"id": id.0, "within": 4}})).unwrap();
|
||||
assert_eq!(paths(&s).len(), 2);
|
||||
assert_eq!(path(&s, id), before);
|
||||
assert_eq!(paths(&s).len(), 1, "no new path");
|
||||
let sp = &path(&s, id).subpaths[0];
|
||||
assert!(!sp.closed, "the rectangle opened");
|
||||
assert!(ends_at(sp, Point::new(50.0, 100.0), Point::new(120.0, 160.0), 1e-6), "from the opening to the stroke's end: {sp:?}");
|
||||
assert!(s.execute("path.freehand", &json!({"points": [[0, 0], [1, 1]], "redraw": {"id": id.0, "within": -1}})).is_err());
|
||||
}
|
||||
|
||||
@@ -4860,6 +4868,460 @@ fn cmd_alt_lends_group_selection_while_direct_selection_is_active() {
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 80.0, 80.0).with_mods(cmd_alt), v).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmd_lends_the_selection_tool_direct_selection_or_group_selection_chosen_last() {
|
||||
// Cmd held with the Selection tool: Direct Selection takes the press until the release, so a
|
||||
// Cmd-click picks one path inside a group where a plain click picks the group.
|
||||
let (none, cmd) = (Mods::default(), Mods { cmd: true, ..Mods::default() });
|
||||
let v = view();
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 100.0, 100.0, 100.0, 100.0);
|
||||
let b = rect(&mut s, 300.0, 100.0, 100.0, 100.0);
|
||||
let group = NodeId(s.execute("object.group", &json!({"ids": [a.0, b.0]})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.select_tool("selection", v).unwrap();
|
||||
assert_eq!(s.lent_tool_id(&none), None);
|
||||
assert_eq!(s.lent_tool_id(&cmd), Some("directSelection"));
|
||||
assert_eq!(s.shown_tool_id(&cmd), "directSelection");
|
||||
assert_eq!(s.shown_tool_id(&none), "selection");
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 150.0, 150.0).with_mods(cmd), v).unwrap();
|
||||
assert_eq!(s.tool_id(), "directSelection");
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 150.0, 150.0).with_mods(cmd), v).unwrap();
|
||||
assert_eq!(s.tool_id(), "selection");
|
||||
let picked = &s.active().unwrap().selection;
|
||||
assert!(picked.contains(a) && !picked.contains(group), "the Cmd-click picks the path, not its group");
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 150.0, 150.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 150.0, 150.0), v).unwrap();
|
||||
assert!(s.active().unwrap().selection.contains(group), "a plain click picks the group");
|
||||
// Cmd pressed once a drag is under way lends nothing: the pointer and the named tool stay.
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 600.0, 500.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 650.0, 550.0), v).unwrap();
|
||||
assert_eq!(s.cursor(Point::new(650.0, 550.0), cmd, v), s.cursor(Point::new(650.0, 550.0), none, v));
|
||||
assert_eq!(s.shown_tool_id(&cmd), "selection");
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 650.0, 550.0).with_mods(cmd), v).unwrap();
|
||||
assert_eq!(s.tool_id(), "selection");
|
||||
// Group Selection lends the Selection tool, and once chosen, is what the Selection tool borrows.
|
||||
s.select_tool("groupSelection", v).unwrap();
|
||||
assert_eq!(s.lent_tool_id(&cmd), Some("selection"));
|
||||
s.select_tool("selection", v).unwrap();
|
||||
assert_eq!(s.lent_tool_id(&cmd), Some("groupSelection"));
|
||||
s.select_tool("directSelection", v).unwrap();
|
||||
s.select_tool("selection", v).unwrap();
|
||||
assert_eq!(s.lent_tool_id(&cmd), Some("directSelection"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cmd_double_click_goes_to_the_tool_the_clicks_went_to() {
|
||||
// With the Selection tool, Cmd-clicks go to Direct Selection, and so does the double-click
|
||||
// after them: it does not isolate the group as the Selection tool's double-click would.
|
||||
let cmd = Mods { cmd: true, ..Mods::default() };
|
||||
let v = view();
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 100.0, 100.0, 100.0, 100.0);
|
||||
let b = rect(&mut s, 300.0, 100.0, 100.0, 100.0);
|
||||
s.execute("object.group", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.select_tool("selection", v).unwrap();
|
||||
for kind in [PointerKind::Down, PointerKind::Up, PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick] {
|
||||
s.pointer(&PointerEvent::new(kind, 150.0, 150.0).with_mods(cmd), v).unwrap();
|
||||
}
|
||||
assert_eq!(s.tool_id(), "selection");
|
||||
assert_eq!(s.doc().unwrap().isolation, None, "Direct Selection's double-click does not isolate the group");
|
||||
// With Group Selection chosen last, the second click selects the group, and the double-click
|
||||
// still goes to Group Selection, as both clicks did.
|
||||
s.select_tool("groupSelection", v).unwrap();
|
||||
s.select_tool("selection", v).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
for kind in [PointerKind::Down, PointerKind::Up, PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick] {
|
||||
s.pointer(&PointerEvent::new(kind, 150.0, 150.0).with_mods(cmd), v).unwrap();
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().isolation, None, "Group Selection's double-click does not isolate the group");
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
// A plain double-click is the Selection tool's: it isolates the group.
|
||||
for kind in [PointerKind::Down, PointerKind::Up, PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick] {
|
||||
s.pointer(&PointerEvent::new(kind, 150.0, 150.0), v).unwrap();
|
||||
}
|
||||
assert!(s.doc().unwrap().isolation.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cmd_double_click_after_a_tool_switch_goes_to_the_new_tool() {
|
||||
// With the Selection tool, a Cmd-click on type goes to Direct Selection, and so does the
|
||||
// Cmd double-click after it, which edits the type. Once another tool is chosen, the
|
||||
// double-click is that tool's: Group Selection's does not edit the type.
|
||||
let cmd = Mods { cmd: true, ..Mods::default() };
|
||||
let v = view();
|
||||
let mut s = session();
|
||||
let id = NodeId(s.execute("text.create", &json!({"x": 100, "y": 200, "size": 48, "text": "Type"})).unwrap()["id"].as_u64().unwrap());
|
||||
let c = s.doc().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap().center();
|
||||
let clicks = |s: &mut Session, then: Option<&str>| {
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.select_tool("selection", v).unwrap();
|
||||
for kind in [PointerKind::Down, PointerKind::Up] {
|
||||
s.pointer(&PointerEvent::new(kind, c.x, c.y).with_mods(cmd), v).unwrap();
|
||||
}
|
||||
if let Some(tool) = then {
|
||||
s.select_tool(tool, v).unwrap();
|
||||
}
|
||||
s.pointer(&PointerEvent::new(PointerKind::DoubleClick, c.x, c.y).with_mods(cmd), v).unwrap()
|
||||
};
|
||||
assert_eq!(clicks(&mut s, None), [UiRequest::SwitchTool("type".into())], "Direct Selection's double-click edits the type");
|
||||
assert_eq!(clicks(&mut s, Some("groupSelection")), [], "Group Selection's double-click does not");
|
||||
assert_eq!(s.tool_id(), "groupSelection");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cmd_double_click_after_switching_away_and_back_goes_to_the_active_tool() {
|
||||
// A Cmd-click with the Selection tool goes to Direct Selection. After a switch to another tool
|
||||
// and back to the Selection tool, or a fresh start of the tool (another view of the document),
|
||||
// the Cmd double-click is the Selection tool's: it isolates the group.
|
||||
let cmd = Mods { cmd: true, ..Mods::default() };
|
||||
let v = view();
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 100.0, 100.0, 100.0, 100.0);
|
||||
let b = rect(&mut s, 300.0, 100.0, 100.0, 100.0);
|
||||
s.execute("object.group", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
for reset in [false, true] {
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.select_tool("selection", v).unwrap();
|
||||
for kind in [PointerKind::Down, PointerKind::Up] {
|
||||
s.pointer(&PointerEvent::new(kind, 150.0, 150.0).with_mods(cmd), v).unwrap();
|
||||
}
|
||||
if reset {
|
||||
s.reset_tool();
|
||||
} else {
|
||||
s.select_tool("rectangle", v).unwrap();
|
||||
s.select_tool("selection", v).unwrap();
|
||||
}
|
||||
s.pointer(&PointerEvent::new(PointerKind::DoubleClick, 150.0, 150.0).with_mods(cmd), v).unwrap();
|
||||
assert_eq!(s.tool_id(), "selection");
|
||||
assert!(s.doc().unwrap().isolation.is_some(), "the Selection tool's double-click isolates the group (reset: {reset})");
|
||||
s.execute("object.exitIsolation", &json!({})).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cmd_press_on_a_selected_object_keeps_select_behind() {
|
||||
// Over a selected object, a Cmd-click with the Selection tool selects the object behind it;
|
||||
// with Select Behind off, Direct Selection takes the press there too.
|
||||
let cmd = Mods { cmd: true, ..Mods::default() };
|
||||
let v = view();
|
||||
let mut s = session();
|
||||
let back = rect(&mut s, 100.0, 100.0, 200.0, 200.0);
|
||||
let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0);
|
||||
s.select_tool("selection", v).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [front.0]})).unwrap();
|
||||
// The canvas shows the marks of the tool a press at the pointer takes, and the status bar and
|
||||
// the help bar name it.
|
||||
s.cursor(Point::new(200.0, 200.0), cmd, v);
|
||||
assert_eq!(s.hover_tool_id(&cmd), "selection");
|
||||
assert_eq!(s.shown_tool_id(&cmd), "selection", "the press selects behind: nothing is lent");
|
||||
s.cursor(Point::new(500.0, 500.0), cmd, v);
|
||||
assert_eq!(s.hover_tool_id(&cmd), "directSelection");
|
||||
assert_eq!(s.shown_tool_id(&cmd), "directSelection");
|
||||
// The bounding box's top middle handle, on the middle of the top segment: the press is lent.
|
||||
assert_eq!(s.hover_tool_at(Some(Point::new(200.0, 150.0)), &cmd, v), "directSelection", "on a box handle");
|
||||
// Turning Select Behind off changes what the bars name over the selection.
|
||||
s.cursor(Point::new(200.0, 200.0), cmd, v);
|
||||
s.prefs.ctrl_click_selects_behind = false;
|
||||
assert_eq!(s.shown_tool_id(&cmd), "directSelection");
|
||||
s.prefs.ctrl_click_selects_behind = true;
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap();
|
||||
assert_eq!(s.tool_id(), "selection");
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 200.0).with_mods(cmd), v).unwrap();
|
||||
let picked = &s.active().unwrap().selection;
|
||||
assert!(picked.contains(back) && !picked.contains(front), "the Cmd-click selects the object behind");
|
||||
// On a selected object's anchor, Direct Selection takes the press.
|
||||
s.execute("select.set", &json!({"ids": [front.0]})).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 250.0, 250.0).with_mods(cmd), v).unwrap();
|
||||
assert_eq!(s.tool_id(), "directSelection");
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 250.0, 250.0).with_mods(cmd), v).unwrap();
|
||||
assert_eq!(s.tool_id(), "selection");
|
||||
s.prefs.ctrl_click_selects_behind = false;
|
||||
s.execute("select.set", &json!({"ids": [front.0]})).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap();
|
||||
assert_eq!(s.tool_id(), "directSelection");
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 200.0).with_mods(cmd), v).unwrap();
|
||||
assert_eq!(s.tool_id(), "selection");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cmd_press_on_a_wide_strokes_outer_half_selects_behind() {
|
||||
// Without Use Preview Bounds the bounding box leaves out the outer half of a wide stroke, which
|
||||
// the Selection tool still hits: a Cmd press there selects the object behind.
|
||||
let cmd = Mods { cmd: true, ..Mods::default() };
|
||||
let v = view();
|
||||
let mut s = session();
|
||||
assert!(!s.prefs.use_preview_bounds);
|
||||
let back = rect(&mut s, 50.0, 50.0, 300.0, 300.0);
|
||||
let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0);
|
||||
s.execute("stroke.set", &json!({"ids": [front.0], "weight": 40})).unwrap();
|
||||
s.select_tool("selection", v).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [front.0]})).unwrap();
|
||||
// 15 pt outside the path, on its stroke.
|
||||
let at = Point::new(200.0, 135.0);
|
||||
assert_eq!(s.hover_tool_at(Some(at), &cmd, v), "selection", "the press selects behind");
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, at.x, at.y).with_mods(cmd), v).unwrap();
|
||||
assert_eq!(s.tool_id(), "selection");
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, at.x, at.y).with_mods(cmd), v).unwrap();
|
||||
let picked = &s.active().unwrap().selection;
|
||||
assert!(picked.contains(back) && !picked.contains(front), "the Cmd-click selects the object behind");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cmd_press_on_a_lone_selected_object_is_lent() {
|
||||
// With nothing behind the selected object, there is nothing to select behind: Direct Selection
|
||||
// takes the press.
|
||||
let cmd = Mods { cmd: true, ..Mods::default() };
|
||||
let v = view();
|
||||
let mut s = session();
|
||||
let lone = rect(&mut s, 150.0, 150.0, 100.0, 100.0);
|
||||
s.select_tool("selection", v).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [lone.0]})).unwrap();
|
||||
assert_eq!(s.hover_tool_at(Some(Point::new(200.0, 200.0)), &cmd, v), "directSelection");
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap();
|
||||
assert_eq!(s.tool_id(), "directSelection");
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 200.0).with_mods(cmd), v).unwrap();
|
||||
assert_eq!(s.tool_id(), "selection");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_layer_effect_that_moves_art_moves_where_a_cmd_press_selects_behind() {
|
||||
// A layer effect draws the selected object 250 pt to the right of its path, over the object
|
||||
// behind it: a Cmd press where it is drawn selects behind. A drop shadow there is not hit, so
|
||||
// the press is lent. Outline view hits the path where it is, and Preview afterwards still finds
|
||||
// the moved art.
|
||||
let cmd = Mods { cmd: true, ..Mods::default() };
|
||||
let v = view();
|
||||
let outline = ViewInfo { outline: true, ..view() };
|
||||
let drawn = Point::new(450.0, 200.0);
|
||||
// On both rectangles' top edges, which Outline view hits, away from the box's handles.
|
||||
let path = Point::new(170.0, 150.0);
|
||||
for effect in ["distort.transform", "stylize.dropShadow"] {
|
||||
let mut s = session();
|
||||
let back = rect(&mut s, 50.0, 150.0, 700.0, 300.0);
|
||||
let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0);
|
||||
let layer = s.doc().unwrap().doc.layers[0].id;
|
||||
let params = if effect == "distort.transform" { json!({"moveH": 250}) } else { json!({"x": 250, "y": 0, "blur": 0}) };
|
||||
s.execute("effect.apply", &json!({"effect": effect, "params": params, "ids": [layer.0], "item": null})).unwrap();
|
||||
s.select_tool("selection", v).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [front.0]})).unwrap();
|
||||
// The back rectangle is drawn moved too, so it is under both points.
|
||||
if effect == "distort.transform" {
|
||||
assert_eq!(s.hover_tool_at(Some(path), &cmd, outline), "selection", "Outline view: on the path");
|
||||
assert_eq!(s.hover_tool_at(Some(drawn), &cmd, v), "selection", "Preview: where the effect draws it");
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, drawn.x, drawn.y).with_mods(cmd), v).unwrap();
|
||||
assert_eq!(s.tool_id(), "selection");
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, drawn.x, drawn.y).with_mods(cmd), v).unwrap();
|
||||
let picked = &s.active().unwrap().selection;
|
||||
assert!(picked.contains(back) && !picked.contains(front), "the Cmd-click selects the object behind");
|
||||
} else {
|
||||
assert_eq!(s.hover_tool_at(Some(drawn), &cmd, v), "directSelection", "on the shadow");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_cmd_clicks_select_behind_a_group_whose_member_is_selected() {
|
||||
// The first Cmd-click on an unselected group lends Direct Selection, which selects the path
|
||||
// under the pointer. The group holds that selected path, so the next Cmd-click there selects
|
||||
// the object behind the group.
|
||||
let cmd = Mods { cmd: true, ..Mods::default() };
|
||||
let v = view();
|
||||
let mut s = session();
|
||||
let back = rect(&mut s, 100.0, 100.0, 200.0, 200.0);
|
||||
let a = rect(&mut s, 150.0, 150.0, 40.0, 40.0);
|
||||
let b = rect(&mut s, 210.0, 150.0, 40.0, 40.0);
|
||||
let group = NodeId(s.execute("object.group", &json!({"ids": [a.0, b.0]})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.select_tool("selection", v).unwrap();
|
||||
let click = |s: &mut Session| {
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 170.0, 170.0).with_mods(cmd), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 170.0, 170.0).with_mods(cmd), v).unwrap();
|
||||
};
|
||||
click(&mut s);
|
||||
let picked = &s.active().unwrap().selection;
|
||||
assert!(picked.contains(a) && !picked.contains(group), "the first Cmd-click picks the path");
|
||||
assert_eq!(s.hover_tool_at(Some(Point::new(170.0, 170.0)), &cmd, v), "selection", "the next press selects behind");
|
||||
click(&mut s);
|
||||
// Made quickly, the two clicks are also a double-click, which neither isolates the group nor
|
||||
// changes what the second click selected, also with Cmd let go before it.
|
||||
s.pointer(&PointerEvent::new(PointerKind::DoubleClick, 170.0, 170.0), v).unwrap();
|
||||
assert_eq!(s.doc().unwrap().isolation, None);
|
||||
let picked = &s.active().unwrap().selection;
|
||||
assert!(picked.contains(back) && !picked.contains(a), "the second Cmd-click selects the object behind the group");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_double_click_after_a_selection_change_is_not_kept_for_select_behind() {
|
||||
// A double-click that follows a Cmd-click selecting behind keeps what it selected, but only
|
||||
// while the document stays as that click left it.
|
||||
let cmd = Mods { cmd: true, ..Mods::default() };
|
||||
let v = view();
|
||||
let mut s = session();
|
||||
rect(&mut s, 100.0, 100.0, 200.0, 200.0);
|
||||
let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0);
|
||||
s.select_tool("selection", v).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [front.0]})).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 200.0).with_mods(cmd), v).unwrap();
|
||||
assert!(!s.active().unwrap().selection.contains(front), "the Cmd-click selects behind");
|
||||
s.execute("select.set", &json!({"ids": [front.0]})).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::DoubleClick, 200.0, 200.0), v).unwrap();
|
||||
assert!(s.doc().unwrap().isolation.is_some(), "the double-click isolates as any other");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_double_click_after_the_pointer_moved_away_is_not_kept_for_select_behind() {
|
||||
let cmd = Mods { cmd: true, ..Mods::default() };
|
||||
let v = view();
|
||||
let mut s = session();
|
||||
rect(&mut s, 100.0, 100.0, 200.0, 200.0);
|
||||
let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0);
|
||||
s.select_tool("selection", v).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [front.0]})).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 200.0).with_mods(cmd), v).unwrap();
|
||||
assert!(!s.active().unwrap().selection.contains(front), "the Cmd-click selects behind");
|
||||
s.pointer(&PointerEvent::new(PointerKind::Move, 400.0, 400.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Move, 200.0, 200.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::DoubleClick, 200.0, 200.0), v).unwrap();
|
||||
assert!(s.doc().unwrap().isolation.is_some(), "the double-click isolates as any other");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_double_click_after_a_select_behind_drag_is_not_kept_for_select_behind() {
|
||||
// A Cmd press that selects behind and then drags is not a click, also when the drag ends where
|
||||
// it began and moves nothing, so a double-click there is a double-click of its own.
|
||||
let cmd = Mods { cmd: true, ..Mods::default() };
|
||||
let v = view();
|
||||
let mut s = session();
|
||||
let back = rect(&mut s, 100.0, 100.0, 200.0, 200.0);
|
||||
let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0);
|
||||
s.select_tool("selection", v).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [front.0]})).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 260.0, 200.0).with_mods(cmd), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 200.0).with_mods(cmd), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 200.0).with_mods(cmd), v).unwrap();
|
||||
assert!(s.active().unwrap().selection.contains(back), "the Cmd press selects behind");
|
||||
s.pointer(&PointerEvent::new(PointerKind::DoubleClick, 200.0, 200.0), v).unwrap();
|
||||
assert!(s.doc().unwrap().isolation.is_some(), "the double-click isolates as any other");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_double_click_after_a_select_behind_press_released_away_is_not_kept_for_select_behind() {
|
||||
// The automation interface can send the release far from the press with no drag between.
|
||||
let cmd = Mods { cmd: true, ..Mods::default() };
|
||||
let v = view();
|
||||
let mut s = session();
|
||||
let back = rect(&mut s, 100.0, 100.0, 200.0, 200.0);
|
||||
let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0);
|
||||
s.select_tool("selection", v).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [front.0]})).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 270.0, 270.0).with_mods(cmd), v).unwrap();
|
||||
assert!(s.active().unwrap().selection.contains(back), "the Cmd press selects behind");
|
||||
s.pointer(&PointerEvent::new(PointerKind::DoubleClick, 270.0, 270.0), v).unwrap();
|
||||
assert!(s.doc().unwrap().isolation.is_some(), "the double-click isolates as any other");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_double_click_in_the_frame_of_a_select_behind_press_keeps_what_it_selected() {
|
||||
// The second press and the double-click can come in one frame, before the release.
|
||||
let cmd = Mods { cmd: true, ..Mods::default() };
|
||||
let v = view();
|
||||
let mut s = session();
|
||||
let back = rect(&mut s, 100.0, 100.0, 200.0, 200.0);
|
||||
let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0);
|
||||
s.select_tool("selection", v).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [back.0]})).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::DoubleClick, 200.0, 200.0).with_mods(cmd), v).unwrap();
|
||||
assert_eq!(s.doc().unwrap().isolation, None, "the double-click neither isolates nor edits");
|
||||
let picked = &s.active().unwrap().selection;
|
||||
assert!(picked.contains(front) && !picked.contains(back), "the press selects behind, back to the topmost");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cmd_click_on_an_unselected_member_of_a_group_holding_the_selection_selects_behind() {
|
||||
// The group counts as selected wherever its art is, not only over its selected member.
|
||||
let cmd = Mods { cmd: true, ..Mods::default() };
|
||||
let v = view();
|
||||
let mut s = session();
|
||||
let back = rect(&mut s, 100.0, 100.0, 300.0, 200.0);
|
||||
let a = rect(&mut s, 150.0, 150.0, 40.0, 40.0);
|
||||
let b = rect(&mut s, 300.0, 150.0, 40.0, 40.0);
|
||||
s.execute("object.group", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
s.select_tool("selection", v).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
assert_eq!(s.hover_tool_at(Some(Point::new(320.0, 170.0)), &cmd, v), "selection", "on the unselected member");
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 320.0, 170.0).with_mods(cmd), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 320.0, 170.0).with_mods(cmd), v).unwrap();
|
||||
let picked = &s.active().unwrap().selection;
|
||||
assert!(picked.contains(back) && !picked.contains(b), "the Cmd-click selects the object behind the group");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cmd_click_on_a_selected_lines_segment_selects_behind() {
|
||||
// An open, unfilled path is only hit near its segments: a Cmd press there selects the object
|
||||
// behind it, and a Cmd press on its anchor is Direct Selection's.
|
||||
let cmd = Mods { cmd: true, ..Mods::default() };
|
||||
let v = view();
|
||||
let mut s = session();
|
||||
let back = rect(&mut s, 100.0, 100.0, 200.0, 200.0);
|
||||
let front = line(&mut s, 150.0, 150.0, 250.0, 250.0);
|
||||
s.select_tool("selection", v).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [front.0]})).unwrap();
|
||||
assert_eq!(s.hover_tool_at(Some(Point::new(150.0, 150.0)), &cmd, v), "directSelection", "on its anchor");
|
||||
// On the segment, away from the anchors and the bounding box's handles.
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 180.0, 180.0).with_mods(cmd), v).unwrap();
|
||||
assert_eq!(s.tool_id(), "selection");
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 180.0, 180.0).with_mods(cmd), v).unwrap();
|
||||
let picked = &s.active().unwrap().selection;
|
||||
assert!(picked.contains(back) && !picked.contains(front), "the Cmd-click selects the object behind");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hovers_lend_decision_holds_only_for_the_tool_and_selection_it_was_found_for() {
|
||||
// While the view moves, the canvas reads the last hover's decision: it does not carry over to
|
||||
// another tool or another selection.
|
||||
let cmd = Mods { cmd: true, ..Mods::default() };
|
||||
let v = view();
|
||||
let mut s = session();
|
||||
rect(&mut s, 100.0, 100.0, 200.0, 200.0);
|
||||
let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0);
|
||||
s.select_tool("selection", v).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [front.0]})).unwrap();
|
||||
assert_eq!(s.hover_tool_at(Some(Point::new(200.0, 200.0)), &cmd, v), "selection");
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert_eq!(s.hover_tool_id(&cmd), "directSelection", "nothing is selected now");
|
||||
assert_eq!(s.hover_tool_at(Some(Point::new(500.0, 500.0)), &cmd, v), "directSelection");
|
||||
s.select_tool("rectangle", v).unwrap();
|
||||
assert_eq!(s.hover_tool_id(&cmd), s.lent_tool_id(&cmd).unwrap(), "the new tool's lend");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_marks_follow_this_frames_pointer_with_cmd_held() {
|
||||
// The canvas asks which tool's marks to draw before it asks for the cursor: the answer is for
|
||||
// the pointer where it is now, and with the pointer off the canvas, the tool Cmd lends.
|
||||
let cmd = Mods { cmd: true, ..Mods::default() };
|
||||
let v = view();
|
||||
let mut s = session();
|
||||
rect(&mut s, 100.0, 100.0, 200.0, 200.0);
|
||||
let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0);
|
||||
s.select_tool("selection", v).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [front.0]})).unwrap();
|
||||
s.cursor(Point::new(200.0, 200.0), cmd, v);
|
||||
assert_eq!(s.hover_tool_id(&cmd), "selection");
|
||||
assert_eq!(s.hover_tool_at(Some(Point::new(500.0, 500.0)), &cmd, v), "directSelection", "away from the selection");
|
||||
assert_eq!(s.hover_tool_at(Some(Point::new(200.0, 200.0)), &cmd, v), "selection", "over the selection");
|
||||
assert_eq!(s.hover_tool_at(None, &cmd, v), "directSelection", "off the canvas");
|
||||
assert_eq!(s.hover_tool_id(&cmd), "directSelection", "kept while the view moves");
|
||||
assert_eq!(s.hover_tool_at(None, &Mods::default(), v), "selection", "without Cmd");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmd_lends_the_selection_tool_and_its_bounding_box_to_direct_selection() {
|
||||
// #3901: with Direct Selection, Cmd held gives the Selection tool for the press: its cursor,
|
||||
@@ -6583,6 +7045,382 @@ fn pencil_redraws_a_selected_compound_path() {
|
||||
assert!(members(&s)[1] != before[1], "the hole is redrawn");
|
||||
}
|
||||
|
||||
/// A Pencil stroke that starts on a selected closed shape and is lifted away from it takes the
|
||||
/// shape with it: the shape opens where the stroke started, keeps its whole outline, fill and
|
||||
/// selection, and ends where the pen was lifted. While the stroke is drawn the shape stays as it
|
||||
/// was and the selection with it (the preview shows the stroke on its own); the release leaves no
|
||||
/// new path.
|
||||
#[test]
|
||||
fn a_stroke_lifted_away_from_a_closed_shape_opens_it_and_follows_the_stroke() {
|
||||
let mut s = session();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap();
|
||||
let id = rect(&mut s, 100.0, 100.0, 200.0, 100.0);
|
||||
let fill = s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint().clone();
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.set_tool_option_cmd(&json!({"tool": "pencil", "values": {"editWithin": 12}})).unwrap();
|
||||
let v = view();
|
||||
s.select_tool("pencil", v).unwrap();
|
||||
let count = |s: &Session| s.doc().unwrap().doc.layers[0].children().map_or(0, |c| c.len());
|
||||
let shape = |s: &Session| s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().clone();
|
||||
let before = shape(&s);
|
||||
// From the right edge, a little hook up and out to the right.
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 300.0, 150.0), v).unwrap();
|
||||
for (x, y) in [(303.0, 140.0), (308.0, 128.0), (316.0, 118.0), (326.0, 112.0), (338.0, 110.0)] {
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, x, y), v).unwrap();
|
||||
assert!(shape(&s) == before, "the shape stays as it was while the stroke is drawn");
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![id], "and stays selected");
|
||||
}
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 338.0, 110.0), v).unwrap();
|
||||
assert_eq!(count(&s), 1, "no new path");
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![id], "the shape stays selected");
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap();
|
||||
assert_eq!(n.appearance.fill_paint(), fill, "the fill stays");
|
||||
let sp = &n.path_data().unwrap().subpaths[0];
|
||||
assert!(!sp.closed, "the shape opened");
|
||||
let ps: Vec<Point> = sp.anchors.iter().map(|a| a.p).collect();
|
||||
for corner in [(100.0, 100.0), (300.0, 100.0), (300.0, 200.0), (100.0, 200.0)] {
|
||||
assert!(ps.iter().any(|p| near(*p, Point::new(corner.0, corner.1))), "{corner:?} kept: {ps:?}");
|
||||
}
|
||||
assert!(ends_at(sp, Point::new(300.0, 150.0), Point::new(338.0, 110.0), 0.5), "from the opening to where the pen was lifted: {ps:?}");
|
||||
// The outline joins the stroke heading up, the stroke's way: next to the anchor where the
|
||||
// stroke leaves the opening is the bottom right corner.
|
||||
let last = ps.len() - 1;
|
||||
let k = (1..last).find(|&i| ps[i].distance(Point::new(300.0, 150.0)) < 0.5).unwrap();
|
||||
assert!(near(ps[k - 1], Point::new(300.0, 200.0)) || near(ps[k + 1], Point::new(300.0, 200.0)), "joins from below: {ps:?}");
|
||||
}
|
||||
|
||||
/// On an open path, a stroke from its middle lifted away from it cuts the path there and drops the
|
||||
/// part the stroke heads along; the part behind stays and ends where the pen was lifted.
|
||||
#[test]
|
||||
fn a_stroke_lifted_away_from_an_open_path_drops_the_part_it_heads_along() {
|
||||
for (towards_end, kept) in [(true, Point::new(100.0, 100.0)), (false, Point::new(300.0, 100.0))] {
|
||||
let mut s = session();
|
||||
let id = line(&mut s, 100.0, 100.0, 300.0, 100.0);
|
||||
let dx = if towards_end { 1.0 } else { -1.0 };
|
||||
let pts: Vec<_> = (0..8).map(|i| json!([200.0 + dx * 4.0 * f64::from(i), 100.0 - 5.0 * f64::from(i)])).collect();
|
||||
s.execute("path.freehand", &json!({"points": pts, "redraw": {"id": id.0, "within": 4}})).unwrap();
|
||||
assert_eq!(paths(&s).len(), 1, "no new path");
|
||||
let sp = &path(&s, id).subpaths[0];
|
||||
let ps: Vec<Point> = sp.anchors.iter().map(|a| a.p).collect();
|
||||
assert!(
|
||||
ends_at(sp, kept, Point::new(200.0 + dx * 28.0, 65.0), 0.5),
|
||||
"towards the end {towards_end}: the part behind stays and ends where the pen was lifted: {ps:?}"
|
||||
);
|
||||
let dropped = Point::new(if towards_end { 300.0 } else { 100.0 }, 100.0);
|
||||
assert!(!ps.iter().any(|p| p.distance(dropped) < 1.0), "the part ahead is dropped: {ps:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A stroke that leaves a selected path and comes back to the same point adds a loop there; the
|
||||
/// path stays closed and keeps its corners.
|
||||
#[test]
|
||||
fn a_stroke_back_to_where_it_started_adds_a_loop() {
|
||||
let mut s = session();
|
||||
let id = rect(&mut s, 0.0, 0.0, 200.0, 100.0);
|
||||
let before = path(&s, id).subpaths[0].anchors.len();
|
||||
let loop_pts = json!([[100, 0], [90, -15], [95, -35], [110, -38], [120, -20], [108, -8], [100, 0]]);
|
||||
s.execute("path.freehand", &json!({"points": loop_pts, "redraw": {"id": id.0, "within": 4}})).unwrap();
|
||||
assert_eq!(paths(&s).len(), 1, "no new path");
|
||||
let sp = &path(&s, id).subpaths[0];
|
||||
assert!(sp.closed && sp.anchors.len() > before, "{sp:?}");
|
||||
let top = kurbo::Shape::bounding_box(&path(&s, id).to_bezpath()).y0;
|
||||
assert!(top < -30.0, "the loop: top {top}");
|
||||
for corner in [(0.0, 0.0), (200.0, 0.0), (200.0, 100.0), (0.0, 100.0)] {
|
||||
assert!(sp.anchors.iter().any(|a| near(a.p, Point::new(corner.0, corner.1))), "{corner:?} kept");
|
||||
}
|
||||
}
|
||||
|
||||
/// On a closed path the stroke replaces the way round it heads from its start, even when that is
|
||||
/// the longer way: the shape doesn't flip to the other side as the stroke goes on.
|
||||
#[test]
|
||||
fn a_redraw_of_a_closed_path_goes_the_way_the_stroke_heads() {
|
||||
let mut s = session();
|
||||
let id = rect(&mut s, 0.0, 0.0, 200.0, 100.0);
|
||||
// From (20, 0) out to the left, round below the rectangle and up its right side to (180, 0).
|
||||
let pts = json!([[20, 0], [10, -15], [-20, -10], [-25, 50], [-20, 120], [100, 125], [220, 120], [225, 50], [210, -10], [190, -12], [180, 0]]);
|
||||
s.execute("path.freehand", &json!({"points": pts, "redraw": {"id": id.0, "within": 4}})).unwrap();
|
||||
assert_eq!(paths(&s).len(), 1);
|
||||
let sp = &path(&s, id).subpaths[0];
|
||||
assert!(sp.closed);
|
||||
let ps: Vec<Point> = sp.anchors.iter().map(|a| a.p).collect();
|
||||
// The rectangle's left, bottom and right sides went with the stroke; its top between 20 and
|
||||
// 180 stays.
|
||||
for corner in [(0.0, 0.0), (0.0, 100.0), (200.0, 100.0), (200.0, 0.0)] {
|
||||
assert!(!ps.iter().any(|p| p.distance(Point::new(corner.0, corner.1)) < 1.0), "{corner:?} replaced: {ps:?}");
|
||||
}
|
||||
let b = kurbo::Shape::bounding_box(&path(&s, id).to_bezpath());
|
||||
assert!(b.y1 > 115.0 && b.x0 < -15.0, "the stroke's way round: {b:?}");
|
||||
}
|
||||
|
||||
/// A stroke lifted farther from the path than Edit selected paths within takes the path with it;
|
||||
/// one lifted within that distance joins it again, its end bent smoothly onto it.
|
||||
#[test]
|
||||
fn a_stroke_lifted_beyond_the_edit_distance_takes_the_path_along() {
|
||||
let mut s = session();
|
||||
let id = rect(&mut s, 0.0, 0.0, 200.0, 100.0);
|
||||
// A hook out of the right side that ends 8 pt from it.
|
||||
let hook = json!([[200, 50], [210, 40], [222, 38], [226, 46], [222, 56], [208, 58]]);
|
||||
s.execute("path.freehand", &json!({"points": hook, "redraw": {"id": id.0, "within": 4}})).unwrap();
|
||||
let sp = &path(&s, id).subpaths[0];
|
||||
assert!(!sp.closed, "8 pt away with 4 pt to edit within: the shape opened");
|
||||
let ends = [sp.anchors.first().unwrap().p, sp.anchors.last().unwrap().p];
|
||||
assert!(ends.iter().any(|p| p.distance(Point::new(208.0, 58.0)) < 0.5), "it ends where the pen was lifted: {ends:?}");
|
||||
}
|
||||
|
||||
/// A shape with a hole that opens keeps its outline running its own way, so the hole stays a hole.
|
||||
#[test]
|
||||
fn opening_a_shape_with_a_hole_keeps_the_hole() {
|
||||
for heads_back in [false, true] {
|
||||
let mut s = session();
|
||||
let outer = rect(&mut s, 0.0, 0.0, 200.0, 200.0);
|
||||
let hole = rect(&mut s, 50.0, 50.0, 100.0, 100.0);
|
||||
s.execute("select.set", &json!({"ids": [outer.0, hole.0]})).unwrap();
|
||||
s.execute("object.compoundPath.make", &json!({})).unwrap();
|
||||
let compound = s.doc().unwrap().selection.objects[0];
|
||||
let member = |s: &Session, i: usize| s.doc().unwrap().doc.node(compound).unwrap().children().unwrap()[i].clone();
|
||||
let (outer_id, sign) = {
|
||||
let m = member(&s, 0);
|
||||
(m.id, m.path_data().unwrap().subpaths[0].signed_area().signum())
|
||||
};
|
||||
// A hook out of the top edge, heading one way or the other along it.
|
||||
let dx = if heads_back { -1.0 } else { 1.0 };
|
||||
let hook: Vec<_> = (0..6).map(|i| json!([100.0 + dx * 6.0 * f64::from(i), -5.0 * f64::from(i)])).collect();
|
||||
s.execute("path.freehand", &json!({"points": hook, "redraw": {"id": outer_id.0, "within": 4}})).unwrap();
|
||||
let sp = member(&s, 0).path_data().unwrap().subpaths[0].clone();
|
||||
assert!(!sp.closed, "heads back {heads_back}: opened");
|
||||
assert_eq!(sp.signed_area().signum(), sign, "heads back {heads_back}: the outline runs its own way, the hole stays a hole");
|
||||
}
|
||||
}
|
||||
|
||||
/// A stroke across a shape from one point of its outline to another carves off the part it cuts
|
||||
/// across, the lobe on that side, and keeps the rest, whichever way it is drawn.
|
||||
#[test]
|
||||
fn a_stroke_across_a_shape_carves_off_the_part_it_cuts() {
|
||||
for reversed in [false, true] {
|
||||
let mut s = session();
|
||||
// A wide shape with a lobe on top between x = 80 and x = 120.
|
||||
let shape = json!([[0, 0], [80, 0], [80, -60], [120, -60], [120, 0], [300, 0], [300, 100], [0, 100]]);
|
||||
let id = NodeId(s.execute("path.freehand", &json!({"points": shape, "closed": true, "fidelity": 0.01})).unwrap()["id"].as_u64().unwrap());
|
||||
// Across the lobe's base, a little inside the shape.
|
||||
let mut cut = vec![json!([70, 0]), json!([85, 8]), json!([100, 10]), json!([115, 8]), json!([130, 0])];
|
||||
if reversed {
|
||||
cut.reverse();
|
||||
}
|
||||
s.execute("path.freehand", &json!({"points": cut, "redraw": {"id": id.0, "within": 4}})).unwrap();
|
||||
let sp = &path(&s, id).subpaths[0];
|
||||
assert!(sp.closed, "reversed {reversed}");
|
||||
let b = kurbo::Shape::bounding_box(&path(&s, id).to_bezpath());
|
||||
assert!(b.y0 > -20.0, "reversed {reversed}: the lobe (up to y = -60) is carved off: {b:?}");
|
||||
assert!(b.x1 > 295.0 && b.y1 > 95.0, "reversed {reversed}: the rest stays: {b:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A stroke leaving an open path across it (no direction along it) drops the nearer, short side,
|
||||
/// not most of the path.
|
||||
#[test]
|
||||
fn a_stroke_leaving_an_open_path_across_it_drops_the_side_it_is_near() {
|
||||
let mut s = session();
|
||||
let id = line(&mut s, 100.0, 100.0, 300.0, 100.0);
|
||||
// Straight up from x = 280, then bending towards the near end.
|
||||
let up = json!([[280, 100], [280, 90], [281, 75], [284, 60], [290, 50]]);
|
||||
s.execute("path.freehand", &json!({"points": up, "redraw": {"id": id.0, "within": 4}})).unwrap();
|
||||
let sp = &path(&s, id).subpaths[0];
|
||||
assert!(ends_at(sp, Point::new(100.0, 100.0), Point::new(290.0, 50.0), 0.5), "the long side stays: {sp:?}");
|
||||
}
|
||||
|
||||
/// A stroke drawn over an open shape's open ends, from near one end to near the other, redraws
|
||||
/// those ends along the stroke and closes the shape, whichever way it is drawn; the shape's body
|
||||
/// between stays.
|
||||
#[test]
|
||||
fn a_stroke_over_an_open_shapes_ends_closes_it_along_the_stroke() {
|
||||
for reversed in [false, true] {
|
||||
let mut s = session();
|
||||
// A C open on the right: from the top right round the left to the bottom right.
|
||||
let c: Vec<_> = (0..=30)
|
||||
.map(|i| {
|
||||
let a = (40.0 + 280.0 * f64::from(i) / 30.0).to_radians();
|
||||
json!([200.0 + 100.0 * a.cos(), 200.0 - 100.0 * a.sin()])
|
||||
})
|
||||
.collect();
|
||||
let id = NodeId(s.execute("path.freehand", &json!({"points": c, "fidelity": 0.5})).unwrap()["id"].as_u64().unwrap());
|
||||
let on = |deg: f64| {
|
||||
let a = deg.to_radians();
|
||||
(200.0 + 100.0 * a.cos(), 200.0 - 100.0 * a.sin())
|
||||
};
|
||||
// From the C near its top end, out round the open side, back onto it near the bottom end.
|
||||
let (a, b) = (on(60.0), on(300.0));
|
||||
let mut stroke = vec![json!([a.0, a.1]), json!([290.0, 150.0]), json!([315.0, 200.0]), json!([290.0, 250.0]), json!([b.0, b.1])];
|
||||
if reversed {
|
||||
stroke.reverse();
|
||||
}
|
||||
s.execute("path.freehand", &json!({"points": stroke, "redraw": {"id": id.0, "within": 4}})).unwrap();
|
||||
assert_eq!(paths(&s).len(), 1, "reversed {reversed}: no new path");
|
||||
let sp = &path(&s, id).subpaths[0];
|
||||
assert!(sp.closed, "reversed {reversed}: the shape closed");
|
||||
let bb = kurbo::Shape::bounding_box(&path(&s, id).to_bezpath());
|
||||
assert!(bb.x1 > 310.0 && bb.x0 < 105.0, "reversed {reversed}: closed along the stroke, the body kept: {bb:?}");
|
||||
// The old ends (at 40° and 320°) are gone.
|
||||
for deg in [40.0, 320.0] {
|
||||
let e = on(deg);
|
||||
assert!(!sp.anchors.iter().any(|q| q.p.distance(Point::new(e.0, e.1)) < 1.0), "reversed {reversed}: the end at {deg}° is redrawn");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A stroke that starts and ends on an open path decides by the way it runs along the path at its
|
||||
/// ends: where it starts it replaces the part it runs along, where it lands it joins the part it runs
|
||||
/// into, an end that goes straight off or onto the path follows the other end, and when both do it
|
||||
/// closes only round both pieces beyond. A stroke lifted away from the path ends there. The path is
|
||||
/// an L whose bottom arm turns up and back over to a hook near the upright arm.
|
||||
#[test]
|
||||
fn a_redraw_on_an_open_path_follows_the_way_its_ends_run() {
|
||||
// From the upright arm's top (100, 0) down, along the bottom, up the right side, back along the
|
||||
// top to the hook, which ends at (160, 60).
|
||||
let shape = [[100.0, 0.0], [100.0, 300.0], [400.0, 300.0], [400.0, 100.0], [160.0, 100.0], [160.0, 60.0]];
|
||||
// A stroke through `pts`, a point every 2 pt, as a hand draws it.
|
||||
let dense = |pts: &[[f64; 2]]| {
|
||||
let mut out = vec![json!(pts[0])];
|
||||
for w in pts.windows(2) {
|
||||
let (a, b) = (Point::new(w[0][0], w[0][1]), Point::new(w[1][0], w[1][1]));
|
||||
let n = (a.distance(b) / 2.0).ceil().max(1.0) as usize;
|
||||
out.extend((1..=n).map(|i| {
|
||||
let q = a.lerp(b, i as f64 / n as f64);
|
||||
json!([q.x, q.y])
|
||||
}));
|
||||
}
|
||||
out
|
||||
};
|
||||
let has = |sp: &vectorcraft_geom::SubPath, x: f64, y: f64| sp.anchors.iter().any(|a| a.p.distance(Point::new(x, y)) < 1.0);
|
||||
// Over the loop above the path, from the top edge round to the left of the upright arm.
|
||||
let over = [[250.0, 40.0], [200.0, -30.0], [100.0, -40.0], [40.0, 0.0]];
|
||||
// Each: its name, the stroke, and whether the path is closed and keeps the bottom right corner,
|
||||
// the upright arm's top and the hook's end.
|
||||
let cases = [
|
||||
// Runs along the top towards the hook, then up the upright arm: the hook goes, the end is
|
||||
// left where the pen is lifted, on the arm, and the rest of the path stays.
|
||||
(
|
||||
"towards the hook, landing up the arm",
|
||||
vec![[250.0, 100.0], [165.0, 100.0], [130.0, 95.0], [100.0, 90.0], [100.0, 40.0]],
|
||||
[false, true, true, false],
|
||||
),
|
||||
// Runs along the top away from the hook, then lands running up the arm: the part between
|
||||
// is replaced, both ends stay.
|
||||
(
|
||||
"away from the hook, landing up the arm",
|
||||
vec![[250.0, 100.0], [300.0, 100.0], [320.0, 60.0], [250.0, 30.0], [140.0, 40.0], [100.0, 90.0], [100.0, 60.0]],
|
||||
[false, false, true, true],
|
||||
),
|
||||
// Straight up off the top, over the arm's top, landing running down the arm: the arm's top and
|
||||
// the hook go and the path closes round the rest.
|
||||
(
|
||||
"straight off, landing down the arm",
|
||||
[&[[250.0, 100.0]][..], &over, &[[40.0, 120.0], [85.0, 140.0], [100.0, 150.0], [100.0, 180.0]]].concat(),
|
||||
[true, true, false, false],
|
||||
),
|
||||
// Straight off and straight onto the arm, round both the arm's top and the hook: it closes.
|
||||
("straight off and on, round both", [&[[250.0, 100.0]][..], &over, &[[40.0, 150.0], [100.0, 150.0]]].concat(), [true, true, false, false]),
|
||||
// The same loop carried on across the arm and lifted inside: the path ends there; the hook,
|
||||
// the shorter side, goes.
|
||||
(
|
||||
"across the arm, lifted away",
|
||||
[&[[250.0, 100.0]][..], &over, &[[40.0, 150.0], [100.0, 150.0], [200.0, 160.0]]].concat(),
|
||||
[false, true, true, false],
|
||||
),
|
||||
];
|
||||
for (name, stroke, [closed, body, top, hook]) in cases {
|
||||
let mut s = session();
|
||||
let id = NodeId(s.execute("path.freehand", &json!({"points": shape, "fit": false})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("path.freehand", &json!({"points": dense(&stroke), "redraw": {"id": id.0, "within": 12}})).unwrap();
|
||||
assert_eq!(paths(&s).len(), 1, "{name}: no new path");
|
||||
let sp = &path(&s, id).subpaths[0];
|
||||
assert_eq!(sp.closed, closed, "{name}: closed: {sp:?}");
|
||||
assert_eq!(has(sp, 400.0, 300.0), body, "{name}: the bottom right corner: {sp:?}");
|
||||
assert_eq!(has(sp, 100.0, 0.0), top, "{name}: the upright arm's top: {sp:?}");
|
||||
assert_eq!(has(sp, 160.0, 60.0), hook, "{name}: the hook's end: {sp:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A stroke that starts on an open C's upper arm running towards its end, goes round the opening
|
||||
/// and lands on the lower arm running back into the C closes it into a ring.
|
||||
#[test]
|
||||
fn a_stroke_run_over_both_arms_of_a_c_closes_it() {
|
||||
let mut s = session();
|
||||
let on = |deg: f64| {
|
||||
let a = deg.to_radians();
|
||||
json!([200.0 + 100.0 * a.cos(), 200.0 - 100.0 * a.sin()])
|
||||
};
|
||||
let c: Vec<_> = (0..=28).map(|i| on(40.0 + 10.0 * f64::from(i))).collect();
|
||||
let id = NodeId(s.execute("path.freehand", &json!({"points": c, "fidelity": 0.5})).unwrap()["id"].as_u64().unwrap());
|
||||
let mut stroke: Vec<_> = (0..=8).map(|i| on(56.0 - 2.0 * f64::from(i))).collect();
|
||||
stroke.extend([json!([300.0, 160.0]), json!([310.0, 200.0]), json!([300.0, 240.0])]);
|
||||
stroke.extend((0..=8).map(|i| on(324.0 - 2.0 * f64::from(i))));
|
||||
s.execute("path.freehand", &json!({"points": stroke, "redraw": {"id": id.0, "within": 4}})).unwrap();
|
||||
let sp = &path(&s, id).subpaths[0];
|
||||
assert!(sp.closed, "a ring: {sp:?}");
|
||||
let bb = kurbo::Shape::bounding_box(&path(&s, id).to_bezpath());
|
||||
assert!(bb.x0 < 105.0 && bb.x1 > 300.0, "the C's body and the stroke: {bb:?}");
|
||||
}
|
||||
|
||||
/// A tall bump redrawn over most of an open line replaces that part: the ends beyond it stay and
|
||||
/// the line stays open.
|
||||
#[test]
|
||||
fn a_tall_redraw_over_most_of_an_open_line_keeps_its_ends() {
|
||||
for reversed in [false, true] {
|
||||
let mut s = session();
|
||||
let id = line(&mut s, 100.0, 300.0, 700.0, 300.0);
|
||||
let mut bump =
|
||||
vec![json!([200, 300]), json!([250, 226]), json!([325, 148]), json!([400, 120]), json!([475, 148]), json!([550, 226]), json!([600, 300])];
|
||||
if reversed {
|
||||
bump.reverse();
|
||||
}
|
||||
s.execute("path.freehand", &json!({"points": bump, "redraw": {"id": id.0, "within": 12}})).unwrap();
|
||||
let sp = &path(&s, id).subpaths[0];
|
||||
assert!(!sp.closed, "reversed {reversed}: still open");
|
||||
assert!(ends_at(sp, Point::new(100.0, 300.0), Point::new(700.0, 300.0), 1e-6), "reversed {reversed}: both ends stay: {sp:?}");
|
||||
assert!(kurbo::Shape::bounding_box(&path(&s, id).to_bezpath()).y0 < 135.0, "reversed {reversed}: the bump");
|
||||
}
|
||||
}
|
||||
|
||||
/// A tall arch over one long side of a thin closed shape replaces that side: the result is the
|
||||
/// bigger of the two shapes the stroke could make, not the arch alone.
|
||||
#[test]
|
||||
fn a_tall_arch_over_a_thin_shapes_side_keeps_the_shape() {
|
||||
for reversed in [false, true] {
|
||||
let mut s = session();
|
||||
let id = rect(&mut s, 100.0, 300.0, 600.0, 60.0);
|
||||
let mut arch =
|
||||
vec![json!([130, 300]), json!([197, 216]), json!([265, 144]), json!([400, 80]), json!([535, 144]), json!([603, 216]), json!([670, 300])];
|
||||
if reversed {
|
||||
arch.reverse();
|
||||
}
|
||||
s.execute("path.freehand", &json!({"points": arch, "redraw": {"id": id.0, "within": 12}})).unwrap();
|
||||
let sp = &path(&s, id).subpaths[0];
|
||||
assert!(sp.closed, "reversed {reversed}");
|
||||
for corner in [(100.0, 300.0), (700.0, 300.0), (700.0, 360.0), (100.0, 360.0)] {
|
||||
assert!(sp.anchors.iter().any(|a| near(a.p, Point::new(corner.0, corner.1))), "reversed {reversed}: {corner:?} kept: {sp:?}");
|
||||
}
|
||||
assert!(kurbo::Shape::bounding_box(&path(&s, id).to_bezpath()).y0 < 95.0, "reversed {reversed}: the arch");
|
||||
}
|
||||
}
|
||||
|
||||
/// A stroke that comes back near the path, within Edit selected paths within but not on it, joins
|
||||
/// it again: the shape stays one closed path, and the stroke's end bends onto it, so no anchor
|
||||
/// lies off the stroke's way back.
|
||||
#[test]
|
||||
fn a_stroke_back_near_the_path_joins_it_smoothly() {
|
||||
let mut s = session();
|
||||
let id = rect(&mut s, 0.0, 0.0, 200.0, 100.0);
|
||||
// A bump out of the top edge that comes back down to 10 pt above it.
|
||||
let bump = json!([[40, 0], [45, -20], [60, -40], [80, -45], [100, -40], [115, -25], [120, -10]]);
|
||||
s.execute("path.freehand", &json!({"points": bump, "redraw": {"id": id.0, "within": 20}})).unwrap();
|
||||
assert_eq!(paths(&s).len(), 1);
|
||||
let sp = &path(&s, id).subpaths[0];
|
||||
assert!(sp.closed, "joined again: still closed");
|
||||
let top = kurbo::Shape::bounding_box(&path(&s, id).to_bezpath()).y0;
|
||||
assert!(top < -35.0, "the bump: top {top}");
|
||||
}
|
||||
|
||||
/// With the Pencil's Live preview off, nothing is added to the document while a filled stroke is
|
||||
/// drawn; the release draws the path with its fill, as one undo step.
|
||||
#[test]
|
||||
|
||||
@@ -1212,6 +1212,26 @@ fn select_part_refuses_hidden_and_locked_objects_of_the_art() {
|
||||
s.execute("symbol.instance.selectPart", &json!({"id": inst.0, "path": [1, 1]})).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cmd_click_with_the_selection_tool_keeps_the_instance_selected_whole() {
|
||||
// Cmd lends Direct Selection the Selection tool: the press picks one object of a dynamic
|
||||
// instance, and back with the Selection tool after the release, the instance stays selected,
|
||||
// whole, as choosing the Selection tool leaves it.
|
||||
let mut s = session();
|
||||
let inst = pair(&mut s, "dynamic");
|
||||
let v = ViewInfo { smart_guides: false, ..Default::default() };
|
||||
let cmd = Mods { cmd: true, ..Mods::default() };
|
||||
s.select_tool("selection", v).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 80.0, 30.0).with_mods(cmd), v).unwrap();
|
||||
assert_eq!(s.tool_id(), "directSelection");
|
||||
assert!(s.doc().unwrap().selection.symbol_part.is_some(), "the lent tool picks the object");
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 80.0, 30.0).with_mods(cmd), v).unwrap();
|
||||
assert_eq!(s.tool_id(), "selection");
|
||||
let sel = &s.doc().unwrap().selection;
|
||||
assert_eq!((&sel.objects, &sel.symbol_part), (&vec![inst], &None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn choosing_the_selection_tool_again_picks_the_instance_whole() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -0,0 +1,829 @@
|
||||
//! A command run from outside the tool (a panel, a menu item, an automation client) while a tool's drag is
|
||||
//! in progress is a step of its own, before the drag's: the drag's next preview, its release and
|
||||
//! Escape keep the command's edit, and the release still draws what the drag drew, with Real-time
|
||||
//! Drawing on and off.
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_geom::Rect;
|
||||
use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey};
|
||||
|
||||
use crate::*;
|
||||
|
||||
/// The view the gestures run in: page coordinates, with Smart Guides off so nothing snaps.
|
||||
fn view() -> ViewInfo {
|
||||
ViewInfo { smart_guides: false, ..ViewInfo::default() }
|
||||
}
|
||||
|
||||
/// Feed the pointer event `(kind, x, y)` to the active tool.
|
||||
fn pointer(s: &mut Session, kind: PointerKind, x: f64, y: f64) {
|
||||
s.pointer(&PointerEvent::new(kind, x, y), view()).unwrap();
|
||||
}
|
||||
|
||||
/// A new 400 × 400 pt document with Real-time Drawing `real_time`, holding one 20 × 20 pt rectangle
|
||||
/// (returned), nothing selected, and the Rectangle tool chosen.
|
||||
fn session(real_time: bool) -> (Session, NodeId) {
|
||||
let mut s = Session::new();
|
||||
s.prefs.real_time_drawing = real_time;
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap();
|
||||
let other = s.doc().unwrap().selection.objects[0];
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.select_tool("rectangle", view()).unwrap();
|
||||
(s, other)
|
||||
}
|
||||
|
||||
fn visible(s: &Session, id: NodeId) -> bool {
|
||||
s.doc().unwrap().doc.node(id).expect("the object is in the document").visible
|
||||
}
|
||||
|
||||
/// The objects of the document's first layer.
|
||||
fn objects(s: &Session) -> usize {
|
||||
s.doc().unwrap().doc.layers[0].children().map_or(0, Vec::len)
|
||||
}
|
||||
|
||||
/// The commands journaled from entry `start` on.
|
||||
fn journaled(s: &Session, start: usize) -> Vec<String> {
|
||||
s.journal.iter().skip(start).map(|(id, _)| id.clone()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_command_during_a_drag_is_a_step_of_its_own_before_the_drag() {
|
||||
for real_time in [true, false] {
|
||||
let (mut s, other) = session(real_time);
|
||||
let (steps, start) = (s.doc().unwrap().history.undo.len(), s.journal.len());
|
||||
pointer(&mut s, PointerKind::Down, 100.0, 100.0);
|
||||
pointer(&mut s, PointerKind::Drag, 150.0, 150.0);
|
||||
s.execute("object.hide", &json!({"ids": [other.0]})).unwrap();
|
||||
assert!(!visible(&s, other), "real time {real_time}: the command hides the object at once");
|
||||
pointer(&mut s, PointerKind::Drag, 200.0, 180.0);
|
||||
assert!(!visible(&s, other), "real time {real_time}: the drag's next preview keeps the command's edit");
|
||||
pointer(&mut s, PointerKind::Up, 200.0, 180.0);
|
||||
assert!(!visible(&s, other), "real time {real_time}: the release keeps the command's edit");
|
||||
assert_eq!(objects(&s), 2, "real time {real_time}: the release draws the rectangle");
|
||||
let drawn = s.doc().unwrap().selection.objects[0];
|
||||
assert_ne!(drawn, other);
|
||||
assert_eq!(s.doc().unwrap().doc.bounds_of(&[drawn], false), Some(Rect::new(100.0, 100.0, 200.0, 180.0)), "real time {real_time}");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 2, "real time {real_time}: the command and the drag are a step each");
|
||||
assert_eq!(journaled(&s, start), ["object.hide", "shape.rectangle"], "real time {real_time}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(objects(&s), 1, "real time {real_time}: Undo takes back the drawn rectangle");
|
||||
assert!(!visible(&s, other), "real time {real_time}: and leaves the command's edit");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(visible(&s, other), "real time {real_time}: the next Undo takes back the command's edit");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn escape_after_a_command_during_a_drag_keeps_the_command() {
|
||||
for real_time in [true, false] {
|
||||
let (mut s, other) = session(real_time);
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
pointer(&mut s, PointerKind::Down, 100.0, 100.0);
|
||||
pointer(&mut s, PointerKind::Drag, 150.0, 150.0);
|
||||
s.execute("object.hide", &json!({"ids": [other.0]})).unwrap();
|
||||
s.tool_key(ToolKey::Escape, Mods::default(), view()).unwrap();
|
||||
pointer(&mut s, PointerKind::Up, 150.0, 150.0);
|
||||
assert!(!visible(&s, other), "real time {real_time}: Escape takes back only the drag");
|
||||
assert_eq!(objects(&s), 1, "real time {real_time}: nothing is drawn");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "real time {real_time}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(visible(&s, other), "real time {real_time}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Every object of the first layer but `other`, as the document has it.
|
||||
fn others(s: &Session, other: NodeId) -> Vec<vectorcraft_doc::Node> {
|
||||
let d = &s.doc().unwrap().doc;
|
||||
d.layers[0].children().map_or_else(Vec::new, |c| c.iter().filter(|n| n.id != other).map(|n| (**n).clone()).collect())
|
||||
}
|
||||
|
||||
/// A new 400 × 400 pt document with Real-time Drawing `real_time`, holding a 40 × 40 pt square at
|
||||
/// (100, 100) and a 20 × 20 pt one at (10, 10) → the session, the larger square (selected) and the
|
||||
/// smaller one.
|
||||
fn two_squares(real_time: bool) -> (Session, NodeId, NodeId) {
|
||||
let mut s = Session::new();
|
||||
s.prefs.real_time_drawing = real_time;
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap();
|
||||
let other = s.doc().unwrap().selection.objects[0];
|
||||
s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 40, "height": 40})).unwrap();
|
||||
let target = s.doc().unwrap().selection.objects[0];
|
||||
(s, target, other)
|
||||
}
|
||||
|
||||
/// A press at the first point of `pts`, drags to the others and a release at the last, with
|
||||
/// `mid` run after the first drag.
|
||||
fn drag_with(s: &mut Session, pts: &[(f64, f64)], mid: impl FnOnce(&mut Session)) {
|
||||
let (&(x0, y0), rest) = pts.split_first().expect("a press");
|
||||
pointer(s, PointerKind::Down, x0, y0);
|
||||
let mut mid = Some(mid);
|
||||
for &(x, y) in rest {
|
||||
pointer(s, PointerKind::Drag, x, y);
|
||||
if let Some(f) = mid.take() {
|
||||
f(s);
|
||||
}
|
||||
}
|
||||
let &(x, y) = pts.last().expect("a release");
|
||||
pointer(s, PointerKind::Up, x, y);
|
||||
}
|
||||
|
||||
/// Is `id` filled red?
|
||||
fn red(s: &Session, id: NodeId) -> bool {
|
||||
s.doc().unwrap().doc.node(id).and_then(|n| n.appearance.fill_paint().color()).is_some_and(|c| c.to_hex() == "#ff0000")
|
||||
}
|
||||
|
||||
/// The Selection tool's move, the Scale and Rotate tools and the Pen, each with a command that
|
||||
/// fills another object red during the drag: the release keeps both, as two undo steps, and Undo
|
||||
/// takes back the drag first.
|
||||
#[test]
|
||||
fn the_move_scale_rotate_and_pen_drags_keep_a_command_run_during_them() {
|
||||
let drags: [(&str, &[(f64, f64)]); 4] = [
|
||||
("selection", &[(120.0, 120.0), (140.0, 130.0), (170.0, 150.0)]),
|
||||
("scale", &[(150.0, 150.0), (170.0, 170.0), (190.0, 190.0)]),
|
||||
("rotate", &[(160.0, 120.0), (150.0, 150.0), (120.0, 160.0)]),
|
||||
("pen", &[(300.0, 300.0), (320.0, 300.0), (350.0, 320.0)]),
|
||||
];
|
||||
for (tool, pts) in drags {
|
||||
for real_time in [true, false] {
|
||||
let at = format!("{tool}, real time {real_time}");
|
||||
let (mut s, _, other) = two_squares(real_time);
|
||||
if tool == "pen" {
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
}
|
||||
s.select_tool(tool, view()).unwrap();
|
||||
let (before, steps) = (others(&s, other), s.doc().unwrap().history.undo.len());
|
||||
drag_with(&mut s, pts, |s| {
|
||||
s.execute("paint.setFill", &json!({"ids": [other.0], "color": "#ff0000"})).unwrap();
|
||||
});
|
||||
assert!(!s.in_interaction(), "{at}");
|
||||
assert!(red(&s, other), "{at}: the release keeps the command's edit");
|
||||
assert_ne!(others(&s, other), before, "{at}: the release keeps the drag's edit");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 2, "{at}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(others(&s, other), before, "{at}: Undo takes back the drag");
|
||||
assert!(red(&s, other), "{at}: and leaves the command's edit");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(!red(&s, other), "{at}: the next Undo takes back the command's edit");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A command that changes the object being moved: the move applies to the changed object.
|
||||
#[test]
|
||||
fn a_move_drag_moves_the_object_as_a_command_during_it_changed_it() {
|
||||
for real_time in [true, false] {
|
||||
let (mut s, target, _) = two_squares(real_time);
|
||||
s.select_tool("selection", view()).unwrap();
|
||||
let fill = |s: &Session| s.doc().unwrap().doc.node(target).unwrap().appearance.fill_paint().color().map(|c| c.to_hex());
|
||||
let was = fill(&s);
|
||||
drag_with(&mut s, &[(120.0, 120.0), (140.0, 130.0), (170.0, 150.0)], |s| {
|
||||
s.execute("paint.setFill", &json!({"ids": [target.0], "color": "#ff0000"})).unwrap();
|
||||
});
|
||||
let moved = s.doc().unwrap().doc.bounds_of(&[target], false);
|
||||
assert_eq!(moved, Some(Rect::new(150.0, 130.0, 190.0, 170.0)), "real time {real_time}");
|
||||
assert_eq!(fill(&s).as_deref(), Some("#ff0000"), "real time {real_time}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.bounds_of(&[target], false), Some(Rect::new(100.0, 100.0, 140.0, 140.0)), "real time {real_time}");
|
||||
assert_eq!(fill(&s).as_deref(), Some("#ff0000"), "real time {real_time}: the fill is a step of its own");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(fill(&s), was, "real time {real_time}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A command that deletes the object being moved: the drag goes on and ends without an edit of
|
||||
/// its own, on release and on Escape, and the deletion stays.
|
||||
#[test]
|
||||
fn a_move_drag_of_an_object_a_command_deleted_ends_without_an_edit() {
|
||||
for (real_time, escape) in [(true, false), (false, false), (true, true), (false, true)] {
|
||||
let at = format!("real time {real_time}, Escape {escape}");
|
||||
let (mut s, target, other) = two_squares(real_time);
|
||||
s.select_tool("selection", view()).unwrap();
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
pointer(&mut s, PointerKind::Down, 120.0, 120.0);
|
||||
pointer(&mut s, PointerKind::Drag, 140.0, 130.0);
|
||||
s.execute("edit.clear", &json!({"ids": [target.0]})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.node(target).is_none(), "{at}");
|
||||
pointer(&mut s, PointerKind::Drag, 170.0, 150.0);
|
||||
if escape {
|
||||
s.tool_key(ToolKey::Escape, Mods::default(), view()).unwrap();
|
||||
}
|
||||
pointer(&mut s, PointerKind::Up, 170.0, 150.0);
|
||||
assert!(!s.in_interaction(), "{at}");
|
||||
assert!(s.doc().unwrap().doc.node(target).is_none(), "{at}: the deletion stays");
|
||||
assert_eq!(others(&s, other), [], "{at}");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "{at}: only the deletion is a step");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.bounds_of(&[target], false), Some(Rect::new(100.0, 100.0, 140.0, 140.0)), "{at}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A command that hides or locks the object being moved: the object stays where it was and
|
||||
/// unselected, and the drag ends without an edit of its own.
|
||||
#[test]
|
||||
fn a_move_drag_of_an_object_a_command_hid_or_locked_leaves_it_alone() {
|
||||
for command in ["object.hide", "object.lock"] {
|
||||
for real_time in [true, false] {
|
||||
let at = format!("{command}, real time {real_time}");
|
||||
let (mut s, target, _) = two_squares(real_time);
|
||||
s.select_tool("selection", view()).unwrap();
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
drag_with(&mut s, &[(120.0, 120.0), (140.0, 130.0), (170.0, 150.0)], |s| {
|
||||
s.execute(command, &json!({"ids": [target.0]})).unwrap();
|
||||
});
|
||||
assert!(!s.in_interaction(), "{at}");
|
||||
assert_eq!(s.doc().unwrap().doc.bounds_of(&[target], false), Some(Rect::new(100.0, 100.0, 140.0, 140.0)), "{at}: not moved");
|
||||
assert!(!s.doc().unwrap().selection.objects.contains(&target), "{at}: not selected");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "{at}: only the command is a step");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The commands that end a drag first still do: Undo during a drag keeps the drag as a step and
|
||||
/// takes it back, and `command.batch` and `swatch.renameGroup` keep it as a step before their own.
|
||||
#[test]
|
||||
fn undo_and_a_batch_during_a_drag_still_keep_the_drag_first() {
|
||||
for real_time in [true, false] {
|
||||
let (mut s, target, other) = two_squares(real_time);
|
||||
s.select_tool("selection", view()).unwrap();
|
||||
pointer(&mut s, PointerKind::Down, 120.0, 120.0);
|
||||
pointer(&mut s, PointerKind::Drag, 170.0, 150.0);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(!s.in_interaction(), "real time {real_time}");
|
||||
assert_eq!(s.doc().unwrap().doc.bounds_of(&[target], false), Some(Rect::new(100.0, 100.0, 140.0, 140.0)), "real time {real_time}");
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.bounds_of(&[target], false), Some(Rect::new(150.0, 130.0, 190.0, 170.0)), "real time {real_time}");
|
||||
pointer(&mut s, PointerKind::Up, 170.0, 150.0);
|
||||
|
||||
let (mut s, target, other2) = two_squares(real_time);
|
||||
assert_eq!(other, other2);
|
||||
s.select_tool("selection", view()).unwrap();
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
pointer(&mut s, PointerKind::Down, 120.0, 120.0);
|
||||
pointer(&mut s, PointerKind::Drag, 170.0, 150.0);
|
||||
s.execute("command.batch", &json!({"commands": [{"command": "object.hide", "params": {"ids": [other.0]}}]})).unwrap();
|
||||
assert!(!s.in_interaction(), "real time {real_time}: the batch keeps the drag first");
|
||||
pointer(&mut s, PointerKind::Up, 170.0, 150.0);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 2, "real time {real_time}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(visible(&s, other), "real time {real_time}: Undo takes back the batch first");
|
||||
assert_eq!(s.doc().unwrap().doc.bounds_of(&[target], false), Some(Rect::new(150.0, 130.0, 190.0, 170.0)), "real time {real_time}");
|
||||
|
||||
// A color group renamed during the drag keeps the drag as a step before the rename.
|
||||
let (mut s, target, _) = two_squares(real_time);
|
||||
s.select_tool("selection", view()).unwrap();
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
pointer(&mut s, PointerKind::Down, 120.0, 120.0);
|
||||
pointer(&mut s, PointerKind::Drag, 170.0, 150.0);
|
||||
s.execute("swatch.renameGroup", &json!({"group": "Brights", "name": "Vivid"})).unwrap();
|
||||
assert!(!s.in_interaction(), "real time {real_time}: the rename keeps the drag first");
|
||||
pointer(&mut s, PointerKind::Up, 170.0, 150.0);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 2, "real time {real_time}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.swatch_groups.iter().any(|g| g.name == "Brights"), "real time {real_time}: Undo takes back the rename");
|
||||
assert_eq!(s.doc().unwrap().doc.bounds_of(&[target], false), Some(Rect::new(150.0, 130.0, 190.0, 170.0)), "real time {real_time}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A copy made with `object.transform` during an Alt-drag runs inside the drag, with Real-time
|
||||
/// Drawing on and off: the release records one step that holds both.
|
||||
#[test]
|
||||
fn a_copy_during_an_alt_drag_is_part_of_the_drag() {
|
||||
for real_time in [true, false] {
|
||||
let (mut s, target, _) = two_squares(real_time);
|
||||
s.select_tool("selection", view()).unwrap();
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
let alt = Mods { alt: true, ..Mods::default() };
|
||||
for (kind, x, y) in [(PointerKind::Down, 120.0, 120.0), (PointerKind::Drag, 170.0, 150.0)] {
|
||||
s.pointer(&PointerEvent::new(kind, x, y).with_mods(alt), view()).unwrap();
|
||||
}
|
||||
s.execute("object.transform", &json!({"matrix": [1, 0, 0, 1, 0, 60], "copy": true, "ids": [target.0]})).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 170.0, 150.0).with_mods(alt), view()).unwrap();
|
||||
assert!(!s.in_interaction(), "real time {real_time}");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "real time {real_time}: one step for the drag and the copy");
|
||||
|
||||
// With Alt let go during the drag, the drag moves again, and the copy is a step of its own.
|
||||
let (mut s, target, _) = two_squares(real_time);
|
||||
s.select_tool("selection", view()).unwrap();
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 120.0, 120.0).with_mods(alt), view()).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 150.0, 140.0).with_mods(alt), view()).unwrap();
|
||||
pointer(&mut s, PointerKind::Drag, 170.0, 150.0);
|
||||
s.execute("object.transform", &json!({"matrix": [1, 0, 0, 1, 0, 60], "copy": true, "ids": [target.0]})).unwrap();
|
||||
pointer(&mut s, PointerKind::Up, 170.0, 150.0);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 2, "real time {real_time}: the copy and the move");
|
||||
}
|
||||
}
|
||||
|
||||
/// A command that changes only the current layer during a drag keeps its change through Escape.
|
||||
#[test]
|
||||
fn escape_keeps_a_current_layer_set_during_a_drag() {
|
||||
for real_time in [true, false] {
|
||||
let (mut s, _) = session(real_time);
|
||||
let first = s.doc().unwrap().active_layer;
|
||||
let second = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let first = first.expect("a current layer");
|
||||
s.execute("layer.setCurrent", &json!({"id": first.0})).unwrap();
|
||||
pointer(&mut s, PointerKind::Down, 100.0, 100.0);
|
||||
pointer(&mut s, PointerKind::Drag, 150.0, 150.0);
|
||||
s.execute("layer.setCurrent", &json!({"id": second.0})).unwrap();
|
||||
s.tool_key(ToolKey::Escape, Mods::default(), view()).unwrap();
|
||||
pointer(&mut s, PointerKind::Up, 150.0, 150.0);
|
||||
assert_eq!(s.doc().unwrap().active_layer, Some(second), "real time {real_time}");
|
||||
}
|
||||
}
|
||||
|
||||
/// With Real-time Drawing on, the drag's preview is on show again right after the command.
|
||||
#[test]
|
||||
fn the_drag_preview_shows_again_after_the_command() {
|
||||
let (mut s, other) = session(true);
|
||||
pointer(&mut s, PointerKind::Down, 100.0, 100.0);
|
||||
pointer(&mut s, PointerKind::Drag, 150.0, 150.0);
|
||||
assert_eq!(objects(&s), 2, "the preview draws the rectangle");
|
||||
s.execute("object.hide", &json!({"ids": [other.0]})).unwrap();
|
||||
assert_eq!(objects(&s), 2, "the preview is on show after the command");
|
||||
s.execute("object.showAll", &json!({})).unwrap();
|
||||
assert_eq!(objects(&s), 2, "and after a second one");
|
||||
assert!(visible(&s, other));
|
||||
assert!(s.in_interaction());
|
||||
pointer(&mut s, PointerKind::Up, 150.0, 150.0);
|
||||
assert_eq!(objects(&s), 2);
|
||||
assert!(visible(&s, other));
|
||||
}
|
||||
|
||||
/// A command that changes the selection during a move drag (Select All, Deselect, a duplicate)
|
||||
/// leaves the drag moving the object it began with.
|
||||
#[test]
|
||||
fn a_selection_made_during_a_move_drag_leaves_the_drag_moving_its_object() {
|
||||
for command in ["select.all", "select.none", "edit.duplicate"] {
|
||||
for real_time in [true, false] {
|
||||
let at = format!("{command}, real time {real_time}");
|
||||
let (mut s, target, other) = two_squares(real_time);
|
||||
s.select_tool("selection", view()).unwrap();
|
||||
drag_with(&mut s, &[(120.0, 120.0), (140.0, 130.0), (170.0, 150.0)], |s| {
|
||||
s.execute(command, &json!({})).unwrap();
|
||||
});
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.bounds_of(&[target], false), Some(Rect::new(150.0, 130.0, 190.0, 170.0)), "{at}: the drag moves its object");
|
||||
assert_eq!(d.bounds_of(&[other], false), Some(Rect::new(10.0, 10.0, 30.0, 30.0)), "{at}: and nothing else");
|
||||
if command == "edit.duplicate" {
|
||||
let copies = others(&s, other).into_iter().filter(|n| n.id != target).map(|n| n.id).collect::<Vec<_>>();
|
||||
assert_eq!(copies.len(), 1, "{at}");
|
||||
assert_eq!(d.bounds_of(&copies, false), Some(Rect::new(100.0, 100.0, 140.0, 140.0)), "{at}: the copy stays where it was made");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A command that selects another object during a move drag: the drag's object stays selected,
|
||||
/// and the fill and stroke proxies keep showing its paints.
|
||||
#[test]
|
||||
fn a_selection_made_during_a_move_drag_leaves_the_paints_of_the_drag_object() {
|
||||
for real_time in [true, false] {
|
||||
let at = format!("real time {real_time}");
|
||||
let (mut s, target, other) = two_squares(real_time);
|
||||
s.execute("paint.setFill", &json!({"ids": [target.0], "color": "#ff0000"})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"ids": [other.0], "color": "#0000ff"})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [target.0]})).unwrap();
|
||||
s.select_tool("selection", view()).unwrap();
|
||||
let fill = |s: &Session| s.paint.fill.color().map(|c| c.to_hex());
|
||||
assert_eq!(fill(&s).as_deref(), Some("#ff0000"), "{at}");
|
||||
pointer(&mut s, PointerKind::Down, 120.0, 120.0);
|
||||
pointer(&mut s, PointerKind::Drag, 140.0, 130.0);
|
||||
s.execute("select.set", &json!({"ids": [other.0]})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().selection.objects, [target], "{at}");
|
||||
assert_eq!(fill(&s).as_deref(), Some("#ff0000"), "{at}: after the command");
|
||||
pointer(&mut s, PointerKind::Drag, 170.0, 150.0);
|
||||
pointer(&mut s, PointerKind::Up, 170.0, 150.0);
|
||||
assert_eq!(s.doc().unwrap().selection.objects, [target], "{at}");
|
||||
assert_eq!(fill(&s).as_deref(), Some("#ff0000"), "{at}: after the release");
|
||||
}
|
||||
}
|
||||
|
||||
/// Replay the journal of `s` from `start` on `replayed`.
|
||||
fn replay_from(s: &Session, start: usize, replayed: &mut Session) {
|
||||
for (id, p) in s.journal.iter().skip(start) {
|
||||
replayed.replay(id, p).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
/// The journal of a move drag with a selection command run during it replays as the drag went:
|
||||
/// the drag moves its own object, not the one the command selected.
|
||||
#[test]
|
||||
fn a_move_drag_after_a_selection_command_replays_on_its_own_object() {
|
||||
for real_time in [true, false] {
|
||||
let at = format!("real time {real_time}");
|
||||
let (mut s, target, other) = two_squares(real_time);
|
||||
s.select_tool("selection", view()).unwrap();
|
||||
let start = s.journal.len();
|
||||
drag_with(&mut s, &[(120.0, 120.0), (140.0, 130.0), (170.0, 150.0)], |s| {
|
||||
s.execute("select.set", &json!({"ids": [other.0]})).unwrap();
|
||||
});
|
||||
let bounds = |s: &Session| {
|
||||
let d = &s.doc().unwrap().doc;
|
||||
(d.bounds_of(&[target], false), d.bounds_of(&[other], false))
|
||||
};
|
||||
assert_eq!(bounds(&s), (Some(Rect::new(150.0, 130.0, 190.0, 170.0)), Some(Rect::new(10.0, 10.0, 30.0, 30.0))), "{at}");
|
||||
let (mut replayed, _, _) = two_squares(real_time);
|
||||
replay_from(&s, start, &mut replayed);
|
||||
assert_eq!(bounds(&replayed), bounds(&s), "{at}: {:?}", journaled(&s, start));
|
||||
assert_eq!(replayed.doc().unwrap().selection.objects, s.doc().unwrap().selection.objects, "{at}");
|
||||
assert_eq!(replayed.doc().unwrap().active_layer, s.doc().unwrap().active_layer, "{at}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Find Objects with `select` during a drag is a step of its own, as it is journaled: it finds and
|
||||
/// selects only the objects outside the drag's preview, as its replay before the drag does.
|
||||
#[test]
|
||||
fn find_objects_with_select_during_a_drag_skips_the_drag_preview() {
|
||||
for real_time in [true, false] {
|
||||
let at = format!("real time {real_time}");
|
||||
let (mut s, other) = session(real_time);
|
||||
let start = s.journal.len();
|
||||
let find = json!({"intersects": [0, 0, 400, 400], "select": true});
|
||||
pointer(&mut s, PointerKind::Down, 100.0, 100.0);
|
||||
pointer(&mut s, PointerKind::Drag, 150.0, 150.0);
|
||||
let r = s.execute("document.find", &find).unwrap();
|
||||
assert_eq!(r["total"], 1, "{at}: {r}");
|
||||
assert_eq!(r["matches"][0]["id"], other.0, "{at}: {r}");
|
||||
pointer(&mut s, PointerKind::Up, 200.0, 180.0);
|
||||
assert_eq!(objects(&s), 2, "{at}: the release draws the rectangle");
|
||||
// The drag's own selection is journaled after the find, so the release replays on it.
|
||||
assert_eq!(journaled(&s, start), ["document.find", "select.set", "shape.rectangle"], "{at}");
|
||||
let (mut replayed, _) = session(real_time);
|
||||
replay_from(&s, start, &mut replayed);
|
||||
assert_eq!(objects(&replayed), 2, "{at}");
|
||||
assert_eq!(replayed.doc().unwrap().selection.objects, s.doc().unwrap().selection.objects, "{at}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A square on a second layer selected with a ruler guide, and a square on the first layer →
|
||||
/// the session (with Real-time Drawing `real_time`) and the square on the first layer.
|
||||
fn square_and_guide(real_time: bool) -> (Session, NodeId) {
|
||||
let mut s = Session::new();
|
||||
s.prefs.real_time_drawing = real_time;
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap();
|
||||
let other = s.doc().unwrap().selection.objects[0];
|
||||
s.execute("layer.new", &json!({})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 40, "height": 40})).unwrap();
|
||||
let target = s.doc().unwrap().selection.objects[0];
|
||||
s.execute("guide.add", &json!({"vertical": true, "pos": 300})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [target.0]})).unwrap();
|
||||
s.execute("guide.select", &json!({"indexes": [0], "toggle": true})).unwrap();
|
||||
(s, other)
|
||||
}
|
||||
|
||||
/// The journal of a move drag of a square and a ruler guide, with a command during it that
|
||||
/// selects an object on another layer, replays with the drag's selection, guide included, with
|
||||
/// the layer the command made current and with the Layers panel rows the command left highlighted.
|
||||
#[test]
|
||||
fn a_move_drag_of_a_guide_after_a_selection_command_replays_its_selection_and_layer() {
|
||||
for real_time in [true, false] {
|
||||
let at = format!("real time {real_time}");
|
||||
let (mut s, other) = square_and_guide(real_time);
|
||||
s.select_tool("selection", view()).unwrap();
|
||||
let start = s.journal.len();
|
||||
drag_with(&mut s, &[(120.0, 120.0), (140.0, 130.0), (170.0, 150.0)], |s| {
|
||||
s.execute("select.set", &json!({"ids": [other.0]})).unwrap();
|
||||
});
|
||||
let (mut replayed, _) = square_and_guide(real_time);
|
||||
replay_from(&s, start, &mut replayed);
|
||||
let state = |s: &mut Session| {
|
||||
let d = s.doc().unwrap();
|
||||
let state = (
|
||||
d.selection.objects.clone(),
|
||||
d.selection.guides.clone(),
|
||||
d.active_layer,
|
||||
d.highlighted_rows(),
|
||||
d.doc.bounds_of(&d.selection.objects, false),
|
||||
);
|
||||
(state, s.execute("guide.list", &json!({})).unwrap())
|
||||
};
|
||||
assert_eq!(state(&mut replayed), state(&mut s), "{at}: {:?}", journaled(&s, start));
|
||||
}
|
||||
}
|
||||
|
||||
/// The journal of a move drag of a targeted square, with a command during it that selects another
|
||||
/// square, replays with the square targeted, as the drag leaves it.
|
||||
#[test]
|
||||
fn a_move_drag_of_a_targeted_object_after_a_selection_command_replays_its_target() {
|
||||
for real_time in [true, false] {
|
||||
let at = format!("real time {real_time}");
|
||||
let setup = || {
|
||||
let (mut s, target, other) = two_squares(real_time);
|
||||
s.execute("layer.target", &json!({"id": target.0})).unwrap();
|
||||
s.select_tool("selection", view()).unwrap();
|
||||
(s, other)
|
||||
};
|
||||
let (mut s, other) = setup();
|
||||
let start = s.journal.len();
|
||||
drag_with(&mut s, &[(120.0, 120.0), (140.0, 130.0), (170.0, 150.0)], |s| {
|
||||
s.execute("select.set", &json!({"ids": [other.0]})).unwrap();
|
||||
});
|
||||
let (mut replayed, _) = setup();
|
||||
replay_from(&s, start, &mut replayed);
|
||||
let state = |s: &Session| {
|
||||
let d = s.doc().unwrap();
|
||||
(d.selection.objects.clone(), d.selection.target, d.doc.bounds_of(&d.selection.objects, false))
|
||||
};
|
||||
assert_eq!(state(&replayed), state(&s), "{at}: {:?}", journaled(&s, start));
|
||||
}
|
||||
}
|
||||
|
||||
/// The journal of a move drag of a targeted square and a ruler guide, with a command during it
|
||||
/// that selects another square, replays with the square targeted and the guide selected.
|
||||
#[test]
|
||||
fn a_move_drag_of_a_targeted_object_and_a_guide_after_a_selection_command_replays_both() {
|
||||
for real_time in [true, false] {
|
||||
let at = format!("real time {real_time}");
|
||||
let setup = || {
|
||||
let (mut s, target, other) = two_squares(real_time);
|
||||
s.execute("guide.add", &json!({"vertical": true, "pos": 300})).unwrap();
|
||||
s.execute("layer.target", &json!({"id": target.0})).unwrap();
|
||||
s.execute("guide.select", &json!({"indexes": [0], "toggle": true})).unwrap();
|
||||
s.select_tool("selection", view()).unwrap();
|
||||
(s, target, other)
|
||||
};
|
||||
let (mut s, target, other) = setup();
|
||||
let start = s.journal.len();
|
||||
drag_with(&mut s, &[(120.0, 120.0), (140.0, 130.0), (170.0, 150.0)], |s| {
|
||||
s.execute("select.set", &json!({"ids": [other.0]})).unwrap();
|
||||
});
|
||||
let state = |s: &mut Session| {
|
||||
let d = s.doc().unwrap();
|
||||
let state = (d.selection.objects.clone(), d.selection.target, d.selection.guides.clone(), d.doc.bounds_of(&d.selection.objects, false));
|
||||
(state, s.execute("guide.list", &json!({})).unwrap())
|
||||
};
|
||||
let live = state(&mut s);
|
||||
assert_eq!((live.0.1, live.0.2.len()), (Some(target), 1), "{at}: the drag leaves the square targeted and the guide selected");
|
||||
let (mut replayed, _, _) = setup();
|
||||
replay_from(&s, start, &mut replayed);
|
||||
assert_eq!(state(&mut replayed), live, "{at}: {:?}", journaled(&s, start));
|
||||
}
|
||||
}
|
||||
|
||||
/// The journal of a move drag of a path with every anchor selected as anchor points, with a
|
||||
/// command during it that selects another square, replays with those anchors selected.
|
||||
#[test]
|
||||
fn a_move_drag_of_every_anchor_of_a_path_after_a_selection_command_replays_its_anchors() {
|
||||
for real_time in [true, false] {
|
||||
let at = format!("real time {real_time}");
|
||||
let setup = || {
|
||||
let (mut s, target, other) = two_squares(real_time);
|
||||
s.execute("select.set", &json!({"ids": [target.0]})).unwrap();
|
||||
s.execute("select.anchors", &json!({"id": target.0, "anchors": [[0, 0]], "mode": "add"})).unwrap();
|
||||
s.select_tool("selection", view()).unwrap();
|
||||
(s, target, other)
|
||||
};
|
||||
let (mut s, target, other) = setup();
|
||||
let every = s.doc().unwrap().selection.anchors.get(&target).cloned();
|
||||
assert!(every.as_ref().is_some_and(|a| a.len() > 1), "{at}: {every:?}");
|
||||
let start = s.journal.len();
|
||||
drag_with(&mut s, &[(120.0, 120.0), (140.0, 130.0), (170.0, 150.0)], |s| {
|
||||
s.execute("select.set", &json!({"ids": [other.0]})).unwrap();
|
||||
});
|
||||
let state = |s: &Session| {
|
||||
let d = s.doc().unwrap();
|
||||
(d.selection.objects.clone(), d.selection.anchors.clone(), d.doc.bounds_of(&d.selection.objects, false))
|
||||
};
|
||||
assert_eq!(state(&s).1.get(&target), every.as_ref(), "{at}: the drag leaves every anchor selected as anchors");
|
||||
let (mut replayed, _, _) = setup();
|
||||
replay_from(&s, start, &mut replayed);
|
||||
assert_eq!(state(&replayed), state(&s), "{at}: {:?}", journaled(&s, start));
|
||||
}
|
||||
}
|
||||
|
||||
/// The journal of a move drag of a targeted layer's art, with a duplicate made on that layer
|
||||
/// during it, replays with the drag moving its own objects, not the duplicates.
|
||||
#[test]
|
||||
fn a_move_drag_of_a_targeted_layer_after_a_duplicate_replays_its_objects() {
|
||||
for real_time in [true, false] {
|
||||
let at = format!("real time {real_time}");
|
||||
let setup = || {
|
||||
let (mut s, _, _) = two_squares(real_time);
|
||||
let layer = s.doc().unwrap().doc.layers[0].id;
|
||||
s.execute("layer.target", &json!({"id": layer.0})).unwrap();
|
||||
s.select_tool("selection", view()).unwrap();
|
||||
s
|
||||
};
|
||||
let mut s = setup();
|
||||
let start = s.journal.len();
|
||||
drag_with(&mut s, &[(120.0, 120.0), (140.0, 130.0), (170.0, 150.0)], |s| {
|
||||
s.execute("edit.duplicate", &json!({})).unwrap();
|
||||
});
|
||||
let mut replayed = setup();
|
||||
replay_from(&s, start, &mut replayed);
|
||||
let state = |s: &Session| {
|
||||
let d = s.doc().unwrap();
|
||||
(d.selection.objects.clone(), d.doc.bounds_of(&d.selection.objects, false), objects(s))
|
||||
};
|
||||
assert_eq!(state(&replayed), state(&s), "{at}: {:?}", journaled(&s, start));
|
||||
}
|
||||
}
|
||||
|
||||
/// A selected user slice and a square → the session (with Real-time Drawing `real_time`), the
|
||||
/// slice and the square.
|
||||
fn slice_and_square(real_time: bool) -> (Session, NodeId, NodeId) {
|
||||
let mut s = Session::new();
|
||||
s.prefs.real_time_drawing = real_time;
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap();
|
||||
let other = s.doc().unwrap().selection.objects[0];
|
||||
let slice = s.execute("object.slice.create", &json!({"x": 200, "y": 200, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("object.slice.select", &json!({"slices": [slice]})).unwrap();
|
||||
(s, NodeId(slice), other)
|
||||
}
|
||||
|
||||
/// The journal of a Slice Selection drag, with a command during it that selects an object,
|
||||
/// replays with the slice selected, as the drag leaves it.
|
||||
#[test]
|
||||
fn a_slice_drag_after_a_selection_command_replays_its_slice_selection() {
|
||||
for real_time in [true, false] {
|
||||
let at = format!("real time {real_time}");
|
||||
let (mut s, slice, other) = slice_and_square(real_time);
|
||||
s.select_tool("sliceSelection", view()).unwrap();
|
||||
let start = s.journal.len();
|
||||
drag_with(&mut s, &[(220.0, 220.0), (230.0, 230.0), (240.0, 240.0)], |s| {
|
||||
s.execute("select.set", &json!({"ids": [other.0]})).unwrap();
|
||||
});
|
||||
assert_eq!(s.doc().unwrap().selection.slices, [slice], "{at}");
|
||||
let (mut replayed, _, _) = slice_and_square(real_time);
|
||||
replay_from(&s, start, &mut replayed);
|
||||
let state = |s: &Session| {
|
||||
let sel = &s.doc().unwrap().selection;
|
||||
(sel.objects.clone(), sel.slices.clone())
|
||||
};
|
||||
assert_eq!(state(&replayed), state(&s), "{at}: {:?}", journaled(&s, start));
|
||||
}
|
||||
}
|
||||
|
||||
/// A Warp stroke over two selected squares, with a command that deletes one of them during the
|
||||
/// stroke: the release still warps the other square, and the stroke's journal entry names it.
|
||||
#[test]
|
||||
fn a_warp_stroke_over_an_object_a_command_deleted_still_warps_the_others() {
|
||||
for real_time in [true, false] {
|
||||
let at = format!("real time {real_time}");
|
||||
let (mut s, target, other) = two_squares(real_time);
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
s.select_tool("warp", view()).unwrap();
|
||||
let before = s.doc().unwrap().doc.node(target).cloned();
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
pointer(&mut s, PointerKind::Down, 120.0, 120.0);
|
||||
pointer(&mut s, PointerKind::Drag, 135.0, 125.0);
|
||||
let r = s.execute("edit.clear", &json!({"ids": [other.0]})).unwrap();
|
||||
assert!(r.get("warning").is_none(), "{at}: {r}");
|
||||
pointer(&mut s, PointerKind::Up, 135.0, 125.0);
|
||||
assert!(!s.in_interaction(), "{at}");
|
||||
assert!(s.doc().unwrap().doc.node(other).is_none(), "{at}: the deletion stays");
|
||||
assert_ne!(s.doc().unwrap().doc.node(target).cloned(), before, "{at}: the release warps the other square");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 2, "{at}: the deletion and the stroke are a step each");
|
||||
let (id, p) = s.journal.last().unwrap();
|
||||
assert_eq!((id.as_str(), &p["ids"]), ("object.liquify", &json!([target.0])), "{at}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The Scale and Rotate tools and the Pen adding to a path, with a command that deletes the
|
||||
/// object they act on during the drag: the drag ends without an edit of its own and the deletion
|
||||
/// stays.
|
||||
#[test]
|
||||
fn a_scale_rotate_or_pen_drag_of_an_object_a_command_deleted_ends_without_an_edit() {
|
||||
let drags: [(&str, &[(f64, f64)]); 3] = [
|
||||
("scale", &[(150.0, 150.0), (170.0, 170.0), (190.0, 190.0)]),
|
||||
("rotate", &[(160.0, 120.0), (150.0, 150.0), (120.0, 160.0)]),
|
||||
("pen", &[(350.0, 350.0), (370.0, 360.0), (380.0, 380.0)]),
|
||||
];
|
||||
for (tool, pts) in drags {
|
||||
for real_time in [true, false] {
|
||||
let at = format!("{tool}, real time {real_time}");
|
||||
let (mut s, target, _) = two_squares(real_time);
|
||||
s.select_tool(tool, view()).unwrap();
|
||||
let target = if tool == "pen" {
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
for (x, y) in [(300.0, 300.0), (350.0, 300.0)] {
|
||||
pointer(&mut s, PointerKind::Down, x, y);
|
||||
pointer(&mut s, PointerKind::Up, x, y);
|
||||
}
|
||||
s.doc().unwrap().selection.objects[0]
|
||||
} else {
|
||||
target
|
||||
};
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
drag_with(&mut s, pts, |s| {
|
||||
s.execute("edit.clear", &json!({"ids": [target.0]})).unwrap();
|
||||
});
|
||||
assert!(!s.in_interaction(), "{at}");
|
||||
assert!(s.doc().unwrap().doc.node(target).is_none(), "{at}: the deletion stays");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "{at}: only the deletion is a step");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(*s.doc().unwrap().doc, *before, "{at}: Undo brings the object back as it was");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A Direct Selection drag of an anchor, with a command during it that numbers the path's anchors
|
||||
/// anew (Add Anchor Point before the dragged one, Reverse Path Direction): the command's edit
|
||||
/// stays, the drag ends without an edit of its own and moves no other anchor of the path.
|
||||
#[test]
|
||||
fn an_anchor_drag_after_a_command_renumbers_its_anchors_moves_no_other_anchor() {
|
||||
let commands = [("path.insertAnchor", json!({"segment": 0, "t": 0.5}), 1), ("path.reverse", json!({}), 0)];
|
||||
for ((id, params, added), real_time) in commands.iter().flat_map(|c| [(c, true), (c, false)]) {
|
||||
let at = format!("{id}, real time {real_time}");
|
||||
let (mut s, target, _) = two_squares(real_time);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.select_tool("directSelection", view()).unwrap();
|
||||
let points = |s: &Session| -> Vec<(f64, f64)> {
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let path = doc.node(target).and_then(|n| n.path_data()).expect("the square is a path");
|
||||
path.anchors().map(|(_, _, a)| (a.p.x, a.p.y)).collect()
|
||||
};
|
||||
let before = points(&s);
|
||||
let &(x, y) = before.last().expect("the square has anchors");
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
let mut params = params.clone();
|
||||
params["id"] = json!(target.0);
|
||||
drag_with(&mut s, &[(x, y), (x + 10.0, y + 10.0), (x + 30.0, y + 20.0)], |s| {
|
||||
s.execute(id, ¶ms).unwrap();
|
||||
});
|
||||
assert!(!s.in_interaction(), "{at}");
|
||||
let after = points(&s);
|
||||
assert_eq!(after.len(), before.len() + added, "{at}: the command's edit stays");
|
||||
assert!(before.iter().all(|p| after.contains(p)), "{at}: no anchor of the square moved: {before:?} → {after:?}");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "{at}: only the command is a step");
|
||||
}
|
||||
}
|
||||
|
||||
/// A Direct Selection drag of an anchor, with a command during it that moves the path: the drag
|
||||
/// goes on and moves the same anchor of the moved path.
|
||||
#[test]
|
||||
fn an_anchor_drag_after_a_command_moves_its_path_moves_the_same_anchor() {
|
||||
for real_time in [true, false] {
|
||||
let at = format!("real time {real_time}");
|
||||
let (mut s, target, _) = two_squares(real_time);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.select_tool("directSelection", view()).unwrap();
|
||||
let points = |s: &Session| -> Vec<(f64, f64)> {
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let path = doc.node(target).and_then(|n| n.path_data()).expect("the square is a path");
|
||||
path.anchors().map(|(_, _, a)| (a.p.x, a.p.y)).collect()
|
||||
};
|
||||
let before = points(&s);
|
||||
let &(x, y) = before.last().expect("the square has anchors");
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
drag_with(&mut s, &[(x, y), (x + 10.0, y + 10.0), (x + 30.0, y + 20.0)], |s| {
|
||||
s.execute("object.move", &json!({"ids": [target.0], "dx": 0, "dy": 50})).unwrap();
|
||||
});
|
||||
let after = points(&s);
|
||||
let last = before.len() - 1;
|
||||
let moved: Vec<(f64, f64)> =
|
||||
before.iter().enumerate().map(|(i, &(px, py))| if i == last { (px + 30.0, py + 70.0) } else { (px, py + 50.0) }).collect();
|
||||
assert_eq!(after, moved, "{at}: the drag moves the same anchor of the moved square");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 2, "{at}: the move and the drag are a step each");
|
||||
}
|
||||
}
|
||||
|
||||
/// With the Live Paint Bucket's Selection tool (Cmd+drag), a fill chosen during the drag stays the
|
||||
/// new-art fill after the release and after Escape, though the drag puts back the bucket's colors
|
||||
/// it began with.
|
||||
#[test]
|
||||
fn a_fill_chosen_during_a_bucket_drag_stays() {
|
||||
for (real_time, escape) in [(true, false), (false, false), (true, true), (false, true)] {
|
||||
let at = format!("real time {real_time}, Escape {escape}");
|
||||
let (mut s, _, _) = two_squares(real_time);
|
||||
s.select_tool("livePaintBucket", view()).unwrap();
|
||||
let cmd = Mods { cmd: true, ..Mods::default() };
|
||||
for (kind, x, y) in [(PointerKind::Down, 120.0, 120.0), (PointerKind::Drag, 140.0, 130.0)] {
|
||||
s.pointer(&PointerEvent::new(kind, x, y).with_mods(cmd), view()).unwrap();
|
||||
}
|
||||
assert!(s.in_interaction(), "{at}: the lent Selection tool drags the square");
|
||||
s.execute("paint.setFill", &json!({"color": "#00ff00", "ids": []})).unwrap();
|
||||
let green = s.paint.fill.clone();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 170.0, 150.0).with_mods(cmd), view()).unwrap();
|
||||
if escape {
|
||||
s.tool_key(ToolKey::Escape, Mods::default(), view()).unwrap();
|
||||
}
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 170.0, 150.0).with_mods(cmd), view()).unwrap();
|
||||
assert_eq!(s.paint.fill, green, "{at}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A command run during a Quick Pen press still runs inside the press, so it records no undo
|
||||
/// step of its own while the press is held.
|
||||
#[test]
|
||||
fn a_command_during_a_quick_pen_press_runs_inside_it() {
|
||||
for real_time in [true, false] {
|
||||
let at = format!("real time {real_time}");
|
||||
let (mut s, other) = session(real_time);
|
||||
s.select_tool(vectorcraft_tools::quickpen::ID, view()).unwrap();
|
||||
pointer(&mut s, PointerKind::Down, 50.0, 50.0);
|
||||
pointer(&mut s, PointerKind::Up, 50.0, 50.0);
|
||||
pointer(&mut s, PointerKind::Down, 100.0, 100.0);
|
||||
pointer(&mut s, PointerKind::Drag, 150.0, 120.0);
|
||||
assert!(s.in_interaction(), "{at}: the press drags a piece");
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
s.execute("object.hide", &json!({"ids": [other.0]})).unwrap();
|
||||
assert!(s.in_interaction(), "{at}");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{at}: no step of its own during the press");
|
||||
}
|
||||
}
|
||||
@@ -532,6 +532,102 @@ fn rearrange_that_moves_no_artboard_records_no_undo_step() {
|
||||
assert_eq!(history(&s), before);
|
||||
}
|
||||
|
||||
/// Rearrange with `indices` lays out only those artboards, in document order whatever order they
|
||||
/// are listed in, with the grid's top-left at `at`: their art and guides go along, and the other
|
||||
/// artboards, their art and their guides stay where they are, all in one undo step.
|
||||
#[test]
|
||||
fn rearrange_lays_out_only_the_listed_artboards() {
|
||||
let mut s = new_doc(json!({"width": 100, "height": 50, "artboards": 4}));
|
||||
let before = boards(&s);
|
||||
let art: Vec<NodeId> = before
|
||||
.iter()
|
||||
.map(|r| {
|
||||
NodeId(
|
||||
s.execute("shape.rectangle", &json!({"x": r.x0 + 10.0, "y": r.y0 + 10.0, "width": 10, "height": 10})).unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap(),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
for i in [0, 1] {
|
||||
s.execute("guide.add", &json!({"vertical": true, "pos": before[i].x0 + 5.0, "artboard": i})).unwrap();
|
||||
}
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let p = json!({"indices": [3, 1], "layout": "row", "spacing": 10, "at": [500, 400]});
|
||||
let r = s.execute("artboard.rearrange", &p).unwrap();
|
||||
assert_eq!(r, json!({"artboards": 4, "indices": [1, 3], "moved": 2, "rows": 1, "columns": 2}));
|
||||
let after = boards(&s);
|
||||
assert_eq!((after[0], after[2]), (before[0], before[2]), "the artboards not listed stay");
|
||||
assert_eq!((after[1], after[3]), (Rect::new(500.0, 400.0, 600.0, 450.0), Rect::new(610.0, 400.0, 710.0, 450.0)));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
for (id, r) in art.iter().zip(&after) {
|
||||
let b = d.node(*id).unwrap().geometric_bounds().unwrap();
|
||||
assert_eq!((b.x0, b.y0), (r.x0 + 10.0, r.y0 + 10.0), "the art is on its artboard");
|
||||
}
|
||||
let guides: Vec<f64> = d.ruler_guides().iter().map(|g| g.pos).collect();
|
||||
assert_eq!(guides, [before[0].x0 + 5.0, 505.0]);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(boards(&s), before);
|
||||
}
|
||||
|
||||
/// Without `at`, the grid of the listed artboards starts at the first one's top-left; one listed
|
||||
/// artboard is laid out alone; a listed locked artboard stays and keeps its cell; when every listed
|
||||
/// artboard is locked, nothing moves, no undo step is recorded and `moved` is 0.
|
||||
#[test]
|
||||
fn rearrange_of_listed_artboards_starts_at_the_first_and_keeps_locked_ones() {
|
||||
let mut s = new_doc(json!({"width": 100, "height": 50, "artboards": 4, "artboardLayout": {"layout": "row", "spacing": 20}}));
|
||||
let before = boards(&s);
|
||||
// Artboards 1 and 3 in one column, from artboard 1's corner.
|
||||
let r = s.execute("artboard.rearrange", &json!({"indices": [1, 3], "layout": "column", "spacing": 10})).unwrap();
|
||||
assert_eq!(r["moved"], 1);
|
||||
let after = boards(&s);
|
||||
assert_eq!(after[1], before[1]);
|
||||
assert_eq!(after[3], Rect::new(before[1].x0, before[1].y1 + 10.0, before[1].x1, before[1].y1 + 60.0));
|
||||
// One artboard goes to `at`.
|
||||
s.execute("artboard.rearrange", &json!({"indices": [2], "at": [-300, -200]})).unwrap();
|
||||
assert_eq!(boards(&s)[2], Rect::new(-300.0, -200.0, -200.0, -150.0));
|
||||
// Artboard 0 locked keeps its place and its cell: artboard 2 goes to the second cell from 0's.
|
||||
s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap();
|
||||
let r = s.execute("artboard.rearrange", &json!({"indices": [0, 2], "layout": "row", "spacing": 5, "at": [1000, 0]})).unwrap();
|
||||
assert_eq!(r["moved"], 1);
|
||||
assert_eq!((boards(&s)[0], boards(&s)[2]), (before[0], Rect::new(1105.0, 0.0, 1205.0, 50.0)));
|
||||
// Every listed artboard locked: nothing moves.
|
||||
let placed = boards(&s);
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let r = s.execute("artboard.rearrange", &json!({"indices": [0], "at": [3000, 3000]})).unwrap();
|
||||
assert_eq!(r, json!({"artboards": 4, "indices": [0], "moved": 0, "rows": 1, "columns": 1}));
|
||||
assert_eq!((boards(&s), s.doc().unwrap().history.undo.len()), (placed, undo));
|
||||
}
|
||||
|
||||
/// Rearrange refuses `indices` that are not a non-empty list of artboards, and an `at` that is not
|
||||
/// [x, y], before anything moves, and leaves the document as it was when `at` would put an
|
||||
/// artboard past the canvas; a listed index given twice counts once.
|
||||
#[test]
|
||||
fn rearrange_refuses_bad_indices_and_at() {
|
||||
let mut s = new_doc(json!({"width": 100, "height": 50, "artboards": 3}));
|
||||
let before = (boards(&s), s.doc().unwrap().history.undo.len());
|
||||
for (p, msg) in [
|
||||
(json!({"indices": []}), "invalid parameters for `artboard.rearrange`: `indices` must be a non-empty list of artboard indices"),
|
||||
(json!({"indices": 1}), "invalid parameters for `artboard.rearrange`: `indices` must be a list of artboard indices"),
|
||||
(json!({"indices": [1.5]}), "invalid parameters for `artboard.rearrange`: `indices` must contain whole numbers"),
|
||||
(json!({"indices": [-1]}), "invalid parameters for `artboard.rearrange`: `indices` must contain whole numbers"),
|
||||
(json!({"indices": ["1"]}), "invalid parameters for `artboard.rearrange`: `indices` must contain whole numbers"),
|
||||
(json!({"indices": [0, 3]}), "no such artboard"),
|
||||
(json!({"indices": [0, 1], "at": [1]}), "invalid parameters for `artboard.rearrange`: `at` must be [x, y]"),
|
||||
(json!({"indices": [0, 1], "at": "0,0"}), "invalid parameters for `artboard.rearrange`: `at` must be [x, y]"),
|
||||
(json!({"at": [0, "1"]}), "invalid parameters for `artboard.rearrange`: `at` must be [x, y]"),
|
||||
(json!({"indices": [0], "at": [1e20, 0]}), "result would exceed the canvas (coordinates out of range)"),
|
||||
(json!({"at": [0, -4.000001e6]}), "result would exceed the canvas (coordinates out of range)"),
|
||||
] {
|
||||
let err = s.execute("artboard.rearrange", &p).unwrap_err().to_string();
|
||||
assert_eq!(err, msg, "{p}");
|
||||
assert_eq!((boards(&s), s.doc().unwrap().history.undo.len()), before, "{p}");
|
||||
}
|
||||
let r = s.execute("artboard.rearrange", &json!({"indices": [2, 2], "at": [0, 500]})).unwrap();
|
||||
assert_eq!((r["indices"].clone(), boards(&s)[2]), (json!([2]), Rect::new(0.0, 500.0, 100.0, 550.0)));
|
||||
}
|
||||
|
||||
/// A session whose New Document profiles are in a fresh folder for test `name` (not made yet).
|
||||
fn with_profiles(name: &str) -> (Session, std::path::PathBuf) {
|
||||
let dir = std::env::temp_dir().join(format!("vc-newdoc-profiles-{name}-{}", std::process::id()));
|
||||
|
||||
@@ -73,13 +73,14 @@ fn arrowheads_are_part_of_the_outline() {
|
||||
assert_eq!(path_of(&n).subpaths.len(), 1, "line and head are one shape");
|
||||
}
|
||||
|
||||
/// Outline Stroke of a Lens-profile line covers 2/3 of the full-width rectangle.
|
||||
/// Outline Stroke of a Lens-profile line covers 7/12 of the full-width rectangle.
|
||||
#[test]
|
||||
fn a_lens_profile_outlines_to_two_thirds_of_the_rectangle() {
|
||||
fn a_lens_profile_outlines_to_seven_twelfths_of_the_rectangle() {
|
||||
let mut s = session();
|
||||
line(&mut s, json!({"weight": 10, "profile": "lens"}));
|
||||
let n = outline(&mut s);
|
||||
assert!(near(area(&n), 2.0 / 3.0 * 10.0 * 100.0, 2.0), "{}", area(&n));
|
||||
// Each half of the lens swells on a cubic, flat at the middle (#5714).
|
||||
assert!(near(area(&n), 7.0 / 12.0 * 10.0 * 100.0, 2.0), "{}", area(&n));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -792,7 +792,7 @@ fn the_document_info_report_has_every_category() {
|
||||
assert!(text.contains(&format!("\n{h}\n")), "{h}: {text}");
|
||||
}
|
||||
assert!(text.contains("Images: 3") && text.contains("Source Sans 3 Regular: built in; embedding allowed"), "{text}");
|
||||
assert!(text.contains("red.png: 600 × 300 px — ") && text.contains("Color Mode: RGB") && text.contains("\nSwatches: "), "{text}");
|
||||
assert!(text.contains("red.png: PNG; 600 × 300 px; 72 ppi — ") && text.contains("Color Mode: RGB") && text.contains("\nSwatches: "), "{text}");
|
||||
let fonts = run(&mut s, "document.info", json!({"format": "text", "category": "fonts"}))["text"].as_str().unwrap().to_string();
|
||||
assert!(fonts.contains("FONTS") && !fonts.contains("OBJECTS"), "{fonts}");
|
||||
let i = run(&mut s, "document.info", json!({"category": "linkedImages"}));
|
||||
@@ -802,7 +802,7 @@ fn the_document_info_report_has_every_category() {
|
||||
// embedded one with no file.
|
||||
let linked: Vec<Value> = i["imageObjects"].as_array().unwrap().iter().filter(|o| o["linked"] == true).cloned().collect();
|
||||
for (o, r) in linked.iter().zip(i["sections"][0]["rows"].as_array().unwrap()) {
|
||||
let shown = format!("{} × {} px — {}", o["width"], o["height"], o["file"].as_str().unwrap());
|
||||
let shown = format!("PNG; {} × {} px; 72 ppi — {}", o["width"], o["height"], o["file"].as_str().unwrap());
|
||||
assert_eq!((&o["name"], shown.as_str()), (&r[0], r[1].as_str().unwrap()));
|
||||
}
|
||||
assert_eq!(linked.len(), 2);
|
||||
|
||||
@@ -0,0 +1,485 @@
|
||||
//! `opacity` on `paint.setFill` and `paint.setStroke`: the opacity of the fill or stroke item the
|
||||
//! paint goes to, and `fillOpacity` and `strokeOpacity` on `paint.proxies`.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Node, NodeKind};
|
||||
use vectorcraft_tools::{PointerEvent, PointerKind};
|
||||
|
||||
use crate::tooling::ViewInfo;
|
||||
use crate::*;
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn rect(s: &mut Session, x: f64) -> NodeId {
|
||||
let r = s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 100, "height": 50})).unwrap();
|
||||
NodeId(r["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
fn text(s: &mut Session) -> NodeId {
|
||||
let r = s.execute("text.create", &json!({"x": 10, "y": 150, "text": "Hi"})).unwrap();
|
||||
NodeId(r["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
fn node(s: &Session, id: NodeId) -> Node {
|
||||
s.doc().unwrap().doc.node(id).unwrap().clone()
|
||||
}
|
||||
|
||||
fn select(s: &mut Session, ids: &[NodeId]) {
|
||||
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
|
||||
}
|
||||
|
||||
fn fill_opacity(s: &Session, id: NodeId) -> f32 {
|
||||
node(s, id).appearance.fill().unwrap().opacity
|
||||
}
|
||||
|
||||
fn undo_labels(s: &Session) -> Vec<String> {
|
||||
s.doc().unwrap().history.undo.iter().map(|e| e.label.clone()).collect()
|
||||
}
|
||||
|
||||
fn proxies(s: &mut Session) -> Value {
|
||||
s.execute("paint.proxies", &json!({})).unwrap()
|
||||
}
|
||||
|
||||
/// `paint.setFill {opacity}` alone sets the opacity of the selected object's top fill item, as one
|
||||
/// undo step named Opacity, and leaves its paint, its stroke and the object's own opacity as they
|
||||
/// were; `paint.setStroke {opacity}` does the same for the top stroke, and `paint.proxies` answers
|
||||
/// both.
|
||||
#[test]
|
||||
fn opacity_alone_sets_the_fill_or_stroke_item() {
|
||||
let mut s = session();
|
||||
let id = rect(&mut s, 10.0);
|
||||
select(&mut s, &[id]);
|
||||
let before = node(&s, id);
|
||||
let undo = undo_labels(&s).len();
|
||||
s.execute("paint.setFill", &json!({"opacity": 40})).unwrap();
|
||||
let n = node(&s, id);
|
||||
assert!((fill_opacity(&s, id) - 0.4).abs() < 1e-6);
|
||||
assert_eq!(n.appearance.fill_paint(), before.appearance.fill_paint());
|
||||
assert_eq!(n.appearance.stroke().unwrap().opacity, 1.0);
|
||||
assert_eq!(n.opacity, 1.0);
|
||||
let labels = undo_labels(&s);
|
||||
assert_eq!((labels.len(), labels.last().map(String::as_str)), (undo + 1, Some("Opacity")));
|
||||
assert_eq!(proxies(&mut s)["fillOpacity"], 40.0);
|
||||
assert_eq!(proxies(&mut s)["strokeOpacity"], 100.0);
|
||||
// The defaults for new art keep their paint.
|
||||
assert_eq!(s.paint.fill, Paint::solid(Color::WHITE));
|
||||
|
||||
s.execute("paint.setStroke", &json!({"opacity": 25})).unwrap();
|
||||
assert!((node(&s, id).appearance.stroke().unwrap().opacity - 0.25).abs() < 1e-6);
|
||||
assert!((fill_opacity(&s, id) - 0.4).abs() < 1e-6);
|
||||
assert_eq!(proxies(&mut s)["strokeOpacity"], 25.0);
|
||||
}
|
||||
|
||||
/// A selected group stands for its contents: every member's fill takes the opacity, as one undo step.
|
||||
#[test]
|
||||
fn a_group_sets_every_member_in_one_step() {
|
||||
let mut s = session();
|
||||
let (a, b) = (rect(&mut s, 10.0), rect(&mut s, 200.0));
|
||||
select(&mut s, &[a, b]);
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
let undo = undo_labels(&s).len();
|
||||
s.execute("paint.setFill", &json!({"opacity": 60})).unwrap();
|
||||
assert!((fill_opacity(&s, a) - 0.6).abs() < 1e-6 && (fill_opacity(&s, b) - 0.6).abs() < 1e-6);
|
||||
assert_eq!(undo_labels(&s).len(), undo + 1);
|
||||
}
|
||||
|
||||
/// A group with a fill of its own: without an active Appearance row, `paint.proxies` answers the
|
||||
/// opacity of the contents' fills, which `paint.setFill {opacity}` sets, not the group's own fill.
|
||||
#[test]
|
||||
fn a_group_with_its_own_fill_answers_for_its_contents() {
|
||||
let mut s = session();
|
||||
let (a, b) = (rect(&mut s, 10.0), rect(&mut s, 200.0));
|
||||
select(&mut s, &[a, b]);
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
let g = s.doc().unwrap().selection.subjects()[0];
|
||||
select(&mut s, &[g]);
|
||||
s.execute("appearance.addFill", &json!({})).unwrap();
|
||||
let own = node(&s, g).appearance.items.iter().position(|it| it.is_fill()).unwrap();
|
||||
s.execute("paint.setFill", &json!({"item": own, "opacity": 30})).unwrap();
|
||||
select(&mut s, &[g]);
|
||||
assert_eq!(proxies(&mut s)["fillOpacity"], 100.0);
|
||||
s.execute("paint.setFill", &json!({"opacity": 60})).unwrap();
|
||||
assert_eq!(proxies(&mut s)["fillOpacity"], 60.0);
|
||||
assert!((node(&s, g).appearance.items[own].opacity() - 0.3).abs() < 1e-6, "the group's own fill keeps its opacity");
|
||||
}
|
||||
|
||||
/// A targeted layer without an active Appearance row: `paint.proxies` answers the opacity of the
|
||||
/// layer's editable art, which `paint.setFill {opacity}` sets, not that of a locked object before it.
|
||||
#[test]
|
||||
fn a_targeted_layer_answers_for_its_editable_art() {
|
||||
let mut s = session();
|
||||
let (locked, open) = (rect(&mut s, 10.0), rect(&mut s, 200.0));
|
||||
s.execute("paint.setFill", &json!({"ids": [locked.0], "opacity": 20})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"ids": [open.0], "opacity": 80})).unwrap();
|
||||
s.execute("object.lock", &json!({"ids": [locked.0]})).unwrap();
|
||||
let layer = s.doc().unwrap().doc.layers[0].id;
|
||||
s.execute("layer.target", &json!({"id": layer.0})).unwrap();
|
||||
assert_eq!(proxies(&mut s)["fillOpacity"], 80.0);
|
||||
s.execute("paint.setFill", &json!({"opacity": 40})).unwrap();
|
||||
assert!((fill_opacity(&s, open) - 0.4).abs() < 1e-6);
|
||||
assert!((fill_opacity(&s, locked) - 0.2).abs() < 1e-6, "the locked object keeps its opacity");
|
||||
assert_eq!(proxies(&mut s)["fillOpacity"], 40.0);
|
||||
}
|
||||
|
||||
/// With the Appearance panel's lower fill row active, that row takes the opacity and the top fill
|
||||
/// keeps its own.
|
||||
#[test]
|
||||
fn the_active_appearance_row_takes_the_opacity() {
|
||||
let mut s = session();
|
||||
let id = rect(&mut s, 10.0);
|
||||
select(&mut s, &[id]);
|
||||
s.execute("appearance.addFill", &json!({})).unwrap(); // [Fill, Stroke, Fill]
|
||||
s.execute("appearance.setActiveItem", &json!({"index": 0})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"opacity": 30})).unwrap();
|
||||
let ap = node(&s, id).appearance;
|
||||
assert!((ap.items[0].opacity() - 0.3).abs() < 1e-6);
|
||||
assert_eq!(ap.items[2].opacity(), 1.0);
|
||||
assert_eq!(proxies(&mut s)["fillOpacity"], 30.0);
|
||||
}
|
||||
|
||||
/// With a path of a compound path selected and its fill row active, the command edits the compound
|
||||
/// path's fill, and `paint.proxies` answers that fill's opacity, not the member's own.
|
||||
#[test]
|
||||
fn an_active_row_of_a_compound_member_answers_for_its_compound() {
|
||||
let mut s = session();
|
||||
let (a, b) = (rect(&mut s, 10.0), rect(&mut s, 200.0));
|
||||
select(&mut s, &[a, b]);
|
||||
let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("paint.setFill", &json!({"ids": [compound.0], "opacity": 40})).unwrap();
|
||||
// A fill row of the member's own, at 100%.
|
||||
s.execute("appearance.addFill", &json!({"ids": [a.0]})).unwrap();
|
||||
assert_eq!(fill_opacity(&s, a), 1.0);
|
||||
select(&mut s, &[a]);
|
||||
let row = node(&s, a).appearance.items.iter().position(|it| it.is_fill()).unwrap();
|
||||
s.execute("appearance.setActiveItem", &json!({"index": row})).unwrap();
|
||||
assert_eq!(proxies(&mut s)["fillOpacity"], 40.0);
|
||||
s.execute("paint.setFill", &json!({"opacity": 70})).unwrap();
|
||||
assert!((fill_opacity(&s, compound) - 0.7).abs() < 1e-6);
|
||||
assert_eq!(proxies(&mut s)["fillOpacity"], 70.0);
|
||||
|
||||
// A fill row of the member's at an index that is not a fill in the compound path: the command
|
||||
// edits the compound path's top fill, which the proxy answers.
|
||||
s.execute("appearance.addFill", &json!({"ids": [a.0]})).unwrap();
|
||||
let (member, outer) = (node(&s, a).appearance, node(&s, compound).appearance);
|
||||
let row = (0..member.items.len()).find(|i| member.items[*i].is_fill() && !outer.items.get(*i).is_some_and(|it| it.is_fill())).unwrap();
|
||||
select(&mut s, &[a]);
|
||||
s.execute("appearance.setActiveItem", &json!({"index": row})).unwrap();
|
||||
assert_eq!(proxies(&mut s)["fillOpacity"], 70.0);
|
||||
s.execute("paint.setFill", &json!({"opacity": 20})).unwrap();
|
||||
assert!((fill_opacity(&s, compound) - 0.2).abs() < 1e-6);
|
||||
assert_eq!(proxies(&mut s)["fillOpacity"], 20.0);
|
||||
}
|
||||
|
||||
/// A color and an opacity change together in one undo step, and the same call again records no
|
||||
/// step.
|
||||
#[test]
|
||||
fn color_and_opacity_are_one_step_and_a_repeat_records_none() {
|
||||
let mut s = session();
|
||||
let id = rect(&mut s, 10.0);
|
||||
select(&mut s, &[id]);
|
||||
let undo = undo_labels(&s).len();
|
||||
let p = json!({"color": "#ff0000", "opacity": 50});
|
||||
s.execute("paint.setFill", &p).unwrap();
|
||||
assert_eq!(node(&s, id).appearance.fill_paint(), Paint::solid(Color::rgb8(255, 0, 0)));
|
||||
assert!((fill_opacity(&s, id) - 0.5).abs() < 1e-6);
|
||||
assert_eq!(undo_labels(&s).len(), undo + 1);
|
||||
assert_eq!(undo_labels(&s).last().map(String::as_str), Some("Fill Color"));
|
||||
s.execute("paint.setFill", &p).unwrap();
|
||||
s.execute("paint.setFill", &json!({"opacity": 50})).unwrap();
|
||||
assert_eq!(undo_labels(&s).len(), undo + 1);
|
||||
}
|
||||
|
||||
/// Bad values, nothing selected, and characters selected with the Type tool answer errors and leave
|
||||
/// the document and the defaults for new art as they were.
|
||||
#[test]
|
||||
fn errors_leave_the_document_and_defaults_alone() {
|
||||
let mut s = session();
|
||||
let id = rect(&mut s, 10.0);
|
||||
select(&mut s, &[id]);
|
||||
for bad in [json!(101), json!(-1), json!("50"), json!(true)] {
|
||||
let e = s.execute("paint.setFill", &json!({"opacity": bad})).unwrap_err();
|
||||
assert!(e.to_string().contains("`opacity` must be a number from 0 to 100"), "{bad}: {e}");
|
||||
}
|
||||
let e = s.execute("paint.setFill", &json!({})).unwrap_err();
|
||||
assert!(e.to_string().contains("give color, none, swatch, gradient or opacity"), "{e}");
|
||||
// An opacity alone places no gradient across the selection.
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
for (span, says) in [(json!("selection"), "give `gradient`"), (json!("all"), "span must be \"object\" or \"selection\"")] {
|
||||
let e = s.execute("paint.setFill", &json!({"opacity": 40, "span": span})).unwrap_err();
|
||||
assert!(e.to_string().contains(says), "{span}: {e}");
|
||||
}
|
||||
assert_eq!(*s.doc().unwrap().doc, *doc);
|
||||
s.execute("paint.setFill", &json!({"opacity": 40, "span": "object"})).unwrap();
|
||||
assert!((fill_opacity(&s, id) - 0.4).abs() < 1e-6);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
for p in [json!({"opacity": 40}), json!({"color": "#ff0000", "opacity": 40})] {
|
||||
let e = s.execute("paint.setFill", &p).unwrap_err();
|
||||
assert!(e.to_string().contains("select objects or give ids"), "{p}: {e}");
|
||||
}
|
||||
assert_eq!(s.paint.fill, Paint::solid(Color::WHITE));
|
||||
assert_eq!(*s.doc().unwrap().doc, *doc);
|
||||
|
||||
// Characters selected with the Type tool.
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool("type", v).unwrap();
|
||||
for kind in [PointerKind::Down, PointerKind::Up] {
|
||||
s.pointer(&PointerEvent::new(kind, 50.0, 250.0), v).unwrap();
|
||||
}
|
||||
s.tool_text("Sample", v).unwrap();
|
||||
s.set_tool_option("select", &json!({"start": 0, "end": 3}));
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
for p in [json!({"opacity": 40}), json!({"color": "#ff0000", "opacity": 40})] {
|
||||
let e = s.execute("paint.setFill", &p).unwrap_err();
|
||||
assert!(e.to_string().contains("type characters have no opacity of their own"), "{p}: {e}");
|
||||
}
|
||||
assert_eq!(*s.doc().unwrap().doc, *doc);
|
||||
assert_eq!(proxies(&mut s)["fillOpacity"], Value::Null);
|
||||
}
|
||||
|
||||
/// Select characters of `t` with the Type tool.
|
||||
fn select_characters(s: &mut Session, t: NodeId) {
|
||||
s.select_tool("type", ViewInfo::default()).unwrap();
|
||||
s.set_tool_option("textSelection", &json!({"editing": t.0, "anchor": 0, "caret": 2}));
|
||||
}
|
||||
|
||||
/// While the Type tool has characters selected, `paint.proxies` answers no opacity even when the
|
||||
/// type object has a fill row of its own that the Appearance panel has active, since
|
||||
/// `paint.setFill {opacity}` would give the opacity to the characters.
|
||||
#[test]
|
||||
fn with_characters_selected_the_proxy_answers_no_opacity() {
|
||||
let mut s = session();
|
||||
let t = text(&mut s);
|
||||
select(&mut s, &[t]);
|
||||
s.execute("appearance.addFill", &json!({})).unwrap();
|
||||
let row = node(&s, t).appearance.items.iter().position(|it| it.is_fill()).unwrap();
|
||||
s.execute("appearance.setActiveItem", &json!({"index": row})).unwrap();
|
||||
assert_eq!(proxies(&mut s)["fillOpacity"], 100.0, "the type object's own fill row");
|
||||
select_characters(&mut s, t);
|
||||
let e = s.execute("paint.setFill", &json!({"opacity": 40})).unwrap_err();
|
||||
assert!(e.to_string().contains("type characters have no opacity of their own"), "{e}");
|
||||
assert_eq!(proxies(&mut s)["fillOpacity"], Value::Null);
|
||||
}
|
||||
|
||||
/// While the Type tool has characters selected, an object named by `id` takes the opacity and the
|
||||
/// paint, and the characters keep theirs.
|
||||
#[test]
|
||||
fn with_characters_selected_an_id_takes_the_opacity() {
|
||||
let mut s = session();
|
||||
let r = rect(&mut s, 10.0);
|
||||
let t = text(&mut s);
|
||||
select(&mut s, &[t]);
|
||||
select_characters(&mut s, t);
|
||||
let before = node(&s, t);
|
||||
s.execute("paint.setFill", &json!({"id": r.0, "opacity": 40})).unwrap();
|
||||
assert!((fill_opacity(&s, r) - 0.4).abs() < 1e-6);
|
||||
s.execute("paint.setStroke", &json!({"id": r.0, "color": "#ff0000", "opacity": 30})).unwrap();
|
||||
let stroke = node(&s, r).appearance.stroke().unwrap().clone();
|
||||
assert!((stroke.opacity - 0.3).abs() < 1e-6);
|
||||
assert_eq!(stroke.paint, Paint::solid(Color::rgb8(255, 0, 0)));
|
||||
assert_eq!(node(&s, t), before, "the characters keep their paint");
|
||||
}
|
||||
|
||||
/// A type object whose characters take the paint is left alone beside a rectangle that takes the
|
||||
/// opacity, with no error; alone, it answers the characters error.
|
||||
#[test]
|
||||
fn type_beside_other_art_is_left_alone() {
|
||||
let mut s = session();
|
||||
let r = rect(&mut s, 10.0);
|
||||
let t = text(&mut s);
|
||||
let runs = |s: &Session| match &node(s, t).kind {
|
||||
NodeKind::Text(t) => t.runs.clone(),
|
||||
_ => panic!("not type"),
|
||||
};
|
||||
let before = (node(&s, t), runs(&s));
|
||||
select(&mut s, &[r, t]);
|
||||
let out = s.execute("paint.setFill", &json!({"opacity": 40})).unwrap();
|
||||
assert_eq!(out["objects"], 1, "only the rectangle took the opacity");
|
||||
assert!((fill_opacity(&s, r) - 0.4).abs() < 1e-6);
|
||||
assert_eq!((node(&s, t), runs(&s)), before);
|
||||
select(&mut s, &[t]);
|
||||
assert_eq!(proxies(&mut s)["fillOpacity"], Value::Null);
|
||||
let e = s.execute("paint.setFill", &json!({"opacity": 40})).unwrap_err();
|
||||
assert!(e.to_string().contains("type characters have no opacity of their own"), "{e}");
|
||||
assert_eq!((node(&s, t), runs(&s)), before);
|
||||
}
|
||||
|
||||
/// A color with an opacity on type alone answers the characters error and takes the color back too.
|
||||
#[test]
|
||||
fn type_alone_takes_back_the_paint_given_with_an_opacity() {
|
||||
let mut s = session();
|
||||
let t = text(&mut s);
|
||||
select(&mut s, &[t]);
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
let undo = undo_labels(&s).len();
|
||||
let e = s.execute("paint.setFill", &json!({"color": "#ff0000", "opacity": 40})).unwrap_err();
|
||||
assert!(e.to_string().contains("type characters have no opacity of their own"), "{e}");
|
||||
assert_eq!(*s.doc().unwrap().doc, *doc);
|
||||
assert_eq!(undo_labels(&s).len(), undo);
|
||||
assert_eq!(s.paint.fill, Paint::solid(Color::WHITE), "the defaults keep their paint");
|
||||
}
|
||||
|
||||
/// An opacity that no target takes (the only selected object has no fill item) is an error, with or
|
||||
/// without a paint, and leaves the document as it was; `paint.proxies` answers null for it, and
|
||||
/// beside an object with a fill item it answers that object's opacity.
|
||||
#[test]
|
||||
fn an_opacity_no_target_takes_is_an_error() {
|
||||
let mut s = session();
|
||||
let (a, b) = (rect(&mut s, 10.0), rect(&mut s, 200.0));
|
||||
select(&mut s, &[a]);
|
||||
s.execute("appearance.removeItem", &json!({"index": 0})).unwrap();
|
||||
assert!(node(&s, a).appearance.fill().is_none());
|
||||
assert_eq!(proxies(&mut s)["fillOpacity"], Value::Null);
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
let e = s.execute("paint.setFill", &json!({"opacity": 40})).unwrap_err();
|
||||
assert!(e.to_string().contains("no target has that fill or stroke to take the opacity"), "{e}");
|
||||
assert_eq!(*s.doc().unwrap().doc, *doc);
|
||||
// A paint given with the opacity creates the fill, which takes the opacity.
|
||||
s.execute("paint.setFill", &json!({"color": "#ff0000", "opacity": 40})).unwrap();
|
||||
assert!((fill_opacity(&s, a) - 0.4).abs() < 1e-6);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(*s.doc().unwrap().doc, *doc);
|
||||
|
||||
select(&mut s, &[b]);
|
||||
s.execute("paint.setFill", &json!({"opacity": 70})).unwrap();
|
||||
select(&mut s, &[a, b]);
|
||||
assert_eq!(proxies(&mut s)["fillOpacity"], 70.0, "the first selected object with a fill item answers");
|
||||
let out = s.execute("paint.setFill", &json!({"opacity": 20})).unwrap();
|
||||
assert_eq!(out["objects"], 1, "the object without a fill item is not counted");
|
||||
assert!((fill_opacity(&s, b) - 0.2).abs() < 1e-6);
|
||||
assert!(node(&s, a).appearance.fill().is_none());
|
||||
}
|
||||
|
||||
/// An object selected in a dynamic symbol instance has no opacity of its own: `opacity` is an error
|
||||
/// that leaves the document alone, and `paint.proxies` answers null.
|
||||
#[test]
|
||||
fn an_object_in_a_symbol_instance_refuses_an_opacity() {
|
||||
let mut s = session();
|
||||
let id = rect(&mut s, 10.0);
|
||||
select(&mut s, &[id]);
|
||||
let inst = s.execute("symbol.new", &json!({"name": "One", "ids": [id.0], "type": "dynamic"})).unwrap()["id"].clone();
|
||||
s.execute("symbol.instance.selectPart", &json!({"id": inst, "path": []})).unwrap();
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
for p in [json!({"opacity": 40}), json!({"color": "#ff0000", "opacity": 40})] {
|
||||
let e = s.execute("paint.setFill", &p).unwrap_err();
|
||||
assert!(e.to_string().contains("an object selected in a symbol instance has no fill or stroke opacity of its own"), "{p}: {e}");
|
||||
}
|
||||
assert_eq!(*s.doc().unwrap().doc, *doc);
|
||||
assert_eq!(proxies(&mut s)["fillOpacity"], Value::Null);
|
||||
}
|
||||
|
||||
/// A gradient mesh point picked with the Mesh tool takes a fill opacity itself, and the proxy shows
|
||||
/// it; the object's fill item and the other points stay as they were.
|
||||
#[test]
|
||||
fn a_picked_mesh_point_takes_the_fill_opacity() {
|
||||
let mut s = session();
|
||||
let m = rect(&mut s, 10.0);
|
||||
select(&mut s, &[m]);
|
||||
s.execute("object.mesh.create", &json!({"rows": 2, "cols": 2})).unwrap();
|
||||
select(&mut s, &[m]);
|
||||
let v = ViewInfo::default();
|
||||
let NodeKind::Mesh(g) = &node(&s, m).kind else { panic!("not a mesh") };
|
||||
let q = g.points[4].p;
|
||||
s.select_tool("mesh", v).unwrap();
|
||||
for kind in [PointerKind::Down, PointerKind::Up] {
|
||||
s.pointer(&PointerEvent::new(kind, q.x, q.y), v).unwrap();
|
||||
}
|
||||
s.execute("paint.setFill", &json!({"opacity": 30})).unwrap();
|
||||
let NodeKind::Mesh(g) = &node(&s, m).kind else { panic!("not a mesh") };
|
||||
let o: Vec<f32> = g.points.iter().map(|p| p.opacity).collect();
|
||||
assert!((o[4] - 0.3).abs() < 1e-6, "{o:?}");
|
||||
assert!(o.iter().enumerate().all(|(i, a)| i == 4 || *a == 1.0), "{o:?}");
|
||||
assert_eq!(proxies(&mut s)["fillOpacity"], 30.0);
|
||||
}
|
||||
|
||||
/// A null `id` or `ids` names no object, so while the Type tool has characters selected the paint
|
||||
/// goes to those characters only, and the rest of the type keeps its paint.
|
||||
#[test]
|
||||
fn a_null_id_leaves_the_paint_to_the_selected_characters() {
|
||||
for key in ["id", "ids"] {
|
||||
let mut s = session();
|
||||
let t = text(&mut s);
|
||||
select(&mut s, &[t]);
|
||||
s.select_tool("type", ViewInfo::default()).unwrap();
|
||||
s.set_tool_option("textSelection", &json!({"editing": t.0, "anchor": 0, "caret": 1}));
|
||||
s.execute("paint.setFill", &json!({"color": "#ff0000", key: null})).unwrap();
|
||||
let NodeKind::Text(tx) = &node(&s, t).kind else { panic!("not type") };
|
||||
let fills: Vec<Paint> = tx.runs.iter().map(|r| r.style.fill.clone()).collect();
|
||||
assert_eq!(fills.first(), Some(&Paint::solid(Color::rgb8(255, 0, 0))), "{key}: {fills:?}");
|
||||
assert!(fills.len() > 1 && fills[1..].iter().all(|f| *f != Paint::solid(Color::rgb8(255, 0, 0))), "{key}: {fills:?}");
|
||||
let e = s.execute("paint.setFill", &json!({"opacity": 40, key: null})).unwrap_err();
|
||||
assert!(e.to_string().contains("type characters have no opacity of their own"), "{key}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A selected Live Paint group stands for its faces in a fill opacity and for its edges in a stroke
|
||||
/// opacity, and `paint.proxies` answers from those same parts.
|
||||
#[test]
|
||||
fn a_live_paint_group_answers_from_the_parts_it_sets() {
|
||||
let mut s = session();
|
||||
let id = rect(&mut s, 10.0);
|
||||
s.execute("livePaint.make", &json!({"ids": [id.0]})).unwrap();
|
||||
let g = s.doc().unwrap().selection.objects[0];
|
||||
select(&mut s, &[g]);
|
||||
s.execute("paint.setStroke", &json!({"opacity": 30})).unwrap();
|
||||
assert_eq!(proxies(&mut s)["strokeOpacity"], 30.0);
|
||||
s.execute("paint.setFill", &json!({"opacity": 40})).unwrap();
|
||||
assert_eq!(proxies(&mut s)["fillOpacity"], 40.0);
|
||||
assert_eq!(proxies(&mut s)["strokeOpacity"], 30.0);
|
||||
}
|
||||
|
||||
/// While the Live Paint Bucket is the active tool, a fill or stroke chosen goes to the bucket, so
|
||||
/// `paint.proxies` answers no opacity for the selection and an opacity is an error that leaves the
|
||||
/// document as it was.
|
||||
#[test]
|
||||
fn the_live_paint_bucket_answers_no_opacity() {
|
||||
let mut s = session();
|
||||
let id = rect(&mut s, 10.0);
|
||||
select(&mut s, &[id]);
|
||||
assert_eq!(proxies(&mut s)["fillOpacity"], 100.0);
|
||||
s.select_tool("livePaintBucket", ViewInfo::default()).unwrap();
|
||||
assert_eq!(proxies(&mut s)["fillOpacity"], Value::Null);
|
||||
assert_eq!(proxies(&mut s)["strokeOpacity"], Value::Null);
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
assert!(s.execute("paint.setFill", &json!({"opacity": 40})).is_err());
|
||||
assert_eq!(*s.doc().unwrap().doc, *doc);
|
||||
}
|
||||
|
||||
/// The Eyedropper armed to sample into the Live Paint Bucket's gradient works for the bucket, so
|
||||
/// the proxies answer no opacity for the selection then too, as they show no paint of its own.
|
||||
#[test]
|
||||
fn the_eyedropper_armed_for_the_bucket_answers_no_opacity() {
|
||||
let mut s = session();
|
||||
let id = rect(&mut s, 10.0);
|
||||
select(&mut s, &[id]);
|
||||
s.select_tool("eyedropper", ViewInfo::default()).unwrap();
|
||||
assert_eq!(proxies(&mut s)["fillOpacity"], 100.0, "the Eyedropper alone shows the selection's");
|
||||
s.set_tool_option("stop", &json!("livePaintBucket"));
|
||||
assert!(s.bucket_paints());
|
||||
assert_eq!(proxies(&mut s)["fillOpacity"], Value::Null);
|
||||
assert_eq!(proxies(&mut s)["strokeOpacity"], Value::Null);
|
||||
}
|
||||
|
||||
/// A `swatch` that is no name does not turn a request into an opacity alone: it is an error and
|
||||
/// leaves the document as it was.
|
||||
#[test]
|
||||
fn a_swatch_that_is_no_name_is_refused_with_an_opacity() {
|
||||
let mut s = session();
|
||||
let id = rect(&mut s, 10.0);
|
||||
select(&mut s, &[id]);
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
for cmd in ["paint.setFill", "paint.setStroke"] {
|
||||
for swatch in [json!(5), json!(true), json!(["a"]), json!({})] {
|
||||
assert!(s.execute(cmd, &json!({"swatch": swatch, "opacity": 40})).is_err(), "{cmd} {swatch}");
|
||||
}
|
||||
// A null swatch names none, so the opacity goes alone.
|
||||
s.execute(cmd, &json!({"swatch": null, "opacity": 40})).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
}
|
||||
assert_eq!(*s.doc().unwrap().doc, *doc);
|
||||
}
|
||||
@@ -2196,6 +2196,550 @@ fn installed_plugins_are_kept_in_the_store() {
|
||||
assert!(vectorcraft_plugins::registry::get(id).is_none());
|
||||
}
|
||||
|
||||
/// Held by the tests that set [`crate::store::BEFORE_STORED_LOAD`].
|
||||
static STORED_HOOK: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
|
||||
/// A stored module's load waits on its worker thread until the test lets it go
|
||||
/// ([`crate::store::BEFORE_STORED_LOAD`]). The hook is cleared when this is dropped.
|
||||
struct HeldLoad {
|
||||
_lock: std::sync::MutexGuard<'static, ()>,
|
||||
entered: std::sync::Arc<std::sync::atomic::AtomicBool>,
|
||||
go: std::sync::Arc<std::sync::atomic::AtomicBool>,
|
||||
gave_up: std::sync::Arc<std::sync::atomic::AtomicBool>,
|
||||
}
|
||||
|
||||
impl HeldLoad {
|
||||
/// Holds the load of the file at `path`. A load the test never lets go gives up after a
|
||||
/// million yields (so a test of code that waits for it ends) and says so in `gave_up`.
|
||||
fn new(path: std::path::PathBuf) -> HeldLoad {
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
let lock = STORED_HOOK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let (entered, go, gave_up) = (Arc::new(AtomicBool::new(false)), Arc::new(AtomicBool::new(false)), Arc::new(AtomicBool::new(false)));
|
||||
let (e, g, q) = (entered.clone(), go.clone(), gave_up.clone());
|
||||
*crate::store::BEFORE_STORED_LOAD.lock().unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(move |p: &std::path::Path| {
|
||||
if p != path {
|
||||
return;
|
||||
}
|
||||
e.store(true, Ordering::SeqCst);
|
||||
if !(0..1_000_000).any(|_| {
|
||||
std::thread::yield_now();
|
||||
g.load(Ordering::SeqCst)
|
||||
}) {
|
||||
q.store(true, Ordering::SeqCst);
|
||||
}
|
||||
}));
|
||||
HeldLoad { _lock: lock, entered, go, gave_up }
|
||||
}
|
||||
|
||||
fn entered(&self) -> bool {
|
||||
self.entered.load(std::sync::atomic::Ordering::SeqCst)
|
||||
}
|
||||
|
||||
fn release(&self) {
|
||||
self.go.store(true, std::sync::atomic::Ordering::SeqCst);
|
||||
}
|
||||
|
||||
fn gave_up(&self) -> bool {
|
||||
self.gave_up.load(std::sync::atomic::Ordering::SeqCst)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for HeldLoad {
|
||||
fn drop(&mut self) {
|
||||
self.release();
|
||||
*crate::store::BEFORE_STORED_LOAD.lock().unwrap_or_else(|e| e.into_inner()) = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// A store holding the module of a filter `id` in `<id>.wasm`.
|
||||
fn store_with(name: &str, id: &str) -> (crate::tests_links::Folder, std::path::PathBuf) {
|
||||
let folder = crate::tests_links::Folder::new(name);
|
||||
let path = folder.0.join(format!("{id}.wasm"));
|
||||
std::fs::create_dir_all(&folder.0).unwrap();
|
||||
std::fs::write(&path, wat::parse_str(tpl::returning(&tpl::manifest(id, "filter", "{}"), r#"{"objects":[]}"#)).unwrap()).unwrap();
|
||||
(folder, path)
|
||||
}
|
||||
|
||||
/// With loads in the background, attaching a plug-in store returns while a stored module is
|
||||
/// still loading: the plug-in installs once its load is done, at the next plug-in command.
|
||||
#[test]
|
||||
fn a_store_attached_with_background_loads_returns_before_its_plugins_load() {
|
||||
let id = "test.engine.background";
|
||||
let (folder, path) = store_with("plugin-background", id);
|
||||
let held = HeldLoad::new(path);
|
||||
let mut s = session();
|
||||
s.load_plugins_in_background(true);
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
let returned_while_loading = !held.gave_up();
|
||||
while !held.entered() {
|
||||
std::thread::yield_now();
|
||||
}
|
||||
assert!(returned_while_loading, "attaching the store waited for the module to load");
|
||||
assert!(vectorcraft_plugins::registry::get(id).is_none(), "nothing installs before its load is done");
|
||||
assert!(s.poll_plugin_loads(), "still loading");
|
||||
held.release();
|
||||
let listed = run(&mut s, "plugin.list", json!({}));
|
||||
assert!(listed.to_string().contains(id), "plugin.list waits for the load and lists it: {listed}");
|
||||
assert!(!s.poll_plugin_loads());
|
||||
assert!(vectorcraft_plugins::registry::remove(id));
|
||||
}
|
||||
|
||||
/// Stored files that can't be opened take nothing from the bytes the stored plug-ins may read
|
||||
/// together: a module after 512 MiB of them still installs.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn unreadable_stored_files_leave_the_store_budget_to_the_others() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let id = "test.engine.budget.after";
|
||||
let (folder, _) = store_with("plugin-budget-unreadable", id);
|
||||
let per_file = vectorcraft_plugins::Limits::default().max_module_bytes as u64;
|
||||
let locked: Vec<_> = (0..crate::store::MAX_PLUGIN_STORE.div_ceil(per_file))
|
||||
.map(|n| {
|
||||
// Sparse files sorted before the module, each as long as a module may be.
|
||||
let path = folder.0.join(format!("a{n:03}.wasm"));
|
||||
std::fs::File::create(&path).unwrap().set_len(per_file).unwrap();
|
||||
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o000)).unwrap();
|
||||
path
|
||||
})
|
||||
.collect();
|
||||
// A process that may read any file (root) opens them all: nothing to check.
|
||||
if std::fs::File::open(&locked[0]).is_ok() {
|
||||
return;
|
||||
}
|
||||
let mut s = session();
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
let installed = vectorcraft_plugins::registry::get(id).is_some();
|
||||
for path in &locked {
|
||||
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).unwrap();
|
||||
}
|
||||
assert!(installed, "the files that couldn't be opened used up the store's bytes");
|
||||
assert!(vectorcraft_plugins::registry::remove(id));
|
||||
}
|
||||
|
||||
/// A stored file whose read fails on the worker thread gives back what it took of the bytes the
|
||||
/// stored plug-ins may read together, so a module after files that use them all up still installs.
|
||||
#[test]
|
||||
fn stored_files_whose_reads_fail_leave_the_store_budget_to_the_others() {
|
||||
struct Unhook {
|
||||
_lock: std::sync::MutexGuard<'static, ()>,
|
||||
}
|
||||
impl Drop for Unhook {
|
||||
fn drop(&mut self) {
|
||||
*crate::store::BEFORE_STORED_LOAD.lock().unwrap_or_else(|e| e.into_inner()) = None;
|
||||
}
|
||||
}
|
||||
let id = "test.engine.budget.failed";
|
||||
let (folder, module) = store_with("plugin-budget-failed", id);
|
||||
let len = std::fs::metadata(&module).unwrap().len();
|
||||
// Files sorted before the module, as long as it, that use up the bytes this test's store may read.
|
||||
for n in 0..4 {
|
||||
std::fs::write(folder.0.join(format!("a{n:03}.wasm")), vec![0; len as usize]).unwrap();
|
||||
}
|
||||
crate::store::PLUGIN_STORE_BUDGET.with(|b| b.set(4 * len));
|
||||
let _unhook = Unhook { _lock: STORED_HOOK.lock().unwrap_or_else(|e| e.into_inner()) };
|
||||
// Each of those files goes away as its load starts, so its read fails.
|
||||
let dir = folder.0.clone();
|
||||
*crate::store::BEFORE_STORED_LOAD.lock().unwrap_or_else(|e| e.into_inner()) = Some(std::sync::Arc::new(move |p: &std::path::Path| {
|
||||
if p.parent() == Some(dir.as_path()) && p.file_name().is_some_and(|n| n.to_string_lossy().starts_with('a')) {
|
||||
let _ = std::fs::remove_file(p);
|
||||
}
|
||||
}));
|
||||
let mut s = session();
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
let installed = vectorcraft_plugins::registry::get(id).is_some();
|
||||
crate::store::PLUGIN_STORE_BUDGET.with(|b| b.set(crate::store::MAX_PLUGIN_STORE));
|
||||
assert!(installed, "the files whose reads failed used up the store's bytes");
|
||||
assert!(vectorcraft_plugins::registry::remove(id));
|
||||
}
|
||||
|
||||
/// A stored file replaced after its module loaded, by one of the same length with the same modified
|
||||
/// time, is skipped: its content no longer holds the module. That holds for a file modified moments
|
||||
/// ago and for one modified an hour ago.
|
||||
#[test]
|
||||
fn a_stored_file_replaced_with_the_same_stamp_while_it_loaded_is_skipped() {
|
||||
struct Unhook {
|
||||
_lock: std::sync::MutexGuard<'static, ()>,
|
||||
}
|
||||
impl Drop for Unhook {
|
||||
fn drop(&mut self) {
|
||||
*crate::store::AFTER_STORED_LOAD.lock().unwrap_or_else(|e| e.into_inner()) = None;
|
||||
}
|
||||
}
|
||||
let _unhook = Unhook { _lock: STORED_HOOK.lock().unwrap_or_else(|e| e.into_inner()) };
|
||||
let hour = std::time::Duration::from_secs(3600);
|
||||
// A modified time ahead of the clock counts as moments ago however long the test takes.
|
||||
for (n, modified) in [std::time::SystemTime::now() + hour, std::time::SystemTime::now() - hour].into_iter().enumerate() {
|
||||
let id = format!("test.engine.background.replaced{n}");
|
||||
let (folder, path) = store_with(&format!("plugin-background-replaced{n}"), &id);
|
||||
std::fs::File::options().write(true).open(&path).unwrap().set_modified(modified).unwrap();
|
||||
let replaced = path.clone();
|
||||
// Set once the file holds other bytes with the old stamp, so the case reaches the check.
|
||||
let rewritten = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let done = rewritten.clone();
|
||||
*crate::store::AFTER_STORED_LOAD.lock().unwrap_or_else(|e| e.into_inner()) = Some(std::sync::Arc::new(move |p: &std::path::Path| {
|
||||
if p == replaced {
|
||||
let mut bytes = std::fs::read(p).unwrap();
|
||||
bytes.reverse();
|
||||
std::fs::write(p, &bytes).unwrap();
|
||||
std::fs::File::options().write(true).open(p).unwrap().set_modified(modified).unwrap();
|
||||
done.store(true, std::sync::atomic::Ordering::SeqCst);
|
||||
}
|
||||
}));
|
||||
let mut s = session();
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
let installed = vectorcraft_plugins::registry::remove(&id);
|
||||
assert!(rewritten.load(std::sync::atomic::Ordering::SeqCst), "the file was not replaced while it loaded ({n})");
|
||||
assert!(!installed, "the module installed from a file that no longer holds it ({n})");
|
||||
}
|
||||
}
|
||||
|
||||
/// While a session loads the plug-ins folder in the background, another session's `plugin.list`
|
||||
/// reports the folder as loading; once the load installs, it reports what loaded.
|
||||
#[test]
|
||||
fn another_session_lists_a_folder_still_loading_as_loading() {
|
||||
// Other tests' `prefs.set` replaces the folder last loaded, which the process keeps.
|
||||
if !in_own_process("another_session_lists_a_folder_still_loading_as_loading") {
|
||||
return;
|
||||
}
|
||||
let id = "test.engine.listedloading";
|
||||
let (folder, _) = store_with("plugin-listed-loading", id);
|
||||
let mut background = session();
|
||||
background.load_plugins_in_background(true);
|
||||
run(&mut background, "prefs.set", json!({"values": {"pluginsFolder": folder.0.display().to_string()}}));
|
||||
let mut other = session();
|
||||
let listed = run(&mut other, "plugin.list", json!({}));
|
||||
assert_eq!(listed["folder"]["loading"], true, "{listed}");
|
||||
background.finish_plugin_loads();
|
||||
let listed = run(&mut other, "plugin.list", json!({}));
|
||||
assert!(vectorcraft_plugins::registry::remove(id));
|
||||
assert_eq!(listed["folder"]["loaded"], json!([id]), "{listed}");
|
||||
assert!(listed["folder"].get("loading").is_none(), "{listed}");
|
||||
}
|
||||
|
||||
/// A `plugin.reload` doesn't replace the record of a folder load that started after it: once that
|
||||
/// load installs, `plugin.list` reports its folder.
|
||||
#[test]
|
||||
fn a_reload_keeps_the_record_of_a_folder_load_started_after_it() {
|
||||
// Other tests' `prefs.set` replaces the folder last loaded, which the process keeps.
|
||||
if !in_own_process("a_reload_keeps_the_record_of_a_folder_load_started_after_it") {
|
||||
return;
|
||||
}
|
||||
let (reloaded, later) = ("test.engine.reloadorder.reloaded", "test.engine.reloadorder.later");
|
||||
let (reload_folder, _) = store_with("plugin-reload-order-reloaded", reloaded);
|
||||
let (later_folder, _) = store_with("plugin-reload-order-later", later);
|
||||
let other = std::rc::Rc::new(std::cell::RefCell::new(None));
|
||||
let started = other.clone();
|
||||
let path = later_folder.0.display().to_string();
|
||||
// Another session sets the plug-ins folder while the reload loads.
|
||||
crate::cmd::plugin::BEFORE_RELOAD_INSTALLS.set(Some(Box::new(move || {
|
||||
let mut background = session();
|
||||
background.load_plugins_in_background(true);
|
||||
run(&mut background, "prefs.set", json!({"values": {"pluginsFolder": path}}));
|
||||
*started.borrow_mut() = Some(background);
|
||||
})));
|
||||
let mut s = session();
|
||||
run(&mut s, "plugin.reload", json!({"path": reload_folder.0.display().to_string()}));
|
||||
let mut background = other.borrow_mut().take().expect("the other session's load started while the reload loaded");
|
||||
background.finish_plugin_loads();
|
||||
let listed = run(&mut s, "plugin.list", json!({}));
|
||||
assert!(vectorcraft_plugins::registry::remove(reloaded) && vectorcraft_plugins::registry::remove(later));
|
||||
assert_eq!(listed["folder"]["loaded"], json!([later]), "{listed}");
|
||||
}
|
||||
|
||||
/// The plug-ins folder already loaded isn't loaded again when the preferences are applied, unless
|
||||
/// a file in it found no loader thread to load it: then it is.
|
||||
#[test]
|
||||
fn a_folder_in_which_a_file_found_no_thread_is_loaded_again() {
|
||||
if !in_own_process("a_folder_in_which_a_file_found_no_thread_is_loaded_again") {
|
||||
return;
|
||||
}
|
||||
let id = "test.engine.nothread";
|
||||
let (folder, _) = store_with("plugin-no-thread", id);
|
||||
let mut s = session();
|
||||
run(&mut s, "prefs.set", json!({"values": {"pluginsFolder": folder.0.display().to_string()}}));
|
||||
assert!(vectorcraft_plugins::registry::remove(id), "installed from the folder");
|
||||
crate::cmd::plugin::sync_prefs(&mut s);
|
||||
assert!(vectorcraft_plugins::registry::get(id).is_none(), "a folder already loaded was loaded again");
|
||||
crate::cmd::plugin::folder_found_no_thread();
|
||||
crate::cmd::plugin::sync_prefs(&mut s);
|
||||
assert!(vectorcraft_plugins::registry::remove(id), "the folder wasn't loaded again");
|
||||
}
|
||||
|
||||
/// A folder listed while the stored plug-ins still load, in the same session, replaces a stored
|
||||
/// plug-in with a module of the same id once it loads, as it does when the loads run one after the
|
||||
/// other: what an earlier load of the session installed doesn't count as a change made elsewhere.
|
||||
#[test]
|
||||
fn a_folder_queued_behind_the_stored_plugins_replaces_one_with_its_id() {
|
||||
let _folder = PREFS_FOLDER.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let id = "test.engine.queued.same";
|
||||
let (store, stored) = store_with("plugin-queued-store", id);
|
||||
let (folder, from_folder) = store_with("plugin-queued-folder", id);
|
||||
let held = HeldLoad::new(stored);
|
||||
let mut s = session();
|
||||
s.load_plugins_in_background(true);
|
||||
s.attach_plugin_store(store.0.clone());
|
||||
while !held.entered() {
|
||||
std::thread::yield_now();
|
||||
}
|
||||
s.prefs.plugins_folder = folder.0.display().to_string();
|
||||
crate::cmd::plugin::sync_prefs(&mut s);
|
||||
held.release();
|
||||
s.finish_plugin_loads();
|
||||
let source = vectorcraft_plugins::registry::get(id).and_then(|p| p.source().map(str::to_string));
|
||||
assert!(vectorcraft_plugins::registry::remove(id));
|
||||
assert_eq!(source.as_deref(), Some(from_folder.display().to_string().as_str()), "the folder's module replaces the stored one");
|
||||
}
|
||||
|
||||
/// A query that only reads runs while the stored plug-ins load in the background, and doesn't
|
||||
/// wait for them; a plug-in command does.
|
||||
#[test]
|
||||
fn a_query_runs_while_the_plugins_load() {
|
||||
let id = "test.engine.background.query";
|
||||
let (folder, path) = store_with("plugin-background-query", id);
|
||||
let held = HeldLoad::new(path);
|
||||
let mut s = session();
|
||||
run(&mut s, "file.new", json!({}));
|
||||
s.load_plugins_in_background(true);
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
while !held.entered() {
|
||||
std::thread::yield_now();
|
||||
}
|
||||
run(&mut s, "document.info", json!({}));
|
||||
let waited = held.gave_up() || !s.plugins_loading();
|
||||
held.release();
|
||||
assert!(!waited, "document.info waited for the plug-ins to load");
|
||||
assert!(crate::waits_for_plugin_loads("plugin.list") && !crate::waits_for_plugin_loads("document.info"));
|
||||
s.finish_plugin_loads();
|
||||
assert!(vectorcraft_plugins::registry::remove(id));
|
||||
}
|
||||
|
||||
/// The stored plug-ins load without holding the lock that `plugin.install` and `plugin.remove`
|
||||
/// take, so another session's plug-in changes don't wait for them.
|
||||
#[test]
|
||||
fn stored_plugins_load_without_holding_the_plugin_changes_lock() {
|
||||
let id = "test.engine.unlocked";
|
||||
let (folder, path) = store_with("plugin-unlocked", id);
|
||||
let held = HeldLoad::new(path);
|
||||
let mut s = session();
|
||||
s.load_plugins_in_background(true);
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
while !held.entered() && !held.gave_up() {
|
||||
std::thread::yield_now();
|
||||
}
|
||||
// Other tests take the lock for a moment; the load holding it would hold it throughout (a
|
||||
// tenth of the yields the held load waits before it gives up).
|
||||
let free = (0..100_000).any(|_| {
|
||||
std::thread::yield_now();
|
||||
crate::cmd::plugin::plugin_changes_free()
|
||||
});
|
||||
// A load that gave up waiting no longer holds anything, so a free lock then shows nothing.
|
||||
let gave_up = held.gave_up();
|
||||
held.release();
|
||||
s.finish_plugin_loads();
|
||||
assert!(!gave_up, "the held load gave up before the lock was looked at");
|
||||
assert!(free, "the lock was held while the module loaded");
|
||||
assert!(vectorcraft_plugins::registry::remove(id));
|
||||
}
|
||||
|
||||
/// Loads canceled as the app quits still end for what they installed: a stored module listing no
|
||||
/// permissions that installed before a later one finished loading has its id's grant forgotten,
|
||||
/// in the process and in `grants.json`, and the module still loading doesn't install.
|
||||
#[test]
|
||||
fn canceled_loads_forget_the_grants_of_what_they_installed() {
|
||||
use vectorcraft_plugins::permissions::sha256_hex;
|
||||
let (first, later) = ("test.engine.cancel.a", "test.engine.cancel.b");
|
||||
let (folder, _) = store_with("plugin-cancel", first);
|
||||
let held_path = folder.0.join(format!("{later}.wasm"));
|
||||
std::fs::write(&held_path, wat::parse_str(tpl::returning(&tpl::manifest(later, "filter", "{}"), r#"{"objects":[]}"#)).unwrap()).unwrap();
|
||||
let empty = json!({"objects": []});
|
||||
let approved = asking(first, r#"["doc.read"]"#, &empty);
|
||||
let grants = folder.0.join("grants.json");
|
||||
let entry = json!([{"id": first, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}]);
|
||||
std::fs::write(&grants, serde_json::to_vec(&entry).unwrap()).unwrap();
|
||||
let held = HeldLoad::new(held_path);
|
||||
let mut s = session();
|
||||
s.load_plugins_in_background(true);
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
while vectorcraft_plugins::registry::get(first).is_none() && !held.gave_up() {
|
||||
s.poll_plugin_loads();
|
||||
std::thread::yield_now();
|
||||
}
|
||||
assert!(vectorcraft_plugins::registry::get(first).is_some(), "the first module installed while the second loads");
|
||||
s.cancel_plugin_loads();
|
||||
// The file goes once it holds no grant.
|
||||
let listed: Vec<Value> = std::fs::read(&grants).map(|b| serde_json::from_slice(&b).unwrap()).unwrap_or_default();
|
||||
assert!(listed.iter().all(|e| e["id"] != first), "{listed:?}");
|
||||
assert!(vectorcraft_plugins::registry::granted(first).is_none());
|
||||
assert!(vectorcraft_plugins::registry::get(later).is_none(), "the module still loading doesn't install");
|
||||
assert!(!s.plugins_loading());
|
||||
drop(held);
|
||||
assert!(vectorcraft_plugins::registry::remove(first));
|
||||
}
|
||||
|
||||
/// The grants for a stored module that lists no permissions stop counting when it installs, in the
|
||||
/// same turn, while a later module of the load is still loading.
|
||||
#[test]
|
||||
fn a_stored_module_without_permissions_ends_its_grant_when_it_installs() {
|
||||
use vectorcraft_plugins::permissions::sha256_hex;
|
||||
let (first, later) = ("test.engine.retire.a", "test.engine.retire.b");
|
||||
let (folder, _) = store_with("plugin-retire", first);
|
||||
let held_path = folder.0.join(format!("{later}.wasm"));
|
||||
std::fs::write(&held_path, wat::parse_str(tpl::returning(&tpl::manifest(later, "filter", "{}"), r#"{"objects":[]}"#)).unwrap()).unwrap();
|
||||
let empty = json!({"objects": []});
|
||||
let approved = asking(first, r#"["doc.read"]"#, &empty);
|
||||
let grants = folder.0.join("grants.json");
|
||||
let entry = json!([{"id": first, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}]);
|
||||
std::fs::write(&grants, serde_json::to_vec(&entry).unwrap()).unwrap();
|
||||
let held = HeldLoad::new(held_path);
|
||||
let mut s = session();
|
||||
s.load_plugins_in_background(true);
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
while vectorcraft_plugins::registry::get(first).is_none() && !held.gave_up() {
|
||||
s.poll_plugin_loads();
|
||||
std::thread::yield_now();
|
||||
}
|
||||
assert!(vectorcraft_plugins::registry::get(first).is_some(), "the first module installed while the second loads");
|
||||
assert!(s.plugins_loading(), "the second module is still loading");
|
||||
let listed: Vec<Value> = std::fs::read(&grants).map(|b| serde_json::from_slice(&b).unwrap()).unwrap_or_default();
|
||||
assert!(listed.iter().all(|e| e["id"] != first), "{listed:?}");
|
||||
assert!(vectorcraft_plugins::registry::granted(first).is_none());
|
||||
drop(held);
|
||||
s.finish_plugin_loads();
|
||||
assert!(vectorcraft_plugins::registry::remove(first));
|
||||
assert!(vectorcraft_plugins::registry::remove(later));
|
||||
}
|
||||
|
||||
/// A grant the load removed for a stored module without permissions doesn't go back for a later
|
||||
/// file with the same id when another window or process granted the id since: that grant stays, and
|
||||
/// the later module, which it doesn't cover, is skipped.
|
||||
#[test]
|
||||
fn a_grant_given_elsewhere_since_the_load_removed_one_is_kept() {
|
||||
use vectorcraft_plugins::permissions::sha256_hex;
|
||||
let id = "test.engine.retire.kept";
|
||||
let folder = crate::tests_links::Folder::new("plugin-retire-kept");
|
||||
std::fs::create_dir_all(&folder.0).unwrap();
|
||||
let empty = json!({"objects": []});
|
||||
let (first, later) = (folder.0.join("a.wasm"), folder.0.join("b.wasm"));
|
||||
std::fs::write(&first, wat::parse_str(tpl::returning(&tpl::manifest(id, "filter", "{}"), r#"{"objects":[]}"#)).unwrap()).unwrap();
|
||||
let approved = asking(id, r#"["doc.read"]"#, &empty);
|
||||
std::fs::write(&later, &approved).unwrap();
|
||||
let grants = folder.0.join("grants.json");
|
||||
let entry = |hash: String| serde_json::to_vec(&json!([{"id": id, "hash": hash, "permissions": ["doc.read"]}])).unwrap();
|
||||
std::fs::write(&grants, entry(sha256_hex(&approved))).unwrap();
|
||||
let held = HeldLoad::new(later.clone());
|
||||
let mut s = session();
|
||||
s.load_plugins_in_background(true);
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
while vectorcraft_plugins::registry::get(id).is_none() && !held.gave_up() {
|
||||
s.poll_plugin_loads();
|
||||
std::thread::yield_now();
|
||||
}
|
||||
// Another process grants the id for another module while the later file loads.
|
||||
let other = asking(id, r#"["doc.read"]"#, &json!({"objects": [{"path": triangle()}]}));
|
||||
std::fs::write(&grants, entry(sha256_hex(&other))).unwrap();
|
||||
drop(held);
|
||||
s.finish_plugin_loads();
|
||||
let source = vectorcraft_plugins::registry::get(id).and_then(|p| p.source().map(str::to_string));
|
||||
assert!(vectorcraft_plugins::registry::remove(id));
|
||||
let listed: Vec<Value> = serde_json::from_slice(&std::fs::read(&grants).unwrap()).unwrap();
|
||||
assert_eq!(source.as_deref(), Some(first.display().to_string().as_str()), "the later module installed");
|
||||
assert_eq!(listed.iter().map(|e| e["hash"].clone()).collect::<Vec<_>>(), [json!(sha256_hex(&other))], "{listed:?}");
|
||||
}
|
||||
|
||||
/// A grant the load removed for a stored module without permissions that can't be written back for
|
||||
/// a later file with the same id leaves that file's module uninstalled: the store doesn't grant it.
|
||||
#[test]
|
||||
fn a_grant_that_cannot_be_put_back_leaves_the_later_module_uninstalled() {
|
||||
use vectorcraft_plugins::permissions::sha256_hex;
|
||||
let id = "test.engine.retire.unwritten";
|
||||
let folder = crate::tests_links::Folder::new("plugin-retire-unwritten");
|
||||
std::fs::create_dir_all(&folder.0).unwrap();
|
||||
let empty = json!({"objects": []});
|
||||
let (first, later) = (folder.0.join("a.wasm"), folder.0.join("b.wasm"));
|
||||
std::fs::write(&first, wat::parse_str(tpl::returning(&tpl::manifest(id, "filter", "{}"), r#"{"objects":[]}"#)).unwrap()).unwrap();
|
||||
let approved = asking(id, r#"["doc.read"]"#, &empty);
|
||||
std::fs::write(&later, &approved).unwrap();
|
||||
let grants = folder.0.join("grants.json");
|
||||
std::fs::write(&grants, serde_json::to_vec(&json!([{"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}])).unwrap()).unwrap();
|
||||
// The first write removes the grant; the second, which puts it back, finds a folder where the
|
||||
// file goes and fails.
|
||||
let blocked = grants.clone();
|
||||
crate::store::AFTER_GRANTS_READ.set(Some(Box::new(move || {
|
||||
crate::store::AFTER_GRANTS_READ.set(Some(Box::new(move || {
|
||||
let _ = std::fs::remove_file(&blocked);
|
||||
std::fs::create_dir_all(&blocked).unwrap();
|
||||
})));
|
||||
})));
|
||||
let mut s = session();
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
crate::store::AFTER_GRANTS_READ.set(None);
|
||||
let source = vectorcraft_plugins::registry::get(id).and_then(|p| p.source().map(str::to_string));
|
||||
let _ = std::fs::remove_dir(&grants);
|
||||
assert!(vectorcraft_plugins::registry::remove(id));
|
||||
assert_eq!(source.as_deref(), Some(first.display().to_string().as_str()), "the later module installed without its grant in the store");
|
||||
}
|
||||
|
||||
/// A grant the load put back for a later stored file with the same id is removed again when that
|
||||
/// file's module doesn't install because the id was installed elsewhere meanwhile: the store doesn't
|
||||
/// grant bytes that weren't installed.
|
||||
#[test]
|
||||
fn a_grant_put_back_for_a_module_that_did_not_install_is_removed_again() {
|
||||
use vectorcraft_plugins::permissions::sha256_hex;
|
||||
let id = "test.engine.retire.superseded";
|
||||
let folder = crate::tests_links::Folder::new("plugin-retire-superseded");
|
||||
std::fs::create_dir_all(&folder.0).unwrap();
|
||||
let empty = json!({"objects": []});
|
||||
let (first, later) = (folder.0.join("a.wasm"), folder.0.join("b.wasm"));
|
||||
let plain = wat::parse_str(tpl::returning(&tpl::manifest(id, "filter", "{}"), r#"{"objects":[]}"#)).unwrap();
|
||||
std::fs::write(&first, &plain).unwrap();
|
||||
let approved = asking(id, r#"["doc.read"]"#, &empty);
|
||||
std::fs::write(&later, &approved).unwrap();
|
||||
let grants = folder.0.join("grants.json");
|
||||
std::fs::write(&grants, serde_json::to_vec(&json!([{"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}])).unwrap()).unwrap();
|
||||
// The first write removes the grant; while the second puts it back, the id is installed
|
||||
// elsewhere.
|
||||
crate::store::AFTER_GRANTS_READ.set(Some(Box::new(move || {
|
||||
crate::store::AFTER_GRANTS_READ.set(Some(Box::new(move || {
|
||||
vectorcraft_plugins::registry::install_bytes(&plain).unwrap();
|
||||
})));
|
||||
})));
|
||||
let mut s = session();
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
crate::store::AFTER_GRANTS_READ.set(None);
|
||||
let source = vectorcraft_plugins::registry::get(id).and_then(|p| p.source().map(str::to_string));
|
||||
assert!(vectorcraft_plugins::registry::remove(id));
|
||||
// A grants file that went away holds no grant; one still there must read as a list.
|
||||
let listed: Vec<Value> = match std::fs::read(&grants) {
|
||||
Ok(b) => serde_json::from_slice(&b).unwrap(),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => vec![],
|
||||
Err(e) => panic!("the grants file could not be read: {e}"),
|
||||
};
|
||||
assert_eq!(source, None, "the later module replaced the one installed elsewhere");
|
||||
assert!(listed.iter().all(|e| e["id"] != id), "the grant put back stayed in the store: {listed:?}");
|
||||
}
|
||||
|
||||
/// A session that waits for its loads and sets the plug-ins folder another session is still
|
||||
/// loading in the background loads the folder itself: its plug-in is installed when `prefs.set`
|
||||
/// returns, and the other session's load, when it installs, counts the same module as loaded.
|
||||
#[test]
|
||||
fn a_folder_another_session_is_loading_is_loaded_by_a_session_that_waits() {
|
||||
let _folder = PREFS_FOLDER.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let id = "test.engine.sharedfolder";
|
||||
let (folder, _) = store_with("plugin-shared-folder", id);
|
||||
let path = folder.0.display().to_string();
|
||||
let mut background = session();
|
||||
background.load_plugins_in_background(true);
|
||||
run(&mut background, "prefs.set", json!({"values": {"pluginsFolder": path}}));
|
||||
assert!(background.plugins_loading(), "the folder loads in the background");
|
||||
let mut waits = session();
|
||||
run(&mut waits, "prefs.set", json!({"values": {"pluginsFolder": path}}));
|
||||
assert!(vectorcraft_plugins::registry::get(id).is_some(), "prefs.set returned before the folder's plug-in installed");
|
||||
let report = run(&mut background, "plugin.list", json!({}));
|
||||
assert!(!background.plugins_loading());
|
||||
assert!(vectorcraft_plugins::registry::remove(id), "{report}");
|
||||
}
|
||||
|
||||
/// A heavy test filter `id` that counts `steps` down, then adds a triangle named "Plug-in".
|
||||
fn heavy(id: &str, steps: u64) -> Vec<u8> {
|
||||
let manifest = format!(r#"{{"id":"{id}","name":"Test {id}","version":"1","kind":"filter","budget":"heavy"}}"#);
|
||||
@@ -4085,6 +4629,168 @@ fn read_only_kind_field_and_omission_refuse_without_undo() {
|
||||
assert!(e.contains("`inputs` needs `api` 2"), "{e}");
|
||||
}
|
||||
|
||||
/// The manifest of a filter at `api` 3 with id `id` that asks for the document information
|
||||
/// `context` (a JSON list), with `doc.read` and `doc.write`, and `rest` (keys after a comma, or
|
||||
/// nothing).
|
||||
fn context_manifest(id: &str, context: &str, rest: &str) -> String {
|
||||
format!(r#"{{"id":"{id}","name":"Test {id}","kind":"filter","api":3,"permissions":["doc.read","doc.write"],"context":{context}{rest}}}"#)
|
||||
}
|
||||
|
||||
/// Installs `src` granted `doc.read` and `doc.write`, in place of any module with its id.
|
||||
fn install_reading(s: &mut Session, src: &str) -> Value {
|
||||
let data = vectorcraft_format::base64_encode(&wat::parse_str(src).unwrap());
|
||||
run(s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read", "doc.write"], "replace": true}))
|
||||
}
|
||||
|
||||
/// A filter at `api` 3 whose manifest lists `context` is given the document's settings, artboards,
|
||||
/// layers and swatches in `_context.document` with nothing selected: plain values, hidden and
|
||||
/// locked layers with their flags, the active artboard and the current layer marked, and the
|
||||
/// document's name without its folder. A filter that doesn't list `context` is given none, and one
|
||||
/// that lists it without `doc.read` or below `api` 3 doesn't install.
|
||||
#[test]
|
||||
fn an_unselected_filter_reads_the_document_context_it_asks_for() {
|
||||
use cmd::plugin::FilterRun;
|
||||
let mut s = session();
|
||||
run(&mut s, "artboard.new", json!({"x": 500, "y": 0, "width": 100, "height": 50}));
|
||||
let hidden = run(&mut s, "layer.new", json!({"name": "Hidden", "visible": false}))["id"].as_u64().unwrap();
|
||||
let locked = run(&mut s, "layer.newSublayer", json!({"parent": hidden, "name": "Locked", "locked": true}))["id"].as_u64().unwrap();
|
||||
run(&mut s, "layer.setCurrent", json!({"id": locked}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Tone", "color": "#ff0000", "global": true}));
|
||||
run(&mut s, "select.none", json!({}));
|
||||
s.doc_mut().unwrap().path = Some("/private/folder/Poster.vectorcraft".into());
|
||||
let second = s.doc().unwrap().doc.artboards[1].id;
|
||||
s.doc_mut().unwrap().active_artboard = Some(second);
|
||||
let id = "test.engine.context";
|
||||
let all = r#"["settings","artboards","layers","swatches"]"#;
|
||||
let installed = install_reading(&mut s, &tpl::returning(&context_manifest(id, all, ""), r#"{"objects":[]}"#));
|
||||
assert_eq!(installed["context"], json!(["settings", "artboards", "layers", "swatches"]));
|
||||
let swatches = run(&mut s, "swatch.list", json!({}))["swatches"].clone();
|
||||
assert!(s.doc().unwrap().selection.objects.is_empty());
|
||||
let given = FilterRun::prepare(&s, &json!({"id": id})).unwrap().params_json()["_context"]["document"].clone();
|
||||
let st = s.doc().unwrap();
|
||||
let d = &st.doc;
|
||||
assert_eq!(given["revision"], json!(st.revision));
|
||||
let board = &d.artboards[1];
|
||||
let settings = json!({
|
||||
"name": "Poster.vectorcraft", "colorMode": "rgb", "units": d.units.label(), "width": board.rect.width(),
|
||||
"height": board.rect.height(), "bleed": d.setup.bleed, "rasterEffectsPpi": d.raster_ppi(), "activeArtboard": second,
|
||||
});
|
||||
assert_eq!(given["settings"], settings);
|
||||
let boards: Vec<Value> = d
|
||||
.artboards
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, a)| json!({"id": a.id, "index": i, "name": a.name, "rect": [a.rect.x0, a.rect.y0, a.rect.x1, a.rect.y1], "active": i == 1}))
|
||||
.collect();
|
||||
assert_eq!((boards.len(), &given["artboards"]), (2, &json!(boards)));
|
||||
let layers = given["layers"].as_array().unwrap();
|
||||
let rows: Vec<(String, u64, bool, bool, bool)> = layers
|
||||
.iter()
|
||||
.map(|l| {
|
||||
(l["name"].as_str().unwrap().to_string(), l["depth"].as_u64().unwrap(), l["visible"] == true, l["locked"] == true, l["current"] == true)
|
||||
})
|
||||
.collect();
|
||||
let bottom = d.layers[0].display_name();
|
||||
assert_eq!(rows, [(bottom, 0, true, false, false), ("Hidden".into(), 0, false, false, false), ("Locked".into(), 1, true, true, true)]);
|
||||
assert_eq!((&layers[0]["parentId"], &layers[1]["sublayers"], &layers[2]["parentId"]), (&Value::Null, &json!(1), &json!(hidden)));
|
||||
assert_eq!((&layers[1]["id"], &layers[2]["id"]), (&json!(hidden), &json!(locked)));
|
||||
assert_eq!(given["swatches"], swatches, "as swatch.list lists them");
|
||||
assert!(given["swatches"].as_array().unwrap().iter().any(|w| w["name"] == "Tone" && w["global"] == true));
|
||||
assert!(!given.to_string().contains("/private/folder"), "no path: {given}");
|
||||
// Only the sections asked for.
|
||||
let some = "test.engine.context.some";
|
||||
install_reading(&mut s, &tpl::returning(&context_manifest(some, r#"["layers"]"#, ""), r#"{"objects":[]}"#));
|
||||
let given = FilterRun::prepare(&s, &json!({"id": some})).unwrap().params_json()["_context"]["document"].clone();
|
||||
let keys: Vec<&String> = given.as_object().unwrap().keys().collect();
|
||||
assert_eq!(keys.len(), 2, "{keys:?}");
|
||||
assert!(given.get("layers").is_some() && given.get("revision").is_some());
|
||||
// A filter without `context` is given none.
|
||||
let legacy = "test.engine.context.legacy";
|
||||
install_reading(&mut s, &tpl::returning(&tpl::manifest(legacy, "filter", "{}"), r#"{"objects":[]}"#));
|
||||
assert!(FilterRun::prepare(&s, &json!({"id": legacy})).unwrap().params_json()["_context"].get("document").is_none());
|
||||
// Without `doc.read`, or below `api` 3, it doesn't install.
|
||||
let needs = "`context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read`";
|
||||
for manifest in [
|
||||
format!(r#"{{"id":"{some}","name":"x","kind":"filter","api":3,"permissions":["doc.write"],"context":["layers"]}}"#),
|
||||
format!(r#"{{"id":"{some}","name":"x","kind":"filter","api":2,"permissions":["doc.read"],"context":["layers"]}}"#),
|
||||
] {
|
||||
let data = vectorcraft_format::base64_encode(&wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap());
|
||||
let e = s.execute("plugin.install", &json!({"dataBase64": data, "grant": ["doc.read", "doc.write"], "replace": true})).unwrap_err();
|
||||
assert!(e.to_string().contains(needs), "{manifest}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A plug-in command, of a filter or of a live effect, whose manifest lists `context` is given it
|
||||
/// too, with nothing selected.
|
||||
#[test]
|
||||
fn a_plugin_command_reads_the_document_context_without_a_selection() {
|
||||
let mut s = session();
|
||||
let made = json!({"objects": [{"path": triangle(), "name": "Saw layers"}]}).to_string();
|
||||
for (id, kind, permissions) in [
|
||||
("test.engine.context.command", "filter", r#"["doc.read","doc.write"]"#),
|
||||
("test.engine.context.effectcommand", "effect", r#"["doc.read","doc.write","effect.render"]"#),
|
||||
] {
|
||||
let manifest = format!(
|
||||
r#"{{"id":"{id}","name":"Test {id}","kind":"{kind}","api":3,"permissions":{permissions},"context":["layers"],"commands":[{{"id":"look","label":"Look"}}]}}"#
|
||||
);
|
||||
let src = tpl::when_given_else(&manifest, tpl::Given::Params, r#""layers":["#, &made, r#"{"objects":[]}"#);
|
||||
let data = vectorcraft_format::base64_encode(&wat::parse_str(src).unwrap());
|
||||
let grant: Vec<Value> = serde_json::from_str(permissions).unwrap();
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": grant, "replace": true}));
|
||||
run(&mut s, "select.none", json!({}));
|
||||
let ids = run(&mut s, &format!("plugin.{id}.look"), json!({}))["ids"].clone();
|
||||
assert_eq!(ids.as_array().map(Vec::len), Some(1), "{kind}: {ids}");
|
||||
assert_eq!(node(&s, NodeId(ids[0].as_u64().unwrap())).name.as_deref(), Some("Saw layers"), "{kind}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A document context holds at most [`cmd::plugin::MAX_CONTEXT_ITEMS`] rows in
|
||||
/// [`cmd::plugin::MAX_CONTEXT_BYTES`] bytes: past either, the run fails before the plug-in starts,
|
||||
/// with the document and undo history as they were. Each row comes off the run's instruction
|
||||
/// budget.
|
||||
#[test]
|
||||
fn the_document_context_is_capped_and_its_rows_cost_instructions() {
|
||||
use cmd::plugin::{CONTEXT_FUEL_PER_ITEM, FilterRun, MAX_CONTEXT_BYTES, MAX_CONTEXT_ITEMS};
|
||||
let mut s = session();
|
||||
let id = "test.engine.context.cap";
|
||||
install_reading(&mut s, &tpl::returning(&context_manifest(id, r#"["swatches"]"#, ""), r#"{"objects":[]}"#));
|
||||
let p = json!({"id": id});
|
||||
let listed = run(&mut s, "swatch.list", json!({}))["swatches"].as_array().unwrap().len();
|
||||
let add = |s: &mut Session, n: usize| {
|
||||
s.edit("Set up", |d, _| {
|
||||
let base = d.swatches.last().unwrap().clone();
|
||||
let at = d.swatches.len();
|
||||
d.swatches.extend((at..at + n).map(|i| vectorcraft_color::Swatch { name: format!("Many {i}"), ..base.clone() }));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
};
|
||||
add(&mut s, MAX_CONTEXT_ITEMS - listed);
|
||||
let full = FilterRun::prepare(&s, &p).unwrap();
|
||||
assert_eq!(full.params_json()["_context"]["document"]["swatches"].as_array().map(Vec::len), Some(MAX_CONTEXT_ITEMS));
|
||||
assert_eq!(full.limits().fuel_base, full.plugin().limits().fuel_base - MAX_CONTEXT_ITEMS as u64 * CONTEXT_FUEL_PER_ITEM);
|
||||
let too_large = "the document information the plug-in asks for is too large to hand over";
|
||||
add(&mut s, 1);
|
||||
let refused = |s: &mut Session| {
|
||||
let Err(e) = FilterRun::prepare(s, &p) else { panic!("prepared past the cap") };
|
||||
assert!(e.to_string().contains(too_large), "{e}");
|
||||
let (doc, undo) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len());
|
||||
let e = s.execute("plugin.run", &p).unwrap_err().to_string();
|
||||
assert!(e.contains(too_large), "{e}");
|
||||
assert_eq!((&s.doc().unwrap().doc, s.doc().unwrap().history.undo.len()), (&doc, undo));
|
||||
};
|
||||
refused(&mut s);
|
||||
// A few rows past the byte cap are refused as well.
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
s.edit("Set up", |d, _| {
|
||||
d.swatches.last_mut().unwrap().name = "n".repeat(MAX_CONTEXT_BYTES);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
refused(&mut s);
|
||||
}
|
||||
|
||||
/// A run past its memory budget fails before the plug-in starts, with the document and undo
|
||||
/// history as they were: a read-only object whose other fields don't fit, a path and a compound
|
||||
/// path that don't fit, and parameters past the input's half of the cap, with objects selected or
|
||||
@@ -4798,6 +5504,82 @@ fn plugin_commands_are_registered_run_and_removed() {
|
||||
assert!(s.execute(grow, &json!({})).is_err(), "removed, it no longer runs");
|
||||
}
|
||||
|
||||
/// At API level 2 a command's `menu` lists it in that menu with its plug-in's name after its
|
||||
/// label, and `plugin.list` gives its `menu` with `after` escaped. A command whose label reads like
|
||||
/// a built-in command of that menu, or like a command a plug-in with a lower id places there,
|
||||
/// stays in its plug-in's submenu, and `plugin.list` marks it `placed: false`. Replaced by a module
|
||||
/// whose command has no `menu`, a command is back in its submenu.
|
||||
#[test]
|
||||
fn placed_plugin_commands_are_listed_in_their_menu() {
|
||||
let mut s = session();
|
||||
let placing = |id: &str, name: &str, commands: &str| {
|
||||
let manifest = format!(r#"{{"id":"{id}","name":"{name}","api":2,"version":"1","kind":"filter","commands":{commands}}}"#);
|
||||
tpl::returning(&manifest, r#"{"objects":[]}"#)
|
||||
};
|
||||
let (ant, bee, cat) = ("test.engine.place.ant", "test.engine.place.bee", "test.engine.place.cat");
|
||||
let low = |id: &str| crate::cmd::plugin::command_id(id, "low");
|
||||
let menu_of = |s: &Session, command: &str| listed(s, command).map(|c| c.menu.iter().map(|m| m.to_string()).collect::<Vec<_>>());
|
||||
let in_select = json!([{"id": "low", "label": "Low Area", "menu": {"path": ["Select"], "after": "\u{202E}Inverse"}}]).to_string();
|
||||
let in_select = in_select.as_str();
|
||||
|
||||
let info = install_wat(&mut s, &placing(ant, "Tidy", in_select));
|
||||
let menu = &info["commands"][0]["menu"];
|
||||
assert_eq!(menu["path"], json!(["Select"]));
|
||||
assert!(menu["after"].as_str().is_some_and(|a| a.ends_with("Inverse") && !a.contains('\u{202E}')), "escaped: {menu}");
|
||||
assert!(menu.get("placed").is_none(), "{menu}");
|
||||
let c = listed(&s, &low(ant)).expect("listed");
|
||||
assert_eq!((c.label, menu_of(&s, &low(ant))), ("Low Area (Tidy)", Some(vec!["Select".to_string()])));
|
||||
|
||||
// Another plug-in of the same name placing the same label at the same spot stays in its submenu.
|
||||
let info = install_wat(&mut s, &placing(bee, "Tidy", in_select));
|
||||
assert_eq!(info["commands"][0]["menu"]["placed"], json!(false));
|
||||
assert_eq!(listed(&s, &low(bee)).map(|c| c.label), Some("Low Area"));
|
||||
assert_eq!(menu_of(&s, &low(bee)), Some(vec!["Object".into(), "Plug-ins".into(), "Tidy".into()]));
|
||||
assert_eq!(menu_of(&s, &low(ant)), Some(vec!["Select".to_string()]));
|
||||
|
||||
// `Paste (in Place)` reads like Edit's Paste in Place; Keep is placed.
|
||||
let edit = r#"[{"id":"paste","label":"Paste","menu":{"path":["Edit"]}},{"id":"keep","label":"Keep","menu":{"path":["Edit"]}}]"#;
|
||||
let info = install_wat(&mut s, &placing(cat, "in Place", edit));
|
||||
assert_eq!(info["commands"][0]["menu"]["placed"], json!(false));
|
||||
assert!(info["commands"][1]["menu"].get("placed").is_none());
|
||||
let paste = crate::cmd::plugin::command_id(cat, "paste");
|
||||
assert_eq!(menu_of(&s, &paste), Some(vec!["Object".into(), "Plug-ins".into(), "in Place".into()]));
|
||||
assert_eq!(menu_of(&s, &crate::cmd::plugin::command_id(cat, "keep")), Some(vec!["Edit".to_string()]));
|
||||
// `Stop Global (Edit)` reads like the other label of Select's Start Global Edit.
|
||||
let dog = "test.engine.place.dog";
|
||||
let info = install_wat(&mut s, &placing(dog, "Edit", r#"[{"id":"stop","label":"Stop Global","menu":{"path":["Select"]}}]"#));
|
||||
assert_eq!(info["commands"][0]["menu"]["placed"], json!(false));
|
||||
run(&mut s, "plugin.remove", json!({"id": dog}));
|
||||
// Object's Show All has one label, so `Hide (All)` is placed beside it.
|
||||
let all = "test.engine.place.all";
|
||||
let info = install_wat(&mut s, &placing(all, "All", r#"[{"id":"hide","label":"Hide","menu":{"path":["Object"]}}]"#));
|
||||
assert!(info["commands"][0]["menu"].get("placed").is_none(), "{}", info["commands"][0]);
|
||||
assert_eq!(menu_of(&s, &crate::cmd::plugin::command_id(all, "hide")), Some(vec!["Object".to_string()]));
|
||||
run(&mut s, "plugin.remove", json!({"id": all}));
|
||||
// `Hide (Edges)` reads like the desktop app's View › Hide Edges, with or without the desktop app.
|
||||
let edges = "test.engine.place.edges";
|
||||
let info = install_wat(&mut s, &placing(edges, "Edges", r#"[{"id":"hide","label":"Hide","menu":{"path":["View"]}}]"#));
|
||||
assert_eq!(info["commands"][0]["menu"]["placed"], json!(false));
|
||||
run(&mut s, "plugin.remove", json!({"id": edges}));
|
||||
// Inspecting a plug-in that is not installed reports what installing it gives: of two commands
|
||||
// with one label at one spot, the second stays in its submenu.
|
||||
let twice = r#"[{"id":"a","label":"Low","menu":{"path":["Select"]}},{"id":"b","label":"Low","menu":{"path":["Select"]}}]"#;
|
||||
let data = vectorcraft_format::base64_encode(&wat::parse_str(placing("test.engine.place.eel", "Eel", twice)).unwrap());
|
||||
let inspected = run(&mut s, "plugin.inspect", json!({"dataBase64": data}));
|
||||
assert!(inspected["commands"][0]["menu"].get("placed").is_none(), "{inspected}");
|
||||
assert_eq!(inspected["commands"][1]["menu"]["placed"], json!(false), "{inspected}");
|
||||
|
||||
// Replaced by a module whose command has no `menu`, Ant's command is back in its submenu and
|
||||
// Bee's takes the spot.
|
||||
install_wat(&mut s, &placing(ant, "Tidy", r#"[{"id":"low","label":"Low Area"}]"#));
|
||||
assert_eq!(menu_of(&s, &low(ant)), Some(vec!["Object".into(), "Plug-ins".into(), "Tidy".into()]));
|
||||
assert_eq!(menu_of(&s, &low(bee)), Some(vec!["Select".to_string()]));
|
||||
for id in [ant, bee, cat] {
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
}
|
||||
assert!(listed(&s, &low(bee)).is_none());
|
||||
}
|
||||
|
||||
/// A command run is journaled like any other, so an action records it with its parameters and
|
||||
/// plays it back.
|
||||
#[test]
|
||||
|
||||
@@ -550,6 +550,18 @@ fn continuous_arc_after_a_line(s: &mut Session, v: ViewInfo) {
|
||||
key(s, ToolKey::AltTap);
|
||||
}
|
||||
|
||||
/// Whether the tool shows only the path's points and its length handles (a handle and the line to
|
||||
/// it from the path's end): no hover preview, label or Smart Guide.
|
||||
fn only_points(s: &mut Session, v: ViewInfo) -> bool {
|
||||
let o = s.overlays(v);
|
||||
let handles: Vec<Point> = o.iter().filter_map(|o| if let Overlay::Handle { p, .. } = o { Some(*p) } else { None }).collect();
|
||||
o.iter().all(|o| match o {
|
||||
Overlay::CurvePoint { .. } | Overlay::Handle { .. } => true,
|
||||
Overlay::Line { b, .. } => handles.contains(b),
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
|
||||
/// The last point of the path the tool drew (any other path is a two-point line).
|
||||
fn drawn_end(s: &Session) -> Point {
|
||||
let drawn = paths(s).into_iter().find(|(_, p)| p.subpaths[0].anchors.len() >= 3).unwrap();
|
||||
@@ -710,9 +722,8 @@ fn a_hover_shows_nothing_after_smart_guides_change() {
|
||||
s.pointer(&PointerEvent::new(PointerKind::Move, at.x, at.y), on).unwrap();
|
||||
let off_anchor = label(&mut s, on).unwrap() - at;
|
||||
assert!(off_anchor.x > 0.0 && (off_anchor.x - off_anchor.y).abs() < 1e-9, "the label sits diagonally off the anchor: {off_anchor:?}");
|
||||
let only_points = |s: &mut Session, v: ViewInfo| s.overlays(v).iter().all(|o| matches!(o, Overlay::CurvePoint { .. }));
|
||||
assert!(!only_points(&mut s, on));
|
||||
assert!(only_points(&mut s, off), "only the path's points show");
|
||||
assert!(only_points(&mut s, off), "only the path's points and length handles show");
|
||||
// A click before the pointer moves does not bring the stale hover back.
|
||||
press_in(&mut s, &[(400.0, 300.0)], off);
|
||||
assert_eq!(label(&mut s, off), None, "no label for the stale hover after the click");
|
||||
@@ -746,7 +757,6 @@ fn a_click_that_adds_nothing_keeps_a_stale_hover_hidden() {
|
||||
s.execute("select.set", &json!({"ids": []})).unwrap();
|
||||
continuous_arc_after_a_line(&mut s, on);
|
||||
s.pointer(&PointerEvent::new(PointerKind::Move, 200.0, 100.0), on).unwrap();
|
||||
let only_points = |s: &mut Session, v: ViewInfo| s.overlays(v).iter().all(|o| matches!(o, Overlay::CurvePoint { .. }));
|
||||
assert!(!only_points(&mut s, on), "the anchor's guide shows");
|
||||
assert!(only_points(&mut s, off));
|
||||
let steps = undo_steps(&s);
|
||||
@@ -891,6 +901,467 @@ fn path_quick_pen_refuses_bad_params() {
|
||||
assert_eq!(paths(&s).len(), before.len());
|
||||
}
|
||||
|
||||
/// The handle beyond the end of the path being drawn makes its last line longer, as one undo step,
|
||||
/// and the next click goes on from the new end.
|
||||
#[test]
|
||||
fn dragging_the_end_handle_lengthens_the_last_line() {
|
||||
let mut s = session();
|
||||
quick_pen(&mut s);
|
||||
click(&mut s, 100.0, 100.0);
|
||||
click(&mut s, 200.0, 100.0);
|
||||
let undo = undo_steps(&s);
|
||||
// The handle stands 20 screen points beyond the end, along the line.
|
||||
press(&mut s, &[(220.0, 100.0), (250.0, 130.0), (280.0, 140.0)]);
|
||||
let ends: Vec<Point> = only_path(&s).anchors.iter().map(|a| a.p).collect();
|
||||
assert_eq!(ends, [pt(100.0, 100.0), pt(260.0, 100.0)]);
|
||||
assert_eq!(undo_steps(&s), undo + 1);
|
||||
click(&mut s, 260.0, 200.0);
|
||||
let ends: Vec<Point> = only_path(&s).anchors.iter().map(|a| a.p).collect();
|
||||
assert_eq!(ends, [pt(100.0, 100.0), pt(260.0, 100.0), pt(260.0, 200.0)], "the drawing went on");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(200.0, 100.0));
|
||||
}
|
||||
|
||||
/// Dragged by its end handle, the last sharp-corner arc goes on around its circle and stays the
|
||||
/// last piece, so C still flips it and `[` `]` still change its size.
|
||||
#[test]
|
||||
fn a_dragged_last_arc_still_flips() {
|
||||
let mut s = session();
|
||||
quick_pen(&mut s);
|
||||
s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "sharpArc"})).unwrap();
|
||||
click(&mut s, 100.0, 300.0);
|
||||
click(&mut s, 300.0, 300.0);
|
||||
let undo = undo_steps(&s);
|
||||
// The half circle over (200, 300) ends heading down, so its end handle is 20 points below. The
|
||||
// handle turned a quarter around the center, to (180, 400), takes the end to (200, 400).
|
||||
press(&mut s, &[(300.0, 320.0), (260.0, 400.0), (180.0, 400.0)]);
|
||||
let sp = only_path(&s);
|
||||
assert!(sp.anchors.last().unwrap().p.distance(pt(200.0, 400.0)) < 1e-6, "three quarters around: {:?}", sp.anchors.last());
|
||||
assert_eq!(sp.anchors.len(), 4);
|
||||
assert_eq!(undo_steps(&s), undo + 1);
|
||||
assert!(s.tool_claims_key(ToolKey::Letter('c'), view()));
|
||||
key(&mut s, ToolKey::Letter('c'));
|
||||
let flipped = only_path(&s);
|
||||
assert_ne!(flipped, sp);
|
||||
assert!(flipped.anchors.last().unwrap().p.distance(pt(200.0, 400.0)) < 1e-6);
|
||||
assert_eq!(undo_steps(&s), undo + 2);
|
||||
// `]` makes the dragged arc 15° larger: it keeps its ends and gains its own undo step.
|
||||
key(&mut s, ToolKey::BracketRight);
|
||||
let larger = only_path(&s);
|
||||
assert_ne!(larger, flipped);
|
||||
assert!(larger.anchors.last().unwrap().p.distance(pt(200.0, 400.0)) < 1e-6);
|
||||
assert_eq!(undo_steps(&s), undo + 3);
|
||||
}
|
||||
|
||||
/// Dragged back past its start, the last sharp-corner arc stops at 1°.
|
||||
#[test]
|
||||
fn a_dragged_last_arc_keeps_at_least_one_degree() {
|
||||
let mut s = session();
|
||||
quick_pen(&mut s);
|
||||
s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "sharpArc"})).unwrap();
|
||||
click(&mut s, 100.0, 300.0);
|
||||
click(&mut s, 300.0, 300.0);
|
||||
// The half circle about (200, 300) runs over the top from (100, 300) to (300, 300); its end
|
||||
// handle is 20 points below the end. The pointer goes back around the circle from there, past
|
||||
// the start of the arc.
|
||||
let (c, r) = (pt(200.0, 300.0), (100.0f64 * 100.0 + 20.0 * 20.0).sqrt());
|
||||
let a0 = 20.0f64.atan2(100.0);
|
||||
let mut pts = vec![(300.0, 320.0)];
|
||||
for d in [45.0f64, 90.0, 135.0, 175.0, 185.0] {
|
||||
let a = a0 - d.to_radians();
|
||||
pts.push((c.x + r * a.cos(), c.y + r * a.sin()));
|
||||
}
|
||||
press(&mut s, &pts);
|
||||
let sp = only_path(&s);
|
||||
let one = 181f64.to_radians();
|
||||
let end = pt(200.0 + 100.0 * one.cos(), 300.0 + 100.0 * one.sin());
|
||||
assert!(sp.anchors.last().unwrap().p.distance(end) < 1e-6, "{:?}", sp.anchors.last());
|
||||
assert_eq!(sp.anchors.first().unwrap().p, pt(100.0, 300.0));
|
||||
}
|
||||
|
||||
/// When the last arc goes on around the circle of the arc before it, its end handle still changes
|
||||
/// the last arc alone, which C then still flips.
|
||||
#[test]
|
||||
fn the_end_handle_changes_the_last_arc_on_a_shared_circle() {
|
||||
let mut s = session();
|
||||
quick_pen(&mut s);
|
||||
s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "sharpArc"})).unwrap();
|
||||
click(&mut s, 100.0, 300.0);
|
||||
click(&mut s, 300.0, 300.0);
|
||||
s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "turn", "value": 90})).unwrap();
|
||||
// A quarter more around the circle about (200, 300), ending heading left.
|
||||
click(&mut s, 200.0, 400.0);
|
||||
let r = 100.0 * std::f64::consts::FRAC_1_SQRT_2;
|
||||
let to = pt(200.0 - r, 300.0 + r);
|
||||
// The handle at (180, 400) turned 45° more around the center takes the end there with it.
|
||||
let (sin, cos) = std::f64::consts::FRAC_PI_4.sin_cos();
|
||||
let (hx, hy) = (-20.0, 100.0);
|
||||
let pointer = (200.0 + hx * cos - hy * sin, 300.0 + hx * sin + hy * cos);
|
||||
press(&mut s, &[(180.0, 400.0), (170.0, 400.0), pointer]);
|
||||
let sp = only_path(&s);
|
||||
assert!(sp.anchors.last().unwrap().p.distance(to) < 1e-6, "135° from (300, 300): {:?}", sp.anchors.last());
|
||||
assert!(sp.anchors.get(2).unwrap().p.distance(pt(300.0, 300.0)) < 1e-9, "the first arc stays");
|
||||
assert!(s.tool_claims_key(ToolKey::Letter('c'), view()));
|
||||
}
|
||||
|
||||
/// Once another path is selected while one was being drawn, the selected path shows its handles.
|
||||
#[test]
|
||||
fn another_selected_path_shows_its_handles() {
|
||||
let mut s = session();
|
||||
quick_pen(&mut s);
|
||||
click(&mut s, 100.0, 100.0);
|
||||
click(&mut s, 200.0, 100.0);
|
||||
let r = s.execute("shape.line", &json!({"x1": 300, "y1": 300, "x2": 400, "y2": 300})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [r["id"]]})).unwrap();
|
||||
let handle =
|
||||
|s: &mut Session| s.overlays(view()).iter().any(|o| matches!(o, vectorcraft_tools::Overlay::Handle { p, .. } if *p == pt(420.0, 300.0)));
|
||||
assert!(handle(&mut s));
|
||||
assert_eq!(s.cursor(pt(420.0, 300.0), Mods::default(), view()), vectorcraft_tools::Cursor::Move);
|
||||
}
|
||||
|
||||
/// A selected path that is not being drawn shows its handles: the one before its start makes the
|
||||
/// first arc shorter around its circle. Escape during a drag takes the drag back.
|
||||
#[test]
|
||||
fn the_start_handle_of_a_selected_path_shortens_its_arc() {
|
||||
let mut s = session();
|
||||
let r = s
|
||||
.execute("path.quickPen", &json!({"start": [100, 100], "pieces": [{"x": 200, "y": 100, "action": "sharpArc"}, {"x": 300, "y": 100}]}))
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [r["id"]]})).unwrap();
|
||||
quick_pen(&mut s);
|
||||
let undo = undo_steps(&s);
|
||||
let before = only_path(&s);
|
||||
// The half circle leaves (100, 100) heading up, so its start handle is 20 points below.
|
||||
let v = view();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 120.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 150.0, 70.0), v).unwrap();
|
||||
assert_ne!(only_path(&s), before, "previewed");
|
||||
key(&mut s, ToolKey::Escape);
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 150.0, 70.0), v).unwrap();
|
||||
assert_eq!(only_path(&s), before, "taken back");
|
||||
assert_eq!(undo_steps(&s), undo);
|
||||
// The handle turned a quarter around the center, to (130, 50), takes the start to the top of
|
||||
// the circle: the arc is a quarter from there to (200, 100).
|
||||
press(&mut s, &[(100.0, 120.0), (130.0, 50.0)]);
|
||||
let sp = only_path(&s);
|
||||
assert!(sp.anchors.first().unwrap().p.distance(pt(150.0, 50.0)) < 1e-6, "{:?}", sp.anchors.first());
|
||||
assert_eq!(sp.anchors.len(), 3);
|
||||
assert_eq!(undo_steps(&s), undo + 1);
|
||||
}
|
||||
|
||||
/// A click on a length handle that does not drag is an ordinary click: while drawing it adds a
|
||||
/// point there, and with no path being drawn it starts a new path.
|
||||
#[test]
|
||||
fn a_click_on_a_handle_adds_a_point() {
|
||||
let mut s = session();
|
||||
quick_pen(&mut s);
|
||||
click(&mut s, 100.0, 100.0);
|
||||
click(&mut s, 200.0, 100.0);
|
||||
let undo = undo_steps(&s);
|
||||
click(&mut s, 220.0, 100.0);
|
||||
let ends: Vec<Point> = only_path(&s).anchors.iter().map(|a| a.p).collect();
|
||||
assert_eq!(ends, [pt(100.0, 100.0), pt(200.0, 100.0), pt(220.0, 100.0)]);
|
||||
assert_eq!(undo_steps(&s), undo + 1);
|
||||
// After Escape the path stays selected with its handles; a click on one starts a new path.
|
||||
key(&mut s, ToolKey::Escape);
|
||||
assert_eq!(s.cursor(pt(240.0, 100.0), Mods::default(), view()), vectorcraft_tools::Cursor::Move);
|
||||
click(&mut s, 240.0, 100.0);
|
||||
assert_eq!(paths(&s).len(), 2);
|
||||
}
|
||||
|
||||
/// During a length drag the tool shows the handle and no preview of a next piece to where the
|
||||
/// pointer was before the press.
|
||||
#[test]
|
||||
fn a_length_drag_shows_no_next_piece() {
|
||||
let mut s = session();
|
||||
quick_pen(&mut s);
|
||||
click(&mut s, 100.0, 100.0);
|
||||
click(&mut s, 200.0, 100.0);
|
||||
let v = view();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Move, 220.0, 100.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 220.0, 100.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 280.0, 100.0), v).unwrap();
|
||||
let o = s.overlays(v);
|
||||
assert!(o.iter().any(|o| matches!(o, vectorcraft_tools::Overlay::Handle { .. })));
|
||||
assert!(!o.iter().any(|o| matches!(o, vectorcraft_tools::Overlay::Path { .. } | vectorcraft_tools::Overlay::Measure { .. })), "{o:?}");
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 280.0, 100.0), v).unwrap();
|
||||
assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(260.0, 100.0));
|
||||
}
|
||||
|
||||
/// A press on a length handle clears the Smart Guides of the hover before it, so none show during
|
||||
/// the drag.
|
||||
#[test]
|
||||
fn a_length_drag_shows_no_smart_guide() {
|
||||
let mut s = session();
|
||||
s.execute("shape.line", &json!({"x1": 220, "y1": 100, "x2": 220, "y2": 300})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": []})).unwrap();
|
||||
quick_pen(&mut s);
|
||||
click(&mut s, 100.0, 100.0);
|
||||
click(&mut s, 200.0, 100.0);
|
||||
let on = ViewInfo { smart_guides: true, ..Default::default() };
|
||||
// The end handle stands on the other line's anchor, so the hover there shows its guide.
|
||||
s.pointer(&PointerEvent::new(PointerKind::Move, 220.0, 100.0), on).unwrap();
|
||||
assert!(!only_points(&mut s, on), "the anchor's guide shows");
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 220.0, 100.0), on).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 280.0, 140.0), on).unwrap();
|
||||
assert!(only_points(&mut s, on), "no guide during the drag: {:?}", s.overlays(on));
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 280.0, 140.0), on).unwrap();
|
||||
let drawn = paths(&s).into_iter().find(|(_, p)| p.subpaths[0].anchors.first().is_some_and(|a| a.p == pt(100.0, 100.0))).unwrap();
|
||||
assert_eq!(drawn.1.subpaths[0].anchors.last().unwrap().p, pt(260.0, 100.0));
|
||||
}
|
||||
|
||||
/// A length drag that would take the path past the canvas leaves it where the drag last put it,
|
||||
/// and the drawing goes on from there.
|
||||
#[test]
|
||||
fn a_length_drag_stays_on_the_canvas() {
|
||||
let mut s = session();
|
||||
quick_pen(&mut s);
|
||||
let x = vectorcraft_doc::MAX_COORD - 1000.0;
|
||||
click(&mut s, x, 100.0);
|
||||
click(&mut s, x + 500.0, 100.0);
|
||||
let undo = undo_steps(&s);
|
||||
let before = only_path(&s);
|
||||
// The end handle is at x + 520; a drag to x + 2000 would put the end at x + 1980, past the canvas.
|
||||
press(&mut s, &[(x + 520.0, 100.0), (x + 2000.0, 100.0)]);
|
||||
assert_eq!(only_path(&s), before);
|
||||
assert_eq!(undo_steps(&s), undo);
|
||||
press(&mut s, &[(x + 520.0, 100.0), (x + 820.0, 100.0)]);
|
||||
assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(x + 800.0, 100.0));
|
||||
assert_eq!(undo_steps(&s), undo + 1);
|
||||
click(&mut s, x + 800.0, 200.0);
|
||||
assert_eq!(only_path(&s).anchors.len(), 3, "the drawing went on");
|
||||
}
|
||||
|
||||
/// A length drag across a line, or out along it and back, leaves its length as it was: it changes
|
||||
/// nothing and records no undo step, on the path being drawn and on a selected path.
|
||||
#[test]
|
||||
fn a_length_drag_that_keeps_the_length_records_no_undo_step() {
|
||||
let mut s = session();
|
||||
quick_pen(&mut s);
|
||||
click(&mut s, 100.0, 100.0);
|
||||
click(&mut s, 200.0, 100.0);
|
||||
let undo = undo_steps(&s);
|
||||
let before = only_path(&s);
|
||||
// The end handle is at (220, 100); the first drag goes straight down from it, the second out
|
||||
// along the line and back.
|
||||
for drag in [[(220.0, 100.0), (220.0, 160.0), (220.0, 160.0)], [(220.0, 100.0), (260.0, 100.0), (220.0, 100.0)]] {
|
||||
press(&mut s, &drag);
|
||||
assert_eq!(only_path(&s), before, "{drag:?}");
|
||||
assert_eq!(undo_steps(&s), undo, "{drag:?}");
|
||||
}
|
||||
key(&mut s, ToolKey::Escape);
|
||||
let undo = undo_steps(&s);
|
||||
for drag in [[(220.0, 100.0), (220.0, 160.0), (220.0, 160.0)], [(220.0, 100.0), (260.0, 100.0), (220.0, 100.0)]] {
|
||||
press(&mut s, &drag);
|
||||
assert_eq!(only_path(&s), before, "{drag:?}");
|
||||
assert_eq!(undo_steps(&s), undo, "{drag:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The paths of a selected compound path show length handles, also after a drag selected the
|
||||
/// compound again.
|
||||
#[test]
|
||||
fn a_compound_path_shows_the_length_handles_of_its_paths() {
|
||||
let mut s = session();
|
||||
let a = s.execute("path.quickPen", &json!({"start": [100, 100], "pieces": [{"x": 200, "y": 100}]})).unwrap();
|
||||
let b = s.execute("path.quickPen", &json!({"start": [100, 300], "pieces": [{"x": 200, "y": 300}]})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a["id"], b["id"]]})).unwrap();
|
||||
s.execute("object.compoundPath.make", &json!({})).unwrap();
|
||||
quick_pen(&mut s);
|
||||
press(&mut s, &[(220.0, 100.0), (250.0, 100.0), (280.0, 100.0)]);
|
||||
press(&mut s, &[(220.0, 300.0), (250.0, 300.0), (270.0, 300.0)]);
|
||||
let mut ends: Vec<Point> = paths(&s).iter().filter_map(|(_, pd)| pd.subpaths[0].anchors.last().map(|a| a.p)).collect();
|
||||
ends.sort_by(|p, q| p.y.total_cmp(&q.y));
|
||||
assert_eq!(ends, [pt(260.0, 100.0), pt(250.0, 300.0)]);
|
||||
}
|
||||
|
||||
/// An edit made outside the tool during a length press ends the press: a later drag does not
|
||||
/// preview from the path as the press found it, and so does not undo the edit.
|
||||
#[test]
|
||||
fn an_outside_edit_during_a_length_press_is_kept() {
|
||||
// The edit comes before the first drag event, or after the drag began.
|
||||
for began in [false, true] {
|
||||
let mut s = session();
|
||||
quick_pen(&mut s);
|
||||
click(&mut s, 100.0, 100.0);
|
||||
click(&mut s, 200.0, 100.0);
|
||||
let v = view();
|
||||
let id = paths(&s)[0].0.0;
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 220.0, 100.0), v).unwrap();
|
||||
if began {
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 250.0, 100.0), v).unwrap();
|
||||
}
|
||||
s.execute("path.quickPenLength", &json!({"id": id, "length": 40})).unwrap();
|
||||
let edited = only_path(&s);
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 280.0, 100.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 280.0, 100.0), v).unwrap();
|
||||
assert_eq!(only_path(&s), edited, "began: {began}");
|
||||
}
|
||||
// Escape after the edit takes the drag back without taking the edit back.
|
||||
let mut s = session();
|
||||
quick_pen(&mut s);
|
||||
click(&mut s, 100.0, 100.0);
|
||||
click(&mut s, 200.0, 100.0);
|
||||
let v = view();
|
||||
let id = paths(&s)[0].0.0;
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 220.0, 100.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 250.0, 100.0), v).unwrap();
|
||||
s.execute("path.quickPenLength", &json!({"id": id, "length": 40})).unwrap();
|
||||
let edited = only_path(&s);
|
||||
key(&mut s, ToolKey::Escape);
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 250.0, 100.0), v).unwrap();
|
||||
assert_eq!(only_path(&s), edited, "escape");
|
||||
}
|
||||
|
||||
/// C and `[` `]` wait for a length drag to end: they neither add an undo step of their own nor
|
||||
/// change the arc the drag is changing.
|
||||
#[test]
|
||||
fn piece_keys_do_nothing_during_a_length_drag() {
|
||||
let mut s = session();
|
||||
quick_pen(&mut s);
|
||||
s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "sharpArc"})).unwrap();
|
||||
click(&mut s, 100.0, 300.0);
|
||||
click(&mut s, 300.0, 300.0);
|
||||
let undo = undo_steps(&s);
|
||||
let v = view();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 300.0, 320.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 260.0, 400.0), v).unwrap();
|
||||
let during = only_path(&s);
|
||||
for k in [ToolKey::Letter('c'), ToolKey::BracketRight, ToolKey::BracketLeft] {
|
||||
assert!(s.tool_claims_key(k, view()), "{k:?} stays with the tool");
|
||||
key(&mut s, k);
|
||||
assert_eq!(only_path(&s), during, "{k:?}");
|
||||
}
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 180.0, 400.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 180.0, 400.0), v).unwrap();
|
||||
assert_eq!(undo_steps(&s), undo + 1);
|
||||
assert!(only_path(&s).anchors.last().unwrap().p.distance(pt(200.0, 400.0)) < 1e-6);
|
||||
}
|
||||
|
||||
/// Choosing Quick Pen again during a length drag leaves the drawing alone: the drag goes on, ends
|
||||
/// where the pointer is let go, and the next click goes on drawing the same path.
|
||||
#[test]
|
||||
fn choosing_the_tool_again_during_a_length_drag_keeps_the_drawing() {
|
||||
let mut s = session();
|
||||
quick_pen(&mut s);
|
||||
click(&mut s, 100.0, 100.0);
|
||||
click(&mut s, 200.0, 100.0);
|
||||
let v = view();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 220.0, 100.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 250.0, 130.0), v).unwrap();
|
||||
quick_pen(&mut s);
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 280.0, 140.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 280.0, 140.0), v).unwrap();
|
||||
let ends: Vec<Point> = only_path(&s).anchors.iter().map(|a| a.p).collect();
|
||||
assert_eq!(ends, [pt(100.0, 100.0), pt(260.0, 100.0)]);
|
||||
click(&mut s, 260.0, 200.0);
|
||||
assert_eq!(paths(&s).len(), 1, "the drawing went on");
|
||||
assert_eq!(only_path(&s).anchors.len(), 3);
|
||||
}
|
||||
|
||||
/// A length drag ends where the pointer is let go, also when no drag event came after the press.
|
||||
#[test]
|
||||
fn a_length_drag_ends_at_the_release_point() {
|
||||
let mut s = session();
|
||||
quick_pen(&mut s);
|
||||
click(&mut s, 100.0, 100.0);
|
||||
click(&mut s, 200.0, 100.0);
|
||||
let undo = undo_steps(&s);
|
||||
let v = view();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 220.0, 100.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 250.0, 100.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 280.0, 100.0), v).unwrap();
|
||||
assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(260.0, 100.0));
|
||||
assert_eq!(undo_steps(&s), undo + 1);
|
||||
// A press let go away from the handle without a drag event drags too.
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 280.0, 100.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 320.0, 100.0), v).unwrap();
|
||||
assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(300.0, 100.0));
|
||||
assert_eq!(only_path(&s).anchors.len(), 2);
|
||||
assert_eq!(undo_steps(&s), undo + 2);
|
||||
}
|
||||
|
||||
/// `path.quickPenLength` refuses a result past the canvas, not only one past the input limit.
|
||||
#[test]
|
||||
fn path_quick_pen_length_stays_on_the_canvas() {
|
||||
let mut s = session();
|
||||
let x = vectorcraft_doc::MAX_COORD - 500_000.0;
|
||||
let r = s.execute("path.quickPen", &json!({"start": [x, 0], "pieces": [{"x": x + 10.0, "y": 0}]})).unwrap();
|
||||
let id = r["id"].as_u64().unwrap();
|
||||
let before = only_path(&s);
|
||||
let undo = undo_steps(&s);
|
||||
let e = s.execute("path.quickPenLength", &json!({"id": id, "length": 1_000_000})).unwrap_err().to_string();
|
||||
assert!(e.contains("would exceed the canvas"), "{e}");
|
||||
assert_eq!(only_path(&s), before);
|
||||
assert_eq!(undo_steps(&s), undo);
|
||||
s.execute("path.quickPenLength", &json!({"id": id, "length": 400_000})).unwrap();
|
||||
assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(x + 400_000.0, 0.0));
|
||||
}
|
||||
|
||||
/// Dragged by the start handle while the path is being drawn, the first line changes and the last
|
||||
/// sharp-corner arc stays the last piece, so C still flips it.
|
||||
#[test]
|
||||
fn the_start_handle_keeps_the_last_arc_a_piece() {
|
||||
let mut s = session();
|
||||
quick_pen(&mut s);
|
||||
click(&mut s, 100.0, 300.0);
|
||||
click(&mut s, 200.0, 300.0);
|
||||
s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "sharpArc"})).unwrap();
|
||||
click(&mut s, 400.0, 300.0);
|
||||
assert!(s.tool_claims_key(ToolKey::Letter('c'), view()));
|
||||
let undo = undo_steps(&s);
|
||||
// The line leaves (100, 300) heading left, seen from the start, so its handle is 20 points left.
|
||||
press(&mut s, &[(80.0, 300.0), (60.0, 300.0), (50.0, 300.0)]);
|
||||
let sp = only_path(&s);
|
||||
assert_eq!(sp.anchors.first().unwrap().p, pt(70.0, 300.0));
|
||||
assert_eq!(undo_steps(&s), undo + 1);
|
||||
assert!(s.tool_claims_key(ToolKey::Letter('c'), view()), "the last arc is still a piece");
|
||||
key(&mut s, ToolKey::Letter('c'));
|
||||
let flipped = only_path(&s);
|
||||
assert_ne!(flipped, sp);
|
||||
assert_eq!(flipped.anchors.first().unwrap().p, pt(70.0, 300.0));
|
||||
assert!(flipped.anchors.last().unwrap().p.distance(pt(400.0, 300.0)) < 1e-9);
|
||||
}
|
||||
|
||||
/// `path.quickPenLength` sets the length of a line or an arc at either end; the same length
|
||||
/// changes nothing and records no undo step; bad params are refused.
|
||||
#[test]
|
||||
fn path_quick_pen_length_sets_an_end() {
|
||||
let mut s = session();
|
||||
let r = s.execute("path.quickPen", &json!({"start": [0, 0], "pieces": [{"x": 100, "y": 0}, {"x": 200, "y": 0, "action": "sharpArc"}]})).unwrap();
|
||||
let id = r["id"].as_u64().unwrap();
|
||||
let r = s.execute("path.quickPenLength", &json!({"id": id, "end": "start", "length": 40})).unwrap();
|
||||
assert_eq!((r["kind"].as_str(), r["length"].as_f64()), (Some("line"), Some(40.0)));
|
||||
assert_eq!(only_path(&s).anchors.first().unwrap().p, pt(60.0, 0.0));
|
||||
let undo = undo_steps(&s);
|
||||
let r = s.execute("path.quickPenLength", &json!({"id": id, "length": std::f64::consts::PI * 50.0})).unwrap();
|
||||
assert_eq!(r["kind"], "arc");
|
||||
assert_eq!(undo_steps(&s), undo, "unchanged");
|
||||
s.execute("path.quickPenLength", &json!({"id": id, "length": std::f64::consts::PI * 25.0})).unwrap();
|
||||
assert!(only_path(&s).anchors.last().unwrap().p.distance(pt(150.0, -50.0)) < 1e-9);
|
||||
assert_eq!(undo_steps(&s), undo + 1);
|
||||
let before = paths(&s);
|
||||
let bad: [Value; 7] = [
|
||||
json!({"length": 10}),
|
||||
json!({"id": id}),
|
||||
json!({"id": id, "length": "10"}),
|
||||
json!({"id": id, "length": 0}),
|
||||
json!({"id": id, "length": 1e7, "end": "start"}),
|
||||
json!({"id": id, "length": 10, "end": "middle"}),
|
||||
json!({"id": id, "length": 10, "subpath": 1}),
|
||||
];
|
||||
for p in bad {
|
||||
assert!(s.execute("path.quickPenLength", &p).is_err(), "{p}");
|
||||
}
|
||||
let curve = s.execute("shape.line", &json!({"x1": 0, "y1": 300, "x2": 100, "y2": 300})).unwrap();
|
||||
s.execute("path.convertAnchor", &json!({"id": curve["id"], "anchor": 1, "to": "smooth", "x": 150, "y": 360})).unwrap();
|
||||
assert!(s.execute("path.quickPenLength", &json!({"id": curve["id"], "length": 10})).is_err(), "not a line or an arc");
|
||||
s.execute("path.quickPen", &json!({"id": id, "closed": true})).unwrap();
|
||||
assert!(s.execute("path.quickPenLength", &json!({"id": id, "length": 10})).is_err(), "closed");
|
||||
assert_eq!(paths(&s).len(), before.len() + 1);
|
||||
}
|
||||
|
||||
/// With `id` and `keep`, the points after the first `keep` are replaced by the pieces.
|
||||
#[test]
|
||||
fn path_quick_pen_replaces_the_points_after_keep() {
|
||||
|
||||
@@ -571,6 +571,22 @@ fn the_folder_store_reads_no_linked_entries() {
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
|
||||
/// A write to an entry that is a link (the copy's metadata names it) must not follow it out of the
|
||||
/// store: the file behind the link keeps its bytes.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn the_folder_store_writes_no_linked_entries() {
|
||||
let base = std::env::temp_dir().join(format!("vc-recovery-write-links-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
let store = FolderStore::new(&base);
|
||||
store.write("1-1/Untitled-1-1.vectorcraft", b"copy").unwrap();
|
||||
std::fs::write(base.join("outside"), b"private").unwrap();
|
||||
std::os::unix::fs::symlink(base.join("outside"), base.join("1-1").join("img")).unwrap();
|
||||
assert!(store.write("1-1/img", b"copy").is_err());
|
||||
assert_eq!(std::fs::read(base.join("outside")).unwrap(), b"private");
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
|
||||
/// A file where a folder of the store's path should be: the error names that file, not the area
|
||||
/// folder or the copy below it, for a write, a lock, a read, a listing, a removal and a recovery
|
||||
/// save.
|
||||
|
||||
@@ -653,7 +653,7 @@ fn a_grants_change_without_its_lock_changes_nothing() {
|
||||
}
|
||||
|
||||
/// Reading and changing the grants file wait for a lock another handle holds only for a bounded
|
||||
/// number of tries: then a read gives no grants and a change fails with the file unchanged. A lock
|
||||
/// number of tries: then a listing and a change fail, with the file unchanged. A lock
|
||||
/// released while it waits is taken.
|
||||
#[test]
|
||||
fn a_grants_change_waits_for_a_held_lock_a_bounded_number_of_tries() {
|
||||
@@ -668,7 +668,8 @@ fn a_grants_change_waits_for_a_held_lock_a_bounded_number_of_tries() {
|
||||
let waits = std::rc::Rc::new(std::cell::Cell::new(0));
|
||||
let counted = waits.clone();
|
||||
WHILE_GRANTS_LOCKED.set(Some(Box::new(move || counted.set(counted.get() + 1))));
|
||||
assert_eq!(stored_grants(&data), Vec::<Value>::new(), "grants are not read without the lock");
|
||||
let listed = stored_grants(&data);
|
||||
assert_eq!(listed.map_err(|e| e.kind()), Err(std::io::ErrorKind::TimedOut), "grants are not listed without the lock");
|
||||
assert_eq!(waits.get(), LOCK_TRIES - 1);
|
||||
waits.set(0);
|
||||
let refused = revoke_grants(&data, None, None);
|
||||
@@ -1319,6 +1320,55 @@ fn script_file_grants_file_that_cannot_be_read_is_left_as_it_is() {
|
||||
}
|
||||
}
|
||||
|
||||
/// `script.grants` fails on a grants file that is there but cannot be read (another version, not
|
||||
/// JSON, no list of grants, over the size limit, not a file, or on Unix a link to a missing file),
|
||||
/// lists none when it is missing, and
|
||||
/// lists the well-formed grants of one that holds a grant that is not.
|
||||
#[test]
|
||||
fn script_grants_fails_on_a_grants_file_that_cannot_be_read() {
|
||||
let mut big = b"{\"version\": 1, \"grants\": []}".to_vec();
|
||||
big.resize((4 << 20) + 1, b' ');
|
||||
let cases = [
|
||||
("list-newer", br#"{"version": 2, "grants": []}"#.to_vec()),
|
||||
("list-broken", b"{ not json".to_vec()),
|
||||
("list-nolist", br#"{"version": 1, "grants": {}}"#.to_vec()),
|
||||
("list-big", big),
|
||||
];
|
||||
for (name, held) in cases {
|
||||
let base = folder(name);
|
||||
write(&base.join("settings/Script Grants.json"), &held);
|
||||
let mut s = with_data(&base);
|
||||
let e = s.execute("script.grants", &json!({})).unwrap_err().to_string();
|
||||
assert!(e.contains("the script file permissions could not be read"), "{name}: {e}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
let base = folder("list-folder");
|
||||
std::fs::create_dir_all(base.join("settings/Script Grants.json")).unwrap();
|
||||
let mut s = with_data(&base);
|
||||
assert!(s.execute("script.grants", &json!({})).is_err(), "a folder in the grants file's place");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let base = folder("list-dangling");
|
||||
std::fs::create_dir_all(base.join("settings")).unwrap();
|
||||
std::os::unix::fs::symlink(base.join("gone.json"), base.join("settings/Script Grants.json")).unwrap();
|
||||
let mut s = with_data(&base);
|
||||
assert!(s.execute("script.grants", &json!({})).is_err(), "a link to a missing file in the grants file's place");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
let base = folder("list-missing");
|
||||
let mut s = with_data(&base);
|
||||
assert_eq!(s.execute("script.grants", &json!({})).unwrap()["grants"], json!([]), "a missing grants file lists none");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
let base = folder("list-mixed");
|
||||
let grant = json!({"script": "/s.jsx", "sha256": "0", "code": [], "path": "/p", "write": false, "folder": false});
|
||||
let text = json!({"version": 1, "grants": [grant, {"script": "x"}]}).to_string();
|
||||
write(&base.join("settings/Script Grants.json"), text.as_bytes());
|
||||
let mut s = with_data(&base);
|
||||
assert_eq!(s.execute("script.grants", &json!({})).unwrap()["grants"].as_array().unwrap().len(), 1);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// `copy` of a file over 8 MiB is refused, as opening one is.
|
||||
#[test]
|
||||
fn script_file_copy_is_held_to_the_file_limit() {
|
||||
|
||||
@@ -326,8 +326,45 @@ fn a_js_script_reads_ecmascript_2015_and_a_jsx_script_does_not() {
|
||||
assert_eq!(modern["log"], json!([2]), "{modern}");
|
||||
let legacy = s.execute("script.run", &path(&write("third.jsx", "#targetengine kept\nvc.log(k2);\nconst c = 1;")));
|
||||
assert!(legacy.unwrap_err().to_string().contains("SyntaxError"));
|
||||
let legacy = s.execute("script.run", &path(&write("fourth.jsx", "#targetengine kept\nvc.log(k2 + kept);"))).unwrap();
|
||||
assert_eq!(legacy["log"], json!([3]), "{legacy}");
|
||||
let fourth = "#targetengine kept\nvc.log(k2 + kept);\ntry { eval('let x = 1'); } catch (e) { vc.log(e.name); }";
|
||||
let legacy = s.execute("script.run", &path(&write("fourth.jsx", fourth))).unwrap();
|
||||
assert_eq!(legacy["log"], json!([3, "SyntaxError"]), "{legacy}");
|
||||
// `for`-`of` and destructuring, in a new engine and in one a `.jsx` script made.
|
||||
let loops = "var s = 0;\nfor (const [a, { b = 1 }] of [[1, {}], [2, { b: 3 }]]) s += a + b;\nvar { p, q: [r] } = { p: 4, q: [5] };\nvc.log(s);\nvc.log(p + r);\nvc.log(typeof Symbol);";
|
||||
let r = s.execute("script.run", &path(&write("loops.js", loops))).unwrap();
|
||||
assert_eq!(r["log"], json!([7, 9, "function"]), "{r}");
|
||||
let kept = s
|
||||
.execute("script.run", &path(&write("fifth.js", "#targetengine kept\nfor (const [i, ...j] of [[kept, 'x', 'y']]) vc.log(i + j.join(''));")))
|
||||
.unwrap();
|
||||
assert_eq!(kept["log"], json!(["1xy"]), "{kept}");
|
||||
let e = s.execute("script.run", &path(&write("pattern.jsx", "var [a] = [1];"))).unwrap_err().to_string();
|
||||
assert!(e.contains("SyntaxError"), "{e}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_js_script_reads_object_literal_extensions_and_function_names_and_a_jsx_script_does_not() {
|
||||
let dir = fresh_folder("es2015-objects");
|
||||
let write = |name: &str, text: &str| {
|
||||
let p = dir.join(name);
|
||||
std::fs::write(&p, text).unwrap();
|
||||
p.to_string_lossy().into_owned()
|
||||
};
|
||||
let mut s = two_docs();
|
||||
let path = |p: &str| json!({"path": p});
|
||||
let modern = "var k = 'b';\nvar a = 1;\nvar o = { a, [k + 1]: 2, m() { return 3; }, f: () => 4 };\n\
|
||||
vc.log(o.a + o.b1 + o.m() + o.f());\nvc.log(o.m.name + ',' + o.f.name + ',' + o.f.bind().name + ',' + Math.max.name);\n";
|
||||
let r = s.execute("script.run", &path(&write("objects.js", modern))).unwrap();
|
||||
assert_eq!(r["log"], json!([10, "m,f,bound f,max"]), "{r}");
|
||||
for (name, text) in [("short.jsx", "var a = 1; var o = { a };"), ("computed.jsx", "var o = { ['b']: 1 };"), ("method.jsx", "var o = { m() {} };")]
|
||||
{
|
||||
let e = s.execute("script.run", &path(&write(name, text))).unwrap_err().to_string();
|
||||
assert!(e.contains("SyntaxError"), "{name}: {e}");
|
||||
}
|
||||
let legacy = s.execute("script.run", &path(&write("names.jsx", "var f = function () {};\nvc.log(f.hasOwnProperty('name'));"))).unwrap();
|
||||
assert_eq!(legacy["log"], json!([false]), "{legacy}");
|
||||
// Script text given without a file keeps the ExtendScript language.
|
||||
assert!(run(&mut s, "var a = 1; var o = { a };").unwrap_err().to_string().contains("SyntaxError"));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
@@ -354,6 +391,40 @@ fn a_js_script_reads_optional_chains_and_coalescing_and_a_jsx_script_does_not()
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_script_reads_e4x_and_has_the_xml_objects() {
|
||||
let dir = fresh_folder("e4x");
|
||||
let write = |name: &str, text: &str| {
|
||||
let p = dir.join(name);
|
||||
std::fs::write(&p, text).unwrap();
|
||||
p.to_string_lossy().into_owned()
|
||||
};
|
||||
let mut s = two_docs();
|
||||
let path = |p: &str| json!({"path": p});
|
||||
// Script text: literals, selectors, for each and the four constructors.
|
||||
let text = "var x = <list><item id=\"a\">1</item><item id=\"b\">2</item></list>;\n\
|
||||
vc.log(x.item.length() + ' ' + x.item.(@id == 'b').toString() + ' ' + x..item[0].@id);\n\
|
||||
var sum = 0; for each (var i in x.item) sum += Number(i); vc.log(sum);\n\
|
||||
vc.log(new XML('<a><b/></a>').b.length() + new XMLList('<c/><c/>').length());\n\
|
||||
vc.log(new Namespace('p', 'urn:p').prefix + ' ' + new QName('urn:q', 'n').localName + ' ' + isXMLName('ok'));\n\
|
||||
vc.log(typeof setDefaultXMLNamespace + ' ' + (1 < 2));\n";
|
||||
let r = run(&mut s, text).unwrap();
|
||||
assert_eq!(r["log"], json!(["2 2 a", 3, 3, "p n true", "function true"]), "{r}");
|
||||
// A .js file, a file it includes, eval, Function and $.evalFile read XML as well.
|
||||
write("lib.jsxinc", "var fromLib = <lib n=\"7\"/>.@n.toString();\n");
|
||||
write("more.jsx", "<m>{fromLib}</m>.toString();\n");
|
||||
let modern = "#include \"lib.jsxinc\"\nlet tag = <t>{fromLib}</t>;\nvc.log(tag.toString());\n\
|
||||
vc.log(eval('<e>5</e>').toString());\nvc.log(new Function('return <f>6</f>.toString()')());\n\
|
||||
vc.log($.evalFile(File($.fileName).parent + '/more.jsx'));\n";
|
||||
let r = s.execute("script.run", &path(&write("modern.js", modern))).unwrap();
|
||||
assert_eq!(r["log"], json!(["7", "5", "6", "7"]), "{r}");
|
||||
// A named engine first made by a .js run gives a later .jsx run the XML objects too.
|
||||
s.execute("script.run", &path(&write("first.js", "#targetengine xmlkept\nlet k = 1;"))).unwrap();
|
||||
let later = s.execute("script.run", &path(&write("second.jsx", "#targetengine xmlkept\nvc.log(XML('<k>2</k>').toString());"))).unwrap();
|
||||
assert_eq!(later["log"], json!(["2"]), "{later}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A new empty folder for test `name`.
|
||||
fn fresh_folder(name: &str) -> std::path::PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("vc-script-run-{name}-{}", std::process::id()));
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
//! The arrow keys with a curved segment selected bend it: its anchors stay, its handles keep their
|
||||
//! directions, and the middle of the curve moves toward the arrow.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_doc::{Appearance, Document, Node, NodeId};
|
||||
use vectorcraft_geom::{Anchor, ParamCurve, PathData, Point, SubPath, Vec2};
|
||||
|
||||
use crate::*;
|
||||
|
||||
/// A session with one open path of one segment from (100, 300) to (400, 300), with the handles
|
||||
/// `out` at its start and `in` at its end, and that segment selected with Direct Selection.
|
||||
fn selected_segment(out: Point, h_in: Point) -> (Session, NodeId) {
|
||||
let (p0, p1) = (Point::new(100.0, 300.0), Point::new(400.0, 300.0));
|
||||
let (s, id) = session_with(vec![Anchor::with_handles(p0, p0, out), Anchor::with_handles(p1, h_in, p1)]);
|
||||
(select(s, id, &[0]), id)
|
||||
}
|
||||
|
||||
/// A session with one open path through `anchors`.
|
||||
fn session_with(anchors: Vec<Anchor>) -> (Session, NodeId) {
|
||||
let mut d = Document::new(1000.0, 1000.0);
|
||||
let id = d.alloc_id();
|
||||
let node = Node::path(id, PathData::single(SubPath::new(anchors, false)), Appearance::default_art());
|
||||
if let Some(ch) = Arc::make_mut(&mut d.layers[0]).children_mut() {
|
||||
ch.push(Arc::new(node));
|
||||
}
|
||||
let mut s = Session::new();
|
||||
s.add_document(d, None);
|
||||
(s, id)
|
||||
}
|
||||
|
||||
/// `s` with segments `segments` of path `id` selected with Direct Selection.
|
||||
fn select(mut s: Session, id: NodeId, segments: &[usize]) -> Session {
|
||||
let refs: Vec<_> = segments.iter().map(|&seg| [0, seg]).collect();
|
||||
s.execute("select.segments", &json!({"id": id.0, "segments": refs})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn undo_steps(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
fn segment(s: &Session, id: NodeId) -> SubPath {
|
||||
s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().subpaths[0].clone()
|
||||
}
|
||||
|
||||
/// Each handle as a vector from its anchor: the outgoing one at the start, the incoming one at
|
||||
/// the end.
|
||||
fn handles(sp: &SubPath) -> (Vec2, Vec2) {
|
||||
(sp.anchors[0].h_out - sp.anchors[0].p, sp.anchors[1].h_in - sp.anchors[1].p)
|
||||
}
|
||||
|
||||
fn middle(sp: &SubPath) -> Point {
|
||||
sp.segment(0).eval(0.5)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arrows_bend_a_selected_curved_segment_and_keep_its_anchors() {
|
||||
// The handle at the start points up, the one at the end left.
|
||||
let (mut s, id) = selected_segment(Point::new(100.0, 150.0), Point::new(300.0, 300.0));
|
||||
let step = s.prefs.keyboard_increment;
|
||||
let before = segment(&s, id);
|
||||
let (up, left) = handles(&before);
|
||||
|
||||
// Up: the upward handle grows, the one across the arrow stays.
|
||||
s.execute("object.nudge", &json!({"dx": 0, "dy": -1})).unwrap();
|
||||
let after = segment(&s, id);
|
||||
let (up2, left2) = handles(&after);
|
||||
assert_eq!((after.anchors[0].p, after.anchors[1].p), (before.anchors[0].p, before.anchors[1].p), "the anchors stay");
|
||||
assert!(up2.hypot() > up.hypot() && up2.cross(up).abs() < 1e-9 && up2.dot(up) > 0.0, "the upward handle grows in its direction: {up2:?}");
|
||||
assert_eq!(left2, left, "the handle across the arrow stays");
|
||||
assert!((middle(&after) - middle(&before) - Vec2::new(0.0, -step)).hypot() < 1e-9, "the middle moves one step up");
|
||||
|
||||
// Right: the handle pointing left shrinks, the upward one stays.
|
||||
s.execute("object.nudge", &json!({"dx": 1, "dy": 0})).unwrap();
|
||||
let last = segment(&s, id);
|
||||
let (up3, left3) = handles(&last);
|
||||
assert_eq!(up3, up2, "the handle across the arrow stays");
|
||||
assert!(left3.hypot() < left2.hypot() && left3.cross(left2).abs() < 1e-9 && left3.dot(left2) > 0.0, "the leftward handle shrinks: {left3:?}");
|
||||
assert!((middle(&last) - middle(&after) - Vec2::new(step, 0.0)).hypot() < 1e-9, "the middle moves one step right");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arrows_move_a_selected_straight_segment_whole() {
|
||||
let (mut s, id) = selected_segment(Point::new(100.0, 300.0), Point::new(400.0, 300.0));
|
||||
let step = s.prefs.keyboard_increment;
|
||||
let before = segment(&s, id);
|
||||
s.execute("object.nudge", &json!({"dx": 0, "dy": 1})).unwrap();
|
||||
let after = segment(&s, id);
|
||||
for (a, b) in before.anchors.iter().zip(&after.anchors) {
|
||||
assert_eq!(b.p - a.p, Vec2::new(0.0, step));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selected_straight_segment_beside_a_curved_one_moves_whole() {
|
||||
let (p0, p1, p2) = (Point::new(100.0, 300.0), Point::new(400.0, 300.0), Point::new(600.0, 300.0));
|
||||
let (s, id) = session_with(vec![
|
||||
Anchor::with_handles(p0, p0, Point::new(100.0, 150.0)),
|
||||
Anchor::with_handles(p1, Point::new(300.0, 300.0), p1),
|
||||
Anchor::corner(p2),
|
||||
]);
|
||||
let mut s = select(s, id, &[0, 1]);
|
||||
let step = s.prefs.keyboard_increment;
|
||||
let before = segment(&s, id);
|
||||
s.execute("object.nudge", &json!({"dx": 0, "dy": -1})).unwrap();
|
||||
let after = segment(&s, id);
|
||||
assert_eq!(after.anchors[0].p, before.anchors[0].p, "the curved segment's other anchor stays");
|
||||
for i in [1, 2] {
|
||||
assert_eq!(after.anchors[i].p - before.anchors[i].p, Vec2::new(0.0, -step), "the straight segment's anchor {i} moves");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_segment_whose_handles_lie_across_the_arrow_records_no_undo_step() {
|
||||
// Both handles point up: ← and → bend nothing.
|
||||
let (mut s, id) = selected_segment(Point::new(100.0, 150.0), Point::new(400.0, 150.0));
|
||||
let (before, steps) = (segment(&s, id), undo_steps(&s));
|
||||
s.execute("object.nudge", &json!({"dx": 1, "dy": 0})).unwrap();
|
||||
assert_eq!(segment(&s, id), before);
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_handle_bent_through_a_smooth_anchor_leaves_the_next_segment_as_it_is() {
|
||||
// A smooth anchor between the selected segment, whose handle there is short and points up,
|
||||
// and the next one.
|
||||
let (p0, p1, p2) = (Point::new(100.0, 300.0), Point::new(400.0, 300.0), Point::new(700.0, 300.0));
|
||||
let smooth = Anchor::with_handles(p0, Point::new(100.0, 310.0), Point::new(100.0, 299.5));
|
||||
let (s, id) = session_with(vec![
|
||||
Anchor::corner(Point::new(-200.0, 300.0)),
|
||||
smooth,
|
||||
Anchor::with_handles(p1, Point::new(300.0, 300.0), p1),
|
||||
Anchor::corner(p2),
|
||||
]);
|
||||
assert_eq!(smooth.kind, vectorcraft_geom::AnchorKind::Smooth);
|
||||
let mut s = select(s, id, &[1]);
|
||||
let h_in = segment(&s, id).anchors[1].h_in;
|
||||
// ↓ shrinks the upward handle through its anchor.
|
||||
s.execute("object.nudge", &json!({"dx": 0, "dy": 1})).unwrap();
|
||||
let after = segment(&s, id).anchors[1];
|
||||
assert!(after.h_out.y > p0.y, "the handle comes out pointing down: {:?}", after.h_out);
|
||||
assert_eq!(after.h_in, h_in, "the next segment's handle stays");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_retracted_handle_the_arrow_leaves_keeps_its_smooth_anchor_smooth() {
|
||||
// A smooth anchor whose outgoing handle is retracted, so it points toward the other handle's
|
||||
// end, level with it and across ↓; only the other handle, pointing up, changes.
|
||||
let (p0, p1) = (Point::new(100.0, 300.0), Point::new(200.0, 400.0));
|
||||
let smooth = Anchor { p: p0, h_in: Point::new(0.0, 300.0), h_out: p0, kind: vectorcraft_geom::AnchorKind::Smooth };
|
||||
let (s, id) = session_with(vec![Anchor::corner(Point::new(-200.0, 300.0)), smooth, Anchor::with_handles(p1, Point::new(200.0, 300.0), p1)]);
|
||||
let mut s = select(s, id, &[1]);
|
||||
let before = segment(&s, id);
|
||||
s.execute("object.nudge", &json!({"dx": 0, "dy": 1})).unwrap();
|
||||
let after = segment(&s, id);
|
||||
assert_ne!(after.anchors[2].h_in, before.anchors[2].h_in, "the upward handle changes");
|
||||
assert_eq!(after.anchors[1], before.anchors[1], "the smooth anchor stays as it was");
|
||||
}
|
||||
@@ -1313,6 +1313,811 @@ fn a_color_a_pattern_brings_leaves_links_to_a_deleted_color_alone() {
|
||||
assert!(doc(&s).swatch("Ink 2").is_none(), "{r}");
|
||||
}
|
||||
|
||||
/// A tint or gradient of a numbered library name ("Ink 2") that a library pattern's art brings
|
||||
/// keeps that name when the document gives the art's color "Ink" another color, so adding the
|
||||
/// library's "Ink 2" next finds it.
|
||||
#[test]
|
||||
fn a_numbered_tint_or_gradient_a_pattern_brings_keeps_the_librarys_name() {
|
||||
let tint = json!({"name": "Ink 2", "swatch": "Ink", "tint": 50});
|
||||
let gradient = json!({"name": "Ink 2", "gradient": {"stops": [{"offset": 0, "swatch": "Ink"}, {"offset": 1, "color": "#ffffff"}]}});
|
||||
for numbered in [tint, gradient] {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
|
||||
run(&mut s, "swatch.new", numbered.clone());
|
||||
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone();
|
||||
run(&mut s, "paint.setFill", json!({"swatch": "Ink 2", "ids": [dot]}));
|
||||
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
|
||||
run(&mut s, "select.set", json!({"ids": [dot]}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
|
||||
let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]}));
|
||||
assert!(doc(&s).swatch("Ink 2").is_some_and(|w| !w.global && !w.spot), "{numbered}: {first}");
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink 2"]}));
|
||||
assert_eq!((&r["added"], &r["existing"]), (&json!([]), &json!(["Ink 2"])), "{numbered}: {first} {r}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A library pattern swatch that comes in under a numbered name skips the names the library gives
|
||||
/// its other swatches: adding the library's "Dots 2" next adds it under its own name.
|
||||
#[test]
|
||||
fn a_library_pattern_swatchs_copy_skips_the_librarys_other_names() {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
|
||||
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone();
|
||||
run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]}));
|
||||
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
|
||||
run(&mut s, "select.set", json!({"ids": [dot]}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": "Squares", "width": 8, "height": 8}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
s.edit("Dots", |d, _| {
|
||||
let paint = vectorcraft_doc::pattern::pattern_paint("Squares");
|
||||
d.swatches.push(vectorcraft_color::Swatch { name: "Dots".into(), paint, global: false, spot: false });
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
run(&mut s, "swatch.new", json!({"name": "Dots 2", "color": "#00ff00", "global": true}));
|
||||
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Squares.vectorcraft"}))["library"].clone();
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Dots", "color": "#ff0000"}));
|
||||
let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Dots"]}));
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Dots 2"]}));
|
||||
assert_eq!(r["added"], json!(["Dots 2"]), "{first} {r}");
|
||||
assert!(is_global(&s, "Dots 2", "#00ff00"), "{first} {r}");
|
||||
}
|
||||
|
||||
/// A library whose spot color "Ink" shares its name with a global color in a color group: a
|
||||
/// pattern's art painted with both brings both. A library tint of the spot color, picked before
|
||||
/// the pattern, links to the document's copy of the spot color the art takes, not to the global
|
||||
/// color the art brings under a numbered name, whether that color has another paint or the same.
|
||||
/// The library's own spot "Ink 2" is green, so the document's blue "Ink 2" is not that swatch.
|
||||
#[test]
|
||||
fn a_library_tint_is_not_linked_to_a_namesake_of_another_kind_a_pattern_brings() {
|
||||
for global_color in ["#ff0000", "#0000ff"] {
|
||||
a_library_tint_skips_a_namesake_the_pattern_brings(global_color);
|
||||
}
|
||||
}
|
||||
|
||||
fn a_library_tint_skips_a_namesake_the_pattern_brings(global_color: &str) {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "spot": true}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#00ff00", "spot": true}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Crimson", "color": global_color, "global": true}));
|
||||
let blue = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 3, "height": 6}))["id"].clone();
|
||||
let red = run(&mut s, "shape.rectangle", json!({"x": 3, "y": 0, "width": 3, "height": 6}))["id"].clone();
|
||||
run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [blue]}));
|
||||
run(&mut s, "paint.setFill", json!({"swatch": "Crimson", "ids": [red]}));
|
||||
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [blue, red]}));
|
||||
run(&mut s, "select.set", json!({"ids": [blue, red]}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
// The global color becomes "Ink" in a color group, and the pattern's art links to it by that name.
|
||||
s.edit("Rename", |d, _| {
|
||||
let i = d.swatches.iter().position(|w| w.name == "Crimson").unwrap();
|
||||
let mut global = d.swatches.remove(i);
|
||||
global.name = "Ink".into();
|
||||
d.swatch_groups.push(vectorcraft_color::SwatchGroup { name: "Reds".into(), swatches: vec![global] });
|
||||
let def = d.pattern_mut("Tiles").unwrap();
|
||||
for node in &mut def.art {
|
||||
for it in &mut std::sync::Arc::make_mut(node).appearance.items {
|
||||
it.paint_mut().map_links(&mut |_, link, _| {
|
||||
let red = link.as_deref() == Some("Crimson");
|
||||
if red {
|
||||
*link = Some("Ink".into());
|
||||
}
|
||||
red
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let art_links: Vec<Option<String>> = doc(&s).pattern("Tiles").unwrap().art.iter().map(|n| tint_link(&n.appearance.fill_paint())).collect();
|
||||
assert_eq!(art_links, [Some("Ink".to_string()), Some("Ink".to_string())]);
|
||||
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff"}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "spot": true}));
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half", "Tiles"]}));
|
||||
assert_eq!(tint_base(&s, "Ink half").as_deref(), Some("Ink 2"), "{global_color}: {r}");
|
||||
assert!(doc(&s).swatch("Ink 2").is_some_and(|w| w.spot), "{global_color}: {r}");
|
||||
}
|
||||
|
||||
/// A color of a numbered library name ("Ink 2") that a pattern's art brings comes in under that
|
||||
/// name when the document does not use it, not as the document's copy of it ("Ink 2 2"), so
|
||||
/// adding the library's "Ink 2" next finds it.
|
||||
#[test]
|
||||
fn a_numbered_color_a_pattern_brings_keeps_its_name_beside_a_copy_of_it() {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#00ff00", "global": true}));
|
||||
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone();
|
||||
run(&mut s, "paint.setFill", json!({"swatch": "Ink 2", "ids": [dot]}));
|
||||
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
|
||||
run(&mut s, "select.set", json!({"ids": [dot]}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink 2 2", "color": "#00ff00", "global": true}));
|
||||
let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]}));
|
||||
assert!(is_global(&s, "Ink 2", "#00ff00"), "{first}");
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink 2"]}));
|
||||
assert_eq!((&r["added"], &r["existing"]), (&json!([]), &json!(["Ink 2"])), "{first} {r}");
|
||||
}
|
||||
|
||||
/// A pattern that a library pattern's art is painted with ("Inner"), brought under a numbered name
|
||||
/// because the document has a swatch "Inner", skips the name "Inner 2" that the library gives a
|
||||
/// color, as does the swatch that comes with it.
|
||||
#[test]
|
||||
fn a_nested_pattern_a_library_pattern_brings_skips_the_librarys_names() {
|
||||
let mut s = session();
|
||||
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 4, "height": 4}))["id"].clone();
|
||||
run(&mut s, "select.set", json!({"ids": [dot]}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": "Inner", "width": 6, "height": 6}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
let tile = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10}))["id"].clone();
|
||||
run(&mut s, "paint.setFill", json!({"swatch": "Inner", "ids": [tile]}));
|
||||
run(&mut s, "select.set", json!({"ids": [tile]}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": "Outer", "width": 12, "height": 12}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Inner 2", "color": "#00ff00", "global": true}));
|
||||
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Outer.vectorcraft"}))["library"].clone();
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Inner", "color": "#ff0000"}));
|
||||
let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Outer"]}));
|
||||
assert!(doc(&s).pattern("Inner 2").is_none(), "{first}");
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Inner 2"]}));
|
||||
assert_eq!(r["added"], json!(["Inner 2"]), "{first} {r}");
|
||||
assert!(is_global(&s, "Inner 2", "#00ff00"), "{first} {r}");
|
||||
}
|
||||
|
||||
/// A library pattern that was pasted into the document with its art linked to the document's
|
||||
/// copy of a numbered library color ("Ink 2 2" for "Ink 2") is found when it is added from the
|
||||
/// library, not added again.
|
||||
#[test]
|
||||
fn a_pasted_pattern_linked_to_a_copy_of_a_numbered_color_is_found() {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#00ff00", "global": true}));
|
||||
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone();
|
||||
run(&mut s, "paint.setFill", json!({"swatch": "Ink 2", "ids": [dot]}));
|
||||
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
|
||||
run(&mut s, "select.set", json!({"ids": [dot]}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
|
||||
let r = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 40}))["id"].clone();
|
||||
run(&mut s, "paint.setFill", json!({"swatch": "Tiles", "ids": [r]}));
|
||||
run(&mut s, "select.set", json!({"ids": [r]}));
|
||||
run(&mut s, "edit.copy", json!({}));
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink 2 2", "color": "#00ff00", "global": true}));
|
||||
run(&mut s, "edit.paste", json!({}));
|
||||
assert!(doc(&s).swatch("Ink 2").is_none(), "the paste reused the copy");
|
||||
run(&mut s, "swatch.delete", json!({"names": ["Tiles"]}));
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]}));
|
||||
assert_eq!(doc(&s).patterns.len(), 1, "{r}");
|
||||
}
|
||||
|
||||
/// A library pattern swatch named after its pattern ("Tiles 2") that comes in with a new pattern
|
||||
/// under a numbered name ("Tiles 2 2"), because the document has another pattern of that name
|
||||
/// without a swatch, takes the library swatch's name.
|
||||
#[test]
|
||||
fn a_new_patterns_swatch_takes_the_library_swatchs_free_name() {
|
||||
let mut s = session();
|
||||
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone();
|
||||
run(&mut s, "select.set", json!({"ids": [dot]}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": "Tiles 2", "width": 8, "height": 8}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
let own = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 9, "height": 9}))["id"].clone();
|
||||
run(&mut s, "select.set", json!({"ids": [own]}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": "Tiles 2", "width": 12, "height": 12}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
run(&mut s, "swatch.delete", json!({"names": ["Tiles 2"]}));
|
||||
assert!(doc(&s).pattern("Tiles 2").is_some(), "the document keeps its pattern");
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles 2"]}));
|
||||
assert_eq!(r["added"], json!(["Tiles 2"]), "{r}");
|
||||
let paint = doc(&s).swatch("Tiles 2").map(|w| w.paint.clone());
|
||||
assert!(matches!(&paint, Some(Paint::Pattern { pattern, .. }) if pattern != "Tiles 2"), "{r} {paint:?}");
|
||||
// Added again after its swatch is deleted, it reuses the pattern under the same swatch name.
|
||||
run(&mut s, "swatch.delete", json!({"names": ["Tiles 2"]}));
|
||||
let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles 2"]}));
|
||||
assert_eq!(again["added"], json!(["Tiles 2"]), "{r} {again}");
|
||||
assert_eq!(doc(&s).swatch("Tiles 2").map(|w| w.paint.clone()), paint, "{r} {again}");
|
||||
}
|
||||
|
||||
/// A library pattern swatch "Tiles" named after its pattern, added to a document that has another
|
||||
/// pattern "Tiles" without a swatch, is named after the pattern that comes in ("Tiles 2"), as
|
||||
/// before numbered names were reserved: only a numbered name is kept for the library swatch.
|
||||
#[test]
|
||||
fn a_new_patterns_swatch_of_an_unnumbered_name_is_named_after_its_pattern() {
|
||||
let mut s = session();
|
||||
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone();
|
||||
run(&mut s, "select.set", json!({"ids": [dot]}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
let own = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 9, "height": 9}))["id"].clone();
|
||||
run(&mut s, "select.set", json!({"ids": [own]}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 12, "height": 12}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
run(&mut s, "swatch.delete", json!({"names": ["Tiles"]}));
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]}));
|
||||
let added = r["added"].as_array().and_then(|a| a.first()).and_then(|n| n.as_str()).unwrap_or_default().to_string();
|
||||
assert_ne!(added, "Tiles", "{r}");
|
||||
let paint = doc(&s).swatch(&added).map(|w| w.paint.clone());
|
||||
assert!(matches!(&paint, Some(Paint::Pattern { pattern, .. }) if *pattern == added), "{r} {paint:?}");
|
||||
assert!(doc(&s).swatch("Tiles").is_none(), "{r}");
|
||||
}
|
||||
|
||||
/// A library whose process color "Ink 2" shares its name with a global color in a color group
|
||||
/// that a pattern's art is painted with: the global color comes in numbered, so adding the
|
||||
/// library's "Ink 2" next adds the process color under its own name.
|
||||
#[test]
|
||||
fn a_numbered_name_is_kept_for_the_library_swatch_it_names() {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#00ff00"}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Crimson", "color": "#0000ff", "global": true}));
|
||||
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone();
|
||||
run(&mut s, "paint.setFill", json!({"swatch": "Crimson", "ids": [dot]}));
|
||||
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
|
||||
run(&mut s, "select.set", json!({"ids": [dot]}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
group_as(&mut s, "Crimson", "Ink 2");
|
||||
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]}));
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink 2"]}));
|
||||
assert_eq!(r["added"], json!(["Ink 2"]), "{first} {r}");
|
||||
assert!(doc(&s).swatch("Ink 2").is_some_and(|w| !w.global && !w.spot), "{first} {r}");
|
||||
}
|
||||
|
||||
/// A library pattern pasted with Add, whose color came in as "Ink 2" and was then deleted without
|
||||
/// unlinking the art, is not reused through a new "Ink 2" when the library gives that name another
|
||||
/// color: adding that color next adds it under its own name. This holds too when the document has
|
||||
/// a pattern "Ink 2" without a swatch.
|
||||
#[test]
|
||||
fn a_pasted_pattern_is_not_reused_by_taking_a_librarys_name() {
|
||||
for bare in [false, true] {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#00ff00", "global": true}));
|
||||
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone();
|
||||
run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]}));
|
||||
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
|
||||
run(&mut s, "select.set", json!({"ids": [dot]}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
|
||||
let r = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 40}))["id"].clone();
|
||||
run(&mut s, "paint.setFill", json!({"swatch": "Tiles", "ids": [r]}));
|
||||
run(&mut s, "select.set", json!({"ids": [r]}));
|
||||
run(&mut s, "edit.copy", json!({}));
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
if bare {
|
||||
let own = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 9, "height": 9}))["id"].clone();
|
||||
run(&mut s, "select.set", json!({"ids": [own]}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": "Ink 2", "width": 12, "height": 12}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
run(&mut s, "swatch.delete", json!({"names": ["Ink 2"]}));
|
||||
assert!(doc(&s).pattern("Ink 2").is_some(), "the document keeps its pattern");
|
||||
}
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
|
||||
run(&mut s, "edit.paste", json!({"swatchConflict": "add"}));
|
||||
assert!(is_global(&s, "Ink 2", "#0000ff"), "the paste brings the blue color as Ink 2 ({bare})");
|
||||
run(&mut s, "swatch.delete", json!({"names": ["Ink 2"], "unlink": false}));
|
||||
run(&mut s, "swatch.delete", json!({"names": ["Tiles"]}));
|
||||
let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]}));
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink 2"]}));
|
||||
assert_eq!(r["added"], json!(["Ink 2"]), "{bare} {first} {r}");
|
||||
assert!(is_global(&s, "Ink 2", "#00ff00"), "{bare} {first} {r}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A library pattern painted with two global colors of one paint, "Ink" and "Ink 2", added beside
|
||||
/// the document's red "Ink" brings them as "Ink 3" and "Ink 2". Adding the pattern again finds it,
|
||||
/// in either order of the library's colors: "Ink" does not reuse the library's "Ink 2".
|
||||
#[test]
|
||||
fn a_color_a_pattern_brings_again_does_not_reuse_a_copy_the_library_names() {
|
||||
for ink_first in [true, false] {
|
||||
let mut s = session();
|
||||
let names = if ink_first { ["Ink", "Ink 2"] } else { ["Ink 2", "Ink"] };
|
||||
for n in names {
|
||||
run(&mut s, "swatch.new", json!({"name": n, "color": "#0000ff", "global": true}));
|
||||
}
|
||||
let mut dots = vec![];
|
||||
for (i, n) in ["Ink", "Ink 2"].iter().enumerate() {
|
||||
let dot = run(&mut s, "shape.rectangle", json!({"x": i * 5, "y": 0, "width": 4, "height": 4}))["id"].clone();
|
||||
run(&mut s, "paint.setFill", json!({"swatch": n, "ids": [dot]}));
|
||||
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
|
||||
dots.push(dot);
|
||||
}
|
||||
run(&mut s, "select.set", json!({"ids": dots}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 12, "height": 6}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
|
||||
let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]}));
|
||||
assert!(is_global(&s, "Ink 2", "#0000ff") && is_global(&s, "Ink 3", "#0000ff"), "{ink_first} {first}");
|
||||
run(&mut s, "swatch.delete", json!({"names": ["Tiles"]}));
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]}));
|
||||
assert_eq!(doc(&s).patterns.len(), 1, "{ink_first} {first} {r}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A library pattern painted with a blue global "Ink" and a green global "Ink 2", added to a
|
||||
/// document with a red "Ink" and a blue global "Ink 2": the art's "Ink" is the document's "Ink 2",
|
||||
/// since that is not the library's "Ink 2", and no third copy comes in.
|
||||
#[test]
|
||||
fn a_color_a_pattern_brings_reuses_a_copy_that_is_not_the_librarys_namesake() {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#00ff00", "global": true}));
|
||||
let mut dots = vec![];
|
||||
for (i, n) in ["Ink", "Ink 2"].iter().enumerate() {
|
||||
let dot = run(&mut s, "shape.rectangle", json!({"x": i * 5, "y": 0, "width": 4, "height": 4}))["id"].clone();
|
||||
run(&mut s, "paint.setFill", json!({"swatch": n, "ids": [dot]}));
|
||||
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
|
||||
dots.push(dot);
|
||||
}
|
||||
run(&mut s, "select.set", json!({"ids": dots}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 12, "height": 6}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true}));
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]}));
|
||||
assert!(doc(&s).swatch("Ink 3").is_none(), "{r}");
|
||||
assert!(is_global(&s, "Ink 2", "#0000ff") && is_global(&s, "Ink 2 2", "#00ff00"), "{r}");
|
||||
}
|
||||
|
||||
/// A library pattern painted with a blue global "Ink", from a library that also has a blue global
|
||||
/// "Ink 2" the art does not use, added beside the document's red "Ink" after the library's "Ink 2"
|
||||
/// came in: the art's "Ink" does not reuse the library's "Ink 2" and comes in as "Ink 3".
|
||||
#[test]
|
||||
fn a_color_a_pattern_brings_does_not_reuse_another_library_colors_copy() {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true}));
|
||||
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone();
|
||||
run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]}));
|
||||
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
|
||||
run(&mut s, "select.set", json!({"ids": [dot]}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
|
||||
let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink 2"]}));
|
||||
assert!(is_global(&s, "Ink 2", "#0000ff"), "{first}");
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]}));
|
||||
assert!(is_global(&s, "Ink 3", "#0000ff"), "{first} {r}");
|
||||
let links: Vec<Option<String>> = doc(&s).pattern("Tiles").unwrap().art.iter().map(|n| tint_link(&n.appearance.fill_paint())).collect();
|
||||
assert_eq!(links, vec![Some("Ink 3".to_string())], "{first} {r}");
|
||||
}
|
||||
|
||||
/// A library pattern painted with a blue global "Ink", pasted beside the document's red "Ink" and
|
||||
/// then left without its color "Ink 2" (deleted without unlinking), is not reused by bringing the
|
||||
/// library's "Ink" back as "Ink 2" when the library has its own blue "Ink 2": the pattern links to
|
||||
/// another copy.
|
||||
#[test]
|
||||
fn a_pasted_pattern_is_not_reused_by_giving_a_librarys_name_to_another_color() {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true}));
|
||||
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone();
|
||||
run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]}));
|
||||
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
|
||||
run(&mut s, "select.set", json!({"ids": [dot]}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
|
||||
let r = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 40}))["id"].clone();
|
||||
run(&mut s, "paint.setFill", json!({"swatch": "Tiles", "ids": [r]}));
|
||||
run(&mut s, "select.set", json!({"ids": [r]}));
|
||||
run(&mut s, "edit.copy", json!({}));
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
|
||||
run(&mut s, "edit.paste", json!({"swatchConflict": "add"}));
|
||||
assert!(is_global(&s, "Ink 2", "#0000ff"), "the paste brings the blue color as Ink 2");
|
||||
run(&mut s, "swatch.delete", json!({"names": ["Ink 2"], "unlink": false}));
|
||||
run(&mut s, "swatch.delete", json!({"names": ["Tiles"]}));
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]}));
|
||||
let added = r["added"].as_array().and_then(|a| a.first()).and_then(|n| n.as_str()).unwrap_or_default().to_string();
|
||||
let pattern = match doc(&s).swatch(&added).map(|w| w.paint.clone()) {
|
||||
Some(Paint::Pattern { pattern, .. }) => pattern,
|
||||
p => panic!("{r} {p:?}"),
|
||||
};
|
||||
let links: Vec<Option<String>> = doc(&s).pattern(&pattern).unwrap().art.iter().map(|n| tint_link(&n.appearance.fill_paint())).collect();
|
||||
assert!(!links.contains(&Some("Ink 2".to_string())), "{r} {links:?}");
|
||||
}
|
||||
|
||||
/// A library pattern painted with two alike gradients of its blue global "Ink", "Ramp 2" and then
|
||||
/// "Ramp", added beside the document's red "Ink": the color comes in as "Ink 2", and both
|
||||
/// gradients come in under their own names, linked to it, instead of "Ramp" taking "Ramp 2".
|
||||
#[test]
|
||||
fn alike_gradients_a_pattern_brings_keep_their_names_when_their_color_is_renamed() {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
|
||||
let ramp = json!({"stops": [{"offset": 0, "swatch": "Ink"}, {"offset": 1, "color": "#ffffff"}]});
|
||||
run(&mut s, "swatch.new", json!({"name": "Ramp 2", "gradient": ramp}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ramp", "gradient": ramp}));
|
||||
let mut dots = vec![];
|
||||
for (i, n) in ["Ramp 2", "Ramp"].iter().enumerate() {
|
||||
let dot = run(&mut s, "shape.rectangle", json!({"x": i * 5, "y": 0, "width": 4, "height": 4}))["id"].clone();
|
||||
run(&mut s, "paint.setFill", json!({"swatch": n, "ids": [dot]}));
|
||||
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
|
||||
dots.push(dot);
|
||||
}
|
||||
run(&mut s, "select.set", json!({"ids": dots}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 12, "height": 6}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]}));
|
||||
assert!(is_global(&s, "Ink 2", "#0000ff"), "{r}");
|
||||
assert!(doc(&s).swatch("Ramp").is_some() && doc(&s).swatch("Ramp 2").is_some(), "{r}");
|
||||
}
|
||||
|
||||
/// A library pattern painted with blue globals "Ink" and "Ink 2", pasted twice beside the
|
||||
/// document's red "Ink" and blue "Ink 2" (with Add, both fills on "Ink 2"; with Merge, one on the
|
||||
/// red "Ink"), is found again as the copy that keeps its blue, not the merged one.
|
||||
#[test]
|
||||
fn a_pattern_pasted_with_add_and_with_merge_is_found_as_the_copy_with_its_colors() {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true}));
|
||||
let mut dots = vec![];
|
||||
for (i, n) in ["Ink", "Ink 2"].iter().enumerate() {
|
||||
let dot = run(&mut s, "shape.rectangle", json!({"x": i * 5, "y": 0, "width": 4, "height": 4}))["id"].clone();
|
||||
run(&mut s, "paint.setFill", json!({"swatch": n, "ids": [dot]}));
|
||||
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
|
||||
dots.push(dot);
|
||||
}
|
||||
run(&mut s, "select.set", json!({"ids": dots}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 12, "height": 6}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
|
||||
let r = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 40}))["id"].clone();
|
||||
run(&mut s, "paint.setFill", json!({"swatch": "Tiles", "ids": [r]}));
|
||||
run(&mut s, "select.set", json!({"ids": [r]}));
|
||||
run(&mut s, "edit.copy", json!({}));
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true}));
|
||||
run(&mut s, "edit.paste", json!({"swatchConflict": "add"}));
|
||||
run(&mut s, "edit.paste", json!({"swatchConflict": "merge"}));
|
||||
let links = |s: &Session, p: &str| -> Vec<Option<String>> {
|
||||
doc(s).pattern(p).unwrap().art.iter().map(|n| tint_link(&n.appearance.fill_paint())).collect()
|
||||
};
|
||||
let kept: Vec<String> = doc(&s).patterns.iter().map(|p| p.name.clone()).filter(|p| !links(&s, p).contains(&Some("Ink".into()))).collect();
|
||||
assert_eq!((doc(&s).patterns.len(), kept.len()), (2, 1), "one pasted copy keeps the blue color");
|
||||
for w in doc(&s).swatches.clone().iter().filter(|w| matches!(w.paint, Paint::Pattern { .. })) {
|
||||
run(&mut s, "swatch.delete", json!({"names": [w.name]}));
|
||||
}
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]}));
|
||||
let pattern = match doc(&s).swatch("Tiles").map(|w| w.paint.clone()) {
|
||||
Some(Paint::Pattern { pattern, .. }) => pattern,
|
||||
p => panic!("{r} {p:?}"),
|
||||
};
|
||||
assert_eq!((doc(&s).patterns.len(), &pattern), (2, &kept[0]), "{r}");
|
||||
}
|
||||
|
||||
/// A library whose color "Tiles 2" shares its name with a pattern swatch in a color group: adding
|
||||
/// the group gives the pattern swatch another name, so adding the color next adds it under its own.
|
||||
#[test]
|
||||
fn a_grouped_pattern_swatch_leaves_a_numbered_name_to_the_librarys_color() {
|
||||
let mut s = session();
|
||||
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 4, "height": 4}))["id"].clone();
|
||||
run(&mut s, "select.set", json!({"ids": [dot]}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": "Dots", "width": 6, "height": 6}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Tiles 2", "color": "#00ff00", "global": true}));
|
||||
s.edit("Group", |d, _| {
|
||||
let i = d.swatches.iter().position(|w| w.name == "Dots").unwrap();
|
||||
let mut w = d.swatches.remove(i);
|
||||
w.name = "Tiles 2".into();
|
||||
d.swatch_groups.push(vectorcraft_color::SwatchGroup { name: "Group".into(), swatches: vec![w] });
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Dots.vectorcraft"}))["library"].clone();
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Group"]}));
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles 2"]}));
|
||||
assert_eq!(r["added"], json!(["Tiles 2"]), "{first} {r}");
|
||||
assert!(is_global(&s, "Tiles 2", "#00ff00"), "{first} {r}");
|
||||
}
|
||||
|
||||
/// As above, with the grouped swatch named after its pattern "Tiles 2", which the document holds
|
||||
/// (pasted there) without a swatch: the reused pattern's swatch leaves the name to the color too.
|
||||
#[test]
|
||||
fn a_grouped_swatch_of_a_reused_pattern_leaves_a_numbered_name_to_the_librarys_color() {
|
||||
let mut s = session();
|
||||
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 4, "height": 4}))["id"].clone();
|
||||
run(&mut s, "select.set", json!({"ids": [dot]}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": "Tiles 2", "width": 6, "height": 6}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
let r = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 40}))["id"].clone();
|
||||
run(&mut s, "paint.setFill", json!({"swatch": "Tiles 2", "ids": [r]}));
|
||||
run(&mut s, "select.set", json!({"ids": [r]}));
|
||||
run(&mut s, "edit.copy", json!({}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Bright", "color": "#00ff00", "global": true}));
|
||||
s.edit("Group", |d, _| {
|
||||
let i = d.swatches.iter().position(|w| w.name == "Tiles 2").unwrap();
|
||||
let w = d.swatches.remove(i);
|
||||
d.swatch_groups.push(vectorcraft_color::SwatchGroup { name: "Group".into(), swatches: vec![w] });
|
||||
d.swatches.iter_mut().find(|w| w.name == "Bright").unwrap().name = "Tiles 2".into();
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
run(&mut s, "edit.paste", json!({}));
|
||||
run(&mut s, "swatch.delete", json!({"names": ["Tiles 2"]}));
|
||||
assert!(doc(&s).pattern("Tiles 2").is_some() && doc(&s).swatch("Tiles 2").is_none(), "the pasted pattern stays");
|
||||
let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Group"]}));
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles 2"]}));
|
||||
assert_eq!(r["added"], json!(["Tiles 2"]), "{first} {r}");
|
||||
assert!(is_global(&s, "Tiles 2", "#00ff00"), "{first} {r}");
|
||||
}
|
||||
|
||||
/// A pattern "Inner 2" that a library pattern's art is painted with, whose library swatch "Inner 2"
|
||||
/// places it with an offset, leaves the name to that swatch: adding the library's "Inner 2" next
|
||||
/// adds it under its own name with its placement. Picked first, "Inner 2" comes in under its own
|
||||
/// name too.
|
||||
#[test]
|
||||
fn a_nested_pattern_leaves_its_name_to_a_library_swatch_that_places_it_otherwise() {
|
||||
for outer_first in [true, false] {
|
||||
let mut s = session();
|
||||
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 4, "height": 4}))["id"].clone();
|
||||
run(&mut s, "select.set", json!({"ids": [dot]}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": "Inner 2", "width": 6, "height": 6}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
let tile = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10}))["id"].clone();
|
||||
run(&mut s, "paint.setFill", json!({"swatch": "Inner 2", "ids": [tile]}));
|
||||
run(&mut s, "select.set", json!({"ids": [tile]}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": "Outer", "width": 12, "height": 12}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
let offset = Paint::Pattern { pattern: "Inner 2".into(), xf: kurbo::Affine::translate((3.0, 0.0)) };
|
||||
let lib_paint = offset.clone();
|
||||
s.edit("Offset", move |d, _| {
|
||||
d.swatches.iter_mut().find(|w| w.name == "Inner 2").unwrap().paint = lib_paint;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Outer.vectorcraft"}))["library"].clone();
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
let picks = if outer_first { ["Outer", "Inner 2"] } else { ["Inner 2", "Outer"] };
|
||||
let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": [picks[0]]}));
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": [picks[1]]}));
|
||||
assert_eq!(doc(&s).swatch("Inner 2").map(|w| w.paint.clone()), Some(offset), "{outer_first} {first} {r}");
|
||||
assert_eq!(doc(&s).patterns.len(), 2, "{outer_first} {first} {r}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A pattern "Inner 2" that a library pattern's art is painted with, brought under a numbered name
|
||||
/// because the document has another pattern "Inner 2" without a swatch, comes with a swatch under
|
||||
/// the library swatch's free name "Inner 2": adding the library's "Inner 2" next finds it.
|
||||
#[test]
|
||||
fn a_nested_patterns_swatch_takes_the_library_swatchs_free_name() {
|
||||
let mut s = session();
|
||||
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 4, "height": 4}))["id"].clone();
|
||||
run(&mut s, "select.set", json!({"ids": [dot]}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": "Inner 2", "width": 6, "height": 6}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
let tile = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10}))["id"].clone();
|
||||
run(&mut s, "paint.setFill", json!({"swatch": "Inner 2", "ids": [tile]}));
|
||||
run(&mut s, "select.set", json!({"ids": [tile]}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": "Outer", "width": 12, "height": 12}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Outer.vectorcraft"}))["library"].clone();
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
let own = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 9, "height": 9}))["id"].clone();
|
||||
run(&mut s, "paint.setFill", json!({"color": "#ff0000", "ids": [own]}));
|
||||
run(&mut s, "select.set", json!({"ids": [own]}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": "Inner 2", "width": 14, "height": 14}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
run(&mut s, "swatch.delete", json!({"names": ["Inner 2"]}));
|
||||
assert!(doc(&s).pattern("Inner 2").is_some(), "the document keeps its pattern");
|
||||
let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Outer"]}));
|
||||
let paint = doc(&s).swatch("Inner 2").map(|w| w.paint.clone());
|
||||
assert!(
|
||||
matches!(&paint, Some(Paint::Pattern { pattern, .. }) if pattern != "Inner 2" && doc(&s).pattern(pattern).is_some()),
|
||||
"{first} {paint:?}"
|
||||
);
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Inner 2"]}));
|
||||
assert_eq!(r["added"], json!([]), "{first} {r}");
|
||||
assert_eq!(doc(&s).swatch("Inner 2").map(|w| w.paint.clone()), paint, "{first} {r}");
|
||||
assert_eq!(doc(&s).patterns.len(), 3, "{first} {r}");
|
||||
}
|
||||
|
||||
/// A library with a pattern swatch "Tiles 2" and, in a color group, a swatch of the same name that
|
||||
/// places the same pattern with an offset: adding the group first leaves the name to the
|
||||
/// ungrouped swatch, which comes in under it next.
|
||||
#[test]
|
||||
fn a_grouped_namesake_of_a_pattern_swatch_leaves_it_the_name() {
|
||||
let mut s = session();
|
||||
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 4, "height": 4}))["id"].clone();
|
||||
run(&mut s, "select.set", json!({"ids": [dot]}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": "Tiles 2", "width": 6, "height": 6}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
s.edit("Group", |d, _| {
|
||||
let offset = Paint::Pattern { pattern: "Tiles 2".into(), xf: kurbo::Affine::translate((3.0, 0.0)) };
|
||||
let w = vectorcraft_color::Swatch { name: "Tiles 2".into(), paint: offset, global: false, spot: false };
|
||||
d.swatch_groups.push(vectorcraft_color::SwatchGroup { name: "Group".into(), swatches: vec![w] });
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Group"]}));
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles 2"]}));
|
||||
let paint = doc(&s).swatch("Tiles 2").map(|w| w.paint.clone());
|
||||
assert!(matches!(&paint, Some(Paint::Pattern { xf, .. }) if *xf == kurbo::Affine::IDENTITY), "{first} {r} {paint:?}");
|
||||
}
|
||||
|
||||
/// A pattern "Inner 2" that a library pattern's art is painted with, whose swatch the library
|
||||
/// deleted before giving the name "Inner 2" to a color, comes in under another name, so adding
|
||||
/// that color next adds it under its own name.
|
||||
#[test]
|
||||
fn a_nested_pattern_does_not_take_a_name_the_library_gives_a_color() {
|
||||
let mut s = session();
|
||||
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 4, "height": 4}))["id"].clone();
|
||||
run(&mut s, "select.set", json!({"ids": [dot]}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": "Inner 2", "width": 6, "height": 6}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
let tile = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10}))["id"].clone();
|
||||
run(&mut s, "paint.setFill", json!({"swatch": "Inner 2", "ids": [tile]}));
|
||||
run(&mut s, "select.set", json!({"ids": [tile]}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": "Outer", "width": 12, "height": 12}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
run(&mut s, "swatch.delete", json!({"names": ["Inner 2"]}));
|
||||
assert!(doc(&s).pattern("Inner 2").is_some(), "the library keeps the pattern");
|
||||
run(&mut s, "swatch.new", json!({"name": "Inner 2", "color": "#00ff00", "global": true}));
|
||||
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Outer.vectorcraft"}))["library"].clone();
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Outer"]}));
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Inner 2"]}));
|
||||
assert_eq!(r["added"], json!(["Inner 2"]), "{first} {r}");
|
||||
assert!(is_global(&s, "Inner 2", "#00ff00"), "{first} {r}");
|
||||
}
|
||||
|
||||
/// A library pattern pasted into the document, whose global color "Ink 2" (in a color group) was
|
||||
/// then deleted without unlinking the art, is not reused by bringing that color back as "Ink 2"
|
||||
/// when the library also has a process color "Ink 2": adding that color next adds it under its
|
||||
/// own name.
|
||||
#[test]
|
||||
fn a_pasted_pattern_is_not_reused_by_bringing_back_a_librarys_name() {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#00ff00"}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Crimson", "color": "#0000ff", "global": true}));
|
||||
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone();
|
||||
run(&mut s, "paint.setFill", json!({"swatch": "Crimson", "ids": [dot]}));
|
||||
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
|
||||
run(&mut s, "select.set", json!({"ids": [dot]}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
group_as(&mut s, "Crimson", "Ink 2");
|
||||
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
|
||||
let r = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 40}))["id"].clone();
|
||||
run(&mut s, "paint.setFill", json!({"swatch": "Tiles", "ids": [r]}));
|
||||
run(&mut s, "select.set", json!({"ids": [r]}));
|
||||
run(&mut s, "edit.copy", json!({}));
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
run(&mut s, "edit.paste", json!({}));
|
||||
assert!(is_global(&s, "Ink 2", "#0000ff"), "the paste brings the global color as Ink 2");
|
||||
run(&mut s, "swatch.delete", json!({"names": ["Ink 2"], "unlink": false}));
|
||||
run(&mut s, "swatch.delete", json!({"names": ["Tiles"]}));
|
||||
let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]}));
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink 2"]}));
|
||||
assert_eq!(r["added"], json!(["Ink 2"]), "{first} {r}");
|
||||
assert!(doc(&s).swatch("Ink 2").is_some_and(|w| !w.global && !w.spot), "{first} {r}");
|
||||
}
|
||||
|
||||
/// Move swatch `name` of `s`'s document into a new color group under the name `to`, and link the
|
||||
/// art of every pattern linked to it to `to`.
|
||||
fn group_as(s: &mut Session, name: &str, to: &str) {
|
||||
s.edit("Group", |d, _| {
|
||||
let i = d.swatches.iter().position(|w| w.name == name).unwrap();
|
||||
let mut w = d.swatches.remove(i);
|
||||
w.name = to.into();
|
||||
d.swatch_groups.push(vectorcraft_color::SwatchGroup { name: "Group".into(), swatches: vec![w] });
|
||||
for def in &mut d.patterns {
|
||||
for node in &mut def.art {
|
||||
for it in &mut std::sync::Arc::make_mut(node).appearance.items {
|
||||
it.paint_mut().map_links(&mut |_, link, _| {
|
||||
let hit = link.as_deref() == Some(name);
|
||||
if hit {
|
||||
*link = Some(to.into());
|
||||
}
|
||||
hit
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// The swatch paint `p` links to.
|
||||
fn tint_link(p: &Paint) -> Option<String> {
|
||||
match p {
|
||||
Paint::Solid { swatch, .. } => swatch.clone(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A library pattern "Tiles" added beside the document's own swatch "Tiles" does not take the name
|
||||
/// "Tiles 2" that the library gives a color, neither for the pattern nor for its swatch; nor does
|
||||
/// its swatch when the document holds the pattern as "Tiles 2" (pasted there) without a swatch.
|
||||
#[test]
|
||||
fn a_pattern_swatch_named_after_its_numbered_pattern_skips_the_librarys_names() {
|
||||
for pasted in [false, true] {
|
||||
let mut s = session();
|
||||
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone();
|
||||
run(&mut s, "select.set", json!({"ids": [dot]}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Tiles 2", "color": "#00ff00", "global": true}));
|
||||
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
|
||||
let r = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 40}))["id"].clone();
|
||||
run(&mut s, "paint.setFill", json!({"swatch": "Tiles", "ids": [r]}));
|
||||
run(&mut s, "select.set", json!({"ids": [r]}));
|
||||
run(&mut s, "edit.copy", json!({}));
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Tiles", "color": "#ff0000"}));
|
||||
if pasted {
|
||||
run(&mut s, "edit.paste", json!({}));
|
||||
assert!(doc(&s).pattern("Tiles 2").is_some(), "the paste numbers the pattern");
|
||||
let names: Vec<String> = doc(&s)
|
||||
.swatches_iter()
|
||||
.filter(|w| matches!(&w.paint, Paint::Pattern { pattern, .. } if pattern == "Tiles 2"))
|
||||
.map(|w| w.name.clone())
|
||||
.collect();
|
||||
run(&mut s, "swatch.delete", json!({"names": names}));
|
||||
}
|
||||
let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]}));
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles 2"]}));
|
||||
assert_eq!(r["added"], json!(["Tiles 2"]), "{pasted}: {first} {r}");
|
||||
assert!(is_global(&s, "Tiles 2", "#00ff00"), "{pasted}: {first} {r}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A library tint added without its global color to a document that has no swatch of the color's
|
||||
/// name brings the color along under its own name.
|
||||
#[test]
|
||||
|
||||
+181
-13
@@ -10,6 +10,25 @@ use vectorcraft_tools::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind
|
||||
|
||||
use crate::{EngineError, Prefs, Result, Session};
|
||||
|
||||
/// What a hover's lend decision holds for ([`Session::hover_tool_at`]).
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
pub(crate) struct HoverKey {
|
||||
/// The active document's uid and revision, which moves with the selection.
|
||||
doc: Option<(u64, u64)>,
|
||||
tool: &'static str,
|
||||
mods: Mods,
|
||||
/// The selection tool and the part selection tool chosen last.
|
||||
last_tools: (Option<&'static str>, Option<&'static str>),
|
||||
ctrl_click_selects_behind: bool,
|
||||
object_selection_by_path_only: bool,
|
||||
type_selection_by_path_only: bool,
|
||||
selection_tolerance: f64,
|
||||
anchor_size: u32,
|
||||
use_preview_bounds: bool,
|
||||
type_glyph_bounds: bool,
|
||||
show_handles_multiple_anchors: bool,
|
||||
}
|
||||
|
||||
/// The tool whose radius is General › Corner Radius.
|
||||
const ROUNDED_RECTANGLE: &str = "roundedRectangle";
|
||||
|
||||
@@ -183,6 +202,9 @@ impl Session {
|
||||
if self.tool.id() == id {
|
||||
return Ok(());
|
||||
}
|
||||
// A double-click or triple-click after the switch is the new tool's, also when the switch
|
||||
// comes back to the tool a Cmd press was lent from.
|
||||
self.press_lent = None;
|
||||
// Sampling type keeps its highlighted characters as the target, and a whole story that
|
||||
// Select All selected. Capture before the Type tool deactivates (which commits typing and
|
||||
// clears its editing state).
|
||||
@@ -208,6 +230,9 @@ impl Session {
|
||||
}
|
||||
if vectorcraft_tools::catalog::is_selection_tool(id) {
|
||||
self.last_selection_tool = Some(self.tool.id());
|
||||
if id != "selection" {
|
||||
self.last_part_selection_tool = Some(self.tool.id());
|
||||
}
|
||||
self.select_whole_instance(id);
|
||||
}
|
||||
Ok(())
|
||||
@@ -251,8 +276,10 @@ impl Session {
|
||||
/// selection tool from other tools (Alt on the lent Direct Selection gesture stays copy/subtract).
|
||||
/// Cmd alone lends Direct Selection the Selection tool, whose bounding box transforms the
|
||||
/// object (#3901; <https://community.adobe.com/t5/illustrator-discussions/handles-disappar-on-shape-with-direct-selection-tool/m-p/14848662>).
|
||||
/// Group Selection lends the Selection tool, and the Selection tool lends Direct Selection or
|
||||
/// Group Selection, whichever was chosen last (Direct Selection until one is).
|
||||
/// Perspective Selection keeps Cmd+Alt drags to copy objects on their perspective plane.
|
||||
/// None for the other selection tools and the view tools.
|
||||
/// None for the view tools.
|
||||
fn lent_tool(&self, id: &str, mods: &Mods) -> Option<&'static str> {
|
||||
use vectorcraft_tools::catalog::{edits_anchors, is_selection_tool};
|
||||
if matches!(id, "hand" | "zoom" | "rotateView") {
|
||||
@@ -261,6 +288,12 @@ impl Session {
|
||||
if id == "directSelection" && mods.cmd {
|
||||
return Some(if mods.alt { "groupSelection" } else { "selection" });
|
||||
}
|
||||
if id == "groupSelection" && mods.cmd {
|
||||
return Some("selection");
|
||||
}
|
||||
if id == "selection" && mods.cmd {
|
||||
return Some(self.last_part_selection_tool.unwrap_or("directSelection"));
|
||||
}
|
||||
if id == "perspectiveSelection" && mods.cmd && mods.alt {
|
||||
return None;
|
||||
}
|
||||
@@ -280,15 +313,118 @@ impl Session {
|
||||
self.lent_tool(self.tool.id(), mods)
|
||||
}
|
||||
|
||||
/// A press with Cmd held (Ctrl elsewhere) and any other tool than a selection tool: the
|
||||
/// selection tool [`Self::lent_tool`] takes the gesture, pressing without Cmd (a plain click,
|
||||
/// not Select Behind). The tool lent to stays as it was, unaware, until the release. → the event
|
||||
/// for the tool, and the warnings of a preview that keeping the typing applied.
|
||||
fn lend_selection_tool(&mut self, ev: &PointerEvent) -> Result<(PointerEvent, Vec<String>)> {
|
||||
if ev.kind != PointerKind::Down || !ev.mods.cmd || self.lender.is_some() {
|
||||
/// The tool the status bar and the help bar name with `mods` held: the selection tool Cmd
|
||||
/// lends ([`Self::lent_tool_id`]) while the button is up, Space does not lend a view tool and
|
||||
/// the active tool is not computing an edit, else the active tool. Over a selected object where
|
||||
/// a Cmd press selects behind, as the cursor last found it, it names the active tool.
|
||||
pub fn shown_tool_id(&self, mods: &Mods) -> &'static str {
|
||||
match self.hovered_lent(mods) {
|
||||
Some(id) if !mods.space && !self.tool_editing() && !self.pointer_held => id,
|
||||
_ => self.tool.id(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The tool whose marks the canvas shows with `mods` held: the selection tool a Cmd press at
|
||||
/// the pointer would borrow, as [`Self::hover_tool_at`] or [`Self::cursor`] last found it
|
||||
/// (before either has, the one [`Self::lent_tool_id`] names), else the active tool. The canvas
|
||||
/// asks this while the view moves, when it does not hit-test the art under the pointer.
|
||||
pub fn hover_tool_id(&self, mods: &Mods) -> &'static str {
|
||||
match self.hovered_lent(mods) {
|
||||
Some(id) if mods.cmd && !mods.space && self.lender.is_none() && !self.tool_editing() && !self.pointer_held => id,
|
||||
_ => self.tool.id(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The selection tool a Cmd press with `mods` would borrow at the pointer: the one
|
||||
/// [`Self::hover_tool_at`] or [`Self::cursor`] last found, while the document, the selection,
|
||||
/// the active tool and the keys are as they were then (none where the press selects behind),
|
||||
/// else the one [`Self::lent_tool_id`] names.
|
||||
fn hovered_lent(&self, mods: &Mods) -> Option<&'static str> {
|
||||
match self.hover_lent {
|
||||
Some((key, lent)) if key == self.hover_key(mods) => lent,
|
||||
_ => self.lent_tool_id(mods),
|
||||
}
|
||||
}
|
||||
|
||||
/// What a hover's lend decision holds for: the active document's state (its uid and revision,
|
||||
/// which moves with the selection), the active tool, the keys, the selection tools chosen last
|
||||
/// and the preferences a press's hit test reads.
|
||||
fn hover_key(&self, mods: &Mods) -> HoverKey {
|
||||
let p = &self.prefs;
|
||||
HoverKey {
|
||||
doc: self.active().map(|d| (d.uid, d.revision)),
|
||||
tool: self.tool.id(),
|
||||
mods: *mods,
|
||||
last_tools: (self.last_selection_tool, self.last_part_selection_tool),
|
||||
ctrl_click_selects_behind: p.ctrl_click_selects_behind,
|
||||
object_selection_by_path_only: p.object_selection_by_path_only,
|
||||
type_selection_by_path_only: p.type_selection_by_path_only,
|
||||
selection_tolerance: p.selection_tolerance,
|
||||
anchor_size: p.anchor_size,
|
||||
use_preview_bounds: p.use_preview_bounds,
|
||||
type_glyph_bounds: p.type_glyph_bounds,
|
||||
show_handles_multiple_anchors: p.show_handles_multiple_anchors,
|
||||
}
|
||||
}
|
||||
|
||||
/// The tool whose marks and widgets the canvas draws this frame with `mods` held and the
|
||||
/// pointer at `p` (None off the canvas): the selection tool a Cmd press there would borrow
|
||||
/// ([`Self::lent_tool_at`]; off the canvas, the one [`Self::lent_tool_id`] names), else the
|
||||
/// active tool. [`Self::hover_tool_id`] then answers the same until the pointer or the keys move.
|
||||
pub fn hover_tool_at(&mut self, p: Option<Point>, mods: &Mods, view: ViewInfo) -> &'static str {
|
||||
let lends = mods.cmd && !mods.space && self.lender.is_none() && !self.tool_editing() && !self.pointer_held;
|
||||
let lent = match p {
|
||||
_ if !lends => None,
|
||||
Some(p) => self.lent_tool_at(p, mods, view),
|
||||
None => self.lent_tool_id(mods),
|
||||
};
|
||||
let key = self.hover_key(mods);
|
||||
self.hover_lent = lends.then_some((key, lent));
|
||||
lent.unwrap_or(self.tool.id())
|
||||
}
|
||||
|
||||
/// The selection tool a press at `p` with `mods` borrows ([`Self::lent_tool`]): none when
|
||||
/// the Selection tool keeps a Cmd press on a selected object to select the object behind it
|
||||
/// (Selection & Anchor Display › Command Click to Select Objects Behind).
|
||||
fn lent_tool_at(&mut self, p: Point, mods: &Mods, view: ViewInfo) -> Option<&'static str> {
|
||||
let id = self.lent_tool(self.tool.id(), mods)?;
|
||||
let behind = self.tool.id() == "selection" && self.with_tool_cx(view, |_, cx| vectorcraft_tools::select::selects_behind_at(cx, p));
|
||||
(!behind).then_some(id)
|
||||
}
|
||||
|
||||
/// Is the press `ev` lent a selection tool ([`Self::lend_selection_tool`])? The frontend asks
|
||||
/// before the press, to tell a gesture of the tool in hand from one of a lent tool.
|
||||
pub fn press_lends_tool(&mut self, ev: &PointerEvent, view: ViewInfo) -> bool {
|
||||
ev.kind == PointerKind::Down && ev.mods.cmd && self.lender.is_none() && self.lent_tool_at(ev.pos, &ev.mods, view).is_some()
|
||||
}
|
||||
|
||||
/// A press with Cmd held (Ctrl elsewhere): the selection tool [`Self::lent_tool_at`] names
|
||||
/// takes the gesture, pressing without Cmd (a plain click, not Select Behind). The tool lent to
|
||||
/// stays as it was, unaware, until the release. With a selection tool active, the double-click
|
||||
/// or triple-click that follows Cmd-clicks goes to the tool the clicks went to, with Cmd kept
|
||||
/// (Cmd+Shift releases a guide), and that tool is given back after it. → the event for the tool,
|
||||
/// and the warnings of a preview that keeping the typing applied.
|
||||
fn lend_selection_tool(&mut self, ev: &PointerEvent, view: ViewInfo) -> Result<(PointerEvent, Vec<String>)> {
|
||||
let follow_up =
|
||||
matches!(ev.kind, PointerKind::DoubleClick | PointerKind::TripleClick) && vectorcraft_tools::catalog::is_selection_tool(self.tool.id());
|
||||
if ev.kind == PointerKind::Down {
|
||||
self.press_lent = None;
|
||||
}
|
||||
if (ev.kind != PointerKind::Down && !follow_up) || !ev.mods.cmd || self.lender.is_some() {
|
||||
return Ok((*ev, vec![]));
|
||||
}
|
||||
let Some(id) = self.lent_tool(self.tool.id(), &ev.mods) else { return Ok((*ev, vec![])) };
|
||||
// A follow-up goes where the press before it went, whatever that press selected, while the
|
||||
// document and the active tool are the ones that press found.
|
||||
let at = (self.active().map(|d| d.uid), self.tool.id());
|
||||
let id = if follow_up {
|
||||
self.press_lent.filter(|(doc, tool, _)| (*doc, *tool) == at).map(|(.., id)| id)
|
||||
} else {
|
||||
self.lent_tool_at(ev.pos, &ev.mods, view)
|
||||
};
|
||||
let Some(id) = id else { return Ok((*ev, vec![])) };
|
||||
if !follow_up {
|
||||
self.press_lent = Some((at.0, at.1, id));
|
||||
}
|
||||
// Typing in progress is kept as its own step first: the lent tool's drag previews from the
|
||||
// document its interaction started from, which would drop the typing (#1881). When it
|
||||
// can't be kept, the press is not lent.
|
||||
@@ -316,7 +452,8 @@ impl Session {
|
||||
}
|
||||
self.selection_at_lend = self.active().map(|d| (d.uid, d.selection.clone()));
|
||||
self.lender = Some(std::mem::replace(&mut self.tool, lent));
|
||||
Ok((PointerEvent { mods: Mods { cmd: false, ..ev.mods }, ..*ev }, settled))
|
||||
let cmd = follow_up && ev.mods.cmd;
|
||||
Ok((PointerEvent { mods: Mods { cmd, ..ev.mods }, ..*ev }, settled))
|
||||
}
|
||||
|
||||
/// The lent selection tool's gesture is over: the tool it was lent to is back as it was (the
|
||||
@@ -341,6 +478,9 @@ impl Session {
|
||||
self.back_to_bucket = outer_bucket;
|
||||
self.keep_tool_settings();
|
||||
self.tool = lender;
|
||||
// Back with the Selection or Group Selection tool, a symbol part the lent Direct
|
||||
// Selection picked gives way to its instance, as choosing the tool does.
|
||||
self.select_whole_instance(self.tool.id());
|
||||
if let Some(points) = mesh_points {
|
||||
self.tool.set_option("meshPoints", &points);
|
||||
}
|
||||
@@ -478,6 +618,7 @@ impl Session {
|
||||
path_only: self.prefs.object_selection_by_path_only,
|
||||
type_path_only: self.prefs.type_selection_by_path_only,
|
||||
double_click_isolate: self.prefs.double_click_to_isolate,
|
||||
double_click_adds_anchor: self.prefs.double_click_adds_anchor_points,
|
||||
select_behind: self.prefs.ctrl_click_selects_behind,
|
||||
highlight_anchors: self.prefs.highlight_anchors_on_hover,
|
||||
snap_tolerance: self.prefs.snap_to_point_tolerance,
|
||||
@@ -771,7 +912,7 @@ impl Session {
|
||||
}
|
||||
self.leave_draw_inside(ev, view)?;
|
||||
self.tell_tool_history_moved();
|
||||
let (ev, settled) = self.lend_selection_tool(ev)?;
|
||||
let (ev, settled) = self.lend_selection_tool(ev, view)?;
|
||||
let ev = &ev;
|
||||
let lent = self.lender.is_some();
|
||||
let mut acts = self.with_tool_cx(view, |t, cx| t.pointer(cx, ev));
|
||||
@@ -795,7 +936,7 @@ impl Session {
|
||||
PointerKind::Up => self.press_point = None,
|
||||
_ => {}
|
||||
}
|
||||
if ev.kind == PointerKind::Up {
|
||||
if ev.kind == PointerKind::Up || (lent && matches!(ev.kind, PointerKind::DoubleClick | PointerKind::TripleClick)) {
|
||||
self.give_back_tool(view)?;
|
||||
}
|
||||
r
|
||||
@@ -1305,7 +1446,11 @@ impl Session {
|
||||
/// press would borrow ([`Self::lend_selection_tool`]).
|
||||
pub fn cursor(&mut self, p: Point, mods: Mods, view: ViewInfo) -> Cursor {
|
||||
// While an edit is computed, a Cmd press is held for the active tool, which shows it is busy.
|
||||
let lent = if mods.cmd && self.lender.is_none() && !self.tool_editing() { self.lent_tool(self.tool.id(), &mods) } else { None };
|
||||
// Cmd pressed once a drag is under way lends nothing, so the tool keeps its pointer.
|
||||
let lends = mods.cmd && self.lender.is_none() && !self.tool_editing() && !self.pointer_held;
|
||||
let lent = if lends { self.lent_tool_at(p, &mods, view) } else { None };
|
||||
let key = self.hover_key(&mods);
|
||||
self.hover_lent = lends.then_some((key, lent));
|
||||
match lent {
|
||||
Some(id) => {
|
||||
let lent = self.make_tool(id);
|
||||
@@ -1318,6 +1463,16 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
/// The object a click of the active tool at `p` with `mods` would act on
|
||||
/// ([`vectorcraft_tools::Tool::hover_object`]), for Smart Guides › Object Highlighting. None
|
||||
/// while Cmd lends a selection tool to the press ([`Self::lent_tool_at`]).
|
||||
pub fn hover_object(&mut self, p: Point, mods: Mods, view: ViewInfo) -> Option<NodeId> {
|
||||
if mods.cmd && self.lender.is_none() && !self.tool_editing() && self.lent_tool_at(p, &mods, view).is_some() {
|
||||
return None;
|
||||
}
|
||||
self.with_tool_cx(view, |t, cx| t.hover_object(cx, p, mods))
|
||||
}
|
||||
|
||||
pub fn tool_options(&self) -> Value {
|
||||
self.tool.options()
|
||||
}
|
||||
@@ -1583,6 +1738,10 @@ impl Session {
|
||||
|
||||
/// Apply tool actions. Errors from previews are reported but keep the interaction alive.
|
||||
pub fn apply_actions(&mut self, acts: Vec<Action>) -> Result<Vec<UiRequest>> {
|
||||
// The tool acts on its own interaction, which a command from outside it may have set aside.
|
||||
if !acts.is_empty() {
|
||||
self.put_back_interaction();
|
||||
}
|
||||
let outer = std::mem::replace(&mut self.in_tool_actions, true);
|
||||
let outer_bucket = self.back_to_bucket;
|
||||
// The Eyedropper's sample into a stop of the Live Paint Bucket's gradient, which switches back to the bucket.
|
||||
@@ -1608,7 +1767,16 @@ impl Session {
|
||||
let mut ui = vec![];
|
||||
for a in acts {
|
||||
match a {
|
||||
Action::Begin(label) => self.begin_interaction(&label)?,
|
||||
Action::Begin(label) => {
|
||||
// The snapshot of the interaction open before, which the tool's drag then joins.
|
||||
let open = self.active().and_then(|st| st.interaction.as_ref()).map(|it| std::sync::Arc::as_ptr(&it.doc));
|
||||
self.begin_interaction(&label)?;
|
||||
if let Some(it) = self.active_mut().and_then(|st| st.interaction.as_mut())
|
||||
&& open != Some(std::sync::Arc::as_ptr(&it.doc))
|
||||
{
|
||||
it.tool = true;
|
||||
}
|
||||
}
|
||||
Action::Preview(cmd, p) => {
|
||||
// Performance › Real-time Drawing and Editing (#394): off, remember the latest
|
||||
// params and apply them once on Commit instead of every move. A ruler guide
|
||||
|
||||
Reference in new issue
Block a user