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
@@ -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()
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user