Merge feat/scripts-api-d1a-app-documents into feat/scripts-api-d4b-text-styles

This commit is contained in:
dotCooCoo committed 2026-11-25 04:53:10 -08:00
commit 771383bed8
1307 files changed
+194081 -268410

No files matched your search

+9 -3
View File
@@ -94,6 +94,7 @@ pub(crate) mod slices;
pub mod spelling;
mod stroke;
mod style;
pub use style::styled_node;
pub mod stylelib;
mod svgfilter;
mod swatch;
@@ -845,19 +846,24 @@ pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000;
pub(crate) use addons::{DecodedImages, refresh_color_masks};
/// Packaging Tools' blanks and the objects their print leaves out, for the Fold Preview window.
pub use addons::{fold_source, print_hidden};
/// Document Info's category titles and the Objects category's count labels.
pub use docinfo::{CATEGORIES, OBJECT_LABELS};
/// Document Info's category titles, the Objects category's count labels, and how its image rows
/// write a resolution and a number of bytes.
pub use docinfo::{CATEGORIES, OBJECT_LABELS, byte_size, ppi_number};
pub use docmenu::guide_indexes;
pub(crate) use edit::{Unrecorded, settle_interaction, typing_in_progress};
pub(crate) use object::bounds_rewrite;
pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned};
/// The rules `object.scale`, `object.reflect` and `object.shear` check their params with.
pub use object::{reflect_axis, scale_factors, shear_tangent};
pub(crate) use paint::LIVE_PAINT_BUCKET;
pub(crate) use paint::{LIVE_PAINT_BUCKET, asks_defaults_only};
pub use plugin_call::{Location, ParamsPlace, key_location, location_in, location_keys};
pub use select::SIMILAR;
pub(crate) use vectorcraft_doc::range::parse_range;
/// What the fill and stroke proxies read from the selected objects, kept with the selection
/// ([`crate::doc_state::SelectionRecord`]).
pub(crate) use paint::SelectionPaints;
/// A date param in Unix seconds that defaults to the clock: `None` when absent (now, see
/// [`clock_date`]), `Some(None)` for null (no date), else `Some(Some(seconds))`.
pub(crate) fn date_param(p: &Value, key: &str, cmd: &str) -> Result<Option<Option<i64>>> {
+1 -1
View File
@@ -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 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,26 +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(|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
@@ -154,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)]);
@@ -409,7 +409,8 @@ fn a_mask_that_hides_nothing_keeps_the_link() {
#[test]
fn color_mask_refuses_previews_and_images_too_large() {
let preview = std::sync::Arc::new(framed());
let (mut s, id) = linked("missing", ImageBlob { mime: "image/png".into(), bytes: preview.clone(), proxy: Some(preview) });
let (mut s, id) =
linked("missing", ImageBlob { mime: "image/png".into(), bytes: preview.clone(), proxy: Some(preview), file_font: Default::default() });
let e = s.execute(COLOR_MASK, &hide_white()).unwrap_err().to_string();
assert!(e.contains(COLOR_MASK) && e.contains("the linked image shows its preview: embed or relink it first"), "{e}");
assert_eq!(mask_of(doc(&s), id), None);
+6 -1
View File
@@ -525,7 +525,12 @@ fn a_linked_image_is_embedded_and_one_that_shows_its_preview_is_refused() {
assert_eq!(im.placement, clip, "its Placement Options kept, as Embed keeps them");
// Pixels the file wasn't read for: the preview, as an image whose file is missing shows it.
let preview = Arc::new(bytes);
let missing = place_linked(&mut s, "missing", ImageBlob { mime: "image/png".into(), bytes: preview.clone(), proxy: Some(preview) }, (12, 10));
let missing = place_linked(
&mut s,
"missing",
ImageBlob { mime: "image/png".into(), bytes: preview.clone(), proxy: Some(preview), file_font: Default::default() },
(12, 10),
);
let before = (image_of(&s, missing), undo_len(&s));
let e = s.execute(C, &json!({})).unwrap_err();
assert!(e.to_string().contains("the linked image shows its preview: embed or relink it first"), "{e}");
+4 -2
View File
@@ -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");
}
}
+24 -18
View File
@@ -398,15 +398,6 @@ pub(crate) fn aligned(p: &Value, cmd: &str) -> Result<bool> {
switch_or(p, "aligned", false, cmd)
}
/// What the appearances of `ids` share, when there are several of them and they all exist.
pub(crate) fn shared_stack(d: &vectorcraft_doc::Document, ids: &[NodeId]) -> Option<SharedStack> {
if ids.len() < 2 {
return None;
}
let aps: Vec<&Appearance> = ids.iter().map(|id| d.node(*id).map(|n| &*n.appearance)).collect::<Option<_>>()?;
Some(SharedStack::of(&aps))
}
/// Do the appearances of `ids` differ (several objects whose stacks aren't all equal)?
pub(crate) fn appearances_differ(d: &vectorcraft_doc::Document, ids: &[NodeId]) -> bool {
let mut aps = ids.iter().filter_map(|id| d.node(*id)).map(|n| &n.appearance);
@@ -1207,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();
@@ -1530,19 +1539,16 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result<Value> {
let mut first_at = None;
let active = s.active_appearance_item.as_ref().and_then(|a| a.objects.first().copied());
let mut active_at = None;
// Aligned rows of a mixed selection are copied right above themselves in each object. Rows of a graph design's art,
// which is left out, go to `to` in an object whose stack is the same as the art's.
// Aligned rows of a mixed selection are copied right above themselves in each object. Aligned rows of objects whose
// stacks are the same, and rows of a graph design's art, which is left out, go to `to` as in one stack.
let of = design_reference(s, p, C)?;
if aligned(p, C)?
&& to.is_some()
&& (shared_stack(&s.doc()?.doc, &ids).is_some() || (of.is_some() && appearances_differ(&s.doc()?.doc, &with_reference(of, &ids))))
{
if aligned(p, C)? && to.is_some() && appearances_differ(&s.doc()?.doc, &with_reference(of, &ids)) {
return Err(bad(C, "`to` takes the rows of one object's stack, not aligned rows"));
}
let before = s.doc()?.doc.clone();
// With `to`, the art's stack is the same as the object's, so its rows are the object's, each of which must exist.
let per =
if to.is_some() { items_per_target(&before, &ids, &idx, aligned(p, C)?) } else { rows_per_target(&before, of, &ids, &idx, aligned(p, C)?) };
// With `to`, aligned rows are rows of stacks that are all the same (the art's too), so each target takes the same
// indices, each of which must exist.
let per = if to.is_some() { vec![idx.clone(); ids.len()] } else { rows_per_target(&before, of, &ids, &idx, aligned(p, C)?) };
s.edit("Duplicate Item", |d, _| {
let mut any = false;
// Copies that became the topmost visible row of their kind: the series stores their paint even when the object
+1 -1
View File
@@ -135,7 +135,7 @@ impl Session {
/// Whether `name` is a built-in preset's, "Custom" (changed settings, as the panel and a traced
/// object show them), or a saved preset's other than the one at `except`.
fn trace_preset_taken(&self, name: &str, except: Option<usize>) -> bool {
pub fn trace_preset_taken(&self, name: &str, except: Option<usize>) -> bool {
tr::preset(name).is_some() || name.trim().eq_ignore_ascii_case("Custom") || self.trace_preset_index(name).is_some_and(|i| Some(i) != except)
}
+129 -19
View File
@@ -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,
@@ -159,6 +160,10 @@ fn node_refs(n: &Node, f: Visit) {
for s in t.para_styles().filter_map(|pa| pa.style_name.as_ref()) {
f(Ref::Name(Res::ParaStyle, s));
}
// The fonts its file carried travel with it, as images do.
for ff in t.file_fonts.iter().flat_map(|ff| &ff.fonts) {
f(Ref::Name(Res::Image, &ff.key));
}
}
NodeKind::Image(im) => f(Ref::Name(Res::Image, &im.key)),
NodeKind::PlacedDocument(pl) => f(Ref::Name(Res::Image, &pl.key)),
@@ -606,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 {
@@ -617,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)
@@ -807,6 +821,9 @@ impl Relink {
if relaid {
refresh_bounds(t);
}
if let Some(fonts) = &mut t.file_fonts {
fonts.map_keys(|key| self.name(Res::Image, key));
}
}
NodeKind::Image(im) => self.name(Res::Image, &mut im.key),
NodeKind::PlacedDocument(pl) => self.name(Res::Image, &mut pl.key),
@@ -1134,6 +1151,8 @@ pub(crate) struct Imported {
/// `{kind, from, to}` for every resource the pasted objects now know under another name: added
/// renamed, or a copy added renamed by an earlier paste.
pub renamed: Vec<Value>,
/// File-font resources refused while binding pasted type.
pub warnings: Vec<String>,
/// The graph designs the pasted graphs draw with that the document has under the same name
/// and that would draw them otherwise than the art they were pasted with: the document keeps
/// its own, and the pasted graphs are drawn again with it.
@@ -1145,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 {
@@ -1158,13 +1180,18 @@ impl Imported {
}
}
/// Point a pasted copy at the document's resources. A pie's legend labels in wedges that now show a color of the
/// other darkness take the contrast a redraw sets there.
pub(crate) fn apply(&self, n: &mut Node) {
/// other darkness take the contrast a redraw sets there. Fonts the copy carries are bound to the faces `d` holds.
pub(crate) fn apply(&mut self, n: &mut Node, d: &Document) {
if self.relinks {
let shades = super::super::graph::wedge_shades(n);
self.relink.node(n);
super::super::graph::follow_wedge_shades(n, &shades);
}
for note in vectorcraft_text::FontDb::global().bind_node_file_fonts(n, &|key| d.images.get(key)) {
if !self.warnings.contains(&note) {
self.warnings.push(note);
}
}
}
}
@@ -1411,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));
@@ -1462,6 +1519,7 @@ impl Clipboard {
&& out.relink.colors.is_empty()
&& out.relink.kinsoku.is_empty()
&& used.styles.is_empty());
out.warnings.extend(vectorcraft_text::FontDb::global().bind_document_file_fonts(d));
Ok(out)
}
@@ -1645,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);
}
@@ -1660,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);
}
}
@@ -1862,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)
}
+4 -4
View File
@@ -13,7 +13,7 @@ use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_color::cms::Model;
use vectorcraft_color::harmony::{Guide, GuideOptions, Harmony, Variation};
use vectorcraft_color::harmony::{self, Guide, GuideOptions, Harmony};
use vectorcraft_color::{Color, Paint, keep_model};
use vectorcraft_doc::live::lerp_color;
use vectorcraft_doc::pattern::PatternDef;
@@ -962,8 +962,8 @@ fn harmony(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "color.harmony";
let base = p.get("color").and_then(color_value).ok_or_else(|| bad(C, "missing or invalid `color`"))?;
let rule = text_param(p, "rule", C)?.ok_or_else(|| bad(C, "missing `rule`"))?;
let rule = Harmony::parse(rule).ok_or_else(|| {
let ids: Vec<String> = Harmony::ALL.iter().map(|h| h.id()).collect();
let rule = harmony::parse(rule).ok_or_else(|| {
let ids: Vec<&str> = Harmony::ALL.iter().map(|h| h.id()).collect();
bad(C, format!("unknown rule `{rule}` ({})", ids.join("|")))
})?;
check_numbers(p, &["steps", "amount"], C)?;
@@ -972,7 +972,7 @@ fn harmony(s: &mut Session, p: &Value) -> Result<Value> {
opts.steps = n.min(u32::MAX as u64) as u32;
}
if let Some(v) = text_param(p, "variation", C)? {
opts.variation = Variation::parse(v).ok_or_else(|| bad(C, format!("unknown variation `{v}` (tintsShades|warmCool|vividMuted)")))?;
opts.variation = harmony::parse_variation(v).ok_or_else(|| bad(C, format!("unknown variation `{v}` (tintsShades|warmCool|vividMuted)")))?;
}
if let Some(a) = p.get("amount").and_then(Value::as_f64) {
opts.amount = a as f32;
+1 -1
View File
@@ -169,7 +169,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Overprint Black…",
["Edit", "Edit Colors"],
None,
"{remove?: false, percentage?: 100, fill?: true, stroke?: true, includeCmyBlacks?: false, includeSpotBlacks?: false, ids?} make the black fills and/or strokes of the selection (or ids; groups: their contents; type: its characters) overprint, or stop (remove). Black: K ≥ percentage with no C, M or Y (any with includeCmyBlacks), not linked to a spot swatch (unless includeSpotBlacks); a gradient is black when every stop is → {changed: objects}",
"{remove?: false, percentage?: 100, fill?: true, stroke?: true, includeCmyBlacks?: false, includeSpotBlacks?: false, ids?} make the black fills and/or strokes of the selection (or ids; groups: their contents; type: its characters; a grayscale or 1-bit image colorized by paint.setFill: its color, as a fill) overprint, or stop (remove). Black: K ≥ percentage with no C, M or Y (any with includeCmyBlacks), not linked to a spot swatch (unless includeSpotBlacks); a gradient is black when every stop is → {changed: objects}",
has_doc,
super::overprint::overprint_black
),
@@ -26,6 +26,7 @@ pub const MAX_FILE: usize = 64 << 10;
/// The most setups `view.proofSetup.list` lists.
pub const MAX_LISTED: usize = 100;
/// The most folder entries `view.proofSetup.list` looks at, setup files or not.
#[cfg(not(target_arch = "wasm32"))]
const MAX_SCANNED: usize = 100_000;
/// The longest `name`, in characters.
const MAX_NAME: usize = 100;
+4 -4
View File
@@ -5,7 +5,7 @@
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use vectorcraft_color::Color;
use vectorcraft_color::harmony::{Harmony, THEME_SIZE};
use vectorcraft_color::harmony::{self, THEME_SIZE};
use vectorcraft_color::recolor::ColorKey;
use vectorcraft_tools::params::color_json;
@@ -98,7 +98,7 @@ fn next_name(s: &Session) -> String {
fn save(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "colorTheme.save";
let rule = match str_param(p, "rule") {
Some(r) => Some(Harmony::parse(r).ok_or_else(|| bad(C, format!("unknown rule `{r}` (see color.harmony)")))?),
Some(r) => Some(harmony::parse(r).ok_or_else(|| bad(C, format!("unknown rule `{r}` (see color.harmony)")))?),
None => None,
};
let colors: Vec<Color> = match (p.get("colors"), p.get("color")) {
@@ -107,7 +107,7 @@ fn save(s: &mut Session, p: &Value) -> Result<Value> {
}
(None, Some(c)) => {
let base = color_value(c).ok_or_else(|| bad(C, "invalid `color`"))?;
rule.ok_or_else(|| bad(C, "`color` needs a `rule` to make the theme from"))?.theme(base)
harmony::theme(rule.ok_or_else(|| bad(C, "`color` needs a `rule` to make the theme from"))?, base)
}
_ => return Err(bad(C, "give `colors`, or `color` and `rule`")),
};
@@ -123,7 +123,7 @@ fn save(s: &mut Session, p: &Value) -> Result<Value> {
if s.prefs.color_themes.iter().enumerate().any(|(i, t)| Some(i) != replace && t.name.eq_ignore_ascii_case(&name)) {
return Err(bad(C, format!("a theme is already called {name} (replace: \"{name}\" overwrites it)")));
}
let theme = ColorTheme { name: name.clone(), colors, rule: rule.map(Harmony::id) };
let theme = ColorTheme { name: name.clone(), colors, rule: rule.map(|h| h.id().to_owned()) };
match replace {
Some(i) => s.prefs.color_themes[i] = theme,
None => s.prefs.color_themes.push(theme),
+20 -9
View File
@@ -23,6 +23,9 @@ use super::{CommandSpec, Result, Session, bad, cmd, has_doc, switch_or, text_par
/// The extension of the files Export writes and Import reads.
pub const EXTS: &[&str] = &["vccomposite"];
/// The id of the export command.
const EXPORT: &str = "type.compositeFonts.export";
/// The largest file Import reads, in bytes.
const MAX_FILE_BYTES: usize = 4 << 20;
@@ -271,7 +274,7 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
}
fn export(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "type.compositeFonts.export";
const C: &str = EXPORT;
let path = text_param(p, "path", C)?;
if path.is_some_and(|p| p.trim().is_empty()) {
return Err(bad(C, "path is empty"));
@@ -306,21 +309,29 @@ fn export(s: &mut Session, p: &Value) -> Result<Value> {
if fonts.is_empty() {
return Err(bad(C, "no composite fonts to export"));
}
let mut file = Map::new();
file.insert("compositeFonts".into(), json!(fonts));
let text = serde_json::to_string_pretty(&file).map_err(|e| bad(C, e.to_string()))?;
if text.len() > MAX_FILE_BYTES {
return Err(bad(C, "the composite fonts make a file larger than 4 MB, which Import can't read; export fewer of them"));
}
let bytes = file_bytes(&fonts)?;
match path {
Some(path) => {
write_file(path, text.as_bytes())?;
write_file(path, &bytes)?;
Ok(json!({ "path": path, "count": fonts.len() }))
}
None => Ok(json!({ "data": text, "count": fonts.len() })),
// The bytes are UTF-8 JSON text, so the lossy conversion changes nothing.
None => Ok(json!({ "data": String::from_utf8_lossy(&bytes), "count": fonts.len() })),
}
}
/// The bytes of an export file holding `fonts`: what [`import`] reads. Refused when they would make a
/// file larger than Import reads.
pub fn file_bytes(fonts: &[CompositeFont]) -> Result<Vec<u8>> {
let mut file = Map::new();
file.insert("compositeFonts".into(), json!(fonts));
let text = serde_json::to_string_pretty(&file).map_err(|e| bad(EXPORT, e.to_string()))?;
if text.len() > MAX_FILE_BYTES {
return Err(bad(EXPORT, "the composite fonts make a file larger than 4 MB, which Import can't read; export fewer of them"));
}
Ok(text.into_bytes())
}
/// The composite fonts in the bytes of an exported file.
fn read_fonts(bytes: &[u8], c: &str) -> Result<Vec<CompositeFont>> {
let v: Value = serde_json::from_slice(bytes).map_err(|e| bad(c, format!("not a composite fonts file: {e}")))?;
+1 -1
View File
@@ -55,7 +55,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Flare",
[],
None,
"{cx, cy, diameter=100, opacity=50 (%), brightness=30 (%), growth=20 (%), fuzziness=50 (%), rays=15, longest=300 (%), rayFuzziness=100 (%), rotation=0 (deg, turns the rays clockwise), x2?, y2? (ring end; else pathLength at direction), pathLength=300, rings=10, largest=50 (%), direction=45 (deg counter-clockwise from 3 o'clock: where the rings run from the centre), seed?, ringSeed? (whole number below 2^53: deterministically places every ring along the path, including the first for small seed values, keeping their count and sizes)} → {id}",
"{cx, cy, diameter=100, opacity=50 (%), brightness=30 (%), growth=20 (%), fuzziness=50 (%), rays=15, longest=300 (%), rayFuzziness=100 (%), rotation=0 (deg, turns the rays clockwise), x2?, y2? (ring end, both or neither: one alone is an error; else pathLength at direction), pathLength=300, rings=10, largest=50 (%), direction=45 (deg counter-clockwise from 3 o'clock: where the rings run from the centre), seed?, ringSeed? (whole number below 2^53: deterministically places every ring along the path, including the first for small seed values, keeping their count and sizes)} → {id}",
has_doc,
super::flare::flare
),
+27 -6
View File
@@ -14,7 +14,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Create Dimension",
[],
None,
"{mode?: linear|angular|radius|diameter, a?: [x,y], b?: [x,y], vertex?: [x,y], source?: {kind: segment, edge: {node,subpath,segment}}|{kind: angle, first: edge, second: edge}|{kind: circle, node}|{kind: arc, edge}|{kind: points, a?, b?, vertex?: {node,subpath,anchor}, freeA?, freeB?: a point that is not an anchor, {kind: onSegment, edge: {node,subpath,segment}, t: 0..1 (curve parameter)}|{kind: anchors, node, anchors: [{subpath,anchor,part?: point|in|out (the anchor, default, or its in or out handle),weight}] (2 or 3 points of one path whose weights add up to 1), across?: (2 anchors only: times the first-to-second anchor vector (x,y) turned to (-y,x), which points down when the vector points right)} (an end is an anchor or a free point, not both)}, orientation?: aligned|horizontal|vertical (linear only: the distance between the points, or only its horizontal or vertical part; default aligned), offset?: pt (the line's distance from the first point: along the left normal of a → b when aligned, downward when horizontal, leftward when vertical; negative goes the other way), options?: {units: in|mm|pt|pc|px|cm|m|ft|yd, precision: 0-6, scale: drawing:real, hideUnits, lineWeight, lineType: solid|dashed|dotted, lineColor: [r,g,b], arrowStyle: filled|open|tick|none, arrowHead: null|a built-in stroke.set arrowhead name (Barbed, LineArrow…; drawn at both ends in place of arrowStyle's head; versions that have the stroke arrowhead but do not read arrowHead draw arrowStyle when they draw the dimension again; custom arrowheads are refused), arrowScale: %, extensionWeight, extensionType, extensionColor, extensionOffset, extensionLength, hideExtensions, fontFamily, fontStyle, fontSize, textColor, textPosition: away|between, textAlignment: left|center|right, textOffset}} → {id,label}; linked measurements follow source edits",
"{mode?: linear|angular|radius|diameter, a?: [x,y], b?: [x,y], vertex?: [x,y], source?: {kind: segment, edge: {node,subpath,segment}}|{kind: angle, first: edge, second: edge}|{kind: circle, node}|{kind: arc, edge}|{kind: extent, node} (linear only: a whole path between its outermost points, leftmost and rightmost when horizontal or aligned, topmost and bottommost when vertical)|{kind: points, a?, b?, vertex?: {node,subpath,anchor}, freeA?, freeB?: a point that is not an anchor, {kind: onSegment, edge: {node,subpath,segment}, t: 0..1 (curve parameter)}|{kind: anchors, node, anchors: [{subpath,anchor,part?: point|in|out (the anchor, default, or its in or out handle),weight}] (2 or 3 points of one path whose weights add up to 1), across?: (2 anchors only: times the first-to-second anchor vector (x,y) turned to (-y,x), which points down when the vector points right)} (an end is an anchor or a free point, not both)}, orientation?: aligned|horizontal|vertical (linear only: the distance between the points, or only its horizontal or vertical part; default aligned), offset?: pt (the line's distance from the first point: along the left normal of a → b when aligned, downward when horizontal, leftward when vertical; negative goes the other way), options?: {units: in|mm|pt|pc|px|cm|m|ft|yd, precision: 0-6, scale: drawing:real, hideUnits, lineWeight, lineType: solid|dashed|dotted, lineColor: [r,g,b], arrowStyle: filled|open|tick|none, arrowHead: null|a built-in stroke.set arrowhead name (Barbed, LineArrow…; drawn at both ends in place of arrowStyle's head; versions that have the stroke arrowhead but do not read arrowHead draw arrowStyle when they draw the dimension again; custom arrowheads are refused), arrowScale: %, extensionWeight, extensionType, extensionColor, extensionOffset, extensionLength, hideExtensions, fontFamily, fontStyle, fontSize, textColor, textPosition: away|between, textAlignment: left|center|right, textOffset}} → {id,label}; linked measurements follow source edits",
has_doc,
create
),
@@ -23,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Update Dimensions",
[],
None,
"{ids?: [dimension ids] (default selection), options?: dimension options, orientation?: aligned|horizontal|vertical (linear dimensions only; the line stays on the side of the points it was on), offset?: pt (as in dimension.create)} restyle, turn or move existing dimensions → {ids}",
"{ids?: [dimension ids] (default selection), options?: dimension options, orientation?: aligned|horizontal|vertical (linear dimensions only; the line stays on the side of the points it was on; for an extent source, an error when that would put the line more than 1,000,000 pt from its first point and no offset is given), offset?: pt (as in dimension.create), at?: [x,y] (after offset: puts a linear dimension's line through this point, gives an angular dimension's arc a radius of the point's distance from the vertex, at least 12 pt, or turns a radius or diameter line toward it; what the dimension measures does not change)} restyle, turn or move existing dimensions → {ids}",
has_doc,
update
),
@@ -80,6 +80,7 @@ fn recipe(s: &Session, p: &Value) -> Result<Dimension> {
| (DimensionMode::Angular, DimensionSource::Angle { .. })
| (DimensionMode::Radius | DimensionMode::Diameter, DimensionSource::Circle { .. } | DimensionSource::Arc { .. })
| (DimensionMode::Linear | DimensionMode::Angular, DimensionSource::Points { .. })
| (DimensionMode::Linear, DimensionSource::Extent { .. })
);
if !compatible {
return Err(error("Dimension mode does not match its source"));
@@ -159,6 +160,7 @@ fn update(s: &mut Session, p: &Value) -> Result<Value> {
return Err(error("Select dimensions to update"));
}
let o = if p.get("options").is_some() { Some(options(s, p)?) } else { None };
let at = if p.get("at").is_some() { Some(point(p, "at")?) } else { None };
// Every dimension is checked before anything changes, and an update that changes none of
// them records no undo step.
let mut next = Vec::with_capacity(ids.len());
@@ -174,10 +176,21 @@ fn update(s: &mut Session, p: &Value) -> Result<Value> {
dim.options = o.clone();
}
if let Some(orientation) = orientation(p, dim.mode)? {
dim.set_orientation(orientation);
// An offset given with the orientation replaces the one the orientation would
// give: the dimension takes the orientation, and `resolve` reads its points.
if let Err(e) = dim.set_orientation(orientation, doc) {
if p.get("offset").is_none() {
return Err(error(e));
}
dim.orientation = orientation;
}
}
dim.offset = distance(p, dim.offset)?;
dim.resolve(doc).map_err(error)?;
if let Some(at) = at {
dim.place(at);
dim.resolve(doc).map_err(error)?;
}
if dim != old {
next.push((*id, dim));
}
@@ -452,7 +465,14 @@ pub(crate) fn refresh(before: &Document, doc: &mut Document) -> Result<bool> {
for (id, old) in dimensions {
let mut next = old.clone();
let moved = next.moved.take();
if next.source.as_ref().is_some_and(|s| s.topology_changed(before, doc)) || next.resolve(doc).is_err() {
// Whether the path a dimension of a whole path measures changed: when it did not, the
// dimension keeps its points without reading the path again, and is only checked.
let whole_changed = match &next.source {
Some(s @ DimensionSource::Extent { .. }) => Some(s.art_changed(before, doc)),
_ => None,
};
let unreadable = if whole_changed == Some(false) { next.validate().is_err() } else { next.resolve(doc).is_err() };
if next.source.as_ref().is_some_and(|s| s.topology_changed(before, doc)) || unreadable {
// The art it measured was deleted, or rebuilt with other anchors, or no longer fits
// (an ellipse that was a circle): it stays where it was, no longer linked, in this
// same undo step, rather than attaching to a different edge.
@@ -465,13 +485,14 @@ pub(crate) fn refresh(before: &Document, doc: &mut Document) -> Result<bool> {
changed = true;
continue;
}
next.keep_gap(&old);
next.keep_gap(&old, (whole_changed == Some(true)).then_some((before, doc)));
if let Some(xf) = next.source.as_ref().and_then(|s| s.reflection(before, doc)) {
next.mirror_line(&old, xf * old.handle());
next.mirror_line(&old, xf * old.handle(), Some((before, doc)));
}
// Moved on its own (the art it measures stayed put): it keeps its new place.
if let Some(v) = moved
&& (next.a, next.b, next.vertex) == (old.a, old.b, old.vertex)
&& whole_changed != Some(true)
{
next.place(old.handle() + v);
if next.resolve(doc).is_err() {
@@ -231,7 +231,7 @@ fn persp_edit(
let d = &s.doc()?.doc;
fallback.filter(|_| ids.iter().any(|id| g.attachment_of(d, *id).is_none()))
};
let kept = if copy && !stores_attachments(&s.doc()?.doc) { crate::cmd::object::preview_copies(s, ids, false)? } else { None };
let kept = if copy && !stores_attachments(&s.doc()?.doc) { crate::cmd::object::preview_copies(s, ids, false, false)? } else { None };
let edited = s.edit(label, |d, sel| {
g.adopt_stored_attachments(d);
let targets = match &kept {
@@ -502,7 +502,7 @@ pub(super) fn plane_move(s: &mut Session, p: &Value) -> Result<Value> {
// lists attachments of its own (`stores_attachments`).
let kept = if objects == "copy" && s.in_interaction() && !stores_attachments(&s.doc()?.doc) {
let on = on_plane(&s.doc()?.doc);
crate::cmd::object::preview_copies(s, &on, false)?
crate::cmd::object::preview_copies(s, &on, false, false)?
} else {
None
};
+273 -17
View File
@@ -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.
+1 -1
View File
@@ -17,7 +17,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Document Setup",
[],
None,
"{units?: \"Points\"|\"Inches\"|\"Millimeters\"|…, bleed?: pt (all sides)|[top, bottom, left, right]|{top?, bottom?, left?, right?} (0–72 pt), outlineImages?: bool (show images in Outline mode), highlightSubstitutedGlyphs?: bool (Highlight Substituted Fonts is a preference: prefs.set highlightSubstitutedFonts; a highlightSubstitutedFonts key is ignored and the reply carries a warning),gridSize?: \"small\"|\"medium\"|\"large\", gridColors?: \"Light\"|\"Medium\"|\"Dark\"|\"Red\"|\"Orange\"|\"Green\"|\"Blue\"|\"Purple\"|[colour, colour] (transparency grid; the first is also the paper colour; #rrggbbaa and #rgba are refused), simulatePaper?: bool, flattenerPreset?: \"High Resolution\"|\"Medium Resolution\"|\"Low Resolution\"|a saved preset (flattener.presets.list), discardWhiteOverprint?: bool, language?: \"English: USA\"|\"German\"|\"French\"|… (also picks its quotes), quotes?: {double?: \"“”\", single?: \"‘’\"} (beside a language: only if they differ from the current ones), typographersQuotes?: bool (typed straight quotes become the document's quotes), superscript?: {size?: %, position?: %}, subscript?: {size?: %, position?: %}, smallCapsSize?: %, exportText?: \"editable\"|\"appearance\" (SVG text as text or as outlines), backgroundContents?: \"transparent\"|\"white\" (white: raster exports are white behind the art), alignNewObjectsToPixelGrid?: bool (Align New Objects to Pixel Grid: paths and compound paths drawn from then on are pixel-aligned, as object.setPixelAligned; art already in the document, pasted, duplicated or placed keeps its own setting), …the keys of its own reply (it can be passed back; the values it only reports are ignored)} change the document setup in one undo step; no params → the current setup",
"{units?: \"Points\"|\"Inches\"|\"Millimeters\"|…, bleed?: pt (all sides)|[top, bottom, left, right]|{top?, bottom?, left?, right?} (0–72 pt), outlineImages?: bool (show images in Outline mode; off: a linked image or placed document shows its box crossed from corner to corner), highlightSubstitutedGlyphs?: bool (Highlight Substituted Fonts is a preference: prefs.set highlightSubstitutedFonts; a highlightSubstitutedFonts key is ignored and the reply carries a warning),gridSize?: \"small\"|\"medium\"|\"large\", gridColors?: \"Light\"|\"Medium\"|\"Dark\"|\"Red\"|\"Orange\"|\"Green\"|\"Blue\"|\"Purple\"|[colour, colour] (transparency grid; the first is also the paper colour; #rrggbbaa and #rgba are refused), simulatePaper?: bool, flattenerPreset?: \"High Resolution\"|\"Medium Resolution\"|\"Low Resolution\"|a saved preset (flattener.presets.list), discardWhiteOverprint?: bool, language?: \"English: USA\"|\"German\"|\"French\"|… (also picks its quotes), quotes?: {double?: \"“”\", single?: \"‘’\"} (beside a language: only if they differ from the current ones), typographersQuotes?: bool (typed straight quotes become the document's quotes), superscript?: {size?: %, position?: %}, subscript?: {size?: %, position?: %}, smallCapsSize?: %, exportText?: \"editable\"|\"appearance\" (SVG text as text or as outlines), backgroundContents?: \"transparent\"|\"white\" (white: raster exports are white behind the art), alignNewObjectsToPixelGrid?: bool (Align New Objects to Pixel Grid: paths and compound paths drawn from then on are pixel-aligned, as object.setPixelAligned; art already in the document, pasted, duplicated or placed keeps its own setting), …the keys of its own reply (it can be passed back; the values it only reports are ignored)} change the document setup in one undo step; no params → the current setup",
has_doc,
setup
)]
+1
View File
@@ -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};
+2 -2
View File
@@ -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,
+12 -3
View File
@@ -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};
@@ -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",
@@ -120,7 +129,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Smooth",
[],
None,
"{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change the smoothing), radius?: pt (12), fidelity?: pt (2.5; kept within 0.000078125 and about 3195, the Smooth tool's 0.05 to 100 px at the highest and the lowest zoom: the tool sends its Fidelity in screen pixels divided by the zoom)} smooth selected paths near the drag, keeping a corner where the path turns by more than 57.5° at the anchor and over radius and twice radius on either side → {ids, before, after}",
"{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change the smoothing), radius?: pt (12; from 0.001 to 1000), fidelity?: pt (2.5; from 0.000078125 to about 3195, the Smooth tool's 0.05 to 100 px at the highest and the lowest zoom: the tool sends its Fidelity in screen pixels divided by the zoom, kept within the range)} smooth selected paths near the drag, keeping a corner where the path turns by more than 57.5° at the anchor and over radius and twice radius on either side, and leaving a subpath as it is when the result would not be smoother (docs/mcp.md) → {ids, before, after}. A radius or fidelity outside its range is refused with an error, and nothing changes",
has_selection,
smooth_region
),
@@ -129,7 +138,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Join",
[],
None,
"{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change the join), tolerance?: pt (12)} join the open-path endpoints scrubbed over, or trim two crossing open paths whose overhanging ends are scrubbed and join them at the crossing → {id}",
"{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change the join), tolerance?: pt (12; from 0.001 to 1000)} join the open-path endpoints scrubbed over, or trim two crossing open paths whose overhanging ends are scrubbed and join them at the crossing → {id}. A tolerance outside 0.001 to 1000 is refused with an error, and nothing changes",
has_doc,
join_scrub
),
+59 -1
View File
@@ -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 }))
}
+491 -118
View File
@@ -1,9 +1,12 @@
use vectorcraft_pathops::addons::pathtools as pt;
use std::collections::HashMap;
use super::common::{dist_to_polyline, ids_json, path_mut, path_of, points_param, poly_bounds, subpath_len, target_paths};
use vectorcraft_pathops::addons::pathtools as pt;
use vectorcraft_pathops::start_nearest;
use super::common::{dist_to_polyline, ids_json, path_mut, path_of, points_param, poly_bounds, ranged, subpath_len, target_paths};
use super::{
Anchor, BezPath, CubicBez, NodeId, ParamCurve, ParamCurveNearest, PathData, Point, Rect, Result, Session, SimplifyOptions, SubPath, Value, json,
number_or, po,
Anchor, BezPath, CubicBez, NodeId, ParamCurve, ParamCurveNearest, PathData, Point, Rect, Result, Session, SimplifyOptions, SubPath, Value, bad,
json, number_or, po,
};
// ---------- Smooth ----------
@@ -323,84 +326,6 @@ fn refit_run(anchors: &[Anchor], tol: f64, sigma: f64, free: [bool; 2]) -> Vec<A
out.into_vec()
}
/// Distance (points) from an anchor within which a smoothed closed path starts at that anchor
/// instead of at a new one split in beside it.
const START_SNAP: f64 = 1e-3;
/// Distance (points) within which two points of a smoothed closed path count as equally near its
/// old start.
const START_TIE: f64 = 1e-6;
/// Where `p` lies along the closed `orig` from its first anchor: the segment index and parameter of
/// the point of `orig` nearest `p`, the first such point in its order. Sorts after every finite place
/// when there is none.
fn place_along(orig: &SubPath, p: Point) -> (usize, f64) {
let mut best: Option<(f64, usize, f64)> = None;
for j in 0..orig.anchors.len() {
let hit = orig.segment(j).nearest(p, 1e-9);
if hit.distance_sq.is_finite() && hit.t.is_finite() && best.is_none_or(|(d, ..)| hit.distance_sq < d) {
best = Some((hit.distance_sq, j, hit.t));
}
}
best.map_or((usize::MAX, f64::INFINITY), |(_, j, t)| (j, t))
}
/// The closed `sp` started at the point on it nearest `start`: at the anchor there, or at a new
/// anchor split into the segment there, which leaves the outline as it is. Of points equally near
/// `start`, the one earliest along `orig` (the path before smoothing) from its first anchor is used,
/// then the first in `sp`'s order. An open `sp`, or one with no segment or no finite nearest point,
/// is returned as it is.
fn start_nearest(mut sp: SubPath, start: Point, orig: &SubPath) -> SubPath {
let n = sp.anchors.len();
if !sp.closed || n < 2 {
return sp;
}
// (distance, place along `orig` once a tie needs it, segment of `sp`, parameter)
type Best = (f64, Option<(usize, f64)>, usize, f64);
let mut best: Option<Best> = None;
for i in 0..n {
let c = sp.segment(i);
let hit = c.nearest(start, 1e-9);
if !hit.distance_sq.is_finite() || !hit.t.is_finite() {
continue;
}
let d = hit.distance_sq.sqrt();
match &mut best {
None => best = Some((d, None, i, hit.t)),
Some((bd, bplace, bi, bt)) if (d - *bd).abs() <= START_TIE => {
let held = *bplace.get_or_insert_with(|| place_along(orig, sp.segment(*bi).eval(*bt)));
let place = place_along(orig, c.eval(hit.t));
if place.0 < held.0 || (place.0 == held.0 && place.1 < held.1) {
best = Some((d, Some(place), i, hit.t));
}
}
Some((bd, ..)) if d < *bd => best = Some((d, None, i, hit.t)),
Some(_) => {}
}
}
let Some((_, _, i, t)) = best else { return sp };
let c = sp.segment(i);
let at = c.eval(t);
let first = if at.distance(c.p0) <= START_SNAP {
i
} else if at.distance(c.p3) <= START_SNAP {
(i + 1) % n
} else {
let mid = if sp.segment_is_line(i) {
Anchor::corner(at)
} else {
let (l, r) = (c.subsegment(0.0..t), c.subsegment(t..1.0));
sp.anchors[i].h_out = l.p1;
sp.anchors[(i + 1) % n].h_in = r.p2;
Anchor::with_handles(at, l.p2, r.p1)
};
sp.anchors.insert(i + 1, mid);
i + 1
};
sp.anchors.rotate_left(first);
sp
}
/// Pieces of curve that one Smooth drag measures against the drag while it searches the segments
/// under it ([`reach_samples`]), shared equally by the curved segments that come within its reach,
/// each of which gets at least one: enough to search 300,000 pt of curve within the default reach
@@ -421,6 +346,8 @@ fn drag_stretches(pts: &[Point]) -> Vec<usize> {
/// The stretches of the drag `pts` among `of` whose bounds come within `radius` of `r` on both
/// axes: every stretch within `radius` of a point in `r`, and perhaps a few more.
fn stretches_near(pts: &[Point], of: &[usize], r: Rect, radius: f64) -> Vec<usize> {
#[cfg(test)]
STRETCH_TESTS.with(|c| c.set(c.get() + of.len()));
let r = r.inflate(radius, radius);
of.iter()
.copied()
@@ -432,8 +359,115 @@ fn stretches_near(pts: &[Point], of: &[usize], r: Rect, radius: f64) -> Vec<usiz
.collect()
}
#[cfg(test)]
thread_local! {
/// Tests: how many times this thread measured a point or a box against one stretch of a drag.
static STRETCH_TESTS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// Most grid cells [`DragReach`] lists one stretch of the drag in. A stretch whose reach covers more
/// is measured against every point and box instead.
const MAX_STRETCH_CELLS: usize = 64;
/// Most grid cells across the drag's bounds on each axis in [`DragReach`].
const MAX_DRAG_CELLS: f64 = 1024.0;
/// The stretches of a Smooth drag listed by the cells of a grid that their reach covers, so that a
/// point or a piece of path is measured only against the stretches whose reach it is in. Each query
/// gives at least every stretch that measuring against the whole drag finds in reach, so the results
/// are the same as measuring against the whole drag.
struct DragReach<'a> {
pts: &'a [Point],
radius: f64,
/// Every stretch of the drag, in order.
all: Vec<usize>,
/// The drag's bounds grown by more than `radius`, with the cell size; `None` when the drag or
/// the reach is not a finite number, and then every query gives every stretch.
grid: Option<(Rect, f64)>,
cells: HashMap<(i64, i64), Vec<usize>>,
/// The stretches whose reach covers more than [`MAX_STRETCH_CELLS`] cells.
wide: Vec<usize>,
}
impl<'a> DragReach<'a> {
fn new(pts: &'a [Point], radius: f64) -> Self {
let all = drag_stretches(pts);
let mut reach = DragReach { pts, radius, all, grid: None, cells: HashMap::new(), wide: vec![] };
if pts.is_empty() || !radius.is_finite() || pts.iter().any(|p| !p.x.is_finite() || !p.y.is_finite()) {
return reach;
}
// Enough more than the reach to cover the rounding of each distance and box measured.
let size = pts.iter().fold(0.0_f64, |m, p| m.max(p.x.abs()).max(p.y.abs()));
let pad = radius + 1e-6 * radius.max(1.0) + 1e-9 * size;
let area = poly_bounds(pts, pad);
let cell = pad.max(area.width().max(area.height()) / MAX_DRAG_CELLS);
if !(cell.is_finite() && cell > 0.0 && area.width().is_finite() && area.height().is_finite()) {
return reach;
}
reach.grid = Some((area, cell));
for &k in &reach.all {
let Some(&a) = pts.get(k) else { continue };
let b = pts.get(k + 1).copied().unwrap_or(a);
let r = Rect::from_points(a, b).inflate(pad, pad);
let ((x0, y0), (x1, y1)) = (reach.cell_of(Point::new(r.x0, r.y0)), reach.cell_of(Point::new(r.x1, r.y1)));
if (x1 - x0 + 1).saturating_mul(y1 - y0 + 1) > MAX_STRETCH_CELLS as i64 {
reach.wide.push(k);
continue;
}
for x in x0..=x1 {
for y in y0..=y1 {
reach.cells.entry((x, y)).or_default().push(k);
}
}
}
reach
}
/// The cell `q` is in, counted from the corner of the grid.
fn cell_of(&self, q: Point) -> (i64, i64) {
let Some((area, cell)) = self.grid else { return (0, 0) };
(((q.x - area.x0) / cell).floor() as i64, ((q.y - area.y0) / cell).floor() as i64)
}
/// Whether `q` is within the reach of the drag, and `slack` more.
fn in_reach(&self, q: Point, slack: f64) -> bool {
let limit = self.radius + slack;
let Some((area, _)) = self.grid else { return dist_to_stretches(self.pts, &self.all, q) <= limit };
if !(q.x >= area.x0 && q.x <= area.x1 && q.y >= area.y0 && q.y <= area.y1) {
return false;
}
let listed = self.cells.get(&self.cell_of(q)).map_or(&[][..], Vec::as_slice);
dist_to_stretches(self.pts, listed, q).min(dist_to_stretches(self.pts, &self.wide, q)) <= limit
}
/// The stretches, in order, that may come within the reach of `r`: at least every one that
/// [`stretches_near`] gives for `r` from the whole drag.
fn near_rect(&self, r: Rect) -> Vec<usize> {
let Some((area, _)) = self.grid else { return self.all.clone() };
let (x0, x1, y0, y1) = (r.x0.max(area.x0), r.x1.min(area.x1), r.y0.max(area.y0), r.y1.min(area.y1));
if !(x0 <= x1 && y0 <= y1) {
return vec![];
}
let ((cx0, cy0), (cx1, cy1)) = (self.cell_of(Point::new(x0, y0)), self.cell_of(Point::new(x1, y1)));
if (cx1 - cx0 + 1).saturating_mul(cy1 - cy0 + 1) > self.all.len() as i64 {
return self.all.clone();
}
let mut out = self.wide.clone();
for x in cx0..=cx1 {
for y in cy0..=cy1 {
out.extend(self.cells.get(&(x, y)).into_iter().flatten());
}
}
out.sort_unstable();
out.dedup();
out
}
}
/// The distance from `q` to the nearest of the stretches `of` of the drag `pts`.
fn dist_to_stretches(pts: &[Point], of: &[usize], q: Point) -> f64 {
#[cfg(test)]
STRETCH_TESTS.with(|c| c.set(c.get() + of.len()));
of.iter()
.filter_map(|&k| {
let a = *pts.get(k)?;
@@ -468,15 +502,18 @@ fn nearest_to_stretches(s: CubicBez, pts: &[Point], of: &[usize]) -> (f64, f64)
best
}
/// How many curved segments of `pd` may come within `radius` of the drag `pts`.
fn segments_in_reach(pd: &PathData, pts: &[Point], radius: f64) -> usize {
let all = drag_stretches(pts);
/// How many curved segments of `pd` may come within the reach of the drag.
fn segments_in_reach(pd: &PathData, reach: &DragReach) -> usize {
pd.subpaths
.iter()
.map(|sp| {
(0..sp.segment_count())
.filter(|&i| {
!vectorcraft_tools::draw2::segment_is_straight(sp, i) && !stretches_near(pts, &all, control_box(sp.segment(i)), radius).is_empty()
if vectorcraft_tools::draw2::segment_is_straight(sp, i) {
return false;
}
let b = control_box(sp.segment(i));
!stretches_near(reach.pts, &reach.near_rect(b), b, reach.radius).is_empty()
})
.count()
})
@@ -516,26 +553,26 @@ fn reach_samples(c: CubicBez, (t0, t1): (f64, f64), (pts, of): (&[Point], &[usiz
reach_samples(c, (mid, t1), (pts, &near), radius, budget, out);
}
/// `sp` cut where the reach `radius` of the drag `pts` crosses its curved segments, and whether each
/// `sp` cut where the reach of the drag crosses its curved segments, and whether each
/// anchor of the result is in reach. An anchor in reach is added in the middle of each stretch of a
/// segment in reach that does not run on from one of the segment's anchors in reach, and an anchor
/// out of reach in the middle of each stretch out of reach between two stretches in reach, so that a
/// stretch in reach is smoothed even when the segment's anchors are not, and the stretches between
/// stay as they are. A segment is searched no more than half the reach apart where it comes within
/// the reach of the drag ([`reach_samples`]), measuring up to `share` pieces of each segment.
fn mark_reached(sp: &SubPath, pts: &[Point], radius: f64, share: usize) -> (SubPath, Vec<bool>) {
let near = |q: Point| dist_to_polyline(pts, q) <= radius;
fn mark_reached(sp: &SubPath, reach: &DragReach, share: usize) -> (SubPath, Vec<bool>) {
let (pts, radius) = (reach.pts, reach.radius);
let n = sp.anchors.len();
let marked: Vec<bool> = sp.anchors.iter().map(|a| near(a.p)).collect();
let marked: Vec<bool> = sp.anchors.iter().map(|a| reach.in_reach(a.p, 0.0)).collect();
let mut places = vec![];
let all = drag_stretches(pts);
for i in 0..sp.segment_count() {
if vectorcraft_tools::draw2::segment_is_straight(sp, i) {
continue;
}
let c = sp.segment(i);
let (mut samples, mut budget) = (vec![], share);
reach_samples(c, (0.0, 1.0), (pts, &all), radius, &mut budget, &mut samples);
let near = reach.near_rect(control_box(c.subsegment(0.0..1.0)));
reach_samples(c, (0.0, 1.0), (pts, &near), radius, &mut budget, &mut samples);
// Stretches of samples alike, in order: (in reach, first, last).
let mut runs: Vec<(bool, usize, usize)> = vec![];
for (k, s) in samples.iter().enumerate() {
@@ -573,7 +610,7 @@ fn mark_reached(sp: &SubPath, pts: &[Point], radius: f64, share: usize) -> (SubP
.anchors
.iter()
.enumerate()
.map(|(j, a)| if added.contains(&j) { dist_to_polyline(pts, a.p) <= radius + 1e-9 * radius.max(1.0) } else { kept.next().unwrap_or(false) })
.map(|(j, a)| if added.contains(&j) { reach.in_reach(a.p, 1e-9 * radius.max(1.0)) } else { kept.next().unwrap_or(false) })
.collect();
(out, marked)
}
@@ -581,13 +618,14 @@ fn mark_reached(sp: &SubPath, pts: &[Point], radius: f64, share: usize) -> (SubP
/// `sp` with the anchors in the drag's reach smoothed and refitted, `None` when none are in reach.
/// A closed path whose first anchor is in reach starts at the point of the refitted path nearest
/// that anchor's place (VectorCraft's own rule).
fn smooth_subpath(sp: &SubPath, pts: &[Point], radius: f64, share: usize, tol: f64, sigma: f64) -> Option<SubPath> {
fn smooth_subpath(sp: &SubPath, reach: &DragReach, share: usize, tol: f64, sigma: f64) -> Option<SubPath> {
if sp.anchors.len() < 2 {
return None;
}
let near = &|q: Point| dist_to_polyline(pts, q) <= radius;
let radius = reach.radius;
let near = &|q: Point| reach.in_reach(q, 0.0);
// A drag along a segment smooths it even when its anchors are out of reach.
let (sp, marked) = mark_reached(sp, pts, radius, share);
let (sp, marked) = mark_reached(sp, reach, share);
let sp = &sp;
if !marked.iter().any(|m| *m) {
return None;
@@ -645,14 +683,28 @@ fn smooth_subpath(sp: &SubPath, pts: &[Point], radius: f64, share: usize, tol: f
(!same_anchors(&res, &anchors)).then(|| SubPath::new(res, false))
}
/// The segment `c`, which ends in the drag's reach (`near`) and starts outside it, split where it
/// enters the reach: the part outside, then the part in reach. `None` when no more than a sliver
/// is outside.
fn split_at_reach(c: CubicBez, near: &dyn Fn(Point) -> bool) -> Option<(CubicBez, CubicBez)> {
/// How much of a segment that ends in the drag's reach is in reach ([`split_at_reach`]).
enum Reach {
/// All of it, or all but a sliver.
Whole,
/// No more than a sliver at its end.
End,
/// The part outside the reach, then the part in reach.
Split(CubicBez, CubicBez),
}
/// Share of the tool's reach that the part of a segment in reach must be longer than for
/// [`split_at_reach`] to split the segment. VectorCraft's own value.
const REACH_SLIVER: f64 = 1.0 / 64.0;
/// The segment `c`, which ends in the drag's reach (`near`, `radius` points) and starts outside it,
/// split where it enters the reach. No more than 2% of its parameter range outside the reach is a
/// sliver, and so is a part in reach no longer than [`REACH_SLIVER`] of the reach.
fn split_at_reach(c: CubicBez, near: &dyn Fn(Point) -> bool, radius: f64) -> Reach {
const STEPS: u32 = 32;
let step = 1.0 / f64::from(STEPS);
// Back from the end in reach to the first sample outside, then halving to the crossing.
let outside = (1..=STEPS).map(|i| 1.0 - f64::from(i) * step).find(|t| !near(c.eval(*t)))?;
let Some(outside) = (1..=STEPS).map(|i| 1.0 - f64::from(i) * step).find(|t| !near(c.eval(*t))) else { return Reach::Whole };
let (mut lo, mut hi) = (outside, outside + step);
for _ in 0..20 {
let mid = (lo + hi) / 2.0;
@@ -668,7 +720,11 @@ fn split_at_reach(c: CubicBez, near: &dyn Fn(Point) -> bool) -> Option<(CubicBez
let s = c.subsegment(range);
if straight { CubicBez::new(s.p0, s.p0, s.p3, s.p3) } else { s }
};
(hi > 0.02).then(|| (part(0.0..hi), part(hi..1.0)))
if hi <= 0.02 {
return Reach::Whole;
}
let (far, reach) = (part(0.0..hi), part(hi..1.0));
if polygon_len(reach) <= REACH_SLIVER * radius { Reach::End } else { Reach::Split(far, reach) }
}
/// `anchors` with each run of `marked` ones smoothed by a Gaussian of spread `sigma` and refitted
@@ -693,27 +749,38 @@ fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool
}
i += 1;
}
let mut out = anchors.to_vec();
let mut out = EditsFromEnd::new(anchors.to_vec());
for (a, b) in runs.into_iter().rev() {
let lo = a.saturating_sub(1);
let hi = (b + 1).min(n - 1);
let (mut lo, mut hi) = (a.saturating_sub(1), (b + 1).min(n - 1));
// How much of the segments leading out of the run is in reach. A segment that is in reach
// only at the run's anchor stays out of the piece, so the piece ends at that anchor rather
// than in a sliver of a segment, which would leave the refit no direction to end along.
let Some(span) = out.get(lo, hi) else { continue };
let (first, start, end, last) = (span[0], span[a - lo], span[b - lo], span[hi - lo]);
let after = if hi > b { split_at_reach(CubicBez::new(last.p, last.h_in, end.h_out, end.p), near, radius) } else { Reach::Whole };
let before = if lo < a { split_at_reach(CubicBez::new(first.p, first.h_out, start.h_in, start.p), near, radius) } else { Reach::Whole };
if matches!(after, Reach::End) {
hi = b;
}
if matches!(before, Reach::End) {
lo = a;
}
if hi == lo {
continue;
}
let mut piece = out[lo..=hi].to_vec();
let Some(piece) = out.get(lo, hi) else { continue };
let mut piece = piece.to_vec();
// The anchors outside the reach, kept with the part of their segment that is outside.
let (mut head, mut tail) = (None, None);
if hi > b
if let Reach::Split(far, reach) = after
&& let [.., inner, outer] = piece.as_mut_slice()
&& let Some((far, reach)) = split_at_reach(CubicBez::new(outer.p, outer.h_in, inner.h_out, inner.p), near)
{
inner.h_out = reach.p2;
tail = Some(Anchor { h_in: far.p1, ..*outer });
*outer = Anchor::with_handles(far.p3, reach.p1, far.p2);
}
if lo < a
if let Reach::Split(far, reach) = before
&& let [outer, inner, ..] = piece.as_mut_slice()
&& let Some((far, reach)) = split_at_reach(CubicBez::new(outer.p, outer.h_out, inner.h_in, inner.p), near)
{
inner.h_in = reach.p2;
head = Some(Anchor { h_out: far.p1, ..*outer });
@@ -725,16 +792,143 @@ fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool
if same_anchors(&new, &piece) {
continue;
}
out.splice(lo..=hi, head.into_iter().chain(new).chain(tail));
out.replace(lo, hi, head.into_iter().chain(new).chain(tail));
}
out
out.finish()
}
/// A list edited by replacing stretches of it, each one ending no later than where the one before
/// started, in time proportional to the items replaced and moved rather than to the list's length
/// for each edit.
struct EditsFromEnd<T> {
/// The start of the list.
head: Vec<T>,
/// The rest of the list, last item first.
rest: Vec<T>,
}
impl<T> EditsFromEnd<T> {
fn new(items: Vec<T>) -> Self {
EditsFromEnd { head: items, rest: vec![] }
}
/// The items `lo` to `hi` of the list, `None` when it is shorter.
fn get(&mut self, lo: usize, hi: usize) -> Option<&[T]> {
while self.head.len() <= hi {
self.head.push(self.rest.pop()?);
}
self.head.get(lo..=hi)
}
/// The list with the items `lo` to `hi` replaced by `with`, as [`Vec::splice`] gives it. Leaves
/// the list as it is when it is shorter.
fn replace(&mut self, lo: usize, hi: usize, with: impl IntoIterator<Item = T>) {
if lo > hi || self.get(lo, hi).is_none() {
return;
}
self.rest.extend(self.head.drain(hi + 1..).rev());
self.head.truncate(lo);
self.head.extend(with);
}
fn finish(mut self) -> Vec<T> {
self.head.extend(self.rest.into_iter().rev());
self.head
}
}
/// Most pieces [`roughness`] cuts one curved segment into.
const ROUGHNESS_SEGMENT_PIECES: usize = 1024;
/// Most pieces [`roughness`] cuts the curved segments of one subpath into, shared equally by them.
const ROUGHNESS_PIECES: usize = 1 << 18;
/// How rough the subpath `sp` is, measured along the lines between points on each curved segment
/// about `step` apart along its control polygon (at least 4 and at most
/// [`ROUGHNESS_SEGMENT_PIECES`] pieces a segment, fewer on a subpath of very many segments): how
/// much it turns along its length in radians, from the direction each segment leaves its first anchor
/// along to the one it arrives at its last anchor along, with each turn at an anchor counted twice;
/// and how much it bends, the sum of each turn between two pieces squared over their mean length.
/// `None` when a point or a turn is not a number.
fn roughness(sp: &SubPath, step: f64) -> Option<(f64, f64)> {
let segments = sp.segment_count();
let most = (ROUGHNESS_PIECES / segments.max(1)).clamp(4, ROUGHNESS_SEGMENT_PIECES);
// The directions along the path, each with whether it leaves an anchor, and the pieces' vectors.
let (mut dirs, mut pieces): (Vec<(kurbo::Vec2, bool)>, Vec<kurbo::Vec2>) = (vec![], vec![]);
for i in 0..segments {
let c = sp.segment(i);
if sp.segment_is_line(i) {
dirs.push((c.p3 - c.p0, true));
pieces.push(c.p3 - c.p0);
continue;
}
let leave = [c.p1 - c.p0, c.p2 - c.p0, c.p3 - c.p0].into_iter().find(|d| d.hypot() > 1e-12).unwrap_or_default();
let arrive = [c.p3 - c.p2, c.p3 - c.p1, c.p3 - c.p0].into_iter().find(|d| d.hypot() > 1e-12).unwrap_or_default();
let len = polygon_len(c);
let k = if step > 0.0 && step.is_finite() && len.is_finite() { (len / step).ceil().clamp(4.0, most as f64) as usize } else { most };
dirs.push((leave, true));
let mut at = c.p0;
for j in 1..=k {
let q = if j == k { c.p3 } else { c.eval(j as f64 / k as f64) };
dirs.push((q - at, false));
pieces.push(q - at);
at = q;
}
dirs.push((arrive, false));
}
// A direction of no length is left out; the turn at an anchor is then taken at the next one.
let mut kept: Vec<(kurbo::Vec2, bool)> = Vec::with_capacity(dirs.len());
let mut at_anchor = false;
for (d, anchor) in dirs {
at_anchor |= anchor;
if d.hypot() > 1e-12 {
kept.push((d, at_anchor));
at_anchor = false;
}
}
pieces.retain(|d| d.hypot() > 1e-12);
let turn = |u: kurbo::Vec2, v: kurbo::Vec2| u.cross(v).atan2(u.dot(v)).abs();
let pairs = |n: usize| if sp.closed { n } else { n.saturating_sub(1) };
let mut turning = 0.0;
for j in 0..pairs(kept.len()) {
let (u, (v, anchor)) = (kept[j].0, kept[(j + 1) % kept.len()]);
turning += if anchor { 2.0 } else { 1.0 } * turn(u, v);
}
let mut bending = 0.0;
for j in 0..pairs(pieces.len()) {
let (u, v) = (pieces[j], pieces[(j + 1) % pieces.len()]);
bending += turn(u, v).powi(2) / (0.5 * (u.hypot() + v.hypot()));
}
(turning.is_finite() && bending.is_finite()).then_some((turning, bending))
}
/// Whether the Smooth tool keeps `new`, the subpath `old` smoothed with the reach `radius`
/// (VectorCraft's own rule). Both are measured with [`roughness`] at one spacing, an eighth of the
/// reach or 1/512 of the diagonal of `old`'s control points, whichever is smaller. `new` must turn
/// no more than a thousandth more than `old` (counting a turn of less than 1 radian as 1), and it
/// must have fewer anchors, turn less, or bend more than a ten-thousandth less. A result that would
/// leave the path rougher, or that adds anchors or changes the path without smoothing it, is not
/// kept.
fn smoother(old: &SubPath, new: &SubPath, radius: f64) -> bool {
let size = old.anchors.iter().fold(None, |r: Option<Rect>, a| {
let b = Rect::from_points(a.p, a.h_in).union_pt(a.h_out);
Some(r.map_or(b, |r| r.union(b)))
});
let step = (radius / 8.0).min(size.map_or(0.0, |r| r.width().hypot(r.height()) / 512.0));
let (Some((t0, b0)), Some((t1, b1))) = (roughness(old, step), roughness(new, step)) else { return false };
let scale = t0.max(1.0);
t1 <= t0 + 1e-3 * scale && (new.anchors.len() < old.anchors.len() || t0 - t1 >= 1e-6 * scale || b0 - b1 > 1e-4 * b0)
}
pub(super) fn smooth_region(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "path.smoothRegion";
let pts = points_param(p, "points", C)?;
let radius = number_or(p, "radius", 12.0, C)?.max(0.0);
let tol = number_or(p, "fidelity", 2.5, C)?.clamp(vectorcraft_tools::draw2::SMOOTH_MIN_TOLERANCE, vectorcraft_tools::draw2::SMOOTH_MAX_TOLERANCE);
let radius = ranged(p, "radius", 12.0, vectorcraft_tools::draw2::REACH_RANGE, C)?;
let tol = number_or(p, "fidelity", 2.5, C)?;
let (lo, hi) = (vectorcraft_tools::draw2::SMOOTH_MIN_TOLERANCE, vectorcraft_tools::draw2::SMOOTH_MAX_TOLERANCE);
if !(lo..=hi).contains(&tol) {
return Err(bad(C, format!("`fidelity` must be from {lo} to {hi} pt")));
}
let sigma = radius * SMOOTH_SPREAD;
let st = s.doc()?;
let mut plan = vec![];
@@ -743,15 +937,16 @@ pub(super) fn smooth_region(s: &mut Session, p: &Value) -> Result<Value> {
for id in target_paths(&st.doc, &st.selection, poly_bounds(&pts, radius)) {
paths.push((id, path_of(&st.doc, id)?.0));
}
let reach = DragReach::new(&pts, radius);
// Each curved segment in reach gets the same share of the search, whatever order they come in.
let in_reach: usize = paths.iter().map(|(_, pd)| segments_in_reach(pd, &pts, radius)).sum();
let in_reach: usize = paths.iter().map(|(_, pd)| segments_in_reach(pd, &reach)).sum();
let share = (MAX_REACH_PIECES / in_reach.max(1)).max(1);
for (id, pd) in paths {
let mut changed = false;
let subs: Vec<SubPath> = pd
.subpaths
.iter()
.map(|sp| match smooth_subpath(sp, &pts, radius, share, tol, sigma) {
.map(|sp| match smooth_subpath(sp, &reach, share, tol, sigma) {
Some(n) if n != *sp && n.anchors.len() >= 2 => {
changed = true;
n
@@ -759,7 +954,10 @@ pub(super) fn smooth_region(s: &mut Session, p: &Value) -> Result<Value> {
_ => sp.clone(),
})
.collect();
if changed {
// A subpath whose result would not be smoother stays as it was.
let subs: Vec<SubPath> =
subs.into_iter().zip(&pd.subpaths).map(|(n, sp)| if n == *sp || smoother(sp, &n, radius) { n } else { sp.clone() }).collect();
if changed && subs != pd.subpaths {
let np = PathData::new(subs);
before += pd.anchor_count();
after += np.anchor_count();
@@ -882,7 +1080,7 @@ fn trim_join(d: &vectorcraft_doc::Document, ids: &[NodeId], pts: &[Point], tol:
pub(super) fn join_scrub(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "path.joinScrub";
let pts = points_param(p, "points", C)?;
let tol = number_or(p, "tolerance", 12.0, C)?.max(0.0);
let tol = ranged(p, "tolerance", 12.0, vectorcraft_tools::draw2::REACH_RANGE, C)?;
let st = s.doc()?;
let targets = target_paths(&st.doc, &st.selection, poly_bounds(&pts, tol));
// Paths that cross with their ends scrubbed are trimmed there and joined (#5844).
@@ -1009,6 +1207,8 @@ pub(super) fn join_scrub(s: &mut Session, p: &Value) -> Result<Value> {
#[cfg(test)]
mod tests {
use vectorcraft_pathops::START_SNAP;
use super::*;
/// A closed ring of four smooth anchors round (100, 100) with radius 50.
@@ -1127,6 +1327,153 @@ mod tests {
pts.iter().map(|&(x, y)| Anchor::corner(Point::new(x, y))).collect()
}
/// A path of `n` smooth anchors 1 pt apart, along x and up and down by 3 pt, every segment
/// curved; closed, the anchors go round a circle `n` pt long instead.
fn wave(n: usize, closed: bool) -> SubPath {
let anchors = (0..n)
.map(|i| {
let f = i as f64;
if closed {
let r = n as f64 / std::f64::consts::TAU + f64::from(u8::from(i % 2 == 1)) * 3.0;
let a = f / n as f64 * std::f64::consts::TAU;
let (p, t) = (Point::new(r * a.cos(), r * a.sin()), kurbo::Vec2::new(-a.sin(), a.cos()) * 0.4);
Anchor::with_handles(p, p - t, p + t)
} else {
let p = Point::new(f, f64::from(u8::from(i % 2 == 1)) * 3.0);
Anchor::with_handles(p, p - kurbo::Vec2::new(0.4, 0.0), p + kurbo::Vec2::new(0.4, 0.0))
}
})
.collect();
SubPath::new(anchors, closed)
}
/// The same drag measured against all of its stretches for every point and box.
fn linear<'a>(pts: &'a [Point], radius: f64) -> DragReach<'a> {
DragReach { grid: None, ..DragReach::new(pts, radius) }
}
/// How many stretch measures `f` made on this thread.
fn stretch_tests(f: impl FnOnce()) -> usize {
STRETCH_TESTS.with(|c| c.set(0));
f();
STRETCH_TESTS.with(std::cell::Cell::get)
}
/// A drag of 200 points over 200 pt of a curved path of 100,000 anchors measures the anchors
/// and segments near the drag against the stretches near them, not every anchor and segment
/// against every stretch (about 40 million measures), and smooths the path as measuring
/// everything does.
#[test]
fn a_drag_over_a_long_path_measures_only_what_is_near_it() {
let sp = wave(100_000, false);
let pts: Vec<Point> = (0..200).map(|i| Point::new(50_000.0 + f64::from(i), 1.5)).collect();
let reach = DragReach::new(&pts, 12.0);
let pd = PathData::single(sp.clone());
let mut in_reach = 0;
let boxes = stretch_tests(|| in_reach = segments_in_reach(&pd, &reach));
assert!(in_reach > 0 && boxes < 100_000, "{in_reach} segments in reach, {boxes} measures");
let share = (MAX_REACH_PIECES / in_reach).max(1);
let mut got = None;
let marks = stretch_tests(|| got = Some(mark_reached(&sp, &reach, share)));
assert!(marks < 100_000, "{marks} measures");
let smoothed = smooth_subpath(&sp, &reach, share, 2.5, 4.0);
assert!(smoothed.is_some());
let all = linear(&pts, 12.0);
assert_eq!(segments_in_reach(&pd, &all), in_reach);
assert_eq!(Some(mark_reached(&sp, &all, share)), got);
assert_eq!(smooth_subpath(&sp, &all, share, 2.5, 4.0), smoothed);
}
/// Paths and drags of many shapes, a drag of one point, one far away, one with a stretch longer
/// than the grid lists by cell, one with a point that is not a number, and reaches of 0 to 50 pt:
/// the grid gives the same segments in reach, the same marks and the same smoothed path as
/// measuring against the whole drag.
#[test]
fn the_drag_grid_gives_the_results_of_measuring_the_whole_drag() {
let far = Point::new(1e7, -1e7);
let paths = [
ring(),
wave(1500, false),
wave(1500, true),
SubPath::polyline(&(0..500).map(|i| Point::new(f64::from(i) * 2.0, f64::from(i % 3) * 4.0)).collect::<Vec<_>>(), false),
SubPath::new(
vec![Anchor::with_handles(Point::new(0.0, 0.0), Point::new(0.0, 0.0), Point::new(3e5, 4e5)), Anchor::corner(Point::new(1e6, 0.0))],
false,
),
SubPath::new(
wave(200, true)
.anchors
.iter()
.map(|a| Anchor::with_handles(a.p + far.to_vec2(), a.h_in + far.to_vec2(), a.h_out + far.to_vec2()))
.collect(),
true,
),
];
let line = |from: (f64, f64), to: (f64, f64), n: u32| -> Vec<Point> {
(0..=n).map(|i| Point::new(from.0, from.1).lerp(Point::new(to.0, to.1), f64::from(i) / f64::from(n))).collect()
};
let mut loop_drag: Vec<Point> =
(0..400).map(|i| Point::new(100.0 + 120.0 * (f64::from(i) * 0.05).cos(), 120.0 * (f64::from(i) * 0.05).sin())).collect();
loop_drag.extend(line((0.0, 0.0), (1500.0, 2.0), 50));
let drags = [
vec![Point::new(150.0, 100.0)],
line((40.0, 90.0), (160.0, 110.0), 30),
line((-100.0, 1.0), (1600.0, 2.0), 1500),
loop_drag,
line((5e6, 5e6), (5e6 + 10.0, 5e6), 5),
vec![Point::new(0.0, 0.0), Point::new(1500.0, 3.0), Point::new(1500.0, 3.2), Point::new(10.0, 0.5)],
vec![Point::new(10.0, 1.0), Point::new(f64::NAN, 0.0), Point::new(12.0, 1.0)],
(0..1000).map(|i| Point::new(f64::from(i) * 0.01, 1.0)).collect(),
line((far.x, far.y), (far.x + 300.0, far.y + 40.0), 80),
];
for pts in &drags {
for radius in [0.0, 0.5, 12.0, 50.0] {
let (grid, all) = (DragReach::new(pts, radius), linear(pts, radius));
for (k, sp) in paths.iter().enumerate() {
let pd = PathData::single(sp.clone());
let in_reach = segments_in_reach(&pd, &all);
assert_eq!(segments_in_reach(&pd, &grid), in_reach, "path {k}, reach {radius}, drag {:?}", pts.first());
let share = (MAX_REACH_PIECES / in_reach.max(1)).max(1);
assert_eq!(mark_reached(sp, &grid, share), mark_reached(sp, &all, share), "path {k}, reach {radius}, drag {:?}", pts.first());
let sigma = radius * SMOOTH_SPREAD;
let want = smooth_subpath(sp, &all, share, 2.5, sigma);
assert_eq!(smooth_subpath(sp, &grid, share, 2.5, sigma), want, "path {k}, reach {radius}, drag {:?}", pts.first());
}
}
}
}
/// Replacing stretches of a list from its end, each one ending no later than where the one
/// before started (sometimes on that item, sometimes with nothing or with more items), gives the
/// list that [`Vec::splice`] gives.
#[test]
fn edits_from_the_end_match_splicing() {
let mut seed = 0x2545_f491_u64;
let mut next = |m: usize| {
seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407);
(seed >> 33) as usize % m.max(1)
};
for round in 0..200 {
let items: Vec<usize> = (0..next(60) + 1).collect();
let (mut want, mut got) = (items.clone(), EditsFromEnd::new(items.clone()));
let mut end = items.len() - 1;
loop {
let hi = end.saturating_sub(next(3));
let lo = hi.saturating_sub(next(6));
let with: Vec<usize> = (0..next(5)).map(|j| 1000 * (round + 1) + j).collect();
let Some(stretch) = want.get(lo..=hi).map(<[usize]>::to_vec) else { break };
assert_eq!(got.get(lo, hi).map(<[usize]>::to_vec), Some(stretch), "round {round}");
want.splice(lo..=hi, with.clone());
got.replace(lo, hi, with);
if lo == 0 {
break;
}
end = lo;
}
assert_eq!(got.finish(), want, "round {round}");
}
}
/// Anchors on one point, anchors that are not numbers or are too far out to measure, and a
/// zigzag of 100,001 anchors 1 pt high give no corner and do not fail; a square's four anchors
/// are its corners, and an open path's ends never are.
@@ -1246,4 +1593,30 @@ mod tests {
assert_eq!(smooth_corners(&jags, true, 12.0), vec![false; 16]);
assert_eq!(smooth_corners(&polyline(&[(0.0, 0.0), (6.0, 0.0), (3.0, 5.196)]), true, 12.0), vec![true; 3]);
}
/// `sp` scaled by `k` about the origin.
fn scaled(sp: &SubPath, k: f64) -> SubPath {
let at = |p: Point| Point::new(p.x * k, p.y * k);
SubPath::new(sp.anchors.iter().map(|a| Anchor { p: at(a.p), h_in: at(a.h_in), h_out: at(a.h_out), ..*a }).collect::<Vec<Anchor>>(), sp.closed)
}
/// The Smooth tool keeps a result that turns less, and not one that turns more with as many
/// anchors, one that adds an anchor and keeps the outline, or one that is the path itself, at
/// any size.
#[test]
fn the_smooth_tool_keeps_only_a_smoother_result() {
let round = ring();
let mut bumped = ring();
bumped.anchors[1].translate(kurbo::Vec2::new(0.0, -25.0));
let split = start_nearest(ring(), round.segment(0).eval(0.3), &round);
assert_eq!(split.anchors.len(), 5, "{split:?}");
for k in [1e-3, 1.0, 1e3] {
let (round, bumped, split) = (scaled(&round, k), scaled(&bumped, k), scaled(&split, k));
let reach = 12.0 * k;
assert!(smoother(&bumped, &round, reach), "at {k}x a bump smoothed away is kept");
assert!(!smoother(&round, &bumped, reach), "at {k}x a bump added is not kept");
assert!(!smoother(&round, &split, reach), "at {k}x an anchor added on the outline is not kept");
assert!(!smoother(&round, &round.clone(), reach), "at {k}x the same path is not kept");
}
}
}
+68 -15
View File
@@ -24,7 +24,7 @@ pub fn specs() -> Vec<CommandSpec> {
"New…",
["File"],
None,
"{preset?: a name from file.newPresets (start from it; the other params change it), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (default: all in one row), rows?: n (gridByColumn only, an error with another layout: that many rows, in place of columns; a preset keeps them until columns without rows or another layout is given), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), profile?: a category of file.newPresets|null (the New Document profile the document starts from, see file.newProfiles; default: a built-in preset's category, kept by the saved and Recent presets made from it; null or no preset: the defaults), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode, profile?: the profile applied, warnings?: [text] (a color profile the profile's file carries that can't be used), profileError?: {profile, reason} (its file could not be read, was larger than 64 MiB or is not a native document, or the request may not read the profiles folder, a reason that leaves out the folder's path: the document has the defaults)}; the size is remembered in file.newPresets' Recent",
"{preset?: a name from file.newPresets (start from it; the other params change it), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (default: all in one row), rows?: n (gridByColumn only, an error with another layout: that many rows, in place of columns; a preset keeps them until columns without rows or another layout is given), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), profile?: a category of file.newPresets|null (the New Document profile the document starts from, see file.newProfiles; default: a built-in preset's category, kept by the saved and Recent presets made from it; null or no preset: the defaults), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode, profile?: the profile applied, warnings?: [text] (a color profile the profile's file carries that can't be used), profileError?: {profile, reason} (its file is a link or a folder, could not be read, was larger than 64 MiB or is not a native document, or the request may not read the profiles folder, a reason that leaves out the folder's path: the document has the defaults)}; the size is remembered in file.newPresets' Recent",
always,
super::newdoc::file_new
),
@@ -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), keepEmpty?: bool (keep a compound path left with no members)} 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 unless keepEmpty); without ids, refused while an object of a symbol instance's art is selected",
has_selection_or_guides,
clear
),
@@ -1221,6 +1221,8 @@ 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")?;
let keep_empty = switch_or(p, "keepEmpty", 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 +1230,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() {
@@ -1252,8 +1255,11 @@ fn clear(s: &mut Session, p: &Value) -> Result<Value> {
return ok();
}
s.edit("Clear", |d, sel| {
let parents: Vec<_> =
ids.iter().filter_map(|id| d.parent_of(*id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })))).collect();
let parents: Vec<_> = if keep_empty {
Vec::new()
} else {
ids.iter().filter_map(|id| d.parent_of(*id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })))).collect()
};
d.remove_many(&ids)?;
for p in parents {
if d.node(p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())) {
@@ -1275,6 +1281,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";
@@ -1552,7 +1569,7 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
let (ids, imported, artboards, into) = s.edit(mode.label(), |d, sel| {
// Converted colors are compared with the document's resources, as another document's are
// (`Clipboard::import_into`); its images are still the document's own.
let imported = clip.import_into(d, choices, same_doc)?;
let mut imported = clip.import_into(d, choices, same_doc)?;
// Draw Inside: the clip group of the object drawn into, made on the first paste.
let into = inside.map(|t| super::create::draw_inside_group(d, t)).transpose()?;
let artboards: Vec<usize> = boards
@@ -1570,7 +1587,7 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
let mut c = d.reid(n);
// A pasted symbol set packs from the density recorded for it at Copy.
d.carry_set_densities(n, &c, &clip.set_densities);
imported.apply(&mut c);
imported.apply(&mut c, d);
let sc = vectorcraft_doc::Scaling { patterns: mode == PasteMode::Drag, ..Default::default() };
if xf != Affine::IDENTITY {
// A cross-document drag carries the graphic's appearance with it,
@@ -1698,6 +1715,7 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
"added": imported.added,
"merged": imported.merged,
"renamed": imported.renamed,
"warnings": imported.warnings,
}))
}
@@ -1828,7 +1846,19 @@ fn duplicate(s: &mut Session, p: &Value) -> Result<Value> {
/// Duplicate `roots` directly above each original, transform the copies, select them
/// ([`copy_above`]).
pub(crate) fn duplicate_in(d: &mut Document, sel: &mut vectorcraft_doc::Selection, roots: &[NodeId], xf: Affine) -> Result<Vec<NodeId>> {
let out = copy_above(d, roots, |_, _, c| {
duplicate_beside(d, sel, roots, xf, false)
}
/// [`duplicate_in`], with each copy directly below its original when `below` is true
/// ([`copy_beside`]).
pub(crate) fn duplicate_beside(
d: &mut Document,
sel: &mut vectorcraft_doc::Selection,
roots: &[NodeId],
xf: Affine,
below: bool,
) -> Result<Vec<NodeId>> {
let out = copy_beside(d, roots, below, |_, _, c| {
c.transform(xf, true);
super::object::keep_pixel_aligned(c, true.into());
})?;
@@ -1841,20 +1871,42 @@ pub(crate) fn duplicate_in(d: &mut Document, sel: &mut vectorcraft_doc::Selectio
/// tree as it is. The copies take new ids in the order of `roots`. Roots listed twice, or inside
/// another root, are copied one at a time: each copy is made from the document as the copies
/// before it left it. Copied type whose layout caches [`Document::reid`] dropped has them again.
pub(crate) fn copy_above(d: &mut Document, roots: &[NodeId], mut change: impl FnMut(&mut Document, &Node, &mut Node)) -> Result<Vec<NodeId>> {
pub(crate) fn copy_above(d: &mut Document, roots: &[NodeId], change: impl FnMut(&mut Document, &Node, &mut Node)) -> Result<Vec<NodeId>> {
copy_beside(d, roots, false, change)
}
/// [`copy_above`], with each copy directly below its original, in the same parent, when `below`
/// is true. The clipping path of a clip group or a clipping layer stays the bottom child: its copy
/// goes directly above it.
pub(crate) fn copy_beside(
d: &mut Document,
roots: &[NodeId],
below: bool,
mut change: impl FnMut(&mut Document, &Node, &mut Node),
) -> Result<Vec<NodeId>> {
let paths = d.index_paths(roots.iter().copied());
let mut found: Vec<_> = roots.iter().filter_map(|id| paths.get(id)).collect();
found.sort_unstable();
// The bottom child of a parent that clips is its clipping path.
let clips_at = |d: &Document, up: &[usize], i: usize| i == 0 && !up.is_empty() && d.node_at(up).is_some_and(Node::clips);
let out = if found.windows(2).all(|w| !w[1].starts_with(w[0])) {
let mut copies = Vec::with_capacity(roots.len());
let (mut copies, mut above) = (Vec::with_capacity(roots.len()), vec![]);
let mut out = Vec::with_capacity(roots.len());
for id in roots {
let Some(n) = paths.get(id).and_then(|p| d.node_at(p)).cloned() else { continue };
let Some(p) = paths.get(id) else { continue };
let Some(n) = d.node_at(p).cloned() else { continue };
let mut c = d.reid(&n);
change(d, &n, &mut c);
copies.push((*id, vec![c]));
out.push(c.id);
let on_floor = below && p.split_last().is_some_and(|(i, up)| clips_at(d, up, *i));
if !below || on_floor { above.push((*id, vec![c])) } else { copies.push((*id, vec![c])) }
}
if !copies.is_empty() {
d.insert_below(copies)?;
}
if !above.is_empty() {
d.insert_beside(above, false)?;
}
let out: Vec<NodeId> = copies.iter().flat_map(|(_, c)| c.iter().map(|n| n.id)).collect();
d.insert_beside(copies, false)?;
out
} else {
let mut out = vec![];
@@ -1863,7 +1915,8 @@ pub(crate) fn copy_above(d: &mut Document, roots: &[NodeId], mut change: impl Fn
let Some(n) = d.node(*id).cloned() else { continue };
let mut c = d.reid(&n);
change(d, &n, &mut c);
out.push(d.insert(par, idx + 1, c)?);
let floor = usize::from(par.and_then(|p| d.node(p)).is_some_and(Node::clips));
out.push(d.insert(par, if below { idx.max(floor) } else { idx + 1 }, c)?);
}
out
};
+57 -13
View File
@@ -97,7 +97,7 @@ fn effect_specs() -> Vec<CommandSpec> {
"Expand Appearance",
["Object"],
None,
"{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (a stroke stays a stroke, with its weight, dashes, arrowheads and width profile, on its own copy of the path, which object.expand or object.path.outlineStroke outline; brushed strokes become their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; Vector Halftone (addon.color.halftone) becomes a group of its dot paths, one per ink; a group's or layer's own fills and strokes become objects among its members, which are expanded too; a symbol instance whose topmost fill or stroke is visible, has an opacity above 0 and has a geometry or raster effect becomes a group of its art, that fill's effects reshaping the art's filled shapes and that stroke's effects reshaping its stroked shapes, as the canvas draws them, its raster effects an image as for other objects; a symbol instance in that art whose topmost fill or stroke has such an effect (its own or one the outer instance passes on) becomes its art and image in turn. An outlined frame of threaded text leaves its thread with the text it shows, and a frame kept as type in a group stays in its thread. A dimension whose art it changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked. Hidden fills, strokes and effects are dropped. One expansion makes at most 1,024 images of raster effects, 256 megapixels in all (VectorCraft's own limits): an object or symbol instance whose image would go past them stays as it is, with its effects, and when nothing else expands that is an error. In Safe Mode, an object with a visible plug-in effect (in it, or in a symbol it places, a plain instance in a group or layer whose raster effect makes an image of it included) is an error and nothing changes. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says; or raster effects were left past the limits), rasterLeft? (how many objects were left so)}",
"{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (a stroke stays a stroke, with its weight, dashes, arrowheads and width profile, on its own copy of the path, which object.expand or object.path.outlineStroke outline; brushed strokes become their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; Vector Halftone (addon.color.halftone) becomes a group of its dot paths, one per ink; a group's or layer's own fills and strokes become objects among its members, which are expanded too; a symbol instance whose topmost fill or stroke is visible, has an opacity above 0 and has a geometry or raster effect becomes a group of its art, that fill's effects reshaping the art's filled shapes and that stroke's effects reshaping its stroked shapes, as the canvas draws them, its raster effects an image as for other objects; a symbol instance in that art whose topmost fill or stroke has such an effect (its own or one the outer instance passes on) becomes its art and image in turn. An outlined frame of threaded text leaves its thread with the text it shows, and a frame kept as type in a group stays in its thread. A dimension whose art it changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked. Hidden fills, strokes and effects are dropped. One expansion makes at most 1,024 images of raster effects, 256 megapixels in all (VectorCraft's own limits): an object or symbol instance whose image would go past them stays as it is, with its effects, and when nothing else expands that is an error. In Safe Mode, an object with a visible plug-in effect (in it, or in a symbol it places, a visible plain instance outside template layers in a group or layer whose raster effect makes an image of it included) is an error and nothing changes. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says; or raster effects were left past the limits), rasterLeft? (how many objects were left so)}",
can_expand,
expand_appearance
),
@@ -927,7 +927,8 @@ fn bevel_effect(id: &str) -> bool {
/// Options ([`effects::PathfinderEffectOptions`], so an effect saved without them and given their
/// defaults is unchanged), each option given equal to the one it stores (a precision that Scale
/// Strokes & Effects took past its range evaluates at the bound but is still edited), and every
/// other value given equal to the one it has?
/// other value given equal to the one it has (a number by its value, so a Soft Mix `mixingRate` of 50
/// over a stored 50.0 is unchanged)?
fn pathfinder_edit_changes_nothing(e: &Effect, params: &Value) -> bool {
if !effects::takes_pathfinder_options(&e.id) {
return false;
@@ -938,8 +939,12 @@ fn pathfinder_edit_changes_nothing(e: &Effect, params: &Value) -> bool {
if let Value::Object(m) = &mut after {
m.extend(given.clone());
}
let others_same = given.iter().filter(|(k, _)| !effects::PATHFINDER_OPTION_KEYS.contains(&k.as_str())).all(|(k, v)| current.get(k) == Some(v));
let same_value = |a: &Value, b: &Value| a == b || a.as_f64().is_some_and(|x| b.as_f64() == Some(x));
// Two integers compare exactly, and a float compares with any number by value.
let same_value = |a: &Value, b: &Value| a == b || ((a.is_f64() || b.is_f64()) && a.as_f64().is_some_and(|x| b.as_f64() == Some(x)));
let others_same = given
.iter()
.filter(|(k, _)| !effects::PATHFINDER_OPTION_KEYS.contains(&k.as_str()))
.all(|(k, v)| current.get(k).is_some_and(|c| same_value(c, v)));
let stored_same = given
.iter()
.filter(|(k, _)| effects::PATHFINDER_OPTION_KEYS.contains(&k.as_str()))
@@ -1611,33 +1616,72 @@ fn expanded_node(
/// Does `n`, an object in it, or the art of a symbol placed in it hold a plug-in effect that
/// expanding it draws: a visible one, the object's own or a visible fill's or stroke's, on an
/// object that expands ([`expandable`]; in a symbol's art, `in_art`, every object does, and so does
/// every object in a group or layer with a raster effect, whose image draws all of it). A symbol's
/// object that expands ([`expandable`]; in a symbol's art, `in_art`, every object does), or that the
/// image of a group or layer with a raster effect draws ([`rasterizes_plugin_effect`]). A symbol's
/// art counts where an instance of it expands. `seen` holds the symbols already looked into.
fn holds_plugin_effect(d: &Document, n: &Node, in_art: bool, seen: &mut std::collections::HashSet<String>) -> bool {
let plugin = |e: &Effect| e.visible && vectorcraft_plugins::effect::plugin_id(&e.id).is_some();
let mut symbols = vec![];
let mut drawn = vec![];
let mut holds = false;
n.walk(&mut |c| {
if !in_art && is_container(c) && !rasterfx::raster_fx(c).is_empty() {
drawn.push(c);
}
if !in_art && !expandable(c) {
return;
}
holds |= c.appearance.effects.iter().any(plugin) || c.appearance.items.iter().any(|i| i.visible() && i.effects().iter().any(plugin));
holds |= has_own_plugin_effect(c);
if let NodeKind::SymbolInstance { symbol, .. } = &c.kind {
symbols.push(symbol.clone());
}
});
holds
|| drawn.into_iter().any(|g| holds_plugin_effect(d, g, true, seen))
|| (!in_art && rasterizes_plugin_effect(d, n, &mut std::collections::HashSet::new()))
|| symbols.into_iter().any(|name| {
seen.insert(name.clone()) && d.symbols.iter().find(|s| s.name == name).is_some_and(|s| holds_plugin_effect(d, &s.art, true, seen))
})
}
/// Does `n` have a visible plug-in effect of its own, or on a visible fill or stroke?
fn has_own_plugin_effect(n: &Node) -> bool {
let plugin = |e: &Effect| e.visible && vectorcraft_plugins::effect::plugin_id(&e.id).is_some();
n.appearance.effects.iter().any(plugin) || n.appearance.items.iter().any(|i| i.visible() && i.effects().iter().any(plugin))
}
/// Does a group or layer in `n` with a raster effect make an image of a visible plug-in effect
/// ([`draws_plugin_effect`])? Expansion makes the image of such a group or layer even when it, or
/// a group around it, is hidden. A group or layer that paints something and whose raster effects
/// are not all shadows and outer glows becomes one image of what it draws, so the groups and layers
/// in it make no images of their own; one that paints nothing makes no image, and its members
/// expand on their own.
fn rasterizes_plugin_effect(d: &Document, n: &Node, seen: &mut std::collections::HashSet<String>) -> bool {
let fx = if is_container(n) { rasterfx::raster_fx(n) } else { vec![] };
if !fx.is_empty() {
if draws_plugin_effect(d, n, seen) {
return true;
}
if !fx.iter().all(effects::RasterFx::is_below) && vectorcraft_render::painted_bounds(d, n).is_some() {
return false;
}
}
n.children().into_iter().flatten().any(|c| rasterizes_plugin_effect(d, c, seen))
}
/// Does `n`, an object the image of `n` draws in it, or the art of a symbol such an instance places,
/// have a visible plug-in effect ([`has_own_plugin_effect`])? The image leaves out a hidden object
/// in `n`, a template layer, a guide or a ruler guide, and everything in it, as the renderer does
/// with templates skipped. `seen` holds the symbols already looked into.
fn draws_plugin_effect(d: &Document, n: &Node, seen: &mut std::collections::HashSet<String>) -> bool {
if has_own_plugin_effect(n) {
return true;
}
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind
&& seen.insert(symbol.clone())
&& d.symbols.iter().find(|s| s.name == *symbol).is_some_and(|s| draws_plugin_effect(d, &s.art, seen))
{
return true;
}
let drawn =
|c: &Node| c.visible && !c.is_ruler_guide() && !matches!(c.kind, NodeKind::Layer { template: true, .. } | NodeKind::Path { guide: true, .. });
n.children().into_iter().flatten().any(|c| drawn(c) && draws_plugin_effect(d, c, seen))
}
fn expand_appearance(s: &mut Session, p: &Value) -> Result<Value> {
let roots = edit_targets(s, p, "effect.expandAppearance")?;
// In Safe Mode a plug-in effect draws nothing: expanding it would drop the effect and keep the
+1 -1
View File
@@ -79,10 +79,10 @@ pub(crate) use encode::{anti_alias, background, with_single_artboard};
pub(crate) use export::with_artboard_fills;
pub(crate) use export::{EXPORT_PARAMS, export_crop, isolated};
pub use export::{export_doc, export_source, selection_doc, unused_option_notes};
pub(crate) use load::decode_native_file;
use load::err;
pub(crate) use load::import_svg;
pub(crate) use load::is_placeholder;
pub(crate) use load::native_file;
pub(crate) use load::page_or_editing_data;
pub(crate) use load::source;
pub use load::{
+19 -11
View File
@@ -140,9 +140,8 @@ pub fn detect(name: &str, bytes: &[u8]) -> Option<&'static Format> {
if let Some(f) = craft_image_codecs::detect(bytes).and_then(image_format) {
return Some(f);
}
// A version 2 PICT is known by its version opcodes after the picture's frame, at byte 522 of a
// file or byte 10 of a bare picture (version 1 by its file's name), so a format whose
// signature starts the file is checked first.
// A PICT is known by its version opcodes after the picture's frame, at byte 522 of a file or
// byte 10 of a bare picture, so a format whose signature starts the file is checked first.
if vectorcraft_metafile::is_pict(bytes) {
return format("pict");
}
@@ -193,8 +192,11 @@ fn restore_or_import(
let mut fallback = None;
if let Some((intact, bytes)) = editing {
let native = if intact { bytes() } else { None };
match native.and_then(|b| native_file(&b).ok()) {
Some((doc, _, warnings)) => return Ok((doc, warnings, true)),
match native.and_then(|b| decode_native_file(&b).ok()) {
Some((mut doc, _, mut warnings)) => {
warnings.extend(vectorcraft_text::FontDb::global().bind_document_file_fonts(&mut doc));
return Ok((doc, warnings, true));
}
None => fallback = Some(if intact { EDITING_DAMAGED } else { EDITING_STALE }),
}
}
@@ -205,9 +207,9 @@ fn restore_or_import(
Ok((doc, warnings, false))
}
/// A native file's document and details, the colour profiles it carries installed where missing
/// (with a warning for each that can't be used).
pub(crate) fn native_file(bytes: &[u8]) -> Result<(Document, vectorcraft_format::FileInfo, Vec<String>)> {
/// Decode a native file and install its colour profiles, preserving profile and depth warnings.
/// The caller must assemble any external resources and bind file fonts before layout.
pub(crate) fn decode_native_file(bytes: &[u8]) -> Result<(Document, vectorcraft_format::FileInfo, Vec<String>)> {
let f = vectorcraft_format::load_file(bytes).map_err(err)?;
let mut warnings = super::native::install_profiles(f.profiles);
warnings.extend(f.depth_notes);
@@ -424,7 +426,8 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
})?
}
"vectorcraft" | "template" => {
let (d, info, warnings) = native_file(bytes)?;
let (mut d, info, mut warnings) = decode_native_file(bytes)?;
warnings.extend(vectorcraft_text::FontDb::global().bind_document_file_fonts(&mut d));
native_pdf_compatible = Some(info.pdf_compatible);
converted = info.is_old() || super::extension(name) == vectorcraft_format::LEGACY_EXTENSION;
(d, warnings, false)
@@ -688,7 +691,8 @@ pub fn open_bytes(s: &mut Session, name: &str, bytes: &[u8], path: Option<String
/// [`open_bytes`] with the `document.open` options in `p` ([`LoadOptions::from_params`]).
pub fn open_bytes_with(s: &mut Session, name: &str, bytes: &[u8], path: Option<String>, p: &Value) -> Result<Value> {
let update_links = s.prefs.update_links == "automatically";
open_read(s, read_for_open(name, bytes, path, p, update_links, s.prefs.low_res_proxy_eps)?)
let p = s.prefs.with_pdf_font_choice(p);
open_read(s, read_for_open(name, bytes, path, &p, update_links, s.prefs.low_res_proxy_eps)?)
}
/// A file read for `document.open` but not opened yet ([`read_for_open`], [`open_read`]).
@@ -860,7 +864,11 @@ impl ReadFile {
let Some((update_links, low_res_proxy_eps)) = self.links_left.take() else { return };
let base = crate::cmd::links::LinkBase::file(self.path.as_deref());
self.links = crate::cmd::links::resolve(&mut self.loaded.doc, base, update_links, low_res_proxy_eps);
Session::refresh_text_bounds(&mut self.loaded.doc);
for note in Session::refresh_text_bounds(&mut self.loaded.doc) {
if !self.loaded.warnings.contains(&note) {
self.loaded.warnings.push(note);
}
}
}
/// The policies with the profile answer and the color mode `colorMode` asks for, once; the
+25 -7
View File
@@ -7,7 +7,9 @@
//! about the point the object turns about: in points in OBJ and USD (whose layer says how many
//! meters a unit is), in meters in glTF, as its specification asks. glTF and USD colors are linear,
//! as their specifications ask; MTL colors are the display colors. Materials are two-sided, since
//! an open solid or a turned plane is seen from both sides.
//! an open solid or a turned plane is seen from both sides. Every corner carries its normal and
//! texture coordinates (`vt`, `TEXCOORD_0`, `primvars:st`); a mesh whose lists do not match, or
//! that holds a value that is not a number, is refused before anything is written.
//!
//! The graphics mapped onto a face of a solid ([`textures`]) are a PNG picture of that face: its
//! color with the graphics drawn over it, flat and unshaded, which the face's own mesh shows through
@@ -140,6 +142,7 @@ pub(crate) fn image_maps(textures: &[Option<Texture>]) -> Vec<bool> {
/// OBJ with its MTL after it and the PNG files of `textures` last (an OBJ's opacity maps each after
/// its texture). `textures` holds the picture of each part that has one, in the order of `parts`.
pub(crate) fn mesh_files(stem: &str, format: &str, parts: &[SolidMesh], textures: &[Option<Texture>]) -> Result<Vec<(String, Vec<u8>)>, String> {
check_parts(parts)?;
let (images, image) = images(parts.len(), textures);
let maps: Vec<bool> = images.iter().map(|(_, map)| map.is_some()).collect();
let names = mesh_file_names(stem, format, &maps)?;
@@ -180,6 +183,21 @@ impl Scene<'_> {
let t = self.textures.get(k)?.as_ref()?;
Some((t.uv.as_slice(), (*self.image.get(k)?)?))
}
/// Part `k`'s texture coordinates, one for each corner, 0 to 1 across from the left and down
/// from the top: its picture's when it has one, else its mesh's own.
fn coords(&self, k: usize) -> Option<&[[f64; 2]]> {
let count = self.parts.get(k)?.mesh.positions.len();
let own = self.parts.get(k).map(|p| p.mesh.uvs.as_slice());
self.texture(k).map(|(uv, _)| uv).into_iter().chain(own).find(|uv| uv.len() == count && count > 0)
}
}
/// An error when a part's mesh cannot be written as it is: its lists do not match, or a
/// position, normal or texture coordinate is not a number
/// ([`vectorcraft_render::effects::Mesh::check`]).
fn check_parts(parts: &[SolidMesh]) -> Result<(), String> {
parts.iter().try_for_each(|p| p.mesh.check())
}
/// A material: a color, with a picture that replaces its red, green and blue.
@@ -230,7 +248,7 @@ fn obj(stem: &str, scene: &Scene) -> (String, String) {
}
// OBJ's texture coordinates run up from the picture's bottom.
for k in 0..parts.len() {
for uv in scene.texture(k).map(|(uv, _)| uv).unwrap_or_default() {
for uv in scene.coords(k).unwrap_or_default() {
let _ = writeln!(o, "vt {} {}", num(uv[0]), num(1.0 - uv[1]));
}
}
@@ -243,9 +261,9 @@ fn obj(stem: &str, scene: &Scene) -> (String, String) {
for (k, p) in parts.iter().enumerate() {
let _ = writeln!(o, "g Solid_{}", k + 1);
let _ = writeln!(o, "usemtl Material_{}", material.get(k).copied().unwrap_or(0) + 1);
let textured = scene.texture(k).filter(|(uv, _)| uv.len() == p.mesh.positions.len()).is_some();
let coords = scene.coords(k).is_some();
for t in &p.mesh.triangles {
if textured {
if coords {
let [a, b, c] = t.map(|i| i as usize);
let corner = |i: usize| format!("{}/{}/{}", i + base, i + uv_base, i + base);
let _ = writeln!(o, "f {} {} {}", corner(a), corner(b), corner(c));
@@ -255,7 +273,7 @@ fn obj(stem: &str, scene: &Scene) -> (String, String) {
}
}
base += p.mesh.positions.len();
uv_base += scene.texture(k).map_or(0, |(uv, _)| uv.len());
uv_base += scene.coords(k).map_or(0, <[_]>::len);
}
let mut m = String::new();
for (k, mat) in materials.iter().enumerate() {
@@ -313,7 +331,7 @@ fn gltf(stem: &str, scene: &Scene) -> String {
"material": material.get(k).copied().unwrap_or(0),
});
// glTF's texture coordinates run down from the picture's top, as the picture's own do.
if let Some((uv, _)) = scene.texture(k).filter(|(uv, _)| uv.len() == count) {
if let Some(uv) = scene.coords(k) {
let bytes = uv.iter().flatten().flat_map(|x| (*x as f32).to_le_bytes()).collect();
let coords = view(&mut buffer, bytes, 34962);
primitive["attributes"]["TEXCOORD_0"] = json!(accessors.len());
@@ -415,7 +433,7 @@ fn usda(stem: &str, scene: &Scene) -> String {
);
let _ = writeln!(u, " float[] primvars:displayOpacity = [{}] (\n interpolation = \"constant\"\n )", c[3]);
// USD's texture coordinates run up from the picture's bottom.
if let Some((uv, _)) = scene.texture(k).filter(|(uv, _)| uv.len() == p.mesh.positions.len()) {
if let Some(uv) = scene.coords(k) {
let st = list(uv.iter().map(|t| format!("({}, {})", num(t[0]), num(1.0 - t[1]))).collect());
let _ = writeln!(u, " texCoord2f[] primvars:st = [{st}] (\n interpolation = \"vertex\"\n )");
}
+49 -13
View File
@@ -1,12 +1,18 @@
use serde_json::Value;
use vectorcraft_render::effects::{Mesh, SolidMesh};
use vectorcraft_render::effects::{Mesh, MeshPart, SolidMesh};
use super::*;
/// A 10 × 10 square facing the viewer: two triangles, each with corners of its own.
fn square(color: [f32; 4]) -> SolidMesh {
let [a, b, c, d] = [[-5.0, -5.0, 0.0], [5.0, -5.0, 0.0], [5.0, 5.0, 0.0], [-5.0, 5.0, 0.0]];
let mesh = Mesh { positions: vec![a, b, c, a, c, d], normals: vec![[0.0, 0.0, 1.0]; 6], triangles: vec![[0, 1, 2], [3, 4, 5]] };
let mesh = Mesh {
positions: vec![a, b, c, a, c, d],
normals: vec![[0.0, 0.0, 1.0]; 6],
uvs: vec![[0.0, 1.0], [1.0, 1.0], [1.0, 0.0], [0.0, 1.0], [1.0, 0.0], [0.0, 0.0]],
triangles: vec![[0, 1, 2], [3, 4, 5]],
parts: vec![MeshPart::Front; 2],
};
SolidMesh::plain(mesh, color)
}
@@ -31,8 +37,9 @@ fn obj_numbers_corners_across_solids_and_names_its_materials() {
assert!(obj.starts_with("mtllib Box.mtl\no Box\n"));
assert_eq!(obj.lines().filter(|l| l.starts_with("v ")).count(), 18);
assert_eq!(obj.lines().filter(|l| l.starts_with("vn ")).count(), 18);
assert_eq!(obj.lines().filter(|l| l.starts_with("vt ")).count(), 18);
// The third solid's last triangle uses corners 13 to 18; red solids share Material_1.
assert_eq!(obj.lines().rfind(|l| l.starts_with("f ")), Some("f 16//16 17//17 18//18"));
assert_eq!(obj.lines().rfind(|l| l.starts_with("f ")), Some("f 16/16/16 17/17/17 18/18/18"));
assert_eq!(obj.lines().filter(|l| l.starts_with("usemtl ")).collect::<Vec<_>>(), ["usemtl Material_1", "usemtl Material_2", "usemtl Material_1"]);
let mtl = text(&files, "Box.mtl");
assert_eq!(mtl.matches("newmtl").count(), 2);
@@ -64,8 +71,12 @@ fn gltf_holds_its_buffer_and_every_accessor_fits_it() {
assert_eq!(g["materials"][1]["alphaMode"], "BLEND");
assert!(g["materials"][0].get("alphaMode").is_none());
assert_eq!(g["materials"][0]["doubleSided"], true);
// Without graphics there are no textures.
assert!(g.get("images").is_none() && g.get("textures").is_none() && prims[0]["attributes"].get("TEXCOORD_0").is_none());
// Without graphics there are no textures, but every corner has its mesh's texture coordinates.
assert!(g.get("images").is_none() && g.get("textures").is_none());
for p in prims {
let uv = &g["accessors"][p["attributes"]["TEXCOORD_0"].as_u64().unwrap() as usize];
assert_eq!((uv["type"].as_str(), uv["count"].as_u64()), (Some("VEC2"), Some(6)));
}
}
#[test]
@@ -82,7 +93,28 @@ fn usda_is_y_up_in_points_with_a_material_for_each_color() {
// sRGB 0.5 is about 0.214 linear.
assert!(u.contains("color3f inputs:diffuseColor = (0.21404"), "{u}");
assert_eq!(u.matches('{').count(), u.matches('}').count());
assert!(!u.contains("primvars:st") && !u.contains("UsdUVTexture"));
// Each mesh carries its own texture coordinates, up from the bottom, with no picture to show.
assert_eq!(u.matches("texCoord2f[] primvars:st = [(0, 0), (1, 0), (1, 1), (0, 0), (1, 1), (0, 1)]").count(), 2, "{u}");
assert!(!u.contains("UsdUVTexture"));
}
#[test]
fn a_mesh_whose_lists_do_not_match_or_hold_no_number_is_refused() {
let good = square(RED);
let mut nan = square(RED);
nan.mesh.uvs[2] = [f64::NAN, 0.0];
let mut infinite = square(RED);
infinite.mesh.normals[0] = [f64::INFINITY, 0.0, 0.0];
let mut short = square(RED);
short.mesh.uvs.pop();
let mut unnamed = square(RED);
unnamed.mesh.parts.pop();
for bad in [nan, infinite, short, unnamed] {
for format in FORMATS_3D {
assert!(plain_files("Box", format, &[good.clone(), bad.clone()]).is_err(), "{format} {bad:?}");
}
}
assert!(plain_files("Box", "obj", &[good]).is_ok());
}
#[test]
@@ -141,7 +173,10 @@ fn prim_names_are_usd_identifiers() {
fn textured(png: &[u8]) -> (Vec<SolidMesh>, Vec<Option<Texture>>) {
let uv = vec![[0.0, 1.0], [1.0, 1.0], [1.0, 0.0], [0.0, 1.0], [1.0, 0.0], [0.0, 0.0]];
let texture = Texture { png: Arc::new(png.to_vec()), opacity: None, uv };
(vec![square(RED), square(BLUE)], vec![None, Some(texture)])
// The picture's coordinates replace the mesh's own.
let mut blue = square(BLUE);
blue.mesh.uvs = vec![[0.25, 0.25]; 6];
(vec![square(RED), blue], vec![None, Some(texture)])
}
#[test]
@@ -154,16 +189,18 @@ fn each_format_carries_a_textured_part_with_its_coordinates_and_picture() {
assert_eq!(files.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["My_Box.obj", "My_Box.mtl", "My_Box-texture-1.png"]);
assert_eq!(files[2].1, png);
let obj = text(&files, "My_Box.obj");
assert_eq!(obj.lines().filter(|l| l.starts_with("vt ")).collect::<Vec<_>>(), ["vt 0 0", "vt 1 0", "vt 1 1", "vt 0 0", "vt 1 1", "vt 0 1"]);
assert_eq!(obj.lines().rfind(|l| l.starts_with("f ")), Some("f 10/4/10 11/5/11 12/6/12"));
assert!(obj.contains("f 1//1 2//2 3//3"), "the plain part keeps no texture coordinates");
// The plain part's own coordinates come first, then the textured part's picture's.
let square_vt = ["vt 0 0", "vt 1 0", "vt 1 1", "vt 0 0", "vt 1 1", "vt 0 1"];
assert_eq!(obj.lines().filter(|l| l.starts_with("vt ")).collect::<Vec<_>>(), [square_vt, square_vt].concat());
assert_eq!(obj.lines().rfind(|l| l.starts_with("f ")), Some("f 10/10/10 11/11/11 12/12/12"));
assert!(obj.contains("f 1/1/1 2/2/2 3/3/3"), "the plain part keeps its mesh's texture coordinates");
let mtl = text(&files, "My_Box.mtl");
assert!(mtl.contains("newmtl Material_2\nKd 1 1 1\nd 1\nillum 1\nmap_Kd -clamp on My_Box-texture-1.png\n"), "{mtl}");
assert_eq!(mtl.matches("map_Kd").count(), 1);
// glTF: TEXCOORD_0 down from the top, and the picture embedded as a data URI.
let g: Value = serde_json::from_str(&text(&mesh_files("Box", "gltf", &parts, &pictures).unwrap(), "Box.gltf")).unwrap();
let prims = g["meshes"][0]["primitives"].as_array().unwrap();
assert!(prims[0]["attributes"].get("TEXCOORD_0").is_none());
assert!(prims[0]["attributes"].get("TEXCOORD_0").is_some(), "the plain part keeps its mesh's texture coordinates");
let uv = &g["accessors"][prims[1]["attributes"]["TEXCOORD_0"].as_u64().unwrap() as usize];
assert_eq!((uv["type"].as_str(), uv["count"].as_u64(), uv["componentType"].as_u64()), (Some("VEC2"), Some(6), Some(5126)));
let view = &g["bufferViews"][uv["bufferView"].as_u64().unwrap() as usize];
@@ -182,8 +219,7 @@ fn each_format_carries_a_textured_part_with_its_coordinates_and_picture() {
let files = mesh_files("Box", "usda", &parts, &pictures).unwrap();
assert_eq!(files.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Box.usda", "Box-texture-1.png"]);
let u = text(&files, "Box.usda");
assert_eq!(u.matches("primvars:st").count(), 1);
assert!(u.contains("texCoord2f[] primvars:st = [(0, 0), (1, 0), (1, 1), (0, 0), (1, 1), (0, 1)]"), "{u}");
assert_eq!(u.matches("texCoord2f[] primvars:st = [(0, 0), (1, 0), (1, 1), (0, 0), (1, 1), (0, 1)]").count(), 2, "{u}");
assert!(u.contains("color3f inputs:diffuseColor.connect = </Box/Materials/Material_2/Texture.outputs:rgb>"), "{u}");
assert!(u.contains("asset inputs:file = @Box-texture-1.png@") && u.contains("uniform token info:id = \"UsdUVTexture\""));
assert!(u.contains("float2 inputs:st.connect = </Box/Materials/Material_2/Coordinates.outputs:result>"));
+18 -17
View File
@@ -8,7 +8,10 @@ use std::sync::Arc;
use serde::Deserialize;
use serde_json::{Value, json};
use vectorcraft_doc::{Document, Node, NodeKind};
use vectorcraft_pdf::{Overprint, PdfError, PdfOptions, PdfPreset, PdfSettings, Standard, THUMBNAIL_SIZE, Thumbnail};
use vectorcraft_pdf::{
APP, ActiveProfiles, Overprint, PdfError, PdfOptions, PdfPreset, PdfSettings, Standard, THUMBNAIL_SIZE, Thumbnail, default_preset_name,
leaves_out_bleed, page_bleed,
};
use super::super::flatten::{FlattenOptions, flatten_document, see_through_images};
use super::super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, str_param};
@@ -17,9 +20,6 @@ use crate::EngineError;
const C: &str = "document.exportPdf";
/// The built-in preset every PDF export starts from.
pub use vectorcraft_pdf::DEFAULT_PRESET;
/// The PDF options `document.formats` lists; `document.exportPdf` documents every field.
pub(crate) const OPTIONS: &[FormatOption] = &[
super::ARTBOARD,
@@ -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
),
@@ -151,13 +151,13 @@ pub fn presets(s: &Session) -> Vec<String> {
/// The built-in preset names, then those of `saved`.
fn names(saved: &[PdfPreset]) -> Vec<String> {
vectorcraft_pdf::builtin_presets().into_iter().map(|p| p.name).chain(saved.iter().map(|p| p.name.clone())).collect()
vectorcraft_pdf::builtin_presets(APP).into_iter().map(|p| p.name).chain(saved.iter().map(|p| p.name.clone())).collect()
}
/// The preset `name` names: a built-in one (any case; `default` is the app default) or one of
/// `saved`.
pub fn find_preset(name: &str, saved: &[PdfPreset]) -> Option<PdfPreset> {
vectorcraft_pdf::builtin_preset(name).or_else(|| saved.iter().find(|p| p.name.eq_ignore_ascii_case(name.trim())).cloned())
vectorcraft_pdf::builtin_preset(name, APP).or_else(|| saved.iter().find(|p| p.name.eq_ignore_ascii_case(name.trim())).cloned())
}
fn preset(cmd: &str, name: &str, saved: &[PdfPreset]) -> Result<PdfSettings> {
@@ -166,9 +166,10 @@ fn preset(cmd: &str, name: &str, saved: &[PdfPreset]) -> Result<PdfSettings> {
.ok_or_else(|| bad(cmd, format!("unknown PDF preset `{name}` (presets: {})", names(saved).join(", "))))
}
/// The settings of the preset `p` names (default: [`DEFAULT_PRESET`]), before `p`'s options.
/// The settings of the preset `p` names (default: [`default_preset_name`]), before `p`'s options.
pub fn preset_settings(cmd: &str, p: &Value, saved: &[PdfPreset]) -> Result<PdfSettings> {
preset(cmd, str_param(p, "preset").unwrap_or(DEFAULT_PRESET), saved)
let default = default_preset_name(APP);
preset(cmd, str_param(p, "preset").unwrap_or(&default), saved)
}
/// Merge `over` into `base`: objects key by key (recursively), `null` keeps the base (the
@@ -194,7 +195,7 @@ pub(crate) fn pdf_error(cmd: &str, e: PdfError) -> EngineError {
}
/// The settings `p` asks for: its preset (built-in or one of `saved`; default
/// [`DEFAULT_PRESET`]) with `p`'s options applied over it. Choosing another standard turns
/// [`default_preset_name`]) with `p`'s options applied over it. Choosing another standard turns
/// Preserve Editing off, the layers off where it has none, and sets the latest compatibility it
/// allows, unless `p` asks for those. Checked as a preset is
/// ([`PdfSettings::check_values`]): profiles that aren't there pass. Keys that aren't PDF options
@@ -219,14 +220,14 @@ pub fn resolve(cmd: &str, p: &Value, saved: &[PdfPreset]) -> Result<PdfSettings>
s.compatibility = s.standard.version();
}
}
s.check_values().map_err(|e| pdf_error(cmd, e))?;
s.check_values().map_err(|e| pdf_error(cmd, e.into()))?;
Ok(s)
}
/// [`resolve`], refusing what the writer can't honour ([`PdfSettings::check`]).
pub fn settings_with(cmd: &str, p: &Value, saved: &[PdfPreset]) -> Result<PdfSettings> {
let s = resolve(cmd, p, saved)?;
s.check().map_err(|e| pdf_error(cmd, e))?;
s.check(&ActiveProfiles::default()).map_err(|e| pdf_error(cmd, e.into()))?;
Ok(s)
}
@@ -240,7 +241,7 @@ pub fn settings(cmd: &str, p: &Value) -> Result<PdfSettings> {
/// built-in presets. Params naming none come back as they are.
pub fn expand_preset<'a>(s: &Session, cmd: &str, p: &'a Value) -> Result<Cow<'a, Value>> {
let expanded = match str_param(p, "preset") {
Some(name) if vectorcraft_pdf::builtin_preset(name).is_none() => {
Some(name) if vectorcraft_pdf::builtin_preset(name, APP).is_none() => {
let set = settings_with(cmd, p, &s.prefs.pdf_presets)?;
let mut q = p.clone();
merge(&mut q, &serde_json::to_value(set).map_err(|e| EngineError::Other(e.to_string()))?);
@@ -316,7 +317,7 @@ pub(super) fn art_page(cmd: &str, doc: &Document, p: &Value) -> Result<Option<(D
}
/// The warning for a PDF/X file that leaves out the document's bleed
/// ([`vectorcraft_pdf::PdfSettings::leaves_out_bleed`]).
/// ([`vectorcraft_pdf::leaves_out_bleed`]).
pub const BLEED_LEFT_OUT: &str = "the document sets a bleed that this PDF/X file leaves out: turn on Use document bleed settings";
/// How far, in points, an object's edge may sit inside the trim edge, or short of the bleed edge,
@@ -579,7 +580,7 @@ fn encode_carrying_at(
// createLayers writes non-printing layers with /PrintState /OFF, so they count only with
// includeNonPrinting, which writes them as printing art.
let set = &opts.settings;
let short = if bleed_check { short_of_bleed(doc, set.bleed_of(doc), opts.artboards.as_deref(), set.include_non_printing) } else { 0 };
let short = if bleed_check { short_of_bleed(doc, page_bleed(&set.bleed, doc), opts.artboards.as_deref(), set.include_non_printing) } else { 0 };
// The pages' background colors, behind the art (the editing data keeps them as colors).
let pages = opts.artboards.clone().unwrap_or_else(|| (0..doc.artboards.len()).collect());
let filled = super::export::with_artboard_fills(doc, p, pages).map_err(|e| bad(cmd, e))?;
@@ -592,7 +593,7 @@ fn encode_carrying_at(
let mut notes = vec![];
// A loss, ahead of the flattening note: the PDF/X pages leave out the bleed that Document
// Setup gives.
if opts.settings.leaves_out_bleed(doc) {
if leaves_out_bleed(&opts.settings, doc) {
notes.push(Note::loss(BLEED_LEFT_OUT));
}
// Art that reaches the trim edge but leaves part of the page's bleed empty.
@@ -760,7 +761,7 @@ fn pdf_settings(s: &mut Session, p: &Value) -> Result<Value> {
};
note_texts(&notes)
}
_ => set.warnings(),
_ => set.warnings(&ActiveProfiles::default()).into_iter().map(|w| w.message).collect(),
};
let v = serde_json::to_value(&set).map_err(|e| EngineError::Other(e.to_string()))?;
Ok(json!({ "settings": v, "presets": presets(s), "changed": diff, "warnings": warnings }))
+21 -2
View File
@@ -47,6 +47,10 @@ pub struct LoadOptions {
/// A `.ai` opens from its editing copy even where that draws differently from its PDF part
/// (which can be older than it), with a warning, instead of from the PDF part.
pub trust_editing_data: bool,
/// A PDF's type in a font it embeds and this machine lacks is drawn in the file's own glyphs
/// (default; the `embeddedFonts` param, and Preferences › File Handling › Use fonts embedded in
/// imported PDFs for opens and places that give none).
pub embedded_fonts: bool,
/// The encoding names in a `.ai` or EPS's editing data are read in when they aren't UTF-8
/// (`legacyNameEncoding`).
pub legacy_names: vectorcraft_eps::NameEncoding,
@@ -74,6 +78,7 @@ impl Default for LoadOptions {
editing_data: true,
trust_editing_data: false,
legacy_names: vectorcraft_eps::NameEncoding::default(),
embedded_fonts: true,
native: true,
link_pages: false,
}
@@ -84,7 +89,7 @@ impl LoadOptions {
/// From command params: `pages` (`"2-3, 5"`, a page number or `"all"`), `page` (one page, when
/// `pages` isn't given), `cropTo` (or `crop`), `password`, `colorMode` (`rgb` | `cmyk`) with `grays`,
/// `textAs` (`text` | `outlines`), `layers` (true | false), `hiddenLayers` (true | false),
/// `importSlices` (true | false), `editingData` (true | false | `always`),
/// `importSlices` (true | false), `editingData` (true | false | `always`), `embeddedFonts` (true | false),
/// `legacyNameEncoding` (one of [`vectorcraft_eps::NameEncoding::LABELS`]), `linkPages` (true |
/// false) and `dxf` (the DXF import options).
pub fn from_params(cmd: &str, p: &Value) -> Result<Self> {
@@ -135,6 +140,10 @@ impl LoadOptions {
Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "linkPages must be true or false"))?,
};
let dxf = super::dxfimport::options(cmd, p.get("dxf"))?;
let embedded_fonts = match p.get("embeddedFonts").filter(|v| !v.is_null()) {
None => true,
Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "embeddedFonts must be true or false"))?,
};
Ok(Self {
pages,
crop,
@@ -148,6 +157,7 @@ impl LoadOptions {
dxf,
editing_data,
trust_editing_data,
embedded_fonts,
legacy_names,
native: true,
link_pages,
@@ -177,6 +187,7 @@ impl LoadOptions {
text_as: self.text_as,
layers: self.layers,
uncalibrated_rgb: editor_document,
embedded_fonts: self.embedded_fonts,
..Default::default()
})
}
@@ -219,7 +230,15 @@ pub(crate) fn opened_page_document(bytes: &[u8], opened: &vectorcraft_pdf::Opene
/// The import options of [`page_document`].
fn page_options(page: usize, o: &LoadOptions) -> ImportOptions {
ImportOptions { pages: Some(vec![page]), crop: o.crop, password: o.password.clone(), text_as: o.text_as, layers: false, ..Default::default() }
ImportOptions {
pages: Some(vec![page]),
crop: o.crop,
password: o.password.clone(),
text_as: o.text_as,
layers: false,
embedded_fonts: o.embedded_fonts,
..Default::default()
}
}
/// Whether `document.open`'s `linkPages` takes the file `name` holding `bytes`: a PDF or a
File diff suppressed because it is too large. Load diff
+5 -1
View File
@@ -1148,10 +1148,14 @@ impl SaveJob {
/// Once written: Save and Save As (except to a template) make the file `st`'s own: path,
/// title, format, options, and the snapshot as the saved state (edits made since the job was
/// made keep the document modified; changes that are not edits to save don't,
/// [`DocState::same_content`]).
/// [`DocState::same_content`]). Saved outside a command a script runs, from the document's
/// content as it is now, the document is as the person left it ([`DocState::by_script`]).
pub fn finish(self, st: &mut DocState) {
let retargets = self.plan.retargets();
if let (true, Some(path)) = (retargets, self.plan.path) {
if !crate::file_access::in_script_command() && st.same_content(&self.source) {
st.by_script = None;
}
st.path = Some(path);
st.format = self.plan.format.id;
st.save_options = self.plan.options;
+5 -4
View File
@@ -2,7 +2,8 @@
use serde_json::{Value, json};
use super::pdf::DEFAULT_PRESET;
use vectorcraft_pdf::{APP, default_preset_name};
use super::*;
fn session(artboards: usize) -> Session {
@@ -310,7 +311,7 @@ fn bad_options_are_refused() {
#[test]
fn options_apply_over_the_preset() {
let mut s = session(1);
let a = b64(&export(&mut s, json!({"preset": DEFAULT_PRESET, "compression": {"compressText": false}})));
let a = b64(&export(&mut s, json!({"preset": default_preset_name(APP), "compression": {"compressText": false}})));
let b = b64(&export(&mut s, json!({"preset": "default"})));
assert!(a.len() > b.len(), "content streams left uncompressed");
assert!(String::from_utf8_lossy(&a).contains(" re") || String::from_utf8_lossy(&a).contains(" l"));
@@ -499,7 +500,7 @@ fn pdf_settings_summarise_changes_and_warnings() {
let mut s = Session::new();
let v = s.execute("document.pdfSettings", &json!({})).unwrap();
assert_eq!(v["settings"]["compatibility"], "1.7");
assert_eq!(v["presets"][0], DEFAULT_PRESET);
assert_eq!(v["presets"][0], default_preset_name(APP));
assert_eq!(v["changed"], json!([]));
assert_eq!(v["warnings"], json!([]));
let p = json!({"compatibility": "1.5", "compression": {"compressText": false}, "createLayers": true, "security": {"copy": false, "openPassword": ""}});
@@ -544,5 +545,5 @@ fn formats_list_the_pdf_options() {
assert!(pdf["options"].get(k).is_some(), "{k}");
}
assert_eq!(pdf["options"]["compatibility"]["default"], "1.7");
assert_eq!(pdf["options"]["preset"]["default"], DEFAULT_PRESET);
assert_eq!(pdf["options"]["preset"]["default"], default_preset_name(APP));
}
@@ -3,7 +3,7 @@
use serde_json::{Value, json};
use vectorcraft_doc::NodeKind;
use vectorcraft_pdf::TextAs;
use vectorcraft_testkit::pdf::{PdfPage, first_extra, pdf, pdf_with_catalog};
use vectorcraft_testkit::pdf::{PdfPage, first_extra, pdf, pdf_with, pdf_with_catalog};
use super::*;
@@ -135,11 +135,12 @@ fn ai_layer_names_are_read_as_pdf_doc_encoding() {
#[test]
fn load_options_read_text_and_layers() {
let o = LoadOptions::from_params("x", &json!({"textAs": "Outlines", "layers": false})).unwrap();
assert_eq!((o.text_as, o.layers), (TextAs::Outlines, false));
let o = LoadOptions::from_params("x", &json!({"textAs": "Outlines", "layers": false, "hiddenLayers": true, "embeddedFonts": false})).unwrap();
assert_eq!((o.text_as, o.layers, o.hidden_layers, o.embedded_fonts), (TextAs::Outlines, false, true, false));
assert!(o.is_partial(), "without its hidden layers, Save doesn't write the file back");
let d = LoadOptions::default();
assert_eq!((d.text_as, d.layers, d.is_partial()), (TextAs::Text, true, false));
assert_eq!((d.hidden_layers, d.embedded_fonts), (false, true));
let n = LoadOptions { native: false, ..Default::default() };
assert!(n.is_partial(), "without the document it carries, Save doesn't write the file back");
}
@@ -180,3 +181,415 @@ fn exports_that_draw_type_in_a_missing_font_say_it_is_the_fallback_font() {
s.execute("text.replaceFont", &json!({"from": {"family": family}, "to": {"family": "Source Serif 4"}})).unwrap();
assert!(!warned(&mut s, json!({"format": "pdf"})), "replaced: nothing is substituted");
}
/// A page in a font the file carries that no machine has (`Zyxwvu-Serif`: a
/// simple TrueType font in WinAnsiEncoding, its program the bundled Source Serif 4's).
fn carried_font_pdf(content: &str, height: f64) -> Vec<u8> {
let data = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/fonts/SourceSerif4-Regular.ttf")).unwrap();
let face = vectorcraft_text::FontDb::global().face("Source Serif 4", "Regular").unwrap();
let widths: Vec<String> =
(32u8..=126).map(|c| format!("{:.0}", face.advance(face.glyph_for(char::from(c))) * 1000.0 / face.units_per_em())).collect();
let hex: String = data.iter().map(|b| format!("{b:02x}")).collect();
let n = first_extra(1);
let page = PdfPage { resources: format!("/Font << /F1 {n} 0 R >>"), ..PdfPage::new(300.0, height, content) };
let font = format!(
"<< /Type /Font /Subtype /TrueType /BaseFont /ABCDEF+Zyxwvu-Serif /FirstChar 32 /LastChar 126 /Widths [{}] /Encoding /WinAnsiEncoding /FontDescriptor {} 0 R >>",
widths.join(" "),
n + 1
);
let descriptor = format!(
"<< /Type /FontDescriptor /FontName /ABCDEF+Zyxwvu-Serif /Flags 34 /FontBBox [-500 -300 1500 1000] /ItalicAngle 0 /Ascent 900 /Descent -300 /CapHeight 660 /StemV 80 /FontFile2 {} 0 R >>",
n + 2
);
let file = format!("<< /Length {} /Filter /ASCIIHexDecode >>\nstream\n{hex}>\nendstream", hex.len() + 1);
pdf_with(&[page], &[&font, &descriptor, &file], None)
}
/// The glyphs of the active document's type (document space origins) and how many come from fonts
/// files carried.
fn glyphs(s: &Session) -> (Vec<kurbo::Point>, usize) {
let db = vectorcraft_text::FontDb::global();
let (mut at, mut carried) = (vec![], 0);
s.doc().unwrap().doc.walk(|n| {
if let NodeKind::Text(t) = &n.kind {
for g in vectorcraft_text::layout(db, t).glyphs {
at.push(t.xf * g.origin);
carried += usize::from(db.is_file_font(g.font_id));
}
}
});
(at, carried)
}
/// Type in a font the PDF carries that isn't installed keeps the file's look until it is edited:
/// no export says it is substituted, it saves and reopens so, and it stays listed as missing. Edited,
/// it takes the substitute, which exports then name.
#[test]
fn type_in_a_font_the_pdf_carries_keeps_its_look_until_edited() {
let mut s = Session::new();
let r = open(&mut s, &carried_font_pdf("BT /F1 24 Tf 20 50 Td (Hamburg Zoo) Tj ET", 100.0), json!({})).unwrap();
let fonts = s.execute("text.fonts", &json!({})).unwrap();
let family = fonts[0]["family"].as_str().unwrap().to_string();
assert_eq!(fonts[0]["status"], "missing", "{fonts}");
assert!(r["warnings"].to_string().contains("until their text is edited"), "{r}");
let missing = s.execute("text.missingFonts", &json!({})).unwrap();
assert!(missing["fonts"].to_string().contains(&family), "still missing: {missing}");
let (at, carried) = glyphs(&s);
assert_eq!((at.len(), carried), (11, 11), "every glyph the file's");
let warned = |s: &mut Session| s.execute("document.serialize", &json!({"format": "png"})).unwrap()["warnings"].to_string().contains(&family);
assert!(!warned(&mut s), "drawn as the file draws it: not substituted");
// Saved and opened again: the same.
let native = s.execute("document.serialize", &json!({"format": "vectorcraft"})).unwrap()["dataBase64"].as_str().unwrap().to_string();
s.execute("document.open", &json!({"name": "kept.vectorcraft", "dataBase64": native})).unwrap();
assert_eq!(glyphs(&s), (at.clone(), carried));
// Edited: the substitute, which exports name, and the font still missing.
let mut id = None;
s.doc().unwrap().doc.walk(|n| {
if matches!(n.kind, NodeKind::Text(_)) {
id = Some(n.id);
}
});
let id = id.unwrap();
let preflight = |s: &mut Session| s.execute("document.preflight", &json!({})).unwrap()["findings"].clone();
assert!(!preflight(&mut s).to_string().contains(&family), "carried font is not substituted");
s.execute("text.setText", &json!({"id": id, "text": "Hamburg Zoo!"})).unwrap();
assert_eq!(glyphs(&s).1, 0, "edited: no glyph from the file's font");
assert!(warned(&mut s), "edited: substituted");
let findings = preflight(&mut s);
assert!(
findings.as_array().unwrap().iter().any(|f| f["code"] == "missingFont"
&& f["name"].as_str().is_some_and(|n| n.contains(&family))
&& f["ids"].as_array().is_some_and(|ids| ids.contains(&json!(id.0)))),
"preflight identifies the substituted text owner: {findings}"
);
assert!(s.execute("text.missingFonts", &json!({})).unwrap()["fonts"].to_string().contains(&family));
// Undone: the file's look again.
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(glyphs(&s), (at, carried));
assert!(!preflight(&mut s).to_string().contains(&family), "undo restores the carried font");
}
#[test]
fn wrapped_carried_font_keeps_pdf_positions_after_native_reopen() {
let db = vectorcraft_text::FontDb::global();
let serif = db.face("Source Serif 4", "Regular").unwrap();
let fallback = db.face(vectorcraft_text::FALLBACK_FAMILY, "Regular").unwrap();
let advance = |face: &vectorcraft_text::FontFace| face.advance(face.glyph_for('H')) / face.units_per_em();
assert!((advance(&serif) - advance(&fallback)).abs() > 0.01, "fixture must differ from the substitute");
let content = "BT /F1 24 Tf 20 160 Td (Hamburg Zoo ) Tj ET BT /F1 24 Tf 20 100 Td (Hamburg Zoo ) Tj ET BT /F1 24 Tf 20 40 Td (Hamburg Zoo) Tj ET";
let bytes = carried_font_pdf(content, 200.0);
let mut reference = Session::new();
open(&mut reference, &bytes, json!({"textAs": "outlines"})).unwrap();
let want = glyph_ink(&reference, false);
assert_eq!(want.len(), 3);
let mut s = Session::new();
open(&mut s, &bytes, json!({})).unwrap();
let compare = |s: &Session| {
let mut areas = 0;
s.doc().unwrap().doc.walk(|n| {
if let NodeKind::Text(t) = &n.kind {
assert!(matches!(t.kind, vectorcraft_doc::TextKind::Area { .. }), "wrapped text must stay one area");
assert_eq!(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).lines.len(), 3);
areas += 1;
}
});
assert_eq!(areas, 1);
let got = glyph_ink(s, false);
assert_eq!(got.len(), want.len());
for (got, want) in got.iter().zip(&want) {
let off = (got.x0 - want.x0).abs().max((got.x1 - want.x1).abs()).max((got.y0 - want.y0).abs()).max((got.y1 - want.y1).abs());
assert!(off < 0.25, "{got:?} is {off} pt from {want:?}");
}
};
compare(&s);
let native = s.execute("document.serialize", &json!({"format": "vectorcraft"})).unwrap()["dataBase64"].as_str().unwrap().to_string();
s.execute("document.open", &json!({"name": "wrapped.vectorcraft", "dataBase64": native})).unwrap();
compare(&s);
}
fn owned_font_document(family: &str, width: f64) -> (vectorcraft_doc::Document, vectorcraft_doc::ImageBlob, vectorcraft_doc::NodeId) {
use kurbo::{Point, Rect, Shape};
use vectorcraft_doc::{CharStyle, Document, FILE_FONT_MIME, FileFont, FileFonts, ImageBlob, Node, TextObject};
use vectorcraft_text::{FileFontInfo, FileGlyph, build_file_font};
let info = FileFontInfo { family: family.into(), style: "Regular".into(), ..Default::default() };
let g = FileGlyph { ch: 'x', outline: Rect::new(0.0, 0.0, width, 700.0).to_path(0.1), advance: width + 100.0 };
let blob = ImageBlob::new(FILE_FONT_MIME, build_file_font(&info, &[g]).unwrap());
let mut doc = Document::new(100.0, 100.0);
doc.images.insert("chosen".into(), blob.clone());
let mut t = TextObject::point(Point::new(10.0, 40.0), "x", CharStyle { font_family: family.into(), size: 20.0, ..Default::default() });
t.file_fonts = Some(Box::new(FileFonts::new(vec![FileFont { family: family.into(), style: "Regular".into(), key: "chosen".into() }], "x")));
let id = doc.alloc_id();
doc.insert(Some(doc.layers[0].id), usize::MAX, Node::new(id, NodeKind::Text(Box::new(t)))).unwrap();
(doc, blob, id)
}
/// No machine fonts are needed: the two native documents own different synthetic glyphs under
/// the same key. Paste must relink its own bytes, including after closing the source tab.
#[test]
fn owned_file_fonts_survive_native_open_close_clipboard_undo_and_export() {
use vectorcraft_doc::Document;
use vectorcraft_text::FontDb;
const FAMILY: &str = "Native Owned File Font Regression";
let open_native = |s: &mut Session, doc: &Document| {
let bytes = vectorcraft_format::save_file(doc);
s.execute("document.open", &json!({"name": "font.vectorcraft", "dataBase64": vectorcraft_format::base64_encode(&bytes)})).unwrap()
};
let face_of = |s: &Session, id| {
let NodeKind::Text(t) = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("text") };
let g = &vectorcraft_text::layout(FontDb::global(), t).glyphs[0];
FontDb::global().face_by_id(g.font_id).unwrap()
};
let (a, a_blob, a_id) = owned_font_document(FAMILY, 200.0);
let (b, b_blob, b_id) = owned_font_document(FAMILY, 800.0);
let mut s = Session::new();
open_native(&mut s, &a);
let a_index = s.active_index().unwrap();
assert_eq!(face_of(&s, a_id).file_data(), a_blob.bytes.as_slice());
open_native(&mut s, &b);
let b_index = s.active_index().unwrap();
let carried = face_of(&s, b_id).id();
assert_eq!(face_of(&s, b_id).file_data(), b_blob.bytes.as_slice());
s.execute("select.set", &json!({"ids": [b_id.0]})).unwrap();
s.execute("edit.copy", &json!({})).unwrap();
assert!(s.close_document(b_index));
assert!(s.set_active(a_index));
let pasted = s.execute("edit.pasteInPlace", &json!({})).unwrap();
assert!(pasted["warnings"].as_array().unwrap().is_empty(), "{pasted}");
assert!(pasted["renamed"].as_array().unwrap().iter().any(|v| v["kind"] == "image" && v["from"] == "chosen"));
let id = vectorcraft_doc::NodeId(pasted["ids"][0].as_u64().unwrap());
assert_eq!(face_of(&s, id).id(), carried);
assert_eq!(face_of(&s, id).file_data(), b_blob.bytes.as_slice());
assert_eq!(face_of(&s, a_id).file_data(), a_blob.bytes.as_slice());
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(face_of(&s, id).file_data(), b_blob.bytes.as_slice());
for options in [json!({"format": "pdf", "advanced": {"outlineText": false}}), json!({"format": "svg", "embedFonts": true})] {
let svg = options["format"] == "svg";
let exported = s.execute("document.serialize", &options).unwrap();
if svg {
let text = exported["text"].as_str().unwrap();
assert_eq!(text.matches("@font-face").count(), 2, "both distinct owned faces are embedded");
} else {
let bytes = vectorcraft_format::base64_decode(exported["dataBase64"].as_str().unwrap()).unwrap();
assert!(bytes.starts_with(b"%PDF-"));
}
// SVG may warn that the same CSS description cannot distinguish these two x glyphs.
assert!(!exported["warnings"].to_string().contains(vectorcraft_text::FALLBACK_FAMILY), "{exported}");
}
let saved = s.execute("document.serialize", &json!({"format": "vectorcraft"})).unwrap();
s.execute("document.open", &json!({"name": "pasted.vectorcraft", "dataBase64": saved["dataBase64"]})).unwrap();
assert_eq!(face_of(&s, id).file_data(), b_blob.bytes.as_slice());
assert_eq!(face_of(&s, a_id).file_data(), a_blob.bytes.as_slice());
let mut unowned = b.clone();
unowned.images.clear();
let report = open_native(&mut s, &unowned);
assert!(report["warnings"].to_string().contains(FAMILY));
assert_eq!(glyphs(&s).1, 0, "a metadata-only reference cannot borrow any open document's font");
}
/// Place owns its carried font even after the decoded source is dropped, whether the destination
/// reuses an equal unbound blob or renames a key occupied by another font.
#[test]
fn placed_fonts_keep_owned_bytes_after_resource_reuse_or_name_collision() {
use vectorcraft_doc::Document;
use vectorcraft_text::FontDb;
const FAMILY: &str = "Placed Owned Font Regression";
let (source, expected, _) = owned_font_document(FAMILY, 200.0);
let bytes = vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&source));
for same_bytes in [true, false] {
let mut host = Document::new(100.0, 100.0);
let blob = if same_bytes { expected.clone() } else { owned_font_document(FAMILY, 800.0).1 };
host.images.insert("chosen".into(), blob);
let mut s = Session::new();
s.add_document(host, None);
let placed = s.execute("file.place", &json!({"name": "font.vectorcraft", "dataBase64": bytes, "link": false})).unwrap();
assert!(placed["warnings"].as_array().unwrap().is_empty(), "{placed}");
let check = |s: &Session| {
let db = FontDb::global();
let mut drawn = 0;
s.doc().unwrap().doc.walk(|n| {
if let NodeKind::Text(t) = &n.kind {
for g in vectorcraft_text::layout(db, t).glyphs {
assert!(db.is_file_font(g.font_id), "the destination, not a source cache, owns the font");
assert_eq!(db.face_by_id(g.font_id).unwrap().file_data(), expected.bytes.as_slice());
drawn += 1;
}
}
});
assert_eq!(drawn, 1);
};
check(&s);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(glyphs(&s).1, 0);
s.execute("edit.redo", &json!({})).unwrap();
check(&s);
let saved = s.execute("document.serialize", &json!({"format": "vectorcraft"})).unwrap();
let reopened = s.execute("document.open", &json!({"name": "placed.vectorcraft", "dataBase64": saved["dataBase64"]})).unwrap();
assert!(reopened["warnings"].as_array().unwrap().is_empty(), "{reopened}");
check(&s);
}
}
fn linked_owned_font_document(family: &str) -> (vectorcraft_doc::Document, vectorcraft_doc::ImageBlob, vectorcraft_doc::NodeId) {
use kurbo::Affine;
use vectorcraft_doc::{Document, ImageBlob, LinkInfo, Node, PlacedDocument};
let (source, expected, _) = owned_font_document(family, 200.0);
let bytes = vectorcraft_format::save_file(&source);
let blob = ImageBlob::new("application/json", bytes);
let key = format!("placed-font-{}", blob.content_key());
let mut host = Document::new(100.0, 100.0);
host.images.insert("chosen".into(), owned_font_document(family, 800.0).1);
host.images.insert(key.clone(), blob);
let placed = PlacedDocument {
key,
link: LinkInfo::new("/font-placement-regression.vectorcraft"),
bounding: false,
page_box: Default::default(),
width: 100.0,
height: 100.0,
xf: Affine::IDENTITY,
placement: Default::default(),
};
let id = host.alloc_id();
host.insert(Some(host.layers[0].id), usize::MAX, Node::new(id, NodeKind::PlacedDocument(Box::new(placed)))).unwrap();
(host, expected, id)
}
/// Break Link and older-version saves must preserve the placed file's own bytes rather than bind
/// text to the host's unrelated font under the same key when reopened.
#[test]
fn placed_carried_fonts_survive_break_link_and_older_version_save() {
use vectorcraft_text::FontDb;
for break_link in [true, false] {
let family = if break_link { "Break Link Owned Font Regression" } else { "Older Save Owned Font Regression" };
let (host, expected, id) = linked_owned_font_document(family);
let mut s = Session::new();
s.add_document(host, None);
if break_link {
let embedded = s.execute("links.embed", &json!({"ids": [id.0]})).unwrap();
assert_eq!(embedded["embedded"], json!([id.0]), "{embedded}");
assert_eq!(glyphs(&s).1, 1);
}
let version = if break_link { vectorcraft_format::VERSION } else { vectorcraft_format::VERSION - 1 };
let saved = s.execute("document.serialize", &json!({"format": "vectorcraft", "version": version, "preview": false})).unwrap();
let reopened = s.execute("document.open", &json!({"name": "placed-font.vectorcraft", "dataBase64": saved["dataBase64"]})).unwrap();
assert!(reopened["warnings"].as_array().unwrap().is_empty(), "{reopened}");
let db = FontDb::global();
let mut drawn = 0;
s.doc().unwrap().doc.walk(|n| {
if let NodeKind::Text(t) = &n.kind {
for g in vectorcraft_text::layout(db, t).glyphs {
assert!(db.is_file_font(g.font_id));
assert_eq!(db.face_by_id(g.font_id).unwrap().file_data(), expected.bytes.as_slice(), "{family}");
drawn += 1;
}
}
});
assert_eq!(drawn, 1, "{family}");
assert!(!s.doc().unwrap().doc.has_placed(), "the reopened art is editable, not a linked source");
}
}
/// Glyphs `a`, `b`, `a` in an unavailable carried font, all named `a` by ToUnicode.
fn two_glyphs_for_one_character_pdf(content: &str) -> Vec<u8> {
let data = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/fonts/SourceSerif4-Regular.ttf")).unwrap();
let face = vectorcraft_text::FontDb::global().face("Source Serif 4", "Regular").unwrap();
let widths: Vec<String> =
(32u8..=126).map(|c| format!("{:.0}", face.advance(face.glyph_for(char::from(c))) * 1000.0 / face.units_per_em())).collect();
let hex: String = data.iter().map(|b| format!("{b:02x}")).collect();
let n = first_extra(1);
let page = PdfPage { resources: format!("/Font << /F1 {n} 0 R >>"), ..PdfPage::new(400.0, 200.0, content) };
let font = format!(
"<< /Type /Font /Subtype /TrueType /BaseFont /ABCDEF+Zyxwvu-Serif /FirstChar 32 /LastChar 126 /Widths [{}] /Encoding /WinAnsiEncoding /FontDescriptor {} 0 R /ToUnicode {} 0 R >>",
widths.join(" "),
n + 1,
n + 3
);
let descriptor = format!(
"<< /Type /FontDescriptor /FontName /ABCDEF+Zyxwvu-Serif /Flags 34 /FontBBox [-500 -300 1500 1000] /ItalicAngle 0 /Ascent 900 /Descent -300 /CapHeight 660 /StemV 80 /FontFile2 {} 0 R >>",
n + 2
);
let file = format!("<< /Length {} /Filter /ASCIIHexDecode >>\nstream\n{hex}>\nendstream", hex.len() + 1);
let cmap = "/CIDInit /ProcSet findresource begin 12 dict begin begincmap /CMapName /Adobe-Identity-UCS def /CMapType 2 def 1 begincodespacerange <00> <FF> endcodespacerange 2 beginbfchar <61> <0061> <62> <0061> endbfchar endcmap CMapName currentdict /CMap defineresource pop end end";
let tounicode = format!("<< /Length {} >>\nstream\n{cmap}\nendstream", cmap.len() + 1);
pdf_with(&[page], &[&font, &descriptor, &file, &tounicode], None)
}
/// The three glyph ink boxes, grouped by x for the TJ fixture or by y for separate lines.
fn glyph_ink(s: &Session, across: bool) -> Vec<kurbo::Rect> {
use kurbo::Shape;
let db = vectorcraft_text::FontDb::global();
let mut lines: [Option<kurbo::Rect>; 3] = [None; 3];
let mut add = |path: &kurbo::BezPath| {
let els = path.elements();
let mut start = 0;
for end in (1..=els.len()).filter(|&e| e == els.len() || matches!(els[e], kurbo::PathEl::MoveTo(_))) {
let ink = kurbo::BezPath::from_vec(els[start..end].to_vec()).bounding_box();
let line = if across {
usize::from(ink.center().x > 90.0) + usize::from(ink.center().x > 230.0)
} else {
usize::from(ink.center().y > 70.0) + usize::from(ink.center().y > 130.0)
};
lines[line] = Some(lines[line].map_or(ink, |l| l.union(ink)));
start = end;
}
};
s.doc().unwrap().doc.walk(|n| match &n.kind {
NodeKind::Text(t) => vectorcraft_text::layout(db, t).glyphs.iter().for_each(|g| add(&(t.xf * g.outline.clone()))),
NodeKind::Path { path, .. } => add(&path.to_bezpath()),
_ => {}
});
lines.into_iter().flatten().collect()
}
/// Two different glyphs of a carried font for one character can't both go into the font kept with
/// the document, which has one glyph per character, so the line with the other glyph is outlines.
/// Opened, saved in the native format and opened again, each glyph is still the one the file draws,
/// where it draws it: the same page opened as outlines is the reference.
#[test]
fn two_glyphs_for_one_character_survive_a_native_save_and_reopen() {
let content = "BT /F1 30 Tf 20 160 Td (a) Tj ET BT /F1 30 Tf 20 100 Td (b) Tj ET BT /F1 30 Tf 20 40 Td (a) Tj ET";
assert_carried_glyph_roundtrip(content, false);
}
#[test]
fn conflicting_carried_glyphs_in_a_filled_and_stroked_tj_survive_native_reopen() {
let content = "BT 2 Tr /F1 30 Tf 20 100 Td [(a) -3500 (b) -3500 (a)] TJ 0 Tr ET";
assert_carried_glyph_roundtrip(content, true);
}
fn assert_carried_glyph_roundtrip(content: &str, across: bool) {
let bytes = two_glyphs_for_one_character_pdf(content);
let mut reference_session = Session::new();
open(&mut reference_session, &bytes, json!({"textAs": "outlines"})).unwrap();
let reference = glyph_ink(&reference_session, across);
assert_eq!(reference.len(), 3, "the file draws three glyphs: {reference:?}");
assert!((reference[0].height() - reference[1].height()).abs() > 2.0, "the file's two glyphs differ in shape: {reference:?}");
assert!((reference[0].height() - reference[2].height()).abs() < 0.01, "the first and third are the same glyph: {reference:?}");
let mut s = Session::new();
open(&mut s, &bytes, json!({})).unwrap();
assert!(
live_texts(&s).iter().any(|t| t == "a") && live_texts(&s).len() < 3,
"some glyphs stay type, the other is outlines: {:?}",
live_texts(&s)
);
let close = |s: &Session, what: &str| {
let got = glyph_ink(s, across);
assert_eq!(got.len(), reference.len(), "{what}: {got:?}");
for (got, want) in got.iter().zip(&reference) {
let off = (got.x0 - want.x0).abs().max((got.x1 - want.x1).abs()).max((got.y0 - want.y0).abs()).max((got.y1 - want.y1).abs());
assert!(off < 0.25, "{what}: {got:?} is {off} pt from the file's {want:?}");
}
};
close(&s, "opened");
let native = s.execute("document.serialize", &json!({"format": "vectorcraft"})).unwrap()["dataBase64"].as_str().unwrap().to_string();
s.execute("document.open", &json!({"name": "kept.vectorcraft", "dataBase64": native})).unwrap();
close(&s, "saved and reopened");
}
+810 -6
View File
@@ -18,6 +18,8 @@ struct L {
rect: [i32; 4],
/// Red, green, blue and alpha, the same for every pixel.
rgba: [u8; 4],
/// The alpha of each pixel, in place of `rgba`'s, stored raw.
alpha: Option<Vec<u8>>,
blend: &'static [u8; 4],
opacity: u8,
clipped: bool,
@@ -40,6 +42,7 @@ fn layer(name: &'static str, rect: [i32; 4], rgba: [u8; 4]) -> L {
name,
rect,
rgba,
alpha: None,
blend: b"norm",
opacity: 255,
clipped: false,
@@ -96,10 +99,15 @@ fn predict(row: &[u8], depth: u16) -> Vec<u8> {
}
}
/// A channel of `n` samples of `v` (in 32 bits, `v` / 255 as a float) at `depth`, raw, zipped
/// (with prediction when `zip` is `Some(true)`) or PackBits rows of `width` when `rle`.
/// One sample of `v` at `depth` (in 32 bits, `v` / 255 as a float).
fn sample_of(v: u8, depth: u16) -> Vec<u8> {
if depth == 32 { (f32::from(v) / 255.0).to_be_bytes().to_vec() } else { vec![v; usize::from(depth / 8)] }
}
/// A channel of `n` samples of `v` (see [`sample_of`]) at `depth`, raw, zipped (with prediction
/// when `zip` is `Some(true)`) or PackBits rows of `width` when `rle`.
fn channel(v: u8, n: usize, width: usize, depth: u16, rle: bool, psb: bool, zip: Option<bool>) -> Vec<u8> {
let sample = if depth == 32 { (f32::from(v) / 255.0).to_be_bytes().to_vec() } else { vec![v; usize::from(depth / 8)] };
let sample = sample_of(v, depth);
let row: Vec<u8> = std::iter::repeat_n(sample.as_slice(), width).flatten().copied().collect();
if let Some(predicted) = zip {
let rows = n.checked_div(width).unwrap_or(0);
@@ -151,11 +159,17 @@ fn layer_info(layers: &[L], depth: u16, rle: bool, psb: bool) -> Vec<u8> {
.filter(|_| !l.bare)
.map(|&(id, v)| (id, channel(v, w * h, w, depth, rle, psb, l.zip)))
.collect();
if let (Some(pixels), Some((_, d))) = (&l.alpha, channels.first_mut()) {
*d = vec![0, 0];
for &p in pixels {
d.extend(sample_of(p, depth));
}
}
let mut mask = vec![];
if let Some(([mt, ml, mb, mr], default, flags, pixels)) = &l.mask {
let mut d = vec![0, 0];
for &p in pixels {
d.extend(std::iter::repeat_n(p, usize::from(depth / 8)));
d.extend(sample_of(p, depth));
}
channels.push((-2, d));
for v in [mt, ml, mb, mr] {
@@ -391,9 +405,9 @@ fn zipped_and_32_bit_layers_read() {
/// A layer without a Unicode name takes the name its Pascal string holds, read as Mac Roman.
#[test]
fn names_without_a_unicode_name_read_as_mac_roman() {
let l = L { legacy: Some(b"Caf\x8E \xD2Old\xD3"), ..layer("", [0, 0, 1, 1], [0, 0, 0, 255]) };
let l = L { legacy: Some(b"Caf\x8E\xCA\xD2Old\xD3\xDB"), ..layer("", [0, 0, 1, 1], [0, 0, 0, 255]) };
let (s, r) = open(&file(1, 1, &[l], 8, false, false), json!({}));
assert_eq!(name(&s.doc().unwrap().doc.layers[0]), "Café “Old”", "{r}");
assert_eq!(name(&s.doc().unwrap().doc.layers[0]), "Café\u{a0}“Old”€", "{r}");
}
#[test]
@@ -1201,6 +1215,790 @@ fn layers_clipped_to_an_adjustment_layer_show_over_the_canvas() {
assert!(r["warnings"].to_string().contains("1 adjustment layer was not applied"), "{r}");
}
/// An adjustment layer of key `key` with `data`, storing no pixels.
fn adjustment(name: &'static str, key: &[u8; 4], data: &[u8]) -> L {
L { blocks: vec![(*key, data.to_vec())], ..layer(name, [0, 0, 0, 0], [0; 4]) }
}
/// The colors of a 1-pixel-high layer's image, left to right.
fn row_of(s: &Session, l: &Node) -> Vec<[u8; 4]> {
let px = image_of(s, l).1;
(0..px.width()).map(|x| px.get_pixel(x, 0).0).collect()
}
/// Invert, Threshold and Posterize adjustment layers merge with the visible layers below them, which
/// they change; the layers above stay apart. Invert turns each value `v` into `255 − v`; Threshold
/// at 128 makes a pixel white when its luminance is above 128 and black at or below it; Posterize at
/// 4 levels maps each channel to the nearest of 0, 85, 170 and 255.
#[test]
fn invert_threshold_and_posterize_merge_with_the_layers_below() {
let top = layer("Top", [0, 0, 1, 1], [1, 2, 3, 255]);
for (depth, psb) in [(8, false), (16, false), (8, true), (16, true)] {
let layers = [
layer("Dark", [0, 0, 1, 1], [10, 20, 30, 255]),
layer("Light", [0, 1, 1, 2], [200, 150, 100, 128]),
adjustment("Invert", b"nvrt", &[]),
top.clone(),
];
let (s, r) = open(&file(2, 1, &layers, depth, false, psb), json!({}));
let d = &s.doc().unwrap().doc;
assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Dark + Light + Invert", "Top"], "{depth} {psb}: {r}");
assert_eq!(r["warnings"], json!([]), "{depth} {psb}");
assert_eq!(row_of(&s, &d.layers[0]), [[245, 235, 225, 255], [55, 105, 155, 128]], "{depth} {psb}: transparency stays");
assert_eq!(row_of(&s, &d.layers[1]), [[1, 2, 3, 255]], "{depth} {psb}: the layer above isn't changed");
}
let grays = [
layer("128", [0, 0, 1, 1], [128, 128, 128, 255]),
layer("129", [0, 1, 1, 2], [129, 129, 129, 255]),
layer("Light", [0, 2, 1, 3], [200, 150, 100, 255]),
layer("Dark", [0, 3, 1, 4], [10, 20, 30, 255]),
];
let layers = [&grays[..], &[adjustment("Threshold", b"thrs", &[0, 128, 0, 0])][..]].concat();
let (s, r) = open(&file(4, 1, &layers, 8, false, false), json!({}));
let d = &s.doc().unwrap().doc;
assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["128 + 129 + Light + Dark + Threshold"], "{r}");
assert_eq!(row_of(&s, &d.layers[0]), [[0, 0, 0, 255], [255, 255, 255, 255], [255, 255, 255, 255], [0, 0, 0, 255]]);
let layers =
[layer("A", [0, 0, 1, 1], [42, 43, 128, 255]), layer("B", [0, 1, 1, 2], [212, 213, 0, 255]), adjustment("Posterize", b"post", &[0, 4, 0, 0])];
let (s, r) = open(&file(2, 1, &layers, 8, false, false), json!({}));
let d = &s.doc().unwrap().doc;
assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["A + B + Posterize"], "{r}");
assert_eq!(row_of(&s, &d.layers[0]), [[0, 85, 170, 255], [170, 255, 0, 255]]);
}
/// An adjustment layer's opacity, layer mask and blend mode decide how much of the adjusted color
/// replaces the color below.
#[test]
fn an_adjustment_layer_takes_its_opacity_mask_and_blend_mode() {
let black = || layer("Black", [0, 0, 1, 2], [0, 0, 0, 255]);
let half = L { opacity: 128, ..adjustment("Invert", b"nvrt", &[]) };
let (s, r) = open(&file(2, 1, &[black(), half], 8, false, false), json!({}));
assert_eq!(row_of(&s, &s.doc().unwrap().doc.layers[0]), [[128, 128, 128, 255]; 2], "{r}");
// Black in the mask leaves the first pixel as it was; outside, the mask's default (white) applies it.
let masked = L { mask: Some(([0, 0, 1, 1], 255, 0, vec![0])), ..adjustment("Invert", b"nvrt", &[]) };
let (s, r) = open(&file(2, 1, &[black(), masked], 8, false, false), json!({}));
let d = &s.doc().unwrap().doc;
assert_eq!(row_of(&s, &d.layers[0]), [[0, 0, 0, 255], [255, 255, 255, 255]], "{r}");
assert!(d.layers[0].extras().mask.is_none(), "the mask is spent on the merge");
// A disabled mask applies it everywhere.
let off = L { mask: Some(([0, 0, 1, 1], 255, 2, vec![0])), ..adjustment("Invert", b"nvrt", &[]) };
let (s, _) = open(&file(2, 1, &[black(), off], 8, false, false), json!({}));
assert_eq!(row_of(&s, &s.doc().unwrap().doc.layers[0]), [[255, 255, 255, 255]; 2]);
// Multiply: the inverted color (55, 155, 205) multiplies the color below.
let multiply = L { blend: b"mul ", ..adjustment("Invert", b"nvrt", &[]) };
let (s, _) = open(&file(1, 1, &[layer("Under", [0, 0, 1, 1], [200, 100, 50, 255]), multiply], 8, false, false), json!({}));
assert_eq!(row_of(&s, &s.doc().unwrap().doc.layers[0]), [[43, 61, 40, 255]]);
// In a mode VectorCraft lacks, the warnings name the mode, as for other layers merged for it.
let dodge = L { blend: b"lddg", ..adjustment("Invert", b"nvrt", &[]) };
let (s, r) = open(&file(1, 1, &[layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), dodge], 8, false, false), json!({}));
assert_eq!(row_of(&s, &s.doc().unwrap().doc.layers[0]), [[255, 255, 255, 255]], "{r}");
let merged = "layers in blend modes VectorCraft doesn't have (Linear Dodge) were merged with the layers below them";
assert_eq!(r["warnings"], json!([merged]));
}
/// Clipped to a layer, an adjustment layer changes only that layer and the layers clipped to it.
#[test]
fn a_clipped_adjustment_layer_changes_only_its_base() {
let layers = [
layer("Other", [0, 1, 1, 2], [10, 10, 10, 255]),
layer("Base", [0, 0, 1, 1], [200, 0, 0, 255]),
L { clipped: true, ..adjustment("Invert", b"nvrt", &[]) },
];
let (s, r) = open(&file(2, 1, &layers, 8, false, false), json!({}));
let d = &s.doc().unwrap().doc;
assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Other", "Base + Invert"], "{r}");
assert_eq!(r["warnings"], json!([]));
assert_eq!((row_of(&s, &d.layers[0]), row_of(&s, &d.layers[1])), (vec![[10, 10, 10, 255]], vec![[55, 255, 255, 255]]));
// Over a layer clipped to the same base, and only inside the base's shape.
let layers = [
layer("Base", [0, 0, 1, 1], [200, 0, 0, 255]),
L { clipped: true, ..layer("Photo", [0, 0, 1, 2], [0, 0, 255, 255]) },
L { clipped: true, ..adjustment("Invert", b"nvrt", &[]) },
];
let (s, r) = open(&file(2, 1, &layers, 8, false, false), json!({}));
let d = &s.doc().unwrap().doc;
assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Base + Photo + Invert"], "{r}");
assert_eq!(row_of(&s, &d.layers[0]), [[255, 255, 0, 255]]);
// Clipped to another adjustment layer, it isn't applied: the layers keep their colors.
let layers = [
layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]),
adjustment("Curves", b"curv", &[0; 4]),
L { clipped: true, ..layer("Photo", [0, 0, 1, 1], [0, 0, 255, 255]) },
L { clipped: true, ..adjustment("Invert", b"nvrt", &[]) },
];
let (s, r) = open(&file(1, 1, &layers, 8, false, false), json!({}));
let d = &s.doc().unwrap().doc;
assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under", "Curves + Photo"], "{r}");
assert_eq!((row_of(&s, &d.layers[0]), row_of(&s, &d.layers[1])), (vec![[10, 20, 30, 255]], vec![[0, 0, 255, 255]]));
assert_eq!(r["warnings"], json!(["2 adjustment layers were not applied"]));
// Its layer mask isn't read then: one too large to read doesn't stop the file opening.
let mut masked = layers;
masked[3].mask = Some(([0, 0, 1, 40_000], 0, 0, vec![200]));
let (s, r) = open(&file(1, 1, &masked, 8, false, false), json!({}));
let d = &s.doc().unwrap().doc;
assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under", "Curves + Photo"], "{r}");
assert_eq!(r["warnings"], json!(["2 adjustment layers were not applied"]));
// An Invert layer that a layer drawing nothing is clipped to isn't applied either.
let layers = [
layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]),
adjustment("Invert", b"nvrt", &[]),
L { clipped: true, ..layer("Empty", [0, 0, 0, 0], [0; 4]) },
];
let (s, r) = open(&file(1, 1, &layers, 8, false, false), json!({}));
let d = &s.doc().unwrap().doc;
assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under"], "{r}");
assert_eq!(row_of(&s, &d.layers[0]), [[10, 20, 30, 255]]);
assert_eq!(r["warnings"], json!(["1 adjustment layer was not applied"]));
}
/// A hidden adjustment layer changes nothing and is left out, with or without the hidden layers; one
/// with nothing below it, or in an isolated group with nothing below it there, changes nothing.
#[test]
fn hidden_and_lone_adjustment_layers_change_nothing() {
for hidden in [false, true] {
let layers = [layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), L { hidden: true, ..adjustment("Invert", b"nvrt", &[]) }];
let (s, r) = open(&file(1, 1, &layers, 8, false, false), json!({"hiddenLayers": hidden}));
let d = &s.doc().unwrap().doc;
assert_eq!((d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), &r["warnings"]), (vec!["Under"], &json!([HIDDEN_1])), "{hidden}");
assert_eq!(row_of(&s, &d.layers[0]), [[10, 20, 30, 255]]);
}
let (s, r) = open(&file(1, 1, &[adjustment("Invert", b"nvrt", &[]), layer("Top", [0, 0, 1, 1], [10, 20, 30, 255])], 8, false, false), json!({}));
assert_eq!((s.doc().unwrap().doc.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), &r["warnings"]), (vec!["Top"], &json!([])));
let layers = [layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), group_end(), adjustment("Invert", b"nvrt", &[]), group("Isolated", b"norm")];
let (s, r) = open(&file(1, 1, &layers, 8, false, false), json!({}));
let d = &s.doc().unwrap().doc;
assert_eq!((d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), &r["warnings"]), (vec!["Under", "Isolated"], &json!([])));
assert_eq!(row_of(&s, &d.layers[0]), [[10, 20, 30, 255]]);
}
/// In a pass-through group with nothing below it in the group, an adjustment layer changes what is
/// below the group when the group is merged; when the group comes in as layers, it isn't applied.
#[test]
fn an_adjustment_layer_in_a_pass_through_group_changes_what_is_below_the_group() {
let layers = |dodge: bool| {
let mut l = vec![layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), group_end(), adjustment("Invert", b"nvrt", &[]), group("Folder", b"pass")];
if dodge {
l.push(L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) });
}
l
};
let (s, r) = open(&file(1, 1, &layers(true), 8, false, false), json!({}));
let d = &s.doc().unwrap().doc;
assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under + Folder + Dodge"], "{r}");
assert_eq!(row_of(&s, &d.layers[0]), [[245, 235, 225, 255]]);
let (s, r) = open(&file(1, 1, &layers(false), 8, false, false), json!({}));
let d = &s.doc().unwrap().doc;
assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under", "Folder"], "{r}");
assert_eq!(r["warnings"], json!(["1 adjustment layer was not applied"]));
// Two at the bottom of the group both change what is below it, in order: inverted, then
// posterized to 4 levels (without the Invert the color would posterize to black).
let stacked = [
layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]),
group_end(),
adjustment("Invert", b"nvrt", &[]),
adjustment("Posterize", b"post", &[0, 4, 0, 0]),
group("Folder", b"pass"),
L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) },
];
let (s, r) = open(&file(1, 1, &stacked, 8, false, false), json!({}));
let d = &s.doc().unwrap().doc;
assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under + Folder + Dodge"], "{r}");
assert_eq!((row_of(&s, &d.layers[0]), r["warnings"].to_string().contains("adjustment")), (vec![[255, 255, 255, 255]], false), "{r}");
// One above a layer of the group, with one kept below that layer, is kept too: the group draws
// them in order over what is below it.
let between = [
layer("Under", [0, 0, 1, 2], [10, 20, 30, 255]),
group_end(),
adjustment("Invert", b"nvrt", &[]),
layer("Top", [0, 1, 1, 2], [100, 100, 100, 255]),
adjustment("Posterize", b"post", &[0, 4, 0, 0]),
group("Folder", b"pass"),
L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) },
];
let (s, r) = open(&file(2, 1, &between, 8, false, false), json!({}));
let d = &s.doc().unwrap().doc;
assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under + Folder + Dodge"], "{r}");
assert_eq!(row_of(&s, &d.layers[0]), [[255, 255, 255, 255], [85, 85, 85, 255]], "{r}");
// Another adjustment layer below it in the group draws nothing, so it still changes what is
// below the group.
let over_curves = [
layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]),
group_end(),
adjustment("Curves", b"curv", &[0; 4]),
adjustment("Invert", b"nvrt", &[]),
group("Folder", b"pass"),
L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) },
];
let (s, r) = open(&file(1, 1, &over_curves, 8, false, false), json!({}));
let d = &s.doc().unwrap().doc;
assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under + Folder + Dodge"], "{r}");
assert_eq!(row_of(&s, &d.layers[0]), [[245, 235, 225, 255]], "{r}");
// One kept in a pass-through group inside the group keeps the ones above it too: inverted, then
// posterized to 4 levels.
let nested = [
layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]),
group_end(),
group_end(),
adjustment("Invert", b"nvrt", &[]),
group("Inner", b"pass"),
adjustment("Posterize", b"post", &[0, 4, 0, 0]),
group("Folder", b"pass"),
L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) },
];
let (s, r) = open(&file(1, 1, &nested, 8, false, false), json!({}));
let d = &s.doc().unwrap().doc;
assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under + Folder + Dodge"], "{r}");
assert_eq!((row_of(&s, &d.layers[0]), r["warnings"].to_string().contains("adjustment")), (vec![[255, 255, 255, 255]], false), "{r}");
// Without the merge, the group comes in as layers and both are counted as not applied.
let (s, r) = open(&file(1, 1, &nested[..7], 8, false, false), json!({}));
let d = &s.doc().unwrap().doc;
assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under", "Folder"], "{r}");
assert_eq!(r["warnings"], json!(["2 adjustment layers were not applied"]));
// Merged in the group with a layer in a mode VectorCraft lacks, it has nothing to change.
let inside = [
layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]),
group_end(),
adjustment("Invert", b"nvrt", &[]),
L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) },
group("Folder", b"pass"),
];
let (s, r) = open(&file(1, 1, &inside, 8, false, false), json!({}));
let d = &s.doc().unwrap().doc;
let names: Vec<&str> = d.layers.iter().map(|l| name(l)).collect();
let merged = "layers in blend modes VectorCraft doesn't have (Linear Dodge) were merged with the layers below them";
assert_eq!((names, &r["warnings"]), (vec!["Under", "Folder"], &json!(["1 adjustment layer was not applied", merged])), "{r}");
assert_eq!(row_of(&s, &d.layers[0]), [[10, 20, 30, 255]]);
}
/// The layer of a pass-through group's sublayers whose name ends with `end`.
fn sublayer<'d>(folder: &'d Node, end: &str) -> &'d Node {
let children = folder.children().map(Vec::as_slice).unwrap_or_default();
let names: Vec<&str> = children.iter().map(|c| name(c)).collect();
children.iter().find(|c| name(c).ends_with(end)).unwrap_or_else(|| panic!("no sublayer ending with {end} in {names:?}"))
}
/// An adjustment layer that changes nothing, in a hidden pass-through group or at 0 opacity or 0
/// fill, keeps no adjustment layer above it in the group from merging with the layers below it:
/// the gray 100 posterizes to 85.
#[test]
fn adjustment_layers_that_change_nothing_hold_none_back() {
let invert = |opacity: u8, fill: u8| {
let mut l = L { opacity, ..adjustment("Invert", b"nvrt", &[]) };
l.blocks.push((*b"iOpa", vec![fill]));
l
};
let cases = [("hidden group", true, invert(255, 255)), ("0 opacity", false, invert(0, 255)), ("0 fill", false, invert(255, 0))];
for (what, hidden, invert) in cases {
let layers = [
group_end(),
group_end(),
invert,
L { hidden, ..group("Inner", b"pass") },
layer("Photo", [0, 0, 1, 1], [100, 100, 100, 255]),
adjustment("Posterize", b"post", &[0, 4, 0, 0]),
group("Folder", b"pass"),
];
let (s, r) = open(&file(1, 1, &layers, 8, false, false), json!({"hiddenLayers": hidden}));
let d = &s.doc().unwrap().doc;
assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Folder"], "{what}: {r}");
assert_eq!(row_of(&s, sublayer(&d.layers[0], "Photo + Posterize")), [[85, 85, 85, 255]], "{what}: {r}");
}
}
/// A layer that stores no pixels draws nothing: an adjustment layer above it in a pass-through group,
/// directly or in a pass-through group inside it, still changes what is below the group.
#[test]
fn an_adjustment_layer_over_layers_that_draw_nothing_changes_what_is_below_the_group() {
let empty = || layer("Empty", [0, 0, 0, 0], [0; 4]);
let direct = [
layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]),
group_end(),
empty(),
adjustment("Invert", b"nvrt", &[]),
group("Folder", b"pass"),
L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) },
];
let (s, r) = open(&file(1, 1, &direct, 8, false, false), json!({}));
let d = &s.doc().unwrap().doc;
assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under + Folder + Dodge"], "{r}");
assert_eq!(row_of(&s, &d.layers[0]), [[245, 235, 225, 255]], "{r}");
assert!(!r["warnings"].to_string().contains("adjustment"), "{r}");
// Inverted in the inner group, then posterized to 4 levels.
let nested = [
layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]),
group_end(),
group_end(),
empty(),
adjustment("Invert", b"nvrt", &[]),
group("Inner", b"pass"),
adjustment("Posterize", b"post", &[0, 4, 0, 0]),
group("Folder", b"pass"),
L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) },
];
let (s, r) = open(&file(1, 1, &nested, 8, false, false), json!({}));
let d = &s.doc().unwrap().doc;
assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under + Folder + Dodge"], "{r}");
assert_eq!(row_of(&s, &d.layers[0]), [[255, 255, 255, 255]], "{r}");
assert!(!r["warnings"].to_string().contains("adjustment"), "{r}");
// Nor does a group of such layers, in any mode, or a layer at 0 opacity: below them, directly
// or in the inner group, Invert and Posterize still change what is below the outer group.
let mut no_fill = layer("Clear", [0, 0, 1, 1], [0, 0, 0, 255]);
no_fill.blocks.push((*b"iOpa", vec![0]));
let photo = || layer("Photo", [0, 0, 1, 1], [0, 0, 255, 255]);
let below: [(&str, Vec<L>); 5] = [
("empty group", vec![group_end(), empty(), group("Empty", b"norm")]),
("empty pass-through group", vec![group_end(), empty(), group("Empty", b"pass")]),
("0 opacity", vec![L { opacity: 0, ..layer("Clear", [0, 0, 1, 1], [0, 0, 0, 255]) }]),
("0 fill in a group", vec![group_end(), no_fill, group("Empty", b"norm")]),
("group clipped to an empty layer", vec![empty(), group_end(), photo(), L { clipped: true, ..group("Clipped", b"norm") }]),
];
for (what, nothing) in below {
let direct = [
&[layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), group_end()][..],
&nothing,
&[adjustment("Invert", b"nvrt", &[]), group("Folder", b"pass"), L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) }],
]
.concat();
let (s, r) = open(&file(1, 1, &direct, 8, false, false), json!({}));
assert_eq!(row_of(&s, &s.doc().unwrap().doc.layers[0]), [[245, 235, 225, 255]], "{what}: {r}");
let nested = [
&[layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), group_end(), group_end()][..],
&nothing,
&[
adjustment("Invert", b"nvrt", &[]),
group("Inner", b"pass"),
adjustment("Posterize", b"post", &[0, 4, 0, 0]),
group("Folder", b"pass"),
L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) },
],
]
.concat();
let (s, r) = open(&file(1, 1, &nested, 8, false, false), json!({}));
assert_eq!(row_of(&s, &s.doc().unwrap().doc.layers[0]), [[255, 255, 255, 255]], "{what}: {r}");
}
}
/// Layers clipped to a layer at 0 fill, or to an adjustment layer, draw: an adjustment layer above
/// them in a pass-through group merges with them and is applied.
#[test]
fn an_adjustment_layer_over_clipped_layers_merges_with_them() {
let mut clear = layer("Base", [0, 0, 1, 1], [0, 0, 0, 255]);
clear.blocks.push((*b"iOpa", vec![0]));
let photo = || L { clipped: true, ..layer("Photo", [0, 0, 1, 1], [0, 0, 255, 255]) };
let layers = [
group_end(),
group_end(),
clear,
photo(),
adjustment("Invert", b"nvrt", &[]),
group("Folder", b"pass"),
L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) },
group("Outer", b"pass"),
];
let (s, r) = open(&file(1, 1, &layers, 8, false, false), json!({}));
let d = &s.doc().unwrap().doc;
let merged = "layers in blend modes VectorCraft doesn't have (Linear Dodge) were merged with the layers below them";
assert_eq!(r["warnings"], json!([merged]), "{r}");
assert_eq!(row_of(&s, sublayer(&d.layers[0], "Dodge")), [[255, 255, 0, 255]], "{r}");
// The same with a group at 0 fill as the base.
let mut clear_group = group("Base", b"norm");
clear_group.blocks.push((*b"iOpa", vec![0]));
let layers = [
group_end(),
group_end(),
group_end(),
layer("Black", [0, 0, 1, 1], [0, 0, 0, 255]),
clear_group,
photo(),
adjustment("Invert", b"nvrt", &[]),
group("Folder", b"pass"),
L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) },
group("Outer", b"pass"),
];
let (s, r) = open(&file(1, 1, &layers, 8, false, false), json!({}));
let d = &s.doc().unwrap().doc;
assert_eq!(r["warnings"], json!([merged]), "{r}");
assert_eq!(row_of(&s, sublayer(&d.layers[0], "Dodge")), [[255, 255, 0, 255]], "{r}");
// Clipped to an Invert layer, which isn't applied then, the photo shows over the canvas, and
// Posterize merges with it: the gray 100 posterizes to 85.
let layers = [
group_end(),
group_end(),
adjustment("Invert", b"nvrt", &[]),
L { clipped: true, ..layer("Photo", [0, 0, 1, 1], [100, 100, 100, 255]) },
group("Folder", b"pass"),
adjustment("Posterize", b"post", &[0, 4, 0, 0]),
group("Outer", b"pass"),
];
let (s, r) = open(&file(1, 1, &layers, 8, false, false), json!({}));
let d = &s.doc().unwrap().doc;
assert_eq!(row_of(&s, sublayer(&d.layers[0], "Posterize")), [[85, 85, 85, 255]], "{r}");
}
/// Invert, Threshold and Posterize data that can't be read is not applied, with a warning: a level
/// out of range, data too short, or a second adjustment block on the layer.
#[test]
fn adjustment_data_that_cant_be_read_isnt_applied() {
let mut twice = adjustment("Twice", b"nvrt", &[]);
twice.blocks.push((*b"post", vec![0, 4, 0, 0]));
let mut apart = adjustment("Apart", b"nvrt", &[]);
apart.blocks.extend([(*b"SoCo", vec![]), (*b"post", vec![0, 4, 0, 0])]);
let cases = [
adjustment("Level 0", b"thrs", &[0, 0, 0, 0]),
adjustment("Level 256", b"thrs", &[1, 0, 0, 0]),
adjustment("No level", b"thrs", &[]),
adjustment("No padding", b"thrs", &[0, 128]),
adjustment("No padding", b"post", &[0, 4]),
adjustment("1 level", b"post", &[0, 1, 0, 0]),
adjustment("256 levels", b"post", &[1, 0, 0, 0]),
twice,
apart,
];
for bad in cases {
let what = bad.name;
let (s, r) = open(&file(1, 1, &[layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), bad], 8, false, false), json!({}));
let d = &s.doc().unwrap().doc;
assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under"], "{what}: {r}");
assert_eq!(row_of(&s, &d.layers[0]), [[10, 20, 30, 255]], "{what}");
assert_eq!(r["warnings"], json!(["1 adjustment layer was not applied"]), "{what}");
}
// The highest level and count are read.
let under = |c: u8| layer("Under", [0, 0, 1, 1], [c, c, c, 255]);
let (s, r) = open(&file(1, 1, &[under(254), adjustment("Max", b"thrs", &[0, 255, 0, 0])], 8, false, false), json!({}));
assert_eq!(row_of(&s, &s.doc().unwrap().doc.layers[0]), [[0, 0, 0, 255]], "{r}");
let (s, r) = open(&file(1, 1, &[under(7), adjustment("Max", b"post", &[0, 255, 0, 0])], 8, false, false), json!({}));
assert_eq!(row_of(&s, &s.doc().unwrap().doc.layers[0]), [[7, 7, 7, 255]], "{r}");
}
/// An adjustment layer whose merge needs more memory than allowed isn't applied: the layers below
/// it stay as they are, with a warning.
#[test]
fn an_adjustment_merge_past_the_memory_allowed_isnt_applied() {
let cms = |c: [f32; 4]| [c[0], c[1], c[2]];
let layers = [layer("Under", [0, 0, 2, 2], [10, 20, 30, 255]), layer("Beside", [2, 2, 4, 4], [1, 2, 3, 255]), adjustment("Invert", b"nvrt", &[])];
let f = file(4, 4, &layers, 8, false, false);
// Each 2 × 2 layer fits 128 bytes; the 4 × 4 canvas of both doesn't.
let (doc, warnings) = psdlayers::import(&f, false, 128, cms).unwrap().unwrap();
assert_eq!(doc.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under", "Beside"]);
assert_eq!(warnings, ["1 adjustment layer was not applied"]);
let (doc, warnings) = psdlayers::import(&f, false, 1 << 20, cms).unwrap().unwrap();
assert_eq!(doc.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under + Beside + Invert"]);
assert!(warnings.is_empty(), "{warnings:?}");
// Clipped: the base's canvas with its shape doesn't fit 300 bytes, so the adjustment is left
// out rather than applied to everything below.
let layers = [layer("Base", [0, 0, 4, 4], [10, 20, 30, 255]), L { clipped: true, ..adjustment("Invert", b"nvrt", &[]) }];
let (doc, warnings) = psdlayers::import(&file(4, 4, &layers, 8, false, false), false, 300, cms).unwrap().unwrap();
assert_eq!(doc.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Base"]);
assert_eq!(warnings, ["1 adjustment layer was not applied"]);
// A layer clipped to an Invert layer whose merge doesn't fit comes in unclipped, and the Invert
// layer isn't applied to the layers below it.
let layers = [
layer("Under", [0, 0, 2, 2], [10, 20, 30, 255]),
adjustment("Invert", b"nvrt", &[]),
L { clipped: true, ..layer("Photo", [0, 0, 4, 4], [1, 2, 3, 255]) },
];
let (doc, warnings) = psdlayers::import(&file(4, 4, &layers, 8, false, false), false, 128, cms).unwrap().unwrap();
assert_eq!(doc.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under", "Photo"], "{warnings:?}");
assert!(warnings.iter().any(|w| w == "1 adjustment layer was not applied"), "{warnings:?}");
}
/// An adjustment layer whose layer mask is too large for the memory allowed isn't applied, merged
/// with the layers below it or clipped to one, and the file still opens with its layers.
#[test]
fn an_adjustment_mask_past_the_memory_allowed_isnt_applied() {
let cms = |c: [f32; 4]| [c[0], c[1], c[2]];
// The 100 × 100 mask takes more than 128 bytes; the 1-pixel layer below it doesn't.
let masked = |clipped: bool| L { clipped, mask: Some(([0, 0, 100, 100], 255, 0, vec![0; 10_000])), ..adjustment("Invert", b"nvrt", &[]) };
for clipped in [false, true] {
let f = file(1, 1, &[layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), masked(clipped)], 8, false, false);
let (doc, warnings) = psdlayers::import(&f, false, 128, cms).unwrap_or_else(|e| panic!("{clipped}: {e}")).unwrap();
assert_eq!(doc.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under"], "{clipped}: {warnings:?}");
assert_eq!(warnings, ["1 adjustment layer was not applied"], "{clipped}");
// With the memory for it, the mask's black leaves the layer as it was.
let (doc, warnings) = psdlayers::import(&f, false, 1 << 20, cms).unwrap().unwrap();
assert_eq!(doc.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under + Invert"], "{clipped}: {warnings:?}");
assert!(warnings.is_empty(), "{clipped}: {warnings:?}");
}
}
/// An adjustment layer's mask is read beside the canvases it changes: a 100 × 1 mask fits 256 bytes
/// alone, but not beside a 6 × 1 canvas, so the layer isn't applied. With the memory for both, it is.
#[test]
fn an_adjustment_mask_counts_the_canvas_it_changes() {
let cms = |c: [f32; 4]| [c[0], c[1], c[2]];
let masked = |clipped: bool| L { clipped, mask: Some(([0, 0, 1, 100], 255, 0, vec![255; 100])), ..adjustment("Invert", b"nvrt", &[]) };
for clipped in [false, true] {
let f = file(6, 1, &[layer("Under", [0, 0, 1, 6], [10, 20, 30, 255]), masked(clipped)], 8, false, false);
let (doc, warnings) = psdlayers::import(&f, false, 256, cms).unwrap_or_else(|e| panic!("{clipped}: {e}")).unwrap();
assert_eq!(doc.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under"], "{clipped}: {warnings:?}");
assert_eq!(warnings, ["1 adjustment layer was not applied"], "{clipped}");
let (doc, warnings) = psdlayers::import(&f, false, 1 << 20, cms).unwrap().unwrap();
assert_eq!(doc.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under + Invert"], "{clipped}: {warnings:?}");
assert!(warnings.is_empty(), "{clipped}: {warnings:?}");
}
}
/// An adjustment layer whose mask is too large to read is left out without stopping the clip or the
/// merge around it: a layer clipped above it still clips to the base, and a layer in a mode
/// VectorCraft lacks above a pass-through group holding it still merges in its mode.
#[test]
fn an_adjustment_mask_too_large_leaves_the_clip_and_merge_around_it() {
let cms = |c: [f32; 4]| [c[0], c[1], c[2]];
let masked = |clipped: bool| L { clipped, mask: Some(([0, 0, 100, 100], 255, 0, vec![255; 10_000])), ..adjustment("Invert", b"nvrt", &[]) };
let layers = [layer("Base", [0, 0, 1, 1], [200, 0, 0, 255]), masked(true), L { clipped: true, ..layer("Photo", [0, 0, 1, 2], [0, 0, 255, 255]) }];
let (doc, warnings) = psdlayers::import(&file(2, 1, &layers, 8, false, false), false, 128, cms).unwrap().unwrap();
assert_eq!(doc.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Base + Photo"], "{warnings:?}");
assert_eq!(warnings, ["1 adjustment layer was not applied"]);
// Gray 100 under Linear Dodge's gray 20 gives gray 120.
let layers = [
layer("Under", [0, 0, 1, 1], [100, 100, 100, 255]),
group_end(),
masked(false),
group("Folder", b"pass"),
L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [20, 20, 20, 255]) },
];
let (doc, warnings) = psdlayers::import(&file(1, 1, &layers, 8, false, false), false, 128, cms).unwrap().unwrap();
assert_eq!(doc.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under + Folder + Dodge"], "{warnings:?}");
let merged = "layers in blend modes VectorCraft doesn't have (Linear Dodge) were merged with the layers below them";
assert_eq!(warnings, ["1 adjustment layer was not applied", merged]);
let Some([c]) = doc.layers[0].children().map(Vec::as_slice) else { panic!("the merged layer holds one image") };
let NodeKind::Image(img) = &c.kind else { panic!("the merged layer holds an image") };
let px = craft_image_codecs::decode(&doc.images[&img.key].bytes).unwrap().to_rgba8();
assert_eq!(px, [120, 120, 120, 255]);
}
/// A layer merged in a pass-through group for its mode or its knockout takes the adjustment layers
/// kept below it with it: an adjustment layer above that group in an outer pass-through group then
/// merges with it, and the gray 100 posterizes to 85.
#[test]
fn an_adjustment_layer_above_a_group_whose_kept_ones_merged_is_applied() {
let tops = [
("Linear Dodge", vec![L { blend: b"lddg", ..layer("Top", [0, 0, 1, 1], [100, 100, 100, 255]) }]),
("knockout", vec![layer("Photo", [0, 0, 1, 1], [50, 50, 50, 255]), knockout(layer("Top", [0, 0, 1, 1], [100, 100, 100, 255]), 1, 255)]),
];
for (what, top) in tops {
let layers = [
&[group_end(), group_end(), adjustment("Invert", b"nvrt", &[])][..],
&top,
&[group("Inner", b"pass"), adjustment("Posterize", b"post", &[0, 4, 0, 0]), group("Folder", b"pass")],
]
.concat();
let (s, r) = open(&file(1, 1, &layers, 8, false, false), json!({}));
let d = &s.doc().unwrap().doc;
assert_eq!(row_of(&s, sublayer(&d.layers[0], "Posterize")), [[85, 85, 85, 255]], "{what}: {r}");
assert!(r["warnings"].to_string().contains("1 adjustment layer was not applied"), "{what}: {r}");
}
}
/// An adjustment layer in a pass-through group, over a layer drawn below that group in an outer
/// pass-through group, isn't kept to change what is below the outer group: a layer merged above
/// them for its mode merges it applied, and the import doesn't count it as not applied. The gray
/// 100 inverts to 155.
#[test]
fn an_adjustment_layer_in_a_group_over_a_drawn_layer_merges_applied() {
let layers = [
group_end(),
layer("Photo", [0, 0, 1, 1], [100, 100, 100, 255]),
group_end(),
adjustment("Invert", b"nvrt", &[]),
group("Inner", b"pass"),
L { blend: b"lddg", ..layer("Top", [0, 0, 1, 1], [0, 0, 0, 255]) },
group("Folder", b"pass"),
];
let (s, r) = open(&file(1, 1, &layers, 8, false, false), json!({}));
let d = &s.doc().unwrap().doc;
assert_eq!(row_of(&s, sublayer(&d.layers[0], "Top")), [[155, 155, 155, 255]], "{r}");
assert!(!r["warnings"].to_string().contains("adjustment"), "{r}");
}
/// A layer whose pixels are all transparent draws nothing: an adjustment layer above it in a
/// pass-through group, directly or in a pass-through group inside it, still changes what is below
/// the group.
#[test]
fn an_adjustment_layer_over_transparent_pixels_changes_what_is_below_the_group() {
let clear = || layer("Clear", [0, 0, 1, 1], [50, 50, 50, 0]);
let dodge = || L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) };
let direct = [
layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]),
group_end(),
clear(),
adjustment("Invert", b"nvrt", &[]),
group("Folder", b"pass"),
dodge(),
];
let (s, r) = open(&file(1, 1, &direct, 8, false, false), json!({}));
assert_eq!(row_of(&s, &s.doc().unwrap().doc.layers[0]), [[245, 235, 225, 255]], "{r}");
let nested = [
layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]),
group_end(),
group_end(),
clear(),
adjustment("Invert", b"nvrt", &[]),
group("Inner", b"pass"),
adjustment("Posterize", b"post", &[0, 4, 0, 0]),
group("Folder", b"pass"),
dodge(),
];
let (s, r) = open(&file(1, 1, &nested, 8, false, false), json!({}));
assert_eq!(row_of(&s, &s.doc().unwrap().doc.layers[0]), [[255, 255, 255, 255]], "{r}");
}
/// A layer or group whose layer mask hides all of it draws nothing: an adjustment layer above it in
/// a pass-through group still changes what is below the group, and a shallow knockout hidden that
/// way merges nothing, so the adjustment layers below it stay kept. A layer's mask hides all of it
/// when it hides each of its pixels that isn't fully transparent, and a group's when it hides each
/// such pixel of the group's layers, whatever the mask's value elsewhere; a layer hidden that way
/// hides the layers clipped to it too. The layers in a pass-through group hidden that way don't
/// count as drawing below an adjustment layer above the group.
#[test]
fn an_adjustment_layer_over_layers_their_masks_hide_changes_what_is_below_the_group() {
let black = |l: L| L { mask: Some(([0, 0, 1, 2], 0, 0, vec![0, 0])), ..l };
let under = || layer("Under", [0, 0, 1, 2], [10, 20, 30, 255]);
let dodge = || L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 2], [0, 0, 0, 255]) };
let photo = || layer("Photo", [0, 0, 1, 2], [100, 100, 100, 255]);
let inverted = [[245, 235, 225, 255], [245, 235, 225, 255]];
let masked_layer = [under(), group_end(), black(photo()), adjustment("Invert", b"nvrt", &[]), group("Folder", b"pass"), dodge()];
// A mask over all of the layer's pixels hides it whatever its value outside them.
let white_outside = L { mask: Some(([0, 0, 1, 2], 255, 0, vec![0, 0])), ..photo() };
let covered_layer = [under(), group_end(), white_outside, adjustment("Invert", b"nvrt", &[]), group("Folder", b"pass"), dodge()];
let masked_group = [
under(),
group_end(),
group_end(),
photo(),
black(group("Inner", b"norm")),
adjustment("Invert", b"nvrt", &[]),
group("Folder", b"pass"),
dodge(),
];
let knockout_cut = knockout(black(layer("Cut", [0, 0, 1, 1], [0, 0, 255, 255])), 1, 255);
let masked_knockout = [
under(),
group_end(),
group_end(),
adjustment("Invert", b"nvrt", &[]),
layer("Photo", [0, 0, 1, 1], [100, 100, 100, 255]),
knockout_cut,
group("Inner", b"pass"),
adjustment("Posterize", b"post", &[0, 4, 0, 0]),
group("Folder", b"pass"),
dodge(),
];
// A knockout whose mask hides each pixel it doesn't leave transparent.
let half = L { alpha: Some(vec![255, 0]), mask: Some(([0, 0, 1, 2], 0, 0, vec![0, 255])), ..layer("Cut", [0, 0, 1, 2], [0, 0, 255, 255]) };
let mut transparent_knockout = masked_knockout.clone();
transparent_knockout[5] = knockout(half, 1, 255);
// A pass-through group its mask hides, below Invert in a pass-through group, with a layer drawn
// above that group, under Posterize.
let masked_pass = [
under(),
group_end(),
group_end(),
group_end(),
photo(),
black(group("Hidden", b"pass")),
adjustment("Invert", b"nvrt", &[]),
group("Inner", b"pass"),
layer("Blue", [0, 0, 1, 1], [0, 0, 100, 255]),
adjustment("Posterize", b"post", &[0, 4, 0, 0]),
group("Folder", b"pass"),
dodge(),
];
// Invert in a pass-through group its mask hides keeps nothing above that group: Posterize
// merges with the layer below it, as with no such group.
let masked_invert = [
under(),
group_end(),
group_end(),
adjustment("Invert", b"nvrt", &[]),
black(group("Hidden", b"pass")),
layer("Blue", [0, 0, 1, 1], [0, 0, 100, 255]),
adjustment("Posterize", b"post", &[0, 4, 0, 0]),
group("Folder", b"pass"),
dodge(),
];
// A mask over only the pixels that aren't fully transparent, white outside it.
let corner = |l: L| L { mask: Some(([0, 0, 1, 1], 255, 0, vec![0])), ..l };
let half_photo = || L { alpha: Some(vec![255, 0]), ..photo() };
let corner_layer = [under(), group_end(), corner(half_photo()), adjustment("Invert", b"nvrt", &[]), group("Folder", b"pass"), dodge()];
let corner_group = [
under(),
group_end(),
group_end(),
half_photo(),
corner(group("Inner", b"norm")),
adjustment("Invert", b"nvrt", &[]),
group("Folder", b"pass"),
dodge(),
];
// The same mask over a group with a pixel drawn outside it: the group draws there.
let drawn_group = [
under(),
group_end(),
group_end(),
photo(),
corner(group("Inner", b"norm")),
adjustment("Invert", b"nvrt", &[]),
group("Folder", b"pass"),
dodge(),
];
// A layer its mask hides, with a layer clipped to it.
let clipped_base = [
under(),
group_end(),
black(photo()),
L { clipped: true, ..layer("Red", [0, 0, 1, 2], [200, 0, 0, 255]) },
adjustment("Invert", b"nvrt", &[]),
group("Folder", b"pass"),
dodge(),
];
let cases = [
("layer", &masked_layer[..], inverted),
("covered layer", &covered_layer[..], inverted),
("group", &masked_group[..], inverted),
("knockout", &masked_knockout[..], [[85, 85, 85, 255], [255, 255, 255, 255]]),
("transparent knockout", &transparent_knockout[..], [[85, 85, 85, 255], [255, 255, 255, 255]]),
("pass-through group", &masked_pass[..], [[0, 0, 85, 255], [255, 255, 255, 255]]),
("adjustment in a pass-through group", &masked_invert[..], [[0, 0, 85, 255], [10, 20, 30, 255]]),
("layer covered where it draws", &corner_layer[..], inverted),
("group covered where it draws", &corner_group[..], inverted),
("group drawn outside its mask", &drawn_group[..], [[10, 20, 30, 255], [155, 155, 155, 255]]),
("clipped base", &clipped_base[..], inverted),
];
let rows = |layers: &[L]| {
let (s, _) = open(&file(2, 1, layers, 8, false, false), json!({}));
row_of(&s, &s.doc().unwrap().doc.layers[0])
};
let got: Vec<_> = cases.iter().map(|(what, layers, _)| (*what, rows(layers))).collect();
let want: Vec<_> = cases.iter().map(|(what, _, want)| (*what, want.to_vec())).collect();
assert_eq!(got, want);
}
/// Damaged Invert, Threshold and Posterize layers, masked and clipped, open without a panic.
#[test]
fn damaged_adjustment_layers_never_panic() {
let layers = [
layer("A", [0, 0, 2, 2], [255, 0, 0, 255]),
L { mask: Some(([0, 0, 1, 1], 0, 0, vec![200])), ..adjustment("Invert", b"nvrt", &[]) },
L { clipped: true, ..adjustment("Threshold", b"thrs", &[0, 128, 0, 0]) },
adjustment("Posterize", b"post", &[0, 3, 0, 0]),
];
let cms = |c: [f32; 4]| [c[0], c[1], c[2]];
let good = file(2, 2, &layers, 8, false, false);
assert!(psdlayers::import(&good, true, 1 << 30, cms).unwrap().is_some());
for i in 0..good.len() {
for v in [0, 1, 0x7f, 0x80, 0xff] {
let mut f = good.clone();
f[i] = v;
let _ = psdlayers::import(&f, true, 1 << 30, cms);
let _ = psdlayers::import(&f, false, 64, cms);
}
}
for n in 0..good.len() {
let _ = psdlayers::import(&good[..n], true, 1 << 30, cms);
}
}
/// Each blend mode VectorCraft lacks merges with the layer below by its formula, from the public
/// descriptions: <https://helpx.adobe.com/photoshop/desktop/repair-retouch/adjust-light-tone/blending-mode-descriptions.html>
/// (Vivid Light, Pin Light, Hard Mix, Darker and Lighter Color) and
@@ -1449,6 +2247,12 @@ fn damaged_layers_never_panic() {
assert!(psdlayers::import(&file(8, 8, &many[..16], 8, false, false), false, 512, cms).unwrap().is_some());
let e = psdlayers::import(&file(8, 8, &many, 8, false, false), false, 512, cms).err();
assert!(e.as_deref().is_some_and(|e| e.contains("take more memory to read than allowed")), "{e:?}");
// Looking through those layers' transparency for pixels that draw, below an adjustment layer,
// takes nothing from the allowance.
let mut clear: Vec<L> = (0..16).map(|_| layer("x", [0, 0, 8, 8], [1, 2, 3, 0])).collect();
clear.push(adjustment("Invert", b"nvrt", &[]));
let opened = psdlayers::import(&file(8, 8, &clear, 8, false, false), false, 512, cms);
assert!(opened.as_ref().is_ok_and(Option::is_some), "{:?}", opened.err());
}
/// A layer in a mode VectorCraft lacks above a pass-through group merges with the group's layers
@@ -863,6 +863,78 @@ fn unembed_keeps_the_clipping_path_of_an_embedded_psd() {
}
}
/// Unembed leaves a clipping mask released or edited in the document as it is, with a path and with
/// a folder, for a plain image and for a distorted one: no clip group of the file's clipping path is
/// put back or nested inside the edited mask. Every case runs, and the test names each one that
/// fails.
#[test]
fn unembed_keeps_a_released_or_edited_clipping_mask() {
let dir = vectorcraft_testkit::TempDir::new("psd-unembed-mask");
let data = vectorcraft_format::base64_encode(&red_psd(&triangle_resources()));
let cases = ["release", "move"]
.into_iter()
.flat_map(|edit| [false, true].into_iter().flat_map(move |distort| [(edit, distort, false), (edit, distort, true)]));
let failed: Vec<_> = cases
.filter(|&(edit, distort, folder)| {
std::panic::catch_unwind(|| unembed_mask_case(&dir.join(format!("{edit}-{distort}-{folder}")), &data, edit, distort, folder)).is_err()
})
.collect();
assert!(failed.is_empty(), "failed: {failed:?}");
}
/// One case of [`unembed_keeps_a_released_or_edited_clipping_mask`]: the clipping mask of a placed
/// PSD file's image released or moved (`edit`), the image or the clip group then distorted with
/// `distort`, and the image unembedded into `out`.
fn unembed_mask_case(out: &std::path::Path, data: &str, edit: &str, distort: bool, folder: bool) {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap();
let r = s.execute("file.place", &json!({"name": "cut.psd", "dataBase64": data, "at": [50, 25]})).unwrap();
let (group, image) = (NodeId(r["ids"][0].as_u64().unwrap()), NodeId(r["image"].as_u64().unwrap()));
if edit == "release" {
s.execute("select.set", &json!({"ids": [group.0]})).unwrap();
s.execute("object.clippingMask.release", &json!({})).unwrap();
} else {
let Some(NodeKind::Group { children, .. }) = s.doc().unwrap().doc.node(group).map(|n| &n.kind) else { panic!("a clip group") };
let mask = children[0].id;
s.execute("select.set", &json!({"ids": [mask.0]})).unwrap();
s.execute("object.move", &json!({"dx": 10, "dy": 0})).unwrap();
}
if distort {
let target = if edit == "release" { image } else { group };
s.execute("select.set", &json!({"ids": [target.0]})).unwrap();
s.execute("object.distort", &json!({"corners": [[0, 0], [100, 8], [90, 50], [6, 44]]})).unwrap();
assert!(s.doc().unwrap().doc.node(image).unwrap().is_distorted_image(), "{edit}, folder: {folder}: distorted");
}
let parent = |s: &Session| s.doc().unwrap().doc.parent_of(image);
let before = (parent(&s), parent(&s).and_then(|p| s.doc().unwrap().doc.node(p).cloned()));
std::fs::create_dir_all(out).unwrap();
if folder {
s.execute("links.unembed", &json!({"ids": [image.0], "folder": out})).unwrap();
} else {
s.execute("links.unembed", &json!({"id": image.0, "path": out.join("cut")})).unwrap();
}
let d = &s.doc().unwrap().doc;
let NodeKind::Image(im) = &d.node(image).unwrap().kind else { panic!("an image") };
assert!(im.link.is_some(), "{edit}, folder: {folder}: linked to the file written");
assert_eq!(parent(&s), before.0, "{edit}, folder: {folder}: the image stays where it was");
let after = before.0.and_then(|p| d.node(p));
match (edit, after.map(|n| &n.kind), before.1.as_ref().map(|n| &n.kind)) {
// Released: the image is in no clip group, as before.
("release", Some(NodeKind::Group { clip, .. }), _) => assert!(!clip, "folder: {folder}: the released mask came back"),
("release", _, _) => {}
// Moved: the same clip group of the moved path holds just the image.
(_, Some(NodeKind::Group { children: a, clip: true }), Some(NodeKind::Group { children: b, clip: true })) => {
assert_eq!(a.len(), 2, "{edit}, folder: {folder}: a clip group was nested inside the edited mask");
let path = |c: &std::sync::Arc<vectorcraft_doc::Node>| match &c.kind {
NodeKind::Path { path, .. } => path.anchors().map(|(_, _, a)| [a.p.x, a.p.y]).collect::<Vec<_>>(),
_ => vec![],
};
assert_eq!((path(&a[0]), a[1].id), (path(&b[0]), image), "{edit}, folder: {folder}: the clipping mask");
}
other => panic!("{edit}, folder: {folder}: {other:?}"),
}
}
/// The PNG a PSD file's merged image is kept as holds the clipping path the file names, and only a
/// text chunk within the size limit that reads as a path gives one back.
#[test]
+3 -1
View File
@@ -65,12 +65,14 @@ fn settings_of(p: &Value, cmd: &str) -> Result<Value> {
};
let rays = count_or(p, "rays", 15, cmd)?.min(50);
let rings = count_or(p, "rings", 10, cmd)?.min(50);
// The end point is given whole or not at all: a lone `x2` or `y2` is refused.
let end = match (p.get("x2").and_then(Value::as_f64), p.get("y2").and_then(Value::as_f64)) {
(Some(x), Some(y)) => Point::new(x, y),
_ => {
(None, None) => {
let a = f64_or(p, "direction", 45.0).to_radians();
finite_end(c + Vec2::new(a.cos(), -a.sin()) * f64_or(p, "pathLength", 300.0), cmd)?
}
_ => Point::new(f64_req(p, "x2", cmd)?, f64_req(p, "y2", cmd)?),
};
let mut v = json!({ "cx": c.x, "cy": c.y, "x2": end.x, "y2": end.y, "rays": rays, "rings": rings, "seed": seed });
if let Some(r) = ring_seed {
+5
View File
@@ -1154,11 +1154,16 @@ fn drop_own_overprints(n: &mut Node) {
(r.style.overprint_fill, r.style.overprint_stroke) = (false, false);
}
}
// An image keeps the flag after its color is removed, and a later color would overprint.
if n.extras().colorize_overprint {
n.extras_mut().colorize_overprint = false;
}
}
}
fn overprints(n: &Node) -> bool {
n.appearance.items.iter().any(AppearanceItem::overprint)
|| n.extras().colorize_overprint
|| matches!(&n.kind, NodeKind::Text(t) if t.runs.iter().any(|r| r.style.overprint_fill || r.style.overprint_stroke))
}
+29 -9
View File
@@ -484,10 +484,17 @@ pub(super) fn used_fonts(d: &Document) -> BTreeSet<UsedFont> {
/// in `art` (art read from a file, its resources in `d`), the type in opacity masks included. The
/// pattern being edited is read from the editing layer only.
pub(super) fn art_fonts(d: &Document, art: &[Node]) -> BTreeSet<UsedFont> {
fonts_of(d, art, false)
}
/// [`art_fonts`]; `drawn`: only those the type is drawn in, not the fonts of runs drawn in a font
/// their file carried ([`in_file_fonts`]).
fn fonts_of(d: &Document, art: &[Node], drawn: bool) -> BTreeSet<UsedFont> {
let mut fonts = BTreeSet::new();
let mut add = |n: &Node| {
if let NodeKind::Text(t) = &n.kind {
fonts.extend(t.runs.iter().flat_map(run_fonts));
let file = if drawn { in_file_fonts(t) } else { vec![] };
fonts.extend(t.runs.iter().filter(|r| !file.contains(&(r.style.font_family.as_str(), r.style.font_style.as_str()))).flat_map(run_fonts));
}
};
let patterns = d.patterns.iter().filter(|p| !pattern_being_edited(d, &p.name)).flat_map(|p| p.art.iter().map(|a| &**a));
@@ -659,21 +666,25 @@ impl<'a> Printed<'a> {
}
}
match &n.kind {
NodeKind::Text(_) => {
NodeKind::Text(t) => {
if overflows && self.own {
self.overflow.insert(n.id);
}
if overflows && let (Some(p), Some(owner)) = (&mut self.preflight, self.owner) {
p.overflow.insert(owner);
}
let file = in_file_fonts(t);
for r in runs {
let fonts = run_fonts(r);
if let (Some(p), Some(owner)) = (&mut self.preflight, self.owner) {
for font in &fonts {
p.fonts.entry(font.clone()).or_default().insert(owner);
// Drawn in a font its file carried: printed as the file drew it.
if !file.contains(&(r.style.font_family.as_str(), r.style.font_style.as_str())) {
let fonts = run_fonts(r);
if let (Some(p), Some(owner)) = (&mut self.preflight, self.owner) {
for font in &fonts {
p.fonts.entry(font.clone()).or_default().insert(owner);
}
}
self.fonts.extend(fonts);
}
self.fonts.extend(fonts);
// Inline graphics draw their symbols' art.
if let Some(art) = r.inline.as_ref().filter(|_| draws_inline(r)) {
self.symbol(&art.symbol);
@@ -757,9 +768,18 @@ fn drawn_runs(t: &vectorcraft_doc::TextObject) -> (Vec<&TextRun>, bool) {
/// What an export that draws type (as outlines, embedded fonts or pixels) says when `d` uses font
/// families that aren't available (their type is drawn in the fallback font, not the font it
/// names) or styles that its family doesn't have (the closest style is drawn).
/// names) or styles that its family doesn't have (the closest style is drawn). Type drawn in a
/// font its file carried isn't substituted.
pub(super) fn substitution_warning(d: &Document) -> Option<String> {
substitution_warning_of(used_fonts(d))
substitution_warning_of(fonts_of(d, &[], true))
}
/// The families and styles of the runs of `t` drawn in a font its file carried
/// ([`vectorcraft_text::FontDb::file_faces`]): drawn as the file drew them, not in a substitute,
/// though the font they name isn't available.
fn in_file_fonts(t: &vectorcraft_doc::TextObject) -> Vec<(&str, &str)> {
let faces = vectorcraft_text::FontDb::global().file_faces(t);
t.runs.iter().zip(faces).filter(|(_, f)| f.is_some()).map(|(r, _)| (r.style.font_family.as_str(), r.style.font_style.as_str())).collect()
}
/// [`substitution_warning`] for type set in `fonts`.
+25 -9
View File
@@ -19,7 +19,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add Freeform Point",
[],
None,
"{at: [x,y] (document coordinates), color? (default: the gradient's colour there; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %; the radius of pure colour around the point, a fraction of half the object's larger side; default 0), line?: true (join it to the selected point: extends the line ending there, else starts one), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point to the freeform gradient (an unplaced one keeps its automatic points first) and select it. On a path directly in a graph series, the graph also stores the edited gradient when it is on the topmost visible fill or stroke, as for the other paint.freeform edits (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its points); the points on a label's characters are not stored → {index}",
"{at: [x,y] (document coordinates), color? (default: the gradient's colour there; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %; the radius of pure colour around the point, a fraction of half the object's larger side; default 0), line?: true (join it to the selected point: extends the line ending there, else starts one), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point to the freeform gradient (an unplaced one keeps its automatic points first) and select it. On a path directly in a graph series, the graph also stores the edited gradient when it is on the topmost visible fill or stroke, as for the other paint.freeform edits (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its points); the points on a label's characters are not stored; an error while the proxies show the Live Paint Bucket's colors and no ids, id or item are given → {index}",
has_doc,
add_point
),
@@ -28,7 +28,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Edit Freeform Point",
[],
None,
"{index? (default: the selected point), at?: [x,y] (document coordinates), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} move or recolour a point of the freeform gradient → {index}",
"{index? (default: the selected point), at?: [x,y] (document coordinates), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} move or recolour a point of the freeform gradient; an error while the proxies show the Live Paint Bucket's colors and no ids, id or item are given → {index}",
has_doc,
set_point
),
@@ -37,7 +37,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Delete Freeform Point",
[],
None,
"{index? (default: the selected point), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} remove a point (never the last one); lines through it close up around it and lines left with one point go → {index}",
"{index? (default: the selected point), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} remove a point (never the last one); lines through it close up around it and lines left with one point go; an error while the proxies show the Live Paint Bucket's colors and no ids, id or item are given → {index}",
has_doc,
delete_point
),
@@ -46,7 +46,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add Freeform Line",
[],
None,
"{points: [index, …] (at least two), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} join points with a smooth line through them, in order → {line}",
"{points: [index, …] (at least two), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} join points with a smooth line through them, in order; an error while the proxies show the Live Paint Bucket's colors and no ids, id or item are given → {line}",
has_doc,
add_line
),
@@ -55,7 +55,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Split Freeform Line",
[],
None,
"{line: line index, segment: the segment from the line's point `segment` to the next, t?: 0..1 along it (default 0.5), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point on a line there (colour, opacity and spread between the segment's ends) and select it → {index}",
"{line: line index, segment: the segment from the line's point `segment` to the next, t?: 0..1 along it (default 0.5), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point on a line there (colour, opacity and spread between the segment's ends) and select it; an error while the proxies show the Live Paint Bucket's colors and no ids, id or item are given → {index}",
has_doc,
split_line
),
@@ -64,7 +64,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Select Freeform Point",
[],
None,
"{index: point index | null to clear} select a point of the freeform gradient behind the active proxy (the first selected object's): the point the Gradient tool, the Gradient and Color panels and Delete act on → {index}",
"{index: point index | null to clear} select a point of the freeform gradient behind the active proxy (the first selected object's; an index is an error while the proxies show the Live Paint Bucket's colors): the point the Gradient tool, the Gradient and Color panels and Delete act on → {index}",
has_doc,
select_point
),
@@ -73,7 +73,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Freeform Gradient",
[],
None,
"{stroke?: bool (default: the active proxy)} the freeform gradient behind the proxy of the first selected object → {mode: points|lines, points: [{at: [x,y] (document coordinates), color, opacity, spread}], lines: [[index, …]], selected: index|null}",
"{stroke?: bool (default: the active proxy)} the freeform gradient behind the proxy of the first selected object (an error while the proxies show the Live Paint Bucket's colors) → {mode: points|lines, points: [{at: [x,y] (document coordinates), color, opacity, spread}], lines: [[index, …]], selected: index|null}",
has_doc,
get
),
@@ -81,6 +81,14 @@ pub fn specs() -> Vec<CommandSpec> {
}
const NOT_FREEFORM: &str = "the paint is not a freeform gradient (apply one with paint.editGradient {kind: \"freeform\"})";
const BUCKET_NOT_FREEFORM: &str = "the Live Paint Bucket's colors have no freeform points (give ids, id or item to edit an object's)";
const BUCKET_NO_POINTS: &str = "the Live Paint Bucket's colors have no freeform points";
/// The error of `paint.freeform.get` and `paint.freeform.selectPoint` when the active proxy shows no freeform gradient:
/// while the Live Paint Bucket paints, the proxies show its colors, which have none.
fn no_proxy_freeform(s: &Session) -> &'static str {
if s.bucket_paints() { BUCKET_NO_POINTS } else { NOT_FREEFORM }
}
impl Session {
/// The selected freeform point (`paint.freeform.selectPoint`), while the gradient it was
@@ -179,6 +187,14 @@ pub(crate) fn parse_mode(m: &str) -> std::result::Result<FreeformMode, String> {
/// as one undo step; returns what it returned for the first. An unplaced gradient gets the
/// automatic points it shows first, and the stops follow the points' colours.
fn edit<R>(s: &mut Session, p: &Value, cmd: &str, mut f: impl FnMut(&mut Freeform, Space) -> std::result::Result<R, String>) -> Result<R> {
// While the Live Paint Bucket paints, the proxies show its colors, which have no freeform points
// (paint.freeform.get finds none): an edit that names no target is refused. A bad `aligned` or
// `target` is refused first, as it is without the bucket.
if super::paint::for_bucket(s, p) {
super::appearance::aligned(p, cmd)?;
super::appearance::targets_contents(p)?;
return Err(bad(cmd, BUCKET_NOT_FREEFORM));
}
let item = item_target(s, p, cmd)?;
let stroke = edits_stroke(s, p, item, !s.fill_active, cmd)?;
let item = item.of_kind(s, !stroke);
@@ -331,7 +347,7 @@ fn select_point(s: &mut Session, p: &Value) -> Result<Value> {
Some(Value::Null) => None,
Some(v) => {
let i = v.as_u64().map(index).ok_or_else(|| bad(C, "`index` must be a whole number or null"))?;
let (f, _) = s.proxy_freeform(!s.fill_active).ok_or_else(|| bad(C, NOT_FREEFORM))?;
let (f, _) = s.proxy_freeform(!s.fill_active).ok_or_else(|| bad(C, no_proxy_freeform(s)))?;
check_index(&f, i).map_err(|e| bad(C, e))?;
Some(i)
}
@@ -343,7 +359,7 @@ fn select_point(s: &mut Session, p: &Value) -> Result<Value> {
fn get(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "paint.freeform.get";
let stroke = switch_or(p, "stroke", !s.fill_active, C)?;
let (f, _) = s.proxy_freeform(stroke).ok_or_else(|| bad(C, NOT_FREEFORM))?;
let (f, _) = s.proxy_freeform(stroke).ok_or_else(|| bad(C, no_proxy_freeform(s)))?;
let selected = if stroke != s.fill_active { s.selected_freeform_point().filter(|i| *i < f.points.len()) } else { None };
let mut v = vectorcraft_tools::params::freeform_json(&f);
v["selected"] = json!(selected);
+1 -1
View File
@@ -24,7 +24,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Gradient",
["Window", "Gradient"],
None,
"{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; diamond runs the stops from the center out to a square with a corner at the end of the vector; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (how the colours between the stops mix: in display RGB, perceptually (OKLab) so the steps look even, or around the hue wheel: hue, saturation and brightness each change evenly from one stop to the next, the hue angle falling with hue-clockwise (red, magenta, blue, cyan, green, yellow) and rising with hue-counterclockwise; two stops whose hues are less than half a color level apart keep that hue; a stop whose RGB numbers are less than half a color level apart is gray and takes the hue of the stop it mixes with, and black that stop's saturation too; these two methods are VectorCraft's own, and SVG and PDF exports draw their gradients as RGB images, CMYK and spot color stops included; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial, conic or diamond, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), spread?: pad|repeat|reflect (linear, radial, conic and diamond: what the gradient paints past the ends of its stops: pad carries the end colors on; repeat and reflect run the stops `repeats` times along the vector (around the circle, for a conic) and on past both ends, reflect mirroring every other run; an error on a freeform gradient), repeats?: 1..100 (a whole number: how many times repeat and reflect run the stops along the vector; VectorCraft's own limit; pad keeps it unused), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial, conic and diamond: the vector turns about the center), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep and is an error for the other kinds; an error when no object is edited, as with nothing selected, the Live Paint Bucket's gradient, or a fill edit of a Live Paint group without faces: the default gradient fits each new object and keeps no aspect), reverse?: bool (the same ramp the other way round: the stops in reverse order, and a hue method turned the other way unless `method` is given too), dither?: bool (fills only: a linear, radial, conic or diamond gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.setFill; without stroke, the kind of the row edited), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient. Without `item`, a Live Paint group's faces take a fill edit and its edges take a stroke edit. On a path directly in a graph series, the graph also stores the gradient when it is on the topmost visible fill or stroke (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its placement), and on its characters their gradient without its placement, fitted to each label. While the Live Paint Bucket is the active tool and no ids, id or i Line truncated
"{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; diamond runs the stops from the center out to a square with a corner at the end of the vector; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (how the colours between the stops mix: in display RGB, perceptually (OKLab) so the steps look even, or around the hue wheel: hue, saturation and brightness each change evenly from one stop to the next, the hue angle falling with hue-clockwise (red, magenta, blue, cyan, green, yellow) and rising with hue-counterclockwise; two stops whose hues are less than half a color level apart keep that hue; a stop whose RGB numbers are less than half a color level apart is gray and takes the hue of the stop it mixes with, and black that stop's saturation too; these two methods are VectorCraft's own, and SVG and PDF exports draw their gradients as RGB images, CMYK and spot color stops included; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial, conic or diamond, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), spread?: pad|repeat|reflect (linear, radial, conic and diamond: what the gradient paints past the ends of its stops: pad carries the end colors on; repeat and reflect run the stops `repeats` times along the vector (around the circle, for a conic) and on past both ends, reflect mirroring every other run; an error on a freeform gradient), repeats?: 1..100 (a whole number: how many times repeat and reflect run the stops along the vector; VectorCraft's own limit; pad keeps it unused), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial, conic and diamond: the vector turns about the center), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep and is an error for the other kinds; an error when no object is edited, as with nothing selected, the Live Paint Bucket's gradient, or a fill edit of a Live Paint group without faces: the default gradient fits each new object and keeps no aspect), reverse?: bool (the same ramp the other way round: the stops in reverse order, and a hue method turned the other way unless `method` is given too), dither?: bool (fills only: a linear, radial, conic or diamond gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.setFill; without stroke, the kind of the row edited), ids?|id?, defaultsOnly?: bool (as paint.setFill), strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient. Without `item`, a Live Paint group's faces take a fill edit and its edges take a stroke edit. On a path directly in a graph series, the graph also stores the gradient when it is on the topmost visible fill or stroke (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its placement), and on its characters their gradient without its placement, fitted to each label. While the Live Paint Bucke Line truncated
has_doc,
edit_gradient
),
+1 -1
View File
@@ -33,7 +33,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Apply Gradient Preset",
[],
None,
"{name: a preset's name (gradient.presets.list), stroke?, item?, ids?|id?, target? (as paint.editGradient)} give the gradient behind the active proxy (or the targeted fill or stroke) the preset's type, stops, method, spread and repeats (a freeform preset's: the first three), and a fill its dither, keeping its placement; a solid or no paint becomes the gradient. One undo step, as paint.editGradient (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), only the default changes, by the active proxy) → {name, ids: the objects painted (none: only the default changed)}",
"{name: a preset's name (gradient.presets.list), stroke?, item?, ids?|id?, defaultsOnly?, target? (as paint.editGradient)} give the gradient behind the active proxy (or the targeted fill or stroke) the preset's type, stops, method, spread and repeats (a freeform preset's: the first three), and a fill its dither, keeping its placement; a solid or no paint becomes the gradient. One undo step, as paint.editGradient (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, by the active proxy) → {name, ids: the objects painted (none: only the default changed)}",
has_doc,
apply
),
+104
View File
@@ -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();
@@ -9611,6 +9692,29 @@ fn appearance_commands_given_the_axes_or_legend_group_edit_its_lines_and_labels(
}
}
/// Aligned rows copied to `to` given the Legend group, whose labels have the same rows, go to `to` in every label.
#[test]
fn aligned_copies_given_the_legend_group_go_to_to_when_its_labels_have_the_same_rows() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
let id = graph(&mut s, "column");
let labels = |s: &Session| -> Vec<vectorcraft_doc::Appearance> {
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
group(&n, "Legend").children().unwrap().iter().map(|c| (*c.appearance).clone()).collect()
};
let legend = group(s.doc().unwrap().doc.node(id).unwrap(), "Legend").id;
s.execute("appearance.addFill", &json!({"ids": [legend.0]})).unwrap();
s.execute("appearance.addStroke", &json!({"ids": [legend.0]})).unwrap();
let was = labels(&s);
assert!(was.len() >= 2 && was.iter().all(|a| *a == was[0]) && was[0].items.len() >= 2, "{was:?}");
let top = was[0].items.len() - 1;
s.execute("appearance.duplicateItem", &json!({"ids": [legend.0], "index": top, "to": 0, "aligned": true})).unwrap();
for a in labels(&s) {
assert_eq!(a.items.len(), was[0].items.len() + 1);
assert_eq!(a.items[0], was[0].items[top], "the copy is at the bottom");
}
}
/// A row index given the Axes group, whose lines and labels have different rows, is refused unless it is `aligned`, a row
/// of the backmost member's stack: then the members that share that row change, the labels keep theirs, and the graph
/// keeps the change when it is drawn again.
+5 -2
View File
@@ -66,7 +66,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Set Current Layer",
[],
None,
"{id} click a row: it alone is highlighted, and the layer it is (or the layer it is in) becomes the current layer, where new art goes. Not an undo step → {id, layer}",
"{id, keepRows?: bool} click a row: it alone is highlighted, and the layer it is (or the layer it is in) becomes the current layer, where new art goes. `keepRows` true leaves the highlighted rows as they are. Not an undo step → {id, layer}",
has_doc,
set_current
),
@@ -633,10 +633,13 @@ fn duplicate_rows(s: &mut Session, p: &Value) -> Result<Value> {
fn set_current(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "layer.setCurrent";
let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?;
let keep_rows = switch_or(p, "keepRows", false, C)?;
let st = s.doc_mut()?;
let layer = st.doc.layer_containing(id).ok_or(EngineError::NoNode(id))?;
st.active_layer = Some(layer);
st.layer_rows = vec![id];
if !keep_rows {
st.layer_rows = vec![id];
}
st.revision += 1;
Ok(json!({ "id": id.0, "layer": layer.0 }))
}
+1 -1
View File
@@ -447,7 +447,7 @@ fn locate(s: &mut Session, p: &Value) -> Result<Value> {
}
let row = ancestry.last().copied().ok_or(EngineError::NoNode(id))?;
st.layer_rows = vec![row];
st.locate_reveal = Some(row);
st.layers_reveal = Some(crate::LayersReveal::Row(row));
st.revision += 1;
let ancestry: Vec<u64> = ancestry.iter().map(|i| i.0).collect();
Ok(if layers_only { json!({ "id": row.0, "objectId": id.0, "ancestry": ancestry }) } else { json!({ "id": id.0, "ancestry": ancestry }) })
+22 -18
View File
@@ -20,7 +20,6 @@ use serde_json::{Map, Value, json};
use vectorcraft_color::{Color, GradientPaint, Paint};
use vectorcraft_doc::{Appearance, Node, NodeId, TextStyleDef};
use super::clipboard::SwatchChoices;
use super::{CommandSpec, EngineError, Result, Session, always, bad, cmd, color_value, has_doc, ids_param, index_opt, ok, point_param, str_param};
use crate::Clipboard;
@@ -713,7 +712,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Use Library Item",
[],
None,
"{library?, kind, item: name (graphic: id or name), center?: [x, y] (graphic; default: the first artboard's centre), to?: fill|stroke (colors, gradients, patterns; default: the kind's), recorded?: the item as it was when used (recorded in the journal so a replay matches)} graphic: place a copy centred on `center`, its resources pasted along, selected, one undo step; colors and gradients: paint the selection (and the defaults) as paint.setFill/paint.setStroke, a gradient fitting each object; a spot color links to the document's spot swatch of its ink's name, added when the document has none of that colour (a name taken by another colour gets a number), one undo step; patterns: add the pattern and its swatch to the document (a name the document gives another pattern gets a number; the same pattern is reused) and paint the selection (and the defaults) with it, one undo step; charStyle/paraStyle: add the style to the document (a name taken by different attributes gets a number; a character style's color linked to a swatch that isn't a global or spot swatch of the document keeps the color it shows, unlinked) and apply it to the selected text, one undo step → {kind, ids?, style?}",
"{library?, kind, item: name (graphic: id or name), center?: [x, y] (graphic; default: the first artboard's centre), to?: fill|stroke (colors, gradients, patterns; default: the kind's), defaultsOnly?: bool (colors, gradients, patterns: paint only the defaults, as with paint.setFill's; the journal records it for an item used while the Live Paint Bucket is the active tool), recorded?: the item as it was when used (recorded in the journal so a replay matches)} graphic: place a copy centred on `center`, its resources pasted along, selected, one undo step; colors and gradients: paint the selection (and the defaults) as paint.setFill/paint.setStroke, a gradient fitting each object; a spot color links to the document's spot swatch of its ink's name, added when the document has none of that colour (a name taken by another colour gets a number), one undo step; patterns: add the pattern and its swatch to the document (a name the document gives another pattern gets a number; the same pattern is reused, also when its art links to the document's own color of a name; a global or spot color its art links to whose name the document gives another color comes in numbered, or as the document's numbered copy of the same color, and the pattern links to it) and paint the selection (and the defaults) with it, one undo step; charStyle/paraStyle: add the style to the document (a name taken by different attributes gets a number; a character style's color linked to a swatch that isn't a global or spot swatch of the document keeps the color it shows, unlinked) and apply it to the selected text, one undo step → {kind, ids?, style?}",
has_doc,
use_item
),
@@ -1186,6 +1185,7 @@ fn item_param<'a>(s: &Session, p: &'a Value, cmd: &str) -> Result<(String, Kind,
fn use_item(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "library.use";
super::switch_or(p, "defaultsOnly", false, C)?;
// A replay (the journal) carries what the item was, so it doesn't depend on the library.
let recorded = p.get("recorded").cloned();
let (kind, data) = match recorded {
@@ -1247,18 +1247,20 @@ fn use_item(s: &mut Session, p: &Value) -> Result<Value> {
}
Kind::FillColor | Kind::StrokeColor => {
let stroke = to_stroke(p, kind)?;
let only = super::paint::defaults_only(s, p, C)?;
let color = data.get("color").cloned().ok_or_else(|| bad(C, "no colour"))?;
let set = if stroke { "paint.setStroke" } else { "paint.setFill" };
match str_param(&data, "spot").map(str::trim).filter(|n| !n.is_empty()) {
Some(ink) => use_spot(s, set, ink, &color, &data)?,
Some(ink) => use_spot(s, set, ink, &color, &data, only)?,
None => {
s.execute(set, &json!({ "color": color }))?;
s.execute(set, &super::paint::with_defaults_only(json!({ "color": color }), only))?;
}
}
Ok(json!({ "kind": if stroke { "strokeColor" } else { "fillColor" } }))
}
Kind::FillGradient | Kind::StrokeGradient => {
let stroke = to_stroke(p, kind)?;
let only = super::paint::defaults_only(s, p, C)?;
let damaged = || bad(C, "the library item is damaged");
let mut g: GradientPaint = data.get("gradient").cloned().and_then(|v| serde_json::from_value(v).ok()).ok_or_else(damaged)?;
if !clean_gradient(&mut g) {
@@ -1268,12 +1270,13 @@ fn use_item(s: &mut Session, p: &Value) -> Result<Value> {
for st in &mut g.gradient.stops {
st.color = super::paint::new_color(s, &json!({}), st.color);
}
super::paint::apply_paint(s, &json!({}), Paint::Gradient(Box::new(g)), !stroke)?;
super::paint::apply_paint(s, &super::paint::with_defaults_only(json!({}), only), Paint::Gradient(Box::new(g)), !stroke)?;
Ok(json!({ "kind": if stroke { "strokeGradient" } else { "fillGradient" } }))
}
Kind::FillPattern | Kind::StrokePattern => {
let stroke = to_stroke(p, kind)?;
let pattern = use_pattern(s, &data, stroke)?;
let only = super::paint::defaults_only(s, p, C)?;
let pattern = use_pattern(s, &data, stroke, only)?;
Ok(json!({ "kind": if stroke { "strokePattern" } else { "fillPattern" }, "pattern": pattern }))
}
Kind::CharStyle | Kind::ParaStyle => {
@@ -1304,8 +1307,8 @@ fn use_item(s: &mut Session, p: &Value) -> Result<Value> {
/// Paint with library spot colour `ink` (`color` its full-strength colour, `data`'s `tint` its
/// tint) through `set` (paint.setFill or paint.setStroke), linked to the document's spot swatch of
/// that name: the one it has when it is the same colour, else a new one (a name taken by another
/// colour gets a number), one undo step (#5812).
fn use_spot(s: &mut Session, set: &str, ink: &str, color: &Value, data: &Value) -> Result<()> {
/// colour gets a number), one undo step (#5812). With `only`, only the default takes it.
fn use_spot(s: &mut Session, set: &str, ink: &str, color: &Value, data: &Value, only: bool) -> Result<()> {
const C: &str = "library.use";
let c = color_value(color).ok_or_else(|| bad(C, "the library item is damaged"))?;
let tint = data.get("tint").and_then(Value::as_f64).filter(|t| t.is_finite()).map_or(1.0, |t| t.clamp(0.0, 1.0));
@@ -1322,7 +1325,7 @@ fn use_spot(s: &mut Session, set: &str, ink: &str, color: &Value, data: &Value)
if tint < 1.0 {
p["tint"] = json!(tint * 100.0);
}
s.execute(set, &p)?;
s.execute(set, &super::paint::with_defaults_only(p, only))?;
Ok(())
})
}
@@ -1340,8 +1343,8 @@ fn to_stroke(p: &Value, kind: Kind) -> Result<bool> {
/// Add library pattern `data` (`{pattern, data}`) to the document, with its swatch and the
/// resources its art uses (the same pattern there already is reused; a name the document gives
/// another one gets a number), and paint the selection's fill (`stroke`: stroke) and the default
/// with it, one undo step → the pattern's name in the document.
fn use_pattern(s: &mut Session, data: &Value, stroke: bool) -> Result<String> {
/// with it (with `only`, only the default), one undo step → the pattern's name in the document.
fn use_pattern(s: &mut Session, data: &Value, stroke: bool, only: bool) -> Result<String> {
const C: &str = "library.use";
let damaged = || bad(C, "the library item is damaged");
let bytes = data.get("data").and_then(Value::as_str).and_then(vectorcraft_format::base64_decode).ok_or_else(damaged)?;
@@ -1353,12 +1356,13 @@ fn use_pattern(s: &mut Session, data: &Value, stroke: bool) -> Result<String> {
if clip.nodes.is_empty() {
return Err(damaged());
}
let choices = SwatchChoices::default();
// The pattern's name in the document, worked out on a copy: nothing to add is no edit.
let mut probe = (*s.doc()?.doc).clone();
let imported = clip.import_into(&mut probe, &choices, false)?;
let renamed = imported.renamed.iter().find(|r| r["kind"] == "pattern" && r["from"] == name.as_str()).and_then(|r| r["to"].as_str());
let target = renamed.unwrap_or(&name).to_string();
// The pattern's name in the document, worked out on a copy: nothing to add is no edit. A global
// 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(&current, &doc, &name, &clip, &Default::default())?;
drop(current);
let target = super::patternlib::imported_name(&imported, &name);
let paint = vectorcraft_doc::pattern::pattern_paint(&target);
// A pattern the document holds without a swatch (an imported SVG's) gets one.
let has_swatch =
@@ -1378,7 +1382,7 @@ fn use_pattern(s: &mut Session, data: &Value, stroke: bool) -> Result<String> {
}
// The pattern itself, not a swatch of its name (a color swatch can share it); `swatch` keeps
// the placement of a pattern the targets already have, as picking its swatch does.
super::paint::apply_paint(s, &json!({ "swatch": target }), paint.clone(), !stroke)
super::paint::apply_paint(s, &super::paint::with_defaults_only(json!({ "swatch": target }), only), paint.clone(), !stroke)
})?;
Ok(target)
}
+64 -10
View File
@@ -108,7 +108,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Unembed",
[],
None,
"{id?: an embedded image (default: the one selected), path?, ids?: [image ids] (instead of id; one id is the same as id), folder?} write the image's pixels to the file at path and link the image to it, keeping its bounds (an image changed by Perspective Distort or Free Distort keeps its corners). The image is written as stored (PNG, JPEG, GIF, WebP or TIFF; as PNG when that format is not one of VectorCraft's raster file formats) when path has no extension or names the stored format, and converted when path ends in another of .png/.jpg/.jpeg/.gif/.webp/.tif/.tiff/.bmp. Written as stored (here and with folder), an image from a PSD or PSB file keeps the clip group of the clipping path that file names, and the file written keeps the path, so Open, Place, Relink and Update Links read the file with that clip group (drawn through a distorted image's corners); a converted file holds no clipping path, and the clip group becomes a plain group. One undo step → {id, path}; no path → {name, dataBase64} (nothing changes: there is no file to link to). With folder: write each embedded image of ids or id (default: the selected embedded images) to a new file in folder, as stored (as PNG when that format is not one of VectorCraft's raster file formats), named after the image (characters a file name can't hold become _; Image when nothing is left), with Name 2 … Name 99 when the name is taken; a file already there is never replaced. Linked images among ids are left as they are. Each image links to its file and keeps its bounds (a distorted image its corners). One undo step (undo does not remove the files); when a file can't be written, the files this call wrote are removed and nothing changes → {unembedded: [{id, path}], skipped: [ids of linked images]}; id with ids, path with folder, and ids of more or fewer than one image without folder are errors",
"{id?: an embedded image (default: the one selected), path?, ids?: [image ids] (instead of id; one id is the same as id), folder?} write the image's pixels to the file at path and link the image to it, keeping its bounds (an image changed by Perspective Distort or Free Distort keeps its corners). The image is written as stored (PNG, JPEG, GIF, WebP or TIFF; as PNG when that format is not one of VectorCraft's raster file formats) when path has no extension or names the stored format, and converted when path ends in another of .png/.jpg/.jpeg/.gif/.webp/.tif/.tiff/.bmp. Written as stored (here and with folder), an image from a PSD or PSB file keeps the clip group of the clipping path that file names, and the file written keeps the path, so Open, Place, Relink and Update Links read the file with that clip group (drawn through a distorted image's corners); a converted file holds no clipping path, and the clip group becomes a plain group. A clipping mask released, edited or made in the document stays as it is, in either case. One undo step → {id, path}; no path → {name, dataBase64} (nothing changes: there is no file to link to). With folder: write each embedded image of ids or id (default: the selected embedded images) to a new file in folder, as stored (as PNG when that format is not one of VectorCraft's raster file formats), named after the image (characters a file name can't hold become _; Image when nothing is left), with Name 2 … Name 99 when the name is taken; a file already there is never replaced. Linked images among ids are left as they are. Each image links to its file and keeps its bounds (a distorted image its corners). One undo step (undo does not remove the files); when a file can't be written, the files this call wrote are removed and nothing changes → {unembedded: [{id, path}], skipped: [ids of linked images]}; id with ids, path with folder, and ids of more or fewer than one image without folder are errors",
has_doc,
unembed
),
@@ -328,7 +328,12 @@ impl<'a> LinkBase<'a> {
/// The open document `st`'s. One with no file of its own looks beside the file it was read from.
pub(crate) fn of(st: &'a crate::DocState) -> Self {
let (path, from) = (st.path.as_deref(), st.links_from.as_deref());
Self::of_files(st.path.as_deref(), st.links_from.as_deref())
}
/// An open document's, by its own file `path` and the file it was read from, `from`
/// ([`crate::DocState::links_from`]), as [`Self::of`] gives them.
pub(crate) fn of_files(path: Option<&'a str>, from: Option<&'a str>) -> Self {
Self { doc: path.or(from), relative: from.or(path) }
}
}
@@ -401,6 +406,29 @@ fn locate(link: &LinkInfo, base: LinkBase) -> Option<Found> {
Some(f)
}
/// The files the links of `d` (a document looking from `base`) lead to now: where [`locate`]
/// finds each linked image's and placed document's file from `base` and from no document (as
/// output reads them, [`full_linked_images`]), the plate files of their own of images placed from
/// DCS files, and the image files its data sets name. The commands a script runs may read these
/// for the documents open when the run began, as the person left them
/// ([`crate::file_access::ScriptGate::linked`]).
pub(crate) fn files_linked(d: &Document, base: LinkBase) -> Vec<String> {
let mut out = vec![];
for g in groups(d, None) {
for from in [base, LinkBase::default()] {
let Some(f) = locate(&g.link, from) else { continue };
out.extend(g.plate_files.iter().filter_map(|p| super::place::dcs::plate_file_path(&f.path, &p.name)));
out.push(f.path);
}
}
let values = d.variables.datasets.iter().flat_map(|set| set.values.values());
out.extend(values.filter_map(|v| match v {
DataValue::Image(path) => fileio::document_path(path, base.doc).ok(),
_ => None,
}));
out
}
/// The place `stored` names from the file `from`, as `resolve` ([`fileio::document_path`]) follows
/// it, when it also follows that place from the document's own file `doc`: a network share the
/// document is no longer on is refused.
@@ -563,7 +591,7 @@ pub(crate) fn full_linked_images<'a>(d: &'a Document, base: LinkBase) -> (Cow<'a
Some(f) if img.blob.bytes.as_slice() == bytes.as_slice() => f.mime.to_string(),
_ => img.blob.mime.clone(),
};
out.images.insert(key, ImageBlob { mime, bytes: img.blob.bytes, proxy: preview });
out.images.insert(key, ImageBlob { mime, bytes: img.blob.bytes, proxy: preview, file_font: Default::default() });
}
let mut warnings = vec![];
match previews.len() {
@@ -1264,7 +1292,31 @@ fn warped(path: &PathData, map: &Homography) -> Option<PathData> {
/// placed as its Placement Options say (`force`: as that Preserve choice says, whatever they say);
/// with `also` (a file's path and the content shown), so do the images outside the layer tree that
/// show that content.
fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Option<Preserve>, also: Option<(&str, &str)>) -> Result<()> {
fn install(d: &mut Document, ids: &[NodeId], read: FileRead, force: Option<Preserve>, also: Option<(&str, &str)>) -> Result<()> {
install_with(d, ids, read, force, also, false)
}
/// What Unembed (`unembed`) does with the clip `to` of an image whose clip group holding just it
/// has a clipping path (`held`): a clipping mask released, edited or made in the document stays as
/// it is, and only a clip group of the old file's own clipping path follows the file written.
fn unembed_clip(to: ClipTo, held: bool) -> ClipTo {
match to {
ClipTo::Nest(_) => ClipTo::Keep,
ClipTo::File(_) if !held => ClipTo::Keep,
to => to,
}
}
/// As [`install`]; with `unembed`, each clip goes through [`unembed_clip`].
fn install_with(
d: &mut Document,
ids: &[NodeId],
(link, img): FileRead,
force: Option<Preserve>,
also: Option<(&str, &str)>,
unembed: bool,
) -> Result<()> {
let keep = |to: ClipTo, held: bool| if unembed { unembed_clip(to, held) } else { to };
let new_pt = super::place::pt_per_px(img.ppi);
let mut clips = vec![];
let nested = nested_ids(d, ids);
@@ -1290,7 +1342,7 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio
_ => None,
};
let clip = refill_distorted(&mut n, old_clip.as_ref(), &link, &img, held);
return (n, clip);
return (n, keep(clip, held.is_some()));
}
if let NodeKind::Image(im) = &mut n.kind {
let o = PlacementOptions { preserve: force.unwrap_or(im.placement.preserve), ..im.placement };
@@ -1300,7 +1352,7 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio
None => (super::place::pt_per_px(None), None),
};
let (xf, c) = placed_xf(im.xf, size(im.width, im.height), old_pt, size(img.width, img.height), new_pt, o);
clip = clip_to(im.xf, old_clip, c, &img, xf, held);
clip = keep(clip_to(im.xf, old_clip, c, &img, xf, held), held.is_some());
(im.key, im.width, im.height, im.xf, im.link) = (img.key.clone(), img.width, img.height, xf, Some(link.clone()));
}
(n, clip)
@@ -1315,7 +1367,8 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio
};
let held = clip_path_of(d, *id).map(|(path, rule)| (path.clone(), rule));
if let Some(n) = d.node_mut(*id) {
clips.push((*id, refill_distorted(n, old_clip.as_ref(), &link, &img, held.as_ref().map(|(path, rule)| (path, *rule)))));
let clip = refill_distorted(n, old_clip.as_ref(), &link, &img, held.as_ref().map(|(path, rule)| (path, *rule)));
clips.push((*id, keep(clip, held.is_some())));
}
continue;
}
@@ -1326,7 +1379,8 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio
// Placement Options' clip, else the clipping path of a DCS file (read again with its
// plates) or of a PSD or PSB file.
let old_clip = d.images.get(&im.key).and_then(file_clip);
clips.push((*id, clip_to(im.xf, old_clip.as_ref(), clip, &img, xf, clip_path_of(d, *id))));
let held = clip_path_of(d, *id);
clips.push((*id, keep(clip_to(im.xf, old_clip.as_ref(), clip, &img, xf, held), held.is_some())));
if let Some(n) = d.node_mut(*id)
&& let NodeKind::Image(im) = &mut n.kind
{
@@ -2829,7 +2883,7 @@ fn unembed(s: &mut Session, p: &Value) -> Result<Value> {
write_file(&path, &bytes)?;
let read = (link_info(&path, &bytes), img);
drop(doc);
s.edit("Unembed", |d, _| editing_brush_art(d, |d| install(d, &[id], read, Some(Preserve::Bounds), None)))?;
s.edit("Unembed", |d, _| editing_brush_art(d, |d| install_with(d, &[id], read, Some(Preserve::Bounds), None, true)))?;
Ok(json!({ "id": id.0, "path": path }))
}
@@ -2896,7 +2950,7 @@ fn unembed_to_folder(s: &mut Session, p: &Value, ids: Option<Vec<NodeId>>) -> Re
drop(doc);
let done: Vec<Value> = reads.iter().map(|(id, (l, _))| json!({ "id": id.0, "path": l.path })).collect();
let edited = s.edit("Unembed", |d, _| {
editing_brush_art(d, |d| reads.into_iter().try_for_each(|(id, read)| install(d, &[id], read, Some(Preserve::Bounds), None)))
editing_brush_art(d, |d| reads.into_iter().try_for_each(|(id, read)| install_with(d, &[id], read, Some(Preserve::Bounds), None, true)))
});
if let Err(e) = edited {
remove_written(&written);
+34 -18
View File
@@ -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)
}
+67 -8
View File
@@ -13,14 +13,29 @@
//! resets new art when it opens such a document.
use std::borrow::Cow;
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_color::{BlendMode, Paint};
use vectorcraft_doc::{Appearance, AppearanceItem, ColorMode, DEFAULT_GRAPHIC_STYLE, Document, FillLayer, GraphicStyle, Node, NodeKind, StrokeLayer};
use vectorcraft_tools::PaintDefaults;
/// The object new art takes its appearance from, with that appearance
/// ([`Session::new_art_source`]).
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct NewArtSource {
doc: u64,
id: vectorcraft_doc::NodeId,
appearance: Appearance,
opacity: f32,
blend: BlendMode,
style: Option<String>,
}
use super::gradient::unplaced;
use super::paint::SelectionPaints;
use super::{CommandSpec, Result, Session, always, cmd, switch_or};
use crate::doc_state::{SelectionRecord, objects_only};
pub fn specs() -> Vec<CommandSpec> {
vec![
@@ -207,16 +222,35 @@ impl Session {
/// After each command: with New Art Has Basic Appearance off, new art takes the appearance of
/// the first selected object (so the last selection's once nothing is selected). Not while the
/// Live Paint Bucket is the active tool: the fill and stroke are the colors it paints with.
/// Live Paint Bucket is the active tool: the fill and stroke are the colors it paints with. Nor
/// after a command that changed only them (`defaultsOnly`), unless a later step of a batch
/// changed what new art would take ([`Session::new_art_source`]).
pub(crate) fn inherit_new_art(&mut self) {
if self.prefs.new_art_basic || self.bucket_paints() {
return;
}
let Some(st) = self.active() else { return };
let Some(n) = st.selection.subjects().first().and_then(|id| st.doc.node(*id)) else { return };
let style = super::style::linked_style(&st.doc, n).map(|g| g.name.clone());
let (ap, opacity, blend) = (super::style::captured(n), n.opacity, n.blend);
self.take_new_art(ap, opacity, blend, style, true);
let Some(source) = self.new_art_source() else { return };
if matches!(&self.defaults_only_ran, Some(Some(ran)) if *ran == source) {
return;
}
let NewArtSource { appearance, opacity, blend, style, .. } = source;
self.take_new_art(appearance, opacity, blend, style, true);
}
/// What [`Session::inherit_new_art`] gives new art: the appearance of the active document's
/// first selected object, if any.
pub(crate) fn new_art_source(&self) -> Option<NewArtSource> {
let st = self.active()?;
let id = *st.selection.subjects().first()?;
let n = st.doc.node(id)?;
Some(NewArtSource {
doc: st.uid,
id,
appearance: super::style::captured(n),
opacity: n.opacity,
blend: n.blend,
style: super::style::linked_style(&st.doc, n).map(|g| g.name.clone()),
})
}
/// After a command changed the selection, with New Art Has Basic Appearance on: the fill and
@@ -236,9 +270,10 @@ impl Session {
if !has_paint {
return;
}
let (fill_mixed, stroke_mixed) = self.proxy_mixed();
let read = self.read_selection_paints();
let (fill_mixed, stroke_mixed) = read.as_ref().map_or_else(|| self.proxy_mixed(), |p| (p.fill_mixed, p.stroke_mixed));
let (fill, stroke) = self.proxy_paints();
let weight_mixed = self.active().is_some_and(|st| st.stroke_mixed().weight);
let weight_mixed = read.as_ref().map_or_else(|| self.active().is_some_and(|st| st.stroke_mixed().weight), |p| p.weight_mixed);
let weight = self.shown_stroke().filter(|st| st.paint != Paint::None && !weight_mixed).map(|st| st.width);
if !fill_mixed {
self.paint.fill = unplaced(&fill);
@@ -250,6 +285,30 @@ impl Session {
self.paint.stroke_width = width;
}
}
/// The [`SelectionPaints`] of the active document's selection, read now and kept in its
/// [`SelectionRecord`] when the record holds none. `None` when anything besides whole objects
/// is selected ([`objects_only`]), with an active Appearance item, when a selected object is in
/// a Live Paint group, and with gradient mesh points picked: the proxies then read the
/// selection with [`Session::proxy_mixed`] and [`crate::DocState::stroke_mixed`]. While the
/// Live Paint Bucket paints, [`Session::load_selection_paints`] returns before reading them.
fn read_selection_paints(&mut self) -> Option<SelectionPaints> {
if self.appearance_item().is_some() {
return None;
}
let st = self.active_mut()?;
if !objects_only(&st.selection) {
return None;
}
if st.selection_paints().is_none() {
let paints = SelectionPaints::of(&st.doc, &st.selection.objects);
let settled = st.selection_record().and_then(|r| r.settled);
st.selection_record =
Some(SelectionRecord { doc: Arc::downgrade(&st.doc), objects: st.selection.objects.clone(), settled, paints: Some(paints) });
}
let paints = st.selection_paints()?.clone();
(!paints.in_live_paint && self.fill_mesh_points().is_empty()).then_some(paints)
}
}
fn set_basic(s: &mut Session, p: &Value) -> Result<Value> {
+34 -5
View File
@@ -634,6 +634,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)]);
@@ -977,8 +1001,9 @@ impl Session {
/// Profile `name`'s document, its file's path and a warning for each color profile the file
/// carries that can't be used: `None` when it has no file (the shipped profile, the defaults),
/// the reason when the request being served may not read it, or its file can't be read, is
/// larger than [`MAX_PROFILE_BYTES`] or isn't a native document VectorCraft reads.
/// the reason when the request being served may not read it, or its file is a link or a folder,
/// can't be read, is larger than [`MAX_PROFILE_BYTES`] or isn't a native document VectorCraft
/// reads.
fn read_profile(&self, name: &str) -> std::result::Result<Option<ReadProfile>, String> {
let Some(path) = self.profile_path(name) else { return Ok(None) };
let file = path.to_string_lossy().to_string();
@@ -989,8 +1014,11 @@ impl Session {
let denied = |_| PROFILE_DENIED.to_string();
let read = crate::file_access::app_folder_read(|| {
crate::file_access::check_read(&file).map_err(denied)?;
if std::fs::symlink_metadata(&path).is_err_and(|e| e.kind() == std::io::ErrorKind::NotFound) {
return Ok(None);
match std::fs::symlink_metadata(&path) {
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
// A link is refused: the script's gate does not check where it leads.
Ok(m) if !m.file_type().is_file() => return Err("not a plain file".to_string()),
_ => {}
}
crate::file_access::check_read(&file).map_err(denied)?;
crate::store::read_capped(&path, MAX_PROFILE_BYTES).map(Some)
@@ -998,10 +1026,11 @@ impl Session {
let Some(bytes) = read else { return Ok(None) };
// The color profiles the file carries are installed where missing, as opening it installs
// them, so the new document's assigned profiles draw and are saved with it.
let (mut doc, _, warnings) = super::fileio::native_file(&bytes).map_err(|e| e.to_string())?;
let (mut doc, _, mut warnings) = super::fileio::decode_native_file(&bytes).map_err(|e| e.to_string())?;
// Linked images in its symbols, patterns and brushes are read from their files, as placing
// a document reads them.
super::links::resolve(&mut doc, super::links::LinkBase::file(Some(&file)), false, false);
warnings.extend(vectorcraft_text::FontDb::global().bind_document_file_fonts(&mut doc));
Ok(Some(ReadProfile { doc, file, warnings }))
}
}
+1 -1
View File
@@ -12,7 +12,7 @@ use vectorcraft_geom::shapes::CornerKind;
use vectorcraft_geom::{Affine, FillRule, PathData, Point, Rect, Vec2};
use vectorcraft_render::effects;
use super::edit::{duplicate_in, outermost, selected_roots, selected_roots_to_transform};
use super::edit::{duplicate_beside, outermost, selected_roots, selected_roots_to_transform};
use super::opacitymask::percent;
use super::{
CommandSpec, Result, Session, bad, bool_or, check_numbers, check_switches, cmd, f64_or, f64_req, has_doc, has_multi, has_selection,
+1 -1
View File
@@ -16,7 +16,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Transform",
[],
None,
"{matrix: [a,b,c,d,e,f], copy?: bool, ids?, strokes?: bool, corners?: bool, typeAreas?: bool, anchors?: bool, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), releaseOutside?: bool, interpolate?: bool (with anchors and a matrix that only moves them: the handles of each segment with one moved end are re-mapped, as path.moveAnchors's; default: prefs interpolateControlPoints)} apply an affine to the selection (or ids); anchors (without ids or copy): paths with anchors selected with Direct Selection have only those anchors and their handles transformed, as the Transform tools and object.move/rotate/scale/reflect/shear do (default: the whole objects); strokes/corners: Scale Strokes & Effects / Scale Corners (default: the preferences); typeAreas: area type among them (not type inside a group) reshapes its frame by the matrix and its text reflows at its size, as a bounding-box handle drag does (default: the type transforms too); releaseOutside (without copy or anchors): a Shaper Group's original shape that ends wholly outside the bounds the group's original shapes had before takes shaper.releaseSource in the same undo step, named Remove from Shaper Group, as the Selection tool's moves in Construction mode do",
"{matrix: [a,b,c,d,e,f], copy?: bool, ids?, strokes?: bool, corners?: bool, typeAreas?: bool, anchors?: bool, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), releaseOutside?: bool, interpolate?: bool (with anchors and a matrix that only moves them: the handles of each segment with one moved end are re-mapped, as path.moveAnchors's; default: prefs interpolateControlPoints), drawBehind?: bool (with copy: in Draw Behind, view.drawMode, each copy goes directly below its original instead of above it, as the Selection and Direct Selection tools' Alt-drags send; default false)} apply an affine to the selection (or ids); anchors (without ids or copy): paths with anchors selected with Direct Selection have only those anchors and their handles transformed, as the Transform tools and object.move/rotate/scale/reflect/shear do (default: the whole objects); strokes/corners: Scale Strokes & Effects / Scale Corners (default: the preferences); typeAreas: area type among them (not type inside a group) reshapes its frame by the matrix and its text reflows at its size, as a bounding-box handle drag does (default: the type transforms too); releaseOutside (without copy or anchors): a Shaper Group's original shape that ends wholly outside the bounds the group's original shapes had before takes shaper.releaseSource in the same undo step, named Remove from Shaper Group, as the Selection tool's moves in Construction mode do",
has_doc,
transform
),
+30 -15
View File
@@ -1,7 +1,7 @@
use super::align::choice;
use super::{
Affine, Arc, Document, EngineError, LastTransform, Node, NodeId, NodeKind, OrientedBox, Point, Rect, Result, Scaling, Session, Value, Vec2, bad,
bool_or, check_numbers, check_switches, duplicate_in, effects, f64_or, f64_req, ids_param, json, matrix_param, ok, outermost, point_param,
bool_or, check_numbers, check_switches, duplicate_beside, effects, f64_or, f64_req, ids_param, json, matrix_param, ok, outermost, point_param,
selected_roots_to_transform,
};
@@ -91,12 +91,22 @@ pub(crate) fn transform_node(n: &mut Node, xf: Affine, sc: Scaling, objects: boo
/// `anchors` (`ids` being the selection): with anchors selected with Direct Selection and no
/// copy, only those anchors transform, their handles with them, and the objects selected whole.
pub(crate) fn apply_transform(s: &mut Session, label: &str, ids: Vec<NodeId>, xf: Affine, p: &Value, anchors: bool) -> Result<Value> {
apply_transform_moving_guides(s, label, ids, xf, p, anchors, None)
apply_transform_moving_guides(s, label, ids, xf, p, anchors, Placing::default())
}
/// [`apply_transform`], with the selected ruler guides moved by `guides` instead of by the
/// Where [`apply_transform_moving_guides`] puts the selected ruler guides and the copies.
#[derive(Clone, Copy, Default)]
struct Placing {
/// The selected ruler guides move by this instead of by the transform's translation.
guides: Option<Vec2>,
/// Each copy goes directly below its original instead of above it.
below: bool,
}
/// [`apply_transform`], with the selected ruler guides moved by `placing.guides` instead of by the
/// translation `xf` when given (a nudge along a turned Constrain Angle moves the art along it and
/// the guides along the page's axes).
/// the guides along the page's axes), and with each copy directly below its original with
/// `placing.below`.
fn apply_transform_moving_guides(
s: &mut Session,
label: &str,
@@ -104,8 +114,9 @@ fn apply_transform_moving_guides(
xf: Affine,
p: &Value,
anchors: bool,
guides: Option<Vec2>,
placing: Placing,
) -> Result<Value> {
let Placing { guides, below } = placing;
let copy = bool_or(p, "copy", false);
let areas = bool_or(p, "typeAreas", false);
let objects = transforms_objects(p);
@@ -138,7 +149,7 @@ fn apply_transform_moving_guides(
} else if none || (!copy && xf == Affine::IDENTITY) {
if copy { vec![] } else { ids }
} else {
let kept = if copy { preview_copies(s, &ids, with_guides)? } else { None };
let kept = if copy { preview_copies(s, &ids, with_guides, below)? } else { None };
s.edit(label, |d, sel| {
let targets = match &kept {
// The document becomes the snapshot with the kept copies, untransformed, and the
@@ -155,7 +166,7 @@ fn apply_transform_moving_guides(
} else {
None
};
let new_ids = duplicate_in(d, sel, &ids, Affine::IDENTITY)?;
let new_ids = duplicate_beside(d, sel, &ids, Affine::IDENTITY, below)?;
if let Some(copies) = guide_copies {
sel.guides = copies.iter().map(|g| d.add_ruler_guide(g)).collect();
}
@@ -212,11 +223,12 @@ fn apply_transform_moving_guides(
/// Returns the copies of `roots` for a transform or a perspective edit with `copy` in an interaction
/// whose document is still its snapshot, as in a preview ([`Session::preview`] puts the snapshot
/// back first). These are the copies the interaction keeps when they were made of that snapshot for
/// the same `roots`; otherwise this copies `roots` with [`duplicate_in`] in a clone of the snapshot,
/// untransformed, and the interaction keeps that clone. It returns `None` outside an interaction,
/// the same `roots` on the same side (`below`: directly below each original); otherwise this copies
/// `roots` with [`duplicate_beside`] in a clone of the snapshot, untransformed, and the interaction
/// keeps that clone. It returns `None` outside an interaction,
/// and when the document is no longer the snapshot, as for a command run in a typing session or a
/// script batch after an earlier edit there: the command then copies the current document.
pub(crate) fn preview_copies(s: &mut Session, roots: &[NodeId], with_guides: bool) -> Result<Option<Arc<crate::PreviewCopies>>> {
pub(crate) fn preview_copies(s: &mut Session, roots: &[NodeId], with_guides: bool, below: bool) -> Result<Option<Arc<crate::PreviewCopies>>> {
let st = s.doc_mut()?;
let Some(it) = &mut st.interaction else { return Ok(None) };
if !Arc::ptr_eq(&st.doc, &it.doc) {
@@ -226,19 +238,20 @@ pub(crate) fn preview_copies(s: &mut Session, roots: &[NodeId], with_guides: boo
if let Some(k) = &it.copies
&& Arc::ptr_eq(&k.from, &it.doc)
&& k.roots == roots
&& k.below == below
&& (k.selection.guides.is_empty() != has_guide_copies)
{
return Ok(Some(k.clone()));
}
let mut doc = it.doc.clone();
let mut selection = st.selection.clone();
let ids = duplicate_in(Arc::make_mut(&mut doc), &mut selection, roots, Affine::IDENTITY)?;
let ids = duplicate_beside(Arc::make_mut(&mut doc), &mut selection, roots, Affine::IDENTITY, below)?;
if has_guide_copies {
let d = Arc::make_mut(&mut doc);
let copies: Vec<_> = st.selection.guides.iter().filter_map(|&i| d.ruler_guide(i)).collect();
selection.guides = copies.iter().map(|g| d.add_ruler_guide(g)).collect();
}
let k = Arc::new(crate::PreviewCopies { from: it.doc.clone(), roots: roots.to_vec(), doc, selection, ids });
let k = Arc::new(crate::PreviewCopies { from: it.doc.clone(), roots: roots.to_vec(), below, doc, selection, ids });
it.copies = Some(k.clone());
Ok(Some(k))
}
@@ -256,7 +269,9 @@ fn resize_type_area(n: &mut Node, xf: Affine) -> bool {
pub(super) fn transform(s: &mut Session, p: &Value) -> Result<Value> {
check_switches(p, &TRANSFORM_SWITCHES, "object.transform")?;
check_switches(p, &["anchors", "releaseOutside", "interpolate"], "object.transform")?;
check_switches(p, &["anchors", "releaseOutside", "interpolate", "drawBehind"], "object.transform")?;
// An Alt-drag copy in Draw Behind goes directly below its original.
let below = bool_or(p, "drawBehind", false) && bool_or(p, "copy", false) && s.draw_mode == crate::DrawMode::Behind;
let m = matrix_param(p, "matrix").ok_or_else(|| bad("object.transform", "missing matrix [a,b,c,d,e,f]"))?;
// An object selected in a symbol instance's art stays where the symbol puts it: the selection
// is left as it is, and the reply's warning goes to the status bar.
@@ -280,7 +295,7 @@ pub(super) fn transform(s: &mut Session, p: &Value) -> Result<Value> {
if grouped {
s.begin_named_undo_group(None);
}
let r = apply_transform(s, "Transform", ids, m, p, anchors);
let r = apply_transform_moving_guides(s, "Transform", ids, m, p, anchors, Placing { guides: None, below });
let released = match &r {
Ok(_) if !moved.is_empty() => crate::cmd::shaper::release_outside(s, &moved),
_ => Ok(false),
@@ -358,7 +373,7 @@ pub(super) fn nudge(s: &mut Session, p: &Value) -> Result<Value> {
return ok();
}
}
apply_transform_moving_guides(s, "Move", ids, Affine::translate((dx, dy)), p, true, Some(Vec2::new(gx, gy)))
apply_transform_moving_guides(s, "Move", ids, Affine::translate((dx, dy)), p, true, Placing { guides: Some(Vec2::new(gx, gy)), below: false })
}
pub(super) fn about(o: Point, a: Affine) -> Affine {
+14 -1
View File
@@ -21,7 +21,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Overprint",
[],
None,
"{fill?: bool, stroke?: bool, item?: appearance item index|null, ids?|id?, target?: \"object\"|\"contents\"} make fills and/or strokes overprint (Overprint Preview, Separations Preview) or knock out: item's, else every fill or stroke of the painted objects (groups: their contents; type: its characters too). Without item and ids, the Appearance panel's active item stands in when it is of that kind. A whole Live Paint group (also its contents with `item`) takes the fill flags on its faces and the stroke flags on its edges, and its hidden source paths keep theirs → {changed: objects}",
"{fill?: bool, stroke?: bool, item?: appearance item index|null, ids?|id?, target?: \"object\"|\"contents\"} make fills and/or strokes overprint (Overprint Preview, Separations Preview) or knock out: item's, else every fill or stroke of the painted objects (groups: their contents; type: its characters too; a grayscale or 1-bit image colorized by paint.setFill: without item, the fill flags set whether its color overprints). Without item and ids, the Appearance panel's active item stands in when it is of that kind. A whole Live Paint group (also its contents with `item`) takes the fill flags on its faces and the stroke flags on its edges, and its hidden source paths keep theirs → {changed: objects}",
has_doc,
set_overprint
),
@@ -97,9 +97,18 @@ fn flags(n: &Node, fill: bool, index: Option<usize>) -> Vec<bool> {
if let (None, NodeKind::Text(t)) = (index, &n.kind) {
v.extend(t.runs.iter().map(|r| if fill { r.style.overprint_fill } else { r.style.overprint_stroke }));
}
if fill && index.is_none() && colorized(n) {
v.push(n.extras().colorize_overprint);
}
v
}
/// Is `n` an image colorized with a color, whose fill overprint is its color's
/// ([`vectorcraft_doc::NodeExtras::colorize_overprint`])?
fn colorized(n: &Node) -> bool {
matches!(n.kind, NodeKind::Image(_)) && n.extras().colorize.as_deref().is_some_and(|p| !p.is_none())
}
/// [`flags`], to change.
fn flags_mut(n: &mut Node, fill: bool, index: Option<usize>) -> Vec<&mut bool> {
let mut v: Vec<&mut bool> = n
@@ -178,6 +187,10 @@ pub(super) fn apply_overprint(d: &mut Document, jobs: &[OverprintJob], cmd: &str
changed.insert(*id);
}
}
if *fill && index.is_none() && colorized(n) && n.extras().colorize_overprint != *on {
n.extras_mut().colorize_overprint = *on;
changed.insert(*id);
}
}
}
Ok(())
+465 -116
View File
@@ -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?, 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), only the default changes (the color the bucket paints with) and the selection keeps its paint → {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) }
),
@@ -45,7 +45,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Swap Fill and Stroke",
[],
Some("Shift+X"),
"{ids?|id?} swap the fill and stroke of the selection (type too) and of the defaults. A Live Paint group's faces take the stroke its edges share and its edges take the fill its faces share, a gradient fitted to each face or edge; a group whose faces' fills or edges' strokes differ (a freeform gradient counts as differing), or that has no face or no edge, keeps its paint. On a path directly in a graph series, the graph also stores the swapped paints and the stroke weight, and on a graph label the swapped paints of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring what the swap changes on its rows for every line of its kind (exceptions: docs/mcp.md). While the Live Paint Bucket is the active tool and no ids or id are given (a null one counts as none), only the defaults change",
"{ids?|id?, defaultsOnly?: bool} swap the fill and stroke of the selection (type too) and of the defaults. A Live Paint group's faces take the stroke its edges share and its edges take the fill its faces share, a gradient fitted to each face or edge; a group whose faces' fills or edges' strokes differ (a freeform gradient counts as differing), or that has no face or no edge, keeps its paint. On a path directly in a graph series, the graph also stores the swapped paints and the stroke weight, and on a graph label the swapped paints of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring what the swap changes on its rows for every line of its kind (exceptions: docs/mcp.md). While the Live Paint Bucket is the active tool and no ids or id are given (a null one counts as none), or `defaultsOnly: true` is given, only the defaults change",
has_doc,
swap
),
@@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Default Fill and Stroke",
[],
Some("D"),
"{ids?|id?} white fill and 1 pt black stroke for the selection and the defaults (in a document whose Default Graphic Style differs from the shipped one, as a New Document profile can redefine it: that style's fills, strokes and effects, without its opacity or a link to it); type gets black fill and no stroke. A Live Paint group's faces get no fill and its edges get a 0.5 pt black stroke, in place of their whole appearance and also when the Default Graphic Style is redefined, and with only Live Paint groups selected (or in ids) the defaults become no fill and a 0.5 pt black stroke (with New Art Has Basic Appearance off, new art then takes the selection's appearance, as after any command). On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke, and on a graph label the black fill and no stroke of its characters 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 (exceptions: docs/mcp.md). While the Live Paint Bucket is the active tool and no ids or id are given (a null one counts as none), only the defaults change",
"{ids?|id?, defaultsOnly?: bool} white fill and 1 pt black stroke for the selection and the defaults (in a document whose Default Graphic Style differs from the shipped one, as a New Document profile can redefine it: that style's fills, strokes and effects, without its opacity or a link to it); type gets black fill and no stroke. A Live Paint group's faces get no fill and its edges get a 0.5 pt black stroke, in place of their whole appearance and also when the Default Graphic Style is redefined, and with only Live Paint groups selected (or in ids) the defaults become no fill and a 0.5 pt black stroke (with New Art Has Basic Appearance off, new art then takes the selection's appearance, as after any command). On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke, and on a graph label the black fill and no stroke of its characters 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 (exceptions: docs/mcp.md). While the Live Paint Bucket is the active tool and no ids or id are given (a null one counts as none), or `defaultsOnly: true` is given, only the defaults change",
has_doc,
default_paint
),
@@ -75,11 +75,12 @@ pub fn specs() -> Vec<CommandSpec> {
"None",
[],
Some("/"),
"{} set the active proxy (fill or stroke) to None, as paint.setFill or paint.setStroke with none does (while the Live Paint Bucket is the active tool, only the default changes) → {objects}",
"{defaultsOnly?: bool} set the active proxy (fill or stroke) to None, as paint.setFill or paint.setStroke with none does (while the Live Paint Bucket is the active tool, or with `defaultsOnly: true`, only the default changes) → {objects}",
has_doc,
|s, _| {
|s, p| {
let f = s.fill_active;
set_paint(s, &json!({"none": true}), f)
let only = switch_or(p, "defaultsOnly", false, "paint.none")?;
set_paint(s, &with_defaults_only(json!({"none": true}), only), f)
}
),
cmd!(
@@ -102,7 +103,7 @@ pub fn proxy_specs() -> Vec<CommandSpec> {
"Invert",
[],
None,
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents and, except with target \"contents\", their own fills and strokes; a compound path's member stands for its compound path; a Live Paint group recolors its faces' fills or its edges' strokes) keeping each colour's model, as edit.colors.invert does; the Appearance panel's active fill/stroke item (appearance.setActiveItem) is inverted instead when it is of that kind and no ids are given; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's solid color changes for this instance only, and a gradient or pattern, or type whose characters differ in color, is refused; with nothing selected, or 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), invert the default. On a path directly in a graph series, the graph also stores the new color of the topmost visible fill or stroke, and on a graph label the new color 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); no undo step when no color changes → {changed}",
"{stroke?: bool (default: the active proxy), ids?|id?, defaultsOnly?: bool, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents and, except with target \"contents\", their own fills and strokes; a compound path's member stands for its compound path; a Live Paint group recolors its faces' fills or its edges' strokes) keeping each colour's model, as edit.colors.invert does; the Appearance panel's active fill/stroke item (appearance.setActiveItem) is inverted instead when it is of that kind and no ids are given; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's solid color changes for this instance only, and a gradient or pattern, or type whose characters differ in color, is refused; with nothing selected, or 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, invert the default. On a path directly in a graph series, the graph also stores the new color of the topmost visible fill or stroke, and on a graph label the new color 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); no undo step when no color changes → {changed}",
has_doc,
|s, p| proxy_recolor(s, p, "paint.invert", "Invert", &super::colorcmds::invert)
),
@@ -111,7 +112,7 @@ pub fn proxy_specs() -> Vec<CommandSpec> {
"Complement",
[],
None,
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} replace the active proxy's colours by their complements ((highest + lowest) − each component, over RGB or CMY; grey unchanged) keeping each colour's model; a Live Paint group recolors its faces' fills or its edges' strokes as with paint.invert; honours the Appearance panel's active item and a selected object of a dynamic symbol instance as paint.invert does; with nothing selected, or 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), the default; no undo step when no color changes → {changed}",
"{stroke?: bool (default: the active proxy), ids?|id?, defaultsOnly?: bool, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} replace the active proxy's colours by their complements ((highest + lowest) − each component, over RGB or CMY; grey unchanged) keeping each colour's model; a Live Paint group recolors its faces' fills or its edges' strokes as with paint.invert; honours the Appearance panel's active item and a selected object of a dynamic symbol instance as paint.invert does; with nothing selected, or 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, the default; no undo step when no color changes → {changed}",
has_doc,
|s, p| proxy_recolor(s, p, "paint.complement", "Complement", &|c: Color| c.complement_keep_model())
),
@@ -120,7 +121,7 @@ pub fn proxy_specs() -> Vec<CommandSpec> {
"Apply Last Color",
[],
Some(","),
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} apply the last solid colour used (paint.recent lastColor) to the active proxy of the selection and the default (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), to the default only) → {objects} (as paint.setFill)",
"{stroke?: bool (default: the active proxy), ids?|id?, defaultsOnly?: bool, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} apply the last solid colour used (paint.recent lastColor) to the active proxy of the selection and the default (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, to the default only) → {objects} (as paint.setFill)",
has_doc,
|s, p| {
let paint = Paint::solid(s.last_solid);
@@ -132,7 +133,7 @@ pub fn proxy_specs() -> Vec<CommandSpec> {
"Apply Last Gradient",
[],
Some("."),
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} apply the last gradient used (paint.recent lastGradient), fitted to each object, to the active proxy of the selection and the default (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), to the default only) → {objects} (as paint.setFill)",
"{stroke?: bool (default: the active proxy), ids?|id?, defaultsOnly?: bool, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} apply the last gradient used (paint.recent lastGradient), fitted to each object, to the active proxy of the selection and the default (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, to the default only) → {objects} (as paint.setFill)",
has_doc,
|s, p| {
let paint = super::gradient::unplaced(&Paint::Gradient(Box::new(s.last_gradient.clone())));
@@ -160,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
),
@@ -223,7 +224,7 @@ impl Session {
// A Live Paint group without faces (or edges) shows the next selected object's paint; any other
// object without a painted object shows the defaults for new art. A face or edge selected with
// its Live Paint group counts with the group, wherever it is in the selection.
let covered = live_paint_covered(&st.doc, st.selection.subjects());
let covered = st.selection_live_paint_covered(st.selection.subjects());
for id in st.selection.subjects().iter().filter(|id| !covered.contains(*id)) {
let Some(n) = st.doc.node(*id) else { continue };
let mut nodes = vec![];
@@ -238,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, .. } => {
@@ -302,6 +377,74 @@ pub(crate) fn painted<'a>(n: &'a Node, top: bool, stroke: bool, out: &mut Vec<&'
}
}
/// What the proxies read from selected objects: the first fill, stroke and stroke weight met, and
/// whether another one differs ([`DocState::proxy_mixed`] without an active Appearance item or
/// picked mesh points, and [`super::stroke::StrokeMixed::weight`]), and whether an object lies in a
/// Live Paint group or may hold a gradient mesh. The objects added to a selection are read with
/// [`SelectionPaints::add`].
#[derive(Clone, Debug, Default)]
pub(crate) struct SelectionPaints {
fill: Option<Paint>,
pub(crate) fill_mixed: bool,
stroke: Option<Paint>,
pub(crate) stroke_mixed: bool,
weight: Option<f64>,
pub(crate) weight_mixed: bool,
/// An object is a face or edge of a Live Paint group, or lies inside one
/// ([`live_paint_covered`]).
pub(crate) in_live_paint: bool,
/// An object is a gradient mesh or a container ([`Session::fill_mesh_points`]).
pub(crate) may_hold_mesh: bool,
}
impl SelectionPaints {
/// Read objects `ids` of `doc`.
pub(crate) fn of(doc: &Document, ids: &[NodeId]) -> Self {
let mut p = Self::default();
p.add(doc, ids);
p
}
/// Read objects `ids` of `doc` too.
pub(crate) fn add(&mut self, doc: &Document, ids: &[NodeId]) {
fn meet<T>(first: &mut Option<T>, mixed: &mut bool, value: T, same: impl Fn(&T, &T) -> bool) {
match first {
Some(f) => *mixed |= !same(f, &value),
None => *first = Some(value),
}
}
// As in `proxy_mixed_with`: every node with an added id, in tree order.
let (mut fills, mut strokes) = (vec![], vec![]);
for n in doc.nodes_in_order(ids.iter().copied()) {
painted(n, true, false, &mut fills);
painted(n, true, true, &mut strokes);
}
for n in fills {
meet(&mut self.fill, &mut self.fill_mixed, proxy_paint(n, false, None), same_in_proxy);
}
for n in strokes {
meet(&mut self.stroke, &mut self.stroke_mixed, proxy_paint(n, true, None), same_in_proxy);
}
// As in `stroke_mixed`: the node each added id names.
for id in ids {
let Some(n) = doc.node(*id) else { continue };
self.in_live_paint |= in_live_paint(doc, *id);
self.may_hold_mesh |= matches!(n.kind, NodeKind::Mesh(_)) || n.is_container();
let mut nodes = vec![];
painted(n, true, true, &mut nodes);
for n in nodes {
let widths: Vec<f64> = match &n.kind {
NodeKind::Text(t) => t.runs.iter().map(|r| r.style.stroke_layer().width).collect(),
_ => n.appearance.stroke().map(|s| s.width).into_iter().collect(),
};
for w in widths {
meet(&mut self.weight, &mut self.weight_mixed, w, |a, b| a == b);
}
}
}
}
}
impl DocState {
/// Whether the selected objects' fills and strokes differ as the proxies show them (a "?"
/// proxy; a group whose contents differ counts). `item` (the Appearance panel's active item)
@@ -328,7 +471,7 @@ impl DocState {
let (mut selected, mut fills, mut strokes) = (vec![], vec![], vec![]);
// The faces and edges of the selected Live Paint groups (or of those inside selected groups): selected as well,
// they count with their group's.
let covered = live_paint_covered(&self.doc, &self.selection.objects);
let covered = self.selection_live_paint_covered(&self.selection.objects);
// Every node with a selected id, in tree order: a repeated id (a damaged file) counts at each
// place it appears.
for n in self.doc.nodes_in_order(self.selection.objects.iter().copied()) {
@@ -373,16 +516,25 @@ impl DocState {
}
}
/// Is `t` the Live Paint Bucket, or a tool armed to switch back to it after its pick?
fn works_for_bucket(t: &dyn vectorcraft_tools::Tool) -> bool {
t.id() == LIVE_PAINT_BUCKET || t.returns_to() == Some(LIVE_PAINT_BUCKET)
}
impl Session {
/// Did the Live Paint Bucket, or the Eyedropper armed for it, lend the active tool (a Cmd+click)?
pub(crate) fn lent_by_bucket(&self) -> bool {
self.lender.as_deref().is_some_and(works_for_bucket)
}
/// Do the fill and stroke proxies, and the paint commands that name no objects, stand for the
/// colors the Live Paint Bucket paints with? They do while the bucket is the active tool, while
/// a Cmd+click with the bucket uses the Selection tool, and while the Eyedropper samples into a
/// stop of the bucket's gradient for the Gradient panel's eyedropper, up to and including the
/// sample its click takes before it switches back to the bucket.
pub fn bucket_paints(&self) -> bool {
let for_bucket = |t: &dyn vectorcraft_tools::Tool| t.id() == LIVE_PAINT_BUCKET || t.returns_to() == Some(LIVE_PAINT_BUCKET);
// A Cmd+click lends the Selection tool to the bucket, or to the Eyedropper armed for it.
self.back_to_bucket || for_bucket(self.tool.as_ref()) || self.lender.as_deref().is_some_and(for_bucket)
self.back_to_bucket || works_for_bucket(self.tool.as_ref()) || self.lent_by_bucket()
}
/// The tool the active tool's armed one-shot pick switches back to after its click
@@ -405,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.
@@ -524,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.
@@ -543,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)> =
@@ -606,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());
@@ -624,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,
@@ -664,114 +971,140 @@ 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) {
n.extras_mut().colorize = paint.color().map(|_| Box::new(paint.clone()));
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}))
}
/// Is the Live Paint Bucket the active tool ([`Session::bucket_paints`]) while `p` names no `ids`,
/// `id` or `item`? A fill,
/// stroke or stroke weight chosen then is what the bucket paints with, so it goes to the defaults
/// and the selection keeps its paint.
pub(crate) fn for_bucket(s: &Session, p: &Value) -> bool {
/// Does `p` name no `ids`, `id` or `item`?
fn names_no_target(p: &Value) -> bool {
// A null `ids` or `id` is no target, as `given_nodes` reads it; `item: null` names the top row.
s.bucket_paints() && ["ids", "id"].iter().all(|k| p.get(k).is_none_or(Value::is_null)) && p.get("item").is_none()
["ids", "id"].iter().all(|k| p.get(k).is_none_or(Value::is_null)) && p.get("item").is_none()
}
/// `p` with `ids: []` when [`for_bucket`]: the paint goes to the defaults only. None otherwise.
/// A bad `target` or `aligned` is refused first, as it is without the bucket.
pub(crate) fn bucket_color_params(s: &Session, p: &Value, cmd: &str) -> Result<Option<Value>> {
/// Is the Live Paint Bucket the active tool ([`Session::bucket_paints`]), or does `p` give
/// `defaultsOnly: true`, while `p` names no `ids`, `id` or `item`? A fill, stroke or stroke weight
/// chosen then is what the bucket paints with, so it goes to the defaults and the selection keeps
/// its paint.
pub(crate) fn for_bucket(s: &Session, p: &Value) -> bool {
names_no_target(p) && (s.bucket_paints() || asks_defaults_only(p))
}
/// Does `p` give `defaultsOnly: true`?
pub(crate) fn asks_defaults_only(p: &Value) -> bool {
p.get("defaultsOnly") == Some(&Value::Bool(true))
}
/// `p` with `ids: []` (and without `defaultsOnly`) when [`for_bucket`]: the paint goes to the
/// defaults only. None otherwise. A bad `target` or `aligned` is refused first, as it is without
/// the bucket, and so is a `defaultsOnly` that is not a bool or comes with `ids`, `id` or `item`.
/// When the bucket routed the command, the journal entry notes `defaultsOnly: true`, so replaying
/// it with another tool active changes the defaults only as well.
pub(crate) fn bucket_color_params(s: &mut Session, p: &Value, cmd: &str) -> Result<Option<Value>> {
let only = switch_or(p, "defaultsOnly", false, cmd)?;
if only && !names_no_target(p) {
return Err(bad(cmd, "`defaultsOnly` cannot be combined with `ids`, `id` or `item`"));
}
if !for_bucket(s, p) {
return Ok(None);
}
super::appearance::aligned(p, cmd)?;
super::appearance::targets_contents(p)?;
if !only {
s.note_journal("defaultsOnly", json!(true));
}
s.note_defaults_only();
let mut v = p.as_object().cloned().unwrap_or_default();
v.remove("defaultsOnly");
v.insert("ids".into(), json!([]));
Ok(Some(Value::Object(v)))
}
/// Whether the paint commands that `cmd` runs with params of its own change only the defaults:
/// `p` gives `defaultsOnly: true`, or the Live Paint Bucket paints ([`Session::bucket_paints`]),
/// which the journal entry of `cmd` notes for a replay.
pub(crate) fn defaults_only(s: &mut Session, p: &Value, cmd: &str) -> Result<bool> {
if switch_or(p, "defaultsOnly", false, cmd)? {
s.note_defaults_only();
return Ok(true);
}
let bucket = s.bucket_paints();
if bucket {
s.note_journal("defaultsOnly", json!(true));
s.note_defaults_only();
}
Ok(bucket)
}
impl Session {
/// Note that the running command changed only the paint defaults, with the appearance new art
/// takes from the selection now ([`Session::inherit_new_art`]). No appearance is captured
/// while inheritance does not run (New Art Has Basic Appearance on, or the bucket painting).
fn note_defaults_only(&mut self) {
let inherits = !self.prefs.new_art_basic && !self.bucket_paints();
self.defaults_only_ran = Some(if inherits { self.new_art_source() } else { None });
}
}
/// `q` with `defaultsOnly: true` when `only` ([`defaults_only`]).
pub(crate) fn with_defaults_only(mut q: Value, only: bool) -> Value {
if only && let Some(o) = q.as_object_mut() {
o.insert("defaultsOnly".into(), json!(true));
}
q
}
/// The Live Paint groups in `roots` (or inside them), given or selected whole, with the ids of
/// their faces and of their edges, found where [`leaf_targets`] finds the objects a paint command
/// changes: a given or selected object other than a group or layer (a blend, say) and a compound
@@ -855,8 +1188,7 @@ pub(crate) fn live_paint_split(d: &Document, roots: &[NodeId]) -> LivePaintParts
/// object: they count with their group, wherever they are in `selected`. The groups are looked for only when an
/// object in `selected` is inside a Live Paint group.
pub(crate) fn live_paint_covered(d: &Document, selected: &[NodeId]) -> std::collections::HashSet<NodeId> {
let inside = |id: &NodeId| d.ancestry(*id).is_some_and(|up| up.iter().rev().skip(1).filter_map(|a| d.node(*a)).any(is_live_paint));
if !selected.iter().any(inside) {
if !selected.iter().any(|id| in_live_paint(d, *id)) {
return std::collections::HashSet::new();
}
let (mut parts, edges, _) = live_paint_split(d, selected);
@@ -864,6 +1196,22 @@ pub(crate) fn live_paint_covered(d: &Document, selected: &[NodeId]) -> std::coll
parts
}
/// Is `id` inside a Live Paint group (one of the groups around it is one)?
fn in_live_paint(d: &Document, id: NodeId) -> bool {
d.ancestry(id).is_some_and(|up| up.iter().rev().skip(1).filter_map(|a| d.node(*a)).any(is_live_paint))
}
impl DocState {
/// [`live_paint_covered`] for `ids`, the selected objects or the selection's subjects: none
/// when the [`SelectionPaints`] of the selection say no selected object is in a Live Paint group.
pub(crate) fn selection_live_paint_covered(&self, ids: &[NodeId]) -> std::collections::HashSet<NodeId> {
if self.selection_paints().is_some_and(|p| !p.in_live_paint) {
return std::collections::HashSet::new();
}
live_paint_covered(&self.doc, ids)
}
}
/// The instance whose object is selected with Direct Selection, and that object's path
/// ([`super::brushsym::selected_part`]), when `p` names no `ids`, `id` or `item`: the paint commands
/// then change that object. A bad `target` or `aligned` is refused as it is for any other selection.
@@ -1109,7 +1457,8 @@ impl Session {
// Only gradient meshes have points to pick: a selection with no mesh and no container that
// could hold one skips reading the tool's options.
let may_hold_mesh = |id: &NodeId| st.doc.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Mesh(_)) || n.is_container());
if st.selection.symbol_part.is_some() || !st.selection.subjects().iter().any(may_hold_mesh) {
let none_may = || st.selection_paints().map_or_else(|| !st.selection.subjects().iter().any(may_hold_mesh), |p| !p.may_hold_mesh);
if st.selection.symbol_part.is_some() || none_may() {
return vec![];
}
let Ok(item) = item_target(self, &Value::Null, "paint.setFill").map(|t| t.of_kind(self, true)) else { return vec![] };
+46 -7
View File
@@ -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)",
"{keepEmpty?: bool (keep a compound path left with no members)} 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
),
@@ -1652,8 +1652,20 @@ 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 keep_empty = switch_or(p, "keepEmpty", false, "path.deleteAnchors")?;
let st = s.doc()?;
let sel = st.selection.anchors.clone();
let segments = st.selection.segments.clone();
@@ -1671,16 +1683,21 @@ pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result<Value> {
.copied()
.filter(|id| !d.ancestry(*id).unwrap_or_default().iter().rev().skip(1).any(|ancestor| targets.contains(ancestor)))
.collect();
// The compound paths that hold a deleted object; one left with no members goes too.
let compounds: BTreeSet<NodeId> = whole_ids
.iter()
.chain(sel.keys())
.filter_map(|id| d.parent_of(*id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. }))))
.collect();
// The compound paths that hold a deleted object; one left with no members goes too, unless `keepEmpty`.
let compounds: BTreeSet<NodeId> = if keep_empty {
BTreeSet::new()
} else {
whole_ids
.iter()
.chain(sel.keys())
.filter_map(|id| d.parent_of(*id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. }))))
.collect()
};
if !whole_ids.is_empty() {
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 +1705,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 +1765,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()
+2 -5
View File
@@ -199,14 +199,11 @@ pub fn specs() -> Vec<CommandSpec> {
// ---------- helpers ----------
/// Number param that also accepts strings like `"10 pt"`.
/// Number param that also accepts a string when all of it is a number (`"10"`, not `"10abc"`).
pub(crate) fn num_param(p: &Value, key: &str) -> Option<f64> {
match p.get(key)? {
Value::Number(n) => n.as_f64(),
Value::String(s) => {
let t: String = s.trim().chars().take_while(|c| c.is_ascii_digit() || matches!(c, '.' | '-' | '+' | 'e' | 'E')).collect();
t.parse().ok()
}
Value::String(s) => whole_number(s),
_ => None,
}
.filter(|v: &f64| v.is_finite())
+6 -1
View File
@@ -43,7 +43,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Replace Pattern Art",
[],
None,
"{name, ids?} make copies of the selected art the tile art of pattern `name`, as Alt-dragging (Option-dragging on macOS) art onto its swatch in the Swatches panel does; the pattern keeps its name, swatch, tile and options (with Size Tile to Art on, the tile fits the new art), every fill and stroke painted with it draws the new tile, and the art stays on the canvas, selected; one undo step, none when the art matches the tile art already; refused while a pattern is edited, with nothing selected, and for art painted with the pattern itself → {name}",
"{name, ids?} make copies of the selected art the tile art of pattern `name`, as Alt-dragging (Option-dragging on macOS) art onto its swatch in the Swatches panel does; the pattern keeps its name, swatch, tile and options (with Size Tile to Art on, the tile fits the new art), every fill and stroke painted with it draws the new tile, and the art stays on the canvas, selected; one undo step, none when the art matches the tile art already; refused while a pattern is edited, with nothing selected, for an id that names no object, and for art painted with the pattern itself → {name}",
can_replace_pattern_art,
pattern_replace_art
),
@@ -244,10 +244,15 @@ fn ids_json(ids: &[NodeId]) -> Value {
json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() })
}
/// The outermost objects among `ids` (layers left out), else the selected ones. An id that names
/// no object is an error, so the command never acts on the other ids alone.
fn roots(s: &Session, p: &Value, cmd: &str) -> Result<Vec<NodeId>> {
match ids_param(p, "ids", cmd)? {
Some(ids) => {
let st = s.doc()?;
if let Some(id) = ids.iter().find(|id| st.doc.node(**id).is_none()) {
return Err(bad(cmd, format!("no such object id {}", id.0)));
}
let mut sel = Selection::default();
sel.set(ids.iter().copied().filter(|id| st.doc.node(*id).is_some_and(|n| !n.is_layer())));
Ok(outermost(&st.doc, sel.in_paint_order(&st.doc)))
+150 -20
View File
@@ -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,
@@ -85,15 +90,30 @@ pub fn swatch_source(w: &Swatch) -> Option<Arc<Document>> {
library_doc(b.id).filter(|d| d.pattern(pattern).is_some())
}
/// Swatches as (the swatch's name in a library, its name in a document).
pub(crate) type SwatchNames = Vec<(String, String)>;
/// Add pattern `name` of library `lib` to `d` with the resources its art uses, as pasting art
/// painted with it does: the same pattern there already is used, and a name another pattern or
/// swatch has gets a number → the pattern's name in `d`, and the swatches the import added for
/// the pattern's art: (the swatch's name in `lib`, its name in `d`), pattern swatches left out.
/// the pattern's art: (the swatch's name in `lib`, its name in `d`), pattern swatches left out,
/// and the swatches `d` had that the art took under another name than its own, in the same form.
/// 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.
pub(crate) fn import(d: &mut Document, lib: &Document, name: &str) -> Result<(String, Vec<(String, String)>)> {
/// 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`]). 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();
let imported = gather(lib, name).import_into(d, &SwatchChoices::add_all(), false)?;
// 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, reserved)?;
*d = probed;
imported
} else {
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());
renamed.unwrap_or(to).to_string()
@@ -103,7 +123,14 @@ pub(crate) fn import(d: &mut Document, lib: &Document, name: &str) -> Result<(St
.filter(|w| !had.contains(&w.name) && !matches!(w.paint, Paint::Pattern { .. }))
.map(|w| (from(&w.name), w.name.clone()))
.collect();
Ok((imported_name(&imported, name), added))
let reused = imported
.renamed
.iter()
.filter(|r| r["kind"] == "swatch")
.filter_map(|r| Some((r["from"].as_str()?.to_string(), r["to"].as_str()?.to_string())))
.filter(|(_, to)| had.contains(to))
.collect();
Ok((imported_name(&imported, name), added, reused))
}
/// Pattern `name` of `lib` with the resources its art uses, as an object painted with it is copied.
@@ -112,17 +139,31 @@ fn gather(lib: &Document, name: &str) -> Clipboard {
Clipboard::gather(lib, vec![user])
}
/// The names in `lib` of the swatches that pattern `name` of `lib` brings with its art.
pub(crate) fn brought_names(lib: &Document, name: &str) -> std::collections::HashSet<String> {
gather(lib, name).swatches.into_iter().map(|w| w.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.
fn imported_name(imported: &Imported, name: &str) -> String {
pub(crate) fn imported_name(imported: &Imported, name: &str) -> String {
let renamed = imported.renamed.iter().find(|r| r["kind"] == "pattern" && r["from"] == name).and_then(|r| r["to"].as_str());
renamed.unwrap_or(name).to_string()
}
/// The pattern of `d` that [`import`] of pattern `name` of library `lib` would use without adding
/// anything to `d` → its name in `d`. 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`, so that those resources are compared too.
pub(crate) fn present_pattern(d: &Document, lib: &Document, name: &str) -> Option<String> {
/// anything to `d` → its name in `d`, and the swatches of `d` that the art takes under another
/// 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, 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()
@@ -131,23 +172,112 @@ pub(crate) fn present_pattern(d: &Document, lib: &Document, name: &str) -> Optio
&& gathered.char_styles.is_empty()
&& gathered.para_styles.is_empty()
&& gathered.brushes.is_empty()
&& gathered.images.is_empty();
&& gathered.images.is_empty()
&& gathered.graph_designs.is_empty();
if only_pattern {
return existing_pattern(d, lib, name);
return existing_pattern(d, lib, name).map(|target| (target, vec![]));
}
// Importing reuses only a pattern under that name or a numbered copy of it with the same tile
// options and as many art objects; without one, the document is not copied.
let def = lib.pattern(name)?;
// Without a pattern to reuse, the document is not copied.
if !has_candidate(d, lib, name) {
return None;
}
let (_, _, imported) = probe_import(d, lib, name, &gathered, reserved).ok()?;
if imported.added != 0 {
return None;
}
let took = imported
.renamed
.iter()
.filter(|r| r["kind"] == "swatch")
.filter_map(|r| Some((r["from"].as_str()?.to_string(), r["to"].as_str()?.to_string())))
.filter(|(_, to)| d.swatches_iter().any(|w| w.name == *to))
.collect();
Some((imported_name(&imported, name), took))
}
/// Whether `d` has a pattern that importing pattern `name` of `lib` can reuse: one under that name
/// or a numbered copy of it with the same tile options and as many art objects.
pub(crate) fn has_candidate(d: &Document, lib: &Document, name: &str) -> bool {
let Some(def) = lib.pattern(name) else { return false };
let bare = |p: &PatternDef| PatternDef { name: String::new(), art: vec![], ..p.clone() };
let copy = |n: &str| {
n == name || n.strip_prefix(name).and_then(|r| r.strip_prefix(' ')).is_some_and(|r| !r.is_empty() && r.bytes().all(|b| b.is_ascii_digit()))
};
if !d.patterns.iter().any(|p| copy(&p.name) && p.art.len() == def.art.len() && bare(p) == bare(def)) {
return None;
d.patterns.iter().any(|p| copy(&p.name) && p.art.len() == def.art.len() && bare(p) == bare(def))
}
/// Import `gathered`, which paints with pattern `name` of `lib`, into a copy of `d` → the swatch
/// choices used, the copy and what the import did. A global or spot color whose name `d` gives
/// 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. 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 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);
}
}
let mut probe = d.clone();
let imported = gathered.import_into(&mut probe, &SwatchChoices::add_all(), false).ok()?;
(imported.added == 0).then(|| imported_name(&imported, name))
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
+7 -7
View File
@@ -5,7 +5,7 @@
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use vectorcraft_pdf::{PdfPreset, builtin_preset, builtin_presets};
use vectorcraft_pdf::{APP, ActiveProfiles, PdfPreset, builtin_preset, builtin_presets};
use super::fileio::pdf::{find_preset, resolve};
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, str_param};
@@ -75,7 +75,7 @@ pub fn specs() -> Vec<CommandSpec> {
impl Session {
/// Every PDF preset: the built-in ones, then the saved ones.
pub fn pdf_presets(&self) -> Vec<PdfPreset> {
let mut v = builtin_presets();
let mut v = builtin_presets(APP);
v.extend(self.prefs.pdf_presets.iter().cloned());
v
}
@@ -93,16 +93,16 @@ impl Session {
/// Whether `name` is taken by a built-in PDF preset or a saved one other than the one at
/// `except`.
fn pdf_preset_taken(&self, name: &str, except: Option<usize>) -> bool {
builtin_preset(name).is_some() || self.pdf_saved_index(name).is_some_and(|i| Some(i) != except)
builtin_preset(name, APP).is_some() || self.pdf_saved_index(name).is_some_and(|i| Some(i) != except)
}
}
fn row(p: PdfPreset, built_in: bool) -> Value {
json!({ "name": p.name, "builtIn": built_in, "supported": p.settings.check().is_ok(), "description": p.description, "settings": p.settings })
json!({ "name": p.name, "builtIn": built_in, "supported": p.settings.check(&ActiveProfiles::default()).is_ok(), "description": p.description, "settings": p.settings })
}
fn list(s: &mut Session, _: &Value) -> Result<Value> {
let rows = builtin_presets().into_iter().map(|p| row(p, true)).chain(s.prefs.pdf_presets.iter().cloned().map(|p| row(p, false)));
let rows = builtin_presets(APP).into_iter().map(|p| row(p, true)).chain(s.prefs.pdf_presets.iter().cloned().map(|p| row(p, false)));
Ok(json!({ "presets": rows.collect::<Vec<_>>() }))
}
@@ -113,7 +113,7 @@ fn save(s: &mut Session, p: &Value) -> Result<Value> {
Some(n) => n.to_string(),
None => s.new_pdf_preset_name(),
};
if builtin_preset(&name).is_some() {
if builtin_preset(&name, APP).is_some() {
return Err(bad(C, format!("`{name}` is a built-in preset and is read-only: save it under another name")));
}
let at = s.pdf_saved_index(&name);
@@ -145,7 +145,7 @@ fn save(s: &mut Session, p: &Value) -> Result<Value> {
fn delete(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "pdf.preset.delete";
let name = str_param(p, "name").ok_or_else(|| bad(C, "missing `name`"))?;
if builtin_preset(name).is_some() {
if builtin_preset(name, APP).is_some() {
return Err(bad(C, format!("`{name}` is a built-in preset and stays")));
}
let i = s.pdf_saved_index(name).ok_or_else(|| bad(C, format!("no saved PDF preset named `{name}`")))?;
+1 -1
View File
@@ -786,7 +786,7 @@ fn prepare(s: &Session, p: &Value) -> Result<PlaceJob> {
(true, _) => return Err(bad(PLACE, "replace: select the one object to replace")),
};
let replaced = old.and_then(|id| st.doc.node(id)).cloned();
Ok(PlaceJob { doc: st.uid, params: p.clone(), old, replaced, target: board_at(&st.doc, at) })
Ok(PlaceJob { doc: st.uid, params: s.prefs.with_pdf_font_choice(p), old, replaced, target: board_at(&st.doc, at) })
}
/// Place the file `read` holds in the active document.
+16
View File
@@ -72,6 +72,9 @@ fn refs(n: &mut Node, f: &mut impl FnMut(Ref)) {
paint_refs(&mut r.style.fill, f);
paint_refs(&mut r.style.stroke, f);
}
if let Some(fonts) = &mut t.file_fonts {
fonts.map_keys(|key| f(Ref::Image(key)));
}
}
NodeKind::Image(im) => f(Ref::Image(&mut im.key)),
NodeKind::PlacedDocument(pl) => f(Ref::Image(&mut pl.key)),
@@ -352,6 +355,19 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) {
dst.images.insert(new.to_string(), blob.clone());
}
}
// Equal font bytes can reuse an existing image entry whose runtime lease is still empty.
// Transfer the validated source lease too: cached text nodes hold only weak references.
for (old, (new, copy)) in &images {
if *copy {
continue;
}
let Some(blob) = src.images.get(old).filter(|b| b.mime == vectorcraft_doc::FILE_FONT_MIME) else { continue };
let Some(target) = new.as_ref().and_then(|key| dst.images.get_mut(key)) else { continue };
let owner = blob.file_font.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
if let Some(face) = owner.as_ref().filter(|face| std::ptr::eq(face.bytes(), blob.bytes.as_slice()) || face.bytes() == blob.bytes.as_slice()) {
*target.file_font.get_mut().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(face.clone());
}
}
for (old, new) in copies(&symbols) {
if let Some(mut def) = src.symbols.iter().find(|s| s.name == old).cloned() {
def.name = new.to_string();
+5 -2
View File
@@ -333,7 +333,7 @@ fn read_source(
}
let a = opened_document_art(name, (bytes, opened), path, page, bounding, page_box, cmd)?;
let bytes = shared.cloned().unwrap_or_else(|| Arc::new(bytes.to_vec()));
let mut blob = ImageBlob { mime: mime(name, &bytes).into(), bytes, proxy: None };
let mut blob = ImageBlob { mime: mime(name, &bytes).into(), bytes, proxy: None, file_font: Default::default() };
let shown = PlacedDocument {
link: LinkInfo { page: Some(page), ..LinkInfo::new(path.unwrap_or(name)) },
key: key.clone(),
@@ -468,7 +468,10 @@ pub(crate) fn full_documents(d: &Document) -> (Cow<'_, Document>, Vec<String>) {
let Some(blob) = out.images.get(&p.key) else { continue };
match vectorcraft_doc::placed_document::full_bytes(&p, blob) {
Some(bytes) => {
out.images.insert(p.key.clone(), ImageBlob { mime: mime(p.link.name(), &bytes).into(), bytes, proxy: blob.proxy.clone() });
out.images.insert(
p.key.clone(),
ImageBlob { mime: mime(p.link.name(), &bytes).into(), bytes, proxy: blob.proxy.clone(), file_font: Default::default() },
);
}
None => {
previews.insert(p.key);
+2 -2
View File
@@ -651,8 +651,8 @@ mod tests {
let s = read(concat!(r"{\rtf1\ansi\uc1 caf\u233?\uc2 \u", "8364", r"\'80\'80 \uc1\u-10179?\u-8704? end\'93q\'94}"));
assert_eq!(text_of(&s), "café€ 😀 end“q”");
assert_eq!(text_of(&read(r"{\rtf1\uc1\u233\bin1 ?X}")), "éX", "binary data is one fallback character");
let mac = read(r"{\rtf1\mac \'8e\'a5}");
assert_eq!(text_of(&mac), "é•", "Mac Roman");
let mac = read(r"{\rtf1\mac \'8e\'ca\'a5\'db\'de}");
assert_eq!(text_of(&mac), "é\u{a0}•€fi", "Mac Roman");
}
#[test]
+2 -15
View File
@@ -185,20 +185,7 @@ pub(in crate::cmd) fn windows_1252(b: u8) -> char {
/// Byte `b` of Mac Roman.
pub(in crate::cmd) fn mac_roman(b: u8) -> char {
const HIGH: [char; 128] = [
'Ä', 'Å', 'Ç', 'É', 'Ñ', 'Ö', 'Ü', 'á', 'à', 'â', 'ä', 'ã', 'å', 'ç', 'é', 'è', //
'ê', 'ë', 'í', 'ì', 'î', 'ï', 'ñ', 'ó', 'ò', 'ô', 'ö', 'õ', 'ú', 'ù', 'û', 'ü', //
'†', '°', '¢', '£', '§', '•', '¶', 'ß', '®', '©', '™', '´', '¨', '≠', 'Æ', 'Ø', //
'∞', '±', '≤', '≥', '¥', 'µ', '∂', '∑', '∏', 'π', '∫', 'ª', 'º', 'Ω', 'æ', 'ø', //
'¿', '¡', '¬', '√', 'ƒ', '≈', '∆', '«', '»', '…', '\u{A0}', 'À', 'Ã', 'Õ', 'Œ', 'œ', //
'–', '—', '“', '”', '‘', '’', '÷', '◊', 'ÿ', 'Ÿ', '⁄', '€', '‹', '›', 'fi', 'fl', //
'‡', '·', '‚', '„', '‰', 'Â', 'Ê', 'Á', 'Ë', 'È', 'Í', 'Î', 'Ï', 'Ì', 'Ó', 'Ô', //
'\u{F8FF}', 'Ò', 'Ú', 'Û', 'Ù', 'ı', 'ˆ', '˜', '¯', '˘', '˙', '˚', '¸', '˝', '˛', 'ˇ',
];
match b {
0x80.. => HIGH.get(usize::from(b - 0x80)).copied().unwrap_or(char::REPLACEMENT_CHARACTER),
_ => char::from(b),
}
craft_codepage::windows_byte(craft_codepage::MAC_ROMAN_CODE_PAGE, b)
}
/// `text` with its line breaks (CR LF, CR or LF) as paragraph breaks, cleaned up as `o` says:
@@ -344,7 +331,7 @@ mod tests {
let ansi = TextOptions { character_set: CharacterSet::Ansi, ..TextOptions::default() };
assert_eq!(decode(&[0x93, b'q', 0x94, 0xE9], ansi), "“q”é");
let mac = TextOptions { character_set: CharacterSet::Ansi, mac: true, ..TextOptions::default() };
assert_eq!(decode(&[0xD2, b'q', 0xD3, 0x8E, 0xA5, 0xDB], mac), "“q”é•€");
assert_eq!(decode(&[0xD2, b'q', 0xD3, 0x8E, 0xCA, 0xA5, 0xDB, 0xDE, 0xF0], mac), "“q”é\u{a0}•€fi\u{f8ff}");
}
/// The other character sets decode by their Encoding Standard decoders: the platform matters
+332 -23
View File
@@ -44,10 +44,11 @@
//! images or symbol instances of those kinds, to read only: its output must return each of them
//! unchanged ([`objects::decode_output_with`]).
use std::collections::HashMap;
use std::sync::{Arc, Mutex, RwLock};
use serde_json::{Map, Value, json};
use vectorcraft_doc::{Effect, Node};
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};
@@ -113,8 +114,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);
@@ -330,7 +342,8 @@ impl FilterRun {
/// Applies the plug-in's `output` to the active document as one undo step: its objects, and what
/// it keeps with the document from now on. An output its permissions don't allow, and one that
/// changes or leaves out a read-only object it was given, is refused, and the document stays as
/// it was.
/// it was. An output that changes neither the objects nor the kept data records no undo step and
/// leaves the document unmodified; its objects are still selected.
fn finish(self, s: &mut Session, output: &[u8]) -> Result<Value> {
let m = self.plugin.manifest();
let may = m.permissions();
@@ -342,18 +355,43 @@ impl FilterRun {
// A command's undo step is named after the command.
let label = self.label();
let (inputs, parent) = (self.inputs, self.parent);
let ids = s.edit(&label, |d, sel| {
let before = (!may_write).then(|| d.layers.clone());
let ids = objects::apply_output(d, &inputs, out.objects, parent, &admit_effects).map_err(err)?;
if before.is_some_and(|b| b != d.layers) {
return Err(not_granted(&m.name, Permission::DocWrite));
// The output is applied to a copy of the document, as `colorcmds::edit_if_changed` applies
// its pass: only a copy whose objects or kept data differ becomes the document, as one undo
// step. Otherwise the document, its undo and redo steps and its saved state stay as they
// were, and only the selection is set.
if s.script_running() {
return Err(EngineError::Busy);
}
if !s.previewing && super::typing_in_progress(s) {
super::settle_interaction(s)?;
}
let now = s.doc()?.doc.clone();
let mut d = (*now).clone();
let before = (!may_write).then(|| d.layers.clone());
let ids = objects::apply_output(&mut d, &inputs, out.objects, parent, &admit_effects).map_err(err)?;
if before.is_some_and(|b| b != d.layers) {
return Err(not_granted(&m.name, Permission::DocWrite));
}
if let Some(data) = out.document_data {
d.set_plugin_data(&m.id, data);
}
let selectable = |d: &Document| ids.iter().copied().filter(|&id| d.node(id).is_some_and(objects::selectable)).collect::<Vec<_>>();
if same_art(&d.layers, &now.layers) && d.plugin_data(&m.id) == now.plugin_data(&m.id) {
let st = s.doc()?;
let mut sel = st.selection.clone();
sel.set(selectable(&st.doc));
if sel != st.selection {
s.select(|_, selection| *selection = sel)?;
}
if let Some(data) = out.document_data {
d.set_plugin_data(&m.id, data);
}
sel.set(ids.iter().copied().filter(|&id| d.node(id).is_some_and(objects::selectable)));
Ok(ids)
})?;
} else {
// The document is shared with `now` no longer, so `s.edit` does not copy it again.
drop(now);
s.edit(&label, |doc, sel| {
*doc = d;
sel.set(selectable(doc));
Ok(())
})?;
}
let mut out = json!({"plugin": m.id, "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()});
if let Some(cmd) = &self.command {
out["command"] = json!(cmd.id);
@@ -362,6 +400,11 @@ impl FilterRun {
}
}
/// Whether layer lists `a` and `b` hold the same art: a layer that is shared is not compared again.
fn same_art(a: &[Arc<Node>], b: &[Arc<Node>]) -> bool {
a.len() == b.len() && a.iter().zip(b).all(|(x, y)| Arc::ptr_eq(x, y) || x == y)
}
/// The error of a filter `name` whose output needs `permission`, which it wasn't granted.
fn not_granted(name: &str, permission: Permission) -> EngineError {
let (name, p) = (permissions::display_text(name, permissions::MAX_SHOWN_NAME), permission.name());
@@ -466,15 +509,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();
@@ -483,15 +789,18 @@ fn spec_of(p: &Plugin, c: &Command) -> &'static CommandSpec {
fields.push_str(own);
}
let params = format!(
"{{{fields}}} run “{label}”, a command of plug-in {}, on the selected paths and compound paths as plugin.run runs a filter, with _context.command {:?}: one undo step → {{plugin, command, ids}}",
"{{{fields}}} run “{label}”, a command of plug-in {}, on the selected paths and compound paths as plugin.run runs a filter, with _context.command {:?}: one undo step, none when the run changes nothing → {{plugin, command, ids}}",
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),
@@ -1270,7 +1579,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), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 or 2), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.<id>.<command id>, which runs it), label, params (doc), paramsSchema, menu?: {path: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}",
always,
list
),
@@ -1288,7 +1597,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Run Plug-in",
[],
None,
"{id, params?: {…} (the plug-in's parameters; or give them as top-level keys; missing ones take their defaults, see plugin.info), ids?: [object id] (left out or null: the selection), …the plug-in's parameters as top-level keys} run an object filter on the selected paths and compound paths (inside selected groups and layers too; hidden, locked, guide and clipping paths, compound paths that clip a clip group and paths inside a group that clips one are left out): it may change, delete or add objects, as one undo step; the result is selected, except the objects it locked or made guides. A filter whose manifest lists inputs (type, image, symbolInstance; it lists doc.read in permissions, so plugin.install needs grant) is also given the selected objects of those kinds to read, in paint order from the bottom, with at most 16 MiB of pixels and 16 MiB of type runs per run (an object that doesn't fit what the objects before it left comes with pixelsOmitted or truncated; an image that reaches the decoder counts toward the pixels even when decoding fails); every object counts toward the input's half of the plug-in's memory cap, ids, bounds, transforms and names included, and an object whose fields besides its pixels and runs don't fit fails the run with a memory-budget error naming it and its size (a path or compound path fails it with the memory-budget error for a selection too large to hand over), and more than 100,000 of these objects fail it with an object-budget error: its output returns each as {id} or exactly as given, or the run is refused and nothing changes. With nothing selected it gets no objects (generators add theirs to the current layer). A filter with a commandAllowlist runs the commands it names while it runs (vc_call, see docs/plugins.md): its calls and its output are one undo step, and a run that fails or makes a call that fails changes nothing → {plugin, ids}",
"{id, params?: {…} (the plug-in's parameters; or give them as top-level keys; missing ones take their defaults, see plugin.info), ids?: [object id] (left out or null: the selection), …the plug-in's parameters as top-level keys} run an object filter on the selected paths and compound paths (inside selected groups and layers too; hidden, locked, guide and clipping paths, compound paths that clip a clip group and paths inside a group that clips one are left out): it may change, delete or add objects, as one undo step (an output that changes no object and no kept data records none and leaves the document unmodified); the result is selected, except the objects it locked or made guides. A filter whose manifest lists inputs (type, image, symbolInstance; it lists doc.read in permissions, so plugin.install needs grant) is also given the selected objects of those kinds to read, in paint order from the bottom, with at most 16 MiB of pixels and 16 MiB of type runs per run (an object that doesn't fit what the objects before it left comes with pixelsOmitted or truncated; an image that reaches the decoder counts toward the pixels even when decoding fails); every object counts toward the input's half of the plug-in's memory cap, ids, bounds, transforms and names included, and an object whose fields besides its pixels and runs don't fit fails the run with a memory-budget error naming it and its size (a path or compound path fails it with the memory-budget error for a selection too large to hand over), and more than 100,000 of these objects fail it with an object-budget error: its output returns each as {id} or exactly as given, or the run is refused and nothing changes. With nothing selected it gets no objects (generators add theirs to the current layer). A filter with a commandAllowlist runs the commands it names while it runs (vc_call, see docs/plugins.md): its calls and its output are one undo step, and a run that fails or makes a call that fails changes nothing → {plugin, ids}",
has_doc,
run
),
@@ -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",
+2
View File
@@ -140,6 +140,7 @@ 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!("usePreciseCursors", "General", "Options", "Use Precise Cursors", bool),
p!("showToolTips", "General", "Options", "Show Tool Tips", bool),
p!("showToolCards", "General", "Options", "Show Tool Cards", bool),
@@ -396,6 +397,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[
p!("recoveryOffForComplex", "File Handling", "Data Recovery", "Turn off Data Recovery for complex documents", bool),
p!("recentFilesCount", "File Handling", "Files", "Number of Recent Files to Display", int(0, 30)),
p!("lowResProxyEps", "File Handling", "Files", "Use Low Resolution Proxy for Linked EPS", bool),
p!("pdfImportEmbeddedFonts", "File Handling", "Files", "Use fonts embedded in imported PDFs", bool),
p!("antiAliasedBitmaps", "File Handling", "Files", "Display Bitmaps as Anti-aliased Images in Pixel Preview", bool),
p!(
"updateLinks",
+8 -3
View File
@@ -5,7 +5,7 @@
use serde::Deserialize;
use serde_json::{Value, json};
use vectorcraft_doc::Document;
use vectorcraft_eps::{Level, PrintJob, PrintPage};
use vectorcraft_eps::{Level, PrintFonts, PrintJob, PrintPage};
use vectorcraft_geom::{Affine, Rect};
use vectorcraft_pdf::{PrintLayers, PrintOptions, PrintPreview, PrintSettings};
@@ -23,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Print Setup",
[],
None,
"{preset?: name ([Default] or a saved print preset, any case: print.presets.list; its settings replace the document's, as choosing it in the Print dialog does), settings?: {copies: 1 (1–999), collate: true, reverse, artboards: all|range|ignore (all the art as one page), range: \"1-3, 5\" (1-based, with artboards: range), skipBlank (leave out artboards with no art that prints), media: letter|legal|tabloid|a3|a4|a5|a6|b4|b5|b4 (jis)|b5 (jis)|b6 (jis)|japanese postcard|japanese double postcard|japanese envelope #3|japanese envelope #4|kaku #2|kaku #3|yonroku-ban|custom (a paper is named by its id or its dialog label, any case and spacing, so `B5 (JIS)` works; b4 and b5 stay the ISO 216 sizes, 250 × 353 and 176 × 250 mm, and the JIS sizes are b4 (jis) 257 × 364 mm, b5 (jis) 182 × 257 mm and b6 (jis) 128 × 182 mm), width, height (custom paper, 72–14400 pt), orientation: portrait|landscape|portraitFlipped|landscapeFlipped, autoRotate: true (turn the paper to each artboard; orientation ignored), transverse (the page a quarter turn on the paper), printLayers: visiblePrintable|visible|all (template layers never print), placement: {origin: topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight (the point of the printed area, the artboard with its bleed and marks, on the same point of the imageable area), x, y (pt, right and down)}, scaling: none|fit|custom|tileFull|tileImageable, scale: {width: 100, height: 100 (1–1000 % with custom and tiling), linked: true (width and height stay equal: give one and the other follows, and turning it on sets the height to the width; a different width and height without linked turn it off, and with linked: true, or linked: null over a linked scale, are an error; a saved scale without linked reads it as false)}, overlap: 0 (pt between tiles), tileRange: \"\" (1-based tiles across then down; empty: all), copiesPerSheet: false (not with tiling: as many copies of each artboard, with its bleed and marks, as fit the imageable area, across then down, not turned; the placement places the grid; an artboard that doesn't fit prints one copy per sheet, with a warning), gutter: 0 (pt between copies, 0–720), margin: 0 (pt the device can't print around the paper: the imageable area is inside it), marks: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25, offset: 6} (as document.exportPdf, at the paper's scale; page information adds the tile and the ink), bleed: {useDocument: true (the document's bleed, document.setup), top, bottom, left, right} (pt), output: {mode: composite|separations (one gray page per ink that prints), emulsion: up|down (down mirrors), image: positive|negative, spotsToProcess, overprintBlack: false (separations: solid 100% K or 100% gray fills, strokes and characters, to within half a percent, overprint in the printed copy, gradients when every stop is (every point of a freeform one); rich, RGB, spot-linked and lighter blacks are not marked, and paints already set to overprint keep it; composite ignores it), inks: [{name: \"Cyan\"|…|a spot swatch, print: true, frequency (lpi, default 60), angle (screen angle, degrees counter-clockwise as PostScript setscreen takes it; default C 15, M 75, Y 0, K 45, spots 45), convertToProcess: false (a spot ink only: it prints on the process plates, with no plate of its own, and its print, frequency and angle are kept for when it prints as a spot ink again; spotsToProcess converts every spot ink whatever it says)}]}, graphics: {autoFlatness: true, flatness: 1 (0.2–100), fonts: none|subset|complete}, color: {intent: perceptual|relativeColorimetric|saturation|absoluteColorimetric, preserveNumbers: true (CMYK colors keep their values), profile: \"\" (the printer profile, an RGB or CMYK one: composite PDF colors are converted to it with the intent, separations separate with a CMYK one; empty: as they are)}, advanced: {printAsBitmap (composite pages print as one image each, at the document's raster effects resolution, or lower for a page larger than 64 Mpx or 32,768 px a side), overprints: preserve|discard|simulate (composite output; preserve writes them to overprint (/OP), simulate prints them as Overprint Preview shows them; separations always keep them), flattenerPreset: \"\" (a flattener preset, built-in or saved: transparency is flattened before printing; empty: it prints live; PostScript defaults to medium)}, tileOrigin: {placed: false, x, y} (where the Print Tiling tool put the pages: print.tiling.set)}} store the print settings with the document, over the ones it has or the preset's (null keeps a value), as one undo step; no settings or preset → {settings} (the current ones, defaults if never set up)",
"{preset?: name ([Default] or a saved print preset, any case: print.presets.list; its settings replace the document's, as choosing it in the Print dialog does), settings?: {copies: 1 (1–999), collate: true, reverse, artboards: all|range|ignore (all the art as one page), range: \"1-3, 5\" (1-based, with artboards: range), skipBlank (leave out artboards with no art that prints), media: letter|legal|tabloid|a3|a4|a5|a6|b4|b5|b4 (jis)|b5 (jis)|b6 (jis)|japanese postcard|japanese double postcard|japanese envelope #3|japanese envelope #4|kaku #2|kaku #3|yonroku-ban|custom (a paper is named by its id or its dialog label, any case and spacing, so `B5 (JIS)` works; b4 and b5 stay the ISO 216 sizes, 250 × 353 and 176 × 250 mm, and the JIS sizes are b4 (jis) 257 × 364 mm, b5 (jis) 182 × 257 mm and b6 (jis) 128 × 182 mm), width, height (custom paper, 72–14400 pt), orientation: portrait|landscape|portraitFlipped|landscapeFlipped, autoRotate: true (turn the paper to each artboard; orientation ignored), transverse (the page a quarter turn on the paper), printLayers: visiblePrintable|visible|all (template layers never print), placement: {origin: topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight (the point of the printed area, the artboard with its bleed and marks, on the same point of the imageable area), x, y (pt, right and down)}, scaling: none|fit|custom|tileFull|tileImageable, scale: {width: 100, height: 100 (1–1000 % with custom and tiling), linked: true (width and height stay equal: give one and the other follows, and turning it on sets the height to the width; a different width and height without linked turn it off, and with linked: true, or linked: null over a linked scale, are an error; a saved scale without linked reads it as false)}, overlap: 0 (pt between tiles), tileRange: \"\" (1-based tiles across then down; empty: all), copiesPerSheet: false (not with tiling: as many copies of each artboard, with its bleed and marks, as fit the imageable area, across then down, not turned; the placement places the grid; an artboard that doesn't fit prints one copy per sheet, with a warning), gutter: 0 (pt between copies, 0–720), margin: 0 (pt the device can't print around the paper: the imageable area is inside it), marks: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25, offset: 6} (as document.exportPdf, at the paper's scale; page information adds the tile and the ink), bleed: {useDocument: true (the document's bleed, document.setup), top, bottom, left, right} (pt), output: {mode: composite|separations (one gray page per ink that prints), emulsion: up|down (down mirrors), image: positive|negative, spotsToProcess, overprintBlack: false (separations: solid 100% K or 100% gray fills, strokes and characters, to within half a percent, overprint in the printed copy, gradients when every stop is (every point of a freeform one); rich, RGB, spot-linked and lighter blacks are not marked, and paints already set to overprint keep it; composite ignores it), inks: [{name: \"Cyan\"|…|a spot swatch, print: true, frequency (lpi, default 60), angle (screen angle, degrees counter-clockwise as PostScript setscreen takes it; default C 15, M 75, Y 0, K 45, spots 45), convertToProcess: false (a spot ink only: it prints on the process plates, with no plate of its own, and its print, frequency and angle are kept for when it prints as a spot ink again; spotsToProcess converts every spot ink whatever it says)}]}, graphics: {autoFlatness: true, flatness: 1 (0.2–100), fonts: none|subset|complete (PostScript output: subset (default) sends each page the glyphs it shows, complete sends every glyph of each font once before the first page, none sends no font and names the printer's own; PDF output embeds subsets of the fonts whose licenses allow it, and draws the others as outlines, with any of them, and none or complete adds a note)}, color: {intent: perceptual|relativeColorimetric|saturation|absoluteColorimetric, preserveNumbers: true (CMYK colors keep their values), profile: \"\" (the printer profile, an RGB or CMYK one: composite PDF colors are converted to it with the intent, separations separate with a CMYK one; empty: as they are)}, advanced: {printAsBitmap (composite pages print as one image each, at the document's raster effects resolution, or lower for a page larger than 64 Mpx or 32,768 px a side), overprints: preserve|discard|simulate (composite output; preserve writes them to overprint (/OP), simulate prints them as Overprint Preview shows them; separations always keep them), flattenerPreset: \"\" (a flattener preset, built-in or saved: transparency is flattened before printing; empty: it prints live; PostScript defaults to medium)}, tileOrigin: {placed: false, x, y} (where the Print Tiling tool put the pages: print.tiling.set)}} store the print settings with the document, over the ones it has or the preset's (null keeps a value), as one undo step; no settings or pre Line truncated
has_doc,
setup
),
@@ -276,6 +276,11 @@ fn print(s: &mut Session, p: &Value) -> Result<Value> {
setting_notes.push("the printer profile converts the colours of PDF output: PostScript prints the document's colours".to_string());
}
let flatness = (!set.graphics.auto_flatness).then_some(set.graphics.flatness);
let fonts = match set.graphics.fonts {
vectorcraft_pdf::FontDownload::None => PrintFonts::Resident,
vectorcraft_pdf::FontDownload::Subset => PrintFonts::Subset,
vectorcraft_pdf::FontDownload::Complete => PrintFonts::Complete,
};
let plan = vectorcraft_pdf::plan(prepared.as_ref().unwrap_or(doc), &PrintOptions { settings: set, postscript: true, ..Default::default() })
.map_err(|e| pdf_error(PRINT, e))?;
let pages: Vec<PrintPage> = plan
@@ -294,7 +299,7 @@ fn print(s: &mut Session, p: &Value) -> Result<Value> {
ink: sh.ink.as_ref().map(|i| (i.name.as_str(), i.frequency, i.angle)),
})
.collect();
let job = PrintJob { level, title: plan.title.clone(), created: plan.created, flatness };
let job = PrintJob { level, title: plan.title.clone(), created: plan.created, flatness, fonts };
let out = vectorcraft_eps::print(&pages, &plan.order, &job).map_err(|e| bad(PRINT, e))?;
for w in plan.warnings.iter().chain(&out.warnings) {
if !warnings.contains(w) {
+1 -1
View File
@@ -67,7 +67,7 @@ fn drop_guides(nodes: &mut Vec<Arc<Node>>) {
/// nothing is drawn get none.
fn bitmap_document(cmd: &str, doc: &Document, set: &PrintSettings, rich_black: bool) -> Result<Document> {
let regions = vectorcraft_pdf::print_regions(doc, set).map_err(|e| pdf_error(cmd, e))?;
let bleed = set.bleed.of(doc);
let bleed = vectorcraft_pdf::page_bleed(&set.bleed, doc);
let mut art = doc.clone();
drop_guides(&mut art.layers);
let anti_alias = if doc.raster_effects.anti_alias { AntiAlias::Art } else { AntiAlias::None };
+34 -8
View File
@@ -874,6 +874,11 @@ struct Meta {
/// images were kept apart: the document entry holds them).
#[serde(skip_serializing_if = "BTreeMap::is_empty")]
images: BTreeMap<String, ImageRef>,
/// A command a script ran opened or changed the document since the person last saved it
/// ([`crate::DocState::by_script`]): the commands scripts run treat the restored document as
/// one a script opened.
#[serde(skip_serializing_if = "std::ops::Not::not")]
by_script: bool,
}
/// One of a copy's images: its entry in the copy's area.
@@ -1033,10 +1038,13 @@ impl RecoveryJob {
let meta_name = format!("{}{META_EXT}", self.file);
// The details name the images, so a crash between writing the document and its details
// would pair the new document with the old copy's images: when the new document has
// images the old details don't name, they name both until the new document is in.
let old = read_meta(store, &self.file).images;
if meta.images.iter().any(|(k, r)| old.get(k).is_none_or(|o| o.blob != r.blob)) {
// images the old details don't name, they name both until the new document is in. Likewise
// when a script's command changed the document since the old details: they say so first.
let old_meta = read_meta(store, &self.file);
let old = old_meta.images;
if (meta.by_script && !old_meta.by_script) || meta.images.iter().any(|(k, r)| old.get(k).is_none_or(|o| o.blob != r.blob)) {
let mut both = meta.clone();
both.by_script |= old_meta.by_script;
for (k, r) in old {
both.images.entry(k).or_insert(r);
}
@@ -1195,6 +1203,7 @@ pub fn jobs(s: &mut Session, store: &Arc<dyn RecoveryStore>) -> Result<(Vec<Reco
links_from: st.links_from.clone().filter(|_| st.path.is_none()),
// Filled in as the copy is written.
images: BTreeMap::new(),
by_script: st.by_script.is_some(),
};
out.push(RecoveryJob { uid: st.uid, file, title, meta, save, store: store.clone() });
}
@@ -1456,9 +1465,19 @@ fn targets(s: &mut Session, store: &dyn RecoveryStore, cmd: &str, p: &Value) ->
/// (for Save As) and format. The copy moves into this session's area (another crash keeps it).
fn restore_one(s: &mut Session, store: &Arc<dyn RecoveryStore>, file: &str) -> Result<Value> {
let bytes = store.read(&format!("{file}{DOC_EXT}")).map_err(EngineError::Other)?;
let meta_bytes = store.read(&format!("{file}{META_EXT}")).unwrap_or_default();
let meta: Meta = serde_json::from_slice(&meta_bytes).unwrap_or_default();
let (mut doc, _, mut warnings) = fileio::native_file(&bytes).map_err(|e| EngineError::Other(format!("recovery copy `{file}`: {e}")))?;
// A details entry that is missing or can't be parsed does not say whether a script's command
// changed the document: the copy restores as one a script opened, and the details written for
// it say so.
let read = store.read(&format!("{file}{META_EXT}")).ok().and_then(|b| serde_json::from_slice::<Meta>(&b).ok().map(|m| (m, b)));
let (meta, meta_bytes) = match read {
Some(both) => both,
None => {
let meta = Meta { by_script: true, ..Meta::default() };
let bytes = serde_json::to_vec_pretty(&meta).map_err(|e| EngineError::Other(e.to_string()))?;
(meta, bytes)
}
};
let (mut doc, _, mut warnings) = fileio::decode_native_file(&bytes).map_err(|e| EngineError::Other(format!("recovery copy `{file}`: {e}")))?;
// A frame whose first paragraph continues from the frame before draws it without the
// paragraph's first-line indent and list marker.
super::threads::mark_continued(&mut doc);
@@ -1473,7 +1492,7 @@ fn restore_one(s: &mut Session, store: &Arc<dyn RecoveryStore>, file: &str) -> R
};
match read {
Ok(data) => {
let mut blob = ImageBlob { mime: r.mime.clone(), bytes: data, proxy: None };
let mut blob = ImageBlob { mime: r.mime.clone(), bytes: data, proxy: None, file_font: Default::default() };
// Until the linked file is read, the preview stands in for it.
if r.proxy {
blob.proxy = Some(blob.bytes.clone());
@@ -1497,8 +1516,10 @@ fn restore_one(s: &mut Session, store: &Arc<dyn RecoveryStore>, file: &str) -> R
for (blob, data) in &blobs {
store.write(&format!("{area}/{blob}"), data).map_err(EngineError::Other)?;
}
store.write(&format!("{mine}{DOC_EXT}"), &bytes).map_err(EngineError::Other)?;
// The details go first: a crash in between leaves no copy without them (a copy is its
// document entry), and the copy in the old area stays whole.
store.write(&format!("{mine}{META_EXT}"), &meta_bytes).map_err(EngineError::Other)?;
store.write(&format!("{mine}{DOC_EXT}"), &bytes).map_err(EngineError::Other)?;
}
// The copy's images in its old area go with the area, once no copy is left there.
store.remove(&format!("{file}{DOC_EXT}")).map_err(EngineError::Other)?;
@@ -1510,6 +1531,8 @@ fn restore_one(s: &mut Session, store: &Arc<dyn RecoveryStore>, file: &str) -> R
let links_from = meta.path.clone().or_else(|| meta.links_from.clone());
let base = super::links::LinkBase::file(links_from.as_deref());
let links = super::links::resolve(&mut doc, base, s.prefs.update_links == "automatically", s.prefs.low_res_proxy_eps);
// Bind only after the copy's external resources and linked files have been restored.
warnings.extend(Session::refresh_text_bounds(&mut doc));
let index = s.add_document(doc, meta.path.clone());
let st = s.doc_mut()?;
st.recovered = true;
@@ -1517,6 +1540,9 @@ fn restore_one(s: &mut Session, store: &Arc<dyn RecoveryStore>, file: &str) -> R
st.imported_from = meta.imported_from.clone();
st.import_losses = meta.import_losses.clone();
st.format = SAVE_FORMATS.iter().copied().find(|f| *f == meta.format).unwrap_or("vectorcraft");
if meta.by_script {
st.by_script = Some(crate::doc_state::ByScript::Opened);
}
if let Some(pdf) = meta.native_pdf_compatible {
st.save_options.insert("pdfCompatible".into(), json!(pdf));
}
+269 -42
View File
@@ -48,7 +48,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Retype",
["Type"],
None,
"{fonts?: [family…], tolerance?: 0..0.05 (default 0: exact matches only)} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live type: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation; with a tolerance above 0, a shape that is no glyph exactly may nearly be one (an outline simplified, a curve split in two, contours in another order, start or direction) when its leftover distance from the glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (VectorCraft's own measure; shapes of at most 8 contours); a compound path holding several glyphs (a word outlined as one path, at most 256 contour groups, 512 contours and 65,536 path elements, and 16,384 contours per command) is split into them, and becomes type only when every one of them matches; matched glyphs become point text in that font and size at the same baseline, one object per line unless lines stack into one (below), with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more exactly matched glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); lines that follow each other in paint order with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the others' tracking), each one the same leading (0.25 to 3 times the size) below the one before, and lined up at their starts, ends or centers become one area type object with that leading (Auto when Auto gives it) and left, right or center alignment, or one multi-line point type object when area type (after Text Wrap) would not draw the outlines' glyphs in their places or when checking the Text Wrap objects on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes; where even that type would move a glyph, the lines before that glyph's line stay one object and the rest are joined again from that line; lines with an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke stay one object each; a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions; with a tolerance, within it), and before a near-matched glyph the line's size and turn would draw further from its shape than the tolerance; a glyph must also paint the area the shape paints under its fill rule (a nonzero compound whose inner contour runs the same way as its outer one paints its center, so a ring glyph does not replace it; a counter narrower than three times the outline tolerance across in some direction, an outline too large to check, or parts of a split compound that overlap where its fill rule leaves the overlap unpainted, or that overlap at all when the compound has an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke, also keep the shape an outline); shapes that match no font, glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts (lines joined by \\n), fonts: [{family, style, size, tracking (1/1000 em), leading (pt, null for Auto or one line), area (bool), score (how closely the line's least close glyph fits, 1 for exact, 0 at a leftover distance of 0.05)}], unmatched: [id…] (shapes that stayed as they are when another shape became type), truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error, with no unmatched list, when no shape becomes type, or when tolerance is not a number from 0 to 0.05",
"{fonts?: [family…], tolerance?: 0..0.05 (default 0: exact matches only)} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live type: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation; with a tolerance above 0, a shape that is no glyph exactly may nearly be one (an outline simplified, a curve split in two, contours in another order, start or direction) when its leftover distance from the glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (VectorCraft's own measure; shapes of at most 8 contours); a compound path holding several glyphs (a word outlined as one path, at most 256 contour groups, 512 contours and 65,536 path elements, and 16,384 contours per command) is split into them (a part matching exactly also with its contours the other way round, or with only some of them so, as an o's counter alone in an even-odd compound), and becomes type only when every one of them matches; matched glyphs become point text in that font and size at the same baseline, one object per line unless lines stack into one (below), with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more exactly matched glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); lines that follow each other in paint order with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the others' tracking), each one the same leading (0.25 to 3 times the size) below the one before, and lined up at their starts, ends or centers become one area type object with that leading (Auto when Auto gives it) and left, right or center alignment, or one multi-line point type object when area type (after Text Wrap) would not draw the outlines' glyphs in their places or when checking the Text Wrap objects on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes; where even that type would move a glyph, the lines before that glyph's line stay one object and the rest are joined again from that line; lines with an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke stay one object each; a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions; with a tolerance, within it), and before a near-matched glyph the line's size and turn would draw further from its shape than the tolerance; a glyph must also paint the area the shape paints under its fill rule (a nonzero compound whose inner contour runs the same way as its outer one paints its center, so a ring glyph does not replace it; a counter narrower than three times the outline tolerance across in some direction, an outline too large to check, or parts of a split compound that overlap where its fill rule leaves the overlap unpainted, or that overlap at all when the compound has an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke, also keep the shape an outline); shapes that match no font, a combining mark that would start a line (a shape whose first 16 matched glyphs include another character's starts it as that character), glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts (lines joined by \\n), fonts: [{family, style, size, tracking (1/1000 em), leading (pt, null for Auto or one line), area (bool), score (how closely the line's least close glyph fits, 1 for exact, 0 at a leftover distance of 0.05)}], unmatched: [id…] (shapes that stayed as they are when another shape became type), truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error, with no unmatched list, when no shape becomes type, or when tolerance is not a number from 0 to 0.05",
has_selected_path,
retype
)]
@@ -272,17 +272,84 @@ impl Line {
}
fn push(&mut self, id: NodeId, m: &GlyphMatch) {
// A gap, past the tracking, wider than half a space before the glyph is spaces the
// outlines left no shape for. Each space takes the tracking too.
self.push_joined(id, m, None);
}
/// For each of `ms`'s glyphs, the distance along the line to the next when untracked type sets
/// them with no spaces (their advances and pair kerning), and when it sets one space between
/// them (the glyph's own advance plus a space where type draws no such layout), taking the
/// characters laid out from `budget`; `None` when the budget is short or type does not draw
/// every glyph without spaces.
fn pair_steps(&self, ms: &[GlyphMatch], system_layout: bool, budget: &mut usize) -> Option<Vec<(f64, f64)>> {
*budget = budget.checked_sub(ms.len().saturating_mul(3))?;
let dir = self.dir();
let gap = (m.origin - self.end).dot(dir) - self.tracking_pt();
// Tracking tighter than a space's width gives each space a negative advance.
let space = space_advance(&self.face) * self.scale + self.tracking_pt();
let spaces = if space.abs() > 1e-9 { gap / space } else { 0.0 };
if spaces.is_finite() && spaces > 0.5 {
let n = (spaces.round() as usize).clamp(1, 64);
self.text.extend(std::iter::repeat_n(' ', n));
let mut bare = self.clone();
bare.tracking = 0.0;
let mut origins = |text: String| -> Vec<Point> {
bare.text = text;
let t = bare.probe(system_layout);
let lay = vectorcraft_text::layout(FontDb::global(), &t);
lay.glyphs.iter().filter(|g| !g.outline.elements().is_empty()).map(|g| t.xf * (g.xf * Point::ORIGIN)).collect()
};
let joined = origins(ms.iter().map(|m| m.ch).collect());
if joined.len() != ms.len() {
return None;
}
let spaced = origins(ms.iter().map(|m| m.ch.to_string()).collect::<Vec<_>>().join(" "));
let space = space_advance(&self.face) * self.scale;
let spaced_ok = spaced.len() == ms.len();
Some(
ms.iter()
.enumerate()
.zip(joined.windows(2))
.map(|((i, m), p)| {
let own = m.face.advance(m.gid) * m.scale + space;
let apart = match (spaced_ok, spaced.get(i), spaced.get(i + 1)) {
(true, Some(a), Some(b)) => (*b - *a).dot(dir),
_ => own,
};
((p[1] - p[0]).dot(dir), apart)
})
.collect(),
)
}
/// [`Line::push`], with `steps` the distances [`Line::pair_steps`] gives for the pair of the
/// line's last glyph and `m`. With `steps`, a gap reads as spaces only when they fit it better
/// than the joined pair does, as when the tracking is measured, however narrow the gap is.
fn push_joined(&mut self, id: NodeId, m: &GlyphMatch, steps: Option<(f64, f64)>) {
// Without `steps`, a gap, past the tracking, wider than half a space before the glyph is
// spaces the outlines left no shape for. Each space takes the tracking too.
let dir = self.dir();
let tr = self.tracking_pt();
let gap = (m.origin - self.end).dot(dir) - tr;
// Tracking tighter than a space's width gives each space a negative advance.
let face_space = space_advance(&self.face) * self.scale;
let space = face_space + tr;
let spaces = if space.abs() > 1e-9 { gap / space } else { 0.0 };
let n = match steps {
Some((joined, apart)) => {
let d = (m.origin - self.matches.last().map_or(self.origin, |p| p.origin)).dot(dir);
// How far `n` spaces set the glyph from where the outlines put it: the pair with one
// space between them is `apart`, and each further space adds a space and the tracking.
let spaced_err = |n: usize| (d - apart + face_space - tr - n as f64 * space).abs();
// Kerning against a space widens or narrows the gap, so the count the gap gives, the
// counts next to it and the count the measured distance gives are compared; the
// rounded count wins a tie.
let measured = (d - apart + face_space - tr) / space;
let best = [spaces.round(), spaces.floor(), spaces.ceil(), measured.round()]
.into_iter()
.filter(|c| c.is_finite())
.map(|c| (c.max(1.0) as usize).min(64))
.min_by(|a, b| spaced_err(*a).total_cmp(&spaced_err(*b)))
.unwrap_or(1);
// The joined pair wins a tie.
if (d - joined - tr).abs() <= spaced_err(best) + self.size() * 1e-5 { 0 } else { best }
}
None if spaces.is_finite() && spaces > 0.5 => (spaces.round() as usize).clamp(1, 64),
None => 0,
};
self.text.extend(std::iter::repeat_n(' ', n));
self.text.push(m.ch);
self.pieces.push(id);
self.matches.push(m.clone());
@@ -426,6 +493,15 @@ impl Line {
/// its characters, spaces included, from `budget` before it runs; without enough left, the
/// line stays as it is, or becomes the best tracked reading laid out before the budget ran out.
fn tracked(self, system_layout: bool, budget: &mut usize) -> Line {
let reach = self.text.chars().count();
self.tracked_reaching(system_layout, budget, reach)
}
/// [`Line::tracked`] for a line whose tracking is applied to `reach` characters, its glyphs and
/// the spaces between them: a measured tracking within 0.05 of a whole number is read as that
/// number only when the difference moves the character `reach` places on by no more than the
/// tolerance [`first_mismatch`] allows.
fn tracked_reaching(self, system_layout: bool, budget: &mut usize, reach: usize) -> Line {
let size = self.size();
let n = self.pieces.len();
// A near-matched glyph sits within the tolerance of where the font draws it, so the gaps
@@ -534,7 +610,12 @@ impl Line {
let mut tries = vec![];
for seed in [lower, median(extra, true), spaced_seed].into_iter().flatten() {
let Some(measured) = measure(seed) else { continue };
for t in [round_tracking(measured), measured] {
let rounded = round_tracking(measured);
let drift = (rounded - measured).abs() / 1000.0 * size * reach.saturating_sub(1) as f64;
for t in [rounded, measured] {
if t != measured && drift > (size * 0.01).max(0.01) {
continue;
}
if !tries.contains(&t) {
tries.push(t);
}
@@ -582,7 +663,12 @@ impl Line {
match (tracked.first_mismatch(&tracked.probe(system_layout)), plain_miss) {
// Under a unit of tracking, or a word space the tracked reading drops, where
// untracked type draws the line: no tracking.
(None, None) if t.abs() < 1.0 || drops_a_word_space => return self,
(None, None)
if (t.abs() < 1.0 && t.abs() / 1000.0 * size * reach.saturating_sub(1) as f64 <= (size * 0.01).max(0.01))
|| drops_a_word_space =>
{
return self;
}
(None, _) => return tracked,
(Some(k), Some(p)) if k > p && best.as_ref().is_none_or(|(b, _)| k > *b) => best = Some((k, tracked)),
_ => {}
@@ -688,18 +774,35 @@ fn set_apart(t: &TextObject, g: &vectorcraft_text::PositionedGlyph, m: &GlyphMat
(finite(shape), finite(moved))
}
/// The most glyphs [`verified`] measures the tracking of after a split.
const MEASURE_SPAN: usize = 32;
/// One part of shape `id`, by the glyph it matched (face, glyph, origin, turn and scale): the parts
/// of a compound path share its id.
type PartKey = (NodeId, u32, u32, [u64; 4]);
fn part_key(id: NodeId, m: &GlyphMatch) -> PartKey {
(id, m.face.id(), m.gid, [m.origin.x.to_bits(), m.origin.y.to_bits(), m.angle.to_bits(), m.scale.to_bits()])
}
/// `lines` checked against their own layout: a line splits where its type stops drawing the
/// outlines, and a glyph its type cannot draw even on its own stays an outline (`unmatched`).
/// The glyphs laid out are bounded by a multiple of the number of glyphs.
fn verified(lines: Vec<Line>, system_layout: bool, unmatched: &mut Vec<NodeId>) -> Vec<Line> {
/// `spacing` holds, for a part of a shape read as a combining mark, the other character that part
/// is. The glyphs laid out are bounded by a multiple of the number of glyphs.
fn verified(
lines: Vec<Line>,
system_layout: bool,
spacing: &std::collections::HashMap<PartKey, GlyphMatch>,
unmatched: &mut Vec<NodeId>,
) -> Vec<Line> {
// Glyphs laid out in all, at most: past it, the glyphs left unchecked stay outlines.
let mut budget = lines.iter().map(|l| l.pieces.len()).sum::<usize>().saturating_mul(16).saturating_add(256);
// Measuring the tracking of the glyphs after a split has a budget of its own, so it cannot
// leave glyphs unchecked; past it they keep no tracking. Each measure takes the glyphs to
// rebuild the rest and the characters it lays out (see [`Line::tracked`]); the budget covers
// one measure of each whole line, as `retype` gives the first, and the glyph checks' budget.
// The glyphs measured again after splits are limited apart from it, at six times each rest's
// glyphs from half as much again as the glyph checks' budget.
// The glyphs measured again after splits are limited apart from it, at six times the glyphs
// each measure reads from half as much again as the glyph checks' budget.
let mut remeasured = budget.saturating_add(budget / 2);
let mut track_budget =
lines.iter().map(|l| l.text.chars().count().saturating_add(l.pieces.len().saturating_mul(394))).fold(budget, usize::saturating_add);
@@ -707,6 +810,44 @@ fn verified(lines: Vec<Line>, system_layout: bool, unmatched: &mut Vec<NodeId>)
let mut out = vec![];
while let Some(l) = todo.pop_front() {
let n = l.pieces.len();
// A combining mark goes with the character before it: a mark that a split left first on
// a line becomes the other character its shape is (`spacing`), alone on a line, or else
// stays an outline, and the line goes on from the glyph after it ([`new_line`] starts no
// line with one).
if l.matches.first().is_some_and(|m| vectorcraft_text::retype::is_combining_mark(m.ch)) {
let first = l.pieces.first().copied();
let alone = first.zip(l.matches.first()).and_then(|(id, mark)| spacing.get(&part_key(id, mark)).map(|m| reposed(&l, id, m)));
if alone.is_none() {
unmatched.extend(first);
}
if n > 1 {
// The tracking was measured with the mark's gap in it: the rest is measured again
// without it, from the same budgets as the rest after a split. A rest that starts
// with a mark too is not measured here: its own pass leaves that mark out and
// measures the glyphs after it.
let measurable = n > 3 && remeasured >= (n - 1).saturating_mul(6) && track_budget >= (n - 1).saturating_mul(6);
let rest = if l.matches.get(1).is_some_and(|m| vectorcraft_text::retype::is_combining_mark(m.ch)) {
l.part(1, n)
} else if measurable {
remeasured = remeasured.saturating_sub((n - 1).saturating_mul(6));
track_budget = track_budget.saturating_sub(n - 1);
l.respaced(1, n, 0.0).map(|r| r.tracked(system_layout, &mut track_budget))
} else if l.tracking == 0.0 {
l.part(1, n)
} else {
l.respaced(1, n, 0.0)
};
match rest {
Some(rest) => todo.push_front(rest),
None => unmatched.extend(l.pieces.get(1..).unwrap_or_default().iter().copied()),
}
}
// Checked before the rest, so the lines keep the outlines' order.
if let Some(alone) = alone {
todo.push_front(alone);
}
continue;
}
// The line's type is laid out over a window from its start that doubles while the type
// draws the window's glyphs as the outlines do, so finding where it stops costs about
// twice the glyphs before that point, not the whole rest of the line each time.
@@ -744,29 +885,10 @@ fn verified(lines: Vec<Line>, system_layout: bool, unmatched: &mut Vec<NodeId>)
// The glyphs before the mismatch, then the rest, each checked as a line of its
// own: the type before the mismatch may draw otherwise without what follows it (a
// font can place a glyph by the glyph after it), and the first glyph on its own
// may still be drawn as it was (a contextual form changed it in the line). The
// rest takes the tracking its own glyphs are spaced by, while the budget for
// measuring it lasts and when type draws its first glyph as it was, followed by the
// next two (else that glyph splits off first, and the tracking is measured from the
// next one); past it, an untracked line's rest keeps its text as it is.
// may still be drawn as it was (a contextual form changed it in the line).
Some(k) => {
let k = k.max(1);
// A measure takes at least six times the rest's glyphs from each budget.
let measurable = n - k >= 3 && remeasured >= (n - k).saturating_mul(6) && track_budget >= (n - k).saturating_mul(6);
let first_drawn = measurable && {
budget = budget.saturating_sub(3);
l.respaced(k, k + 3, l.tracking).is_some_and(|p| p.first_mismatch(&p.probe(system_layout)) != Some(0))
};
let rest = if first_drawn {
// Rebuilding the rest for the measure takes its glyphs from the budget.
remeasured = remeasured.saturating_sub((n - k).saturating_mul(6));
track_budget = track_budget.saturating_sub(n - k);
l.respaced(k, n, 0.0).map(|r| r.tracked(system_layout, &mut track_budget))
} else if l.tracking == 0.0 {
l.part(k, n)
} else {
l.respaced(k, n, 0.0)
};
let rest = rest_after_split(&l, k, system_layout, &mut budget, &mut remeasured, &mut track_budget);
match rest {
Some(r) => todo.push_front(r),
None => unmatched.extend(l.pieces.get(k..).unwrap_or_default().iter().copied()),
@@ -780,6 +902,75 @@ fn verified(lines: Vec<Line>, system_layout: bool, unmatched: &mut Vec<NodeId>)
out
}
/// The rest of `l` from glyph `k` (at least 1) after [`verified`] splits it there. The rest takes
/// the tracking its own glyphs are spaced by, while the budgets for measuring it last and when type
/// draws its first glyph as it was, followed by the next two (else that glyph splits off first, and
/// the tracking is measured from the next one); past it, an untracked line's rest keeps its text as
/// it is. The tracking is measured from the rest's first [`MEASURE_SPAN`] glyphs at most, and the
/// glyphs after them follow at that tracking, so each split costs the same however long the rest
/// is, and splits at irregular gaps early in a line leave the budget for a long evenly tracked run
/// after them. A gap after the glyphs measured reads as spaces only when they fit it better than
/// the joined pair does, as in the glyphs measured: laying those pairs out is set aside from
/// `track_budget` before the tracking is measured, and without enough for both the rest is not
/// measured.
fn rest_after_split(l: &Line, k: usize, system_layout: bool, budget: &mut usize, remeasured: &mut usize, track_budget: &mut usize) -> Option<Line> {
let n = l.pieces.len();
let span = (n - k).min(MEASURE_SPAN);
let more = n - k - span;
// What [`Line::pair_steps`] takes for the last glyph measured and the glyphs after it.
let pairs = if more > 0 { more.saturating_add(1).saturating_mul(3) } else { 0 };
// A measure takes at least six times the glyphs it reads from each budget.
let measurable = n - k >= 3 && *remeasured >= span.saturating_mul(6) && *track_budget >= span.saturating_mul(6).saturating_add(pairs);
let first_drawn = measurable && {
*budget = budget.saturating_sub(3);
l.respaced(k, k + 3, l.tracking).is_some_and(|p| p.first_mismatch(&p.probe(system_layout)) != Some(0))
};
if !first_drawn {
return if l.tracking == 0.0 { l.part(k, n) } else { l.respaced(k, n, 0.0) };
}
// Rebuilding the glyphs measured takes them from the budget.
*remeasured = remeasured.saturating_sub(span.saturating_mul(6));
*track_budget = track_budget.saturating_sub(span).saturating_sub(pairs);
let mut pair_budget = pairs;
// The characters the rest's tracking applies to: its glyphs and the spaces between them (a
// space before glyph `at` follows glyph `at - 1`).
let reach = l
.text
.chars()
.scan(0usize, |glyph, c| {
let at = *glyph;
*glyph += usize::from(c != ' ');
Some(if c == ' ' { at > k } else { at >= k })
})
.filter(|kept| *kept)
.count()
.max(n - k);
let mut r = l.respaced(k, k + span, 0.0)?.tracked_reaching(system_layout, track_budget, reach);
// Tracking that leaves a space under half its advance: the gaps alone do not show the spaces
// past the glyphs measured (only the kerning a space breaks may), so the whole rest is measured
// while the budget lasts.
let space = space_advance(&r.face) * r.scale;
if more > 0
&& space + r.tracking_pt() < space / 2.0
&& *remeasured >= (n - k).saturating_mul(6)
&& track_budget.saturating_add(pair_budget) >= (n - k).saturating_mul(6)
&& let Some(whole) = l.respaced(k, n, 0.0)
{
*remeasured = remeasured.saturating_sub((n - k).saturating_mul(6));
*track_budget = track_budget.saturating_add(pair_budget).saturating_sub(n - k);
return Some(whole.tracked(system_layout, track_budget));
}
// The glyphs after those measured follow at that tracking.
let steps = match more {
0 => vec![],
_ => l.matches.get(k + span - 1..).and_then(|ms| r.pair_steps(ms, system_layout, &mut pair_budget)).unwrap_or_default(),
};
for (j, (id, m)) in l.pieces.iter().zip(&l.matches).skip(k + span).enumerate() {
r.push_joined(*id, m, steps.get(j).copied());
}
Some(r)
}
/// Most units (anchors, subpaths and shapes) that Text Wrap objects may copy into the wrap shapes
/// of the area type on the layers Retype changes
/// ([`vectorcraft_doc::text::wrap_copy_units`]) when Retype checks how they flow new area type.
@@ -1105,6 +1296,8 @@ fn join(l: &mut Line, pc: &Piece, cands: &[GlyphMatch]) -> bool {
.iter()
.flat_map(|c| c.poses())
.filter(|fp| !(fp.gid == current.gid && fp.face.id() == current.face.id() && fp.angle == current.angle))
// No line starts with a combining mark (see [`new_line`]).
.filter(|fp| !vectorcraft_text::retype::is_combining_mark(fp.ch))
.collect();
for fp in others {
let mut turned = reposed(l, id, &fp);
@@ -1139,10 +1332,11 @@ fn reposed(l: &Line, id: NodeId, m: &GlyphMatch) -> Line {
}
}
/// A new line of shape `pc` alone, as the first of its candidate glyphs `cands` (none: `None`),
/// with near matches taken at tolerance `slack`.
/// A new line of shape `pc` alone, as the first of its candidate glyphs `cands` that is not a
/// combining mark (none: `None`), with near matches taken at tolerance `slack`. No line starts
/// with a mark: a mark combines with the character before it.
fn new_line(pc: &Piece, cands: &[GlyphMatch], slack: f64) -> Option<Line> {
let m = cands.first()?;
let m = cands.iter().find(|m| !vectorcraft_text::retype::is_combining_mark(m.ch))?;
let dir = Vec2::new(m.angle.cos(), m.angle.sin());
Some(Line {
pieces: vec![pc.id],
@@ -1616,6 +1810,7 @@ fn retype(s: &mut Session, p: &Value) -> Result<Value> {
let mut unmatched = vec![];
// An unmatched shape between glyphs ends the line: the type after it is painted after it.
let mut open = false;
let mut spacing: std::collections::HashMap<PartKey, GlyphMatch> = std::collections::HashMap::new();
// How many glyphs each shape is: a shape of several becomes type only when all of them do.
let mut glyphs_of: std::collections::HashMap<NodeId, usize> = std::collections::HashMap::new();
for (pc, parts) in pieces.iter().zip(&found) {
@@ -1636,8 +1831,40 @@ fn retype(s: &mut Session, p: &Value) -> Result<Value> {
Some(l) if open => join(l, pc, &cands),
_ => false,
};
// A part that joined a line, perhaps as a mark, that is also another character, in
// that face or else in the face most shapes fit of those it is a character in: the
// character, should a split leave the part first on a line ([`verified`]). Kept by
// the glyph the part joined as, since the parts of a compound path share its id.
let is_mark = |m: &GlyphMatch| vectorcraft_text::retype::is_combining_mark(m.ch);
if joined
&& cands.iter().any(is_mark)
&& let Some(m) = cands
.iter()
.find(|m| !is_mark(m))
.or_else(|| ms.iter().enumerate().filter(|(_, m)| !is_mark(m)).max_by(ranked).map(|(_, m)| m))
&& let Some(at) = lines.last().and_then(|l| l.matches.last())
{
spacing.insert(part_key(pc.id, at), m.clone());
}
if !joined {
lines.extend(new_line(pc, &cands, tolerance));
// A part that is only marks in that face may be another character in a face
// fewer shapes fit: it starts its line in the one of those most shapes fit.
let started = new_line(pc, &cands, tolerance).or_else(|| {
let face = ms.iter().enumerate().filter(|(_, m)| !is_mark(m)).max_by(ranked).map(|(_, m)| m.face.id());
let cands: Vec<GlyphMatch> = ms.iter().filter(|m| Some(m.face.id()) == face).cloned().collect();
new_line(pc, &cands, tolerance)
});
match started {
Some(l) => lines.push(l),
// Only combining marks: no line starts with one, so the shape stays an
// outline (a shape of several glyphs then is not whole type, see
// `partial_lines`) and the glyph after it starts the next line.
None => {
unmatched.push(pc.id);
open = false;
continue;
}
}
}
open = true;
}
@@ -1656,7 +1883,7 @@ fn retype(s: &mut Session, p: &Value) -> Result<Value> {
lines.iter().map(|l| l.text.chars().count().saturating_add(l.pieces.len().saturating_mul(393))).fold(256usize, usize::saturating_add);
let mut lines: Vec<Line> = lines.into_iter().map(|l| l.tracked(system_layout, &mut budget)).collect();
share_tracking(&mut lines, system_layout);
let mut lines = verified(lines, system_layout, &mut unmatched);
let mut lines = verified(lines, system_layout, &spacing, &mut unmatched);
if pieces.len() > 1 || glyphs_of.values().any(|n| *n > 1) {
lines.retain(|l| {
let lone = matches!(l.pieces.as_slice(), [id] if lone_pieces.contains(id));
+17 -7
View File
@@ -26,7 +26,7 @@ pub(in crate::cmd) fn specs() -> Vec<CommandSpec> {
"Find Matching Fonts",
[],
None,
"{count?: 1..96 (default 10)} the fonts whose glyphs match the selected outlined text, as the Retype panel lists them: each selected shape (paths and compound paths, inside groups too) is compared with the glyphs of up to 96 loaded fonts, those of the document's live type first, by type.retype's matching (exact matches only); of two versions of a font loaded at once, only the version its family and style name gives is compared, the one choosing the font sets; the fonts rank by how many shapes each matches, then by the mean distance left after fitting, then by family and style name; the document does not change → {fonts: [{family, style, matched (shapes it matches)}] (the first count), shapes (shapes compared), more (more fonts match than count), truncated (shapes past the limits were left out)}; a count that is not a whole number from 1 to 96 is an error",
"{count?: 1..96 (default 10)} the fonts whose glyphs match the selected outlined text, as the Retype panel lists them: each selected shape (paths and compound paths, inside groups too) is compared with the glyphs of up to 96 loaded fonts, those of the document's live type first, by type.retype's matching (exact matches only), a font whose glyphs match the shapes only as combining marks not listed; of two versions of a font loaded at once, only the version its family and style name gives is compared, the one choosing the font sets; the fonts rank by how many shapes each matches, then by the mean distance left after fitting, then by family and style name; the document does not change → {fonts: [{family, style, matched (shapes it matches)}] (the first count), shapes (shapes compared), more (more fonts match than count), truncated (shapes past the limits were left out)}; a count that is not a whole number from 1 to 96 is an error",
has_selected_path,
retype_fonts
)]
@@ -44,6 +44,8 @@ struct Ranked {
matched: usize,
/// The sum of those matches' leftover distances.
residual: f64,
/// Whether some shape matched a glyph of it that is not a combining mark.
character: bool,
}
impl Ranked {
@@ -101,23 +103,31 @@ fn retype_fonts_in(s: &mut Session, p: &Value, db: &FontDb) -> Result<Value> {
for pc in &pieces {
// A shape can fit several glyphs or poses of one font: it counts once for the font, at its
// closest fit.
let mut best: Vec<(Arc<vectorcraft_text::FontFace>, f64)> = vec![];
let mut best: Vec<(Arc<vectorcraft_text::FontFace>, f64, bool)> = vec![];
for m in index.all_matches(&pc.path) {
match best.iter_mut().find(|(f, _)| f.id() == m.face.id()) {
Some(b) => b.1 = b.1.min(m.residual),
None => best.push((m.face, m.residual)),
let character = !vectorcraft_text::retype::is_combining_mark(m.ch);
match best.iter_mut().find(|(f, _, _)| f.id() == m.face.id()) {
Some(b) => {
b.1 = b.1.min(m.residual);
b.2 |= character;
}
None => best.push((m.face, m.residual, character)),
}
}
for (face, residual) in best {
for (face, residual, character) in best {
match ranked.iter_mut().find(|r| r.face.id() == face.id()) {
Some(r) => {
r.matched += 1;
r.residual += residual;
r.character |= character;
}
None => ranked.push(Ranked { face, matched: 1, residual }),
None => ranked.push(Ranked { face, matched: 1, residual, character }),
}
}
}
// A font whose glyphs match the shapes only as combining marks would retype none of them, as
// type.retype starts no line with a mark: it is not listed.
ranked.retain(|r| r.character);
ranked.sort_by(|a, b| {
b.matched
.cmp(&a.matched)
@@ -106,6 +106,21 @@ fn shapes_that_are_no_glyph_list_no_font() {
assert!(s.execute("type.retypeFonts", &json!({})).is_err());
}
#[test]
fn a_font_that_matches_only_combining_marks_is_not_listed() {
let mut s = session();
// A lone combining mark (a drawn dot, bar or ring is the same shape): type.retype keeps it.
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "\u{312}", "size": 40, "font": "Source Sans 3", "style": "Regular"}));
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = query(&mut s, json!({}), bundled());
assert_eq!(r, json!({"fonts": [], "shapes": 1, "more": false, "truncated": false}));
// After a base, the mark counts with it.
let g = outlined(&mut s, json!({"x": 40, "y": 200, "text": "x\u{312}", "size": 40, "font": "Source Sans 3", "style": "Regular"}));
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = query(&mut s, json!({}), bundled());
assert!(names(&r).contains(&("Source Sans 3".into(), "Regular".into(), 2)), "{r}");
}
#[test]
fn shapes_past_the_limits_are_reported_as_left_out() {
let mut s = session();
+478 -5
View File
@@ -97,6 +97,165 @@ fn a_drawn_shape_is_reported_and_left_alone() {
assert!(s.doc().unwrap().doc == before);
}
#[test]
fn a_mark_in_one_font_starts_its_line_as_another_fonts_character() {
use vectorcraft_text::test_fonts::{SPACING_COMMA_FAMILY, spacing_comma_font};
// The comma below of Source Sans 3 is only marks there, and a modifier letter in this face.
vectorcraft_text::FontDb::global().add_font(spacing_comma_font().unwrap());
let mut s = session();
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "\u{326}", "size": 40, "font": "Source Sans 3", "style": "Regular"}));
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
assert_eq!(r["texts"], json!(["\u{2bb}"]), "{r}");
assert_eq!(r["fonts"][0]["family"], json!(SPACING_COMMA_FAMILY), "{r}");
// After a base, it joins the line as the mark; moved off its base, the split leaves it first,
// and it becomes the other face's character there.
let g = outlined(&mut s, json!({"x": 40, "y": 200, "text": "x\u{326}yz", "size": 40, "font": "Source Sans 3", "style": "Regular"}));
let mark = s.doc().unwrap().doc.children(Some(NodeId(g))).unwrap()[1].id.0;
s.execute("select.set", &json!({"ids": [mark]})).unwrap();
s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
assert_eq!((&r["texts"], &r["unmatched"]), (&json!(["x", "\u{2bb}", "yz"]), &json!([])), "{r}");
assert_eq!(r["fonts"][1]["family"], json!(SPACING_COMMA_FAMILY), "{r}");
}
#[test]
fn a_combining_mark_starts_no_line() {
// A combining mark on its own (a drawn dot, bar or ring is the same shape) stays an outline.
let mut s = session();
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "\u{312}", "size": 40, "font": "Source Sans 3", "style": "Regular"}));
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let before = s.doc().unwrap().doc.clone();
let e = s.execute("type.retype", &json!({})).unwrap_err().to_string();
assert!(e.contains("no selected shape matches"), "{e}");
assert!(s.doc().unwrap().doc == before, "nothing changes");
// A shape that is both a mark (tilde below) and a character (small tilde) starts its line as
// the character.
let g = outlined(&mut s, json!({"x": 140, "y": 100, "text": "\u{303}", "size": 40, "font": "Source Sans 3", "style": "Regular"}));
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
assert_eq!(r["texts"], json!(["\u{2dc}"]), "{r}");
// A glyph after it does not turn it back into the mark (diaeresis below, diaeresis).
let g = outlined(&mut s, json!({"x": 240, "y": 100, "text": "\u{324}a", "size": 40, "font": "Source Sans 3", "style": "Regular"}));
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
assert_eq!((&r["texts"], &r["unmatched"]), (&json!(["\u{a8}", "a"]), &json!([])), "{r}");
// First on a line, the mark stays an outline and the glyphs after it are retyped.
let g = outlined(&mut s, json!({"x": 40, "y": 200, "text": "\u{312}ab", "size": 40, "font": "Source Sans 3", "style": "Regular"}));
let mark = s.doc().unwrap().doc.children(Some(NodeId(g))).unwrap()[0].id.0;
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
assert_eq!(r["texts"], json!(["ab"]), "{r}");
assert_eq!(r["unmatched"], json!([mark]));
// After a base, the mark is retyped with it.
let g = outlined(&mut s, json!({"x": 40, "y": 300, "text": "x\u{323}", "size": 40, "font": "Source Sans 3", "style": "Regular"}));
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
assert_eq!(r["texts"], json!(["x\u{323}"]), "{r}");
// Moved off its base, the mark is where the line splits, and the part after the split does
// not start with it either.
let g = outlined(&mut s, json!({"x": 300, "y": 200, "text": "x\u{312}yz", "size": 40, "font": "Source Sans 3", "style": "Regular"}));
let mark = s.doc().unwrap().doc.children(Some(NodeId(g))).unwrap()[1].id.0;
s.execute("select.set", &json!({"ids": [mark]})).unwrap();
s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
assert_eq!((&r["texts"], &r["unmatched"]), (&json!(["x", "yz"]), &json!([mark])), "{r}");
// A mark that is also another character (dot below, dot above) becomes that character there.
let g = outlined(&mut s, json!({"x": 300, "y": 120, "text": "x\u{323}yz", "size": 40, "font": "Source Sans 3", "style": "Regular"}));
let mark = s.doc().unwrap().doc.children(Some(NodeId(g))).unwrap()[1].id.0;
s.execute("select.set", &json!({"ids": [mark]})).unwrap();
s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
assert_eq!((&r["texts"], &r["unmatched"]), (&json!(["x", "\u{2d9}", "yz"]), &json!([])), "{r}");
// Tracked, the part after the mark keeps the tracking its own glyphs are spaced by.
let id = s
.execute("text.create", &json!({"x": 40, "y": 60, "text": "x\u{312}yzw", "size": 40, "font": "Source Sans 3", "style": "Regular"}))
.unwrap()["id"]
.as_u64()
.unwrap();
s.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": 5, "tracking": 50})).unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
let mark = s.doc().unwrap().doc.children(Some(NodeId(g))).unwrap()[1].id.0;
s.execute("select.set", &json!({"ids": [mark]})).unwrap();
s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
assert_eq!((&r["texts"], &r["unmatched"]), (&json!(["x", "yzw"]), &json!([mark])), "{r}");
assert_eq!(r["fonts"][1]["tracking"], json!(50.0), "{r}");
// A one-contour glyph after a mark that stays an outline (a bar, then a dot) is alone, and
// beside other shapes it stays an outline too.
let dot = outlined(&mut s, json!({"x": 300, "y": 300, "text": "\u{312}.", "size": 40, "font": "Source Sans 3", "style": "Regular"}));
let mut pair: Vec<u64> = s.doc().unwrap().doc.children(Some(NodeId(dot))).unwrap().iter().map(|n| n.id.0).collect();
pair.sort_unstable();
let word = outlined(&mut s, json!({"x": 40, "y": 380, "text": "ab", "size": 40, "font": "Source Sans 3", "style": "Regular"}));
s.execute("select.set", &json!({"ids": [dot, word]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
assert_eq!(r["texts"], json!(["ab"]), "{r}");
let mut left: Vec<u64> = r["unmatched"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();
left.sort_unstable();
assert_eq!(left, pair, "{r}");
}
#[test]
fn marks_of_one_compound_path_each_become_their_own_character() {
// Two marks that are also other characters (dot below, dot above; tilde, small tilde), moved
// off their base and made one compound path: each becomes the character its own shape is.
let mut s = session();
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "x\u{323}\u{303}yz", "size": 40, "font": "Source Sans 3", "style": "Regular"}));
let kids: Vec<u64> = s.doc().unwrap().doc.children(Some(NodeId(g))).unwrap().iter().map(|n| n.id.0).collect();
assert_eq!(kids.len(), 5);
s.execute("select.set", &json!({"ids": [kids[1], kids[2]]})).unwrap();
s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap();
s.execute("object.compoundPath.make", &json!({})).unwrap();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
assert_eq!(r["unmatched"], json!([]), "{r}");
let texts: Vec<&str> = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap()).collect();
let mut marks = texts.get(1..3).unwrap_or_default().to_vec();
marks.sort_unstable();
assert_eq!((texts.first(), texts.get(3), texts.len()), (Some(&"x"), Some(&"yz"), 4), "{r}");
assert_eq!(marks, ["\u{2d9}", "\u{2dc}"], "{r}");
}
#[test]
fn marks_first_after_a_split_leave_other_lines_their_tracking() {
// Twenty marks moved off their base, each one first on its line in turn, do not use up the
// measures of the other lines: the tracked line retyped with them keeps its tracking.
let mut s = session();
let marks = outlined(
&mut s,
json!({"x": 40, "y": 100, "text": format!("x{}a", "\u{312}".repeat(20)), "size": 40, "font": "Source Sans 3", "style": "Regular"}),
);
let mut moved: Vec<u64> = s.doc().unwrap().doc.children(Some(NodeId(marks))).unwrap().iter().map(|n| n.id.0).collect();
assert_eq!(moved.len(), 22);
moved = moved[1..21].to_vec();
let id = s
.execute("text.create", &json!({"x": 40, "y": 300, "text": "x\u{312}yzw", "size": 40, "font": "Source Sans 3", "style": "Regular"}))
.unwrap()["id"]
.as_u64()
.unwrap();
s.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": 5, "tracking": 50})).unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
let tracked = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
let mark = s.doc().unwrap().doc.children(Some(NodeId(tracked))).unwrap()[1].id.0;
moved.push(mark);
s.execute("select.set", &json!({"ids": moved})).unwrap();
s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap();
s.execute("select.set", &json!({"ids": [marks, tracked]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
let texts = r["texts"].as_array().unwrap();
let at = texts.iter().position(|t| t == "yzw").unwrap_or_else(|| panic!("yzw in {r}"));
assert_eq!(r["fonts"][at]["tracking"], json!(50.0), "{r}");
let mut left: Vec<u64> = r["unmatched"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();
left.sort_unstable();
moved.sort_unstable();
assert_eq!(left, moved, "{r}");
}
#[test]
fn mixed_selection_retypes_the_glyphs_and_keeps_the_rest() {
let mut s = session();
@@ -121,7 +280,7 @@ fn two_words_keep_their_space() {
#[test]
fn craft_fonts_glyphs_retype_too() {
let Some(f) = vectorcraft_text::CRAFT_FONTS.iter().find(|f| f.is_japanese()) else {
let Some(f) = vectorcraft_text::CRAFT_FONTS.iter().find(|f| f.has_script("Jpan")) else {
eprintln!("skipped: built without craft-fonts (set CRAFT_FONTS_DIR to a craft-fonts checkout to run it)");
return;
};
@@ -1385,6 +1544,34 @@ fn glyphs_side_by_side_in_an_even_odd_compound_still_become_type() {
assert_eq!(r["texts"], json!(["oo"]), "{r}");
}
#[test]
fn a_glyph_with_only_some_contours_turned_in_an_even_odd_compound_still_becomes_type() {
// An even-odd compound paints the same whichever way its contours run, so an o's counter may
// run the same way as its outer contour: neither the part as it is nor all its contours turned
// is the glyph. Filled by the nonzero rule, the same contours paint the o's counter, and the
// compound stays an outline.
for turned in [1usize, 2] {
let mut s = session();
let c = one_compound(&mut s, "do");
// One path per contour: the d's two, then the o's two.
let paths = children_of(&s, c);
assert_eq!(paths.len(), 4, "a d and an o are two contours each");
let p = paths[paths.len() - turned];
s.edit("test", |d, _| {
let data = d.node_mut(NodeId(p)).unwrap().path_data_mut().unwrap();
*data = vectorcraft_geom::PathData::from_bezpath(&data.to_bezpath().reverse_subpaths());
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [c]})).unwrap();
assert!(s.execute("type.retype", &json!({})).is_err(), "nonzero, contour {turned} turned paints the counter");
s.execute("path.setFillRule", &json!({"rule": "evenOdd", "ids": [c]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
assert_eq!(r["texts"], json!(["do"]), "contour {turned} turned: {r}");
assert_eq!(r["unmatched"], json!([]), "{r}");
}
}
#[test]
fn a_compound_whose_glyph_stays_an_outline_keeps_its_other_glyphs_too() {
let mut s = session();
@@ -1707,13 +1894,19 @@ fn slight_tracking_without_spaces_is_kept() {
/// The lines Retype reads from the outlines in group `g` (all in the face of its first glyph's
/// first match), before their tracking is measured and their layout checked.
fn lines_in(s: &Session, g: u64) -> Vec<super::Line> {
lines_in_family(s, g, None)
}
/// [`lines_in`] with the face of the first glyph's match in `family` when given.
fn lines_in_family(s: &Session, g: u64, family: Option<&str>) -> Vec<super::Line> {
let d = &s.doc().unwrap().doc;
let (mut barrier, mut truncated, mut pieces) = (true, false, vec![]);
super::collect(d.node(NodeId(g)).unwrap(), d.parent_of(NodeId(g)), 0, &mut barrier, &mut truncated, &mut pieces);
let db = vectorcraft_text::FontDb::global();
let wanted = pieces.iter().filter_map(|pc| vectorcraft_text::retype::shape_key(&pc.path)).collect();
let index = super::RetypeIndex::build(db, super::candidate_faces(db, d, &[]), &wanted);
let face = index.matches(&pieces[0].path)[0].face.id();
let first = index.matches(&pieces[0].path);
let face = first.iter().find(|m| family.is_none_or(|f| m.face.family == f)).unwrap_or(&first[0]).face.id();
let mut lines: Vec<super::Line> = vec![];
for pc in &pieces {
let cands: Vec<_> = index.matches(&pc.path).into_iter().filter(|m| m.face.id() == face).collect();
@@ -1743,7 +1936,7 @@ fn the_glyphs_after_one_type_cannot_draw_keep_their_tracking() {
l.matches[bad].gid = other;
let bad_id = l.pieces[bad];
let mut unmatched = vec![];
let out = super::verified(vec![l], false, &mut unmatched);
let out = super::verified(vec![l], false, &Default::default(), &mut unmatched);
assert_eq!(unmatched, vec![bad_id], "{bad}");
let last = out.last().unwrap();
assert_eq!(last.pieces.len(), 5 - bad, "{bad}: {:?}", out.iter().map(|l| (l.pieces.len(), l.tracking)).collect::<Vec<_>>());
@@ -1795,7 +1988,7 @@ fn the_rest_of_a_widely_tracked_line_keeps_its_tracking_after_a_split() {
assert_eq!(l.tracking, 8000.0);
l.matches[0].gid += 1;
let mut unmatched = vec![];
let out = super::verified(vec![l], false, &mut unmatched);
let out = super::verified(vec![l], false, &Default::default(), &mut unmatched);
assert_eq!(unmatched.len(), 1);
let last = out.last().unwrap();
assert_eq!((last.pieces.len(), last.tracking), (99, 8000.0), "{:?}", out.iter().map(|l| (l.pieces.len(), l.tracking)).collect::<Vec<_>>());
@@ -1817,12 +2010,292 @@ fn glyphs_type_cannot_draw_do_not_use_up_the_tracking_measure() {
m.gid += 1;
}
let mut unmatched = vec![];
let out = super::verified(vec![l], false, &mut unmatched);
let out = super::verified(vec![l], false, &Default::default(), &mut unmatched);
assert_eq!(unmatched.len(), 5);
let last = out.last().unwrap();
assert_eq!((last.pieces.len(), last.tracking), (95, 300.0), "{:?}", out.iter().map(|l| (l.pieces.len(), l.tracking)).collect::<Vec<_>>());
}
#[test]
fn irregular_gaps_before_a_long_tracked_run_do_not_split_the_run() {
// The first eight gaps each take another tracking, and the 92 glyphs after them are tracked
// 300: measuring the rest after each irregular gap must not use up the budget the run needs,
// so the run is one object with its tracking.
let mut s = session();
let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": "i".repeat(100), "size": 6})).unwrap()["id"].as_u64().unwrap();
s.execute("text.setRangeStyle", &json!({"id": id, "tracking": 300})).unwrap();
for (i, t) in [50, 170, 90, 230, 130, 410, 20, 520].into_iter().enumerate() {
s.execute("text.setRangeStyle", &json!({"id": id, "start": i, "end": i + 1, "tracking": t})).unwrap();
}
s.execute("select.set", &json!({"ids": [id]})).unwrap();
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
let texts: Vec<&str> = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap()).collect();
assert_eq!(texts.concat(), "i".repeat(100), "{r}");
assert_eq!(r["unmatched"], json!([]));
assert!(texts.len() <= 9, "at most one object per irregular gap, then the run: {texts:?}");
let run = text_of(&s, r["ids"].as_array().unwrap().last().unwrap().as_u64().unwrap());
assert_eq!(run.plain_text().chars().count(), 92, "{texts:?}");
assert!(run.runs.iter().all(|r| r.style.tracking == 300.0), "{texts:?}");
}
#[test]
fn a_long_run_after_a_split_keeps_the_fraction_of_its_tracking() {
// Tracking 300.04 reads as 300 over the 32 glyphs measured, but 400 glyphs apart the two
// differ by more than the tolerance: the run after the irregular gaps keeps 300.04 and stays
// one object.
let mut s = session();
let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": "i".repeat(400), "size": 6})).unwrap()["id"].as_u64().unwrap();
s.execute("text.setRangeStyle", &json!({"id": id, "tracking": 300.04})).unwrap();
for (i, t) in [50, 170, 90, 230, 130, 410, 20, 520].into_iter().enumerate() {
s.execute("text.setRangeStyle", &json!({"id": id, "start": i, "end": i + 1, "tracking": t})).unwrap();
}
s.execute("select.set", &json!({"ids": [id]})).unwrap();
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
let texts: Vec<&str> = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap()).collect();
assert_eq!(texts.concat(), "i".repeat(400), "{r}");
assert!(texts.len() <= 9, "at most one object per irregular gap, then the run: {texts:?}");
let run = text_of(&s, r["ids"].as_array().unwrap().last().unwrap().as_u64().unwrap());
assert_eq!(run.plain_text().chars().count(), 392, "{texts:?}");
assert!(run.runs.iter().all(|r| near(r.style.tracking, 300.04, 1e-3)), "{texts:?}");
}
#[test]
fn a_long_spaced_run_after_a_split_keeps_the_fraction_of_its_tracking() {
// Tracking 300.04 read as 300 moves the last of the 192 glyphs after the irregular gaps by less
// than the tolerance, counting the glyphs alone, but the word spaces between them take the
// tracking too: the run keeps 300.04 and stays one object.
let mut s = session();
let text = vec!["ii"; 100].join(" ");
let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": text, "size": 6})).unwrap()["id"].as_u64().unwrap();
s.execute("text.setRangeStyle", &json!({"id": id, "tracking": 300.04})).unwrap();
// The first eight glyphs, at 0, 1, 3, 4, 6, 7, 9 and 10 (a space after each two).
for (i, t) in [50, 170, 90, 230, 130, 410, 20, 520].into_iter().enumerate() {
let at = i + i / 2;
s.execute("text.setRangeStyle", &json!({"id": id, "start": at, "end": at + 1, "tracking": t})).unwrap();
}
s.execute("select.set", &json!({"ids": [id]})).unwrap();
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
let texts: Vec<&str> = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap()).collect();
assert_eq!(texts.concat().replace(' ', ""), "i".repeat(200), "{r}");
assert!(texts.len() <= 9, "at most one object per irregular gap, then the run: {texts:?}");
let run = text_of(&s, r["ids"].as_array().unwrap().last().unwrap().as_u64().unwrap());
assert_eq!(run.plain_text().chars().filter(|c| *c == 'i').count(), 192, "{texts:?}");
assert!(run.runs.iter().all(|r| near(r.style.tracking, 300.04, 1e-3)), "{texts:?}");
}
#[test]
fn a_long_run_after_a_split_keeps_a_tracking_under_one_unit_that_adds_up() {
// Tracking 0.2 moves none of the 32 glyphs measured by more than the tolerance, but moves the
// glyphs 399 places on: the rest after a split keeps it and stays one object.
let mut s = session();
let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": "M".repeat(400), "size": 6})).unwrap()["id"].as_u64().unwrap();
s.execute("text.setRangeStyle", &json!({"id": id, "tracking": 0.2})).unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
let mut budget = 100_000;
let mut l = lines_in(&s, g).into_iter().next().unwrap().tracked(false, &mut budget);
assert!(near(l.tracking, 0.2, 0.01), "{}", l.tracking);
l.matches[0].gid += 1;
let mut unmatched = vec![];
let out = super::verified(vec![l], false, &Default::default(), &mut unmatched);
assert_eq!(unmatched.len(), 1);
let last = out.last().unwrap();
assert!(last.pieces.len() == 399 && near(last.tracking, 0.2, 0.01), "{:?}", out.iter().map(|l| (l.pieces.len(), l.tracking)).collect::<Vec<_>>());
}
#[test]
fn a_long_rest_tracked_past_a_negative_space_advance_keeps_its_word_spaces_after_a_split() {
// Tracking tighter than the space is wide, by one half to one and a half spaces more, gives the
// space a negative advance; the word space past the glyphs the tracking is measured from is
// still read.
for (unit, times) in
[("AV", 1.5), ("AV", 1.7), ("TA", 1.5), ("TA", 1.7), ("To", 1.5), ("To", 1.7), ("MM", 1.5), ("MM", 1.7), ("Wo", 1.6), ("Wo", 1.8)]
{
let mut s = session();
let text = format!("{} {}", unit.repeat(20), unit.repeat(5));
let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": text, "size": 10})).unwrap()["id"].as_u64().unwrap();
let probe = s.execute("text.create", &json!({"x": 10, "y": 200, "text": unit, "size": 10})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [probe]})).unwrap();
let pg = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
let pl = lines_in(&s, pg).into_iter().next().unwrap();
let tracking = -(super::space_advance(&pl.face) / pl.face.units_per_em() * 1000.0 * times).round();
s.execute("text.setRangeStyle", &json!({"id": id, "tracking": tracking})).unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
let mut budget = 100_000;
let mut l = lines_in(&s, g).into_iter().next().unwrap().tracked(false, &mut budget);
assert_eq!((l.text.as_str(), l.tracking), (text.as_str(), tracking), "{times}");
l.matches[0].gid += 1;
let mut unmatched = vec![];
let out = super::verified(vec![l], false, &Default::default(), &mut unmatched);
assert_eq!(unmatched.len(), 1, "{times}");
let texts: Vec<(&str, f64)> = out.iter().map(|l| (l.text.as_str(), l.tracking)).collect();
assert_eq!(texts, vec![(&text[1..], tracking)], "{times}");
}
}
#[test]
fn a_long_rest_with_a_positive_pair_kerning_that_matches_a_space_gains_no_space_after_a_split() {
// The font adds 120 units to each i before an i. Tracking that leaves a space 120 wide makes the
// gap a kerned pair leaves the same as the gap a word space leaves; the joined reading wins the
// tie, as it does for the glyphs the tracking is measured from.
use vectorcraft_text::test_fonts::{POSITIVE_KERNING_FAMILY, POSITIVE_KERNING_UNITS, positive_kerning_font};
vectorcraft_text::FontDb::global().add_font(positive_kerning_font().unwrap());
let mut s = session();
let text = "i".repeat(60);
let probe = s.execute("text.create", &json!({"x": 10, "y": 200, "text": "i", "size": 10, "font": POSITIVE_KERNING_FAMILY})).unwrap()["id"]
.as_u64()
.unwrap();
s.execute("select.set", &json!({"ids": [probe]})).unwrap();
let pg = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
let pl = lines_in_family(&s, pg, Some(POSITIVE_KERNING_FAMILY)).into_iter().next().unwrap();
let space = super::space_advance(&pl.face) / pl.face.units_per_em() * 1000.0;
let tracking = (f64::from(POSITIVE_KERNING_UNITS) - space).round();
assert!(space + tracking >= space / 2.0, "the space must stay at least half its width: {space} {tracking}");
let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": text, "size": 10, "font": POSITIVE_KERNING_FAMILY})).unwrap()["id"]
.as_u64()
.unwrap();
s.execute("text.setRangeStyle", &json!({"id": id, "tracking": tracking})).unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
let mut budget = 100_000;
let mut l = lines_in_family(&s, g, Some(POSITIVE_KERNING_FAMILY)).into_iter().next().unwrap().tracked(false, &mut budget);
assert_eq!((l.text.as_str(), l.tracking), (text.as_str(), tracking));
l.matches[0].gid += 1;
let mut unmatched = vec![];
let out = super::verified(vec![l], false, &Default::default(), &mut unmatched);
assert_eq!(unmatched.len(), 1);
let texts: Vec<(&str, f64)> = out.iter().map(|l| (l.text.as_str(), l.tracking)).collect();
assert_eq!(texts, vec![(&text[1..], tracking)]);
}
#[test]
fn a_long_rest_with_a_positive_pair_kerning_that_matches_a_space_gains_no_space_when_the_budget_runs_short() {
// As above, with a measuring budget that covers the tracking's measure but not the layout of
// the pairs after the glyphs measured: those pairs still read no space.
use vectorcraft_text::test_fonts::{POSITIVE_KERNING_FAMILY, POSITIVE_KERNING_UNITS, positive_kerning_font};
vectorcraft_text::FontDb::global().add_font(positive_kerning_font().unwrap());
let mut s = session();
let text = "i".repeat(60);
let probe = s.execute("text.create", &json!({"x": 10, "y": 200, "text": "i", "size": 10, "font": POSITIVE_KERNING_FAMILY})).unwrap()["id"]
.as_u64()
.unwrap();
s.execute("select.set", &json!({"ids": [probe]})).unwrap();
let pg = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
let pl = lines_in_family(&s, pg, Some(POSITIVE_KERNING_FAMILY)).into_iter().next().unwrap();
let space = super::space_advance(&pl.face) / pl.face.units_per_em() * 1000.0;
let tracking = (f64::from(POSITIVE_KERNING_UNITS) - space).round();
let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": text, "size": 10, "font": POSITIVE_KERNING_FAMILY})).unwrap()["id"]
.as_u64()
.unwrap();
s.execute("text.setRangeStyle", &json!({"id": id, "tracking": tracking})).unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
let mut budget = 100_000;
let l = lines_in_family(&s, g, Some(POSITIVE_KERNING_FAMILY)).into_iter().next().unwrap().tracked(false, &mut budget);
assert_eq!((l.text.as_str(), l.tracking), (text.as_str(), tracking));
// What measuring the tracking of the rest's first 32 glyphs takes.
let span = super::MEASURE_SPAN;
let mut measure = 100_000;
let measured = l.respaced(1, 1 + span, 0.0).unwrap().tracked_reaching(false, &mut measure, 59);
assert_eq!(measured.tracking, tracking);
let measure = 100_000 - measure;
// The pairs after the glyphs measured take three characters each.
let pairs = (60 - 1 - span + 1) * 3;
for short in (0..pairs).step_by(7) {
let mut track_budget = (span + measure + short).max(span * 6);
let (mut glyphs, mut remeasured) = (100_000, 100_000);
let r = super::rest_after_split(&l, 1, false, &mut glyphs, &mut remeasured, &mut track_budget).unwrap();
assert_eq!(r.text, text[1..], "a budget {short} short of the pairs");
}
}
#[test]
fn a_word_space_after_a_glyph_kerned_against_it_reads_as_one_space_past_the_glyphs_measured() {
// The font adds 130 units to an i before a space, so the gap before the next glyph is more than
// one and a half spaces wide; the distance the pair with one space between them is laid out at
// fits one space.
use vectorcraft_text::test_fonts::{SPACE_KERNING_FAMILY, space_kerning_font};
vectorcraft_text::FontDb::global().add_font(space_kerning_font().unwrap());
let mut s = session();
let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": "ii ii", "size": 10, "font": SPACE_KERNING_FAMILY})).unwrap()["id"]
.as_u64()
.unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
let l = lines_in_family(&s, g, Some(SPACE_KERNING_FAMILY)).into_iter().next().unwrap();
assert_eq!(l.pieces.len(), 4);
let mut r = l.respaced(0, 2, 0.0).unwrap();
let mut budget = 1_000;
let steps = r.pair_steps(&l.matches[1..], false, &mut budget).unwrap();
for (j, (id, m)) in l.pieces.iter().zip(&l.matches).skip(2).enumerate() {
r.push_joined(*id, m, steps.get(j).copied());
}
assert_eq!(r.text, "ii ii");
}
#[test]
fn a_word_space_after_a_glyph_kerned_toward_it_is_kept_past_the_glyphs_measured() {
// The font takes 130 units off an i before a space, so the gap before the next glyph is under
// half a space wide; the distance the pair with one space between them is laid out at fits it.
use vectorcraft_text::test_fonts::{SPACE_NARROWING_FAMILY, space_narrowing_font};
vectorcraft_text::FontDb::global().add_font(space_narrowing_font().unwrap());
let mut s = session();
let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": "ii ii", "size": 10, "font": SPACE_NARROWING_FAMILY})).unwrap()["id"]
.as_u64()
.unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
let l = lines_in_family(&s, g, Some(SPACE_NARROWING_FAMILY)).into_iter().next().unwrap();
assert_eq!(l.pieces.len(), 4);
let mut r = l.respaced(0, 2, 0.0).unwrap();
let mut budget = 1_000;
let steps = r.pair_steps(&l.matches[1..], false, &mut budget).unwrap();
for (j, (id, m)) in l.pieces.iter().zip(&l.matches).skip(2).enumerate() {
r.push_joined(*id, m, steps.get(j).copied());
}
assert_eq!(r.text, "ii ii");
}
#[test]
fn a_long_tightly_tracked_rest_keeps_its_word_spaces_after_a_split() {
// Tracking as tight as a space is wide leaves the space no advance, and only the kerning it
// breaks shows it is there: the word space past the glyphs the rest's tracking is measured
// from is read by that measure too.
let mut s = session();
let text = format!("{} {}", "AV".repeat(20), "AV".repeat(5));
let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": text, "size": 10})).unwrap()["id"].as_u64().unwrap();
let face = text_of(&s, id).runs[0].style.font_family.clone();
let probe = s.execute("text.create", &json!({"x": 10, "y": 200, "text": "AV", "size": 10})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [probe]})).unwrap();
let pg = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
let pl = lines_in(&s, pg).into_iter().next().unwrap();
assert_eq!(pl.face.family, face);
let tracking = -(super::space_advance(&pl.face) / pl.face.units_per_em() * 1000.0).round();
s.execute("text.setRangeStyle", &json!({"id": id, "tracking": tracking})).unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
let mut budget = 100_000;
let mut l = lines_in(&s, g).into_iter().next().unwrap().tracked(false, &mut budget);
assert_eq!((l.text.as_str(), l.tracking), (text.as_str(), tracking));
l.matches[0].gid += 1;
let mut unmatched = vec![];
let out = super::verified(vec![l], false, &Default::default(), &mut unmatched);
assert_eq!(unmatched.len(), 1);
let texts: Vec<(&str, f64)> = out.iter().map(|l| (l.text.as_str(), l.tracking)).collect();
assert_eq!(texts, vec![(&text[1..], tracking)]);
}
#[test]
fn tightly_tracked_type_keeps_its_tracking() {
// Tracking tighter than a space: the space moves the next glyph back.
+4 -3
View File
@@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Run Script",
[],
None,
"{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that l Line truncated
"{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that l Line truncated
always,
run
),
@@ -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) {
+11 -8
View File
@@ -11,7 +11,7 @@ use vectorcraft_geom::PathData;
use vectorcraft_tools::builder::is_live_paint;
use super::appearance::{ItemTarget, edit_items, item_target};
use super::paint::{live_paint_covered, live_paint_parts_skipped, painted};
use super::paint::{live_paint_parts_skipped, painted};
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, ok, str_param};
use crate::DocState;
use crate::inspect::{ALIGNS, CAPS, JOINS, StrokeMixed, node_stroke, scale_layer};
@@ -23,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Stroke Options",
["Window", "Stroke"],
None,
"{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path, stop?}} (a custom head with its art, as document.inspect reports one; stop: where the stroke ends under the head, in head units back from the tip, 0..64 (otherwise, or without one, halfway along the head); refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, target?: \"object\"|\"contents\", 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)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone; a Live Paint group takes them on its edges only. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take; on a graph's axis line, tick mark or radar ring, the graph stores the paint, weight, opacity and blend mode of its topmost visible fill and stroke rows that the edit changes, and the weight it writes to the topmost visible stroke, for every line of its kind, and not its caps, joins, dashes, alignment or arrowheads. 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), only the stroke for new art changes (the bucket paints edges with its color and weight) → {objects: how many objects took the stroke options}",
"{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path, stop?}} (a custom head with its art, as document.inspect reports one; stop: where the stroke ends under the head, in head units back from the tip, 0..64 (otherwise, or without one, halfway along the head); refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, defaultsOnly?: bool, target?: \"object\"|\"contents\", 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)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone; a Live Paint group takes them on its edges only. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take; on a graph's axis line, tick mark or radar ring, the graph stores the paint, weight, opacity and blend mode of its topmost visible fill and stroke rows that the edit changes, and the weight it writes to the topmost visible stroke, for every line of its kind, and not its caps, joins, dashes, alignment or arrowheads. 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 (refused with ids, id or item), only the stroke for new art changes (the bucket paints edges with its color and weight) → {objects: how many objects took the stroke options}",
has_doc,
stroke_set
),
@@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Stroke Weight Up",
[],
Some("Cmd+Alt+."),
"{ids?|id?} raise each selected stroke's weight by one step of Units › Stroke (a quarter unit below one unit, then whole units; up to 1000 pt), each from its own weight: the selected objects' active or top stroke, type's stroked characters; objects without a stroke, and a Live Paint group's faces, are left alone. With nothing selected (and no ids), the weight of the next object drawn, and so while the Live Paint Bucket is the active tool and no ids or id are given (a null one counts as none). On a path directly in a graph series, the graph also stores the new weight of the topmost visible stroke, and on a graph label the new weight of its characters' stroke or its stroke row 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) → {objects}",
"{ids?|id?, defaultsOnly?: bool (as stroke.set)} raise each selected stroke's weight by one step of Units › Stroke (a quarter unit below one unit, then whole units; up to 1000 pt), each from its own weight: the selected objects' active or top stroke, type's stroked characters; objects without a stroke, and a Live Paint group's faces, are left alone. With nothing selected (and no ids), the weight of the next object drawn, and so while the Live Paint Bucket is the active tool and no ids or id are given (a null one counts as none), or `defaultsOnly: true` is given. On a path directly in a graph series, the graph also stores the new weight of the topmost visible stroke, and on a graph label the new weight of its characters' stroke or its stroke row 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) → {objects}",
has_doc,
|s, p| stroke_step(s, p, true)
),
@@ -41,7 +41,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Stroke Weight Down",
[],
Some("Cmd+Alt+,"),
"{ids?|id?} lower each selected stroke's weight by one step, as stroke.weightUp raises it, down to a quarter unit (a thinner weight is kept) → {objects}",
"{ids?|id?, defaultsOnly?: bool (as stroke.set)} lower each selected stroke's weight by one step, as stroke.weightUp raises it, down to a quarter unit (a thinner weight is kept) → {objects}",
has_doc,
|s, p| stroke_step(s, p, false)
),
@@ -50,7 +50,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Stroke Options",
[],
None,
"{arrowScale?: [start %, end %], swapArrows?: bool, flipProfile?: \"along\"|\"across\", brush?: name|null, item?: stroke item index|null, aligned?: bool (as stroke.set), ids?|id?, target?: \"object\"|\"contents\"} Stroke panel extras (with nothing selected, all but brush set up the next object drawn, and so while the Live Paint Bucket is the active tool and no ids, id, item or brush are given, a null ids or id counting as none; without item, a Live Paint group's edges take them and its faces are left alone)",
"{arrowScale?: [start %, end %], swapArrows?: bool, flipProfile?: \"along\"|\"across\", brush?: name|null, item?: stroke item index|null, aligned?: bool (as stroke.set), ids?|id?, defaultsOnly?: bool (as stroke.set; refused with brush), target?: \"object\"|\"contents\"} Stroke panel extras (with nothing selected, all but brush set up the next object drawn, and so while the Live Paint Bucket is the active tool, or with `defaultsOnly: true`, and no ids, id, item or brush are given, a null ids or id counting as none; without item, a Live Paint group's edges take them and its faces are left alone)",
has_doc,
stroke_advanced
),
@@ -465,7 +465,7 @@ impl Session {
// A Live Paint group without edges shows the next selected object's stroke; any other object
// without a painted object shows none. A face or edge selected with its Live Paint group counts
// with the group, wherever it is in the selection.
let covered = live_paint_covered(&st.doc, &st.selection.objects);
let covered = st.selection_live_paint_covered(&st.selection.objects);
for id in st.selection.objects.iter().filter(|id| !covered.contains(*id)) {
let Some(n) = st.doc.node(*id) else { continue };
let mut nodes = vec![];
@@ -540,7 +540,7 @@ impl DocState {
} else {
let selected: Vec<&Node> = self.selection.objects.iter().filter_map(|id| self.doc.node(*id)).collect();
// The faces and edges of the selected Live Paint groups: selected as well, they count with their group's.
let covered = live_paint_covered(&self.doc, &self.selection.objects);
let covered = self.selection_live_paint_covered(&self.selection.objects);
for n in selected.into_iter().filter(|n| !covered.contains(&n.id)) {
painted(n, true, true, &mut nodes);
}
@@ -618,7 +618,10 @@ fn stroke_advanced(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(C, "nothing to change"));
}
// As stroke.set: the stroke the Live Paint Bucket paints with changes; the selection keeps its own.
// A brush still goes to the selection.
// A brush still goes to the selection, and new art has no brush for `defaultsOnly` to set.
if brush.is_some() && super::switch_or(p, "defaultsOnly", false, C)? {
return Err(bad(C, "`defaultsOnly` cannot be combined with `brush`"));
}
let bucket_p = if brush.is_none() { super::paint::bucket_color_params(s, p, C)? } else { None };
let bucket = bucket_p.is_some();
let p = bucket_p.as_ref().unwrap_or(p);
+8 -7
View File
@@ -329,14 +329,15 @@ impl Session {
let g = st.doc.graphic_style_by_id(n.extras().graphic_style?)?;
Some((g, in_sync(n, g)))
}
}
/// A copy of `n` with style `g` applied as `graphicStyle.apply` applies it (Override Character
/// Color as set): the Graphic Styles panel's previews.
pub fn styled(&self, n: &Node, g: &GraphicStyle) -> Node {
let mut n = n.clone();
style_node(&mut n, g, &mut None, self.prefs.override_char_color);
n
}
/// A copy of `n` with style `g` applied as `graphicStyle.apply` applies it, type's characters too
/// with `override_char_color` (the preference Override Character Color): the Graphic Styles
/// panel's previews.
pub fn styled_node(n: &Node, g: &GraphicStyle, override_char_color: bool) -> Node {
let mut n = n.clone();
style_node(&mut n, g, &mut None, override_char_color);
n
}
// ---------- commands ----------
+471 -29
View File
@@ -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)} copy library swatches into the document as one undo step. A swatch the document already has (same name and paint) isn't added again; a name taken by another swatch gets a number (\"Clay 1 2\"). A pattern swatch brings its pattern, as pasting art painted with it does: the same pattern the document has is used, 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, and the pattern links to it → {library, added: [names in the document], 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
),
@@ -97,6 +98,8 @@ pub fn specs() -> Vec<CommandSpec> {
#[derive(Clone, Debug, Default)]
pub struct DesignLibraries {
libs: Vec<DesignLibrary>,
/// How many times a library was set; the next library's [`DesignLibrary::generation`].
loads: u64,
}
/// A document loaded as a swatch library that holds graph designs ([`DesignLibraries`]).
@@ -108,6 +111,9 @@ pub struct DesignLibrary {
pub name: String,
/// The designs and the resources their art uses.
pub doc: Arc<vectorcraft_doc::Document>,
/// Which load of the library this is: it differs from every other load's, so a picture of a design of
/// this library is stale once the library is loaded again.
pub generation: u64,
}
impl DesignLibraries {
@@ -125,8 +131,9 @@ impl DesignLibraries {
/// before; with no designs, `id` no longer has any.
fn set(&mut self, id: &str, name: &str, doc: Option<vectorcraft_doc::Document>) {
self.libs.retain(|l| l.id != id);
self.loads += 1;
if let Some(doc) = doc {
self.libs.push(DesignLibrary { id: id.to_string(), name: name.to_string(), doc: Arc::new(doc) });
self.libs.push(DesignLibrary { id: id.to_string(), name: name.to_string(), doc: Arc::new(doc), generation: self.loads });
}
}
}
@@ -1011,6 +1018,126 @@ fn free_in(taken: &mut HashSet<String>, base: &str) -> String {
name
}
/// [`free_in`] for a library swatch's copy: a numbered name also skips the names `reserved` says
/// the library's other swatches have, so that a later add finds the copy as this swatch's.
fn free_copy_in(taken: &mut HashSet<String>, base: &str, reserved: impl Fn(&str) -> bool) -> String {
let name = if taken.contains(base) {
(2..).map(|i| format!("{base} {i}")).find(|n| !taken.contains(n) && !reserved(n)).unwrap_or_else(|| base.to_string())
} else {
base.to_string()
};
taken.insert(name.clone());
name
}
/// 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),
}
}
/// Link the swatches of `d` that `pending` names (document name, library swatch) to their colors
/// under the names `links` gives them, for each whose colors `links` names now. Those leave
/// `pending` and are returned.
fn settle<'a>(
d: &mut vectorcraft_doc::Document,
pending: &mut Vec<(String, &'a Swatch)>,
links: &HashMap<String, String>,
) -> Vec<(String, &'a Swatch)> {
let mut done = vec![];
pending.retain(|(name, w)| {
let all = all_linked(&w.paint, links);
if all {
done.push((name.clone(), *w));
}
!all
});
relink_in(d, &done, links);
done
}
/// Give the swatches of `d` that `list` names (document name, library swatch) the library swatch's
/// paint with its colors linked to the names `links` gives them, in one pass over the document's
/// swatches.
fn relink_in(d: &mut vectorcraft_doc::Document, list: &[(String, &Swatch)], links: &HashMap<String, String>) {
if list.is_empty() {
return;
}
let paints: HashMap<&str, Paint> = list.iter().map(|(name, w)| (name.as_str(), relinked(&w.paint, links))).collect();
for x in d.swatches_iter_mut() {
if let Some(paint) = paints.get(x.name.as_str()) {
x.paint = paint.clone();
}
}
}
/// Whether paint `a` shows what paint `b` shows: the same color, or the same gradient with the
/// colors its stops show, whichever swatches those colors link to.
fn shows(a: &Paint, b: &Paint) -> bool {
let unlinked = |p: &Paint| match p {
Paint::Gradient(g) => {
let mut g = g.clone();
g.swatch = None;
g.gradient.stops.iter_mut().for_each(|s| s.swatch = None);
Paint::Gradient(g)
}
other => other.clone(),
};
match (a.color(), b.color()) {
(Some(x), Some(y)) => x == y,
_ => unlinked(a) == unlinked(b),
}
}
/// The names of the swatches the colors of paint `p` link to: a tint's base color, or the colors
/// of a gradient's stops.
fn linked_names(p: &Paint) -> Vec<&str> {
match p {
Paint::Solid { swatch: Some(b), .. } => vec![b.as_str()],
Paint::Gradient(g) => g.gradient.stops.iter().filter_map(|s| s.swatch.as_deref()).collect(),
_ => vec![],
}
}
/// Paint `p` with each link to a swatch that `links` names changed to the name it maps to.
fn relinked(p: &Paint, links: &HashMap<String, String>) -> Paint {
let mut out = p.clone();
let swap = |name: &mut String| {
if let Some(to) = links.get(name.as_str()) {
*name = to.clone();
}
};
match &mut out {
Paint::Solid { swatch: Some(b), .. } => swap(b),
Paint::Gradient(g) => g.gradient.stops.iter_mut().filter_map(|s| s.swatch.as_mut()).for_each(swap),
_ => {}
}
out
}
/// Whether `links` names every swatch the colors of paint `p` link to, the built-in Registration
/// swatch aside (every document has it under its own name).
fn all_linked(p: &Paint, links: &HashMap<String, String>) -> bool {
linked_names(p).iter().all(|n| *n == REGISTRATION || links.contains_key(*n))
}
fn add(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "swatch.library.add";
let (info, lib) = library_param(s, p, C)?;
@@ -1021,6 +1148,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
Some(other) => return Err(bad(C, format!("apply is \"fill\" or \"stroke\", not `{other}`"))),
};
let focus = switch_or(p, "focus", true, C)?;
switch_or(p, "defaultsOnly", false, C)?;
let picked = picked(&lib, &names_param(p, C)?, C)?;
// Swatches the document already has (same name and paint; for a pattern swatch, a swatch of the
// same pattern) are reused, not added again. The patterns are in a built-in pattern library's
@@ -1030,34 +1158,226 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
// The document's swatches by name (the first of a name wins, as in `Document::swatch`), looked
// up once so that a large palette takes linear time.
let mut by_name: std::collections::HashMap<&str, &Swatch> = std::collections::HashMap::new();
// The document's numbered copies ("Ink 2") by the name they are numbered after, in order.
let mut copies: HashMap<&str, Vec<&Swatch>> = HashMap::new();
for w in d.swatches_iter() {
by_name.entry(w.name.as_str()).or_insert(w);
let std::collections::hash_map::Entry::Vacant(e) = by_name.entry(w.name.as_str()) else { continue };
e.insert(w);
if let Some((base, n)) = w.name.rsplit_once(' ')
&& !n.is_empty()
&& n.bytes().all(|b| b.is_ascii_digit())
{
copies.entry(base).or_default().push(w);
}
}
let there = |w: &Swatch| match (&w.paint, &patterns) {
(Paint::Pattern { pattern, .. }, Some(src)) => {
patternlib::present_pattern(d, src, pattern).and_then(|target| library_pattern_swatch(d, w, &target))
// The library's swatches by name (the first of a name wins), looked up once.
let mut lib_by_name: HashMap<&str, &Swatch> = HashMap::new();
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));
}
_ => match by_name.get(w.name.as_str()) {
Some(x) => x.paint == w.paint,
None => w.name == REGISTRATION && d.swatch(&w.name).is_some_and(|x| x.paint == w.paint),
}
.then(|| w.name.clone()),
}
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
// numbered copy whose name the library gives a swatch of the same paint stands for that swatch
// alone, as adding that swatch finds it under its own name. Paints are compared with their
// colors linked as `links` says ([`relinked`]).
let same_kind = |x: &Swatch, w: &Swatch| x.global == w.global && x.spot == w.spot;
// A color is the same swatch only as the same kind: a library global color is not the
// document's process color of the same name and paint, which a tint cannot link to.
let same_color_kind = |x: &Swatch, w: &Swatch| w.paint.color().is_none() || same_kind(x, w);
let numbered = |w: &Swatch, paint: &Paint, links: &HashMap<String, String>| {
let c = copies.get(w.name.as_str())?;
let own = |x: &Swatch| lib_by_name.get(x.name.as_str()).is_some_and(|l| relinked(&l.paint, links) == x.paint && same_color_kind(x, l));
let found = c.iter().find(|x| !own(x) && x.paint == *paint && same_kind(x, w));
found.map(|x| x.name.clone())
};
let unlinked = HashMap::new();
// Whether a library global or spot color that paint `p` links to has no place in `links`
// while the document gives its name another swatch, which such a link would find instead.
let misplaced = |p: &Paint, links: &HashMap<String, String>| {
linked_names(p)
.into_iter()
.any(|n| !links.contains_key(n) && by_name.contains_key(n) && lib_by_name.get(n).is_some_and(|b| b.global || b.spot))
};
let picked_names: HashSet<&str> = picked.iter().map(|(_, w)| w.name.as_str()).collect();
// The picked patterns the document already has, each probed once: library pattern name → its
// name in the document and the colors of the document its art takes under other names.
let mut present: HashMap<&str, Option<(String, patternlib::SwatchNames)>> = HashMap::new();
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, &lib_names));
}
}
// Whether the document's swatch `x` of the name of library swatch `w` is `w` with its colors
// linked to swatches of the document → the library's global and spot colors to bring back,
// those this call picks included.
// `x` shows `w`'s paint with each color linked to: the name `links` gives it; its own name when
// that is the document's color of the library color's paint and kind; or, for a library color
// the document has under no name, that color's own name, which then comes in under it.
// Registration and colors the library does not have keep their names.
let fit = |x: &Swatch, w: &Swatch, links: &HashMap<String, String>| -> Option<Vec<String>> {
let (ours, theirs) = (linked_names(&w.paint), linked_names(&x.paint));
if ours.len() != theirs.len() {
return None;
}
let map: HashMap<String, String> = ours.iter().zip(&theirs).map(|(l, t)| (l.to_string(), t.to_string())).collect();
if relinked(&w.paint, &map) != x.paint {
return None;
}
let mut restore = vec![];
for (&l, &t) in ours.iter().zip(&theirs) {
let ok = match (links.get(l), lib_by_name.get(l).filter(|b| b.global || b.spot)) {
(Some(to), _) => to == t,
(None, None) => l == t,
(None, Some(b)) => match by_name.get(t) {
Some(y) => l == t && y.paint == b.paint && same_kind(y, b),
None if l == t && !group_names.contains(t) => {
restore.push(l.to_string());
true
}
None => false,
},
};
if !ok {
return None;
}
}
Some(restore)
};
// `paint` is `w`'s paint with the colors it links to as `links` has them in the document → the
// name of the document's swatch, and the library colors to bring back for it ([`fit`]).
let there = |w: &Swatch, paint: &Paint, links: &HashMap<String, String>| -> Option<(String, Vec<String>)> {
if let (Paint::Pattern { pattern, .. }, Some(_)) = (&w.paint, &patterns) {
let (target, _) = present.get(pattern.as_str())?.as_ref()?;
return library_pattern_swatch(d, w, target).map(|n| (n, vec![]));
}
if let Some(restore) = by_name.get(w.name.as_str()).filter(|x| same_color_kind(x, w)).and_then(|x| fit(x, w, links)) {
return Some((w.name.clone(), restore));
}
if misplaced(&w.paint, links) {
return None;
}
let found = match by_name.get(w.name.as_str()) {
Some(_) => numbered(w, paint, links),
None if group_names.contains(w.name.as_str()) => numbered(w, paint, links),
None => (w.name == REGISTRATION && d.swatch(&w.name).is_some_and(|x| x.paint == *paint)).then(|| w.name.clone()),
};
// A numbered copy brings back the colors it links to that the document deleted, as a
// swatch of `w`'s own name does.
found.map(|n| {
let back = by_name.get(n.as_str()).and_then(|x| fit(x, w, links)).unwrap_or_default();
(n, back)
})
};
// The global or spot color of the document that library color `b` is: its own name, or the
// numbered copy of it that adding `b` would find. While no color or color group has its name,
// a numbered copy is looked for only when this call does not add `b` under its own name.
let base_in_doc = |b: &Swatch| match by_name.get(b.name.as_str()) {
Some(x) if x.paint == b.paint && same_kind(x, b) => Some(b.name.clone()),
Some(_) => numbered(b, &b.paint, &unlinked),
None if group_names.contains(b.name.as_str()) || !picked_names.contains(b.name.as_str()) => numbered(b, &b.paint, &unlinked),
None => None,
};
// The library's global and spot colors that the picked tints and gradients link to, with the
// name each has in the document: library name → document name. Each is looked up for itself,
// whether or not this call picks it, once.
let mut base_names: HashMap<String, String> = HashMap::new();
let mut looked_up: HashSet<&str> = HashSet::new();
for (_, w) in &picked {
for base in linked_names(&w.paint) {
if !looked_up.insert(base) {
continue;
}
if let Some(n) = lib_by_name.get(base).filter(|b| b.global || b.spot).and_then(|b| base_in_doc(b)) {
base_names.insert(base.to_string(), n);
}
}
}
// A color that the art of a picked pattern the document holds takes under another name (a
// numbered copy that the library also names) is the one the picked tints and gradients link
// to, as when the pattern came in, unless this call adds the color itself. The colors the art
// takes are those of an import into a copy of the document, which adds nothing.
if looked_up.iter().any(|n| !base_names.contains_key(*n)) {
for (_, w) in &picked {
let Paint::Pattern { pattern, .. } = &w.paint else { continue };
let Some(Some((_, took))) = present.get(pattern.as_str()) else { continue };
for (from, to) in took.iter().cloned() {
let fits = |b: &&Swatch| by_name.get(to.as_str()).is_some_and(|x| (x.global || x.spot) && x.paint == b.paint && same_kind(x, b));
if looked_up.contains(from.as_str()) && !picked_names.contains(from.as_str()) && lib_by_name.get(from.as_str()).is_some_and(fits) {
base_names.entry(from).or_insert(to);
}
}
}
}
// Library name → the name of the document's swatch.
let mut existing: Vec<(String, String)> = vec![];
let mut fresh = vec![];
// The library colors that the document's tints and gradients found here link to by name while
// the document has no swatch of that name (one deleted without unlinking them): they come back
// under their own names.
let mut restore: Vec<String> = vec![];
// Those that this call picks: they are added first, so that they keep their names, which the
// art of a pattern added before them could otherwise take.
let mut reserved: HashSet<String> = HashSet::new();
for &(group, w) in &picked {
match there(w) {
Some(name) => existing.push((w.name.clone(), name)),
// A tint or gradient is compared with its colors linked to the names they have here.
let paint = relinked(&w.paint, &base_names);
match there(w, &paint, &base_names) {
Some((name, back)) => {
existing.push((w.name.clone(), name));
for n in back {
if picked_names.contains(n.as_str()) {
reserved.insert(n);
} else if !restore.contains(&n) {
restore.push(n);
}
}
}
None => fresh.push((group, w)),
}
}
if !reserved.is_empty() {
let (first, rest): (Vec<_>, Vec<_>) = fresh.into_iter().partition(|(_, w)| reserved.contains(&w.name));
fresh = first;
fresh.extend(rest);
}
let undo_before = s.doc()?.history.undo.len();
// Library name → the name it got in the document.
let added: Vec<(String, String)> = if fresh.is_empty() {
// Library name → the name it got in the document. The colors the patterns brought that no
// library swatch of this call stands for are added too; they are listed after the others and
// are never the one `apply` paints with.
let mut brought_alone: Vec<(String, String)> = vec![];
// Library name → the name of the document's global or spot color for it, which the tints and
// gradients added here link to: one that is global or spot as the library color is.
let base_of = |l: &str, n: &str| {
let (Some(w), Some(x)) = (lib_by_name.get(l), by_name.get(n)) else { return false };
(x.global || x.spot) && same_kind(x, w)
};
let mut links: HashMap<String, String> = existing.iter().filter(|(l, n)| base_of(l, n)).cloned().collect();
links.extend(base_names);
let added: Vec<(String, String)> = if fresh.is_empty() && restore.is_empty() {
vec![]
} else {
let (added, reused) = s.edit("Add to Swatches", |d, _| {
let (added, reused, brought) = s.edit("Add to Swatches", |d, _| {
let mut out = vec![];
// Library pattern swatches that stand for a swatch added earlier in this call.
let mut reused = vec![];
@@ -1069,13 +1389,81 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
// The swatches the patterns imported in this call brought with their art: (library
// name, document name).
let mut brought: Vec<(String, String)> = vec![];
// The colors to bring back come first, under their own names, which no swatch or color
// group of the document has; the tints and gradients added here link to them too.
for n in &restore {
let Some(b) = lib_by_name.get(n.as_str()) else { continue };
let name = free_in(&mut taken, &b.name);
d.swatches.push(Swatch { name: name.clone(), ..(*b).clone() });
links.insert(n.clone(), name.clone());
brought.push((n.clone(), name));
}
// The swatches added here with a link `links` did not name yet: (document name, library
// swatch).
let mut pending: Vec<(String, &Swatch)> = vec![];
for (group, w) in fresh {
let (name, sw) = if let (Paint::Pattern { pattern, .. }, Some(src)) = (&w.paint, &patterns) {
// The pattern comes with its swatch; a pattern the document has without one
// gets one. The swatch a pattern that comes in brings is named after the pattern:
// it takes the library swatch's name and color group instead.
// The tints and gradients added so far link to their colors first, so that the
// pattern's art finds them. A color they wait for that the pattern's art brings
// is named by importing the pattern into a copy first.
let brings = if pending.is_empty() { Default::default() } else { patternlib::brought_names(src, pattern) };
let waited = |n: &&str| !links.contains_key(*n) && brings.contains(*n);
// A global or spot color the pattern brought, or took from the document under
// a numbered name: library name → document name. A color this call picks is
// added under its own name instead of the one the pattern took. A library global
// or spot color is only a document color of its paint and kind, as for `base_of`.
let colors_of = |d: &vectorcraft_doc::Document, colors: &[(String, String)], took: &[(String, String)]| {
let mut out: HashMap<String, String> = HashMap::new();
for (from, to) in colors.iter().chain(took.iter().filter(|(from, _)| !picked_names.contains(from.as_str()))) {
let library = lib_by_name.get(from.as_str()).filter(|b| b.global || b.spot);
let fits = |x: &Swatch| (x.global || x.spot) && library.is_none_or(|b| x.paint == b.paint && same_kind(x, b));
if d.swatch(to).is_some_and(fits) {
out.entry(from.clone()).or_insert_with(|| to.clone());
}
}
out
};
// The names learned from the copy, which the import into the document confirms.
let mut learned = vec![];
if pending.iter().any(|(_, w)| linked_names(&w.paint).iter().any(waited)) {
let mut probe = d.clone();
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);
learned.push(from);
}
}
}
let settled = settle(d, &mut pending, &links);
let had = taken_names(d);
let (target, colors) = patternlib::import(d, src, pattern)?;
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
// linked again.
let mut found = colors_of(d, &colors, &took);
let mut changed = false;
for from in learned {
let real = found.remove(&from);
if real.as_ref() != links.get(&from) {
changed = true;
match real {
Some(to) => links.insert(from, to),
None => links.remove(&from),
};
}
}
for (from, to) in found {
links.entry(from).or_insert(to);
}
if changed {
relink_in(d, &settled, &links);
pending.extend(settled.into_iter().filter(|(_, w)| !all_linked(&w.paint, &links)));
}
brought.extend(colors);
if let Some(name) = library_pattern_swatch(d, w, &target).filter(|n| had.contains(n)) {
reused.push((w.name.clone(), name));
@@ -1087,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 {
@@ -1101,8 +1485,29 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
(name.clone(), Swatch { name, paint, global: false, spot: false })
} else {
// A color a pattern added earlier in this call brought with its art is that
// swatch: it moves to the library swatch's place.
let at = brought.iter().position(|(from, _)| *from == w.name);
// swatch when it shows the library swatch's color: it moves to the library
// swatch's place, when its colors link where the library swatch's do: to the
// names `links` gives them, not elsewhere for a color this call has yet to add,
// and otherwise to a color of the library color's paint and process, global or spot kind,
// or under the same name when the library has no such swatch (Registration).
let fits = |x: &Paint| {
let (ours, theirs) = (linked_names(&w.paint), linked_names(x));
ours.len() == theirs.len()
&& ours.iter().zip(&theirs).all(|(l, t)| match links.get(*l) {
Some(to) => to == t,
None => {
!picked_names.contains(l)
&& match lib_by_name.get(*l) {
Some(b) => d.swatch(t).is_some_and(|x| x.paint == b.paint && same_kind(x, b)),
None => l == t,
}
}
})
};
let same = |to: &str| {
d.swatch(to).is_some_and(|x| shows(&x.paint, &w.paint) && x.global == w.global && x.spot == w.spot && fits(&x.paint))
};
let at = brought.iter().position(|(from, to)| *from == w.name && same(to));
let moved = at.map(|i| brought.swap_remove(i).1).and_then(|n| {
let i = d.swatches.iter().position(|x| x.name == n)?;
Some(d.swatches.remove(i))
@@ -1110,11 +1515,23 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
match moved {
Some(sw) => (sw.name.clone(), sw),
None => {
let name = free_in(&mut taken, &w.name);
(name.clone(), Swatch { name, ..(*w).clone() })
// A numbered copy skips the names of the library's other swatches,
// which a later add looks up as theirs.
let name = free_copy_in(&mut taken, &w.name, |n| lib_by_name.contains_key(n));
// A tint or gradient links to its colors under the names they have in
// the document; a color that comes in later in this call is linked
// when it has come in.
let paint = relinked(&w.paint, &links);
if !all_linked(&w.paint, &links) {
pending.push((name.clone(), w));
}
(name.clone(), Swatch { name, paint, ..(*w).clone() })
}
}
};
if sw.global || sw.spot {
links.insert(w.name.clone(), name.clone());
}
match group {
Some(g) => {
let found = placed.iter().find(|(n, _)| *n == g).map(|&(_, i)| i);
@@ -1135,16 +1552,41 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
}
out.push((w.name.clone(), name));
}
Ok((out, reused))
// A library global or spot color that a tint or gradient added here links to, which the
// document does not have and nothing in this call brought, comes in with it, as pasting
// art painted with the tint brings its color. It is listed with the colors patterns
// brought.
let mut wanted: Vec<&str> = vec![];
let mut seen: HashSet<&str> = HashSet::new();
for (_, w) in &pending {
for n in linked_names(&w.paint) {
if n != REGISTRATION && !links.contains_key(n) && seen.insert(n) {
wanted.push(n);
}
}
}
for n in wanted {
let Some(b) = lib_by_name.get(n).filter(|b| b.global || b.spot) else { continue };
let name = free_copy_in(&mut taken, &b.name, |x| lib_by_name.contains_key(x));
d.swatches.push(Swatch { name: name.clone(), ..(*b).clone() });
links.insert(n.to_string(), name.clone());
brought.push((n.to_string(), name));
}
relink_in(d, &pending, &links);
Ok((out, reused, brought))
})?;
existing.extend(reused);
brought_alone = brought;
added
};
let names = |list: &[(String, String)]| list.iter().map(|(_, n)| n.clone()).collect::<Vec<_>>();
let mut out = json!({"library": shown_library_id(s, &info.id), "added": names(&added), "existing": names(&existing)});
let mut added_names = names(&added);
added_names.extend(names(&brought_alone));
let mut out = json!({"library": shown_library_id(s, &info.id), "added": added_names, "existing": names(&existing)});
if let (Some(cmd), Some((_, first))) = (apply, picked.first()) {
let name = added.iter().chain(&existing).find(|(l, _)| *l == first.name).map_or(first.name.clone(), |(_, n)| n.clone());
s.execute(cmd, &json!({"swatch": name, "focus": focus}))?;
let only = super::paint::defaults_only(s, p, C)?;
s.execute(cmd, &super::paint::with_defaults_only(json!({"swatch": name, "focus": focus}), only))?;
// Adding and applying undo together.
squash(s, undo_before, "Add to Swatches");
out["applied"] = json!(name);
+33 -16
View File
@@ -11,8 +11,8 @@ use super::menucmds::whole_or;
use super::stroke::StrokeChange;
use super::typecmd::refresh_bounds;
use super::{
CommandSpec, EngineError, Result, Session, bad, bool_or, check_numbers, check_switches, cmd, color_value, has_doc, has_selection, index,
number_or, object_param, point_param, str_param, switch_or, targets, text_param,
CommandSpec, EngineError, Result, Session, bad, bool_or, check_numbers, check_switches, cmd, color_value, finite_numbers, has_doc, has_selection,
index, number_or, object_param, str_param, switch_or, targets, text_param,
};
pub fn specs() -> Vec<CommandSpec> {
@@ -85,7 +85,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Area / Path Type",
[],
None,
"{path: id, mode: \"area\"|\"onPath\", text?: \"\", vertical?: bool = false, at?: [x, y] (on-path start: nearest point), size?: pt 0.1..1296 (outside it: an error), font?, style?, color?, keepModel? (as text.create), fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (area: as text.areaOptions; default autoHeight when the autoSizeAreaType preference is on), placeholder?: bool (placeholder text instead, as text.create), justify?, leadingModel?, charAlign? (as text.create)} turn a path into an area-type frame or a type-on-a-path baseline (the path's paint is dropped) → {id, bounds: {x, y, width, height} (as text.create), overflow?: [id] (the text doesn't fit; left out when it fits)}",
"{path: id, mode: \"area\"|\"onPath\", text?: \"\", vertical?: bool = false, at?: [x, y] (on-path start: nearest point; anything but two numbers: an error), size?: pt 0.1..1296 (outside it: an error), font?, style?, color?, keepModel? (as text.create), fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (area: as text.areaOptions; default autoHeight when the autoSizeAreaType preference is on), placeholder?: bool (placeholder text instead, as text.create), justify?, leadingModel?, charAlign? (as text.create)} turn a path into an area-type frame or a type-on-a-path baseline (the path's paint is dropped) → {id, bounds: {x, y, width, height} (as text.create), overflow?: [id] (the text doesn't fit; left out when it fits)}",
has_doc,
create_in_path
),
@@ -255,9 +255,15 @@ fn byte_param(p: &Value, k: &str) -> Option<usize> {
/// The byte offset that `p` gives for `k`, or `default` when `p` leaves it out or gives null. Any
/// other value that is not a whole number of at least 0, such as `"2"`, `-1` or `1.5`, is an error.
fn offset_or(p: &Value, k: &str, default: usize, cmd: &str) -> Result<usize> {
Ok(offset_given(p, k, cmd)?.unwrap_or(default))
}
/// The byte offset that `p` gives for `k`, or `None` when `p` leaves it out or gives null. Any
/// other value that is not a whole number of at least 0, such as `"2"`, `-1` or `1.5`, is an error.
fn offset_given(p: &Value, k: &str, cmd: &str) -> Result<Option<usize>> {
match p.get(k) {
None | Some(Value::Null) => Ok(default),
Some(_) => Ok(index(whole_or(p, k, 0, cmd)?)),
None | Some(Value::Null) => Ok(None),
Some(_) => Ok(Some(index(whole_or(p, k, 0, cmd)?))),
}
}
@@ -280,7 +286,7 @@ pub(crate) fn edit_range(s: &mut Session, p: &Value) -> Result<Value> {
None | Some(Value::Null) => None,
Some(v) => Some(serde_json::from_value(v.clone()).map_err(|e| bad(C, format!("bad `runs`: {e}")))?),
};
let insert = str_param(p, "insert").unwrap_or("").to_string();
let insert = text_param(p, "insert", C)?.unwrap_or("").to_string();
let clear = clear_param(s, p, id, C)?;
let caret = s.edit("Typing", |d, _| {
for other in &clear {
@@ -1313,8 +1319,7 @@ pub fn effective_kerning(db: &vectorcraft_text::FontDb, t: &TextObject, lay: &ve
/// The character at byte `start` of `p` in text object `t`, its bytes and its font's face. An error
/// when there is no character there, it is an inline graphic, or its font is not available.
fn glyph_target(t: &TextObject, p: &Value, c: &str) -> Result<(char, std::ops::Range<usize>, std::sync::Arc<vectorcraft_text::FontFace>)> {
check_numbers(p, &["start"], c)?;
let start = byte_param(p, "start").ok_or_else(|| bad(c, "missing `start` (the byte offset of a character)"))?;
let start = offset_given(p, "start", c)?.ok_or_else(|| bad(c, "missing `start` (the byte offset of a character)"))?;
let mut at = 0;
for run in &t.runs {
let end = at + run.text.len();
@@ -1558,8 +1563,7 @@ fn glyph_alternates(s: &mut Session, p: &Value) -> Result<Value> {
fn touch_type(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "text.touchType";
let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing `id`"))?;
check_numbers(p, &["start"], C)?;
let start = byte_param(p, "start").ok_or_else(|| bad(C, "missing `start` (the byte offset of a character)"))?;
let start = offset_given(p, "start", C)?.ok_or_else(|| bad(C, "missing `start` (the byte offset of a character)"))?;
if !["dx", "dy", "hScale", "vScale", "rotation"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) {
return Err(bad(C, "nothing to change: give dx, dy, hScale, vScale or rotation"));
}
@@ -1797,7 +1801,7 @@ fn touch_type(s: &mut Session, p: &Value) -> Result<Value> {
fn create_in_path(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "text.createInPath";
let pid = object_param(p, "path", C)?.ok_or_else(|| bad(C, "missing `path` (a path object id)"))?;
let on_path = match str_param(p, "mode").unwrap_or("area") {
let on_path = match text_param(p, "mode", C)?.unwrap_or("area") {
"area" => false,
"onPath" | "path" => true,
o => return Err(bad(C, format!("mode must be area|onPath, got {o}"))),
@@ -1815,8 +1819,12 @@ fn create_in_path(s: &mut Session, p: &Value) -> Result<Value> {
check_switches(p, &["vertical", "placeholder"], C)?;
super::color_param(p, "color", C)?;
let style = super::create::new_type_style(s, p, C)?;
let text = str_param(p, "text").unwrap_or("").to_string();
let start = match point_param(p, "at") {
let text = text_param(p, "text", C)?.unwrap_or("").to_string();
let at = match p.get("at").filter(|v| !v.is_null()) {
None => None,
Some(v) => Some(finite_numbers::<2>(v).map(|[x, y]| Point::new(x, y)).ok_or_else(|| bad(C, "`at` must be a point: [x, y]"))?),
};
let start = match at {
Some(at) if on_path => vectorcraft_geom::ArcPath::new(path).fraction_at(at).unwrap_or(0.0),
_ => 0.0,
};
@@ -1842,6 +1850,7 @@ fn create_in_path(s: &mut Session, p: &Value) -> Result<Value> {
system_layout: false,
fractional_widths: true,
list_count: 0,
file_fonts: None,
list_level_counts: Vec::new(),
cached_bounds: None,
cached_baselines: Vec::new(),
@@ -1886,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
@@ -2150,6 +2166,7 @@ fn headline_tracking(t: &TextObject, target: f64) -> Option<f64> {
system_layout: t.system_layout,
fractional_widths: t.fractional_widths,
list_count: 0,
file_fonts: None,
list_level_counts: Vec::new(),
cached_bounds: None,
cached_baselines: Vec::new(),
+2 -2
View File
@@ -13,7 +13,7 @@ use super::edit::selected_roots;
use super::pathops::{length_given, number_given, shape_node};
use super::{
CommandSpec, EngineError, Result, Session, bad, check_numbers, cmd, color_value, f64_req, has_doc, has_selection, index, index_opt, number_or,
object_param, ok, str_param, switch_or, targets, text_param,
object_param, ok, switch_or, targets, text_param,
};
pub fn specs() -> Vec<CommandSpec> {
@@ -873,7 +873,7 @@ pub(crate) fn style_chars(t: &mut TextObject, range: Option<TextRange>, mut f: i
}
fn set_text(s: &mut Session, p: &Value) -> Result<Value> {
let text = str_param(p, "text").ok_or_else(|| bad("text.setText", "missing `text`"))?.to_string();
let text = text_param(p, "text", "text.setText")?.ok_or_else(|| bad("text.setText", "missing `text`"))?.to_string();
let ids = text_targets(s, p, "text.setText")?;
// The text the type already has is no undo step.
edit_if_nodes_changed(s, "Typing", &ids, |d| {
+81 -44
View File
@@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Save for Web",
[],
None,
"{path?, preset?: a webExport.presets name (its settings, then these keys), format?: gif (default)|jpg|png8|png24, reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray (gif/png8, as the next five), colors?: 128 (2–256), dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, webSnap?: 0 (0–100 %: colours that close to a web-safe one become it), lossy?: 0 (0–100, gif), colorTable?: {locked?: [\"#rrggbb\"…] (kept when reducing), transparent?: [\"#rrggbb\"…] (become transparent), webShift?: [\"#rrggbb\"…] (become web-safe), sort?: none|hue|luminance|popularity, deleted?: [\"#rrggbb\"…] (taken out of the table: their pixels take the nearest color left, and at least one color stays), customPalette?: [\"#rrggbb\"…] (a fixed palette used instead of the reduction's, at most `colors` entries, its transparent colors taking one slot together; a new reduction without colorTable clears it and deleted), shifted?: {\"#source\": \"#rrggbb\"…} (each source color is written as the color given, wherever it is in the image; kept when reducing as a locked color is, before the locked ones, while one palette slot is left for the reduction; at most 256; a source the table does not hold shifts nothing; a color shifted to itself is removed; a shifted color is not web-shifted, and a transparent one stays transparent; GIF lossy moves no pixel into or out of a shifted color)} (colours as the preview's colors[].source; #rrggbbaa and #rgba are refused here and in matte), transparency?: true (gif/png8/png24), matte?: white (default)|black|none|\"#rrggbb\" (what edges blend into; jpg and opaque png24: the background), interlaced?: false (gif/png8/png24), quality?: 60 (jpg: 0–100), progressive?: false (jpg), optimized?: true (jpg), embedProfile?: false (jpg: sRGB profile), width?: px | height?: px | percent?: 100 (the image size, proportional; width wins over height, height over percent), antiAlias?: none|art (default)|type, clipToArtboard?: true (the artboard; false: the art and the slices), artboard?: 0 (0-based), convertToSrgb?: true (PNG files say they are sRGB), metadata?: none|copyright (default)|contact|all (File Info written as PNG text, a GIF or JPEG comment), slices?: all (default)|selected|none (one image per slice: images/<slice name>.<ext>), output?: images (default)|html (an HTML page placing the image or slices, <stem>.html)} → {path, files: [path…], bytes (total), width, height, warnings: [] or [a note that an image couldn't be decoded and is missing from the image]}; no path → {files: [{name, dataBase64}], bytes, width, height, warnings} (names such as page.html, images/page_01.gif). A single image without HTML is written at path itself",
"{path?, preset?: a webExport.presets name (its settings, then these keys), format?: gif (default)|jpg|png8|png24, reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray (gif/png8, as the next five), colors?: 128 (2–256), dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, webSnap?: 0 (0–100 %: colours that close to a web-safe one become it), lossy?: 0 (0–100, gif), colorTable?: {locked?: [\"#rrggbb\"…] (kept when reducing), transparent?: [\"#rrggbb\"…] (become transparent), webShift?: [\"#rrggbb\"…] (become web-safe), sort?: none|hue|luminance|popularity, deleted?: [\"#rrggbb\"…] (taken out of the table: their pixels take the nearest color left, and at least one color stays), customPalette?: [\"#rrggbb\"…] (a fixed palette used instead of the reduction's, at most `colors` entries, its transparent colors taking one slot together (the transparent pixels' slot when there are any), its shifted and then its locked colors kept first; a new reduction without colorTable clears it and deleted), shifted?: {\"#source\": \"#rrggbb\"…} (each source color is written as the color given, wherever it is in the image; kept when reducing as a locked color is, before the locked ones, while one palette slot is left for the reduction; at most 256; a source the table does not hold shifts nothing; a color shifted to itself is removed; a shifted color is not web-shifted, and a transparent one stays transparent; GIF lossy moves no pixel into or out of a shifted color)} (colours as the preview's colors[].source; #rrggbbaa and #rgba are refused here and in matte), transparency?: true (gif/png8/png24), matte?: white (default)|black|none|\"#rrggbb\" (what edges blend into; jpg and opaque png24: the background), interlaced?: false (gif/png8/png24), quality?: 60 (jpg: 0–100), progressive?: false (jpg), optimized?: true (jpg), embedProfile?: false (jpg: sRGB profile), width?: px | height?: px | percent?: 100 (the image size, proportional; width wins over height, height over percent), antiAlias?: none|art (default)|type, clipToArtboard?: true (the artboard; false: the art and the slices), artboard?: 0 (0-based), convertToSrgb?: true (PNG files say they are sRGB), metadata?: none|copyright (default)|contact|all (File Info written as PNG text, a GIF or JPEG comment), slices?: all (default)|selected|none (one image per slice: images/<slice name>.<ext>), output?: images (default)|html (an HTML page placing the image or slices, <stem>.html)} → {path, files: [path…], bytes (total), width, height, warnings: [] or [a note that an image couldn't be decoded and is missing from the image]}; no path → {files: [{name, dataBase64}], bytes, width, height, warnings} (names such as page.html, images/page_01.gif). A single image without HTML is written at path itself",
has_doc,
export
),
@@ -800,11 +800,18 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8
transparency: s.transparency,
matte,
};
let mut ix = reduced(rgba, w, h, s, &o, &kept)?;
let (mut ix, dropped) = reduced(rgba, w, h, s, &o, &kept)?;
// Map to transparent works on the colours the reduction made.
let before = ix.palette.clone();
let clear = ix.transparent.map(usize::from);
let mapped: Vec<[u8; 3]> = before.iter().enumerate().filter(|(i, c)| Some(*i) != clear && to_clear.contains(c)).map(|(_, c)| *c).collect();
let mut mapped: Vec<[u8; 3]> = before.iter().enumerate().filter(|(i, c)| Some(*i) != clear && to_clear.contains(c)).map(|(_, c)| *c).collect();
// The colors mapped to transparent that did not fit in a fixed palette and whose pixels became
// transparent.
for c in dropped {
if !mapped.contains(&c) {
mapped.push(c);
}
}
let remap = web::to_transparent(&mut ix, |i| Some(i) != clear && before.get(i).is_some_and(|c| to_clear.contains(c)));
let mut sources = ix.palette.clone();
for (old, new) in remap.iter().enumerate() {
@@ -868,8 +875,17 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8
/// color table's fixed one, without the deleted colors. The pixels of a deleted color take the
/// nearest color left, with `o`'s dither. A deletion has to leave a color that is not mapped to
/// transparent. A fixed palette keeps its colors mapped to transparent, which take one slot of
/// `colors` together, and its first opaque colors that fit in the rest.
fn reduced(rgba: &[u8], w: u32, h: u32, s: &WebSettings, o: &PaletteOptions, locked: &[[u8; 3]]) -> std::result::Result<Indexed, String> {
/// `colors` together (the transparent pixels' slot when there are any), and the opaque colors that
/// fit in the rest: the `locked` ones first, in their order, then the others in palette order. Also returns the
/// colors mapped to transparent that did not fit and whose pixels became transparent.
fn reduced(
rgba: &[u8],
w: u32,
h: u32,
s: &WebSettings,
o: &PaletteOptions,
locked: &[[u8; 3]],
) -> std::result::Result<(Indexed, Vec<[u8; 3]>), String> {
let table = &s.color_table;
let deleted = ColorTable::colors(&table.deleted, "deleted")?;
let custom = ColorTable::colors(&table.custom_palette, "customPalette")?;
@@ -880,13 +896,13 @@ fn reduced(rgba: &[u8], w: u32, h: u32, s: &WebSettings, o: &PaletteOptions, loc
let clear = ix.transparent.map(usize::from);
let gone = |i: usize, c: &[u8; 3]| Some(i) != clear && deleted.contains(c);
if !ix.palette.iter().enumerate().any(|(i, c)| gone(i, c)) {
return Ok(ix);
return Ok((ix, vec![]));
}
let left: Vec<[u8; 3]> = ix.palette.iter().enumerate().filter(|&(i, c)| Some(i) != clear && !deleted.contains(c)).map(|(_, c)| *c).collect();
if left.is_empty() || !opaque_left(&left) {
return Err(KEEP_ONE.into());
}
return Ok(quantize::quantize_to(rgba, w, h, o, &left));
return Ok((quantize::quantize_to(rgba, w, h, o, &left), vec![]));
}
// A fixed palette holds at most `colors` entries, the transparent one included.
let has_clear = s.transparency && rgba.as_chunks::<4>().0.iter().any(|p| p[3] < 128);
@@ -901,32 +917,46 @@ fn reduced(rgba: &[u8], w: u32, h: u32, s: &WebSettings, o: &PaletteOptions, loc
return Err(KEEP_ONE.into());
}
// The colors mapped to transparent all become the one transparent entry, so together they take
// one slot, and the opaque colors fill the rest in palette order. When no pixel takes one of
// them and no pixel is transparent, that slot goes to the next opaque color instead.
let kept = fixed_palette(&left, &to_clear, s.colors, has_clear, true);
// one slot, and the opaque colors fill the rest. With transparent pixels that slot is theirs, so
// the colors mapped to transparent take no entry of their own and their pixels take the
// transparent pixels' entry. Without them, when no pixel takes one of those colors, the slot
// goes to the next opaque color instead.
let kept = fixed_palette(&left, &to_clear, locked, s.colors, has_clear, !has_clear);
let mut ix = quantize::quantize_to(rgba, w, h, o, &kept);
clear_dropped(&mut ix, rgba, o, &kept, &left, &to_clear);
let dropped = clear_dropped(&mut ix, rgba, o, &kept, &left, &to_clear);
if !has_clear && !ix.palette.iter().any(|c| to_clear.contains(c)) && left.iter().any(|c| to_clear.contains(c)) {
return Ok(quantize::quantize_to(rgba, w, h, o, &fixed_palette(&left, &to_clear, s.colors, has_clear, false)));
return Ok((quantize::quantize_to(rgba, w, h, o, &fixed_palette(&left, &to_clear, locked, s.colors, has_clear, false)), vec![]));
}
Ok(ix)
Ok((ix, dropped))
}
/// The entries of the fixed palette `left` that fit in `colors`. With `clear`, the colors in
/// `to_clear` are kept and take one slot together; without it they are left out. The list holds
/// at most 256 entries, less one when `has_clear` (the transparent pixels' entry).
fn fixed_palette(left: &[[u8; 3]], to_clear: &[[u8; 3]], colors: u16, has_clear: bool, clear: bool) -> Vec<[u8; 3]> {
/// The entries of the fixed palette `left` that fit in `colors`, in palette order. The opaque
/// colors in `locked` are kept first, in the order `locked` lists them (the colors shifted by hand
/// before the locked ones), then the other opaque colors in palette order. With `clear`,
/// the colors in `to_clear` are kept and take one slot together; without it they are left out. The
/// list holds at most 256 entries, less one when `has_clear` (the transparent pixels' entry).
fn fixed_palette(left: &[[u8; 3]], to_clear: &[[u8; 3]], locked: &[[u8; 3]], colors: u16, has_clear: bool, clear: bool) -> Vec<[u8; 3]> {
let any_clear = clear && left.iter().any(|c| to_clear.contains(c));
let total = 256 - usize::from(has_clear);
let mut room = (usize::from(colors.clamp(2, 256)) - usize::from(has_clear || any_clear)).min(total - usize::from(any_clear));
let opaque = left.iter().filter(|c| !to_clear.contains(c)).count().min(room);
let mut clear_room = if clear { total - opaque } else { 0 };
let room = (usize::from(colors.clamp(2, 256)) - usize::from(has_clear || any_clear)).min(total - usize::from(any_clear));
let opaque = |c: &&[u8; 3]| !to_clear.contains(c);
let mut first: Vec<[u8; 3]> = vec![];
for c in locked.iter().filter(opaque).filter(|c| left.contains(c)) {
if first.len() < room && !first.contains(c) {
first.push(*c);
}
}
let rest = room - first.len();
let others: Vec<[u8; 3]> = left.iter().filter(opaque).filter(|c| !locked.contains(c)).take(rest).copied().collect();
let mut clear_room = if clear { total - first.len() - others.len() } else { 0 };
left.iter()
.copied()
.filter(|c| {
let slots = if to_clear.contains(c) { &mut clear_room } else { &mut room };
let keep = *slots > 0;
*slots = slots.saturating_sub(1);
if !to_clear.contains(c) {
return first.contains(c) || others.contains(c);
}
let keep = clear_room > 0;
clear_room = clear_room.saturating_sub(1);
keep
})
.collect()
@@ -935,32 +965,39 @@ fn fixed_palette(left: &[[u8; 3]], to_clear: &[[u8; 3]], colors: u16, has_clear:
/// Makes transparent the pixels of `ix` whose nearest color is a color of `left` mapped to
/// transparent (`to_clear`) that does not fit in the fixed palette `kept`. Such a pixel takes the
/// transparent entry, or an entry mapped to transparent, which Map to Transparent clears later.
fn clear_dropped(ix: &mut Indexed, rgba: &[u8], o: &PaletteOptions, kept: &[[u8; 3]], left: &[[u8; 3]], to_clear: &[[u8; 3]]) {
/// Returns those colors that a pixel took.
fn clear_dropped(ix: &mut Indexed, rgba: &[u8], o: &PaletteOptions, kept: &[[u8; 3]], left: &[[u8; 3]], to_clear: &[[u8; 3]]) -> Vec<[u8; 3]> {
let dropped: Vec<[u8; 3]> = left.iter().filter(|c| to_clear.contains(c) && !kept.contains(c)).copied().collect();
if dropped.is_empty() {
return;
return vec![];
}
let all: Vec<[u8; 3]> = kept.iter().chain(&dropped).copied().collect();
let near = quantize::nearest_entries(rgba, o, &all);
if !near.iter().any(|n| n.is_some_and(|n| n >= kept.len())) {
return;
}
let entry = match ix.transparent.or_else(|| ix.palette.iter().position(|c| to_clear.contains(c)).and_then(|i| u8::try_from(i).ok())) {
Some(i) => i,
None => {
// A kept color mapped to transparent that no pixel took; at most 255 entries are used then.
let (Some(c), Ok(i)) = (kept.iter().find(|c| to_clear.contains(c)), u8::try_from(ix.palette.len())) else {
return;
};
ix.palette.push(*c);
i
let Indexed { palette, transparent, indices, .. } = ix;
// The entry such pixels take, looked up at the first of them.
let mut entry: Option<Option<u8>> = None;
let mut taken = vec![false; dropped.len()];
let mut pixel = 0;
quantize::nearest_entries(rgba, o, &all, |n| {
if let Some(d) = n.and_then(|n| n.checked_sub(kept.len())) {
let e = *entry.get_or_insert_with(|| {
transparent.or_else(|| palette.iter().position(|c| to_clear.contains(c)).and_then(|i| u8::try_from(i).ok())).or_else(|| {
// A kept color mapped to transparent that no pixel took; at most 255 entries are used then.
let c = kept.iter().find(|c| to_clear.contains(c))?;
let i = u8::try_from(palette.len()).ok()?;
palette.push(*c);
Some(i)
})
});
if let (Some(e), Some(v)) = (e, indices.get_mut(pixel)) {
*v = e;
if let Some(t) = taken.get_mut(d) {
*t = true;
}
}
}
};
for (v, n) in ix.indices.iter_mut().zip(&near) {
if n.is_some_and(|n| n >= kept.len()) {
*v = entry;
}
}
pixel += 1;
});
dropped.into_iter().zip(taken).filter(|(_, t)| *t).map(|(c, _)| c).collect()
}
/// An optimised image as straight RGBA → `(pixels, width, height)` (the dialog's preview).
+35 -4
View File
@@ -30,7 +30,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Sample Color",
[],
None,
"{color (#rrggbbaa and #rgba are refused), stroke?: bool (default: whichever proxy is active), ids?, stop?: index, clearStroke?: bool} sample a color into the active fill/stroke (and the selection; `ids: []` changes only the paint default, and so does a sample without ids while the Live Paint Bucket is the active tool, `stop` included); `clearStroke: true` requires `stroke: false`, `ids: []` and no `stop`, and clears the default stroke after sampling an image into the fill; with `stop`, recolor that stop of the gradient behind the proxy instead (paint.editGradient); in a CMYK document an RGB color is stored as CMYK through the color settings, as paint.setFill stores it",
"{color (#rrggbbaa and #rgba are refused), stroke?: bool (default: whichever proxy is active), ids?, defaultsOnly?: bool, stop?: index, clearStroke?: bool} sample a color into the active fill/stroke (and the selection; `ids: []` changes only the paint default, and so does a sample without ids while the Live Paint Bucket is the active tool or with `defaultsOnly: true` (refused with ids), `stop` included); `clearStroke: true` requires `stroke: false`, `ids: []` and no `stop`, and clears the default stroke after sampling an image into the fill; with `stop`, recolor that stop of the gradient behind the proxy instead (paint.editGradient); with `stop` and objects in `ids`, whatever tool is active, the stops come from the topmost fill (or stroke) of the first object that paint.editGradient edits for those ids (a compound path for its member); in a CMYK document an RGB color is stored as CMYK through the color settings, as paint.setFill stores it",
has_doc,
sample_color
),
@@ -523,15 +523,27 @@ fn sample_color(s: &mut Session, p: &Value) -> Result<Value> {
if clear_stroke && (stroke || p.get("stroke") != Some(&Value::Bool(false)) || p.get("ids") != Some(&json!([])) || p.get("stop").is_some()) {
return Err(bad(C, "`clearStroke` requires `stroke: false`, `ids: []` and no `stop`"));
}
let only = super::switch_or(p, "defaultsOnly", false, C)?;
if only && p.get("ids").is_some_and(|v| !v.is_null()) {
return Err(bad(C, "`defaultsOnly` cannot be combined with `ids`, `id` or `item`"));
}
let c = p.get("color").ok_or_else(|| bad(C, "missing color"))?;
let (id, mut q) = match p.get("stop") {
None | Some(Value::Null) => (if stroke { "paint.setStroke" } else { "paint.setFill" }, json!({ "color": c })),
Some(v) => {
let i = v.as_u64().map(index).ok_or_else(|| bad(C, "`stop` must be a stop index"))?;
let color = super::paint::new_color(s, p, color_value(c).ok_or_else(|| bad(C, format!("bad color {c}")))?);
let (fill, stroke_paint) = s.proxy_paints();
let Paint::Gradient(g) = (if stroke { stroke_paint } else { fill }) else {
return Err(bad(C, "the paint behind the proxy is not a gradient"));
let (paint, source) = match given_stop_paint(s, p, stroke)? {
Some(paint) => (paint, "the paint of the first object in `ids`"),
None => {
// The default's gradient with `defaultsOnly`, as the proxies show it while the Live
// Paint Bucket paints.
let (fill, stroke_paint) = if only { (s.paint.fill.clone(), s.paint.stroke.clone()) } else { s.proxy_paints() };
(if stroke { stroke_paint } else { fill }, "the paint behind the proxy")
}
};
let Paint::Gradient(g) = paint else {
return Err(bad(C, format!("{source} is not a gradient")));
};
let mut stops = g.gradient.stops;
let n = stops.len();
@@ -542,6 +554,7 @@ fn sample_color(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(ids) = p.get("ids") {
q["ids"] = ids.clone();
}
let q = super::paint::with_defaults_only(q, only);
let spec = find_command(id).ok_or_else(|| EngineError::UnknownCommand(id.into()))?;
let result = super::run_checked(s, spec, &q)?;
if clear_stroke {
@@ -550,6 +563,24 @@ fn sample_color(s: &mut Session, p: &Value) -> Result<Value> {
Ok(result)
}
/// The paint whose gradient `paint.sampleColor` recolors a stop of when `p` gives `stop` and
/// objects in `ids`: the fill (or stroke, `stroke`) of the first object `paint.editGradient` edits
/// for those ids (a compound path for its member, a group's painted objects, not the art of a graph
/// design in a series). None without `stop` or without objects in `ids`: the gradient behind the
/// proxy is used.
fn given_stop_paint(s: &Session, p: &Value, stroke: bool) -> Result<Option<Paint>> {
const C: &str = "paint.sampleColor";
if p.get("stop").is_none_or(Value::is_null) || p.get("ids").and_then(Value::as_array).is_none_or(Vec::is_empty) {
return Ok(None);
}
let q = json!({ "ids": p.get("ids"), "stroke": stroke });
let item = super::appearance::item_target(s, &q, C)?.of_kind(s, !stroke);
let ids = super::appearance::drop_design_art_rows(s, item.targets_for(s, &q, !stroke)?, item, !stroke, C)?;
let d = &s.doc()?.doc;
let Some(n) = ids.first().and_then(|id| d.node(*id)) else { return Ok(None) };
Ok(Some(super::paint::proxy_paint(n, stroke, None)))
}
// ---------- artboards ----------
fn artboard_move(s: &mut Session, p: &Value) -> Result<Value> {
+213 -5
View File
@@ -25,10 +25,11 @@ pub struct DocState {
/// Panel state, not art selection: not saved, not undoable (`layer.setCurrent`,
/// `layer.highlight`).
pub layer_rows: Vec<NodeId>,
/// The row the last Locate Object or Locate Layer (`layer.locate`) highlighted, until the
/// Layers panel takes it: the panel opens the layers around that row and scrolls to it, also
/// when the row was already highlighted. Panel state: not saved, not undoable.
pub locate_reveal: Option<NodeId>,
/// What the Layers panel reveals at its next pass, until the panel takes it: the panel opens
/// the layers around the row and scrolls to it, also when the row was already highlighted.
/// Set by `layer.locate` and, for what a top-level command, an interaction's commit or a
/// selection changed, by [`DocState::request_reveal`]. Panel state: not saved, not undoable.
pub layers_reveal: Option<LayersReveal>,
/// The variable highlighted in the Variables panel: what its Delete, Options… and Select
/// Bound Object act on. Panel state, not art selection: not saved, not undoable
/// (`variable.highlight`). A name, so renaming a variable moves the highlight with it.
@@ -128,6 +129,11 @@ pub struct DocState {
/// paths the document links to are looked at within them later too, when the Links panel
/// asks about a link outside any caller's scope.
pub opened_by: Option<Arc<file_access::AutomationRoots>>,
/// What the commands scripts ran did to the document since the person last opened or saved it:
/// `None` when they did nothing. The commands a script runs read and write the document's file,
/// and read the files it links to, only as the person left them ([`DocState::as_person_left`]).
/// Not saved.
pub(crate) by_script: Option<ByScript>,
/// The live-effect plug-in stages deferred while the document is drawn on screen, and the time
/// budget of its first view ([`vectorcraft_plugins::deferred`]). Not saved.
pub plugin_effects: vectorcraft_plugins::deferred::Deferrals,
@@ -144,6 +150,50 @@ pub struct DocState {
/// measured: the next refresh checks only the layer trees that differ from it
/// ([`cmd::inline::refresh`]). Not saved.
pub(crate) inline_resolved: Option<cmd::inline::Resolved>,
/// The selected objects as [`crate::Session::select`] last checked them or the proxies last
/// read them, with the document they were checked in ([`SelectionRecord`]). Not saved.
pub(crate) selection_record: Option<SelectionRecord>,
}
/// A selection of objects alone ([`objects_only`]) with the document it was checked or read in:
/// while the document and the selected objects stay the same, a command that adds objects checks
/// and reads only the added ones.
#[derive(Clone, Debug)]
pub(crate) struct SelectionRecord {
/// The document, held as [`EmptyArtboards::doc`] holds it.
pub(crate) doc: std::sync::Weak<Document>,
pub(crate) objects: Vec<NodeId>,
/// Lock Guides as it was when [`crate::Session::select`] left these objects selected; `None`
/// when it did not.
pub(crate) settled: Option<bool>,
/// What the proxies read from these objects; `None` when they were not read.
pub(crate) paints: Option<cmd::SelectionPaints>,
}
/// Whether `sel` holds selected objects and nothing else: no anchors, segments, key, target,
/// slices, ruler guides, object of a symbol instance's art or object on a path.
pub(crate) fn objects_only(sel: &Selection) -> bool {
sel.anchors.is_empty()
&& sel.segments.is_empty()
&& sel.key.is_none()
&& sel.target.is_none()
&& sel.slices.is_empty()
&& sel.guides.is_empty()
&& sel.key_guide.is_none()
&& sel.key_anchor.is_none()
&& sel.symbol_part.is_none()
&& sel.on_path_member.is_none()
}
/// What the commands scripts ran did to an open document since the person last opened or saved it
/// ([`DocState::by_script`]).
#[derive(Clone, Debug)]
pub(crate) enum ByScript {
/// A command a script ran opened it (or made it).
Opened,
/// A command a script ran changed it or gave it another file: the document, its file and the
/// file it was read from as they were before the first such command.
Changed { doc: Arc<Document>, path: Option<String>, links_from: Option<String> },
}
/// Whether a document has an artboard for Delete Empty Artboards to delete, with the document that
@@ -179,6 +229,30 @@ thread_local! {
static NEXT_DOC_UID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
/// What the Layers panel is asked to reveal ([`DocState::layers_reveal`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LayersReveal {
/// Open the layers around this row and scroll to it: it was highlighted, located or isolated.
Row(NodeId),
/// The current layer changed with no row highlighted: reveal that layer.
Current(NodeId),
/// The last selected object changed: reveal its row when Panel Options › Locate Selected
/// Objects is on.
Selected(NodeId),
}
/// What decides a [`LayersReveal`], as of one moment: the isolation, the highlighted rows, the
/// current layer and the last selected object of one document, with the request pending then.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct LayersView {
uid: u64,
isolation: Option<NodeId>,
rows: Vec<NodeId>,
active_layer: Option<NodeId>,
last_selected: Option<NodeId>,
reveal: Option<LayersReveal>,
}
/// The rows open in the Layers panel: the layers, sublayers and groups that show what they hold.
/// A document opens with the ones it was saved with ([`Document::layers_open`]), else with only
/// its top-level layers open (a `.ai` another app wrote opens with none open).
@@ -326,7 +400,7 @@ impl DocState {
revision: 1,
active_layer,
layer_rows: vec![],
locate_reveal: None,
layers_reveal: None,
variables_highlight: None,
variables_sort: Default::default(),
isolation: None,
@@ -360,11 +434,77 @@ impl DocState {
links_from: None,
last_perspective: None,
opened_by: file_access::current(),
by_script: None,
empty_artboards: Default::default(),
plugin_effects: Default::default(),
art_to_fit: Default::default(),
measured_in_own: None,
inline_resolved: None,
selection_record: None,
}
}
/// The [`SelectionRecord`] of the selection now: `None` when the document or the selected
/// objects changed since it was made, or when anything besides whole objects is selected
/// ([`objects_only`]). Only a new [`Document`] makes the record stale: the document's new art
/// is the one state that changes in place and matters to it, and [`crate::Session::select`]
/// checks the whole selection while there is new art.
pub(crate) fn selection_record(&self) -> Option<&SelectionRecord> {
self.selection_record
.as_ref()
.filter(|r| std::ptr::eq(r.doc.as_ptr(), Arc::as_ptr(&self.doc)) && objects_only(&self.selection) && r.objects == self.selection.objects)
}
/// What the proxies read from the selected objects, when the [`SelectionRecord`] of the
/// selection now holds it.
pub(crate) fn selection_paints(&self) -> Option<&cmd::SelectionPaints> {
self.selection_record().and_then(|r| r.paints.as_ref())
}
/// Keep the [`SelectionRecord`] of the selection that [`crate::Session::select`] left, with
/// Lock Guides `guides_locked`. `record` is the record of the selection before: when the
/// selected objects start with its objects, the added objects are read into its paints.
pub(crate) fn record_selection(&mut self, record: Option<SelectionRecord>, guides_locked: bool) {
if !objects_only(&self.selection) {
self.selection_record = None;
return;
}
let objects = &self.selection.objects;
self.selection_record = Some(match record {
Some(mut r) if objects.starts_with(&r.objects) => {
let added = &objects[r.objects.len()..];
if let Some(p) = &mut r.paints {
p.add(&self.doc, added);
}
r.objects.extend_from_slice(added);
r.settled = Some(guides_locked);
r
}
_ => SelectionRecord { doc: Arc::downgrade(&self.doc), objects: objects.clone(), settled: Some(guides_locked), paints: None },
});
}
/// The document, its file and the file it was read from as the person last left them, for the
/// commands scripts run ([`DocState::by_script`]): `None` for a document a script's command
/// opened.
pub(crate) fn as_person_left(&self) -> Option<(&Arc<Document>, Option<&str>, Option<&str>)> {
match &self.by_script {
None => Some((&self.doc, self.path.as_deref(), self.links_from.as_deref())),
Some(ByScript::Opened) => None,
Some(ByScript::Changed { doc, path, links_from }) => Some((doc, path.as_deref(), links_from.as_deref())),
}
}
/// Notes what a command a script ran did to the document, which was `was` (the document, its
/// file and the file it was read from) before the command ran, or not open when `was` is
/// `None`. The first change is kept until the person saves the document.
pub(crate) fn note_script_command(&mut self, was: Option<(&Arc<Document>, &Option<String>, &Option<String>)>) {
if self.by_script.is_some() {
return;
}
let Some((doc, path, links_from)) = was else {
self.by_script = Some(ByScript::Opened);
return;
};
if !Arc::ptr_eq(doc, &self.doc) || *path != self.path || *links_from != self.links_from {
self.by_script = Some(ByScript::Changed { doc: doc.clone(), path: path.clone(), links_from: links_from.clone() });
}
}
/// `measure`'s answer for the document now. `measure` runs once for each version of the document,
@@ -657,6 +797,74 @@ impl DocState {
pub fn highlighted_rows(&self) -> Vec<NodeId> {
self.layer_rows.iter().copied().filter(|id| self.doc.node(*id).is_some()).collect()
}
/// What decides the Layers panel's reveal request now.
pub(crate) fn layers_view(&self) -> LayersView {
LayersView {
uid: self.uid,
isolation: self.isolation,
rows: self.layer_rows.clone(),
active_layer: self.active_layer,
last_selected: self.selection.objects.last().copied(),
reveal: self.layers_reveal,
}
}
/// [`DocState::layers_view`] as it was when interaction `it` began: what a commit of the
/// interaction changed is compared with that, since the previews changed the state meanwhile.
pub(crate) fn layers_view_before(&self, it: &Interaction) -> LayersView {
LayersView {
uid: self.uid,
isolation: it.isolation,
rows: it.layer_rows.clone(),
active_layer: it.active_layer,
last_selected: it.selection.objects.last().copied(),
reveal: self.layers_reveal,
}
}
/// Ask the Layers panel to reveal what changed since `before`, in this order: isolation entered
/// or left, the highlighted rows, the last selected object, the current layer. A request made
/// meanwhile (`layer.locate`) stands, and nothing is asked while an interaction is open, so a
/// drag's previews reveal nothing and its commit does.
pub(crate) fn request_reveal(&mut self, before: &LayersView) {
if self.uid != before.uid || self.layers_reveal != before.reveal || self.interaction.is_some() {
return;
}
let now = self.layers_view();
let mut request = None;
if now.isolation != before.isolation {
request = self.reveal_isolation(now.isolation, before.isolation);
}
if request.is_none() && now.rows != before.rows {
request = self.highlighted_rows().first().copied().map(LayersReveal::Row);
}
// A new selection asks for its object even when it changed the current layer too: the panel
// falls back to the current layer when it does not locate the object.
if request.is_none() && now.last_selected != before.last_selected {
request = now.last_selected.map(LayersReveal::Selected);
// An emptied selection leaves no object to locate.
if request.is_none() && matches!(self.layers_reveal, Some(LayersReveal::Selected(_))) {
self.layers_reveal = None;
}
}
if request.is_none() && now.active_layer != before.active_layer {
request = self.current_layer().map(LayersReveal::Current);
}
if request.is_some() {
self.layers_reveal = request;
}
}
/// The request for isolation moving from `before` to `now`: entering opens the isolated row,
/// leaving opens the layers around the row that was isolated.
fn reveal_isolation(&mut self, now: Option<NodeId>, before: Option<NodeId>) -> Option<LayersReveal> {
if let Some(root) = now.filter(|r| self.doc.node(*r).is_some()) {
self.layers_open.set(root, true);
return Some(LayersReveal::Row(root));
}
let former = before?;
for around in self.doc.ancestry(former)?.into_iter().filter(|a| *a != former) {
self.layers_open.set(around, true);
}
Some(LayersReveal::Row(former))
}
/// The object whose opacity mask View Opacity Mask shows ([`DocState::mask_view`]): only while
/// its mask is being edited, so leaving editing by any route (undo, deleting the object) ends it.
pub fn shown_mask(&self) -> Option<NodeId> {
+184 -13
View File
@@ -27,7 +27,8 @@
//! [`ScriptScope`] holds the folders a running script's own files (its includes and `$.evalFile`)
//! are read from, and the places its `File` and `Folder` objects read and write, inside the roots.
//! [`ScriptGate`] holds the same places for the commands the script runs with `vc.run`, with the
//! files of the open documents.
//! files of the open documents, and for reading, the files the documents open when the run began
//! link to, each as the person last left the document.
use std::cell::RefCell;
use std::ffi::OsString;
@@ -283,19 +284,56 @@ impl ScopeHandle {
/// What a command a running script runs (`vc.run`) may read and write: the places the script's
/// `File` and `Folder` objects may ([`ScriptScope`]), and the files the documents open in the app
/// were opened from or saved to. The automation roots apply as well. A path refused by its name
/// alone ([`ScriptScope::refused_by_name`]) is refused here too.
/// were opened from or saved to by the person ([`crate::DocState::as_person_left`]). Reading, and
/// only reading, the files the documents link to as the person left them when the run began is
/// allowed as well ([`ScriptGate::linked`]). The automation roots apply as well. A path refused by
/// its name alone ([`ScriptScope::refused_by_name`]) is refused here too.
#[derive(Clone, Debug)]
pub(crate) struct ScriptGate {
pub(crate) read: ScriptScope,
pub(crate) write: ScriptScope,
/// The paths of the open documents' files, as the documents hold them.
/// The paths of the open documents' files, as the documents held them when the person last
/// opened or saved them. A document a script's command opened has none here.
pub(crate) documents: Vec<String>,
/// The files the documents link to as the person left them when the run began: readable, not
/// writable.
pub(crate) linked: LinkedFiles,
/// Another gate a path must pass as well ([`ScopeHandle::within_current`]).
pub(crate) also: Option<Arc<ScriptGate>>,
}
/// The files the commands a script runs may only read because the documents open when the run
/// began link to them as the person left them ([`ScriptGate::linked`]).
#[derive(Clone, Debug, Default)]
pub(crate) struct LinkedFiles {
/// The real paths of the files, as they were when the run's first command was run, sorted. A
/// path that leads to another file now is not one of them.
files: Arc<[PathBuf]>,
}
impl LinkedFiles {
/// Is `real`, a real path, one of the files?
fn has(&self, real: &Path) -> bool {
self.files.binary_search_by(|f| f.as_path().cmp(real)).is_ok()
}
}
impl ScriptGate {
/// The real paths of the files at `paths` that are files now, each once, for
/// [`ScriptGate::linked`]. A path refused by its name alone, and one that cannot be resolved,
/// is left out.
pub(crate) fn real_files(paths: impl IntoIterator<Item = String>) -> LinkedFiles {
let mut real: Vec<PathBuf> = paths
.into_iter()
.filter(|p| !ScriptScope::refused_by_name(Path::new(p)))
.filter_map(|p| resolve(&p).ok())
.filter(|p| p.is_file())
.collect();
real.sort();
real.dedup();
LinkedFiles { files: real.into() }
}
/// This gate with `next` at the end of its chain of `also` gates, so a path must pass every
/// gate already in the chain as well as `next`.
fn followed_by(&self, next: Arc<ScriptGate>) -> ScriptGate {
@@ -317,7 +355,8 @@ impl ScriptGate {
Access::Read => self.read.allows(&real) || self.write.allows(&real),
Access::Write => self.write.allows(&real),
};
scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real))
let linked = matches!(access, Access::Read) && self.linked.has(&real) && !self.read.keeps_out(&real);
scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real)) || linked
});
if allowed { Ok(()) } else { Err(format!("Script file access denied: {path}")) }
}
@@ -361,6 +400,11 @@ fn check_gate(path: &str, access: Access) -> Result<(), String> {
GATE.with(|g| g.borrow().clone()).map_or(Ok(()), |g| g.check(path, access))
}
/// Whether this thread runs a command a script runs ([`with_script_gate`]).
pub(crate) fn in_script_command() -> bool {
GATE.with(|g| g.borrow().is_some())
}
/// The roots in force on this thread, if any.
pub fn current() -> Option<Arc<AutomationRoots>> {
match SCOPE.with(|s| s.borrow().clone()) {
@@ -627,7 +671,13 @@ impl ScriptScope {
pub(crate) fn allows(&self, real: &Path) -> bool {
(self.files.iter().any(|f| inside(real, f) && real.components().count() == f.components().count())
|| self.roots.iter().any(|r| inside(real, r)))
&& !self.fenced.iter().any(|f| inside(real, f) && !self.open.iter().any(|o| inside(o, f) && inside(real, o)))
&& !self.keeps_out(real)
}
/// Is the real path `real` in a folder kept out ([`ScriptScope::fence`]), and not in a place
/// left open there?
fn keeps_out(&self, real: &Path) -> bool {
self.fenced.iter().any(|f| inside(real, f) && !self.open.iter().any(|o| inside(o, f) && inside(real, o)))
}
/// The scope of a script run from a file in the folder whose real path, with its links already
@@ -789,15 +839,17 @@ impl ScriptScope {
self.allows(&real.join(rest))
}
/// What the file or folder at `path` is, located as [`ScriptScope::locate`] locates it.
/// What the file or folder at `path` is, located as [`ScriptScope::locate`] locates it. Whether
/// it is hidden is a link's own, and the rest is what the link leads to.
pub(crate) fn stat(&self, path: &Path) -> Result<ScriptEntry, ScriptRead> {
let real = self.locate(path)?;
let meta = std::fs::metadata(&real).map_err(|e| ScriptRead::Failed(e.to_string()))?;
let link = std::fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_symlink());
let own = std::fs::symlink_metadata(path).ok().filter(|m| m.file_type().is_symlink());
let link = own.is_some();
#[cfg(windows)]
let hidden = std::os::windows::fs::MetadataExt::file_attributes(&meta) & 2 != 0;
let hidden = std::os::windows::fs::MetadataExt::file_attributes(own.as_ref().unwrap_or(&meta)) & 2 != 0;
#[cfg(not(windows))]
let hidden = real.file_name().is_some_and(|n| n.to_string_lossy().starts_with('.'));
let hidden = if link { path.file_name() } else { real.file_name() }.is_some_and(|n| n.to_string_lossy().starts_with('.'));
Ok(ScriptEntry {
dir: meta.is_dir(),
file: meta.is_file(),
@@ -925,8 +977,13 @@ mod tests {
#[test]
fn a_narrowed_scope_keeps_the_script_gates_of_both() {
let (base, _) = folders("narrowed-gate");
let gate =
|dir: &str| ScriptGate { read: ScriptScope::of_folder(&base.join(dir)), write: ScriptScope::default(), documents: vec![], also: None };
let gate = |dir: &str| ScriptGate {
read: ScriptScope::of_folder(&base.join(dir)),
write: ScriptScope::default(),
documents: vec![],
linked: LinkedFiles::default(),
also: None,
};
let (inside, other) = (s(base.join("in/a.svg")), s(base.join("outside/secret.svg")));
let reads = |saved: ScopeHandle, gate_here: Option<ScriptGate>| {
let narrowed = match gate_here {
@@ -949,7 +1006,13 @@ mod tests {
#[test]
fn a_scope_narrowed_several_times_keeps_every_gate() {
let (base, _) = folders("narrowed-thrice");
let gate = |dir: &Path| ScriptGate { read: ScriptScope::of_folder(dir), write: ScriptScope::default(), documents: vec![], also: None };
let gate = |dir: &Path| ScriptGate {
read: ScriptScope::of_folder(dir),
write: ScriptScope::default(),
documents: vec![],
linked: LinkedFiles::default(),
also: None,
};
let (inside, other) = (s(base.join("in/a.svg")), s(base.join("outside/secret.svg")));
let narrow = |saved: ScopeHandle, g: ScriptGate| with_script_gate(g, || saved.within_current());
let reads = |h: &ScopeHandle| h.clone().run(|| (check_read(&inside).is_ok(), check_read(&other).is_ok()));
@@ -964,6 +1027,114 @@ mod tests {
let _ = std::fs::remove_dir_all(base);
}
/// A file an open document linked to when the run began is readable through the gate; its path
/// written with `..`, writing it, a file next to it and a file that was not there when the gate
/// was made are not allowed, and the automation roots still apply.
#[test]
fn a_gate_reads_only_the_linked_files_it_was_given() {
let (base, roots) = folders("linked");
let (secret, other) = (base.join("outside/secret.svg"), base.join("outside/other.svg"));
std::fs::write(&other, "<svg/>").unwrap();
let later = base.join("outside/later.svg");
let linked = ScriptGate::real_files([s(secret.clone()), s(later.clone()), s(base.join("outside"))]);
assert_eq!(linked.files.len(), 1, "a missing file and a folder are left out: {linked:?}");
let gate =
ScriptGate { read: ScriptScope::of_folder(&base.join("in")), write: ScriptScope::default(), documents: vec![], linked, also: None };
std::fs::write(&later, "<svg/>").unwrap();
let (read, write) =
(|p: &Path| gate.check(&s(p.to_path_buf()), Access::Read).is_ok(), |p: &Path| gate.check(&s(p.to_path_buf()), Access::Write).is_ok());
assert!(read(&secret));
assert!(!read(&base.join("outside/../outside/secret.svg")), "a path with `..` is refused by its name");
assert!(!write(&secret), "linked files are not written");
assert!(!read(&other), "a file next to a linked one");
assert!(!read(&later), "a file made after the gate");
assert!(!read(&base.join("outside")), "the linked file's folder");
let g = gate.clone();
assert!(confine(Some(&roots), || with_script_gate(g, || check_read(&s(secret.clone())).is_err())), "the roots apply first");
let _ = std::fs::remove_dir_all(base);
}
/// A linked file in a folder the script's scope keeps out, such as the settings folder, is not
/// read through the gate; one in a place left open there is.
#[test]
fn a_gate_reads_no_linked_file_in_a_folder_kept_out() {
let (base, _) = folders("linked-fenced");
let (kept, open) = (base.join("outside/kept.svg"), base.join("outside/open/a.svg"));
std::fs::create_dir_all(base.join("outside/open")).unwrap();
std::fs::write(&kept, "<svg/>").unwrap();
std::fs::write(&open, "<svg/>").unwrap();
let real = |p: &Path| resolve(&s(p.to_path_buf())).unwrap();
let mut read = ScriptScope::of_folder(&base.join("in"));
read.fence(real(&base.join("outside")), &[real(&base.join("outside/open"))]);
let gate = ScriptGate {
read,
write: ScriptScope::default(),
documents: vec![],
linked: ScriptGate::real_files([s(kept.clone()), s(open.clone())]),
also: None,
};
assert!(gate.check(&s(kept), Access::Read).is_err(), "in the folder kept out");
assert!(gate.check(&s(open), Access::Read).is_ok(), "in a place left open");
let _ = std::fs::remove_dir_all(base);
}
/// A path read through the linked files gives no access to the file it leads to after it is
/// pointed elsewhere by a link in one of its folders.
#[test]
fn a_path_read_through_a_linked_file_gives_nothing_once_it_leads_elsewhere() {
let (base, _) = folders("linked-redirected");
#[cfg(unix)]
let made = |target: &Path, link: &Path| std::os::unix::fs::symlink(target, link).is_ok();
#[cfg(windows)]
let made = |target: &Path, link: &Path| std::os::windows::fs::symlink_dir(target, link).is_ok();
#[cfg(not(any(unix, windows)))]
let made = |_: &Path, _: &Path| false;
let (first, second, via) = (base.join("outside/first"), base.join("outside/second"), base.join("outside/via"));
for dir in [&first, &second] {
std::fs::create_dir_all(dir).unwrap();
std::fs::write(dir.join("a.svg"), "<svg/>").unwrap();
}
// Windows needs Developer Mode or elevation to make links: nothing to test without them.
if !made(&first, &via) {
eprintln!("skipped: symbolic links can't be made here");
let _ = std::fs::remove_dir_all(base);
return;
}
let (doc, elsewhere) = (s(via.join("a.svg")), s(second.join("a.svg")));
let gate = ScriptGate {
read: ScriptScope::default(),
write: ScriptScope::default(),
documents: vec![],
linked: ScriptGate::real_files([doc.clone()]),
also: None,
};
assert!(gate.check(&doc, Access::Read).is_ok(), "read through the linked file");
std::fs::remove_dir(&via).or_else(|_| std::fs::remove_file(&via)).unwrap();
assert!(made(&second, &via));
for (path, access) in [(&doc, Access::Read), (&doc, Access::Write), (&elsewhere, Access::Read), (&elsewhere, Access::Write)] {
assert!(gate.check(path, access).is_err(), "{path} {access:?}");
}
let _ = std::fs::remove_dir_all(base);
}
/// A link to a linked file read through the gate counts only while it leads to that file.
#[cfg(unix)]
#[test]
fn a_gate_refuses_a_link_that_now_leads_elsewhere() {
let (base, _) = folders("linked-moved");
let (secret, other, link) = (base.join("outside/secret.svg"), base.join("outside/other.svg"), base.join("outside/link.svg"));
std::fs::write(&other, "<svg/>").unwrap();
std::os::unix::fs::symlink(&secret, &link).unwrap();
let linked = ScriptGate::real_files([s(link.clone())]);
let gate = ScriptGate { read: ScriptScope::default(), write: ScriptScope::default(), documents: vec![], linked, also: None };
assert!(gate.check(&s(link.clone()), Access::Read).is_ok() && gate.check(&s(secret.clone()), Access::Read).is_ok());
std::fs::remove_file(&link).unwrap();
std::os::unix::fs::symlink(&other, &link).unwrap();
assert!(gate.check(&s(link.clone()), Access::Read).is_err(), "the link leads to another file now");
assert!(gate.check(&s(other), Access::Read).is_err());
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn network_paths_are_told_by_name() {
for p in [r"\\server\share\x.svg", "//server/share/x.svg", r"\\?\UNC\server\share\x.svg", r"\\?\unc\server\share"] {
+8
View File
@@ -10,6 +10,9 @@ pub struct Interaction {
pub preview: Option<(String, Value)>,
/// A replaced or canceled preview restores these new-art paints from before the interaction.
pub(crate) paint: vectorcraft_tools::PaintDefaults,
/// A preview of the interaction gave `defaultsOnly: true`: every later preview and a cancel put
/// `paint` back, whichever preview is the latest.
pub(crate) used_defaults_only: bool,
/// An accepted batch preview uses these final paints after changing the document color mode.
pub(crate) preview_paint: Option<vectorcraft_tools::PaintDefaults>,
/// Conversion of new-art paints waits until a color-mode preview is accepted.
@@ -33,6 +36,9 @@ pub struct Interaction {
/// The bounding box of `selection` in `doc`, measured once for a move drag
/// ([`crate::Session::move_drag_box`]): each step offsets it by the drag's move.
pub(crate) move_box: std::sync::OnceLock<Option<vectorcraft_doc::OrientedBox>>,
/// A switch to another document keeps the previews as one undo step in this one, as a panel field's scrub keeps
/// its edits; otherwise the switch cancels the interaction, as it does a drag.
pub keep_on_switch: bool,
}
/// What Object → Transform → Transform Again (⌘D) repeats ([`SessionState::last_transform`]).
@@ -55,6 +61,8 @@ pub(crate) struct PreviewCopies {
pub(crate) from: Arc<Document>,
/// The transform or perspective edit copied these objects.
pub(crate) roots: Vec<NodeId>,
/// Each copy is directly below its original, not above it.
pub(crate) below: bool,
/// This is `from` with the copies added, untransformed.
pub(crate) doc: Arc<Document>,
/// This is the selection after copying, with the copies selected.
+22 -3
View File
@@ -75,8 +75,9 @@ pub struct Session {
/// back as it was at the release ([`Session::pointer`]).
pub(crate) lender: Option<Box<dyn Tool>>,
/// Set while tool actions that end by switching back to the Live Paint Bucket are applied (the
/// Eyedropper's sample into a stop of the bucket's gradient): their paint commands change the
/// colors the bucket paints with ([`Session::bucket_paints`]).
/// Eyedropper's sample into a stop of the bucket's gradient), and while a tool the bucket lent
/// is deactivated as it goes back: their paint commands change the colors the bucket paints
/// with ([`Session::bucket_paints`]).
pub(crate) back_to_bucket: bool,
/// Pointer and key input that came while the tool computed an edit on another thread, each with
/// its number and view, made in order once the edit is applied.
@@ -106,6 +107,19 @@ pub struct Session {
/// The selection tool chosen last (Selection, Direct Selection or Group Selection): the one Cmd
/// lends the other tools. None until one is chosen.
pub(crate) last_selection_tool: Option<&'static str>,
/// Direct Selection or Group Selection, whichever was chosen last: the one Cmd lends the
/// Selection tool. None until one is chosen.
pub(crate) last_part_selection_tool: Option<&'static str>,
/// The selection tool Cmd lent the last press, which also takes the double-click or
/// triple-click that follows it, with the uid of the document and the id of the tool it was
/// lent from: a follow-up in another document, after a tool switch (also one back to the same
/// tool) or after the tool starts afresh is not lent. None when the press was not lent.
pub(crate) press_lent: Option<(Option<u64>, &'static str, &'static str)>,
/// The selection tool a Cmd press would borrow at the pointer, as [`Session::hover_tool_at`]
/// or [`Session::cursor`] last found it with Cmd held (None inside when it found none), with
/// the document state, active tool and keys it was found for. None when it was last asked
/// without Cmd.
pub(crate) hover_lent: Option<(tooling::HoverKey, Option<&'static str>)>,
pub(crate) last_view: ViewInfo,
/// The selection tools' measurements for the active document as it is: a pointer move or a
/// cursor asked for again over an unchanged document and selection measures nothing again.
@@ -234,6 +248,11 @@ pub struct Session {
/// The running top-level query command changed the selection and is journaled like any other
/// command ([`Session::journal_query`]).
journal_query: bool,
/// The running top-level command changed only the paint defaults, as the Live Paint Bucket
/// or `defaultsOnly: true` has a paint command do, when new art would have taken this
/// appearance (none: nothing selected): unless a later batch step changes it, the selection's
/// appearance does not replace the defaults afterwards ([`Session::inherit_new_art`]).
pub(crate) defaults_only_ran: Option<Option<cmd::newart::NewArtSource>>,
/// From `edit.undoGroup.begin` to `edit.undoGroup.end`: the name of the undo step (`None`: after
/// its first edit). Each document opened or created meanwhile opens an undo group of its own
/// ([`Session::add_document`]). `None` otherwise.
@@ -435,7 +454,7 @@ pub(crate) use command_sets::SELECTS_GIVEN_IDS;
#[cfg(test)]
use command_sets::given_ids;
pub use command_sets::{DRAWS_SHAPE, FIT_ACTIVE_ARTBOARD, ON_ACTIVE_ARTBOARD, waits_for_tool_edit};
pub use doc_state::{DocState, OpenRows, RecalledSelection};
pub use doc_state::{DocState, LayersReveal, OpenRows, RecalledSelection};
pub use error::{EngineError, READ_ONLY_LOCATION, Result, SCRIPT_BUSY};
#[cfg(test)]
use history::history_budget_for;
+23
View File
@@ -55,6 +55,12 @@ pub struct Prefs {
/// re-mapped by the turn, scale and move that take its old ends to its new ends. Off (the
/// default), the handles of a moved anchor move with it and the other handles stay.
pub interpolate_control_points: bool,
/// General › Delete Removes Anchor Points and Keeps Paths Joined: the default of the
/// `keepJoined` param of `edit.clear` (the Delete and Backspace keys and Edit › Clear). On,
/// Clear removes the direct-selected anchors of a path as Remove Anchor Points does, refitting
/// the curve around each one, instead of deleting them with their segments. Off (the default),
/// Clear opens the path there.
pub delete_keeps_paths_joined: bool,
pub use_precise_cursors: bool,
pub show_tool_tips: bool,
/// General › Show Tool Cards: with tool tips on, a tool button's tool tip is a card with what the
@@ -281,6 +287,10 @@ pub struct Prefs {
pub recovery_off_for_complex: bool,
pub recent_files_count: u32,
pub low_res_proxy_eps: bool,
/// File Handling › Use fonts embedded in imported PDFs: type in a font a PDF embeds and this
/// machine lacks is drawn in the file's own glyphs (on by default); off, it is set in the
/// fallback font with the missing-font warning (#4568).
pub pdf_import_embedded_fonts: bool,
pub anti_aliased_bitmaps: bool,
pub update_links: String,
/// PDF Text: what the text of a PDF, `.ai` or `.ait` file opened or placed from the app
@@ -446,6 +456,17 @@ pub const KEY_HOLD_DELAY: f64 = 0.35;
pub const KEY_HOLD_DELAY_RANGE: (f64, f64) = (0.2, 1.0);
impl Prefs {
/// The `document.open` / place params `p` with `embeddedFonts: false` added when Preferences
/// › File Handling › Use fonts embedded in imported PDFs is off and `p` gives no choice of its own.
pub fn with_pdf_font_choice(&self, p: &serde_json::Value) -> serde_json::Value {
if self.pdf_import_embedded_fonts || p.get("embeddedFonts").is_some_and(|v| !v.is_null()) {
return p.clone();
}
let mut out = if p.is_object() { p.clone() } else { serde_json::json!({}) };
out["embeddedFonts"] = serde_json::json!(false);
out
}
/// The Hold Shortcut Delay in seconds, inside its range. A restored settings file is not
/// checked against the range, so a value outside it is brought inside, and one that is not a
/// number gives the default.
@@ -464,6 +485,7 @@ impl Default for Prefs {
corner_radius: 12.0,
disable_auto_add_delete: false,
interpolate_control_points: false,
delete_keeps_paths_joined: false,
use_precise_cursors: false,
show_tool_tips: true,
show_tool_cards: false,
@@ -592,6 +614,7 @@ impl Default for Prefs {
recovery_off_for_complex: false,
recent_files_count: 20,
low_res_proxy_eps: false,
pdf_import_embedded_fonts: true,
anti_aliased_bitmaps: false,
update_links: s("askWhenModified"),
pdf_text_as: s("text"),
+382 -71
View File
@@ -13,9 +13,25 @@
//! changed document; a change that changes nothing runs no command. A change to a document that is
//! not the active one makes it active for the command and makes the other one active again after.
//!
//! VectorCraft's own rules, which the help pages do not state:
//! - Collections list documents in tab order and art in paint order (bottom first), counted from 0.
//! `pageItems` lists every object, with the objects inside groups and compound paths after the
//! Collections are counted from 0, and `pageItems` lists art topmost first, as
//! <https://ai-scripting.docsforadobe.dev/jsobjref/CMYKColor/> reads the frontmost path as
//! `pathItems[0]`. A collection read with a name, `pageItems["name"]`, gives the object `getByName`
//! gives, and a script may name the application's members without `app.`, as
//! <https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/> describes; here
//! that holds for `activeDocument`, `documents` and `selection`.
//!
//! VectorCraft's own rules:
//! - A document's selection lists the selected objects topmost first, as `pageItems` does, whatever
//! order they were selected or made in. The objectReferences page above says instead that the
//! first object is the one last added to the page; VectorCraft does not follow that sentence.
//! - A collection read with a name that nothing has throws `Not found`, and `"name" in pageItems` is
//! false then. Assigning to such a name throws the same error.
//! - Assigning `activeDocument` or `selection` without `app.` assigns `app.activeDocument` or the
//! active document's selection. A top-level `var selection = ...` does the same and does
//! not make a variable of the script. Assigning `documents` keeps its value.
//! - Collections list documents in tab order. The objectReferences page says `documents[0]` is
//! always the active document; VectorCraft does not follow that yet.
//! - `pageItems` lists every object, with the objects inside groups and compound paths after the
//! group or compound path, and leaves out layers and ruler guides. An index out of range gives
//! `undefined`; `index` and `getByName` throw `Not found` when nothing matches.
//! - Script coordinates are points with Y up from the bottom of the first artboard
@@ -26,8 +42,20 @@
//! - Assigning `Document.selection` takes one object, a list of them, `null` or `[]`; every object
//! must be one of that document's that can be selected, or nothing changes.
//! - Members the help pages list that are not here yet throw an error that says so.
//! - Assigning `hidden`, `locked`, `opacity`, `position`, `left`, `top`, `width` or `height` to an
//! object in a hidden or locked layer, and `zOrder()` on one, throw `Cannot edit` and change
//! nothing, even for the value the object has. The exception is `opacity` given the value the
//! object has when that changes nothing; on a graph's mark or label whose series or kind keeps
//! another opacity it would still change the graph, so it is refused too. Its `name` and `note`
//! still change. An object that is hidden or locked itself, or is in a hidden or locked group,
//! takes them.
//! - `name` and `note` take a number or a Boolean as the text `String(value)` gives.
//! - A compound path whose last path `move` or `remove()` takes out stays, empty.
//! - An object with nothing in it, such as an empty group or a compound path whose paths moved out,
//! reads its bounds, `position`, `width` and `height` as zeros, and assigning them does nothing.
use std::cell::{Cell, RefCell};
use std::collections::{HashMap, HashSet};
use std::rc::Rc;
use std::sync::Arc;
@@ -86,13 +114,15 @@ pub(super) enum Coords {
const DOCUMENT_COORDS: &str = "CoordinateSystem.DOCUMENTCOORDINATESYSTEM";
const ARTBOARD_COORDS: &str = "CoordinateSystem.ARTBOARDCOORDINATESYSTEM";
/// What the object model keeps for one run: its coordinate system, the last list of a document's
/// page items, kept while that document is unchanged, whether a call's own savepoint
/// ([`atomically`]) is open, and the settings of each `DocumentPreset` the run made.
/// What the object model keeps for one run: its coordinate system, the lists of page items and the
/// answers of which objects are on a locked artboard for the last [`ITEM_LISTS`] documents read,
/// each kept while its document is unchanged, whether a call's own savepoint ([`atomically`]) is
/// open, and the settings of each `DocumentPreset` the run made.
#[derive(Default)]
pub(super) struct State {
coords: Cell<Coords>,
items: RefCell<Option<ItemList>>,
items: RefCell<Vec<ItemList>>,
locked: RefCell<Vec<LockedList>>,
saving: Cell<bool>,
presets: RefCell<Vec<Vec<(String, Data)>>>,
text: text::TextState,
@@ -135,6 +165,57 @@ fn atomically<T>(h: &Host, f: impl FnOnce(&Host) -> std::result::Result<T, HostE
/// A document's uid, the document as it was, and the ids of its page items then.
type ItemList = (u64, Arc<Document>, Rc<Vec<NodeId>>);
/// A document's uid, the document and its new art ([`Document::new_art`]) as they were, and for
/// each object of a layer or sublayer asked about then, whether it was on a locked artboard.
type LockedList = (u64, Arc<Document>, Arc<HashSet<NodeId>>, HashMap<NodeId, bool>);
/// How many documents' lists [`State`] keeps at once, of each kind.
const ITEM_LISTS: usize = 4;
/// The kept list of the document `uid` as `doc` is, if there is one.
fn kept_items(lists: &[ItemList], uid: u64, doc: &Arc<Document>) -> Option<Rc<Vec<NodeId>>> {
lists.iter().find(|(u, d, _)| *u == uid && Arc::ptr_eq(d, doc)).map(|(_, _, ids)| ids.clone())
}
/// Keeps `list` in place of any earlier list of the same document, dropping the least recently
/// kept list beyond [`ITEM_LISTS`].
fn keep_items(lists: &mut Vec<ItemList>, list: ItemList) {
lists.retain(|(u, _, _)| *u != list.0);
if lists.len() >= ITEM_LISTS {
lists.remove(0);
}
lists.push(list);
}
/// Whether node `id` of `st` is on a locked artboard ([`Document::on_locked_artboard`]). Each
/// object of a layer or sublayer is measured once while the document and its new art stay as they
/// are, so the members of a group are answered with one measurement of the group.
fn on_locked_artboard(h: &Host, st: &DocState, id: NodeId) -> bool {
if !st.doc.artboards.iter().any(|a| a.locked) {
return false;
}
let Some(object) = st.doc.layer_object(id).map(|n| n.id) else {
return false;
};
let new_art = st.doc.new_art.get();
let mut lists = h.dom.locked.borrow_mut();
let at = match lists.iter().position(|(u, d, n, _)| *u == st.uid && Arc::ptr_eq(d, &st.doc) && Arc::ptr_eq(n, &new_art)) {
Some(at) => at,
None => {
lists.retain(|(u, ..)| *u != st.uid);
if lists.len() >= ITEM_LISTS {
lists.remove(0);
}
lists.push((st.uid, st.doc.clone(), new_art, HashMap::new()));
lists.len() - 1
}
};
match lists.get_mut(at) {
Some((.., held)) => *held.entry(object).or_insert_with(|| st.doc.on_locked_artboard(object)),
None => st.doc.on_locked_artboard(object),
}
}
type Answer = std::result::Result<Data, HostError>;
/// A member function: the run's host and the call's arguments, `this` first.
@@ -162,7 +243,8 @@ fn method(link: &Link, f: Member) -> HostMember {
}
/// A member the help pages list that is not available yet: reading or assigning it throws, after
/// the check that a document, page item or text range `this` is still there.
/// the check that a document, page item or text range `this` is still there. `hasOwnProperty` is
/// false for it, so a script that checks for the member first skips it.
fn later(link: &Link, class: &'static str, name: &'static str) -> (String, HostMember) {
let message = format!("{class}.{name} is not available yet");
let l = link.clone();
@@ -183,7 +265,7 @@ fn later(link: &Link, class: &'static str, name: &'static str) -> (String, HostM
}
Err(HostError::Error(message.clone()))
});
(name.to_string(), HostMember::Property { get: f.clone(), set: f })
(name.to_string(), HostMember::Unavailable(f))
}
fn text(s: impl Into<String>) -> Data {
@@ -345,31 +427,30 @@ fn item_ref(h: &Host, st: &DocState, id: NodeId) -> Data {
}
}
/// The ids of a document's page items in paint order ([`State`] keeps the last list).
/// The ids of a document's page items, topmost first, each group or compound path before the
/// objects in it ([`State`] keeps the lists of the last documents read).
fn page_items(h: &Host, st: &DocState) -> Rc<Vec<NodeId>> {
if let Some((uid, doc, ids)) = &*h.dom.items.borrow()
&& *uid == st.uid
&& Arc::ptr_eq(doc, &st.doc)
{
return ids.clone();
if let Some(ids) = kept_items(&h.dom.items.borrow(), st.uid, &st.doc) {
return ids;
}
fn walk(nodes: &[Arc<crate::doc::Node>], out: &mut Vec<NodeId>) {
for n in nodes {
for n in nodes.iter().rev() {
match &n.kind {
NodeKind::Layer { children, .. } => walk(children, out),
NodeKind::RulerGuide { .. } => {}
NodeKind::Group { children, .. } | NodeKind::Compound { children, .. } => {
_ => {
out.push(n.id);
walk(children, out);
if let Some(children) = n.children() {
walk(children, out);
}
}
_ => out.push(n.id),
}
}
}
let mut ids = Vec::new();
walk(&st.doc.layers, &mut ids);
let ids = Rc::new(ids);
*h.dom.items.borrow_mut() = Some((st.uid, st.doc.clone(), ids.clone()));
keep_items(&mut h.dom.items.borrow_mut(), (st.uid, st.doc.clone(), ids.clone()));
ids
}
@@ -544,6 +625,31 @@ fn done_unless_refused(r: std::result::Result<Data, HostError>) -> std::result::
}
}
/// Makes `layer` the current layer of the active document `uid` again, with `rows` the highlighted
/// Layers panel rows, after selecting objects made the layer of the last of them current and
/// cleared the rows. Nothing runs when `layer` is gone. `layer.highlight` puts the rows back when
/// they changed, and then `layer.setCurrent` with `keepRows` makes `layer` current when it is not.
fn restore_layer(h: &Host, uid: u64, layer: Option<NodeId>, rows: &[NodeId]) -> std::result::Result<(), HostError> {
let Some(layer) = layer else { return Ok(()) };
let rows = {
let s = h.session.borrow();
let Some(st) = s.active().filter(|st| st.uid == uid) else { return Ok(()) };
if st.doc.node(layer).is_none() {
return Ok(());
}
let rows: Vec<NodeId> = rows.iter().copied().filter(|r| st.doc.node(*r).is_some()).collect();
(st.highlighted_rows() != rows).then(|| rows.iter().map(|r| r.0).collect::<Vec<_>>())
};
if let Some(rows) = rows {
command(h, "layer.highlight", &json!({"ids": rows, "mode": "set"}))?;
}
let current = h.session.borrow().active().is_some_and(|st| st.active_layer == Some(layer));
if !current {
command(h, "layer.setCurrent", &json!({"id": layer.0, "keepRows": true}))?;
}
Ok(())
}
/// Runs `f` with the document `uid` active, and makes the document that was active before active
/// again after. With `keep_selection`, the document's selection is put back as it was when `f`'s
/// commands changed it (commands given ids select them first), direct-selected anchors, segments,
@@ -556,10 +662,11 @@ fn on_doc<T>(
keep_selection: bool,
f: impl FnOnce(&Host) -> std::result::Result<T, HostError>,
) -> std::result::Result<T, HostError> {
let (index, active, before) = {
let (index, active, before, layer) = {
let s = h.session.borrow();
let index = s.documents().iter().position(|d| d.uid == uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?;
(index, s.active_index(), s.documents()[index].selection.clone())
let st = &s.documents()[index];
(index, s.active_index(), st.selection.clone(), (st.active_layer, st.highlighted_rows()))
};
let switch = active != Some(index);
if switch {
@@ -575,6 +682,9 @@ fn on_doc<T>(
if let Some(doc) = doc {
restored = restore_selection(h, &doc, &before);
}
if restored.is_ok() {
restored = restore_layer(h, uid, layer.0, &layer.1);
}
}
// The document that was active is active again before any error is given: `f`'s error first,
// then the selection's, then the switch back's.
@@ -632,6 +742,18 @@ fn app_selection(h: &Host, _: &[Data]) -> Answer {
}
}
/// `app.selection = objects`: the active document's selection, as `selection` of that document is
/// assigned.
fn app_set_selection(h: &Host, a: &[Data]) -> Answer {
let doc = {
let s = h.session.borrow();
let active = s.active_index().and_then(|index| s.documents().get(index).map(|st| Doc { index, uid: st.uid }));
active.ok_or_else(|| HostError::Error(NO_ACTIVE_DOCUMENT.into()))?
};
let ids = selection_ids(h, doc, arg(a, 1))?;
set_selection(h, doc, ids)
}
fn app_coords(h: &Host, _: &[Data]) -> Answer {
Ok(text(if h.dom.coords.get() == Coords::Document { DOCUMENT_COORDS } else { ARTBOARD_COORDS }))
}
@@ -678,10 +800,15 @@ fn app_ref(_: &Host, _: &[Data]) -> Answer {
Ok(host_ref("Application", &[]))
}
/// `documents[i]`, and `documents["name"]` as `getByName` reads it.
fn docs_at(h: &Host, a: &[Data]) -> Answer {
let s = h.session.borrow();
let at = match arg(a, 1) {
Data::Number(n) => whole(*n).and_then(|i| usize::try_from(i).ok()).and_then(|i| s.documents().get(i)),
Data::String(name) => match s.documents().iter().find(|d| d.title() == *name) {
None if !probing(a) => return Err(HostError::Error(NOT_FOUND.into())),
found => found,
},
_ => None,
};
Ok(at.map_or(Data::Undefined, |st| doc_ref(h, st.uid)))
@@ -820,7 +947,10 @@ impl NewDoc<'_> {
if let Some(d) = self.preview {
let mode = match d {
Data::String(s) if s == "DocumentPreviewMode.DefaultPreview" => "default",
Data::String(s) if s == "DocumentPreviewMode.PixelPreview" => "pixel",
// Pixel Preview is a setting of the app's view, which a script cannot turn on.
Data::String(s) if s == "DocumentPreviewMode.PixelPreview" => {
return Err(HostError::Error("DocumentPreviewMode.PixelPreview is not available yet".into()));
}
Data::String(s) if s == "DocumentPreviewMode.OverprintPreview" => "overprint",
_ => return Err(HostError::Type("previewMode must be a DocumentPreviewMode value".into())),
};
@@ -897,6 +1027,9 @@ fn docs_add_document(h: &Host, a: &[Data]) -> Answer {
None | Some(Data::Null) => Vec::new(),
Some(d) => {
let i = preset_of(h, d).ok_or_else(|| HostError::Type("presetSettings must be a DocumentPreset".into()))?;
// The settings are charged as data passed to the call before they are copied.
let bytes = h.dom.presets.borrow()[i].iter().map(|(k, v)| k.len() as u64 + 2 + data_size(v)).sum::<u64>();
h.charge_call(bytes)?;
h.dom.presets.borrow()[i].clone()
}
};
@@ -944,6 +1077,10 @@ fn docs_add_document(h: &Host, a: &[Data]) -> Answer {
let reason = e["reason"].as_str().unwrap_or_default();
return Err(HostError::Error(format!("the New Document profile {profile} could not be read: {reason}")));
}
// Each warning from reading the profile's file goes to the console.
for w in value.get("warnings").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str) {
super::each_line(&format!("addDocument: {w}"), |line, cut| h.line(super::console::Entry::Log(line), cut));
}
let s = h.session.borrow();
let st = s.active().ok_or_else(|| HostError::Error(NO_ACTIVE_DOCUMENT.into()))?;
Ok(doc_ref(h, st.uid))
@@ -1010,8 +1147,11 @@ fn preset_field(link: &Link, key: &'static str) -> HostMember {
let l = link.clone();
let get: HostFunction = Rc::new(move |a: Vec<Data>| {
let h = current(&l)?;
h.charge_call(16)?;
let i = preset_of(&h, arg(&a, 0)).ok_or_else(not_preset)?;
// The value handed back is charged as the setter charges it, before it is copied.
let i = preset_of(&h, arg(&a, 0));
let bytes = i.map_or(0, |i| h.dom.presets.borrow()[i].iter().find(|(k, _)| k == key).map_or(0, |(_, v)| data_size(v)));
h.charge_call(16 + bytes)?;
let i = i.ok_or_else(not_preset)?;
let presets = h.dom.presets.borrow();
Ok(presets[i].iter().find(|(k, _)| k == key).map_or(Data::Undefined, |(_, v)| v.clone()))
});
@@ -1137,19 +1277,37 @@ fn doc_selection(h: &Host, a: &[Data]) -> Answer {
selection_of(h, doc.uid)
}
/// The selection of the document `uid`: `null` when nothing is selected, otherwise a new list of
/// the selected objects.
/// The selection of the document `uid`: a new list of the selected objects, topmost first as
/// `pageItems` lists them, empty when nothing is selected.
fn selection_of(h: &Host, uid: u64) -> Answer {
let s = h.session.borrow();
let st = s.documents().iter().find(|d| d.uid == uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?;
let ids: Vec<NodeId> = st.selection.objects.iter().copied().filter(|i| st.doc.node(*i).and_then(typename).is_some()).collect();
if ids.is_empty() {
return Ok(Data::Null);
}
if ids.len() > MAX_LISTED {
let picked: HashSet<NodeId> = st.selection.objects.iter().copied().filter(|i| st.doc.node(*i).and_then(typename).is_some()).collect();
if picked.len() > MAX_LISTED {
return Err(HostError::Range(format!("the selection has more than {MAX_LISTED} objects")));
}
h.charge_call(16 * ids.len() as u64)?;
// Only the selected objects are ordered, by their place in the tree, so the cost follows the
// size of the selection and not of the document. `pageItems` walks each list of children
// topmost first and puts a group before the objects in it: a higher index comes first, and an
// ancestor's path, a prefix of its descendants' paths, sorts before them.
let mut placed: Vec<(Vec<std::cmp::Reverse<usize>>, NodeId)> = Vec::with_capacity(picked.len());
let mut unplaced: Vec<NodeId> = Vec::new();
let mut seen: HashSet<NodeId> = HashSet::with_capacity(picked.len());
let mut steps = 0u64;
for id in st.selection.objects.iter().copied().filter(|i| picked.contains(i) && seen.insert(*i)) {
match st.doc.index_path(id) {
Some(path) => {
steps += path.len() as u64;
placed.push((path.into_iter().map(std::cmp::Reverse).collect(), id));
}
// A selected object outside the tree's walk still comes last, in the order it was
// selected.
None => unplaced.push(id),
}
}
placed.sort();
let ids: Vec<NodeId> = placed.into_iter().map(|(_, id)| id).chain(unplaced).collect();
h.charge_call(steps + 16 * ids.len() as u64)?;
Ok(Data::Array(ids.iter().map(|i| item_ref(h, st, *i)).collect()))
}
@@ -1163,10 +1321,16 @@ fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result<Vec<NodeId
d => vec![d],
};
let mut ids: Vec<NodeId> = Vec::with_capacity(list.len());
for d in list {
let item = item_of(h, d)?;
// The document is read once for every object: nothing changes it while the list is checked.
let (d, isolation, guides_locked) = with_doc(h, doc, |s, st| (st.doc.clone(), st.isolation, s.guides_locked()));
let locks = d.locked_artboards();
for v in list {
let item = item_of(h, v)?;
// A path made into a guide is not selected while Lock Guides is on, as the selection
// commands leave it out.
let ok = item.doc.uid == doc.uid
&& with_doc(h, doc, |_, st| crate::cmd::select::is_selectable(&st.doc, st.isolation, &st.doc.locked_artboards(), item.id));
&& crate::cmd::select::is_selectable(&d, isolation, &locks, item.id)
&& !(guides_locked && crate::is_guide_path(&d, item.id));
if !ok {
let name = with_doc(h, item.doc, |_, st| st.doc.node(item.id).and_then(typename).unwrap_or("page item"));
return Err(HostError::Error(format!("Cannot select {name} {}", item.id.0)));
@@ -1237,8 +1401,21 @@ fn items_parent(h: &Host, a: &[Data]) -> Answer {
Ok(doc_ref(h, doc.uid))
}
/// Whether an indexer was called for `name in collection` ([`vectorcraft_js::HostClass::index`]),
/// where a name nothing has gives `undefined` instead of the `Not found` error a read throws.
fn probing(a: &[Data]) -> bool {
matches!(arg(a, 2), Data::Bool(true))
}
/// `pageItems[i]`, and `pageItems["name"]` as `getByName` reads it.
fn items_at(h: &Host, a: &[Data]) -> Answer {
let doc = items_doc(h, a)?;
if let Data::String(_) = arg(a, 1) {
return match items_by_name(h, a) {
Err(HostError::Error(e)) if e == NOT_FOUND && probing(a) => Ok(Data::Undefined),
r => r,
};
}
let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) };
let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) };
Ok(with_doc(h, doc, |_, st| page_items(h, st).get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id))))
@@ -1335,8 +1512,20 @@ fn set_props(h: &Host, a: &[Data], unchanged: impl FnOnce(&crate::doc::Node) ->
Ok(Data::Undefined)
}
/// The text a string property such as `name` or `note` is given: a number or a Boolean becomes the
/// text `String(value)` gives, and any other value that is not a string is refused.
fn text_arg(v: &Data, what: &str) -> std::result::Result<String, HostError> {
match v {
Data::String(s) => Ok(s.clone()),
Data::Number(n) => Ok(vectorcraft_js::number_to_string(*n)),
Data::Bool(b) => Ok(b.to_string()),
_ => Err(HostError::Type(format!("{what} must be a string"))),
}
}
/// `name = value`: a number or a Boolean becomes the text `String(value)` gives.
fn item_set_name(h: &Host, a: &[Data]) -> Answer {
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("name must be a string".into())) };
let name = &text_arg(arg(a, 1), "name")?;
if name.len() > MAX_TEXT_BYTES {
return Err(HostError::Range("the name is too long".into()));
}
@@ -1351,9 +1540,10 @@ fn item_note(h: &Host, a: &[Data]) -> Answer {
read_item(h, a, |_, n| Ok(text(note_of(n))))
}
/// `note = text`: the Attributes panel's note, set with `attributes.set`, which trims it.
/// `note = text`: the Attributes panel's note, set with `attributes.set`, which trims it. A number
/// or a Boolean becomes the text `String(value)` gives.
fn item_set_note(h: &Host, a: &[Data]) -> Answer {
let Data::String(note) = arg(a, 1) else { return Err(HostError::Type("note must be a string".into())) };
let note = &text_arg(arg(a, 1), "note")?;
if note.len() > MAX_TEXT_BYTES {
return Err(HostError::Range("the note is too long".into()));
}
@@ -1365,12 +1555,27 @@ fn item_set_note(h: &Host, a: &[Data]) -> Answer {
Ok(Data::Undefined)
}
/// Refuses a change to the item's appearance, place, stacking order or size while a layer it is in
/// is hidden or locked. Its name and note may still change.
fn refuse_in_closed_layer(h: &Host, item: Item) -> std::result::Result<(), HostError> {
let refused = with_doc(h, item.doc, |_, st| {
let d = &st.doc;
let closed = |i: &NodeId| d.node(*i).is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. }) && (!n.visible || n.locked));
d.ancestry(item.id).is_some_and(|a| a.iter().any(closed)).then(|| d.node(item.id).and_then(typename).unwrap_or("page item"))
});
match refused {
Some(name) => Err(HostError::Error(format!("Cannot edit {name} {}: a layer it is in is hidden or locked", item.id.0))),
None => Ok(()),
}
}
fn item_hidden(h: &Host, a: &[Data]) -> Answer {
read_item(h, a, |_, n| Ok(Data::Bool(!n.visible)))
}
fn item_set_hidden(h: &Host, a: &[Data]) -> Answer {
let hidden = boolean(arg(a, 1), "hidden")?;
refuse_in_closed_layer(h, this_item(h, a)?)?;
set_props(h, a, |n| n.visible != hidden, json!({"visible": !hidden}))
}
@@ -1380,6 +1585,7 @@ fn item_locked(h: &Host, a: &[Data]) -> Answer {
fn item_set_locked(h: &Host, a: &[Data]) -> Answer {
let locked = boolean(arg(a, 1), "locked")?;
refuse_in_closed_layer(h, this_item(h, a)?)?;
set_props(h, a, |n| n.locked == locked, json!({"locked": locked}))
}
@@ -1392,7 +1598,24 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer {
if !(0.0..=100.0).contains(&v) {
return Err(HostError::Range("opacity must be from 0 to 100".into()));
}
set_props(h, a, |n| (f64::from(n.opacity) * 100.0 - v).abs() < 1e-4, json!({"opacity": v}))
// A value the getter reports for the item's opacity sends the opacity it has, and
// `object.setProps` finds the no-op itself: an opacity a graph mark or label already has still
// replaces the one the graph keeps for its series or kind.
// The opacity the item already has may be assigned while its layer is hidden or locked, unless
// it would still replace the opacity a graph keeps for the item's series or kind.
let item = this_item(h, a)?;
let (now, keeps_other) = with_doc(h, item.doc, |_, st| {
let d = &st.doc;
// Only the exact number the getter reports counts as the same opacity.
let now = d.node(item.id).map(|n| f64::from(n.opacity) * 100.0).filter(|now| (now * 1e4).round() / 1e4 == v);
let keeps_other =
crate::cmd::graph::series_object_opacity_differs(d, &[item.id]) || crate::cmd::graph::label_object_opacity_differs(d, &[item.id]);
(now, keeps_other)
});
if now.is_none() || keeps_other {
refuse_in_closed_layer(h, item)?;
}
set_props(h, a, |_| false, json!({"opacity": now.unwrap_or(v)}))
}
fn item_selected(h: &Host, a: &[Data]) -> Answer {
@@ -1415,18 +1638,19 @@ fn item_set_selected(h: &Host, a: &[Data]) -> Answer {
}
/// The item's geometric bounds (`visual`: its visible bounds) in document coordinates and the
/// document's [`Frame`].
fn item_rect(h: &Host, item: Item, visual: bool) -> std::result::Result<(Rect, Frame), HostError> {
with_doc(h, item.doc, |_, st| {
let r = st.doc.bounds_of(&[item.id], visual).ok_or_else(|| HostError::Error("the object has no bounds".into()))?;
Ok((r, frame(st)?))
})
/// document's [`Frame`]. An object with nothing in it, such as an empty group or a compound path
/// whose paths moved out, has no bounds: its bounds read as zeros, and moving or resizing it does
/// nothing.
fn item_rect(h: &Host, item: Item, visual: bool) -> std::result::Result<(Option<Rect>, Frame), HostError> {
with_doc(h, item.doc, |_, st| Ok((st.doc.bounds_of(&[item.id], visual), frame(st)?)))
}
fn bounds(h: &Host, a: &[Data], visual: bool) -> Answer {
let item = this_item(h, a)?;
let (r, f) = item_rect(h, item, visual)?;
Ok(f.bounds(h.dom.coords.get(), r))
match item_rect(h, item, visual)? {
(Some(r), f) => Ok(f.bounds(h.dom.coords.get(), r)),
(None, _) => Ok(Data::Array(vec![num(0.0), num(0.0), num(0.0), num(0.0)])),
}
}
fn item_geometric(h: &Host, a: &[Data]) -> Answer {
@@ -1439,8 +1663,10 @@ fn item_visible(h: &Host, a: &[Data]) -> Answer {
fn item_position(h: &Host, a: &[Data]) -> Answer {
let item = this_item(h, a)?;
let (r, f) = item_rect(h, item, false)?;
Ok(pair(f.to_script(h.dom.coords.get(), Point::new(r.x0, r.y0))))
match item_rect(h, item, false)? {
(Some(r), f) => Ok(pair(f.to_script(h.dom.coords.get(), Point::new(r.x0, r.y0)))),
(None, _) => Ok(pair([0.0, 0.0])),
}
}
fn item_left(h: &Host, a: &[Data]) -> Answer {
@@ -1459,19 +1685,20 @@ fn item_top(h: &Host, a: &[Data]) -> Answer {
fn item_width(h: &Host, a: &[Data]) -> Answer {
let item = this_item(h, a)?;
Ok(num(item_rect(h, item, false)?.0.width()))
Ok(num(item_rect(h, item, false)?.0.map_or(0.0, |r| r.width())))
}
fn item_height(h: &Host, a: &[Data]) -> Answer {
let item = this_item(h, a)?;
Ok(num(item_rect(h, item, false)?.0.height()))
Ok(num(item_rect(h, item, false)?.0.map_or(0.0, |r| r.height())))
}
/// Moves the item so its top-left corner is at `x` and `y` in script coordinates (`None`: that one
/// stays).
fn move_to(h: &Host, a: &[Data], x: Option<f64>, y: Option<f64>) -> Answer {
let item = this_item(h, a)?;
let (r, f) = item_rect(h, item, false)?;
refuse_in_closed_layer(h, item)?;
let (Some(r), f) = item_rect(h, item, false)? else { return Ok(Data::Undefined) };
let c = h.dom.coords.get();
let now = f.to_script(c, Point::new(r.x0, r.y0));
let to = f.to_document(c, [x.unwrap_or(now[0]), y.unwrap_or(now[1])]);
@@ -1507,7 +1734,8 @@ fn resize(h: &Host, a: &[Data], width: bool) -> Answer {
return Err(HostError::Range(format!("{what} must be more than 0 and at most 3999856 points")));
}
let item = this_item(h, a)?;
let (r, _) = item_rect(h, item, false)?;
refuse_in_closed_layer(h, item)?;
let (Some(r), _) = item_rect(h, item, false)? else { return Ok(Data::Undefined) };
let now = if width { r.width() } else { r.height() };
if now <= 0.0 {
return Err(HostError::Error(format!("the object has no {what} to scale")));
@@ -1530,9 +1758,11 @@ fn item_set_height(h: &Host, a: &[Data]) -> Answer {
resize(h, a, false)
}
/// `editable`: false for an object that is hidden or locked, in a hidden or locked layer or group,
/// or on a locked artboard.
fn item_editable(h: &Host, a: &[Data]) -> Answer {
let item = this_item(h, a)?;
Ok(Data::Bool(with_doc(h, item.doc, |_, st| editable(&st.doc, item.id))))
Ok(Data::Bool(with_doc(h, item.doc, |_, st| editable(&st.doc, item.id) && !on_locked_artboard(h, st, item.id))))
}
/// The item's place in its parent's stacking order, from 1 at the bottom.
@@ -1544,7 +1774,7 @@ fn item_z_order_position(h: &Host, a: &[Data]) -> Answer {
/// `remove()`: deletes the object. A hidden or locked object, one in a hidden or locked layer or
/// group, a group holding one, or an object on a locked artboard is refused, as [`items_remove_all`]
/// refuses it.
/// refuses it. A compound path whose last path this is stays, empty.
fn item_remove(h: &Host, a: &[Data]) -> Answer {
let item = this_item(h, a)?;
let (whole, on_locked) = with_doc(h, item.doc, |_, st| {
@@ -1556,7 +1786,8 @@ fn item_remove(h: &Host, a: &[Data]) -> Answer {
if on_locked {
return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {}", item.id.0)));
}
edit_item(h, item, "edit.clear", &json!({"ids": [item.id.0]}))?;
// A compound path whose last path this is stays, empty, as it does after `move`.
edit_item(h, item, "edit.clear", &json!({"ids": [item.id.0], "keepEmpty": true}))?;
Ok(Data::Undefined)
}
@@ -1602,9 +1833,9 @@ struct Destination {
}
/// The object a relative object of `move` or `duplicate` names: a page item or a layer of the
/// same document as `item`. A copy (`copy`) may go directly above or below `item` itself, as
/// `layer.move` puts copies.
fn destination(h: &Host, item: Item, target: &Data, how: &Data, copy: bool) -> std::result::Result<Destination, HostError> {
/// same document as `item`. An object may go directly above or below itself: a copy goes there, as
/// `layer.move` puts copies, and a move there leaves the object where it is.
fn destination(h: &Host, item: Item, target: &Data, how: &Data) -> std::result::Result<Destination, HostError> {
let how = placement_of(how)?;
let beside = matches!(how, Placement::Above | Placement::Below);
let handle = handle_of(target, "PageItem").or_else(|| handle_of(target, "Layer"));
@@ -1623,7 +1854,7 @@ fn destination(h: &Host, item: Item, target: &Data, how: &Data, copy: bool) -> s
let d = &st.doc;
let t = d.node(target).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
let inside = d.ancestry(target).is_some_and(|a| a.iter().any(|i| *i == item.id && *i != target));
if inside || (target == item.id && !(copy && beside)) {
if inside || (target == item.id && !beside) {
return Err(HostError::Error("an object cannot go into itself".into()));
}
let (parent, beside) = match how {
@@ -1641,7 +1872,8 @@ fn destination(h: &Host, item: Item, target: &Data, how: &Data, copy: bool) -> s
if !editable(d, parent) {
return Err(HostError::Error("the layer or group is hidden or locked".into()));
}
if !editable(d, item.id) {
// An object on a locked artboard is not moved, as `editable` reads false for it.
if !editable(d, item.id) || on_locked_artboard(h, st, item.id) {
let name = d.node(item.id).and_then(typename).unwrap_or("page item");
return Err(HostError::Error(format!("Cannot move {name} {}", item.id.0)));
}
@@ -1682,14 +1914,19 @@ fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Resul
}
/// `move(relativeObject, insertionLocation?)`: moves the item into or beside `relativeObject`, a
/// page item or a layer of its document (`insertionLocation` defaults to `PLACEATBEGINNING`).
/// page item or a layer of its document (`insertionLocation` defaults to `PLACEATBEGINNING`). An
/// object that is hidden or locked, in a hidden or locked layer or group, or on a locked artboard
/// is refused. Moving an object directly above or below itself leaves it where it is, and a compound
/// path whose last path moves out stays, empty.
fn item_move(h: &Host, a: &[Data]) -> Answer {
let item = this_item(h, a)?;
if matches!(arg(a, 1), Data::Undefined) {
return Err(HostError::Type("move needs a relative object".into()));
}
let to = destination(h, item, arg(a, 1), arg(a, 2), false)?;
place(h, item.doc, item.id, &to)?;
let to = destination(h, item, arg(a, 1), arg(a, 2))?;
if to.beside != Some(item.id) {
place(h, item.doc, item.id, &to)?;
}
Ok(arg(a, 0).clone())
}
@@ -1713,6 +1950,13 @@ fn item_duplicate(h: &Host, a: &[Data]) -> Answer {
if in_compound(h, item) {
return Err(HostError::Error(COMPOUND_MEMBER.into()));
}
// `edit.duplicate` copies only what it can select.
let refused = with_doc(h, item.doc, |_, st| {
(!editable(&st.doc, item.id) || on_locked_artboard(h, st, item.id)).then(|| st.doc.node(item.id).and_then(typename).unwrap_or("page item"))
});
if let Some(name) = refused {
return Err(HostError::Error(format!("Cannot duplicate {name} {}", item.id.0)));
}
let to = match arg(a, 1) {
Data::Undefined => {
if !matches!(arg(a, 2), Data::Undefined) {
@@ -1720,7 +1964,7 @@ fn item_duplicate(h: &Host, a: &[Data]) -> Answer {
}
None
}
target => Some(destination(h, item, target, arg(a, 2), true)?),
target => Some(destination(h, item, target, arg(a, 2))?),
};
let id = atomically(h, |h| {
let (_, made) = on_doc(h, item.doc.uid, true, |h| command_value(h, "edit.duplicate", &json!({"ids": [item.id.0]})))?;
@@ -1736,7 +1980,7 @@ fn item_duplicate(h: &Host, a: &[Data]) -> Answer {
}
/// `zOrder(method)`: one of the four Object › Arrange commands for the item. A path inside a
/// compound path is refused.
/// compound path is refused, and so is an object in a hidden or locked layer.
fn item_z_order(h: &Host, a: &[Data]) -> Answer {
let id = match arg(a, 1) {
Data::String(s) if s == "ZOrderMethod.BRINGTOFRONT" => "object.arrange.bringToFront",
@@ -1749,6 +1993,7 @@ fn item_z_order(h: &Host, a: &[Data]) -> Answer {
if in_compound(h, item) {
return Err(HostError::Error(COMPOUND_MEMBER_ORDER.into()));
}
refuse_in_closed_layer(h, item)?;
let (before, after) = with_doc(h, item.doc, |_, st| {
let at = st.doc.position(item.id);
let count = at.and_then(|(p, ..)| st.doc.children(p).map(Vec::len)).unwrap_or(0);
@@ -1779,6 +2024,31 @@ fn layer_typename(h: &Host, a: &[Data]) -> Answer {
Ok(text("Layer"))
}
/// `toString()` of an object with a name: `[Class name]`, `[PathItem ]` for an object with no name.
fn named_text(class: &str, name: Answer) -> Answer {
match name? {
Data::String(n) => Ok(text(format!("[{class} {n}]"))),
_ => Ok(text(format!("[{class} ]"))),
}
}
fn item_to_string(h: &Host, a: &[Data]) -> Answer {
read_item(h, a, |_, n| Ok(text(format!("[{} {}]", typename(n).unwrap_or("PageItem"), n.name.as_deref().unwrap_or("")))))
}
fn doc_to_string(h: &Host, a: &[Data]) -> Answer {
named_text("Document", doc_name(h, a))
}
fn layer_to_string(h: &Host, a: &[Data]) -> Answer {
named_text("Layer", layer_name(h, a))
}
/// `toString()` of an object without a name: `[Class]`.
fn class_text(name: &'static str) -> HostMember {
HostMember::Method(Rc::new(move |_| Ok(text(format!("[{name}]")))))
}
fn typename_of(name: &'static str) -> HostMember {
HostMember::Get(Rc::new(move |_| Ok(text(name))))
}
@@ -1831,9 +2101,10 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
("typename", typename_of("Application")),
("documents", get(l, app_documents)),
("activeDocument", property(l, app_active, app_set_active)),
("selection", get(l, app_selection)),
("selection", property(l, app_selection, app_set_selection)),
("coordinateSystem", property(l, app_coords, app_set_coords)),
("getIsFileOpen", method(l, app_is_open)),
("toString", class_text("Application")),
]);
application.push(("textFonts".into(), text::app_text_fonts(l)));
application.push(later(l, "Application", "beep"));
@@ -1844,7 +2115,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
h.charge_call(64)?;
new_preset(&h)
});
let mut members = vec![("typename".to_string(), typename_of("DocumentPreset"))];
let mut members = vec![("typename".to_string(), typename_of("DocumentPreset")), ("toString".to_string(), class_text("DocumentPreset"))];
members.extend(PRESET_FIELDS.iter().map(|k| (k.to_string(), preset_field(link, k))));
HostClass { name: "DocumentPreset".into(), parent: None, members, index: None, construct: Some(f) }
};
@@ -1862,6 +2133,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
("getByName", method(l, docs_by_name)),
("add", method(l, docs_add)),
("addDocument", method(l, docs_add_document)),
("toString", class_text("Documents")),
]),
Some(function(l, docs_at)),
),
@@ -1879,6 +2151,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
("pageItems", get(l, doc_page_items)),
("textFrames", text::doc_text_frames(l)),
("selection", property(l, doc_selection, doc_set_selection)),
("toString", method(l, doc_to_string)),
]);
document.extend(text::styles::doc_members(l));
document.extend(
@@ -1897,6 +2170,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
("index", method(l, items_index)),
("getByName", method(l, items_by_name)),
("removeAll", method(l, items_remove_all)),
("toString", class_text("PageItems")),
]),
Some(function(l, items_at)),
));
@@ -1923,6 +2197,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
("move", method(l, item_move)),
("remove", method(l, item_remove)),
("zOrder", method(l, item_z_order)),
("toString", method(l, item_to_string)),
]);
page_item.extend(
[
@@ -1951,8 +2226,19 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
classes.push(class("PageItem", None, page_item, None));
classes.extend(ITEM_CLASSES.iter().filter(|c| **c != "TextFrame").map(|c| class(c, Some("PageItem"), Vec::new(), None)));
classes.extend(text::classes(l));
classes.push(class("Layer", None, named(vec![("typename", get(l, layer_typename)), ("name", get(l, layer_name))]), None));
realm.define_host_classes(classes, vec![("app".into(), host_ref("Application", &[]))])
classes.push(class(
"Layer",
None,
named(vec![("typename", get(l, layer_typename)), ("name", get(l, layer_name)), ("toString", method(l, layer_to_string))]),
None,
));
realm.define_host_classes(classes, vec![("app".into(), host_ref("Application", &[]))])?;
// The application's members a script may name without `app.`, assigned as `app.<member>` is.
realm.define_host_globals(vec![
("activeDocument".into(), function(l, app_active), Some(function(l, app_set_active))),
("documents".into(), function(l, app_documents), None),
("selection".into(), function(l, app_selection), Some(function(l, app_set_selection))),
])
}
#[cfg(test)]
@@ -1967,4 +2253,29 @@ mod tests {
assert_eq!(done_unless_refused(Err(HostError::Abort("canceled".into()))), Err(HostError::Abort("canceled".into())));
assert_eq!(done_unless_refused(Err(HostError::Range("too large".into()))), Err(HostError::Range("too large".into())));
}
#[test]
fn page_item_lists_are_kept_for_several_documents() {
let docs: Vec<Arc<Document>> = (0..=ITEM_LISTS).map(|_| Arc::new(Document::new(100.0, 100.0))).collect();
let ids = |n: u64| Rc::new(vec![NodeId(n)]);
let mut lists = Vec::new();
keep_items(&mut lists, (1, docs[0].clone(), ids(1)));
keep_items(&mut lists, (2, docs[1].clone(), ids(2)));
// Reading two documents in turn keeps both lists.
assert_eq!(kept_items(&lists, 1, &docs[0]), Some(ids(1)));
assert_eq!(kept_items(&lists, 2, &docs[1]), Some(ids(2)));
// A changed document has no kept list, and its new list replaces the old one.
let changed = Arc::new(Document::new(100.0, 100.0));
assert_eq!(kept_items(&lists, 1, &changed), None);
keep_items(&mut lists, (1, changed.clone(), ids(3)));
assert_eq!(lists.len(), 2);
assert_eq!(kept_items(&lists, 1, &changed), Some(ids(3)));
// Past the limit, the list kept longest ago goes.
for (uid, d) in (10..).zip(&docs[2..]) {
keep_items(&mut lists, (uid, d.clone(), ids(uid)));
}
assert_eq!(lists.len(), ITEM_LISTS);
assert_eq!(kept_items(&lists, 2, &docs[1]), None);
assert_eq!(kept_items(&lists, 1, &changed), Some(ids(3)));
}
}
+159 -44
View File
@@ -54,7 +54,9 @@
//! for, loses the grant before that code runs. A run with nobody to ask gets `null` and
//! [`NO_PICKER`].
//! - The commands a script runs with `vc.run` read and write only in the places above and in the
//! files of the open documents ([`crate::file_access::ScriptGate`]).
//! files the person gave the open documents ([`crate::file_access::ScriptGate`]). They also read
//! the files that the documents open when the run began link to, as the person last left those
//! documents and as those links led then.
//! - `open('w')` empties the file at once; what a script writes is kept in memory, at most
//! [`MAX_FILE_BYTES`] a file, and written when it closes the file or the run ends; a run writes at
//! most [`MAX_RUN_BYTES`] in all and ends past that. `write` encodes in the file's encoding (an
@@ -67,8 +69,15 @@
//! file and once more for each such object. `write` joins its values only for an open file and
//! only up to twice [`MAX_FILE_BYTES`] UTF-16 code units. Each file written is named in the
//! report's `written` (at most [`super::MAX_WRITTEN`]), also after a run that failed.
//! - Hidden settings, aliases and `execute` are not available: they return `false` and set `error`.
//! `execute` is counted in the report's `fileExecutes`.
//! - On Unix, where a name that starts with a dot is hidden, setting `hidden` renames the file in
//! its folder, adding one dot or taking its leading dots off, under the rules for `rename`: the
//! old and the new name must both be places the script may write, and a name in use is refused.
//! `createAlias` makes a symbolic link at the object's path, a place the script may write where
//! nothing is, that leads to the real path of a file the script may read. `hidden` and `alias`
//! tell of a link itself, and setting `hidden`, `rename` and `remove` change the link, never what
//! it leads to. On other systems both set `error` and change nothing.
//! - `execute` is not available: it returns `false`, sets `error`, and is counted in the report's
//! `fileExecutes`.
//! - In a wasm build every lookup fails with [`NO_WEB`].
use std::collections::HashMap;
@@ -118,6 +127,7 @@ pub(crate) const WRITE_FAILED: &str = "Script file could not be written";
pub(crate) const NOT_EMPTY: &str = "Script folder is not empty";
pub(crate) const NAME_TAKEN: &str = "Script file name is already in use";
pub(crate) const BAD_NAME: &str = "Script file name must be a name without a folder";
#[cfg(not(unix))]
pub(crate) const NO_ALIAS: &str = "Script files cannot make aliases";
pub(crate) const NO_HIDDEN: &str = "Script file hidden setting cannot be changed";
pub(crate) const PROTECTED: &str = "Script file access to the app's own folders is not allowed";
@@ -454,10 +464,11 @@ impl Disk {
}
}
/// The gate for a command the script runs: the places it reads and writes now, and the files of
/// the open documents, `documents`.
pub(crate) fn gate(&self, documents: Vec<String>) -> crate::file_access::ScriptGate {
crate::file_access::ScriptGate { read: self.scope.clone(), write: self.writes.clone(), documents, also: None }
/// The gate for a command the script runs: the places it reads and writes now, the files the
/// person gave the open documents, `documents`, and the files it may only read because the documents open when
/// the run began link to them, `linked`.
pub(crate) fn gate(&self, documents: Vec<String>, linked: crate::file_access::LinkedFiles) -> crate::file_access::ScriptGate {
crate::file_access::ScriptGate { read: self.scope.clone(), write: self.writes.clone(), documents, linked, also: None }
}
/// The files written since this was last asked, to name in the report.
@@ -912,8 +923,15 @@ fn read_head(real: &Path, max: usize) -> std::io::Result<Vec<u8>> {
/// that is not well formed is left out. It is read under [`lock_store`]'s lock, so it is read
/// between two changes, and none are read when the lock cannot be taken.
fn read_store(store: &Path) -> Vec<serde_json::Value> {
let Ok(_lock) = lock_store(store) else { return Vec::new() };
load_store(store, false).unwrap_or_default()
list_store(store).unwrap_or_default()
}
/// The grants [`read_store`] reads; none when the grants file is missing, and `Err` when the lock
/// cannot be taken or the file is there but cannot be read, is too large, is not a grants file of
/// this version or holds no list of grants.
fn list_store(store: &Path) -> std::io::Result<Vec<serde_json::Value>> {
let _lock = lock_store(store)?;
load_store(store, false)
}
/// The grants the grants file at `store` holds, to change and write back; none when it is missing,
@@ -929,7 +947,8 @@ fn try_read_store(store: &Path) -> std::io::Result<Vec<serde_json::Value>> {
fn load_store(store: &Path, strict: bool) -> std::io::Result<Vec<serde_json::Value>> {
let bytes = match read_head(store, MAX_STORE_BYTES) {
Ok(bytes) => bytes,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
// A link whose target is missing is there but cannot be read.
Err(e) if e.kind() == std::io::ErrorKind::NotFound && std::fs::symlink_metadata(store).is_err() => return Ok(Vec::new()),
Err(e) => return Err(e),
};
if bytes.len() > MAX_STORE_BYTES {
@@ -947,14 +966,14 @@ fn load_store(store: &Path, strict: bool) -> std::io::Result<Vec<serde_json::Val
&& g["write"].is_boolean()
&& g["folder"].is_boolean()
};
let grants = v["grants"].as_array().ok_or_else(|| std::io::Error::other("the grants file holds no list of grants"))?;
if strict {
let grants = v["grants"].as_array().ok_or_else(|| std::io::Error::other("the grants file holds no list of grants"))?;
if grants.len() > MAX_STORED_GRANTS || !grants.iter().all(valid) {
return Err(std::io::Error::other("the grants file holds a grant that cannot be read"));
}
return Ok(grants.clone());
}
Ok(v["grants"].as_array().map(|a| a.iter().filter(|g| valid(g)).take(MAX_STORED_GRANTS).cloned().collect()).unwrap_or_default())
Ok(grants.iter().filter(|g| valid(g)).take(MAX_STORED_GRANTS).cloned().collect())
}
/// The number in the name of the next file [`write_store`] writes before it takes the grants file's
@@ -1054,9 +1073,9 @@ fn lock_store(_: &Path) -> std::io::Result<std::fs::File> {
}
/// The grants the grants file beside the data folder `data_dir` keeps: each script, the SHA-256 of
/// its text, the path and whether it may be written (`script.grants`).
pub(crate) fn stored_grants(data_dir: &Path) -> Vec<serde_json::Value> {
read_store(&data_dir.with_file_name(GRANTS_FILE))
/// its text, the path and whether it may be written (`script.grants`); as [`list_store`] reads them.
pub(crate) fn stored_grants(data_dir: &Path) -> std::io::Result<Vec<serde_json::Value>> {
list_store(&data_dir.with_file_name(GRANTS_FILE))
}
/// Removes from the grants file beside `data_dir` the grants of the script `script` and of the path
@@ -1883,44 +1902,41 @@ fn remove(host: &Host, a: &[Data]) -> Result<Data, HostError> {
/// `rename(path, name)`: the file or folder named `name` in the same folder; → `{fs}`, its new path.
fn rename(host: &Host, a: &[Data]) -> Result<Data, HostError> {
let (path, name) = (arg_text(a, 0), arg_text(a, 1));
let mut disk = host.disk.borrow_mut();
Ok(match rename_in(&mut disk, &path, &name) {
Ok(new) => Data::Object(vec![("fs".into(), Data::String(new))]),
Err(m) => error(m),
})
}
/// Renames the file or folder at `path`, a link itself, to `name` in the same folder. → its new
/// path.
fn rename_in(disk: &mut Disk, path: &str, name: &str) -> Result<String, &'static str> {
let bad = name.is_empty() || name == "." || name == ".." || name.contains('/') || (WINDOWS && (name.contains('\\') || name.contains(':')));
if bad || name.contains('\0') {
return Ok(error(BAD_NAME));
return Err(BAD_NAME);
}
let Some(new) = Path::new(&path).parent().map(|p| p.join(&name).to_string_lossy().into_owned()) else { return Ok(error(ACCESS_DENIED)) };
let mut disk = host.disk.borrow_mut();
let (from, to) = match (disk.target(&path, false), disk.target(&new, false)) {
(Ok(f), Ok(t)) => (f, t),
(Err(m), _) | (_, Err(m)) => return Ok(error(m)),
};
let Ok(was) = std::fs::symlink_metadata(&from) else { return Ok(error(NOT_FOUND)) };
let new = Path::new(path).parent().map(|p| p.join(name).to_string_lossy().into_owned()).ok_or(ACCESS_DENIED)?;
let (from, to) = (disk.target(path, false)?, disk.target(&new, false)?);
let was = std::fs::symlink_metadata(&from).map_err(|_| NOT_FOUND)?;
// A folder that holds the settings folder is not moved, also when its name is given in another
// case where case does not matter.
let holds = |f: &Path| std::fs::canonicalize(&from).map_or(true, |kept| crate::file_access::path_inside(f, &kept));
if was.is_dir() && disk.fenced.as_deref().is_some_and(holds) {
return Ok(error(ACCESS_DENIED));
return Err(ACCESS_DENIED);
}
// A name that differs in case alone may name the same file, which then takes the new name.
if let Ok(there) = std::fs::symlink_metadata(&to)
&& !(from.to_string_lossy().eq_ignore_ascii_case(&to.to_string_lossy()) && same_file((&from, &was), (&to, &there)))
{
return Ok(error(NAME_TAKEN));
return Err(NAME_TAKEN);
}
// Open objects hold real paths with the names the file system keeps, and `from` keeps the last
// name as given, which where case does not matter can differ in case: they are matched by the
// kept name. A link is renamed itself, and no object holds a path through it. When the kept
// name cannot be learned, nothing is renamed, so no object goes on under the old path's rules.
let kept = if was.file_type().is_symlink() {
from.clone()
} else {
match std::fs::canonicalize(&from) {
Ok(kept) => kept,
Err(_) => return Ok(error(WRITE_FAILED)),
}
};
if std::fs::rename(&from, &to).is_err() {
return Ok(error(WRITE_FAILED));
}
let kept = if was.file_type().is_symlink() { from.clone() } else { std::fs::canonicalize(&from).map_err(|_| WRITE_FAILED)? };
std::fs::rename(&from, &to).map_err(|_| WRITE_FAILED)?;
// Open objects of the file, or of files in the folder, write to the new path, and the rules for
// reading apply to them there.
let moved = |p: &mut Option<std::path::PathBuf>| {
@@ -1935,7 +1951,102 @@ fn rename(host: &Host, a: &[Data]) -> Result<Data, HostError> {
// The old path no longer holds the file, so the report names it as well as the new one.
disk.wrote(&from);
disk.wrote(&to);
Ok(Data::Object(vec![("fs".into(), Data::String(new))]))
Ok(new)
}
/// `setHidden(path, hidden)`: on Unix, where a name that starts with a dot is hidden, the file or
/// link at `path` (a link itself, never what it leads to) renamed with one dot added or its leading
/// dots taken off; → `{fs}`, its path. A file already as asked keeps its name. A name that would be
/// left empty, a folder, and every system that is not Unix give `{error}`.
fn set_hidden(host: &Host, a: &[Data]) -> Result<Data, HostError> {
let (path, on) = (arg_text(a, 0), matches!(a.get(1), Some(Data::Bool(true))));
let mut disk = host.disk.borrow_mut();
let at = match disk.target(&path, false) {
Ok(t) => t,
Err(m) => return Ok(error(m)),
};
if !cfg!(unix) {
return Ok(error(NO_HIDDEN));
}
match std::fs::symlink_metadata(&at) {
Err(_) => return Ok(error(NOT_FOUND)),
Ok(m) if m.is_dir() => return Ok(error(NOT_REGULAR)),
Ok(_) => {}
}
let Some(name) = Path::new(&path).file_name().map(|n| n.to_string_lossy().into_owned()) else { return Ok(error(ACCESS_DENIED)) };
if name.starts_with('.') == on {
return Ok(Data::Object(vec![("fs".into(), Data::String(path))]));
}
let new = if on { format!(".{name}") } else { name.trim_start_matches('.').to_string() };
if new.is_empty() {
return Ok(error(NO_HIDDEN));
}
Ok(match rename_in(&mut disk, &path, &new) {
Ok(fs) => Data::Object(vec![("fs".into(), Data::String(fs))]),
Err(m) => error(m),
})
}
/// `createAlias(path, target)`: on Unix a symbolic link at `path` that leads to the real path of the
/// file `target`. `path` must be a place the script may write where nothing is, not even a link
/// that leads nowhere, and `target` a file the script may read. Every system that is not Unix gives
/// `{error}`.
fn create_alias(host: &Host, a: &[Data]) -> Result<Data, HostError> {
let (path, to) = (arg_text(a, 0), arg_text(a, 1));
let mut disk = host.disk.borrow_mut();
let at = match disk.target(&path, false) {
Ok(t) => t,
Err(m) => return Ok(error(m)),
};
if std::fs::symlink_metadata(&at).is_ok() {
return Ok(error(NAME_TAKEN));
}
if to.is_empty() {
return Ok(error(NOT_FOUND));
}
let real = match disk.stat(&to) {
Ok(Some(e)) if e.file => disk.checked(&to).ok().and_then(|p| disk.scope.locate(p).ok()),
Ok(Some(_)) => return Ok(error(NOT_REGULAR)),
Ok(None) => return Ok(error(NOT_FOUND)),
Err(m) => return Ok(error(m)),
};
let Some(real) = real else { return Ok(error(ACCESS_DENIED)) };
#[cfg(test)]
if let Some(hook) = BEFORE_ALIAS_LINK.with(|h| h.borrow_mut().take()) {
hook(&at);
}
Ok(make_link(&mut disk, &at, &real))
}
/// A symbolic link at the real path `at` that leads to the real path `real`. → `true`, or `{error}`.
#[cfg(unix)]
fn make_link(disk: &mut Disk, at: &Path, real: &Path) -> Data {
// Making the link fails when something took its place since it was looked up.
if std::os::unix::fs::symlink(real, at).is_err() {
return error(WRITE_FAILED);
}
// A link put in place of a folder above it since it was looked up may have taken the new link
// elsewhere: that link is removed again, when it is still the one made here.
let placed = at.parent().is_some_and(|p| std::fs::canonicalize(p).is_ok_and(|c| c == p));
let ours = std::fs::read_link(at).is_ok_and(|l| l == real);
if !placed {
if ours {
let _ = std::fs::remove_file(at);
}
return error(ACCESS_DENIED);
}
// Something else at `at` replaced the new link since it was made: it is left alone.
if !ours {
return error(WRITE_FAILED);
}
disk.wrote(at);
Data::Bool(true)
}
/// Every system that is not Unix: `{error}` with [`NO_ALIAS`].
#[cfg(not(unix))]
fn make_link(_: &mut Disk, _: &Path, _: &Path) -> Data {
error(NO_ALIAS)
}
/// Do the paths `a` and `b`, with their metadata, name one file? On Unix by device and inode; on
@@ -2309,13 +2420,8 @@ pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunEr
}))
};
let value = |s: &str| HostItem::Value(Data::String(s.to_string()));
let text = HostItem::Object(vec![
("notOpen".into(), value(NOT_OPEN)),
("badMode".into(), value(BAD_MODE)),
("noAlias".into(), value(NO_ALIAS)),
("noHidden".into(), value(NO_HIDDEN)),
("tooLarge".into(), value(TOO_LARGE)),
]);
let text =
HostItem::Object(vec![("notOpen".into(), value(NOT_OPEN)), ("badMode".into(), value(BAD_MODE)), ("tooLarge".into(), value(TOO_LARGE))]);
let system = if WINDOWS {
"Windows"
} else if cfg!(target_os = "macos") {
@@ -2357,6 +2463,8 @@ pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunEr
("create".into(), call(link, create)),
("setLength".into(), call(link, set_length)),
("setReadonly".into(), call(link, set_readonly)),
("setHidden".into(), call(link, set_hidden)),
("createAlias".into(), call(link, create_alias)),
("pick".into(), call(link, pick)),
];
realm.define_file_classes(items)
@@ -2367,9 +2475,16 @@ pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunEr
#[cfg(test)]
pub(crate) type CopyHook = Box<dyn FnOnce(&Path, &Path)>;
/// Tests: what the next `createAlias` does with the real path of its link.
#[cfg(test)]
pub(crate) type AliasHook = Box<dyn FnOnce(&Path)>;
#[cfg(test)]
thread_local! {
pub(crate) static BEFORE_COPY_READ: std::cell::RefCell<Option<CopyHook>> = const { std::cell::RefCell::new(None) };
/// Tests: what the next `createAlias` does with the real path of its link, after looking it up
/// and before making the link.
pub(crate) static BEFORE_ALIAS_LINK: std::cell::RefCell<Option<AliasHook>> = const { std::cell::RefCell::new(None) };
/// Tests: while set, the bytes `flush` writes fail after the file was opened for them.
pub(crate) static FLUSH_WRITE_FAILS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
+16 -1
View File
@@ -217,6 +217,15 @@ pub(crate) struct Files {
levels: usize,
/// The files `$.evalFile` is running, the script first.
frames: Vec<Frame>,
/// The run reads ECMAScript 2015 ([`es2015_script`]): its files are parsed that way.
es2015: bool,
}
/// A script at `path` runs with [`vectorcraft_js::Options::es2015`] when its file name ends in
/// `.js` (in any letter case); a `.jsx` script, any other file and a script given as text run as
/// ECMAScript 5.1 with the ExtendScript extensions.
pub(crate) fn es2015_script(path: Option<&str>) -> bool {
path.and_then(|p| Path::new(p).extension()).is_some_and(|e| e.eq_ignore_ascii_case("js"))
}
/// The output being built: its UTF-16 text, the line it is on, the units since that line began,
@@ -311,9 +320,15 @@ impl Files {
chain: real.into_iter().collect(),
levels: 0,
frames: vec![Frame { shown: Arc::from(path.unwrap_or_default()), dir }],
es2015: es2015_script(path),
}
}
/// The options a file of this run is parsed with, preprocessor lines aside.
pub(crate) fn options(&self) -> Options {
Options { max_source_units: MAX_TOTAL_BYTES, es2015: self.es2015, ..Options::default() }
}
/// The `JSINCLUDE` folders of this process: absolute folders separated by `;`.
pub(crate) fn jsinclude_env() -> Vec<PathBuf> {
#[cfg(test)]
@@ -456,7 +471,7 @@ impl Files {
return Ok(());
}
let fail = |kind, message: String, line, column| Failure { kind, message, index, file: shown.clone(), line, column };
let options = Options { preprocessor_lines: true, max_source_units: MAX_TOTAL_BYTES, ..Options::default() };
let options = Options { preprocessor_lines: true, ..self.options() };
let program = vectorcraft_js::parse_utf16(&units, &options).map_err(|e| fail(FailKind::Syntax, e.message, e.line, e.column))?;
let mut cursor = 0usize;
for d in &program.directives {
+71 -12
View File
@@ -802,6 +802,35 @@ struct Host {
args: RefCell<(Data, u64)>,
/// The run's state of the script object model (`app`).
dom: dom::State,
/// The documents open when the run began as the person last left them, each with its own file
/// and the file it was read from ([`crate::DocState::as_person_left`],
/// [`crate::cmd::links::LinkBase::of_files`]), until the run's first command takes the files
/// they link to from them ([`Host::linked`]).
run_docs: RefCell<Vec<RunDoc>>,
/// The files the documents open when the run began link to as the person left them
/// ([`crate::file_access::ScriptGate::linked`]).
linked: std::cell::OnceCell<crate::file_access::LinkedFiles>,
}
/// A document open when a run began, with its own file and the file it was read from.
type RunDoc = (Arc<crate::Document>, Option<String>, Option<String>);
impl Host {
/// The files the commands the run runs may read because the documents open when the run began
/// link to them, found once, from those documents as the person left them: a link a script's
/// command added or changed, in this run or an earlier one, and a document it opened, give it
/// no file to read.
fn linked(&self) -> crate::file_access::LinkedFiles {
self.linked
.get_or_init(|| {
let docs = std::mem::take(&mut *self.run_docs.borrow_mut());
let files = docs.iter().flat_map(|(d, path, from)| {
crate::cmd::links::files_linked(d, crate::cmd::links::LinkBase::of_files(path.as_deref(), from.as_deref()))
});
crate::file_access::ScriptGate::real_files(files.collect::<Vec<_>>())
})
.clone()
}
}
/// A run's host calls by kind, as its report gives them in `hostCallCounts`.
@@ -1046,7 +1075,7 @@ impl Host {
}
let bridge = self.bridge.get().saturating_add(bytes);
self.bridge.set(bridge);
if bridge > MAX_BRIDGE_BYTES {
if bridge > bridge_bytes() {
return Err(self.over(OVER_BRIDGE));
}
let n = self.calls_this_slice.get() + 1;
@@ -1243,9 +1272,19 @@ fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value
let before: Vec<(u64, Arc<crate::Document>, u64)> =
if mutating { s.docs.iter().map(|d| (d.uid, d.doc.clone(), d.doc.peek_next_id())).collect() } else { Vec::new() };
crate::file_access::start_recording_writes();
// The command reads and writes only where the script's own files may, and the open documents' files.
let gate = host.disk.borrow().gate(s.docs.iter().filter_map(|d| d.path.clone()).collect());
// The command reads and writes only where the script's own files may, and the files the person gave
// the open documents; it also reads the files the documents open when the run began link to, as the
// person left them. A document a script's command opened gives it no file.
let documents = s.docs.iter().filter_map(|d| d.as_person_left().and_then(|(_, path, _)| path.map(str::to_string))).collect();
let gate = host.disk.borrow().gate(documents, host.linked());
let was: Vec<(u64, RunDoc)> = s.docs.iter().map(|d| (d.uid, (d.doc.clone(), d.path.clone(), d.links_from.clone()))).collect();
let r = crate::file_access::with_script_gate(gate, || s.execute(id, params));
// What the command opened, changed or gave another file is not as the person left it.
for st in &mut s.docs {
let prior = was.iter().find(|(uid, _)| *uid == st.uid);
st.note_script_command(prior.map(|(_, (doc, path, from))| (doc, path, from)));
}
drop(was);
// A file a command wrote before it failed is on disk all the same.
let mut written = host.written.borrow_mut();
for path in crate::file_access::finish_recording_writes(r.is_ok()) {
@@ -1562,7 +1601,7 @@ fn eval_file(host: &Host, args: Vec<Data>) -> std::result::Result<Data, HostErro
if f.line > 0 { host.placed(error, f.file, f.line, f.column) } else { error }
})?;
// A file without preprocessor lines is parsed here first, so its syntax error names its place.
let options = vectorcraft_js::Options { max_source_units: include::MAX_TOTAL_BYTES, ..vectorcraft_js::Options::default() };
let options = host.files.borrow().options();
if let Err(e) = vectorcraft_js::parse(&expanded.source, &options) {
host.files.borrow_mut().end_eval();
let (_, file, line, column) = expanded.map.locate(e.line, e.column);
@@ -1652,16 +1691,10 @@ fn kind_id(kind: &RunErrorKind) -> &'static str {
/// program. A message the script supplied itself ([`RunError::authored`]) is given as it is.
fn explained(e: &RunError) -> String {
const HOST_OBJECTS: &[&str] = &["Window", "BridgeTalk"];
const APP_MEMBERS: &[&str] = &["activeDocument", "documents", "selection"];
let message = &e.message;
let first = message.strip_prefix("ReferenceError: ").and_then(|m| m.split_whitespace().next());
let names_host_object = first.is_some_and(|f| HOST_OBJECTS.contains(&f));
if e.kind == RunErrorKind::Thrown
&& !e.authored
&& let Some(member) = first.filter(|f| APP_MEMBERS.contains(f))
{
format!("{message} (use `app.{member}`)")
} else if e.kind == RunErrorKind::Thrown && !e.authored && names_host_object {
if e.kind == RunErrorKind::Thrown && !e.authored && names_host_object {
format!("{message} (scripts here use the `vc` object; objects other applications give their scripts are not available)")
} else {
message.to_string()
@@ -2060,11 +2093,16 @@ impl Session {
// A realm made here gets the script extensions, `$` and the dialogs; a kept one has them
// from its first run, and they act for the run that calls them.
let fresh = realm.is_none();
let options = Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), ..Options::default() };
// A `.js` script reads ECMAScript 2015; `eval`, `Function`, includes and `$.evalFile` read
// code the way the script does.
let es2015 = include::es2015_script(request.file.as_deref());
let options = Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), es2015, ..Options::default() };
let strict = options.strict;
// A kept engine reads each run's code the way that run's script does.
let mut realm = match realm {
Some(mut realm) => {
realm.set_limits(limits);
realm.set_es2015(es2015);
realm
}
None => {
@@ -2134,6 +2172,14 @@ impl Session {
dollar: dollar::RunState::new(&request.locale),
args: RefCell::new((Data::Undefined, 0)),
dom: dom::State::default(),
run_docs: RefCell::new(
self.docs
.iter()
.filter_map(DocState::as_person_left)
.map(|(doc, path, from)| (doc.clone(), path.map(str::to_string), from.map(str::to_string)))
.collect(),
),
linked: std::cell::OnceCell::new(),
});
*link.borrow_mut() = Some(host.clone());
let args = match to_data(&Value::Object(request.args), &DataLimits::default(), 0, &mut (0, 0)) {
@@ -2159,6 +2205,7 @@ impl Session {
Ok(expanded) => {
*host.script_map.borrow_mut() = expanded.map;
realm.set_strict_writes(expanded.strict == Some(true));
realm.set_script_name(Some(host.name.to_string()));
if fresh {
let l = link.clone();
realm.set_source_locator(Rc::new(move |tag, line| match current(&l) {
@@ -2167,6 +2214,7 @@ impl Session {
}));
}
(if fresh { realm.add_script_extensions() } else { Ok(()) })
.and_then(|()| if fresh { realm.add_unit_values() } else { Ok(()) })
.and_then(|()| if fresh { realm.define_host_object("vc", vc_object(&link)) } else { Ok(()) })
.and_then(|()| if fresh { realm.define_host_object("$", dollar_object(&link, info, &localization)) } else { Ok(()) })
.and_then(|()| if fresh { dialogs::install(&mut realm, &link) } else { Ok(()) })
@@ -2578,6 +2626,15 @@ fn growth_objects() -> u64 {
GROWTH_OBJECTS
}
/// The data a run may pass to and from commands.
fn bridge_bytes() -> u64 {
#[cfg(test)]
if let Some(n) = TEST_BRIDGE_BYTES.with(Cell::get) {
return n;
}
MAX_BRIDGE_BYTES
}
/// The limits of a command's result on its way to the script.
fn result_limits() -> DataLimits {
#[cfg(test)]
@@ -2595,6 +2652,8 @@ thread_local! {
pub(crate) static PANIC_IN_SLICE: Cell<bool> = const { Cell::new(false) };
/// Tests: the objects a run may add in place of [`GROWTH_OBJECTS`].
pub(crate) static TEST_GROWTH: Cell<Option<u64>> = const { Cell::new(None) };
/// Tests: the data a run may pass to and from commands in place of [`MAX_BRIDGE_BYTES`].
pub(crate) static TEST_BRIDGE_BYTES: Cell<Option<u64>> = const { Cell::new(None) };
/// Tests: the heap of a named engine in place of [`ENGINE_HEAP_BYTES`].
pub(crate) static TEST_ENGINE_HEAP: Cell<Option<usize>> = const { Cell::new(None) };
/// Tests: the bytes of source maps a named engine keeps, in place of [`KEPT_MAP_BYTES`].
+24 -3
View File
@@ -24,6 +24,10 @@ impl Session {
});
// Clicks find an image's own fills and strokes where their effects draw them.
vectorcraft_doc::hit::set_image_paint(vectorcraft_render::effects::image_paint);
// Direct Selection picks and outlines the parts of a dynamic symbol's instance where the
// effects of the instance's fill and stroke draw them.
vectorcraft_doc::hit::set_instance_row_art(vectorcraft_render::effects::add_instance_row_effects_to_parts);
vectorcraft_doc::hit::set_instance_reshapes(vectorcraft_render::effects::has_item_geometry);
// Clicks inside a clip group fall in the region its clipping path's effects give it.
vectorcraft_doc::hit::set_clip_region(vectorcraft_render::effects::reshaped_clip_outline);
// Clicks and marquees find paths, compound paths, groups and layers where their geometry
@@ -65,6 +69,9 @@ impl Session {
selection_at_lend: None,
lent_selection: None,
last_selection_tool: None,
last_part_selection_tool: None,
press_lent: None,
hover_lent: None,
last_view: ViewInfo::default(),
preview_memo: Default::default(),
depth: 0,
@@ -114,6 +121,7 @@ impl Session {
journal_note: Default::default(),
note_depth: 1,
journal_query: false,
defaults_only_ran: None,
explicit_undo_group: None,
batch_stash: None,
batch_steps: None,
@@ -207,6 +215,7 @@ impl Session {
return;
}
self.press_type_selection = None;
self.press_lent = None;
let view = self.last_view;
// The edit the tool computes on another thread and the input held for it belong to the
// document being left. The switch goes on whatever they did, as for the deactivation.
@@ -215,9 +224,14 @@ impl Session {
let _ = self.give_back_tool(view);
let _ = self.deactivate_tool(view);
// A batch leaves its interaction open in the document it leaves, to keep or roll back with
// the rest of the batch; anything else in progress (a drag) is cancelled.
// the rest of the batch; one that keeps on a switch is kept; anything else in progress (a
// drag) is cancelled.
if self.batch_stash.is_none() {
let _ = self.cancel_interaction();
let _ = if self.active().and_then(|st| st.interaction.as_ref()).is_some_and(|it| it.keep_on_switch) {
self.commit_interaction()
} else {
self.cancel_interaction()
};
}
self.keep_tool_settings();
self.tool = self.make_tool(self.tool.id());
@@ -290,7 +304,9 @@ impl Session {
/// what is fitted to type's bounds (an envelope warping it) would come out differently. That
/// holds for the type in symbol definitions, pattern tiles, graph designs and opacity masks too,
/// not only in the layers (#1738).
pub(crate) fn refresh_text_bounds(doc: &mut Document) {
pub(crate) fn refresh_text_bounds(doc: &mut Document) -> Vec<String> {
// The fonts files carried for their type draw it ([`vectorcraft_doc::FileFonts`]).
let warnings = vectorcraft_text::FontDb::global().bind_document_file_fonts(doc);
// Inline graphics in text take their size from their symbols' art (not saved either).
doc.resolve_inline_art();
let mut uncached = |t: &TextObject| t.cached_bounds.is_none();
@@ -300,6 +316,7 @@ impl Session {
// The symbols' type is measured now: the inline graphics showing those symbols take their
// art's measured size, a symbol's type before the type that shows that symbol inline.
doc.resolve_inline_art_with(&mut cmd::typecmd::refresh_bounds_for_first_frame);
warnings
}
/// Measure the type in open document `index` that `stale` picks (in its trees as
@@ -341,6 +358,8 @@ impl Session {
// (importers and the native reader have seen to theirs already, with a warning).
doc.limit_depth();
cmd::compositefonts::filter_loaded(&mut doc);
// Importers report binding failures; programmatic additions still need owned resources.
let _ = vectorcraft_text::FontDb::global().bind_document_file_fonts(&mut doc);
// Inline graphics in text take their size from their symbols' art (not saved).
doc.resolve_inline_art();
// Ruler guides a reader left in the saved list become nodes on their layers.
@@ -403,6 +422,8 @@ impl Session {
st.opened_as_tab = old.opened_as_tab;
st.revision = old.revision + 1;
st.format = old.format;
// What scripts' commands did to the document stays until the person saves it.
st.by_script = old.by_script.clone();
st.save_options = old.save_options.clone();
// The remembered artboard pick follows the artboards it named when the file read back has
// the artboards the document had at the save, in the same order and with the same ids (a
+72 -16
View File
@@ -1,12 +1,17 @@
use super::{
Arc, Document, EngineError, Interaction, LastTransform, NamedStep, Result, Selection, Session, TOO_DEEP, Value, cmd, deselect_hidden, doc_sane,
objects_in_range,
Arc, Document, EngineError, Interaction, LastTransform, NamedStep, NodeKind, Result, Selection, Session, TOO_DEEP, Value, cmd, deselect_hidden,
doc_sane, objects_in_range,
};
use crate::doc_state::objects_only;
impl Session {
/// Run `f` on a mutable copy of the active document. Outside an interaction this records one
/// undo step labelled `label`; inside one it just mutates (the interaction commits later).
pub fn edit<T>(&mut self, label: &str, f: impl FnOnce(&mut Document, &mut Selection) -> Result<T>) -> Result<T> {
self.revealing(|s| s.edit_unwatched(label, f))
}
fn edit_unwatched<T>(&mut self, label: &str, f: impl FnOnce(&mut Document, &mut Selection) -> Result<T>) -> Result<T> {
if self.script_running() {
return Err(EngineError::Busy);
}
@@ -197,19 +202,41 @@ impl Session {
/// Change only the selection (not an undo step).
pub fn select(&mut self, f: impl FnOnce(&Document, &mut Selection)) -> Result<()> {
self.revealing(|s| s.select_unwatched(f))
}
fn select_unwatched(&mut self, f: impl FnOnce(&Document, &mut Selection)) -> Result<()> {
self.active_appearance_item = None;
let menu = self.menu.clone();
let st = self.doc_mut()?;
let before = st.selection.objects.clone();
let new_art = st.selection.new_art.clone();
let record = if st.selection_record().is_some() { st.selection_record.take() } else { None };
f(&st.doc, &mut st.selection);
st.selection.prune(&st.doc);
// Lock Guides locks the paths made into guides too (#1534), and Lock Slices and Hide
// Slices keep the slices out, whatever selects them.
deselect_hidden(&menu, &st.doc, &mut st.selection);
// The art on a locked artboard can't be selected, whatever selects it, except new art
// that was selected and still is.
st.protect_locked_artboards(&before, &new_art, None);
let added = objects_only(&st.selection) && st.selection.objects.starts_with(&before);
// Objects added to objects this checked in the same document, with Lock Guides as it was
// then and no art on a locked artboard to protect, are checked alone, by the rules `prune`
// and `deselect_hidden` apply to an object.
let settled = record.as_ref().is_some_and(|r| r.settled == Some(menu.guides_locked))
&& st.selection.new_art.is_empty()
&& st.doc.new_art.get().is_empty()
&& !st.doc.artboards.iter().any(|a| a.locked);
if added && settled {
let doc = &st.doc;
let tail = st.selection.objects.split_off(before.len());
st.selection.objects.extend(tail.into_iter().filter(|id| {
doc.node(*id).is_some_and(|n| !n.is_ruler_guide() && !(menu.guides_locked && matches!(n.kind, NodeKind::Path { guide: true, .. })))
}));
} else {
st.selection.prune(&st.doc);
// Lock Guides locks the paths made into guides too (#1534), and Lock Slices and Hide
// Slices keep the slices out, whatever selects them.
deselect_hidden(&menu, &st.doc, &mut st.selection);
// The art on a locked artboard can't be selected, whatever selects it, except new art
// that was selected and still is.
st.protect_locked_artboards(&before, &new_art, None);
}
st.record_selection(record, menu.guides_locked);
// Selecting art makes its layer (or sublayer) the current one, as in the Layers panel of
// the reference app: new art then goes beside it.
if st.selection.objects != before
@@ -301,6 +328,7 @@ impl Session {
selection: Arc::new(st.selection.clone()),
preview: None,
paint,
used_defaults_only: false,
preview_paint: None,
color_mode_paints: None,
deferred_color_mode: None,
@@ -312,6 +340,7 @@ impl Session {
plane_placed: false,
copies: None,
move_box: std::sync::OnceLock::new(),
keep_on_switch: false,
});
Ok(())
}
@@ -322,7 +351,8 @@ impl Session {
return Err(EngineError::Busy);
}
// While the Live Paint Bucket is active, paint previews change only the bucket's colors, so
// each preview starts from the colors the interaction began with.
// each preview starts from the colors the interaction began with; so does a preview with
// `defaultsOnly: true`, and one after it.
let bucket = self.bucket_paints();
let (paint, restore_paint) = {
let menu = self.menu.clone();
@@ -337,9 +367,11 @@ impl Session {
st.doc = it.doc.clone();
// A batch, or a preview that changed the new-art paints (a pattern rename), started from
// the paints the interaction began with.
it.used_defaults_only |= cmd::asks_defaults_only(params);
let restore_paint = bucket
|| cmd == "command.batch"
|| it.preview.as_ref().is_some_and(|(id, _)| id == "command.batch")
|| it.used_defaults_only
|| it.preview.as_ref().is_some_and(|(id, p)| id == "command.batch" || cmd::asks_defaults_only(p))
|| it.color_mode_paints.is_some();
let paint = it.paint.clone();
it.preview_paint = None;
@@ -369,6 +401,8 @@ impl Session {
let outer = std::mem::replace(&mut self.previewing, true);
let r = self.execute(cmd, params);
self.previewing = outer;
// A step inside a batch that changed only the defaults counts as well.
let ran_defaults_only = self.defaults_only_ran.is_some();
if let Some(paint) = color_mode_paint {
self.paint = paint;
}
@@ -376,6 +410,7 @@ impl Session {
let batch_paint = (r.is_ok() && cmd == "command.batch").then(|| self.paint.clone());
let st = self.doc_mut()?;
if let Some(it) = &mut st.interaction {
it.used_defaults_only |= ran_defaults_only;
// A failed preview leaves the document at the snapshot, so nothing is left to commit
// (not even an earlier successful preview, which the reset above already undid).
it.preview = r.is_ok().then(|| (cmd.to_string(), params));
@@ -390,6 +425,17 @@ impl Session {
}
pub fn commit_interaction(&mut self) -> Result<()> {
// The interaction is taken below, so its starting state is read first: the commit is what
// the previews that came before it changed.
let before = (self.depth == 0).then(|| self.active().and_then(|st| st.interaction.as_ref().map(|it| st.layers_view_before(it)))).flatten();
let r = self.commit_interaction_unwatched();
if let Some(before) = before {
self.reveal_since(&before);
}
r
}
fn commit_interaction_unwatched(&mut self) -> Result<()> {
self.clear_deferred_overlay_cache();
self.decoded_images.empty();
if let Some(paint) = self.active().and_then(|st| st.interaction.as_ref()).and_then(|it| it.preview_paint.clone()) {
@@ -433,11 +479,12 @@ impl Session {
let m = cmd::matrix_param(&preview.1, "matrix");
if let Some(m) = m {
// The options are the last preview's params with the values it noted, without the
// matrix and the ids.
// matrix, the ids and `drawBehind` (Transform Again puts its copies above).
let mut options = preview.1.clone();
if let Some(o) = options.as_object_mut() {
o.remove("matrix");
o.remove("ids");
o.remove("drawBehind");
}
st.last_transform = Some(LastTransform::Matrix(m, options));
st.last_perspective = None;
@@ -484,12 +531,18 @@ impl Session {
self.decoded_images.empty();
self.pending_paint = None;
// While the Live Paint Bucket is active, a previewed color is the bucket's color, which the
// cancel puts back as well.
// cancel puts back as well, as it does a color previewed with `defaultsOnly: true`.
let bucket = self.bucket_paints();
let used_defaults_only = self.active().and_then(|st| st.interaction.as_ref()).is_some_and(|it| it.used_defaults_only);
if let Some(paint) = self
.active()
.and_then(|st| st.interaction.as_ref())
.filter(|it| bucket || it.preview.as_ref().is_some_and(|(id, _)| id == "command.batch") || it.color_mode_paints.is_some())
.filter(|it| {
bucket
|| it.used_defaults_only
|| it.preview.as_ref().is_some_and(|(id, p)| id == "command.batch" || cmd::asks_defaults_only(p))
|| it.color_mode_paints.is_some()
})
.map(|it| it.paint.clone())
{
self.paint = paint;
@@ -502,8 +555,11 @@ impl Session {
// A canceled preview's Assign Profile is undone with it.
self.sync_front_profiles();
// With New Art Has Basic Appearance off, new art takes the appearance of the selection as
// the document has it again, not as a preview left it.
self.inherit_new_art();
// the document has it again, not as a preview left it. An interaction that changed only the
// defaults (`defaultsOnly: true`) leaves the defaults it began with.
if !used_defaults_only {
self.inherit_new_art();
}
Ok(())
}
Loaded 100 of 1307 files, more files were not shown because too many files have changed in this diff. Show more