mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-19 06:38:44 +00:00
Merge main into fix/metafile-empty-artboard-first
This commit is contained in:
@@ -407,7 +407,18 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
/// The command `id`: a built-in one, or a command an installed plug-in adds
|
||||
/// ([`plugin::command_specs`]).
|
||||
pub fn find_command(id: &str) -> Option<&'static CommandSpec> {
|
||||
command_specs().iter().find(|c| c.id == id).or_else(|| plugin::find_spec(id))
|
||||
static INDEX: std::sync::OnceLock<std::collections::HashMap<&'static str, &'static CommandSpec>> = std::sync::OnceLock::new();
|
||||
INDEX.get_or_init(|| index_by_id(command_specs())).get(id).copied().or_else(|| plugin::find_spec(id))
|
||||
}
|
||||
|
||||
/// `specs` by id. An id that more than one spec has names the first of them, as a search of
|
||||
/// `specs` in order finds.
|
||||
pub(crate) fn index_by_id(specs: &[CommandSpec]) -> std::collections::HashMap<&'static str, &CommandSpec> {
|
||||
let mut index = std::collections::HashMap::with_capacity(specs.len());
|
||||
for spec in specs {
|
||||
index.entry(spec.id).or_insert(spec);
|
||||
}
|
||||
index
|
||||
}
|
||||
|
||||
/// Runs command `spec`'s implementation with `p`. A plug-in command's runs the plug-in
|
||||
@@ -821,10 +832,12 @@ pub(crate) fn unique_name_from(base: &str, next: &mut std::collections::HashMap<
|
||||
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};
|
||||
pub use docmenu::guide_indexes;
|
||||
pub(crate) use edit::{settle_interaction, typing_in_progress};
|
||||
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};
|
||||
pub use plugin_call::{Location, ParamsPlace, key_location, location_in, location_keys};
|
||||
@@ -886,6 +899,9 @@ pub(crate) use buildcmds::TracePresetChanges;
|
||||
/// The shapes a group selected alone gives the Pathfinder panel.
|
||||
pub use pathops::shape_count;
|
||||
|
||||
/// The Shape Mode commands' warning when a selected open path encloses no area.
|
||||
pub use pathops::SHAPE_MODE_OPEN_PATH_NO_AREA;
|
||||
|
||||
/// The gaps View › Show Live Paint Gaps shows on a Live Paint group.
|
||||
pub use buildcmds::live_paint_gaps;
|
||||
|
||||
@@ -901,6 +917,10 @@ pub use brushsym::current_symbol;
|
||||
/// Data window reads files by it too).
|
||||
pub use variablecmds::utf16_order_without_mark;
|
||||
|
||||
/// How the Graph Data window's Import Data and Import Data Sets' `%` columns read a graph data
|
||||
/// file: its size limit, its text, its cells and the data `graph.setData` takes from them.
|
||||
pub use graph::{MAX_GRAPH_DATA_FILE, graph_cell_text, graph_data_from_grid, graph_data_text, graph_grid_from_text};
|
||||
|
||||
/// The Variables panel's sort (`variable.sort`) and its rows in that order.
|
||||
pub use variablecmds::{VariableSort, VariableSortKey, variable_order};
|
||||
|
||||
|
||||
@@ -14,8 +14,10 @@ mod pen;
|
||||
mod select;
|
||||
mod shapes;
|
||||
mod typetools;
|
||||
mod units;
|
||||
|
||||
pub(crate) use image::{DecodedImages, refresh_color_masks};
|
||||
pub use packaging::{fold_source, print_hidden};
|
||||
pub(crate) use packaging::{role_swatch_edited, role_swatches_merged};
|
||||
|
||||
use super::CommandSpec;
|
||||
@@ -35,5 +37,6 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
v.extend(select::specs());
|
||||
v.extend(shapes::specs());
|
||||
v.extend(typetools::specs());
|
||||
v.extend(units::specs());
|
||||
v
|
||||
}
|
||||
|
||||
@@ -6,8 +6,10 @@
|
||||
//! (Object › Plug-ins › Packaging Tools) and its Fold Lines panel are the UI's.
|
||||
|
||||
mod check;
|
||||
mod fold;
|
||||
mod roles;
|
||||
|
||||
pub use fold::{fold_source, print_hidden};
|
||||
pub(crate) use roles::{role_swatch_edited, role_swatches_merged};
|
||||
|
||||
use super::super::CommandSpec;
|
||||
@@ -15,6 +17,7 @@ use super::super::CommandSpec;
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
let mut v = roles::specs();
|
||||
v.extend(check::specs());
|
||||
v.extend(fold::specs());
|
||||
v
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::PathData;
|
||||
use vectorcraft_three_d::fold::{FoldLine, IssueCode, LineKind, MAX_SEGMENTS, blanks};
|
||||
use vectorcraft_three_d::fold::{Blank, FoldLine, Issue, IssueCode, LineKind, MAX_SEGMENTS, blanks};
|
||||
|
||||
use super::super::super::pathops::length_given;
|
||||
use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, switch_or};
|
||||
@@ -14,7 +14,7 @@ use crate::{Result, Session};
|
||||
const CHECK: &str = "addon.packaging.check";
|
||||
|
||||
/// How far apart the ends of two lines may be and still be joined, in points.
|
||||
const TOLERANCE: (f64, f64, f64) = (0.01, 0.1, 10.0);
|
||||
pub(super) const TOLERANCE: (f64, f64, f64) = (0.01, 0.1, 10.0);
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
@@ -101,23 +101,44 @@ fn kind(role: Role) -> LineKind {
|
||||
}
|
||||
}
|
||||
|
||||
fn check(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let select = switch_or(p, "select", false, CHECK)?;
|
||||
let tolerance = match length_given(p, "tolerance", CHECK)? {
|
||||
None => TOLERANCE.1,
|
||||
Some(t) if (TOLERANCE.0..=TOLERANCE.2).contains(&t) => t,
|
||||
Some(_) => return Err(bad(CHECK, format!("`tolerance` must be from {} to {} pt", TOLERANCE.0, TOLERANCE.2))),
|
||||
};
|
||||
/// The fold lines a check or a fold reads: where they came from (`ids`, `selection` or
|
||||
/// `document`), the lines, and the ids of those on a non-printing layer.
|
||||
pub(super) struct Lines {
|
||||
pub scope: &'static str,
|
||||
pub lines: Vec<FoldLine>,
|
||||
pub non_printing: Vec<u64>,
|
||||
}
|
||||
|
||||
/// The tolerance `p` gives for `cmd`, or the default.
|
||||
pub(super) fn tolerance(p: &Value, cmd: &str) -> Result<f64> {
|
||||
match length_given(p, "tolerance", cmd)? {
|
||||
None => Ok(TOLERANCE.1),
|
||||
Some(t) if (TOLERANCE.0..=TOLERANCE.2).contains(&t) => Ok(t),
|
||||
Some(_) => Err(bad(cmd, format!("`tolerance` must be from {} to {} pt", TOLERANCE.0, TOLERANCE.2))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The fold lines among the objects `p` names for `cmd` (`ids`, else the selection), or, while
|
||||
/// nothing is selected and `ids` is left out, every shown fold line of the document. Hidden lines
|
||||
/// are left out in every scope, members of a selected group included.
|
||||
pub(super) fn lines(s: &Session, p: &Value, cmd: &str) -> Result<Lines> {
|
||||
let given = p.get("ids").is_some_and(|v| !v.is_null());
|
||||
let roots = checked_ids_or_selection(s, p, CHECK)?;
|
||||
let roots = checked_ids_or_selection(s, p, cmd)?;
|
||||
let d = &s.doc()?.doc;
|
||||
// Hidden lines are left out in every scope, members of a selected group included.
|
||||
let shown = |ids: Vec<NodeId>| ids.into_iter().filter(|id| d.is_visible(*id)).collect::<Vec<_>>();
|
||||
let (scope, targets) = match (given, roots.is_empty()) {
|
||||
(true, _) => ("ids", shown(role_targets(d, &roots, false).0)),
|
||||
(false, false) => ("selection", shown(role_targets(d, &roots, false).0)),
|
||||
(false, true) => ("document", shown_targets(d)),
|
||||
};
|
||||
Ok(match (given, roots.is_empty()) {
|
||||
(true, _) => lines_of(d, "ids", shown(role_targets(d, &roots, false).0)),
|
||||
(false, false) => lines_of(d, "selection", shown(role_targets(d, &roots, false).0)),
|
||||
(false, true) => document_lines(d),
|
||||
})
|
||||
}
|
||||
|
||||
/// Every shown fold line of `d`.
|
||||
pub(super) fn document_lines(d: &Document) -> Lines {
|
||||
lines_of(d, "document", shown_targets(d))
|
||||
}
|
||||
|
||||
fn lines_of(d: &Document, scope: &'static str, targets: Vec<NodeId>) -> Lines {
|
||||
let table = RoleTable::of(d);
|
||||
let mut lines = vec![];
|
||||
let mut non_printing = vec![];
|
||||
@@ -136,12 +157,21 @@ fn check(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
segments = segments.saturating_add(path.subpaths.iter().map(|sp| sp.segment_count()).sum());
|
||||
lines.push(FoldLine { path, kind: kind(role), key: id.0 });
|
||||
}
|
||||
let (found, mut issues) = blanks(&lines, tolerance);
|
||||
if !non_printing.is_empty() {
|
||||
issues.push(vectorcraft_three_d::fold::Issue { code: IssueCode::NonPrinting, keys: non_printing, at: None });
|
||||
Lines { scope, lines, non_printing }
|
||||
}
|
||||
|
||||
/// The blanks `lines` make and their issues, the non-printing one last.
|
||||
pub(super) fn found(lines: &Lines, tolerance: f64) -> (Vec<Blank>, Vec<Issue>) {
|
||||
let (found, mut issues) = blanks(&lines.lines, tolerance);
|
||||
if !lines.non_printing.is_empty() {
|
||||
issues.push(Issue { code: IssueCode::NonPrinting, keys: lines.non_printing.clone(), at: None });
|
||||
}
|
||||
let ok = !issues.iter().any(|i| i.code.is_error());
|
||||
let rows: Vec<Value> = issues
|
||||
(found, issues)
|
||||
}
|
||||
|
||||
/// `issues` as the rows `addon.packaging.check` and `addon.packaging.fold` answer with.
|
||||
pub(super) fn issue_rows(issues: &[Issue], scope: &str) -> Vec<Value> {
|
||||
issues
|
||||
.iter()
|
||||
.map(|i| {
|
||||
let mut row = json!({
|
||||
@@ -155,7 +185,18 @@ fn check(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
row
|
||||
})
|
||||
.collect();
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn check(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let select = switch_or(p, "select", false, CHECK)?;
|
||||
let tolerance = tolerance(p, CHECK)?;
|
||||
let lines = lines(s, p, CHECK)?;
|
||||
let scope = lines.scope;
|
||||
let (found, issues) = found(&lines, tolerance);
|
||||
let d = &s.doc()?.doc;
|
||||
let ok = !issues.iter().any(|i| i.code.is_error());
|
||||
let rows = issue_rows(&issues, scope);
|
||||
if select {
|
||||
let mut ids: Vec<NodeId> = issues.iter().flat_map(|i| i.keys.iter().map(|k| NodeId(*k))).filter(|id| d.node(*id).is_some()).collect();
|
||||
ids.sort_unstable_by_key(|id| id.0);
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
//! Fold Preview's model (`addon.packaging.fold`): a blank folded into its 3D shape by
|
||||
//! [`vectorcraft_three_d::fold::fold`], and what the Fold Preview window needs to draw it: the
|
||||
//! document's blanks ([`fold_source`]) and the objects its print leaves out ([`print_hidden`]).
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
|
||||
use vectorcraft_three_d::fold::{Blank, Issue, fold, pick};
|
||||
|
||||
use super::super::super::{CommandSpec, bad, cmd, finite_numbers, has_doc, number_or};
|
||||
use super::check::{TOLERANCE, document_lines, found, issue_rows, lines, tolerance};
|
||||
use super::roles::{RoleTable, can_carry};
|
||||
use crate::{Result, Session};
|
||||
|
||||
const FOLD: &str = "addon.packaging.fold";
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
query "addon.packaging.fold",
|
||||
"Fold",
|
||||
[],
|
||||
None,
|
||||
"{ids?: [id…] (default: the selection), base?: [x, y] (the panel under this point; default: the largest panel), amount?: 0..1 (1), tolerance?: pt 0.01..10 (0.1)} fold the blank that the fold lines among the objects make (as addon.packaging.check finds them; while nothing is selected and ids is left out, every fold line of the document) into its 3D shape. The base panel stays in place; every other panel turns about the hinges that join it to the base, each by its angle times amount: a Crease or a Perforation by 90° away from the printed side, a Partial Cut by 90° toward it. Hinges that close a loop of panels are not turned about: gap is how far apart their two placements end up when every hinge is folded all the way, whatever amount is, and closes is true within tolerance or 0.5% of the hinge's length. Changes nothing in the document → {ok (no error), blank (the index of the blank folded, or null when none is), blanks, base, panels: [{outline (SVG path data, document coordinates), frame: {x, y, z, origin} (where the flat blank's x and y directions, its printed side and its origin go, in points: x right, y up, z toward the printed side of the flat blank), parent (null for the base and loose panels), depth}], hinges: [{a, b, angle (degrees), kind: tree|closing, closes, gap}], collisions: [[a, b]] (panels that pass through each other; panels stacked in one plane do not), issues (as addon.packaging.check)}. Errors: a base point in no panel",
|
||||
has_doc,
|
||||
fold_command
|
||||
)]
|
||||
}
|
||||
|
||||
/// The blanks the shown fold lines of `d` make, and their issues (`addon.packaging.check` on the
|
||||
/// whole document): what the Fold Preview window folds.
|
||||
pub fn fold_source(d: &Document) -> (Vec<Blank>, Vec<Issue>) {
|
||||
found(&document_lines(d), TOLERANCE.1)
|
||||
}
|
||||
|
||||
/// The objects the print on a folded blank leaves out: the layers that do not print and, unless
|
||||
/// `fold_lines`, every object with a line role.
|
||||
pub fn print_hidden(d: &Document, fold_lines: bool) -> Vec<NodeId> {
|
||||
fn walk(n: &Node, table: &RoleTable, fold_lines: bool, out: &mut Vec<NodeId>) {
|
||||
match &n.kind {
|
||||
NodeKind::Layer { printable: false, .. } => out.push(n.id),
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => children.iter().for_each(|c| walk(c, table, fold_lines, out)),
|
||||
_ if !fold_lines && can_carry(n) && table.role_of(n).is_some() => out.push(n.id),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let table = RoleTable::of(d);
|
||||
let mut out = vec![];
|
||||
d.layers.iter().for_each(|l| walk(l, &table, fold_lines, &mut out));
|
||||
out
|
||||
}
|
||||
|
||||
fn fold_command(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let tolerance = tolerance(p, FOLD)?;
|
||||
let amount = number_or(p, "amount", 1.0, FOLD)?;
|
||||
if !(0.0..=1.0).contains(&amount) {
|
||||
return Err(bad(FOLD, "`amount` must be from 0 to 1"));
|
||||
}
|
||||
let base = match p.get("base") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(v) => {
|
||||
let [x, y] = finite_numbers::<2>(v).ok_or_else(|| bad(FOLD, "`base` must be a point: [x, y]"))?;
|
||||
Some(vectorcraft_geom::Point::new(x, y))
|
||||
}
|
||||
};
|
||||
let lines = lines(s, p, FOLD)?;
|
||||
let (blanks, issues) = found(&lines, tolerance);
|
||||
let ok = !issues.iter().any(|i| i.code.is_error());
|
||||
let picked = pick(&blanks, base);
|
||||
if base.is_some() && picked.is_none() {
|
||||
return Err(bad(FOLD, "`base` is in no panel"));
|
||||
}
|
||||
let folded = picked.and_then(|(b, panel)| Some((b, blanks.get(b)?, fold(blanks.get(b)?, Some(panel), amount, tolerance)?)));
|
||||
let Some((index, blank, f)) = folded else {
|
||||
return Ok(json!({
|
||||
"ok": ok, "blank": null, "blanks": blanks.len(), "base": null, "panels": [], "hinges": [], "collisions": [],
|
||||
"issues": issue_rows(&issues, lines.scope),
|
||||
}));
|
||||
};
|
||||
let column = |m: &[[f64; 3]; 3], k: usize| json!([m[0][k], m[1][k], m[2][k]]);
|
||||
let panels: Vec<Value> = blank
|
||||
.panels
|
||||
.iter()
|
||||
.zip(&f.panels)
|
||||
.map(|(panel, placed)| {
|
||||
json!({
|
||||
"outline": panel.outline.to_bezpath().to_svg(),
|
||||
"frame": {"x": column(&placed.pose.m, 0), "y": column(&placed.pose.m, 1), "z": column(&placed.pose.m, 2), "origin": placed.pose.t},
|
||||
"parent": placed.parent,
|
||||
"depth": placed.depth,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let hinges: Vec<Value> = f
|
||||
.hinges
|
||||
.iter()
|
||||
.map(|h| json!({"a": h.a, "b": h.b, "angle": h.angle, "kind": if h.tree { "tree" } else { "closing" }, "closes": h.closes, "gap": h.gap}))
|
||||
.collect();
|
||||
Ok(json!({
|
||||
"ok": ok,
|
||||
"blank": index,
|
||||
"blanks": blanks.len(),
|
||||
"base": f.base,
|
||||
"panels": panels,
|
||||
"hinges": hinges,
|
||||
"collisions": f.collisions.iter().map(|(a, b)| [a, b]).collect::<Vec<_>>(),
|
||||
"issues": issue_rows(&issues, lines.scope),
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,157 @@
|
||||
//! Tests for the Fold Preview's model: a blank drawn in a document folded into its 3D shape.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::*;
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn path(s: &mut Session, d: &str) -> u64 {
|
||||
s.execute("path.create", &json!({ "d": d })).unwrap()["id"].as_u64().unwrap()
|
||||
}
|
||||
|
||||
fn role(s: &mut Session, role: &str, ids: &[u64]) {
|
||||
s.execute("addon.packaging.setRole", &json!({ "role": role, "ids": ids })).unwrap();
|
||||
}
|
||||
|
||||
fn fold(s: &mut Session, p: Value) -> Value {
|
||||
s.execute("addon.packaging.fold", &p).unwrap()
|
||||
}
|
||||
|
||||
/// A tray blank: a 100 pt base (x 140 to 240, y 140 to 240) with a 40 pt wall on each side →
|
||||
/// (outline, creases).
|
||||
fn tray(s: &mut Session) -> (u64, Vec<u64>) {
|
||||
let outline = path(s, "M140 100 L240 100 L240 140 L280 140 L280 240 L240 240 L240 280 L140 280 L140 240 L100 240 L100 140 L140 140 Z");
|
||||
let creases = vec![path(s, "M140 140 L240 140"), path(s, "M240 140 L240 240"), path(s, "M240 240 L140 240"), path(s, "M140 240 L140 140")];
|
||||
role(s, "cut", &[outline]);
|
||||
role(s, "crease", &creases);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
(outline, creases)
|
||||
}
|
||||
|
||||
fn vector(v: &Value) -> [f64; 3] {
|
||||
let a = v.as_array().unwrap();
|
||||
[a[0].as_f64().unwrap(), a[1].as_f64().unwrap(), a[2].as_f64().unwrap()]
|
||||
}
|
||||
|
||||
/// The middle of the bounds of the points of SVG path data `d` (absolute moves and lines only).
|
||||
fn middle(d: &str) -> [f64; 2] {
|
||||
let n: Vec<f64> = d.split(|c: char| !(c.is_ascii_digit() || c == '.' || c == '-')).filter_map(|t| t.parse().ok()).collect();
|
||||
let span = |k: usize| n.iter().skip(k).step_by(2).fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), &t| (lo.min(t), hi.max(t)));
|
||||
let ((x0, x1), (y0, y1)) = (span(0), span(1));
|
||||
[(x0 + x1) / 2.0, (y0 + y1) / 2.0]
|
||||
}
|
||||
|
||||
fn near(a: [f64; 3], b: [f64; 3]) -> bool {
|
||||
a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-9)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tray_folds_its_walls_up_round_the_base() {
|
||||
let mut s = session();
|
||||
tray(&mut s);
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
let r = fold(&mut s, json!({}));
|
||||
assert_eq!((r["ok"].as_bool(), r["blank"].as_u64(), r["blanks"].as_u64()), (Some(true), Some(0), Some(1)), "{r}");
|
||||
let panels = r["panels"].as_array().unwrap();
|
||||
assert_eq!(panels.len(), 5);
|
||||
let base = r["base"].as_u64().unwrap() as usize;
|
||||
let frame = &panels[base]["frame"];
|
||||
assert!(
|
||||
near(vector(&frame["x"]), [1.0, 0.0, 0.0]) && near(vector(&frame["z"]), [0.0, 0.0, 1.0]) && near(vector(&frame["origin"]), [0.0; 3]),
|
||||
"{frame}"
|
||||
);
|
||||
assert!(panels[base]["parent"].is_null());
|
||||
assert!(panels[base]["outline"].as_str().unwrap().starts_with('M'), "SVG path data");
|
||||
for (i, p) in panels.iter().enumerate().filter(|(i, _)| *i != base) {
|
||||
assert_eq!((p["parent"].as_u64(), p["depth"].as_u64()), (Some(base as u64), Some(1)), "{p}");
|
||||
// Each wall stands square to the base, below it (away from the print), its print facing out:
|
||||
// away from the base's middle (190, 190), toward the side the wall lies on.
|
||||
let [cx, cy] = middle(p["outline"].as_str().unwrap());
|
||||
let (x, y, o) = (vector(&p["frame"]["x"]), vector(&p["frame"]["y"]), vector(&p["frame"]["origin"]));
|
||||
let placed: [f64; 3] = std::array::from_fn(|k| o[k] + x[k] * cx - y[k] * cy);
|
||||
let (dx, dy) = (cx - 190.0, 190.0 - cy);
|
||||
let out = if dx.abs() > dy.abs() { [dx.signum(), 0.0, 0.0] } else { [0.0, dy.signum(), 0.0] };
|
||||
assert!(near(vector(&p["frame"]["z"]), out), "wall {i}: {p}");
|
||||
assert!((placed[2] + 20.0).abs() < 1e-9, "wall {i}'s middle is 20 pt below the base: {placed:?}");
|
||||
}
|
||||
let hinges = r["hinges"].as_array().unwrap();
|
||||
assert_eq!(hinges.len(), 4);
|
||||
assert!(hinges.iter().all(|h| h["kind"] == "tree" && h["angle"] == 90.0 && h["closes"] == true), "{r}");
|
||||
assert_eq!(r["collisions"], json!([]));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "a fold records no undo step");
|
||||
|
||||
// Flat, every frame is the flat blank's own.
|
||||
let r = fold(&mut s, json!({ "amount": 0 }));
|
||||
for p in r["panels"].as_array().unwrap() {
|
||||
assert!(near(vector(&p["frame"]["z"]), [0.0, 0.0, 1.0]) && near(vector(&p["frame"]["origin"]), [0.0; 3]), "{p}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_base_is_the_panel_under_a_point() {
|
||||
let mut s = session();
|
||||
tray(&mut s);
|
||||
// The left wall: x 100 to 140, y 140 to 240.
|
||||
let r = fold(&mut s, json!({ "base": [120, 190] }));
|
||||
let base = r["base"].as_u64().unwrap() as usize;
|
||||
let panels = r["panels"].as_array().unwrap();
|
||||
assert!(near(vector(&panels[base]["frame"]["z"]), [0.0, 0.0, 1.0]));
|
||||
// The tray's base is now a child of the wall, and the other walls its children.
|
||||
let depths: Vec<u64> = panels.iter().map(|p| p["depth"].as_u64().unwrap()).collect();
|
||||
let mut sorted = depths.clone();
|
||||
sorted.sort_unstable();
|
||||
assert_eq!(sorted, [0, 1, 2, 2, 2], "{depths:?}");
|
||||
let e = s.execute("addon.packaging.fold", &json!({ "base": [10, 10] })).unwrap_err().to_string();
|
||||
assert!(e.contains("`base` is in no panel"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_values_are_refused() {
|
||||
let mut s = session();
|
||||
tray(&mut s);
|
||||
for (p, want) in [
|
||||
(json!({ "amount": 1.5 }), "`amount` must be from 0 to 1"),
|
||||
(json!({ "amount": -0.1 }), "`amount` must be from 0 to 1"),
|
||||
(json!({ "amount": "1" }), "`amount` must be a number"),
|
||||
(json!({ "base": [1] }), "`base` must be a point"),
|
||||
(json!({ "base": "middle" }), "`base` must be a point"),
|
||||
(json!({ "tolerance": 50 }), "`tolerance` must be from"),
|
||||
] {
|
||||
let e = s.execute("addon.packaging.fold", &p).unwrap_err().to_string();
|
||||
assert!(e.contains(want), "{p}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_a_blank_nothing_is_folded_and_the_issues_say_why() {
|
||||
let mut s = session();
|
||||
let r = fold(&mut s, json!({}));
|
||||
assert_eq!((r["ok"].as_bool(), r["blank"].is_null(), r["blanks"].as_u64()), (Some(false), true, Some(0)), "{r}");
|
||||
assert_eq!(r["panels"], json!([]));
|
||||
assert_eq!(r["issues"][0]["code"], "noCut");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_print_leaves_out_fold_lines_and_layers_that_do_not_print() {
|
||||
let mut s = session();
|
||||
let (outline, creases) = tray(&mut s);
|
||||
let art = path(&mut s, "M150 150 L200 150 L200 200 Z");
|
||||
let notes = s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("layer.setProps", &json!({"id": notes, "printable": false})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let hidden: Vec<u64> = cmd::print_hidden(d, false).into_iter().map(|id| id.0).collect();
|
||||
for id in creases.iter().chain([&outline, ¬es]) {
|
||||
assert!(hidden.contains(id), "{id} in {hidden:?}");
|
||||
}
|
||||
assert!(!hidden.contains(&art));
|
||||
let shown: Vec<u64> = cmd::print_hidden(d, true).into_iter().map(|id| id.0).collect();
|
||||
assert_eq!(shown, vec![notes], "with the fold lines shown, only the layer is left out");
|
||||
let (blanks, issues) = cmd::fold_source(d);
|
||||
assert_eq!((blanks.len(), blanks[0].panels.len()), (1, 5));
|
||||
assert!(issues.is_empty(), "{issues:?}");
|
||||
}
|
||||
@@ -3,11 +3,13 @@
|
||||
//! anchor edits, Split / Add Points at Crossings, Slide Anchor Along Path, the Corner Tool's corners
|
||||
//! ([`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`]), Common Tangents ([`tangents`]) and Tangent Circle
|
||||
//! into Paths, Trim at Crossings ([`trim`]), Smooth Bridge ([`bridge`]), Common Tangents
|
||||
//! ([`tangents`]) and Tangent Circle
|
||||
//! ([`tangent_circle`]).
|
||||
//! Its tools, panels and submenu (Object › Plug-ins › Path Precision Tools) are the tools crate's
|
||||
//! and the UI's.
|
||||
|
||||
mod bridge;
|
||||
mod corners;
|
||||
#[cfg(test)]
|
||||
mod effect_tests;
|
||||
@@ -183,6 +185,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
v.extend(corners::specs());
|
||||
v.extend(shared_edge::specs());
|
||||
v.extend(trim::specs());
|
||||
v.extend(bridge::specs());
|
||||
v.extend(tangent_circle::specs());
|
||||
v.extend(tangents::specs());
|
||||
v
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
//! Smooth Bridge: two selected circles joined into one outline by two concave arcs that touch both
|
||||
//! circles, replacing the circles or added above them.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{NodeId, NodeKind};
|
||||
use vectorcraft_geom::PathData;
|
||||
use vectorcraft_pathops::addons::pathtools as pt;
|
||||
|
||||
use super::super::super::pathops::{Beside, remove_each};
|
||||
use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_selection, switch_or};
|
||||
use super::given;
|
||||
use crate::{EngineError, Result, Session};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
/// The command, and its undo step's name.
|
||||
const C: &str = "addon.pathtools.bridge";
|
||||
const LABEL: &str = "Smooth Bridge";
|
||||
/// The arcs' radius as a percentage of the smaller circle's radius: by default, and the range.
|
||||
const RADIUS: f64 = 100.0;
|
||||
const RADII: (f64, f64) = (1.0, 1000.0);
|
||||
|
||||
pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"addon.pathtools.bridge",
|
||||
"Smooth Bridge",
|
||||
["Object", "Plug-ins", "Path Precision Tools"],
|
||||
None,
|
||||
"{radius?: % 1..1000 (100; the radius of the bridge's two arcs as a percentage of the smaller circle's radius: larger makes a wider, gentler bridge), keepOriginals?: bool (false: the outline replaces the two circles, painted as the upper one; true: it goes directly above the upper one and the circles stay), ids?: [id, id] (default: the selection)} join two circles (paths whose outline is a circle, not hidden or locked) into one closed outline: around each circle on its side away from the other, and along two concave arcs, one on each side, that touch both circles so the outline runs on smoothly into them. Overlapping and touching circles are joined too; one circle inside the other, or circles too far apart for the radius (the arcs would not reach both, or would cross), is an error, which suggests a larger radius when one up to 1000% would bridge them. One undo step; the outline is selected → {id}",
|
||||
has_selection,
|
||||
bridge
|
||||
)]
|
||||
}
|
||||
|
||||
fn bridge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let percent = given(p, "radius", Some(RADII), C)?.unwrap_or(RADIUS);
|
||||
let keep = switch_or(p, "keepOriginals", false, C)?;
|
||||
let roots = checked_ids_or_selection(s, p, C)?;
|
||||
let circles: Vec<(NodeId, pt::Circle)> = {
|
||||
let d = &s.doc()?.doc;
|
||||
let editable = d.editable();
|
||||
d.paint_order(roots.iter().copied())
|
||||
.into_iter()
|
||||
.filter_map(|id| match &d.node(id)?.kind {
|
||||
NodeKind::Path { path, guide: false, clipping: false, .. } if editable(id) => Some((id, pt::circle_of(path)?)),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let ([(below, a), (above, b)], 2) = (circles.as_slice(), roots.len()) else {
|
||||
return Err(bad(C, "select two circles to bridge"));
|
||||
};
|
||||
let (below, above) = (*below, *above);
|
||||
let at = |percent: f64| pt::smooth_bridge(*a, *b, a.radius.min(b.radius) * percent / 100.0);
|
||||
let outline = match at(percent) {
|
||||
Ok(sp) => PathData::single(sp),
|
||||
Err(pt::BridgeError::Inside) => return Err(bad(C, "one circle is inside the other")),
|
||||
// A larger radius bridges circles a smaller one cannot, so only suggest one that is allowed.
|
||||
Err(pt::BridgeError::TooFar) if at(RADII.1).is_ok() => {
|
||||
return Err(bad(C, "the circles are too far apart for this radius: raise the radius"));
|
||||
}
|
||||
Err(pt::BridgeError::TooFar) => return Err(bad(C, "the circles are too far apart for this radius")),
|
||||
Err(pt::BridgeError::Bad) => return Err(bad(C, "select two circles to bridge")),
|
||||
};
|
||||
let id = s.edit(LABEL, |d, sel| {
|
||||
let id = if keep {
|
||||
// A copy of the upper circle (its appearance) with the outline as its path, right above
|
||||
// it; the circles stay as they are, live shapes included.
|
||||
// Fresh ids throughout, its opacity mask's art included.
|
||||
let upper = d.node(above).cloned().ok_or(EngineError::NoNode(above))?;
|
||||
let mut n = d.reid(&upper);
|
||||
if let NodeKind::Path { path, live, .. } = &mut n.kind {
|
||||
*path = outline;
|
||||
*live = None;
|
||||
}
|
||||
let id = n.id;
|
||||
let mut beside = Beside::above(d, &[above]);
|
||||
beside.put(d, above, vec![n])?;
|
||||
beside.finish(d)?;
|
||||
id
|
||||
} else {
|
||||
// The upper circle becomes the outline (a plain path now) and the lower one goes.
|
||||
if let Some(NodeKind::Path { path, live, .. }) = d.node_mut(above).map(|n| &mut n.kind) {
|
||||
*path = outline;
|
||||
*live = None;
|
||||
}
|
||||
remove_each(d, &[below])?;
|
||||
above
|
||||
};
|
||||
sel.set([id]);
|
||||
Ok(id)
|
||||
})?;
|
||||
Ok(json!({ "id": id.0 }))
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
//! Smooth Bridge: the outline in place of the circles or above them, one undo step, the radius,
|
||||
//! and what it refuses.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{NodeId, NodeKind};
|
||||
use vectorcraft_geom::kurbo::Shape;
|
||||
|
||||
use crate::Session;
|
||||
|
||||
const BRIDGE: &str = "addon.pathtools.bridge";
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// A circle about (`x`, `y`) with radius `r`.
|
||||
fn circle(s: &mut Session, x: f64, y: f64, r: f64) -> NodeId {
|
||||
let id = s.execute("shape.ellipse", &json!({"x": x - r, "y": y - r, "width": 2.0 * r, "height": 2.0 * r})).unwrap()["id"].as_u64().unwrap();
|
||||
NodeId(id)
|
||||
}
|
||||
|
||||
fn select(s: &mut Session, ids: &[NodeId]) {
|
||||
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
|
||||
}
|
||||
|
||||
fn top_level(s: &Session) -> Vec<NodeId> {
|
||||
s.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id).collect()
|
||||
}
|
||||
|
||||
fn area(s: &Session, id: NodeId) -> f64 {
|
||||
s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().to_bezpath().area().abs()
|
||||
}
|
||||
|
||||
fn err(s: &mut Session, p: Value) -> String {
|
||||
s.execute(BRIDGE, &p).unwrap_err().to_string()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_circles_become_one_outline_in_the_upper_ones_place() {
|
||||
let mut s = session();
|
||||
let a = circle(&mut s, 100.0, 100.0, 20.0);
|
||||
let b = circle(&mut s, 160.0, 100.0, 20.0);
|
||||
select(&mut s, &[a, b]);
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
let r = s.execute(BRIDGE, &json!({})).unwrap();
|
||||
assert_eq!(r["id"], json!(b.0));
|
||||
assert_eq!(top_level(&s), [b]);
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let NodeKind::Path { path, live, .. } = &d.node(b).unwrap().kind else { panic!("a path") };
|
||||
assert!(live.is_none(), "a plain path now");
|
||||
assert!(path.subpaths.len() == 1 && path.subpaths[0].closed);
|
||||
let bounds = path.bounds().unwrap();
|
||||
assert!((bounds.x0 - 80.0).abs() < 1e-2 && (bounds.x1 - 180.0).abs() < 1e-2 && (bounds.height() - 40.0).abs() < 1e-2, "{bounds:?}");
|
||||
// Both circles and the bridge between them: more than the two circles' area.
|
||||
assert!(area(&s, b) > 2.0 * std::f64::consts::PI * 400.0);
|
||||
assert_eq!(s.doc().unwrap().selection.objects.to_vec(), [b]);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "one undo step");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(top_level(&s), [a, b]);
|
||||
assert!(matches!(&s.doc().unwrap().doc.node(b).unwrap().kind, NodeKind::Path { live: Some(_), .. }), "the circle is back as it was");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keep_originals_adds_the_outline_above_the_upper_circle() {
|
||||
let mut s = session();
|
||||
let a = circle(&mut s, 100.0, 100.0, 30.0);
|
||||
let b = circle(&mut s, 170.0, 100.0, 10.0);
|
||||
let c = circle(&mut s, 300.0, 250.0, 5.0);
|
||||
s.execute("paint.setFill", &json!({"ids": [b.0], "color": "#00ff00"})).unwrap();
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
let id = NodeId(s.execute(BRIDGE, &json!({"ids": [b.0, a.0], "keepOriginals": true, "radius": 400})).unwrap()["id"].as_u64().unwrap());
|
||||
assert_eq!(top_level(&s), [a, b, id, c]);
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.node(id).unwrap().appearance, d.node(b).unwrap().appearance, "painted as the upper circle");
|
||||
assert!(matches!(&d.node(a).unwrap().kind, NodeKind::Path { live: Some(_), .. }), "the circles stay as they are");
|
||||
assert!(matches!(&d.node(b).unwrap().kind, NodeKind::Path { live: Some(_), .. }));
|
||||
let bounds = d.node(id).unwrap().path_data().unwrap().bounds().unwrap();
|
||||
assert!((bounds.x0 - 70.0).abs() < 1e-2 && (bounds.x1 - 180.0).abs() < 1e-2 && (bounds.y0 - 70.0).abs() < 1e-2, "{bounds:?}");
|
||||
assert_eq!(s.doc().unwrap().selection.objects.to_vec(), [id]);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_kept_outline_gets_its_own_mask_art() {
|
||||
let mut s = session();
|
||||
let a = circle(&mut s, 100.0, 100.0, 20.0);
|
||||
let b = circle(&mut s, 150.0, 100.0, 20.0);
|
||||
let m = NodeId(s.execute("shape.rectangle", &json!({"x": 130, "y": 80, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("transparency.makeOpacityMask", &json!({"ids": [b.0, m.0]})).unwrap();
|
||||
let id = NodeId(s.execute(BRIDGE, &json!({"ids": [a.0, b.0], "keepOriginals": true})).unwrap()["id"].as_u64().unwrap());
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let art = |n: NodeId| d.node(n).unwrap().extras().mask.as_deref().map(|m| m.art.id);
|
||||
let (kept, copied) = (art(b).unwrap(), art(id).unwrap());
|
||||
assert_ne!(kept, copied, "the outline's mask art has ids of its own");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_larger_radius_makes_a_wider_bridge() {
|
||||
let area_at = |radius: f64| {
|
||||
let mut s = session();
|
||||
let a = circle(&mut s, 100.0, 100.0, 20.0);
|
||||
let b = circle(&mut s, 150.0, 100.0, 15.0);
|
||||
let id = NodeId(s.execute(BRIDGE, &json!({"ids": [a.0, b.0], "radius": radius})).unwrap()["id"].as_u64().unwrap());
|
||||
area(&s, id)
|
||||
};
|
||||
let (default, wider, widest) = (area_at(100.0), area_at(200.0), area_at(400.0));
|
||||
assert!(default < wider && wider < widest, "{default} {wider} {widest}");
|
||||
let (narrow, default, wide) = (area_at(65.0), default, area_at(300.0));
|
||||
assert!(narrow < default && default < wide, "{narrow} {default} {wide}");
|
||||
// The default is 100%: the smaller circle's radius.
|
||||
let mut s = session();
|
||||
let a = circle(&mut s, 100.0, 100.0, 20.0);
|
||||
let b = circle(&mut s, 150.0, 100.0, 15.0);
|
||||
let id = NodeId(s.execute(BRIDGE, &json!({"ids": [a.0, b.0]})).unwrap()["id"].as_u64().unwrap());
|
||||
assert!((area(&s, id) - default).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_and_touching_circles_are_joined() {
|
||||
for (gap, radius) in [(-15.0, 50.0), (0.0, 50.0), (0.0, 1.0)] {
|
||||
let mut s = session();
|
||||
let a = circle(&mut s, 100.0, 100.0, 20.0);
|
||||
let b = circle(&mut s, 140.0 + gap, 100.0, 20.0);
|
||||
let id = NodeId(s.execute(BRIDGE, &json!({"ids": [a.0, b.0], "radius": radius})).unwrap()["id"].as_u64().unwrap());
|
||||
assert_eq!(top_level(&s), [id], "gap {gap}");
|
||||
}
|
||||
// Unequal overlapping circles at every radius, the largest included.
|
||||
for radius in [1.0, 100.0, 300.0, 1000.0] {
|
||||
let mut s = session();
|
||||
let a = circle(&mut s, 100.0, 100.0, 10.0);
|
||||
let b = circle(&mut s, 125.0, 100.0, 30.0);
|
||||
let id = NodeId(s.execute(BRIDGE, &json!({"ids": [a.0, b.0], "radius": radius})).unwrap()["id"].as_u64().unwrap());
|
||||
assert_eq!(top_level(&s), [id], "radius {radius}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn far_apart_nested_and_other_objects_are_refused() {
|
||||
let mut s = session();
|
||||
let a = circle(&mut s, 50.0, 100.0, 10.0);
|
||||
let far = circle(&mut s, 250.0, 100.0, 10.0);
|
||||
let near = circle(&mut s, 110.0, 100.0, 10.0);
|
||||
let inner = circle(&mut s, 52.0, 100.0, 4.0);
|
||||
let square = NodeId(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap());
|
||||
let oval = NodeId(s.execute("shape.ellipse", &json!({"x": 300, "y": 0, "width": 40, "height": 20})).unwrap()["id"].as_u64().unwrap());
|
||||
let before = top_level(&s);
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
// 60 pt apart: the default radius (10 pt) cannot reach, the largest (100 pt) can.
|
||||
assert!(err(&mut s, json!({"ids": [a.0, near.0]})).ends_with("too far apart for this radius: raise the radius"));
|
||||
assert!(s.execute(BRIDGE, &json!({"ids": [a.0, near.0], "radius": 1000})).is_ok());
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
// 200 pt apart even the largest radius (1000%, 100 pt) closes the neck: it stays open only above
|
||||
// ((200 / 2)² − 10²) / (2 × 10) = 495 pt. No larger radius is suggested.
|
||||
for radius in [100, 1000] {
|
||||
let e = err(&mut s, json!({"ids": [a.0, far.0], "radius": radius}));
|
||||
assert!(e.ends_with("the circles are too far apart for this radius"), "{e}");
|
||||
}
|
||||
assert!(err(&mut s, json!({"ids": [a.0, inner.0]})).contains("one circle is inside the other"));
|
||||
for ids in [json!([a.0, square.0]), json!([a.0, oval.0]), json!([a.0]), json!([a.0, far.0, inner.0])] {
|
||||
assert!(err(&mut s, json!({ "ids": ids })).contains("select two circles to bridge"), "{ids}");
|
||||
}
|
||||
assert!(err(&mut s, json!({"ids": [a.0, far.0], "radius": 0.5})).contains("`radius` must be from 1 to 1000"));
|
||||
assert!(err(&mut s, json!({"ids": [a.0, far.0], "radius": 1001})).contains("`radius`"));
|
||||
assert!(err(&mut s, json!({"ids": [a.0, far.0], "radius": "big"})).contains("`radius` must be a number"));
|
||||
assert!(err(&mut s, json!({"ids": [a.0, far.0], "keepOriginals": "yes"})).contains("`keepOriginals` must be true or false"));
|
||||
assert_eq!(top_level(&s), before);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "nothing changed, no undo step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locked_and_hidden_circles_are_not_bridged() {
|
||||
let mut s = session();
|
||||
let a = circle(&mut s, 100.0, 100.0, 20.0);
|
||||
let b = circle(&mut s, 150.0, 100.0, 20.0);
|
||||
select(&mut s, &[b]);
|
||||
s.execute("object.lock", &json!({})).unwrap();
|
||||
assert!(err(&mut s, json!({"ids": [a.0, b.0]})).contains("select two circles to bridge"));
|
||||
s.execute("object.unlockAll", &json!({})).unwrap();
|
||||
select(&mut s, &[a]);
|
||||
s.execute("object.hide", &json!({})).unwrap();
|
||||
assert!(err(&mut s, json!({"ids": [a.0, b.0]})).contains("select two circles to bridge"));
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
//! Unit Converter (`addon.units.*`), a built-in add-on that shows one length in every unit at once.
|
||||
//! `addon.units.convert` reads a length as a number field reads it ([`Unit::parse`]: units and
|
||||
//! arithmetic) and gives it in each unit of Preferences › Units › East Asian Type
|
||||
//! ([`Unit::EAST_ASIAN`]), written as the fields write it ([`Unit::number`], [`Unit::format`]).
|
||||
//! `addon.units.selectionSize` gives the selection's width and height, measured as the Transform
|
||||
//! panel measures them, in the same units. Its panel and its place in Object › Plug-ins are the
|
||||
//! UI's; the panel applies a length to the selection with `object.setBounds`.
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{OrientedBox, Unit, decimal_point, finite_in_every_unit};
|
||||
use vectorcraft_render::effects;
|
||||
|
||||
use super::super::{CommandSpec, always, bad, cmd, has_selection};
|
||||
use crate::{Result, Session};
|
||||
|
||||
const CONVERT: &str = "addon.units.convert";
|
||||
const SELECTION_SIZE: &str = "addon.units.selectionSize";
|
||||
/// The most characters of a refused value an error message shows.
|
||||
const SHOWN_CHARS: usize = 64;
|
||||
/// The longest `value` or `unit` text `addon.units.convert` reads, in bytes.
|
||||
const MAX_TEXT_LEN: usize = 1024;
|
||||
/// The most `+ - * /` signs `addon.units.convert` reads in one `value`: [`Unit::parse`] takes one
|
||||
/// level of recursion per sign.
|
||||
const MAX_OPERATORS: usize = 128;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
query "addon.units.convert",
|
||||
"Convert Units",
|
||||
[],
|
||||
None,
|
||||
"{value: a length (a number, or text as a number field reads it, with a unit suffix and + - * / arithmetic: \"10mm\", \"1in/2\", \"2p6\", \"3cm*50%\"; a decimal comma reads as a point: \"0,5 mm\"; at most 1024 bytes and 128 operators), unit?: the unit of a number without a suffix (a unit's name, suffix or key: points, picas, inches, millimeters, centimeters, pixels, feetInches, meters, yards, feet, q, ha; default: points)} the length in every unit of Preferences › Units › East Asian Type, written as the number fields write it (rounded to 3 decimals in pt, px, picas, Q and Ha and to 4 in the others; pixels are points). Nothing in the document changes → {points, units: [{unit (its key), label, number (no suffix), text (with the suffix)}]}",
|
||||
always,
|
||||
convert
|
||||
),
|
||||
cmd!(
|
||||
query "addon.units.selectionSize",
|
||||
"Selection Size in Units",
|
||||
[],
|
||||
None,
|
||||
"{} the selection's width and height as the Transform panel shows them (its bounding box, rotated with rotated objects; with Use Preview Bounds, the visual bounds; with anchor points selected (Direct Selection), the box around those points), each as addon.units.convert gives it → {width: {points, units}, height: {points, units}}",
|
||||
has_selection,
|
||||
selection_size
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// The length `pt` (points) in every unit of [`Unit::EAST_ASIAN`]: `{points, units: [{unit,
|
||||
/// label, number, text}]}`.
|
||||
pub fn in_every_unit(pt: f64) -> Value {
|
||||
let units: Vec<Value> =
|
||||
Unit::EAST_ASIAN.iter().map(|u| json!({"unit": u.key(), "label": u.label(), "number": u.number(pt), "text": u.format(pt)})).collect();
|
||||
json!({ "points": pt, "units": units })
|
||||
}
|
||||
|
||||
/// The unit `p` gives for a number without a suffix (points when left out; null is an error).
|
||||
fn unit_param(p: &Value) -> Result<Unit> {
|
||||
let Some(given) = p.get("unit") else { return Ok(Unit::Points) };
|
||||
let named = given.as_str().filter(|name| name.len() <= MAX_TEXT_LEN).and_then(Unit::named_east_asian);
|
||||
named.ok_or_else(|| {
|
||||
let u = match given {
|
||||
Value::String(s) => clipped(s).escape_debug().to_string(),
|
||||
other => shown(other),
|
||||
};
|
||||
bad(CONVERT, format!("unknown units `{u}`"))
|
||||
})
|
||||
}
|
||||
|
||||
fn convert(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
let unit = unit_param(p)?;
|
||||
let Some(v) = p.get("value").filter(|v| !v.is_null()) else {
|
||||
return Err(bad(CONVERT, "missing `value`"));
|
||||
};
|
||||
let pt = match v {
|
||||
Value::String(s) if readable(s) => unit.parse(&decimal_point(s)),
|
||||
Value::Number(n) => n.as_f64().map(|n| unit.to_pt(n)),
|
||||
_ => None,
|
||||
};
|
||||
let pt = pt.filter(|&pt| finite_in_every_unit(pt));
|
||||
pt.map(in_every_unit).ok_or_else(|| {
|
||||
let v = shown(v);
|
||||
bad(CONVERT, format!("`value` must be a number, not {v}"))
|
||||
})
|
||||
}
|
||||
|
||||
/// Is `s` short enough to read: at most [`MAX_TEXT_LEN`] bytes and [`MAX_OPERATORS`] `+ - * /`
|
||||
/// signs?
|
||||
fn readable(s: &str) -> bool {
|
||||
s.len() <= MAX_TEXT_LEN && s.chars().filter(|c| matches!(c, '+' | '-' | '*' | '/')).count() <= MAX_OPERATORS
|
||||
}
|
||||
|
||||
/// `v` as an error message shows it: text cut at [`SHOWN_CHARS`] characters with "…", as JSON,
|
||||
/// an array as `[…]` and an object as `{…}`.
|
||||
fn shown(v: &Value) -> String {
|
||||
match v {
|
||||
Value::String(s) => Value::String(clipped(s)).to_string(),
|
||||
Value::Array(_) => "[…]".into(),
|
||||
Value::Object(_) => "{…}".into(),
|
||||
other => other.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// `s` cut at [`SHOWN_CHARS`] characters, with "…" when it is longer.
|
||||
fn clipped(s: &str) -> String {
|
||||
match s.char_indices().nth(SHOWN_CHARS) {
|
||||
Some((at, _)) => format!("{}…", s.get(..at).unwrap_or_default()),
|
||||
None => s.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn selection_size(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let measure = s.bounds_measure();
|
||||
let b = match effects::preview::anchor_bounds_with(&st.selection, &st.doc, measure) {
|
||||
Some(r) => Some(OrientedBox::aligned(r)),
|
||||
None => s.transform_box(&st.selection.objects),
|
||||
};
|
||||
let b = b.ok_or_else(|| bad(SELECTION_SIZE, "nothing selected"))?;
|
||||
Ok(json!({ "width": in_every_unit(b.rect.width()), "height": in_every_unit(b.rect.height()) }))
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
//! Unit Converter's commands: a length in every unit, read as number fields read it, the selection's
|
||||
//! size as the Transform panel measures it, bad params refused, and nothing in the document changed.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::Unit;
|
||||
|
||||
use crate::{EngineError, Session};
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn convert(s: &mut Session, p: Value) -> Value {
|
||||
s.execute("addon.units.convert", &p).unwrap()
|
||||
}
|
||||
|
||||
/// The row of `r` for the unit with key `key`.
|
||||
fn row<'a>(r: &'a Value, key: &str) -> &'a Value {
|
||||
r["units"].as_array().unwrap().iter().find(|u| u["unit"] == key).unwrap_or_else(|| panic!("{key} in {r}"))
|
||||
}
|
||||
|
||||
fn near(a: f64, b: f64) -> bool {
|
||||
(a - b).abs() < 1e-9
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_length_comes_back_in_every_unit_in_order() {
|
||||
let mut s = session();
|
||||
let r = convert(&mut s, json!({"value": "10mm"}));
|
||||
assert!(near(r["points"].as_f64().unwrap(), 720.0 / 25.4));
|
||||
let keys: Vec<&str> = r["units"].as_array().unwrap().iter().map(|u| u["unit"].as_str().unwrap()).collect();
|
||||
assert_eq!(keys, Unit::EAST_ASIAN.map(Unit::key));
|
||||
assert_eq!(row(&r, "millimeters")["number"], "10");
|
||||
assert_eq!(row(&r, "millimeters")["text"], "10 mm");
|
||||
assert_eq!(row(&r, "centimeters")["text"], "1 cm");
|
||||
assert_eq!(row(&r, "inches")["text"], "0.3937 in");
|
||||
assert_eq!(row(&r, "points")["text"], "28.346 pt");
|
||||
assert_eq!(row(&r, "q")["text"], "40 Q");
|
||||
assert_eq!(row(&r, "ha")["text"], "40 H");
|
||||
assert_eq!(row(&r, "pixels")["number"], row(&r, "points")["number"], "pixels are points");
|
||||
assert_eq!(row(&r, "feetInches")["label"], "Feet & Inches");
|
||||
// Each row is what a field of that unit shows for the length.
|
||||
for u in Unit::EAST_ASIAN {
|
||||
let pt = 720.0 / 25.4;
|
||||
assert_eq!(row(&r, u.key())["text"], u.format(pt), "{u:?}");
|
||||
assert_eq!(row(&r, u.key())["number"], u.number(pt), "{u:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn values_read_as_number_fields_read_them() {
|
||||
let mut s = session();
|
||||
let pt = |s: &mut Session, p: Value| convert(s, p)["points"].as_f64().unwrap();
|
||||
assert!(near(pt(&mut s, json!({"value": "1in/2"})), 36.0));
|
||||
assert!(near(pt(&mut s, json!({"value": "2p6"})), 30.0));
|
||||
assert!(near(pt(&mut s, json!({"value": "1080/2 px"})), 540.0));
|
||||
assert!(near(pt(&mut s, json!({"value": "3cm*50%"})), 1.5 * 72.0 / 2.54));
|
||||
assert!(near(pt(&mut s, json!({"value": "13q"})), 13.0 * 72.0 / 101.6));
|
||||
// A number without a unit is in `unit`, points by default.
|
||||
assert!(near(pt(&mut s, json!({"value": 12})), 12.0));
|
||||
assert!(near(pt(&mut s, json!({"value": 2, "unit": "in"})), 144.0));
|
||||
assert!(near(pt(&mut s, json!({"value": "2", "unit": "Inches"})), 144.0));
|
||||
assert!(near(pt(&mut s, json!({"value": "3+1", "unit": "cm"})), 4.0 * 72.0 / 2.54));
|
||||
assert!(near(pt(&mut s, json!({"value": 6, "unit": "ha"})), 6.0 * 72.0 / 101.6));
|
||||
assert!(near(pt(&mut s, json!({"value": 1, "unit": "feetInches"})), 864.0));
|
||||
// A suffix wins over `unit`.
|
||||
assert!(near(pt(&mut s, json!({"value": "1in", "unit": "mm"})), 72.0));
|
||||
// A decimal comma reads as a point, as in the number fields.
|
||||
assert!(near(pt(&mut s, json!({"value": "0,5 in"})), 36.0));
|
||||
assert!(near(pt(&mut s, json!({"value": "1,5", "unit": "in"})), 108.0));
|
||||
// Each number of a sum reads its own separator.
|
||||
assert!(near(pt(&mut s, json!({"value": "100.5 mm-0,5", "unit": "mm"})), 100.0 * 72.0 / 25.4));
|
||||
// A comma in a sum is a decimal comma, as in the number fields: 1,500+2 is 3.5.
|
||||
assert!(near(pt(&mut s, json!({"value": "1,500+2", "unit": "mm"})), 3.5 * 72.0 / 25.4));
|
||||
// A sum of 128 signs still reads.
|
||||
assert!(near(pt(&mut s, json!({"value": format!("1{}", "+1".repeat(128))})), 129.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keys_the_commands_do_not_take_are_refused() {
|
||||
let s = session();
|
||||
s.check_params("addon.units.convert", &json!({"value": 1, "unit": "mm"})).unwrap();
|
||||
s.check_params("addon.units.selectionSize", &json!({})).unwrap();
|
||||
for (id, p) in [
|
||||
("addon.units.convert", json!({"value": 1, "units": "mm"})),
|
||||
("addon.units.convert", json!({"value": 1, "ids": [1]})),
|
||||
("addon.units.selectionSize", json!({"ids": [1]})),
|
||||
("addon.units.selectionSize", json!({"value": 1})),
|
||||
] {
|
||||
match s.check_params(id, &p) {
|
||||
Err(EngineError::BadParams { cmd, .. }) => assert_eq!(cmd, id, "{p}"),
|
||||
other => panic!("{id} {p}: expected BadParams, got {other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_selection_size_follows_preview_bounds_and_selected_anchors() {
|
||||
let mut s = session();
|
||||
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 72, "height": 36})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [id], "color": "#000000"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"ids": [id], "weight": 10})).unwrap();
|
||||
let wh = |s: &mut Session| {
|
||||
let r = s.execute("addon.units.selectionSize", &json!({})).unwrap();
|
||||
(r["width"]["points"].as_f64().unwrap(), r["height"]["points"].as_f64().unwrap())
|
||||
};
|
||||
assert_eq!(wh(&mut s), (72.0, 36.0), "geometric bounds");
|
||||
// Use Preview Bounds: the stroke's outer half on every side.
|
||||
s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": true})).unwrap();
|
||||
let (w, h) = wh(&mut s);
|
||||
assert!(near(w, 82.0) && near(h, 46.0), "{w} × {h}");
|
||||
s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": false})).unwrap();
|
||||
// Two neighboring anchors selected (Direct Selection): the box around them, one edge of the
|
||||
// rectangle.
|
||||
s.execute("select.anchors", &json!({"id": id, "anchors": [[0, 0], [0, 1]], "mode": "set"})).unwrap();
|
||||
let (w, h) = wh(&mut s);
|
||||
assert!((near(w, 72.0) && near(h, 0.0)) || (near(w, 0.0) && near(h, 36.0)), "{w} × {h}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn it_needs_no_document_and_changes_nothing() {
|
||||
let mut s = Session::new();
|
||||
assert!(near(convert(&mut s, json!({"value": "1in"}))["points"].as_f64().unwrap(), 72.0));
|
||||
let mut s = session();
|
||||
let (before, steps) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len());
|
||||
convert(&mut s, json!({"value": "5mm"}));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps);
|
||||
assert!(*s.doc().unwrap().doc == *before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_values_and_units_are_refused() {
|
||||
let mut s = session();
|
||||
for p in [
|
||||
json!({}),
|
||||
json!({"value": null}),
|
||||
json!({"value": "abc"}),
|
||||
json!({"value": "10 furlongs"}),
|
||||
json!({"value": "1in/0"}),
|
||||
json!({"value": "1e400"}),
|
||||
// Finite in points, too large in Q and Ha.
|
||||
json!({"value": 1.5e308}),
|
||||
json!({"value": "1.5e308"}),
|
||||
// A thousands comma is refused, as the number fields refuse it.
|
||||
json!({"value": "1,000 mm"}),
|
||||
json!({"value": "1,000.5"}),
|
||||
json!({"value": "+1,000"}),
|
||||
json!({"value": "1,000\""}),
|
||||
json!({"value": "1,000'"}),
|
||||
// A long expression is refused instead of exhausting the stack.
|
||||
json!({"value": format!("1{}", "+1".repeat(200_000))}),
|
||||
json!({"value": format!("1{}", "+1".repeat(129))}),
|
||||
json!({"value": true}),
|
||||
json!({"value": [1]}),
|
||||
json!({"value": 1, "unit": "furlongs"}),
|
||||
json!({"value": 1, "unit": 5}),
|
||||
json!({"value": 1, "unit": ["mm"]}),
|
||||
// Only an omitted `unit` is points.
|
||||
json!({"value": 1, "unit": null}),
|
||||
] {
|
||||
match s.execute("addon.units.convert", &p) {
|
||||
Err(EngineError::BadParams { cmd, .. }) => assert_eq!(cmd, "addon.units.convert", "{p}"),
|
||||
other => panic!("{p}: expected BadParams, got {other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_value_or_unit_is_refused_with_a_short_message() {
|
||||
let mut s = session();
|
||||
let long = "9".repeat(100_000);
|
||||
for (p, says) in [
|
||||
(json!({"value": long.clone()}), format!("`value` must be a number, not \"{}…\"", "9".repeat(64))),
|
||||
(json!({"value": [long.clone()]}), "`value` must be a number, not […]".to_string()),
|
||||
(json!({"value": 1, "unit": long.clone()}), format!("unknown units `{}…`", "9".repeat(64))),
|
||||
(json!({"value": 1, "unit": "furlongs"}), "unknown units `furlongs`".to_string()),
|
||||
(json!({"value": "a\"b\nc"}), "`value` must be a number, not \"a\\\"b\\nc\"".to_string()),
|
||||
] {
|
||||
match s.execute("addon.units.convert", &p) {
|
||||
Err(e @ EngineError::BadParams { .. }) => assert!(e.to_string().ends_with(&says), "{e}"),
|
||||
other => panic!("expected BadParams, got {other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_selection_size_is_the_transform_panels() {
|
||||
let mut s = session();
|
||||
assert!(s.execute("addon.units.selectionSize", &json!({})).is_err(), "nothing selected");
|
||||
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 72, "height": 36})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
let r = s.execute("addon.units.selectionSize", &json!({})).unwrap();
|
||||
assert!(near(r["width"]["points"].as_f64().unwrap(), 72.0));
|
||||
assert!(near(r["height"]["points"].as_f64().unwrap(), 36.0));
|
||||
assert_eq!(row(&r["width"], "inches")["text"], "1 in");
|
||||
assert_eq!(row(&r["height"], "picas")["text"], "3 p");
|
||||
// A turned object keeps its own sides, as the Transform panel's W and H show them.
|
||||
s.execute("object.rotate", &json!({"angle": 30})).unwrap();
|
||||
let r = s.execute("addon.units.selectionSize", &json!({})).unwrap();
|
||||
let b = s.transform_box(&s.doc().unwrap().selection.objects).unwrap();
|
||||
assert!(near(r["width"]["points"].as_f64().unwrap(), b.rect.width()));
|
||||
assert!(near(r["width"]["points"].as_f64().unwrap(), 72.0));
|
||||
assert!(near(r["height"]["points"].as_f64().unwrap(), 36.0));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "only the rotation is a step");
|
||||
}
|
||||
@@ -36,8 +36,8 @@ mod symbols;
|
||||
|
||||
pub(crate) use brushes::{apply_brush, brush_targets, stroke_paint};
|
||||
use brushes::{
|
||||
brush_apply, brush_delete, brush_duplicate, brush_freehand, brush_get, brush_list, brush_move, brush_new, brush_options, brush_place_art,
|
||||
brush_remove, brush_replace_art, brush_selection_art, brush_set_current, brush_unused, expand_brush,
|
||||
brush_apply, brush_delete, brush_duplicate, brush_freehand, brush_get, brush_list, brush_move, brush_new, brush_object_options, brush_options,
|
||||
brush_place_art, brush_remove, brush_replace_art, brush_selection_art, brush_set_current, brush_unused, expand_brush,
|
||||
};
|
||||
pub(crate) use dynamic::{edit_part, fit_parts, part_only, selected_part};
|
||||
use dynamic::{symbol_instance_reset, symbol_instance_select_part, symbol_instance_set_appearance};
|
||||
@@ -165,10 +165,19 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Brush Options…",
|
||||
[],
|
||||
None,
|
||||
"{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180° (counter-clockwise from level), roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180° (counter-clockwise), modes: [fixed|random|pressure|tilt|bearing|rotation for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°), rotation_relative_to_path. art: width 1..1000%, width_mode: null (fixed)|pressure|tilt|bearing|rotation, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest; tilt: width with the pen lying flat to width_max upright; bearing and rotation: width at −180° to width_max at 180°; half way on a stroke drawn without that input), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art (drawn as the corner that joins a side tile on its right to one below it) or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}",
|
||||
"{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180° (counter-clockwise from level), roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180° (counter-clockwise), modes: [fixed|random|pressure|tilt|bearing|rotation for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°), rotation_relative_to_path, hue_jitter 0..180° (each copy turns the hue of its solid colors, after the colorization, by its own amount up to this far either way, the same on every redraw; colors without a hue stay; 0: off). art: width 1..1000%, width_mode: null (fixed)|pressure|tilt|bearing|rotation, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest; tilt: width with the pen lying flat to width_max upright; bearing and rotation: width at −180° to width_max at 180°; half way on a stroke drawn without that input), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art (drawn as the corner that joins a side tile on its right to one below it) or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}",
|
||||
has_doc,
|
||||
brush_options
|
||||
),
|
||||
cmd!(
|
||||
"brush.objectOptions",
|
||||
"Options of Selected Object…",
|
||||
[],
|
||||
None,
|
||||
"{ids?|id?, params?: {…the fields brush.options takes that a path can set for itself: calligraphic angle (counter-clockwise from level), roundness, size, variation, modes; scatter size, spacing, scatter, rotation (counter-clockwise), modes, rotation_relative_to_path, colorization; art width, width_mode, width_max, flip_along, flip_across, overlap, colorization; pattern scale, spacing, fit, flip_along, flip_across, colorization (values outside their ranges are clamped; a colorization object changes only the fields it gives; a null item of an array such as size: [40, null] keeps each stroke's own item, else the brush's)}, reset?: bool} set the brush settings of the brushed strokes of the selected paths on those strokes only, leaving the brush and its other strokes as they are (the Brushes panel's Options of Selected Object); params add to each stroke's own settings, a mode params does not set (no modes, or a null item) stays the one each stroke draws with when a changed variation or range would change it, a setting equal to the brush's own value is dropped, and reset: true clears them so the strokes draw the brush again; without params or reset nothing changes; one undo step, none when nothing changes. The brushes' own edits (brush.options) still reach the settings a stroke does not set, applying a brush (brush.apply, stroke.setAdvanced or a brush.freehand extend with another brush) or removing it clears them, and a renamed brush keeps them. Refused with nothing painted with a brush selected, for paths painted with brushes of different types, for a bristle brush, for a field the type does not take and for a value of the wrong kind → {ids: the brushed paths, changed: the paths whose settings changed, options: the first stroke's own settings}",
|
||||
has_doc,
|
||||
brush_object_options
|
||||
),
|
||||
cmd!(
|
||||
"object.expandBrush",
|
||||
"Expand Brush Strokes",
|
||||
@@ -256,7 +265,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Redefine Symbol",
|
||||
[],
|
||||
None,
|
||||
"{name, ids?|id?} replace the symbol's art with the selection (instances update, keeping their appearance changes to the objects at paths the new art still has; the selection becomes an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds) → {name, id}",
|
||||
"{name, ids?|id?, keepArt?: false} replace the symbol's art with the selection (instances update, keeping their appearance changes to the objects at paths the new art still has; the selection becomes an instance, or with keepArt: true stays ordinary art where it is, still selected, and id is null; a frame of threaded text in the selection that becomes an instance leaves its thread with the text it shows, which the symbol's art holds; art that holds an instance of the symbol (opacity masks included), directly or through the symbols it nests, is refused) → {name, id}",
|
||||
has_selection,
|
||||
symbol_update
|
||||
),
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use super::{
|
||||
AppearanceItem, Arc, BTreeSet, Bristle, Brush, BrushKind, Color, Document, EngineError, Node, NodeId, NodeKind, Paint, Result, Session, Value,
|
||||
anchor, bad, brush, check_numbers, find_command, ids_json, json, name_param, names_param, ok, roots, selection_art, set_unknown, str_param,
|
||||
switch_or,
|
||||
};
|
||||
|
||||
// ---------- brushes ----------
|
||||
@@ -31,7 +32,12 @@ pub(super) fn brush_list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
pub(super) fn brush_get(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let name = name_param(p, "brush.get")?;
|
||||
let b = brush::find(&s.doc()?.doc, name).ok_or_else(|| EngineError::Other(format!("no brush named `{name}`")))?;
|
||||
Ok(serde_json::to_value(b).unwrap_or_default())
|
||||
let mut v = serde_json::to_value(&b).unwrap_or_default();
|
||||
// A scatter brush saves its hue jitter only when it is not 0; brush.get shows it either way.
|
||||
if let (BrushKind::Scatter(sc), Some(o)) = (&b.kind, v.as_object_mut()) {
|
||||
o.entry("hue_jitter").or_insert(json!(sc.hue_jitter));
|
||||
}
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// The art `brush.new` takes from `ids` or `id`, else from the selection ([`selection_art`]).
|
||||
@@ -57,6 +63,8 @@ pub(crate) fn apply_brush(d: &mut Document, ids: &[NodeId], name: &str, stroke:
|
||||
st.width = 1.0;
|
||||
}
|
||||
st.brush = Some(name.to_string());
|
||||
// The path's own brush settings (Options of Selected Object) go with the brush they set.
|
||||
st.brush_options.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -85,6 +93,7 @@ pub(super) fn brush_remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
for it in &mut n.appearance.items {
|
||||
if let AppearanceItem::Stroke(st) = it {
|
||||
st.brush = None;
|
||||
st.brush_options.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -129,13 +138,17 @@ fn merge(base: &mut Value, patch: &Value) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets brush `to` on the strokes in `items` that paint with brush `from`.
|
||||
/// Sets brush `to` on the strokes in `items` that paint with brush `from`. A renamed brush keeps
|
||||
/// each stroke's own settings for it; a stroke left without a brush loses them.
|
||||
fn set_stroke_brush(items: &mut [AppearanceItem], from: &str, to: Option<&str>) {
|
||||
for it in items {
|
||||
if let AppearanceItem::Stroke(st) = it
|
||||
&& st.brush.as_deref() == Some(from)
|
||||
{
|
||||
st.brush = to.map(str::to_string);
|
||||
if to.is_none() {
|
||||
st.brush_options.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -494,6 +507,166 @@ pub(super) fn brush_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "name": out }))
|
||||
}
|
||||
|
||||
/// Options of Selected Object: set the brush settings of the brushed strokes of the selected paths
|
||||
/// (or `ids`) on those strokes only, leaving the brush as it is. `params` adds to each stroke's
|
||||
/// own settings, `reset` clears them; without either, nothing changes and the settings are given.
|
||||
pub(super) fn brush_object_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "brush.objectOptions";
|
||||
let params = match p.get("params") {
|
||||
None | Some(Value::Null) => serde_json::Map::new(),
|
||||
Some(Value::Object(o)) => o.clone(),
|
||||
Some(_) => {
|
||||
let key = "params";
|
||||
return Err(bad(C, format!("`{key}` must be an object")));
|
||||
}
|
||||
};
|
||||
let reset = switch_or(p, "reset", false, C)?;
|
||||
if reset && !params.is_empty() {
|
||||
return Err(bad(C, "give `params` or `reset`, not both"));
|
||||
}
|
||||
let d = &s.doc()?.doc;
|
||||
let lib = brush::library(d);
|
||||
let ids = brush_targets(d, &roots(s, p)?);
|
||||
// Each brushed stroke: its path, its place in the appearance, its brush and its settings now.
|
||||
let mut strokes = vec![];
|
||||
for id in &ids {
|
||||
let Some(n) = d.node(*id) else { continue };
|
||||
for (i, it) in n.appearance.items.iter().enumerate() {
|
||||
let AppearanceItem::Stroke(st) = it else { continue };
|
||||
if let Some(b) = st.brush.as_deref().and_then(|name| lib.iter().find(|b| b.name == name)) {
|
||||
strokes.push((*id, i, b, &st.brush_options));
|
||||
}
|
||||
}
|
||||
}
|
||||
let Some(&(_, _, first, _)) = strokes.first() else { return Err(bad(C, "no path painted with a brush is selected")) };
|
||||
if strokes.iter().any(|(_, _, b, _)| b.kind.type_id() != first.kind.type_id()) {
|
||||
return Err(bad(C, "the selected paths are painted with brushes of different types"));
|
||||
}
|
||||
// Only a bristle brush has none.
|
||||
if first.kind.stroke_option_keys().is_empty() {
|
||||
return Err(bad(C, "a bristle brush has no options of its own on a path"));
|
||||
}
|
||||
let out: Vec<NodeId> = ids.iter().copied().filter(|id| strokes.iter().any(|(s, ..)| s == id)).collect();
|
||||
// Without params or reset the settings are only given: nothing is normalized or changed.
|
||||
if !reset && params.is_empty() {
|
||||
let keys = first.kind.stroke_option_keys();
|
||||
let own: serde_json::Map<String, Value> =
|
||||
strokes[0].3.iter().filter(|(k, _)| keys.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone())).collect();
|
||||
return Ok(json!({ "ids": ids_json(&out), "changed": [], "options": own }));
|
||||
}
|
||||
let mut changes = vec![];
|
||||
let mut options = None;
|
||||
for (id, i, b, own) in &strokes {
|
||||
let next = if reset {
|
||||
serde_json::Map::new()
|
||||
} else {
|
||||
// Settings saved for another type of brush are left out.
|
||||
let keys = b.kind.stroke_option_keys();
|
||||
let mut merged: serde_json::Map<String, Value> =
|
||||
own.iter().filter(|(k, _)| keys.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone())).collect();
|
||||
let was = merged.clone();
|
||||
// A colorization object changes only the fields it gives, and a null item of an
|
||||
// array keeps the stroke's own item (else the brush's).
|
||||
for (k, v) in ¶ms {
|
||||
let next = match (merged.get(k), v) {
|
||||
(Some(Value::Object(mine)), Value::Object(fields)) if k == "colorization" => {
|
||||
let mut c = mine.clone();
|
||||
c.extend(fields.clone());
|
||||
Value::Object(c)
|
||||
}
|
||||
(Some(mine), _) => brush::keep_items(v, mine),
|
||||
(None, _) => v.clone(),
|
||||
};
|
||||
merged.insert(k.clone(), next);
|
||||
}
|
||||
keep_drawn_modes(b, &was, ¶ms, &mut merged);
|
||||
keep_largest_width(b, &was, ¶ms, &mut merged);
|
||||
b.stroke_options_that_differ(&merged).map_err(|e| bad(C, e))?
|
||||
};
|
||||
options.get_or_insert_with(|| next.clone());
|
||||
if &next != *own {
|
||||
changes.push((*id, *i, next));
|
||||
}
|
||||
}
|
||||
let changed: Vec<NodeId> = ids.iter().copied().filter(|id| changes.iter().any(|(c, ..)| c == id)).collect();
|
||||
if !changes.is_empty() {
|
||||
s.edit("Options of Selected Object", |d, _| {
|
||||
for (id, i, next) in changes {
|
||||
if let Some(AppearanceItem::Stroke(st)) = d.node_mut(id).and_then(|n| n.appearance.items.get_mut(i)) {
|
||||
st.brush_options = next;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
Ok(json!({ "ids": ids_json(&out), "changed": ids_json(&changed), "options": options.unwrap_or_default() }))
|
||||
}
|
||||
|
||||
/// The modes brush `b` draws with, for a Calligraphic or a Scatter brush.
|
||||
fn drawn_modes(b: &Brush) -> Option<Vec<Value>> {
|
||||
let modes = match &b.kind {
|
||||
BrushKind::Calligraphic(c) => serde_json::to_value(c.modes()),
|
||||
BrushKind::Scatter(s) => serde_json::to_value(s.modes()),
|
||||
_ => return None,
|
||||
};
|
||||
match modes {
|
||||
Ok(Value::Array(m)) => Some(m),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep each mode a stroke of brush `b` draws with (with its own settings `was`) that `params`
|
||||
/// does not set (no `modes`, or a `null` item) and that `merged`, its settings with `params`,
|
||||
/// would change. A mode the stroke leaves to its values follows them, so without this a changed
|
||||
/// variation or range would also change the mode.
|
||||
fn keep_drawn_modes(
|
||||
b: &Brush,
|
||||
was: &serde_json::Map<String, Value>,
|
||||
params: &serde_json::Map<String, Value>,
|
||||
merged: &mut serde_json::Map<String, Value>,
|
||||
) {
|
||||
let given = match params.get("modes") {
|
||||
None | Some(Value::Null) => vec![],
|
||||
Some(Value::Array(m)) => m.clone(),
|
||||
// A value of the wrong kind is refused when the settings are checked.
|
||||
Some(_) => return,
|
||||
};
|
||||
let (Some(before), Some(after)) =
|
||||
(b.with_stroke_options(was).ok().as_ref().and_then(drawn_modes), b.with_stroke_options(merged).ok().as_ref().and_then(drawn_modes))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
if before == after {
|
||||
return;
|
||||
}
|
||||
let kept = before.into_iter().zip(after).enumerate().map(|(j, (w, a))| if given.get(j).is_some_and(|g| !g.is_null()) { a } else { w }).collect();
|
||||
merged.insert("modes".into(), Value::Array(kept));
|
||||
}
|
||||
|
||||
/// Keep the largest width a stroke of art brush `b` draws with (with its own settings `was`) when
|
||||
/// `params` sets `width` and no `width_max`. Without a `width_max` of its own the largest width is
|
||||
/// the width, so without this a changed width would also change the largest width.
|
||||
fn keep_largest_width(
|
||||
b: &Brush,
|
||||
was: &serde_json::Map<String, Value>,
|
||||
params: &serde_json::Map<String, Value>,
|
||||
merged: &mut serde_json::Map<String, Value>,
|
||||
) {
|
||||
if params.get("width").is_none_or(Value::is_null) || params.get("width_max").is_some_and(|m| !m.is_null()) {
|
||||
return;
|
||||
}
|
||||
let art = |o: &serde_json::Map<String, Value>| match b.with_stroke_options(o).ok().map(|b| b.kind) {
|
||||
Some(BrushKind::Art(a)) => Some(a),
|
||||
_ => None,
|
||||
};
|
||||
let (Some(before), Some(after)) = (art(was), art(merged)) else { return };
|
||||
let follows_pen = |a: &brush::ArtBrush| a.width_mode.is_some_and(|m| m.follows_pen());
|
||||
// Only a width that followed the pen has a largest width, and only one that still does uses it.
|
||||
if before.width_max.is_none() && follows_pen(&before) && follows_pen(&after) && after.width != before.width {
|
||||
merged.insert("width_max".into(), json!(before.width));
|
||||
}
|
||||
}
|
||||
|
||||
/// The name `brush.placeArt` gives each pattern brush tile it places, by tile, in the order it
|
||||
/// places them; `brush.replaceArt` reads a group of that name as that tile.
|
||||
const TILE_NAMES: [&str; 5] = ["Side Tile", "Outer Corner Tile", "Inner Corner Tile", "Start Tile", "End Tile"];
|
||||
|
||||
@@ -612,6 +612,8 @@ pub(super) fn symbol_update(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
// Redefining the symbol being edited leaves symbol editing mode in the same step.
|
||||
let session = s.doc()?.doc.symbol_edit.clone().filter(|e| e.symbol == name);
|
||||
// `keepArt` leaves the art as ordinary art instead of replacing it with an instance.
|
||||
let keep_art = switch_or(p, "keepArt", false, C)?;
|
||||
if session.is_some() {
|
||||
crate::cmd::settle_interaction(s)?;
|
||||
s.end_text_edit();
|
||||
@@ -625,10 +627,20 @@ pub(super) fn symbol_update(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
let mut art = selection_art(s, p)?.ok_or_else(|| EngineError::Other("nothing selected".into()))?;
|
||||
// Nor can art that holds an instance of it, directly or through the symbols it nests.
|
||||
if crate::cmd::symboledit::holds_symbol(&s.doc()?.doc, &art, &name, &mut Default::default()) {
|
||||
return Err(EngineError::Other("a symbol can't hold an instance of itself".into()));
|
||||
}
|
||||
crate::cmd::threads::keep_shown_text(&s.doc()?.doc, &mut art);
|
||||
let (art, size, c) = normalize(art)?;
|
||||
let old = natural_size(&s.doc()?.doc, &name);
|
||||
let editing = session.is_some();
|
||||
// The isolation the kept art is selected in: the one from before symbol editing mode when
|
||||
// the step leaves it.
|
||||
let iso = match &session {
|
||||
Some(se) => se.back_isolation,
|
||||
None => s.doc()?.isolation,
|
||||
};
|
||||
let id = s.edit("Redefine Symbol", |d, sel| {
|
||||
if editing {
|
||||
crate::cmd::symboledit::finish(d, sel);
|
||||
@@ -647,15 +659,22 @@ pub(super) fn symbol_update(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
// Each instance keeps its appearance changes to the objects the new art still has.
|
||||
fit_overrides(d, &instances);
|
||||
if keep_art {
|
||||
// The art stays where it is and stays selected, apart from art that is hidden or
|
||||
// locked, in a hidden or locked group or layer, or on a locked artboard.
|
||||
let locks = d.locked_artboards();
|
||||
sel.set(ids.iter().copied().filter(|i| crate::cmd::select::is_selectable(d, iso, &locks, *i)));
|
||||
return Ok(None);
|
||||
}
|
||||
let reg = d.symbol_registration(&name);
|
||||
let id = instance_in_place(d, &ids, &name, place_xf(c + reg.offset_from_center(size.0, size.1), size, reg))?;
|
||||
sel.set([id]);
|
||||
Ok(id)
|
||||
Ok(Some(id))
|
||||
})?;
|
||||
if let Some(se) = &session {
|
||||
crate::cmd::symboledit::leave_editing(s, se)?;
|
||||
}
|
||||
Ok(json!({ "name": name, "id": id.0 }))
|
||||
Ok(json!({ "name": name, "id": id.map(|i| i.0) }))
|
||||
}
|
||||
|
||||
/// How many levels of nested instances Delete Symbol expands before it gives up.
|
||||
|
||||
@@ -659,6 +659,7 @@ fn fit_to_edge(row: &mut AppearanceItem, run: Option<(f64, bool, bool, bool)>) {
|
||||
}
|
||||
s.profile = None;
|
||||
s.brush = None;
|
||||
s.brush_options.clear();
|
||||
}
|
||||
if !starts {
|
||||
s.start_arrow = None;
|
||||
|
||||
@@ -579,6 +579,11 @@ impl SwatchChoices {
|
||||
Some(v) => Ok(Self { all: one(v)?, by_name: BTreeMap::new() }),
|
||||
}
|
||||
}
|
||||
/// 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() }
|
||||
}
|
||||
fn of(&self, name: &str) -> SwatchChoice {
|
||||
self.by_name.get(name).copied().unwrap_or(self.all)
|
||||
}
|
||||
|
||||
@@ -121,7 +121,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Separations Preview",
|
||||
[],
|
||||
None,
|
||||
"{on?: bool, plates?: [names], toggle?: plate, only?: plate} Separations Preview: show the chosen plates (one plate = greyscale ink coverage) → {on, plates: [{name, spot, visible, rgb}]}",
|
||||
"{on?: bool, plates?: [names], toggle?: plate, only?: plate, soloToggle?: plate (only that plate, or every plate when it is the only one shown)} Separations Preview: show the chosen plates (one plate = grayscale ink coverage) → {on, plates: [{name, spot, visible, rgb}]}",
|
||||
always,
|
||||
separations
|
||||
),
|
||||
@@ -754,10 +754,12 @@ fn map_art_colors(n: &mut vectorcraft_doc::Node, f: &mut dyn FnMut(&Color, proof
|
||||
}
|
||||
|
||||
/// `f` applied to the colors in `n`'s subtree that [`proof::map_node_colors`] does not visit: the
|
||||
/// effect colors ([`map_effect_colors`]), the series paints and label styles a graph keeps
|
||||
/// effect colors ([`map_effect_colors`]), the Hue Shift key colors of strokes' own brush settings
|
||||
/// ([`map_stroke_brush_keys`]), the series paints and label styles a graph keeps
|
||||
/// ([`map_graph_colors`]) and the art of every opacity mask.
|
||||
fn map_more_colors(n: &mut vectorcraft_doc::Node, f: &mut dyn FnMut(&Color, proof::Link) -> Color) {
|
||||
map_effect_colors(&mut n.appearance, f);
|
||||
map_stroke_brush_keys(&mut n.appearance, f);
|
||||
if let Some(e) = n.extras_if_any() {
|
||||
if let Some(g) = e.graph.as_deref_mut() {
|
||||
map_graph_colors(g, f);
|
||||
@@ -773,6 +775,23 @@ fn map_more_colors(n: &mut vectorcraft_doc::Node, f: &mut dyn FnMut(&Color, proo
|
||||
}
|
||||
}
|
||||
|
||||
/// `f` applied to the Hue Shift key color of each stroke's own brush settings in appearance `a`
|
||||
/// (Options of Selected Object, `colorization.key` of [`StrokeLayer::brush_options`]); a key
|
||||
/// that does not read is left as it is.
|
||||
///
|
||||
/// [`StrokeLayer::brush_options`]: vectorcraft_doc::StrokeLayer::brush_options
|
||||
fn map_stroke_brush_keys(a: &mut vectorcraft_doc::Appearance, f: &mut dyn FnMut(&Color, proof::Link) -> Color) {
|
||||
for it in &mut a.items {
|
||||
let vectorcraft_doc::AppearanceItem::Stroke(st) = it else { continue };
|
||||
let Some(c) = st.brush_options.get_mut("colorization").and_then(Value::as_object_mut) else { continue };
|
||||
let Some(key) = c.get("key").and_then(|k| serde_json::from_value::<Color>(k.clone()).ok()) else { continue };
|
||||
let n = f(&key, None);
|
||||
if n != key {
|
||||
c.insert("key".into(), json!(n));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether art color `c` is the Hue Shift key color `key`, with the tolerance the brush's
|
||||
/// colorization matches it with.
|
||||
fn matches_key(c: &Color, key: &Color) -> bool {
|
||||
@@ -1036,6 +1055,13 @@ fn separations(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(n) = text_param(p, "only", C)? {
|
||||
v.separations = Some(vec![check(n)?]);
|
||||
}
|
||||
// The panel's Alt-click on a plate's eye: that plate alone, or every plate when it already
|
||||
// shows alone among the active document's plates.
|
||||
if let Some(n) = text_param(p, "soloToggle", C)? {
|
||||
let n = check(n)?;
|
||||
let alone = v.separations.as_ref().is_some_and(|vis| all.iter().filter(|a| vis.contains(a)).eq([&n]));
|
||||
v.separations = Some(if alone { all.clone() } else { vec![n] });
|
||||
}
|
||||
if let Some(n) = text_param(p, "toggle", C)? {
|
||||
let n = check(n)?;
|
||||
let vis = v.separations.get_or_insert_with(|| all.clone());
|
||||
|
||||
@@ -62,7 +62,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Circle Through Points",
|
||||
[],
|
||||
None,
|
||||
"{points?: [[x, y], [x, y], [x, y]] (left out: the three selected anchor points, where a path selected whole counts all its anchors and selected segments' ends do not count)} → {id, cx, cy, radius}: a circle with the current paint whose edge passes through the three points, not pixel-aligned even while Align New Objects to Pixel Grid is on; two points that are the same or three on one line are an error, and nothing is drawn",
|
||||
"{points?: [[x, y], [x, y]] or [[x, y], [x, y], [x, y]] (two: the ends of a diameter; left out: the two or three selected anchor points, where a path selected whole counts all its anchors and selected segments' ends do not count)} → {id, cx, cy, radius}: a circle with the current paint whose edge passes through the points, not pixel-aligned even while Align New Objects to Pixel Grid is on; two points that are the same, three on one line, or a circle reaching past the canvas are an error, and nothing is drawn",
|
||||
has_doc,
|
||||
circle_through_points
|
||||
),
|
||||
@@ -126,7 +126,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Create Text",
|
||||
[],
|
||||
None,
|
||||
"{x, y, text, rotation?: deg clockwise about x, y (0: level), vertical?: bool = false, size?: pt 0.1..1296 (outside it: an error, and no type is made), font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (as text.areaOptions)}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on",
|
||||
"{x, y, text, rotation?: deg clockwise about x, y (0: level), vertical?: bool = false, size?: pt 0.1..1296 (outside it: an error, and no type is made), font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused; size, font, style and color left out come from [Normal Character Style], the defaults unless the document redefined it), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (as text.areaOptions)}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on",
|
||||
has_doc,
|
||||
text_create
|
||||
),
|
||||
@@ -413,16 +413,16 @@ fn ellipse(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
add_art_turned(s, "Ellipse", path_kind(live.to_path(), Some(live)), rotation)
|
||||
}
|
||||
|
||||
/// A live ellipse whose edge passes through three points: `points`, or the three selected anchor
|
||||
/// points ([`selected_anchor_points`]). One undo step, named as an Ellipse tool drag is.
|
||||
/// A live ellipse whose edge passes through two or three points: `points`, or the two or three
|
||||
/// selected anchor points ([`selected_anchor_points`]). Two points are the ends of a diameter. One
|
||||
/// undo step, named as an Ellipse tool drag is.
|
||||
fn circle_through_points(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "shape.circleThroughPoints";
|
||||
let points = match p.get("points").filter(|v| !v.is_null()) {
|
||||
Some(v) => three_points(v).ok_or_else(|| bad(C, "`points` must be three [x, y] pairs of numbers"))?,
|
||||
None => selected_anchor_points(s)?.ok_or_else(|| bad(C, "direct-select three anchor points, or give `points`"))?,
|
||||
Some(v) => two_or_three_points(v).ok_or_else(|| bad(C, "`points` must be two or three [x, y] pairs of numbers"))?,
|
||||
None => selected_anchor_points(s)?.ok_or_else(|| bad(C, "direct-select two or three anchor points, or give `points`"))?,
|
||||
};
|
||||
let [a, b, c] = points;
|
||||
let (center, radius) = shapes::circle_through(a, b, c)
|
||||
let (center, radius) = shapes::circle_through_points(&points)
|
||||
.ok_or_else(|| bad(C, "no circle passes through these points: two are the same or all three lie on one line"))?;
|
||||
let r = Rect::new(center.x - radius, center.y - radius, center.x + radius, center.y + radius);
|
||||
let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: Affine::translate(r.origin().to_vec2()) };
|
||||
@@ -434,24 +434,25 @@ fn circle_through_points(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The three points `[[x, y], [x, y], [x, y]]` holds, each pair two finite numbers.
|
||||
fn three_points(v: &Value) -> Option<[Point; 3]> {
|
||||
/// The two or three points `[[x, y], [x, y]]` or `[[x, y], [x, y], [x, y]]` holds, each pair two
|
||||
/// finite numbers.
|
||||
fn two_or_three_points(v: &Value) -> Option<Vec<Point>> {
|
||||
let pair = |v: &Value| match v.as_array().map(Vec::as_slice) {
|
||||
Some([x, y]) => x.as_f64().zip(y.as_f64()).filter(|(x, y)| x.is_finite() && y.is_finite()).map(|(x, y)| Point::new(x, y)),
|
||||
_ => None,
|
||||
};
|
||||
match v.as_array().map(Vec::as_slice) {
|
||||
Some([a, b, c]) => Some([pair(a)?, pair(b)?, pair(c)?]),
|
||||
match v.as_array() {
|
||||
Some(pairs) if matches!(pairs.len(), 2 | 3) => pairs.iter().map(pair).collect(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The positions of the selected anchor points, when there are exactly three. They are counted as
|
||||
/// The positions of the selected anchor points, when there are two or three. They are counted as
|
||||
/// the other anchor commands count them ([`super::path::anchor_targets`]): a selected path with
|
||||
/// anchors picked by Direct Selection gives those, and a path selected whole gives all of its own.
|
||||
/// A selected segment's ends are not selected anchor points, so a selection with segments gives
|
||||
/// none; so does a selection holding an object that is not a path, or an anchor that is gone.
|
||||
fn selected_anchor_points(s: &Session) -> Result<Option<[Point; 3]>> {
|
||||
fn selected_anchor_points(s: &Session) -> Result<Option<Vec<Point>>> {
|
||||
let st = s.doc()?;
|
||||
if st.selection.segments.values().any(|set| !set.is_empty()) {
|
||||
return Ok(None);
|
||||
@@ -472,10 +473,7 @@ fn selected_anchor_points(s: &Session) -> Result<Option<[Point; 3]>> {
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
Ok(match points.as_slice() {
|
||||
&[a, b, c] => Some([a, b, c]),
|
||||
_ => None,
|
||||
})
|
||||
Ok(matches!(points.len(), 2 | 3).then_some(points))
|
||||
}
|
||||
|
||||
/// The whole-number count `p` gives for `key` (`5` or `5.0`), or `default` when it is left out or
|
||||
@@ -942,7 +940,13 @@ fn text_create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = made.get("id").and_then(Value::as_u64).map(NodeId);
|
||||
let made = super::typecmd::with_bounds(s, id, made);
|
||||
let mut made = super::typecmd::with_overflow(s, id.as_slice(), made);
|
||||
if p.get("font").is_some() || p.get("style").is_some() {
|
||||
// A face from a redefined [Normal Character Style] is checked too, as one given here is.
|
||||
let normal_face = s
|
||||
.doc()
|
||||
.ok()
|
||||
.and_then(|d| super::textstyles::style_attrs(&d.doc, false, super::textstyles::NORMAL_CHAR))
|
||||
.is_some_and(|m| m.contains_key("font_family") || m.contains_key("font_style"));
|
||||
if p.get("font").is_some() || p.get("style").is_some() || normal_face {
|
||||
let runs = match id.and_then(|i| s.doc().ok()?.doc.node(i)).map(|n| &n.kind) {
|
||||
Some(NodeKind::Text(t)) => t.runs.iter().flat_map(super::fonts::run_fonts).collect(),
|
||||
_ => Default::default(),
|
||||
@@ -970,8 +974,9 @@ pub(crate) fn new_type_para() -> vectorcraft_doc::ParaStyle {
|
||||
|
||||
/// The paragraph alignment, leading model and character alignment new type starts with (`t`'s
|
||||
/// paragraph and runs): `justify` from `p` (else as [`new_type_para`] left it), `leadingModel`
|
||||
/// and `charAlign` from `p`, else em box top to top and em box centre while the
|
||||
/// interface is in Japanese (#432), else the Roman baseline for both. Noted in the journal, so a
|
||||
/// and `charAlign` from `p` (`charAlign` else from a redefined `[Normal Character Style]` that
|
||||
/// sets it), else em box top to top and em box centre while the interface is in Japanese (#432),
|
||||
/// else the Roman baseline for both. Noted in the journal, so a
|
||||
/// replay sets the same whatever the interface.
|
||||
pub(crate) fn new_type_alignment(s: &mut Session, p: &Value, cmd: &str, t: &mut TextObject) -> Result<()> {
|
||||
use vectorcraft_doc::{CharAlign, LeadingModel};
|
||||
@@ -991,7 +996,14 @@ pub(crate) fn new_type_alignment(s: &mut Session, p: &Value, cmd: &str, t: &mut
|
||||
l
|
||||
}
|
||||
};
|
||||
let align = match super::textedit::char_align_param(p, cmd)? {
|
||||
// A redefined [Normal Character Style] that sets Character Alignment gives it to new type.
|
||||
let normal_align = s
|
||||
.doc()
|
||||
.ok()
|
||||
.and_then(|d| super::textstyles::style_attrs(&d.doc, false, super::textstyles::NORMAL_CHAR))
|
||||
.filter(|m| m.contains_key("charAlign"))
|
||||
.and(t.runs.first().map(|r| r.style.char_align));
|
||||
let align = match super::textedit::char_align_param(p, cmd)?.or(normal_align) {
|
||||
Some(a) => a,
|
||||
None => {
|
||||
let a = if japanese { CharAlign::EmBoxCenter } else { CharAlign::RomanBaseline };
|
||||
@@ -1019,17 +1031,25 @@ pub(crate) fn new_area_fit(s: &Session, p: &Value, c: &str, t: &mut TextObject)
|
||||
}
|
||||
|
||||
/// The character style new type gets: `size`, `font`, `style` and `color` from `p` (an RGB
|
||||
/// `color` in a CMYK document as [`super::paint::new_color`] stores it), else the defaults,
|
||||
/// filled as `[Normal Character Style]` is (black unless redefined; never the current fill,
|
||||
/// #7975), in the document's
|
||||
/// language. A `size` outside [`super::typecmd::TYPE_SIZES`] is an error.
|
||||
/// `color` in a CMYK document as [`super::paint::new_color`] stores it), else
|
||||
/// `[Normal Character Style]`'s (the default font, size and black fill unless redefined;
|
||||
/// never the current fill, #7975), in the style's language, else the document's. A `size` outside
|
||||
/// [`super::typecmd::TYPE_SIZES`] is an error.
|
||||
pub(crate) fn new_type_style(s: &Session, p: &Value, cmd: &str) -> Result<CharStyle> {
|
||||
let mut style = CharStyle::default();
|
||||
let mut style = s.doc().map_or_else(|_| CharStyle::default(), |d| super::textstyles::normal_char_style(&d.doc));
|
||||
if let Some(sz) = p.get("size").and_then(Value::as_f64) {
|
||||
style.size = super::typecmd::given_type_size(sz, cmd)?;
|
||||
}
|
||||
if str_param(p, "font").is_some() || str_param(p, "style").is_some() {
|
||||
// A face given to the command takes its own version and axis settings, as a font change
|
||||
// does, not those [Normal Character Style] gave another face.
|
||||
style.font_version = None;
|
||||
style.font_axes.clear();
|
||||
}
|
||||
if let Some(f) = str_param(p, "font") {
|
||||
style.font_family = f.to_string();
|
||||
// A family alone starts in Regular, whatever style [Normal Character Style] has.
|
||||
style.font_style = CharStyle::default().font_style;
|
||||
}
|
||||
if let Some(f) = str_param(p, "style") {
|
||||
style.font_style = f.to_string();
|
||||
@@ -1039,12 +1059,15 @@ pub(crate) fn new_type_style(s: &Session, p: &Value, cmd: &str) -> Result<CharSt
|
||||
}
|
||||
style.fill = match p.get("color").and_then(color_value) {
|
||||
Some(c) => vectorcraft_color::Paint::solid(super::paint::new_color(s, p, c)),
|
||||
None => s.doc().map_or_else(|_| CharStyle::default().fill, |d| super::textstyles::normal_char_fill(&d.doc)),
|
||||
None => style.fill,
|
||||
};
|
||||
// In the language Document Setup chose, else Preferences › Hyphenation › Default Language; none
|
||||
// for the default. Type already in a document keeps its own.
|
||||
let chosen = |name: &str| vectorcraft_doc::setup::char_language(name).ok().flatten();
|
||||
let document = s.doc().ok().and_then(|d| chosen(&d.doc.setup.language));
|
||||
style.language = document.or_else(|| chosen(&s.prefs.hyphenation_language)).map(str::to_string);
|
||||
// In the language a redefined [Normal Character Style] gives, else the one Document Setup chose,
|
||||
// else Preferences › Hyphenation › Default Language; none for the default. Type already in a
|
||||
// document keeps its own.
|
||||
if style.language.is_none() {
|
||||
let chosen = |name: &str| vectorcraft_doc::setup::char_language(name).ok().flatten();
|
||||
let document = s.doc().ok().and_then(|d| chosen(&d.doc.setup.language));
|
||||
style.language = document.or_else(|| chosen(&s.prefs.hyphenation_language)).map(str::to_string);
|
||||
}
|
||||
Ok(style)
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@ use vectorcraft_tools::distort::{PinSet, arap, collect_points, mesh_for, project
|
||||
use super::edit::{duplicate_in, outermost, refuse_symbol_part, selected_roots};
|
||||
use super::{
|
||||
CommandSpec, Result, Session, bad, check_numbers, check_switches, cmd, f64_or, f64_req, finite_numbers, has_doc, has_selection, matrix_param,
|
||||
named_id, named_ids, number_or, object_param, ok, point_indices, point_param, str_param, switch_or, targets,
|
||||
named_id, named_ids, number_or, object_param, ok, point_indices, point_param, str_param, switch_or, targets, text_param, u64_req,
|
||||
};
|
||||
use crate::EngineError;
|
||||
|
||||
@@ -35,7 +35,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Width Point",
|
||||
[],
|
||||
None,
|
||||
"{id, t: 0..1 (fraction of the path length), left, right: side widths in pt, index?: width point to edit or move, adjustAdjoining?: bool (the nearest points either side change their widths in proportion, using the sampled widths for a new point)} → {index}. Without index a point already at t is replaced; a point moved onto another one's t joins it as a discontinuous point (on the side it came from), so the width steps there. Creates a uniform profile first if needed",
|
||||
"{id, t: 0..1 (fraction of the path length), left, right: side widths in pt, index?: width point to edit or move, adjustAdjoining?: bool (the nearest points either side change their widths in proportion, using the sampled widths for a new point), outIndex?, outLeft, outRight: the outgoing half of the discontinuous point whose incoming half is index, single?: \"incoming\" | \"outgoing\"} → {index}. Without index a point already at t is replaced; a point moved onto another one's t joins it as a discontinuous point (on the side it came from), so the width steps there. With outIndex both halves change in one step and keep their place (t must be theirs); adjustAdjoining then changes the nearest point before from the incoming half and the nearest point after from the outgoing half. single keeps only that half's widths, leaving one continuous point. Creates a uniform profile first if needed",
|
||||
has_doc,
|
||||
width_point_set
|
||||
),
|
||||
@@ -214,6 +214,15 @@ fn uniform() -> WidthProfile {
|
||||
/// Width points closer than this (in t) are at the same place: a discontinuous point.
|
||||
const SAME_T: f64 = 1e-6;
|
||||
|
||||
/// The outgoing half of the discontinuous width point whose incoming half is point `a`: point `a`
|
||||
/// and the next one are the two halves when they are the only points within 1e-6 (in t) of `a`'s
|
||||
/// place. None when `a` is out of range or not such an incoming half.
|
||||
pub fn width_point_pair(points: &[(f64, f64, f64)], a: usize) -> Option<usize> {
|
||||
let t = points.get(a)?.0;
|
||||
let at: Vec<usize> = (0..points.len()).filter(|i| (points[*i].0 - t).abs() <= SAME_T).collect();
|
||||
(at == [a, a + 1]).then_some(a + 1)
|
||||
}
|
||||
|
||||
/// The stroke of `id` that width point commands edit (a compound path's for its members).
|
||||
fn stroke_mut(d: &mut Document, id: NodeId) -> Result<&mut vectorcraft_doc::StrokeLayer> {
|
||||
let id = stroke_owner(d, id);
|
||||
@@ -265,9 +274,9 @@ fn place(points: &mut Vec<(f64, f64, f64)>, mut pt: (f64, f64, f64), from_below:
|
||||
}
|
||||
|
||||
/// Adjust Adjoining Width Points: point `i` changes from `old` to `new` widths, and the nearest
|
||||
/// points at other positions either side change in proportion (by the same amount from zero).
|
||||
fn adjust_adjoining(points: &mut [(f64, f64, f64)], i: usize, old: (f64, f64, f64), new: (f64, f64, f64)) {
|
||||
let t = points[i].0;
|
||||
/// points farther than [`SAME_T`] from place `t` on the sides `sides` names (before, after)
|
||||
/// change in proportion (by the same amount from zero).
|
||||
fn adjust_adjoining(points: &mut [(f64, f64, f64)], i: usize, t: f64, old: (f64, f64, f64), new: (f64, f64, f64), sides: [bool; 2]) {
|
||||
let scale = |v: f64, o: f64, n: f64| {
|
||||
let width = if o > 1e-9 {
|
||||
let product = v * n;
|
||||
@@ -284,8 +293,8 @@ fn adjust_adjoining(points: &mut [(f64, f64, f64)], i: usize, old: (f64, f64, f6
|
||||
};
|
||||
width.max(0.0)
|
||||
};
|
||||
let before = (0..i).rev().find(|j| (points[*j].0 - t).abs() > SAME_T);
|
||||
let after = (i + 1..points.len()).find(|j| (points[*j].0 - t).abs() > SAME_T);
|
||||
let before = (0..i).rev().find(|j| (points[*j].0 - t).abs() > SAME_T).filter(|_| sides[0]);
|
||||
let after = (i + 1..points.len()).find(|j| (points[*j].0 - t).abs() > SAME_T).filter(|_| sides[1]);
|
||||
for j in before.into_iter().chain(after) {
|
||||
let q = &mut points[j];
|
||||
(q.1, q.2) = (scale(q.1, old.1, new.1), scale(q.2, old.2, new.2));
|
||||
@@ -303,6 +312,46 @@ fn same_points(a: Option<&WidthProfile>, b: Option<&WidthProfile>) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// Set both halves of the discontinuous point whose incoming half is `i` and outgoing half `j` to
|
||||
/// the widths of `inc` and `out` (their places are ignored: the point keeps its place). With
|
||||
/// `single` (`true` for the outgoing half) only that half's widths remain, as one continuous point.
|
||||
/// With `adjust`, the nearest point before changes with the incoming half and the nearest point after
|
||||
/// with the outgoing half, once each. → the index of the point (its incoming half).
|
||||
fn set_pair(
|
||||
points: &mut Vec<(f64, f64, f64)>,
|
||||
(i, inc): (usize, (f64, f64, f64)),
|
||||
(j, out): (usize, (f64, f64, f64)),
|
||||
adjust: bool,
|
||||
single: Option<bool>,
|
||||
) -> Result<usize> {
|
||||
const C: &str = "stroke.widthPoint.set";
|
||||
if width_point_pair(points, i) != Some(j) {
|
||||
return Err(bad(C, "`index` and `outIndex` must be the two halves of one discontinuous width point"));
|
||||
}
|
||||
let at = points[i].0;
|
||||
let (old_in, old_out) = (points[i], points[j]);
|
||||
if (old_in.0 - inc.0).abs() > SAME_T {
|
||||
return Err(bad(C, "a discontinuous width point keeps its place"));
|
||||
}
|
||||
let (new_in, new_out) = match single {
|
||||
None => ((old_in.0, inc.1, inc.2), (old_out.0, out.1, out.2)),
|
||||
Some(false) => ((old_in.0, inc.1, inc.2), (old_in.0, inc.1, inc.2)),
|
||||
Some(true) => ((old_in.0, out.1, out.2), (old_in.0, out.1, out.2)),
|
||||
};
|
||||
// Both halves measure their neighbors from the point's place, so a point within SAME_T of the
|
||||
// outgoing half but not of that place is the point after the pair.
|
||||
if adjust {
|
||||
adjust_adjoining(points, i, at, old_in, new_in, [true, false]);
|
||||
adjust_adjoining(points, j, at, old_out, new_out, [false, true]);
|
||||
}
|
||||
points[i] = new_in;
|
||||
points[j] = new_out;
|
||||
if single.is_some() {
|
||||
points.remove(j);
|
||||
}
|
||||
Ok(i)
|
||||
}
|
||||
|
||||
fn width_point_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "stroke.widthPoint.set";
|
||||
let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?;
|
||||
@@ -312,6 +361,25 @@ fn width_point_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(C, "left/right must be non-negative widths"));
|
||||
}
|
||||
let adjust = switch_or(p, "adjustAdjoining", false, C)?;
|
||||
let single = match text_param(p, "single", C)? {
|
||||
None => None,
|
||||
Some(side @ ("incoming" | "outgoing")) => Some(side == "outgoing"),
|
||||
Some(_) => return Err(bad(C, "`single` must be `incoming` or `outgoing`")),
|
||||
};
|
||||
// The outgoing half of a discontinuous point: its index and side widths (points).
|
||||
// `single`, `outLeft` or `outRight` without `outIndex` is refused as a missing `outIndex`.
|
||||
let out_widths = ["outLeft", "outRight"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null()));
|
||||
let out = match p.get("outIndex") {
|
||||
None | Some(Value::Null) if single.is_none() && !out_widths => None,
|
||||
_ => {
|
||||
let j = usize::try_from(u64_req(p, "outIndex", C)?).map_err(|_| bad(C, "no such width point"))?;
|
||||
let (l, r) = (f64_req(p, "outLeft", C)?, f64_req(p, "outRight", C)?);
|
||||
if !(l.is_finite() && r.is_finite()) || l < 0.0 || r < 0.0 || l.max(r) > 1.0e5 {
|
||||
return Err(bad(C, "left/right must be non-negative widths"));
|
||||
}
|
||||
Some((j, l, r))
|
||||
}
|
||||
};
|
||||
// When the profile comes out as it was, within a rounding error (1e-9), the document and its undo
|
||||
// history stay as they are.
|
||||
let mut pos = 0;
|
||||
@@ -324,11 +392,19 @@ fn width_point_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(C, "width factors must be finite"));
|
||||
}
|
||||
let mut prof = st.profile.take().unwrap_or_else(uniform);
|
||||
pos = match point_index(p, &prof, C)? {
|
||||
Some(i) => {
|
||||
pos = match (point_index(p, &prof, C)?, out) {
|
||||
(None, Some(_)) => return Err(bad(C, "missing index")),
|
||||
(Some(i), Some((j, l, r))) => {
|
||||
let out = (t, l / half, r / half);
|
||||
if !out.1.is_finite() || !out.2.is_finite() {
|
||||
return Err(bad(C, "width factors must be finite"));
|
||||
}
|
||||
set_pair(&mut prof.points, (i, pt), (j, out), adjust, single)?
|
||||
}
|
||||
(Some(i), None) => {
|
||||
let old = prof.points[i];
|
||||
if adjust {
|
||||
adjust_adjoining(&mut prof.points, i, old, pt);
|
||||
adjust_adjoining(&mut prof.points, i, old.0, old, pt, [true, true]);
|
||||
}
|
||||
if (old.0 - t).abs() <= SAME_T {
|
||||
// Widths only: it keeps its place (and its side of a discontinuous point).
|
||||
@@ -339,12 +415,12 @@ fn width_point_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
place(&mut prof.points, pt, old.0 < t)
|
||||
}
|
||||
}
|
||||
None => {
|
||||
(None, None) => {
|
||||
let old = adjust.then(|| prof.at(t));
|
||||
prof.points.retain(|q| (q.0 - t).abs() > SAME_T);
|
||||
let i = place(&mut prof.points, pt, true);
|
||||
if let Some((left, right)) = old {
|
||||
adjust_adjoining(&mut prof.points, i, (t, left, right), pt);
|
||||
adjust_adjoining(&mut prof.points, i, pt.0, (t, left, right), pt, [true, true]);
|
||||
}
|
||||
i
|
||||
}
|
||||
|
||||
@@ -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}, 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), 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), 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",
|
||||
has_doc,
|
||||
info
|
||||
),
|
||||
@@ -178,14 +178,58 @@ fn repeat_entry(d: &Document, n: &Node, spec: &RepeatSpec) -> (Value, (String, S
|
||||
(entry, (name, format!("{}, {detail}", kind.label())))
|
||||
}
|
||||
|
||||
/// The artboards the Artboard tool has selected while it is the current tool, in artboard order,
|
||||
/// with the index of its active artboard; none with another tool or when it has none of the
|
||||
/// document's artboards selected. Indices the document does not have are left out.
|
||||
fn artboard_tool_selection(s: &Session) -> Option<(Vec<usize>, usize)> {
|
||||
if s.tool_id() != "artboard" {
|
||||
return None;
|
||||
}
|
||||
let n = s.active().map_or(0, |d| d.doc.artboards.len());
|
||||
let t = s.tool_options_of("artboard");
|
||||
let index = |v: &Value| v.as_u64().and_then(|i| usize::try_from(i).ok()).filter(|i| *i < n);
|
||||
let mut picked: Vec<usize> = t["selected"].as_array().into_iter().flatten().filter_map(index).collect();
|
||||
picked.sort_unstable();
|
||||
picked.dedup();
|
||||
let first = *picked.first()?;
|
||||
let active = index(&t["active"]).filter(|a| picked.contains(a)).unwrap_or(first);
|
||||
Some((picked, active))
|
||||
}
|
||||
|
||||
/// The artboards `picked` as Document Info › Document lists them while the Artboard tool is the
|
||||
/// current tool: their `selectedArtboards` entries (in the document's units), and for each its
|
||||
/// rows: its name, width, height and the X and Y of its top-left corner from the ruler origin of
|
||||
/// artboard `active`.
|
||||
fn selected_artboard_rows(d: &Document, picked: &[usize], active: usize) -> (Vec<Value>, Vec<(String, String)>) {
|
||||
let (u, per) = (d.units, d.units.points());
|
||||
let origin = d.ruler_origin_for(active);
|
||||
let mut entries = vec![];
|
||||
let mut rows = vec![];
|
||||
for &i in picked {
|
||||
let Some(a) = d.artboards.get(i) else { continue };
|
||||
let (w, h, x, y) = (a.rect.width(), a.rect.height(), a.rect.x0 - origin.x, a.rect.y0 - origin.y);
|
||||
entries.push(json!({ "index": i, "name": a.name, "width": w / per, "height": h / per, "x": x / per, "y": y / per }));
|
||||
rows.extend([
|
||||
("Artboard".to_string(), a.name.clone()),
|
||||
("Width".into(), u.format(w)),
|
||||
("Height".into(), u.format(h)),
|
||||
("X".into(), u.format(x)),
|
||||
("Y".into(), u.format(y)),
|
||||
]);
|
||||
}
|
||||
(entries, rows)
|
||||
}
|
||||
|
||||
/// The Document Info categories of `d` (only `category` when given) from `info` (what
|
||||
/// `document.info` reports), its fonts and their Font Details rows, its image objects, the rows of
|
||||
/// the brushes its art uses, the rows of its Repeat objects and the rows of its objects filled or
|
||||
/// stroked with a spot color, with a pattern and with a gradient.
|
||||
/// `document.info` reports), the rows of the artboards the Artboard tool has selected, its fonts
|
||||
/// and their Font Details rows, its image objects, the rows of the brushes its art uses, the rows
|
||||
/// of its Repeat objects and the rows of its objects filled or stroked with a spot color, with a
|
||||
/// pattern and with a gradient.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn sections(
|
||||
d: &Document,
|
||||
info: &Value,
|
||||
selected_artboards: &[(String, String)],
|
||||
fonts: &BTreeSet<super::fonts::UsedFont>,
|
||||
font_details: &[(String, String)],
|
||||
images: &[ImageRow],
|
||||
@@ -215,7 +259,19 @@ fn sections(
|
||||
rows.extend(
|
||||
d.artboards.iter().map(|a| (a.name.clone(), format!("{} × {}", u.format(a.rect.width()), u.format(a.rect.height())))),
|
||||
);
|
||||
rows.extend(selected_artboards.iter().cloned());
|
||||
rows.push(("Raster Effects".into(), format!("{} ppi", d.raster_effects_ppi)));
|
||||
let setup = &d.setup;
|
||||
let colors = match setup.grid_colors_name() {
|
||||
"Custom" => setup.grid_colors.map(|c| c.to_hex()).join(", "),
|
||||
name => name.to_string(),
|
||||
};
|
||||
rows.extend([
|
||||
("Grid Size".to_string(), setup.grid_size.label().to_string()),
|
||||
("Grid Colors".into(), colors),
|
||||
("Simulate Colored Paper".into(), if setup.simulate_paper { "On" } else { "Off" }.into()),
|
||||
("Flattener Preset".into(), setup.flattener().to_string()),
|
||||
]);
|
||||
let counts = [
|
||||
("Swatches", "swatches"),
|
||||
("Character Styles", "characterStyles"),
|
||||
@@ -556,6 +612,7 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some("text") => true,
|
||||
Some(f) => return Err(bad(C, format!("format `{f}`: text or json"))),
|
||||
};
|
||||
let artboard_tool = artboard_tool_selection(s);
|
||||
let st = s.doc()?;
|
||||
let d = &st.doc;
|
||||
let selection_only = bool_or(p, "selectionOnly", false);
|
||||
@@ -787,7 +844,22 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
});
|
||||
// The document's name: its file's, else its title.
|
||||
out["document"]["name"] = json!(st.title());
|
||||
let sections = sections(d, &out, &fonts, &font_rows, &image_rows, &brush_rows, &repeat_rows, &spot_rows, &pattern_rows, &gradient_rows, category);
|
||||
let (selected_entries, selected_rows) = artboard_tool.map(|(picked, active)| selected_artboard_rows(d, &picked, active)).unwrap_or_default();
|
||||
out["document"]["selectedArtboards"] = json!(selected_entries);
|
||||
let sections = sections(
|
||||
d,
|
||||
&out,
|
||||
&selected_rows,
|
||||
&fonts,
|
||||
&font_rows,
|
||||
&image_rows,
|
||||
&brush_rows,
|
||||
&repeat_rows,
|
||||
&spot_rows,
|
||||
&pattern_rows,
|
||||
&gradient_rows,
|
||||
category,
|
||||
);
|
||||
if text {
|
||||
return Ok(json!({ "text": report_text(&st.title(), selection_only, §ions) }));
|
||||
}
|
||||
@@ -804,6 +876,13 @@ fn document_summary(d: &Document) -> Value {
|
||||
"unitId": d.units.key(),
|
||||
"artboards": d.artboards.iter().map(|a| json!({ "name": a.name, "width": a.rect.width() / u, "height": a.rect.height() / u })).collect::<Vec<_>>(),
|
||||
"rasterEffectsPpi": d.raster_effects_ppi,
|
||||
"transparency": {
|
||||
"gridSize": d.setup.grid_size.id(),
|
||||
"gridColors": d.setup.grid_colors.map(|c| c.to_hex()),
|
||||
"gridColorsName": d.setup.grid_colors_name(),
|
||||
"simulatePaper": d.setup.simulate_paper,
|
||||
"flattenerPreset": d.setup.flattener(),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -875,6 +954,101 @@ mod tests {
|
||||
assert!(i["objects"]["textObjects"].is_null() && i["objects"]["paths"] == 1);
|
||||
}
|
||||
|
||||
/// The Document category's rows from `info`, as (label, value) pairs.
|
||||
fn document_rows(i: &Value) -> Vec<(String, String)> {
|
||||
let doc = i["sections"].as_array().unwrap().iter().find(|s| s["id"] == "document").unwrap();
|
||||
doc["rows"].as_array().unwrap().iter().map(|r| (r[0].as_str().unwrap().to_string(), r[1].as_str().unwrap().to_string())).collect()
|
||||
}
|
||||
|
||||
/// Document lists File › Document Setup's transparency settings: the grid's size and colors
|
||||
/// (a preset's name, else both colors), Simulate Colored Paper and the flattener preset.
|
||||
#[test]
|
||||
fn info_lists_the_transparency_settings() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
|
||||
let i = s.execute("document.info", &json!({})).unwrap();
|
||||
let t = &i["document"]["transparency"];
|
||||
assert_eq!(
|
||||
(t["gridSize"].clone(), t["gridColorsName"].clone(), t["simulatePaper"].clone(), t["flattenerPreset"].clone()),
|
||||
(json!("medium"), json!("Light"), json!(false), json!("Medium Resolution"))
|
||||
);
|
||||
let rows = document_rows(&i);
|
||||
let at = rows.iter().position(|(l, _)| l == "Raster Effects").unwrap();
|
||||
let expected =
|
||||
[("Grid Size", "Medium"), ("Grid Colors", "Light"), ("Simulate Colored Paper", "Off"), ("Flattener Preset", "Medium Resolution")];
|
||||
assert_eq!(rows[at + 1..at + 5], expected.map(|(l, v)| (l.to_string(), v.to_string())), "{rows:?}");
|
||||
s.execute(
|
||||
"document.setup",
|
||||
&json!({"gridSize": "large", "gridColors": ["#ff0000", "#00ff00"], "simulatePaper": true, "flattenerPreset": "High Resolution"}),
|
||||
)
|
||||
.unwrap();
|
||||
let i = s.execute("document.info", &json!({})).unwrap();
|
||||
assert_eq!(i["document"]["transparency"]["gridColors"], json!(["#ff0000", "#00ff00"]));
|
||||
assert_eq!(i["document"]["transparency"]["gridColorsName"], "Custom");
|
||||
let rows = document_rows(&i);
|
||||
let expected =
|
||||
[("Grid Size", "Large"), ("Grid Colors", "#ff0000, #00ff00"), ("Simulate Colored Paper", "On"), ("Flattener Preset", "High Resolution")];
|
||||
assert_eq!(rows[at + 1..at + 5], expected.map(|(l, v)| (l.to_string(), v.to_string())), "{rows:?}");
|
||||
let report = s.execute("document.info", &json!({"category": "document", "format": "text"})).unwrap()["text"].as_str().unwrap().to_string();
|
||||
assert!(report.contains("Grid Colors: #ff0000, #00ff00\nSimulate Colored Paper: On\nFlattener Preset: High Resolution\n"), "{report}");
|
||||
}
|
||||
|
||||
/// While the Artboard tool is the current tool, Document lists each artboard it has selected
|
||||
/// after the artboards: its name, width, height and the X and Y of its top-left corner from the
|
||||
/// ruler origin of the tool's active artboard. With another tool it lists none.
|
||||
#[test]
|
||||
fn info_lists_the_artboards_the_artboard_tool_selected() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
s.execute("artboard.new", &json!({"x": 150, "y": 40, "width": 60, "height": 80})).unwrap();
|
||||
s.execute("artboard.new", &json!({"x": 400, "y": 10, "width": 100, "height": 50})).unwrap();
|
||||
s.execute("artboard.setProps", &json!({"index": 2, "name": "Back"})).unwrap();
|
||||
let before = s.execute("document.info", &json!({})).unwrap();
|
||||
assert_eq!(before["document"]["selectedArtboards"], json!([]));
|
||||
s.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap();
|
||||
s.set_tool_option("selected", &json!([2, 1, 7]));
|
||||
let i = s.execute("document.info", &json!({})).unwrap();
|
||||
// Artboard 2 is active: positions are measured from its top-left corner.
|
||||
assert_eq!(
|
||||
i["document"]["selectedArtboards"],
|
||||
json!([
|
||||
{"index": 1, "name": "Artboard 2", "width": 60.0, "height": 80.0, "x": -250.0, "y": 30.0},
|
||||
{"index": 2, "name": "Back", "width": 100.0, "height": 50.0, "x": 0.0, "y": 0.0},
|
||||
])
|
||||
);
|
||||
let rows = document_rows(&i);
|
||||
let at = rows.iter().position(|(l, _)| l == "Artboards").unwrap() + 4;
|
||||
let expected = [
|
||||
("Artboard", "Artboard 2"),
|
||||
("Width", "60 pt"),
|
||||
("Height", "80 pt"),
|
||||
("X", "-250 pt"),
|
||||
("Y", "30 pt"),
|
||||
("Artboard", "Back"),
|
||||
("Width", "100 pt"),
|
||||
("Height", "50 pt"),
|
||||
("X", "0 pt"),
|
||||
("Y", "0 pt"),
|
||||
("Raster Effects", "72 ppi"),
|
||||
];
|
||||
assert_eq!(rows[at..at + 11], expected.map(|(l, v)| (l.to_string(), v.to_string())), "{rows:?}");
|
||||
// The rows follow the document's units and its ruler origin.
|
||||
s.execute("document.setup", &json!({"units": "Millimeters"})).unwrap();
|
||||
s.execute("document.setRulerOrigin", &json!({"x": 390, "y": 0, "artboard": 2})).unwrap();
|
||||
s.set_tool_option("selected", &json!([2]));
|
||||
let i = s.execute("document.info", &json!({"category": "document"})).unwrap();
|
||||
let entry = &i["document"]["selectedArtboards"];
|
||||
assert_eq!((entry.as_array().unwrap().len(), entry[0]["index"].clone()), (1, json!(2)));
|
||||
assert!((entry[0]["x"].as_f64().unwrap() - 10.0 * 25.4 / 72.0).abs() < 1e-9, "{entry}");
|
||||
let rows = document_rows(&i);
|
||||
assert!(rows.contains(&("X".into(), "3.5278 mm".into())) && rows.contains(&("Y".into(), "3.5278 mm".into())), "{rows:?}");
|
||||
// Another tool: no artboard rows.
|
||||
s.select_tool("selection", crate::tooling::ViewInfo::default()).unwrap();
|
||||
let i = s.execute("document.info", &json!({})).unwrap();
|
||||
assert_eq!(i["document"]["selectedArtboards"], json!([]));
|
||||
assert!(!document_rows(&i).iter().any(|(l, _)| l == "X"), "{:?}", document_rows(&i));
|
||||
}
|
||||
|
||||
/// Document Info's fonts include the type in an opacity mask, in a symbol's art and in a
|
||||
/// pattern swatch that nothing paints with; with `selectionOnly`, only the selected type's.
|
||||
#[test]
|
||||
|
||||
@@ -238,7 +238,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Guide",
|
||||
[],
|
||||
None,
|
||||
"{index, pos: pt} | {dx?, dy?: pt, copy?: bool} put ruler guide `index` at `pos`, or move the selected guides (vertical ones by dx, horizontal ones by dy); copy leaves them and selects the moved copies",
|
||||
"{index, pos: pt} | {dx?, dy?: pt, copy?: bool, interpolate?: bool (with art selected too: as object.move's)} put ruler guide `index` at `pos`, or move the selected guides (vertical ones by dx, horizontal ones by dy); copy leaves them and selects the moved copies",
|
||||
guides_unlocked,
|
||||
guide_move
|
||||
),
|
||||
@@ -990,6 +990,7 @@ pub(crate) fn guide_move(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let dx = number_or(p, "dx", 0.0, "guide.move")?;
|
||||
let dy = number_or(p, "dy", 0.0, "guide.move")?;
|
||||
let copy = switch_or(p, "copy", false, "guide.move")?;
|
||||
switch_or(p, "interpolate", false, "guide.move")?;
|
||||
if !s.doc()?.selection.is_empty() {
|
||||
let ids = super::edit::selected_roots(s)?;
|
||||
return super::object::apply_transform(
|
||||
|
||||
@@ -11,7 +11,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Pencil",
|
||||
[],
|
||||
None,
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise, 0..360: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks. A pressure, tilt or rotation outside its range, or a point array of more than six numbers, is an error), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\" (default) | \"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end?: \"end\" (default) | \"start\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it. Any other style, extend end or connect end is an error, and nothing changes",
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise, 0..360: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks. A pressure, tilt or rotation outside its range, or a point array of more than six numbers, is an error), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\" (default) | \"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end?: \"end\" (default) | \"start\"}, connect?: {id, end: \"start\"|\"end\"} (only with extend), redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it. Any other style, extend end or connect end, connect without extend, and a connect that names no other path with an open end are errors, a stroke of one point included, and nothing changes",
|
||||
has_doc,
|
||||
freehand
|
||||
),
|
||||
@@ -101,7 +101,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Path Eraser",
|
||||
[],
|
||||
None,
|
||||
"{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change what is erased), width?: pt (8)} erase the parts of selected paths under the drag → {ids}",
|
||||
"{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change what is erased), width?: pt (8; from 0.001 to 1000)} erase the parts of selected paths under the drag → {ids}. A width outside 0.001 to 1000 is refused with an error, and nothing changes",
|
||||
has_selection,
|
||||
erase_segments
|
||||
),
|
||||
|
||||
@@ -522,13 +522,13 @@ fn apply_plan(s: &mut Session, label: &str, plan: Vec<(NodeId, Vec<PathData>)>)
|
||||
Ok(ids_json(&ids))
|
||||
}
|
||||
|
||||
/// The Path Eraser's band width, in points (VectorCraft's own range).
|
||||
const PATH_ERASER_WIDTHS: (f64, f64) = (0.001, 1000.0);
|
||||
|
||||
pub(super) fn erase_segments(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "path.eraseSegments";
|
||||
let pts = points_param(p, "points", C)?;
|
||||
let w = number_or(p, "width", 8.0, C)?;
|
||||
if !(w.is_finite() && w > 0.0) {
|
||||
return Err(bad(C, "width must be positive"));
|
||||
}
|
||||
let w = ranged(p, "width", 8.0, PATH_ERASER_WIDTHS, C)?;
|
||||
let st = s.doc()?;
|
||||
let mut plan = vec![];
|
||||
for id in target_paths(&st.doc, &st.selection, poly_bounds(&pts, w)) {
|
||||
|
||||
@@ -174,9 +174,13 @@ fn no_stroke(name: &str) -> EngineError {
|
||||
bad("brush.freehand", format!("cannot apply brush `{name}`: path has no stroke"))
|
||||
}
|
||||
|
||||
/// Sets brush `name` on the stroke of object `id` of `d`.
|
||||
/// Sets brush `name` on the stroke of object `id` of `d`. The stroke's own settings for another
|
||||
/// brush (Options of Selected Object) are cleared.
|
||||
fn set_brush(d: &mut Document, id: NodeId, name: &str) {
|
||||
if let Some(st) = d.node_mut(id).and_then(|n| n.appearance.stroke_mut()) {
|
||||
if st.brush.as_deref() != Some(name) {
|
||||
st.brush_options.clear();
|
||||
}
|
||||
st.brush = Some(name.to_string());
|
||||
}
|
||||
}
|
||||
@@ -209,7 +213,11 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s
|
||||
let label = if brush || brush_name.is_some() { "Paintbrush" } else { "Pencil" };
|
||||
let keep_selected = switch_or(p, "keepSelected", true, C)?;
|
||||
let filled = switch_or(p, "fill", false, C)?;
|
||||
if let Some(ext) = p.get("extend").filter(|v| !v.is_null()) {
|
||||
let extend = p.get("extend").filter(|v| !v.is_null());
|
||||
if extend.is_none() && p.get("connect").is_some_and(|v| !v.is_null()) {
|
||||
return Err(bad(C, "connect needs extend"));
|
||||
}
|
||||
if let Some(ext) = extend {
|
||||
let id = object_param(ext, "id", C)?.ok_or_else(|| bad(C, "extend needs id"))?;
|
||||
let at_start = match ext.get("end").filter(|v| !v.is_null()).map(Value::as_str) {
|
||||
None | Some(Some("end")) => false,
|
||||
@@ -234,26 +242,9 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s
|
||||
};
|
||||
let Some(p0) = pts.first_mut() else { return Err(bad(C, "needs points")) };
|
||||
*p0 = end;
|
||||
if pts.len() < 2 {
|
||||
// No stroke to add: the brush alone changes, when it is not the path's already, and the
|
||||
// path is selected or deselected as a longer continuation leaves it.
|
||||
if let Some(name) = brush_name
|
||||
&& s.doc()?.doc.node(target).and_then(|n| n.appearance.stroke()).is_some_and(|st| st.brush.as_deref() != Some(name))
|
||||
{
|
||||
s.edit("Paintbrush", |d, sel| {
|
||||
set_brush(d, target, name);
|
||||
if keep_selected {
|
||||
sel.set([id]);
|
||||
} else {
|
||||
sel.remove(id);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
return Ok(json!({ "id": id.0 }));
|
||||
}
|
||||
// A stroke that ends on an open end of another path connects the two: (that path, its last
|
||||
// open subpath, that subpath starting at the end the stroke ends on, it ends at its end).
|
||||
// It is checked before a stroke of one point returns, so a bad `connect` is refused there too.
|
||||
let connect = match p.get("connect").filter(|v| !v.is_null()) {
|
||||
Some(cn) => {
|
||||
let other = object_param(cn, "id", C)?.ok_or_else(|| bad(C, "connect needs id"))?;
|
||||
@@ -276,6 +267,24 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
if pts.len() < 2 {
|
||||
// No stroke to add: the brush alone changes, when it is not the path's already, and the
|
||||
// path is selected or deselected as a longer continuation leaves it.
|
||||
if let Some(name) = brush_name
|
||||
&& s.doc()?.doc.node(target).and_then(|n| n.appearance.stroke()).is_some_and(|st| st.brush.as_deref() != Some(name))
|
||||
{
|
||||
s.edit("Paintbrush", |d, sel| {
|
||||
set_brush(d, target, name);
|
||||
if keep_selected {
|
||||
sel.set([id]);
|
||||
} else {
|
||||
sel.remove(id);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
return Ok(json!({ "id": id.0 }));
|
||||
}
|
||||
// `closed`, when given, says whether the stroke closes the path: the Pencil and the
|
||||
// Paintbrush send it, by their Close Paths When Ends Are Within and Alt at the release.
|
||||
// Left out, an extending stroke that ends within four Fidelities of the path's other end
|
||||
|
||||
@@ -6,6 +6,7 @@ use std::sync::Arc;
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind, RulerMode, Unit};
|
||||
use vectorcraft_geom::{Affine, Point, Vec2};
|
||||
use vectorcraft_tools::distort::perspective::{PerspectiveGrid, Plane};
|
||||
|
||||
use super::clipboard::SwatchChoices;
|
||||
use super::{
|
||||
@@ -713,6 +714,85 @@ pub(crate) fn settle_interaction(s: &mut Session) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The document state that commands also change without an undo step: the perspective grid's view
|
||||
/// options (whether it shows, Lock Grid, Lock Station Point, Snap to Grid and Show Rulers), its
|
||||
/// active plane, the grid preferences, the export settings, and the current brush and symbol. Each
|
||||
/// undo and redo step keeps it as the document on its other side had it
|
||||
/// ([`crate::HistoryEntry::unrecorded`]).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) struct Unrecorded {
|
||||
grid: vectorcraft_doc::GridPrefs,
|
||||
export_settings: serde_json::Map<String, Value>,
|
||||
brush: Option<Value>,
|
||||
symbol: Option<Value>,
|
||||
options: [bool; 5],
|
||||
plane: Plane,
|
||||
}
|
||||
|
||||
impl Unrecorded {
|
||||
pub(crate) fn of(d: &Document) -> Self {
|
||||
let g = PerspectiveGrid::current(d);
|
||||
Unrecorded {
|
||||
grid: d.grid.clone(),
|
||||
export_settings: d.export_settings.clone(),
|
||||
brush: d.unknown.get(vectorcraft_brush::CURRENT_KEY).cloned(),
|
||||
symbol: d.unknown.get(super::brushsym::CURRENT_SYMBOL).cloned(),
|
||||
options: [g.visible, g.locked, g.lock_station, g.snap, g.rulers],
|
||||
plane: g.plane,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Undo and redo bring back `d`; `step` is that state as the document on the step's other side had
|
||||
/// it. A part the step did not change (`d` has it as `step` does) stays as it is in `now`, the
|
||||
/// document before the undo or redo, since it changed after the step without an undo step. A part
|
||||
/// the step changed comes back with `d`. A current brush or symbol that `d` does not hold also
|
||||
/// comes back with `d`. The point Automatic Plane Positioning holds comes back with `d`, and is let go when the
|
||||
/// active plane kept is not the one it holds.
|
||||
fn keep_unrecorded(now: &Document, step: &Unrecorded, d: &mut Arc<Document>) {
|
||||
fn pick<T: Clone + PartialEq>(back: &T, step: &T, now: &T) -> T {
|
||||
if back == step { now.clone() } else { back.clone() }
|
||||
}
|
||||
let back = Unrecorded::of(d);
|
||||
let cur = Unrecorded::of(now);
|
||||
let mut want = Unrecorded {
|
||||
grid: pick(&back.grid, &step.grid, &cur.grid),
|
||||
export_settings: pick(&back.export_settings, &step.export_settings, &cur.export_settings),
|
||||
brush: pick(&back.brush, &step.brush, &cur.brush),
|
||||
symbol: pick(&back.symbol, &step.symbol, &cur.symbol),
|
||||
options: std::array::from_fn(|i| pick(&back.options[i], &step.options[i], &cur.options[i])),
|
||||
plane: pick(&back.plane, &step.plane, &cur.plane),
|
||||
};
|
||||
if want.brush != back.brush && want.brush.as_ref().and_then(Value::as_str).is_some_and(|n| vectorcraft_brush::find(d, n).is_none()) {
|
||||
want.brush = back.brush.clone();
|
||||
}
|
||||
if want.symbol != back.symbol && want.symbol.as_ref().and_then(Value::as_str).is_some_and(|n| !d.symbols.iter().any(|s| s.name == n)) {
|
||||
want.symbol = back.symbol.clone();
|
||||
}
|
||||
if want == back {
|
||||
return;
|
||||
}
|
||||
let m = Arc::make_mut(d);
|
||||
for (key, v) in [(vectorcraft_brush::CURRENT_KEY, &want.brush), (super::brushsym::CURRENT_SYMBOL, &want.symbol)] {
|
||||
match v {
|
||||
Some(v) => m.unknown.insert(key.into(), v.clone()),
|
||||
None => m.unknown.remove(key),
|
||||
};
|
||||
}
|
||||
if (want.options, want.plane) != (back.options, back.plane) {
|
||||
let mut g = PerspectiveGrid::current(m);
|
||||
[g.visible, g.locked, g.lock_station, g.snap, g.rulers] = want.options;
|
||||
if g.plane != want.plane {
|
||||
g.plane = want.plane;
|
||||
g.inferred = None;
|
||||
}
|
||||
g.keep_positioning_valid();
|
||||
super::distortcmds::store_grid(m, &g);
|
||||
}
|
||||
m.grid = want.grid;
|
||||
m.export_settings = want.export_settings;
|
||||
}
|
||||
|
||||
fn undo(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
settle_interaction(s)?;
|
||||
let menu = s.menu.clone();
|
||||
@@ -723,6 +803,7 @@ fn undo(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let editing = st.doc.mask_edit.map(|m| m.layer);
|
||||
let editing_symbol = st.doc.symbol_edit.clone();
|
||||
let doc = std::mem::replace(&mut st.doc, e.doc);
|
||||
keep_unrecorded(&doc, &e.unrecorded, &mut st.doc);
|
||||
let selection = std::mem::replace(&mut st.selection, Arc::unwrap_or_clone(e.selection));
|
||||
let selection = shared_selection(selection, st.history.redo.last());
|
||||
let mut turned = crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs);
|
||||
@@ -758,6 +839,7 @@ fn redo(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let editing = st.doc.mask_edit.map(|m| m.layer);
|
||||
let editing_symbol = st.doc.symbol_edit.clone();
|
||||
let doc = std::mem::replace(&mut st.doc, e.doc);
|
||||
keep_unrecorded(&doc, &e.unrecorded, &mut st.doc);
|
||||
let selection = std::mem::replace(&mut st.selection, Arc::unwrap_or_clone(e.selection));
|
||||
let selection = shared_selection(selection, st.history.undo.last());
|
||||
let mut turned = crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs);
|
||||
@@ -1076,8 +1158,10 @@ fn cut(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// Select every surviving piece while retaining intentional compound-path structure.
|
||||
/// `roots` contains the copied targets: whole-object roots are removed in full, while partial paths
|
||||
/// lose only the copied geometry. An exhausted partial path is removed, along with its compound
|
||||
/// parent if now empty; layers remain. Returns JSON `null` on success, replacing direct-selection
|
||||
/// references with surviving object IDs.
|
||||
/// parent if now empty; a compound left with one member stays a compound path, as after Clear;
|
||||
/// layers remain. Removed and replaced roots go through one [`super::pathops::Beside`], which
|
||||
/// rebuilds each parent's children once when the roots are separate. Returns JSON `null` on
|
||||
/// success, replacing direct-selection references with surviving object IDs.
|
||||
fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let sel = st.selection.clone();
|
||||
@@ -1085,13 +1169,18 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
|
||||
// The selected ruler guides were copied too (#3226): they go in the same undo step.
|
||||
let gone = selection.guides.clone();
|
||||
d.retain_guides(selection, |g| !g.id.is_some_and(|id| gone.contains(&id)));
|
||||
// The compound paths that hold a root; one left with no members goes too.
|
||||
let compounds: BTreeSet<NodeId> = roots
|
||||
.iter()
|
||||
.filter_map(|id| d.parent_of(*id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. }))))
|
||||
.collect();
|
||||
let mut survivors = vec![];
|
||||
let mut pieces = super::pathops::Beside::replacing(d, roots);
|
||||
for id in roots {
|
||||
let Some(node) = d.node(*id) else { continue };
|
||||
let has_direct = sel.anchors.contains_key(id) || sel.segments.contains_key(id);
|
||||
if !has_direct || node.path_data().is_none() {
|
||||
remove_leaving_no_empty_compound(d, *id)?;
|
||||
pieces.put(d, *id, vec![])?;
|
||||
continue;
|
||||
}
|
||||
let original = super::path::deletion_source(d, *id)?;
|
||||
@@ -1114,12 +1203,14 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
|
||||
}
|
||||
subpaths.retain(|sp| sp.anchors.len() >= 2);
|
||||
if subpaths.is_empty() {
|
||||
remove_leaving_no_empty_compound(d, *id)?;
|
||||
pieces.put(d, *id, vec![])?;
|
||||
} else {
|
||||
survivors.extend(super::path::replace_deleted_pieces(d, &mut pieces, original, subpaths)?);
|
||||
}
|
||||
}
|
||||
pieces.finish(d)?;
|
||||
let emptied: Vec<NodeId> = compounds.into_iter().filter(|p| d.node(*p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty()))).collect();
|
||||
super::pathops::remove_each(d, &emptied)?;
|
||||
selection.set(survivors);
|
||||
selection.anchors.clear();
|
||||
selection.segments.clear();
|
||||
@@ -1128,19 +1219,6 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
|
||||
ok()
|
||||
}
|
||||
|
||||
/// Remove object `id`, and the compound path that held it when it was the compound's last member.
|
||||
/// A compound left with one member stays a compound path, as after Clear.
|
||||
fn remove_leaving_no_empty_compound(d: &mut Document, id: NodeId) -> Result<()> {
|
||||
let parent = d.parent_of(id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })));
|
||||
d.remove(id)?;
|
||||
if let Some(p) = parent
|
||||
&& d.node(p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty()))
|
||||
{
|
||||
d.remove(p)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn clear(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let guides = switch_or(p, "guides", false, "edit.clear")?;
|
||||
let explicit = if p.get("ids").is_some() { Some(checked_ids_param(s, p, "ids", "edit.clear")?) } else { None };
|
||||
@@ -1751,3 +1829,6 @@ pub(crate) fn copy_above(d: &mut Document, roots: &[NodeId], mut change: impl Fn
|
||||
pub(crate) fn arc_nodes(v: Vec<Node>) -> Vec<Arc<Node>> {
|
||||
v.into_iter().map(Arc::new).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -0,0 +1,343 @@
|
||||
//! Cut with direct-selected anchors removes the objects selected whole and the paths it empties
|
||||
//! through one [`Beside`](super::super::pathops::Beside), and leaves the document, the selection,
|
||||
//! the clipboard and the undo history exactly as removing each of them on its own does.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, NodeId, NodeKind, tree_walks};
|
||||
|
||||
use super::*;
|
||||
use crate::tests_large_edits::{session, square};
|
||||
|
||||
/// Cut's removal with every root selected whole or emptied taken out by its own
|
||||
/// [`Document::remove`], and its compound path removed right after when that left it empty. The
|
||||
/// tests compare [`cut_direct_selection`] with it.
|
||||
fn cut_one_at_a_time(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let sel = st.selection.clone();
|
||||
s.edit("Cut", |d, selection| {
|
||||
let gone = selection.guides.clone();
|
||||
d.retain_guides(selection, |g| !g.id.is_some_and(|id| gone.contains(&id)));
|
||||
let mut survivors = vec![];
|
||||
let mut pieces = super::super::pathops::Beside::replacing(d, roots);
|
||||
for id in roots {
|
||||
let Some(node) = d.node(*id) else { continue };
|
||||
let has_direct = sel.anchors.contains_key(id) || sel.segments.contains_key(id);
|
||||
if !has_direct || node.path_data().is_none() {
|
||||
remove_one(d, *id)?;
|
||||
continue;
|
||||
}
|
||||
let original = super::super::path::deletion_source(d, *id)?;
|
||||
let seg_refs = sel.segments.get(id);
|
||||
let anchor_refs = sel.anchors.get(id);
|
||||
let mut subpaths = Vec::new();
|
||||
let owned = std::mem::take(&mut super::super::path::path_mut(d, *id)?.subpaths);
|
||||
for (si, sp) in owned.into_iter().enumerate() {
|
||||
let cuts = super::super::clipboard::subpath_selected_segments(&sp, si, seg_refs, anchor_refs);
|
||||
if cuts.is_empty() {
|
||||
subpaths.push(sp);
|
||||
} else if seg_refs.is_some_and(|segments| !segments.is_empty()) {
|
||||
subpaths.extend(super::super::path::without_segments(sp, &cuts));
|
||||
} else {
|
||||
let gone: BTreeSet<usize> = anchor_refs.into_iter().flat_map(|refs| super::super::path::subpath_refs(refs, si)).collect();
|
||||
subpaths.extend(super::super::path::without_anchors(sp, &gone));
|
||||
}
|
||||
}
|
||||
subpaths.retain(|sp| sp.anchors.len() >= 2);
|
||||
if subpaths.is_empty() {
|
||||
remove_one(d, *id)?;
|
||||
} else {
|
||||
survivors.extend(super::super::path::replace_deleted_pieces(d, &mut pieces, original, subpaths)?);
|
||||
}
|
||||
}
|
||||
pieces.finish(d)?;
|
||||
selection.set(survivors);
|
||||
selection.anchors.clear();
|
||||
selection.segments.clear();
|
||||
Ok(())
|
||||
})?;
|
||||
ok()
|
||||
}
|
||||
|
||||
/// Removes object `id`, and the compound path that held it when it was the compound's last member.
|
||||
fn remove_one(d: &mut Document, id: NodeId) -> Result<()> {
|
||||
let parent = d.parent_of(id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })));
|
||||
d.remove(id)?;
|
||||
if let Some(p) = parent
|
||||
&& d.node(p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty()))
|
||||
{
|
||||
d.remove(p)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Cut as `edit.cut` runs it for a direct selection, with [`cut_one_at_a_time`] in place of
|
||||
/// [`cut_direct_selection`].
|
||||
fn reference_cut(s: &mut Session) {
|
||||
let (direct, roots) = copy_cut_targets(s).unwrap();
|
||||
assert!(direct, "the selection is a direct selection");
|
||||
copy(s, &json!({})).unwrap();
|
||||
cut_one_at_a_time(s, &roots).unwrap();
|
||||
}
|
||||
|
||||
fn run(s: &mut Session, cmd: &str, p: Value) -> Value {
|
||||
s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}"))
|
||||
}
|
||||
|
||||
/// Selects `whole` as objects, then anchors `anchors` of each path in `partial`.
|
||||
fn select_direct(s: &mut Session, whole: &[NodeId], partial: &[(NodeId, Value)]) {
|
||||
run(s, "select.set", json!({"ids": whole.iter().map(|id| id.0).collect::<Vec<_>>()}));
|
||||
for (id, anchors) in partial {
|
||||
run(s, "select.anchors", json!({"id": id.0, "anchors": anchors, "mode": "add"}));
|
||||
}
|
||||
}
|
||||
|
||||
/// The ids of every node of the document, depth first, with the depth of each.
|
||||
fn tree(d: &Document) -> Vec<(usize, NodeId)> {
|
||||
fn walk(n: &vectorcraft_doc::Node, depth: usize, out: &mut Vec<(usize, NodeId)>) {
|
||||
out.push((depth, n.id));
|
||||
for c in n.children().into_iter().flatten() {
|
||||
walk(c, depth + 1, out);
|
||||
}
|
||||
}
|
||||
let mut out = vec![];
|
||||
for l in &d.layers {
|
||||
walk(l, 0, &mut out);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether `a` and `b` hold the same document, selection, clipboard and number of undo and redo
|
||||
/// steps.
|
||||
fn assert_same(a: &Session, b: &Session, when: &str) {
|
||||
let (x, y) = (a.doc().unwrap(), b.doc().unwrap());
|
||||
assert_eq!(tree(&x.doc), tree(&y.doc), "{when}: the tree");
|
||||
assert!(*x.doc == *y.doc, "{when}: the document");
|
||||
assert_eq!(x.selection, y.selection, "{when}: the selection");
|
||||
// Each session's document has its own uid; the clipboard names the one it came from.
|
||||
assert_eq!(a.clipboard.source_doc.is_some(), b.clipboard.source_doc.is_some(), "{when}: the clipboard's source");
|
||||
let unsourced = |c: &Clipboard| Clipboard { source_doc: None, ..c.clone() };
|
||||
assert!(unsourced(&a.clipboard) == unsourced(&b.clipboard), "{when}: the clipboard");
|
||||
assert_eq!(x.history.undo.len(), y.history.undo.len(), "{when}: the undo steps");
|
||||
assert_eq!(x.history.redo.len(), y.history.redo.len(), "{when}: the redo steps");
|
||||
}
|
||||
|
||||
/// Runs `edit.cut` on one session that `make` builds and [`reference_cut`] on another, and checks
|
||||
/// that both hold the same after the Cut, after Undo and after Redo. Returns the first session after
|
||||
/// the Cut.
|
||||
fn same_as_one_at_a_time(make: impl Fn() -> Session) -> Session {
|
||||
let (mut a, mut b) = (make(), make());
|
||||
let before = a.doc().unwrap().doc.clone();
|
||||
assert_same(&a, &b, "before");
|
||||
run(&mut a, "edit.cut", json!({}));
|
||||
reference_cut(&mut b);
|
||||
assert_same(&a, &b, "Cut");
|
||||
let after = a.doc().unwrap().doc.clone();
|
||||
run(&mut a, "edit.undo", json!({}));
|
||||
run(&mut b, "edit.undo", json!({}));
|
||||
assert_same(&a, &b, "Undo");
|
||||
assert!(*a.doc().unwrap().doc == *before, "Undo gives back the document");
|
||||
run(&mut a, "edit.redo", json!({}));
|
||||
run(&mut b, "edit.redo", json!({}));
|
||||
assert_same(&a, &b, "Redo");
|
||||
assert!(*a.doc().unwrap().doc == *after, "Redo gives back the Cut");
|
||||
run(&mut a, "edit.undo", json!({}));
|
||||
run(&mut a, "edit.redo", json!({}));
|
||||
a
|
||||
}
|
||||
|
||||
/// A new document; [`rect`] adds squares to it.
|
||||
fn new_doc() -> Session {
|
||||
let mut s = Session::new();
|
||||
run(&mut s, "file.new", json!({"width": 800, "height": 600}));
|
||||
s
|
||||
}
|
||||
|
||||
/// Adds a 10 pt square to the current layer, 20 pt right of the last one.
|
||||
fn rect(s: &mut Session) -> NodeId {
|
||||
let x = 20.0 * s.doc().unwrap().doc.node_count() as f64;
|
||||
NodeId(run(s, "shape.rectangle", json!({"x": x, "y": 10, "width": 10, "height": 10}))["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
/// Makes a compound path of `ids` and returns it with its members in order.
|
||||
fn compound(s: &mut Session, ids: &[NodeId]) -> (NodeId, Vec<NodeId>) {
|
||||
run(s, "select.set", json!({"ids": ids.iter().map(|id| id.0).collect::<Vec<_>>()}));
|
||||
let c = NodeId(run(s, "object.compoundPath.make", json!({}))["id"].as_u64().unwrap());
|
||||
let members = s.doc().unwrap().doc.node(c).unwrap().children().unwrap().iter().map(|m| m.id).collect();
|
||||
(c, members)
|
||||
}
|
||||
|
||||
/// Anchors 0 to 2 of a square: Cut leaves it no segment, so it is removed.
|
||||
fn three_anchors() -> Value {
|
||||
json!([[0, 0], [0, 1], [0, 2]])
|
||||
}
|
||||
|
||||
/// Anchors 0 and 1 of a square: Cut keeps its other three sides.
|
||||
fn two_anchors() -> Value {
|
||||
json!([[0, 0], [0, 1]])
|
||||
}
|
||||
|
||||
/// The compound path whose members are cut one whole and one emptied goes with them; the other
|
||||
/// compound path keeps its one member left, as a compound path.
|
||||
#[test]
|
||||
fn cut_removes_a_compound_whose_members_all_go_and_keeps_one_with_one_member_left() {
|
||||
let make = || {
|
||||
let mut s = new_doc();
|
||||
let first = [(); 2].map(|()| rect(&mut s));
|
||||
let (gone, gone_members) = compound(&mut s, &first);
|
||||
let second = [(); 3].map(|()| rect(&mut s));
|
||||
let (kept, kept_members) = compound(&mut s, &second);
|
||||
let other = rect(&mut s);
|
||||
select_direct(
|
||||
&mut s,
|
||||
&[gone_members[0], kept_members[0]],
|
||||
&[(gone_members[1], three_anchors()), (kept_members[1], three_anchors()), (other, two_anchors())],
|
||||
);
|
||||
(s, gone, kept, kept_members[2], other)
|
||||
};
|
||||
let s = same_as_one_at_a_time(|| make().0);
|
||||
let (_, gone, kept, left, other) = make();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(d.node(gone).is_none(), "the compound path whose members all went is removed");
|
||||
let kept = d.node(kept).expect("the compound path with a member left stays");
|
||||
assert!(matches!(kept.kind, NodeKind::Compound { .. }));
|
||||
assert_eq!(kept.children().unwrap().iter().map(|m| m.id).collect::<Vec<_>>(), [left]);
|
||||
assert_eq!(s.doc().unwrap().selection.objects, [other], "the cut square's other sides stay selected");
|
||||
}
|
||||
|
||||
/// Objects inside two groups and on the layer, removed whole, emptied or cut apart between kept
|
||||
/// siblings, keep the order and ids that removing them one at a time leaves.
|
||||
#[test]
|
||||
fn cut_inside_groups_keeps_the_order_and_ids_of_removing_one_at_a_time() {
|
||||
let make = || {
|
||||
let mut s = new_doc();
|
||||
let a = [(); 4].map(|()| rect(&mut s));
|
||||
run(&mut s, "select.set", json!({"ids": a.iter().map(|id| id.0).collect::<Vec<_>>()}));
|
||||
run(&mut s, "object.group", json!({}));
|
||||
let b = [(); 4].map(|()| rect(&mut s));
|
||||
run(&mut s, "select.set", json!({"ids": b.iter().map(|id| id.0).collect::<Vec<_>>()}));
|
||||
run(&mut s, "object.group", json!({}));
|
||||
let c = [(); 4].map(|()| rect(&mut s));
|
||||
select_direct(
|
||||
&mut s,
|
||||
&[a[0], a[2], b[3], c[1]],
|
||||
&[(a[1], two_anchors()), (b[0], three_anchors()), (b[2], two_anchors()), (c[3], three_anchors())],
|
||||
);
|
||||
s
|
||||
};
|
||||
let s = same_as_one_at_a_time(make);
|
||||
assert_eq!(s.doc().unwrap().selection.objects.len(), 2, "the two squares cut apart stay selected");
|
||||
}
|
||||
|
||||
/// Selected ruler guides go with the objects, in the Cut's undo step.
|
||||
#[test]
|
||||
fn cut_removes_the_selected_guides_with_the_objects() {
|
||||
let make = || {
|
||||
let mut s = new_doc();
|
||||
let [a, b, c] = [(); 3].map(|()| rect(&mut s));
|
||||
run(&mut s, "guide.add", json!({"vertical": true, "pos": 30}));
|
||||
run(&mut s, "guide.add", json!({"vertical": false, "pos": 40}));
|
||||
select_direct(&mut s, &[a, c], &[(b, two_anchors())]);
|
||||
run(&mut s, "guide.select", json!({"indexes": [1], "toggle": true}));
|
||||
s
|
||||
};
|
||||
let s = same_as_one_at_a_time(make);
|
||||
assert_eq!(s.doc().unwrap().doc.ruler_guides().len(), 1, "the selected guide is removed");
|
||||
assert_eq!(s.clipboard.guides.len(), 1, "the selected guide is on the clipboard");
|
||||
}
|
||||
|
||||
/// Roots that are not separate (one inside another) are removed one at a time, as before.
|
||||
#[test]
|
||||
fn cut_of_roots_inside_another_root_matches_removing_one_at_a_time() {
|
||||
let make = || {
|
||||
let mut s = new_doc();
|
||||
let a = [(); 3].map(|()| rect(&mut s));
|
||||
run(&mut s, "select.set", json!({"ids": a.iter().map(|id| id.0).collect::<Vec<_>>()}));
|
||||
let group = NodeId(run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap());
|
||||
let b = rect(&mut s);
|
||||
select_direct(&mut s, &[group, b], &[(a[1], two_anchors())]);
|
||||
(s, vec![a[1], group, b])
|
||||
};
|
||||
let (mut x, roots) = make();
|
||||
let (mut y, _) = make();
|
||||
copy(&mut x, &json!({})).unwrap();
|
||||
copy(&mut y, &json!({})).unwrap();
|
||||
cut_direct_selection(&mut x, &roots).unwrap();
|
||||
cut_one_at_a_time(&mut y, &roots).unwrap();
|
||||
assert_same(&x, &y, "Cut");
|
||||
}
|
||||
|
||||
/// One layer of 10,000 squares with every fifth of the first 10,000 selected whole (2,000) and
|
||||
/// anchors 0 and 1 of the square after them picked.
|
||||
fn many() -> Session {
|
||||
let mut s = session(10_001, square);
|
||||
let ids = crate::tests_large_edits::layer(&s, 0);
|
||||
let whole: Vec<NodeId> = ids.iter().take(10_000).step_by(5).copied().collect();
|
||||
select_direct(&mut s, &whole, &[(ids[10_000], two_anchors())]);
|
||||
s
|
||||
}
|
||||
|
||||
/// The tree walks [`tree_walks`] counts while `f` runs on `s`.
|
||||
fn walks(s: &mut Session, f: impl FnOnce(&mut Session)) -> u64 {
|
||||
let before = tree_walks();
|
||||
f(s);
|
||||
tree_walks() - before
|
||||
}
|
||||
|
||||
/// Cut of 2,000 objects selected whole among 10,000, with a direct selection, walks the document's
|
||||
/// tree a few times, where removing them one at a time walks it several times for each object.
|
||||
#[test]
|
||||
fn direct_selection_cut_of_2000_of_10000_objects_takes_few_tree_walks() {
|
||||
let s = same_as_one_at_a_time(many);
|
||||
assert_eq!(crate::tests_large_edits::layer(&s, 0).len(), 8_001);
|
||||
let (mut a, mut b) = (many(), many());
|
||||
let batched = walks(&mut a, |s| {
|
||||
run(s, "edit.cut", json!({}));
|
||||
});
|
||||
let one_at_a_time = walks(&mut b, reference_cut);
|
||||
println!("tree walks: Cut {batched}, one at a time {one_at_a_time}");
|
||||
assert!(batched <= 64, "Cut walked the document's tree {batched} times");
|
||||
assert!(one_at_a_time >= 4 * batched.max(1), "one at a time walked it {one_at_a_time} times, Cut {batched}");
|
||||
}
|
||||
|
||||
/// This thread's CPU time, where the system reports it (`/proc/thread-self/schedstat` on Linux).
|
||||
fn cpu_time() -> Option<Duration> {
|
||||
let stat = std::fs::read_to_string("/proc/thread-self/schedstat").ok()?;
|
||||
stat.split_whitespace().next()?.parse().ok().map(Duration::from_nanos)
|
||||
}
|
||||
|
||||
/// The middle of `v`.
|
||||
fn median(mut v: Vec<Duration>) -> Duration {
|
||||
v.sort_unstable();
|
||||
v[v.len() / 2]
|
||||
}
|
||||
|
||||
/// Times Cut of [`many`] and [`reference_cut`] seven times each, in turn, and prints every run's
|
||||
/// CPU and wall-clock time with the medians. Run it with
|
||||
/// `cargo test --release -p vectorcraft-engine --lib -- --ignored --nocapture direct_selection_cut_timing`.
|
||||
#[test]
|
||||
#[ignore = "timing; prints the numbers"]
|
||||
fn direct_selection_cut_timing() {
|
||||
let mut runs: [(Vec<Duration>, Vec<Duration>); 2] = Default::default();
|
||||
for round in 0..7 {
|
||||
for (k, (cpu, wall)) in runs.iter_mut().enumerate() {
|
||||
let mut s = many();
|
||||
let (c0, w0) = (cpu_time(), Instant::now());
|
||||
if k == 0 {
|
||||
reference_cut(&mut s);
|
||||
} else {
|
||||
run(&mut s, "edit.cut", json!({}));
|
||||
}
|
||||
let w = w0.elapsed();
|
||||
let c = c0.zip(cpu_time()).map(|(a, b)| b.saturating_sub(a)).unwrap_or(w);
|
||||
println!("round {round} {}: cpu {c:?}, wall {w:?}", ["one at a time", "Cut"][k]);
|
||||
cpu.push(c);
|
||||
wall.push(w);
|
||||
}
|
||||
}
|
||||
for (k, (cpu, wall)) in runs.into_iter().enumerate() {
|
||||
println!("median {}: cpu {:?}, wall {:?}", ["one at a time", "Cut"][k], median(cpu), median(wall));
|
||||
}
|
||||
}
|
||||
@@ -28,7 +28,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
"Map Graphic",
|
||||
[],
|
||||
None,
|
||||
"{symbol: name of a document symbol, face?: front|back (front; Plane has only a front; the back reads left to right as seen from behind; on Revolve the front is its swept side, which is the only face), x?: pt, y?: pt (0, 0: the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on Revolve from the middle of the side unrolled flat, x around the axis and y along the profile), scale?: % (1..10000; default 100, or less so the graphic fits inside the object, on Revolve inside the half of the side seen from the front), rotation?: degrees (-360..360, 0; counterclockwise), index?: int (the 3D effect's position; default: each object's first 3D effect, its own before its fills' and strokes'), item?: appearance item index|null (refused without index; as effect.setParams), ids?|id?} add a graphic to the 3D effect of each selected object, drawn on that face turned, foreshortened and shaded with it and clipped to it (on Revolve wrapped around the side, and drawn only where its outside faces the viewer); every object's 3D effect must be Extrude & Bevel (on a solid cap), Rotate (the Plane type) or Revolve; one undo step → {ids, graphic}",
|
||||
"{symbol: name of a document symbol, face?: front|back|side (front; Plane has only a front; the back reads left to right as seen from behind; side is Extrude & Bevel's walls and bevels; on Revolve the front is its swept side, which is the only face), x?: pt, y?: pt (0, 0: the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on a side from the middle of the side unrolled flat: on Extrude & Bevel x along the outline, clockwise from its top, and y from the front toward the back; on Revolve x around the axis and y along the profile), scale?: % (1..10000; default 100, or less so the graphic fits inside the object, on Extrude & Bevel's side inside the side unrolled about x = 0, short of its cut, on Revolve inside the half of the side seen from the front), rotation?: degrees (-360..360, 0; counterclockwise), index?: int (the 3D effect's position; default: each object's first 3D effect, its own before its fills' and strokes'), item?: appearance item index|null (refused without index; as effect.setParams), ids?|id?} add a graphic to the 3D effect of each selected object, drawn on that face turned, foreshortened and shaded with it and clipped to it (on a side wrapped around it, and drawn only where its outside faces the viewer); every object's 3D effect must be Extrude & Bevel (on a solid cap, or on the side, hollow or not), Rotate (the Plane type) or Revolve; one undo step → {ids, graphic}",
|
||||
has_doc,
|
||||
map_graphic
|
||||
),
|
||||
@@ -113,22 +113,32 @@ fn map_graphic(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if !effects::takes_graphics(&effect.id) {
|
||||
return Err(bad(C, format!("object {}: {}", id.0, effects::GRAPHICS_NOT_TAKEN)));
|
||||
}
|
||||
// A hollow Extrude & Bevel keeps the graphics it has, to show when Cap is turned on again,
|
||||
// but has no cap to show a new one on.
|
||||
// A hollow Extrude & Bevel keeps the graphics it has on its caps, to show when Cap is turned
|
||||
// on again, but has no cap to show a new one on. Its side takes graphics.
|
||||
let merged = effects::merged_params(&effect.id, &effect.params);
|
||||
let extrude = (effect.id == effects::EXTRUDE).then(|| effects::extrude_options(&merged));
|
||||
if extrude.is_some_and(|o| o.depth > 0.0 && !o.cap) {
|
||||
let side = base.face == effects::PlanarFace::Side;
|
||||
if !side && extrude.is_some_and(|o| o.depth > 0.0 && !o.cap) {
|
||||
return Err(bad(C, format!("object {}: a hollow Extrude & Bevel has no caps: turn on Cap to map a graphic", id.0)));
|
||||
}
|
||||
// With a depth of 0 the art is a plane, which has only a front.
|
||||
if base.face == effects::PlanarFace::Back && extrude.is_some_and(|o| o.depth <= 0.0) {
|
||||
if base.face != effects::PlanarFace::Front && extrude.is_some_and(|o| o.depth <= 0.0) {
|
||||
return Err(bad(C, format!("object {}: with a depth of 0 the object has one face: map its graphics onto the front", id.0)));
|
||||
}
|
||||
let mut graphic = base.clone();
|
||||
if p.get("scale").is_none()
|
||||
&& let (Some(frame), Some(art)) = (effects::graphic_frame_at(Some(d), n, item, index), effects::graphic_bounds(d, &graphic.symbol))
|
||||
&& let Some(art) = effects::graphic_bounds(d, &graphic.symbol)
|
||||
{
|
||||
graphic.scale = frame.fitting_scale(art);
|
||||
// A graphic on the side starts fitting inside the side unrolled about x = 0, short of
|
||||
// its cut; one on a cap inside the object's bounds.
|
||||
let fit = if side {
|
||||
effects::graphic_side_size(Some(d), n, item, index).map(|(w, h)| effects::graphic_fitting_scale(w, h, art))
|
||||
} else {
|
||||
effects::graphic_frame_at(Some(d), n, item, index).map(|frame| frame.fitting_scale(art))
|
||||
};
|
||||
if let Some(fit) = fit {
|
||||
graphic.scale = fit;
|
||||
}
|
||||
}
|
||||
let params = effects::with_graphic(&effects::merged_params(&effect.id, &effect.params), &graphic);
|
||||
effects::validate_three_d_at_in(Some(d), n, &effect.id, ¶ms, (item, index)).map_err(|e| bad(C, e))?;
|
||||
|
||||
@@ -135,6 +135,47 @@ fn map_graphic_refuses_what_cannot_take_it_and_changes_nothing() {
|
||||
assert!(s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "ids": [id.0]})).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn map_graphic_puts_a_graphic_on_the_side_of_an_extrude() {
|
||||
let (mut s, id) = setup("threeD.extrude");
|
||||
// A hollow Extrude & Bevel takes a graphic on its side.
|
||||
s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": {"cap": false}})).unwrap();
|
||||
s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "side", "y": 4.0, "ids": [id.0]})).unwrap();
|
||||
assert_eq!(graphics(&s, id), json!([{"symbol": "Mark", "face": "side", "x": 0.0, "y": 4.0, "scale": 100.0, "rotation": 0.0}]));
|
||||
// A plane, and a depth of 0, have no side.
|
||||
let (mut s, plane) = setup("threeD.rotate");
|
||||
let history = undo_len(&s);
|
||||
let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "side", "ids": [plane.0]})).unwrap_err().to_string();
|
||||
assert!(e.contains("one face"), "{e}");
|
||||
assert_eq!(undo_len(&s), history);
|
||||
let (mut s, flat) = setup("threeD.extrude");
|
||||
s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": {"depth": 0.0}})).unwrap();
|
||||
let history = undo_len(&s);
|
||||
let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "side", "ids": [flat.0]})).unwrap_err().to_string();
|
||||
assert!(e.contains("one face"), "{e}");
|
||||
assert_eq!(undo_len(&s), history);
|
||||
// A graphic taller than the side starts scaled to fit it: the side of the 100 × 100 square is
|
||||
// about 300 pt wide short of its cut and 10 pt deep here, and the graphic with its stroke is
|
||||
// 11 × 21.
|
||||
let (mut s, id) = setup("threeD.extrude");
|
||||
s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": {"depth": 10.0}})).unwrap();
|
||||
s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "side", "ids": [id.0]})).unwrap();
|
||||
let scale = graphics(&s, id)[0]["scale"].as_f64().unwrap();
|
||||
assert!((scale - 1000.0 / 21.0).abs() < 1e-9, "{scale}");
|
||||
// A graphic wider than the side is kept short of the cut, at a bottom corner of the square: the
|
||||
// part about x = 0 is three quarters of the outline.
|
||||
let (mut s, id) = setup("threeD.extrude");
|
||||
let wide = s.execute("path.create", &json!({"d":"M0 380L400 380L400 390L0 390Z"})).unwrap()["id"].clone();
|
||||
s.execute("threeD.addGraphic", &json!({"name": "Wide", "ids": [wide]})).unwrap();
|
||||
s.execute("threeD.mapGraphic", &json!({"symbol": "Wide", "face": "side", "ids": [id.0]})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let (span, _) = vectorcraft_render::effects::graphic_side_size(Some(d), d.node(id).unwrap(), None, 0).unwrap();
|
||||
let art = vectorcraft_render::effects::graphic_bounds(d, "Wide").unwrap();
|
||||
assert!((span - 300.0).abs() < 1e-6 || (span - 303.0).abs() < 1e-6, "{span}");
|
||||
let scale = graphics(&s, id)[0]["scale"].as_f64().unwrap();
|
||||
assert!((scale - 100.0 * span / art.width()).abs() < 1e-9, "{scale}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_params_edits_graphics_and_checks_them() {
|
||||
let (mut s, id) = setup("threeD.extrude");
|
||||
|
||||
@@ -1150,21 +1150,27 @@ fn random_brushes_baked<'a>(
|
||||
std::borrow::Cow::Owned(def)
|
||||
}
|
||||
|
||||
/// Does brush `name` of `brushes` draw different art for different points: a calligraphic or
|
||||
/// scatter brush with Random variation, or a bristle brush?
|
||||
fn draws_random_art(brushes: &[vectorcraft_brush::Brush], name: &str) -> bool {
|
||||
/// Does brush `name` of `brushes`, with the stroke's own brush settings `options`, draw different
|
||||
/// art for different points: a calligraphic or scatter brush with Random variation, or a bristle
|
||||
/// brush?
|
||||
fn draws_random_art(brushes: &[vectorcraft_brush::Brush], name: &str, options: &serde_json::Map<String, Value>) -> bool {
|
||||
use vectorcraft_brush::{BrushKind, Variation};
|
||||
brushes.iter().find(|b| b.name == name).is_some_and(|b| match &b.kind {
|
||||
let Some(brush) = brushes.iter().find(|b| b.name == name) else { return false };
|
||||
let edited = if options.is_empty() { None } else { brush.with_stroke_options(options).ok() };
|
||||
let b = edited.as_ref().unwrap_or(brush);
|
||||
match &b.kind {
|
||||
BrushKind::Calligraphic(c) => c.modes().contains(&Variation::Random),
|
||||
BrushKind::Scatter(s) => s.modes().contains(&Variation::Random),
|
||||
BrushKind::Bristle(_) => true,
|
||||
BrushKind::Art(_) | BrushKind::Pattern(_) => false,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Is `n` a path with a visible stroke whose brush varies at random ([`draws_random_art`])?
|
||||
fn random_brushed(brushes: &[vectorcraft_brush::Brush], n: &Node) -> bool {
|
||||
let random = |st: &vectorcraft_doc::appearance::StrokeLayer| st.visible && st.brush.as_deref().is_some_and(|b| draws_random_art(brushes, b));
|
||||
let random = |st: &vectorcraft_doc::appearance::StrokeLayer| {
|
||||
st.visible && st.brush.as_deref().is_some_and(|b| draws_random_art(brushes, b, &st.brush_options))
|
||||
};
|
||||
matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })
|
||||
&& n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(st) if random(st)))
|
||||
}
|
||||
|
||||
@@ -65,6 +65,7 @@ pub mod zip;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
pub(crate) use action_batch::action_step;
|
||||
pub use action_batch::batch_overwrites_one_file;
|
||||
pub use dxf::{UNSUPPORTED, Unsupported, unsupported};
|
||||
pub use encode::{
|
||||
@@ -95,7 +96,7 @@ pub use naming::{NameParts as FileNameParts, parse_date as parse_file_date, rend
|
||||
pub(crate) use native::preview_png;
|
||||
pub use native::with_compression_pref;
|
||||
pub(crate) use pdfimport::opened_page_document;
|
||||
pub use pdfimport::{LoadOptions, page_document};
|
||||
pub use pdfimport::{LoadOptions, page_document, pages_can_link};
|
||||
pub(crate) use psdlayers::import_active as psd_layers;
|
||||
pub use psdlayers::{PsdInfo, info as psd_info};
|
||||
pub(crate) use psdslices::over as psd_slices;
|
||||
@@ -133,7 +134,7 @@ mod formats;
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) use access::list_dir;
|
||||
pub(crate) use access::{check_images_in, check_scripts_of};
|
||||
pub(crate) use access::{check_images_in, check_scripts_of, with_readable_settings_folder};
|
||||
pub use access::{check_linked_images, check_linked_scripts, write_file_with, write_save_file, write_save_file_with};
|
||||
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
|
||||
@@ -171,13 +171,14 @@ pub(crate) fn names_linked_scripts(cmd: &str, format: &str, p: &Value, artboards
|
||||
}
|
||||
}
|
||||
|
||||
/// The error for an SVG that would name a linked image's file outside the read roots.
|
||||
/// The error for a file that would name a linked image's file outside the read roots.
|
||||
pub(crate) const IMAGE_OUTSIDE: &str = "a linked image file is outside the read roots";
|
||||
|
||||
/// `cmd` may write `d`, the document an output of `st` writes (all of it, or the objects it
|
||||
/// exports), in format `format` (a format id) with options `p`: any format but SVG and SVGZ, and
|
||||
/// those too unless read roots are in force and the file would name a linked image's file outside
|
||||
/// them (a relative path taken from `st`'s folder; a URL is not checked). An `<image>` names the
|
||||
/// exports), in format `format` (a format id) with options `p`: always, unless read roots are in
|
||||
/// force and the file would name a linked image's file outside them (a relative path taken from
|
||||
/// `st`'s folder; a URL is not checked). In any format but SVG and SVGZ, the file names them when it
|
||||
/// carries the native document ([`check_native_images`]). An `<image>` names the
|
||||
/// file with SVG Options › Images set to Link, and with Embed when the document holds no pixels for
|
||||
/// the image, for the images of the art each file draws (with chosen artboards, the art over each
|
||||
/// one; hidden layers and objects only with `hiddenLayers`, template layers and the opacity-mask
|
||||
@@ -193,9 +194,12 @@ pub fn check_linked_images(cmd: &str, format: &str, st: &crate::DocState, d: &ve
|
||||
/// [`check_linked_images`] for `d`, a document whose links are looked for from `base` (the
|
||||
/// objects on the clipboard, looked for from the document they came from).
|
||||
pub(crate) fn check_images_in(cmd: &str, format: &str, d: &vectorcraft_doc::Document, base: crate::cmd::links::LinkBase, p: &Value) -> Result<()> {
|
||||
if !matches!(format, "svg" | "svgz") || crate::file_access::current().is_none() {
|
||||
if crate::file_access::current().is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
if !matches!(format, "svg" | "svgz") {
|
||||
return check_native_images(cmd, format, d, base, p);
|
||||
}
|
||||
// Options that don't read as the encoder's choices count as Link, Preserve Editing, hidden
|
||||
// layers kept and SVG 1.1: the encoder refuses them anyway.
|
||||
let (link, preserve, hidden, tiny) = match super::svg::options_map(p) {
|
||||
@@ -222,6 +226,38 @@ pub(crate) fn check_images_in(cmd: &str, format: &str, d: &vectorcraft_doc::Docu
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `cmd` may write `d` in format `format` (a format id other than SVG and SVGZ) with options `p`:
|
||||
/// always, unless read roots are in force, the file carries the native document (a native file or
|
||||
/// template, an EPS file, a `.ai` or `.ait` file or a PDF with Preserve Editing, as
|
||||
/// [`names_linked_scripts`] counts them with `d`'s artboards) and that document names a file
|
||||
/// outside them ([`crate::cmd::links::names_hidden_file`]: a linked image or placed file, the
|
||||
/// relative path kept of one taken from `base`, a data set's image, or stored brushes that can't be
|
||||
/// read). The error names no file or folder.
|
||||
pub(crate) fn check_native_images(
|
||||
cmd: &str,
|
||||
format: &str,
|
||||
d: &vectorcraft_doc::Document,
|
||||
base: crate::cmd::links::LinkBase,
|
||||
p: &Value,
|
||||
) -> Result<()> {
|
||||
let carried =
|
||||
crate::file_access::current().is_some() && !matches!(format, "svg" | "svgz") && names_linked_scripts(cmd, format, p, d.artboards.len());
|
||||
if carried && crate::cmd::links::names_hidden_file(d, base) { Err(bad(cmd, IMAGE_OUTSIDE)) } else { Ok(()) }
|
||||
}
|
||||
|
||||
/// `doc` as a file written for the request being served carries it: without an Export for Screens
|
||||
/// `folder` outside the read roots ([`super::screens::leave_out_unreadable_settings_folder`]). The
|
||||
/// open document keeps it.
|
||||
pub(crate) fn with_readable_settings_folder(doc: &vectorcraft_doc::Document) -> std::borrow::Cow<'_, vectorcraft_doc::Document> {
|
||||
let settings = super::screens::leave_out_unreadable_settings_folder(doc.export_settings.clone());
|
||||
if settings.len() == doc.export_settings.len() {
|
||||
return std::borrow::Cow::Borrowed(doc);
|
||||
}
|
||||
let mut kept = doc.clone();
|
||||
kept.export_settings = settings;
|
||||
std::borrow::Cow::Owned(kept)
|
||||
}
|
||||
|
||||
/// `path` checked for writing against the automation roots in force.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn may_write(path: &str) -> Result<()> {
|
||||
|
||||
@@ -54,24 +54,19 @@ pub(super) fn action_batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
for (i, c) in cmds.iter().enumerate() {
|
||||
let id = c.get("command").and_then(Value::as_str).unwrap_or("");
|
||||
let refuse = |reason: &str| bad(C, action_step(i, id, reason));
|
||||
if id.is_empty() {
|
||||
return Err(bad(C, format!("commands[{i}]: missing `command`")));
|
||||
return Err(refuse("missing `command`"));
|
||||
}
|
||||
if id == "command.batch" || id == "action.batch" {
|
||||
return Err(bad(C, "batches cannot nest"));
|
||||
return Err(refuse("batches cannot nest"));
|
||||
}
|
||||
// `command.batch` refuses the batch when it reaches this step, which would fail every file or data set it plays.
|
||||
if id == "prefs.import" {
|
||||
return Err(bad(C, format!("commands[{i}]: `prefs.import` runs on its own, not as a batch step")));
|
||||
return Err(refuse("`prefs.import` runs on its own, not as a batch step"));
|
||||
}
|
||||
if find_command(id).is_none() {
|
||||
return Err(bad(
|
||||
C,
|
||||
match super::super::params::nearest_command(id) {
|
||||
Some(near) => format!("commands[{i}]: unknown command `{id}`; did you mean `{near}`?"),
|
||||
None => format!("commands[{i}]: unknown command `{id}`"),
|
||||
},
|
||||
));
|
||||
return Err(refuse(&super::super::params::unknown_command(id).to_string()));
|
||||
}
|
||||
}
|
||||
// Every option is checked before the destination folder is made.
|
||||
@@ -160,7 +155,7 @@ pub fn batch_overwrites_one_file(s: &Session, p: &Value) -> bool {
|
||||
Some(f) => own_format.is_some_and(|own| super::format(f).is_some_and(|f| f.id == own)),
|
||||
};
|
||||
match c.get("command").and_then(Value::as_str).unwrap_or("") {
|
||||
"document.save" | "file.save" => !save && (path || own_file()),
|
||||
"document.save" => !save && (path || own_file()),
|
||||
"file.saveAs" => !save && path,
|
||||
"file.saveCopy" | "file.saveAsTemplate" => path,
|
||||
"document.export" | "document.exportSelection" => !export && path,
|
||||
@@ -184,7 +179,7 @@ fn saves_move_to_each_file(steps: &[Value], redirected: bool) -> bool {
|
||||
/// in the destination folder when `redirected`) and makes that file the document's own: a save in
|
||||
/// the native template format writes a copy and leaves the document's file as it was.
|
||||
fn retargeting_save(c: &Value, redirected: bool) -> bool {
|
||||
if !matches!(c.get("command").and_then(Value::as_str), Some("document.save" | "file.save" | "file.saveAs")) {
|
||||
if !matches!(c.get("command").and_then(Value::as_str), Some("document.save" | "file.saveAs")) {
|
||||
return false;
|
||||
}
|
||||
let params = c.get("params");
|
||||
@@ -219,7 +214,7 @@ fn batch_folder(s: &mut Session, cmd: &str, p: &Value, override_open: bool, run:
|
||||
// open, so its artboard files count ([`dataset_output_paths`]). No output takes the name of a
|
||||
// source file in the destination folder, other than that file's own output, or of a subfolder
|
||||
// of the destination folder that holds source files.
|
||||
let (steps, places) = filter_steps(run.steps, override_open, false);
|
||||
let (steps, places) = filter_steps(run.steps, override_open);
|
||||
let run = Run { steps: &steps, ..*run };
|
||||
let in_dest: Vec<Option<(String, bool)>> = files.iter().map(|path| name_in_folder(path, run.dest_folder)).collect();
|
||||
let mut picker =
|
||||
@@ -272,7 +267,7 @@ fn batch_datasets(s: &mut Session, cmd: &str, run: &Run<'_>) -> Result<Value> {
|
||||
}
|
||||
let doc_stem = st.path.as_deref().and_then(|p| std::path::Path::new(p).file_stem().and_then(|s| s.to_str())).unwrap_or("Untitled").to_string();
|
||||
let stems = dataset_stems(&names, &doc_stem, run.dataset_file_naming, run, &st.doc)?;
|
||||
let (steps, places) = filter_steps(run.steps, true, false);
|
||||
let (steps, places) = filter_steps(run.steps, true);
|
||||
let run = Run { steps: &steps, ..*run };
|
||||
let mut processed = Vec::new();
|
||||
let mut failed = 0usize;
|
||||
@@ -353,22 +348,13 @@ impl StemPicker {
|
||||
}
|
||||
}
|
||||
|
||||
/// Drop Open (and optionally Close) steps when the batch supplies the file itself → the steps that
|
||||
/// stay, and the index of each in `cmds`.
|
||||
/// Drop the `document.open` steps when `drop_open` (the batch opens each source file itself) → the
|
||||
/// steps that stay, and the index of each in `cmds`.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn filter_steps(cmds: &[Value], drop_open: bool, drop_close: bool) -> (Vec<Value>, Vec<usize>) {
|
||||
fn filter_steps(cmds: &[Value], drop_open: bool) -> (Vec<Value>, Vec<usize>) {
|
||||
cmds.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, c)| {
|
||||
let id = c.get("command").and_then(Value::as_str).unwrap_or("");
|
||||
if drop_open && matches!(id, "document.open" | "file.open") {
|
||||
return false;
|
||||
}
|
||||
if drop_close && matches!(id, "file.close" | "document.close") {
|
||||
return false;
|
||||
}
|
||||
true
|
||||
})
|
||||
.filter(|(_, c)| !(drop_open && c.get("command").and_then(Value::as_str) == Some("document.open")))
|
||||
.map(|(i, c)| (c.clone(), i))
|
||||
.unzip()
|
||||
}
|
||||
@@ -385,12 +371,24 @@ fn play_steps(s: &mut Session, run: &Run<'_>, places: &[usize], commands: Vec<Va
|
||||
let Some((n, id, reason)) = batch_step_failure(&text) else { return e };
|
||||
let same = run.steps.get(n).and_then(|c| c.get("command")).and_then(Value::as_str) == Some(id);
|
||||
match places.get(n) {
|
||||
Some(place) if same => EngineError::Other(format!("action step {} (`{id}`) failed: {reason}", place + 1)),
|
||||
Some(&place) if same => EngineError::Other(action_step(place, id, reason)),
|
||||
_ => e,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// The text naming the member at `index` of an `action.batch`'s `commands`, counted from 1, with
|
||||
/// its command id when it has one, and `reason`: ``action step 2 (`object.move`) failed: …``. The
|
||||
/// checks before a batch runs and the errors of its steps as they run give the same text.
|
||||
pub(crate) fn action_step(index: usize, id: &str, reason: &str) -> String {
|
||||
let n = index.saturating_add(1);
|
||||
if id.is_empty() {
|
||||
format!("action step {n} failed: {reason}")
|
||||
} else {
|
||||
format!("action step {n} (`{}`) failed: {reason}", vectorcraft_apischema::shown_key(id))
|
||||
}
|
||||
}
|
||||
|
||||
/// The step number, command id and reason in the error `command.batch` gives when one of its steps
|
||||
/// fails (``batch step 2 (`object.move`) failed: …``); none for any other error.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -540,7 +538,7 @@ fn dataset_output_extensions(run: &Run<'_>, doc: &vectorcraft_doc::Document, def
|
||||
outputs.push(DatasetOutput { ext: String::new(), artboards: false, joiner: "-", folder: true });
|
||||
continue;
|
||||
}
|
||||
let writes = (run.override_save && matches!(id, "document.save" | "file.save" | "file.saveAs"))
|
||||
let writes = (run.override_save && matches!(id, "document.save" | "file.saveAs"))
|
||||
|| (run.override_export && matches!(id, "document.export" | "document.exportSelection"));
|
||||
if writes {
|
||||
let format = step.get("params").and_then(|p| p.get("format")).and_then(Value::as_str).filter(|f| !f.is_empty());
|
||||
@@ -551,7 +549,7 @@ fn dataset_output_extensions(run: &Run<'_>, doc: &vectorcraft_doc::Document, def
|
||||
};
|
||||
if safe_extension(&ext) {
|
||||
let format_id = super::format(format.unwrap_or(default_ext)).map(|f| f.id).unwrap_or("vectorcraft");
|
||||
let is_save = matches!(id, "document.save" | "file.save" | "file.saveAs");
|
||||
let is_save = matches!(id, "document.save" | "file.saveAs");
|
||||
let artboards = if is_save {
|
||||
!doc.artboards.is_empty() && matches!(format_id, "vectorcraft" | "template" | "ai" | "ait")
|
||||
} else {
|
||||
@@ -693,7 +691,7 @@ fn rewrite_paths(
|
||||
.map(|c| {
|
||||
let id = c.get("command").and_then(Value::as_str).unwrap_or("");
|
||||
let mut c = c.clone();
|
||||
let rewrite = (override_save && matches!(id, "document.save" | "file.save" | "file.saveAs"))
|
||||
let rewrite = (override_save && matches!(id, "document.save" | "file.saveAs"))
|
||||
|| (override_export && matches!(id, "document.export" | "document.exportForScreens" | "document.exportSelection" | "assets.export"));
|
||||
if !rewrite {
|
||||
return c;
|
||||
@@ -2385,10 +2383,97 @@ mod tests {
|
||||
let mut s = Session::new();
|
||||
let p = json!({"folder": src.to_string_lossy(), "commands": [{"command": "object.unlockAll"}, {"command": "prefs.import", "params": {}}]});
|
||||
let e = s.execute("action.batch", &p).unwrap_err().to_string();
|
||||
assert!(e.contains("commands[1]: `prefs.import` runs on its own, not as a batch step"), "{e}");
|
||||
assert!(e.contains("action step 2 (`prefs.import`) failed: `prefs.import` runs on its own, not as a batch step"), "{e}");
|
||||
assert!(s.active().is_none(), "no file was opened");
|
||||
}
|
||||
|
||||
/// Each step the checks before the batch refuse is named by its place in `commands`, from 1,
|
||||
/// as a step that fails as it runs is, and no source file is opened.
|
||||
#[test]
|
||||
fn a_refused_step_is_named_by_its_place_from_1() {
|
||||
let src = tmp("step-number-refused-src");
|
||||
write_svg(&src, "a.svg", "#f00");
|
||||
let prefix = "invalid parameters for `action.batch`: ";
|
||||
let cases = [
|
||||
(json!({"params": {}}), "action step 2 failed: missing `command`"),
|
||||
(json!({"command": "select.al"}), "action step 2 (`select.al`) failed: unknown command `select.al`; did you mean `select.all`?"),
|
||||
(json!({"command": "command.batch", "params": {"commands": []}}), "action step 2 (`command.batch`) failed: batches cannot nest"),
|
||||
(json!({"command": "action.batch", "params": {}}), "action step 2 (`action.batch`) failed: batches cannot nest"),
|
||||
(
|
||||
json!({"command": "view.saved.new", "params": {"center": [0, 0], "zoom": 0}}),
|
||||
"action step 2 (`view.saved.new`) failed: invalid parameters for `view.saved.new`: `zoom` must be a number > 0, not 0",
|
||||
),
|
||||
];
|
||||
for (step, want) in cases {
|
||||
let mut s = Session::new();
|
||||
let p = json!({"folder": src.to_string_lossy(), "commands": [{"command": "object.unlockAll"}, step]});
|
||||
let e = s.execute("action.batch", &p).unwrap_err().to_string();
|
||||
assert_eq!(e, format!("{prefix}{want}"), "{step}");
|
||||
assert!(s.active().is_none(), "{step}: a file was opened");
|
||||
assert!(s.journal.is_empty(), "{step}: a step ran");
|
||||
}
|
||||
}
|
||||
|
||||
/// The parameter check of an `action.batch` names the step whose params it refuses, from 1;
|
||||
/// that of a `command.batch` passes the step's error on as it is.
|
||||
#[test]
|
||||
fn the_parameter_check_names_the_refused_step() {
|
||||
let bad_view = json!({"command": "view.saved.new", "params": {"center": [0, 0], "zoom": 0}});
|
||||
let commands = json!([{"command": "object.unlockAll"}, {"command": "select.all"}, bad_view]);
|
||||
let own = "invalid parameters for `view.saved.new`: `zoom` must be a number > 0, not 0";
|
||||
let e = crate::cmd::params::check_params("action.batch", &json!({"commands": commands})).unwrap_err().to_string();
|
||||
assert_eq!(e, format!("invalid parameters for `action.batch`: action step 3 (`view.saved.new`) failed: {own}"));
|
||||
let e = crate::cmd::params::check_params("command.batch", &json!({"commands": commands})).unwrap_err().to_string();
|
||||
assert_eq!(e, own);
|
||||
}
|
||||
|
||||
/// The ids of the File menu's Open… and Save in the app (`file.open`, `file.save`) and
|
||||
/// `document.close` are not engine commands, so a step with one is refused before the batch
|
||||
/// starts, with Override Open and Override Save on or off.
|
||||
#[test]
|
||||
fn steps_with_ids_that_are_not_engine_commands_are_refused() {
|
||||
let src = tmp("step-number-aliases-src");
|
||||
write_svg(&src, "a.svg", "#f00");
|
||||
for id in ["file.open", "file.save", "document.close"] {
|
||||
for overrides in [true, false] {
|
||||
let mut s = Session::new();
|
||||
let p = json!({
|
||||
"folder": src.to_string_lossy(),
|
||||
"overrideOpen": overrides,
|
||||
"overrideSave": overrides,
|
||||
"commands": [{"command": "object.unlockAll"}, {"command": id, "params": {}}],
|
||||
});
|
||||
let e = s.execute("action.batch", &p).unwrap_err().to_string();
|
||||
assert!(
|
||||
e.starts_with(&format!("invalid parameters for `action.batch`: action step 2 (`{id}`) failed: unknown command `{id}`")),
|
||||
"{e}"
|
||||
);
|
||||
assert!(s.active().is_none(), "{id}: a file was opened");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `command.batch` keeps its own numbering, from 0, for a step that fails.
|
||||
#[test]
|
||||
fn command_batch_keeps_its_own_step_numbers() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let e = s
|
||||
.execute("command.batch", &json!({"commands": [{"command": "object.unlockAll"}, {"command": "object.align", "params": {}}]}))
|
||||
.unwrap_err();
|
||||
assert!(e.to_string().starts_with("batch step 1 (`object.align`) failed: "), "{e}");
|
||||
}
|
||||
|
||||
/// A step's id in the error is cut short, as an unknown key's is.
|
||||
#[test]
|
||||
fn a_long_step_id_is_cut_short() {
|
||||
let id = "x".repeat(10_000);
|
||||
let shown = action_step(0, &id, "why");
|
||||
assert!(shown.len() < 1_000, "{}", shown.len());
|
||||
assert!(shown.starts_with("action step 1 (`xxx") && shown.ends_with("…`) failed: why"), "{shown}");
|
||||
assert_eq!(action_step(usize::MAX, "", "why"), format!("action step {} failed: why", usize::MAX));
|
||||
}
|
||||
|
||||
/// Only the error `command.batch` gives for a failed step is read as one.
|
||||
#[test]
|
||||
fn batch_step_failure_reads_only_a_step_error() {
|
||||
|
||||
@@ -117,7 +117,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Batch…",
|
||||
[],
|
||||
None,
|
||||
"{commands: [{command, params}] (the action's steps), source?: folder (default) | datasets, folder? (required for folder: the source folder), includeSubdirs?: false, destination?: none (default: leave each file open) | saveAndClose (save over the source and close; for source datasets, save the open document over its own file after each data set, and refuse a document that was never saved, was converted from an older version or was restored by Data Recovery, unless a recorded Save or Save As step writes a file first; a Save or Save As step that overrideSave points into destinationFolder makes each data set's file the document's own) | folder (save or export into destinationFolder and close), destinationFolder? (required when destination is folder; also the folder Override Save/Export write into), datasetFileNaming?: fileNumber | fileDataSetName (default) | dataSetName (used only for source datasets; ignored for folder), overrideOpen?: true (skip document.open / file.open steps: the batch opens each source file), overrideSave?: true (point document.save / file.save / file.saveAs at destinationFolder/{stem}.{ext}), overrideExport?: true (point document.export / document.exportSelection the same way, and give document.exportForScreens / assets.export the folder destinationFolder/{stem}, one for each source file or data set, in which the export names its files as it does outside Batch), stopOnError?: true, label?} play the commands on every readable file in folder (and its subfolders when includeSubdirs; {stem} is the file's name without its extension and without trailing periods and spaces, with `-2`, `-3`… added to a name an earlier file used or whose file or folder has the name of one an earlier file wrote or of another source file or a folder of source files in destinationFolder), or on every data set of the open document. Data set names use the document stem plus a three-digit ordinal, the document stem and an underscore plus the data set name, or the data set name alone. Invalid file name characters become `-` and trailing periods and spaces are dropped; a name already used in the batch or whose output file or folder already exists in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix before the format-derived extension. Caps: 500 files or data sets, 8 folder levels, 256 steps. Batches cannot nest, and a prefs.import step is refused (commands[i], from 0) before any file is opened. A switch (includeSubdirs, overrideOpen, overrideSave, overrideExport, stopOnError) that is not true or false, or a source, folder, destination, destinationFolder, datasetFileNaming or label that is not a string, is an error before any folder is made or file opened; null reads as left out. A step that fails is named in the error by its place in commands, from 1, counting the Open steps the batch skips (action step 3 (`object.align`) failed: …); the batch's own opening of a file, choosing of a data set and destination save, export or close give their errors without a step number. → {processed: [{path|dataset, result|error}…], count, failed, stopped, warning?} (warning: for source datasets, when Save and Close without such a step, or a Save, Save a Copy, Save as Template or export step (document.export, exportSelection, exportForScreens, exportPdf, exportEps, exportDxf, exportForWeb, exportForOffice) that writes a file and is not pointed into destinationFolder, saves every data set over the same file)",
|
||||
"{commands: [{command, params}] (the action's steps), source?: folder (default) | datasets, folder? (required for folder: the source folder), includeSubdirs?: false, destination?: none (default: leave each file open) | saveAndClose (save over the source and close; for source datasets, save the open document over its own file after each data set, and refuse a document that was never saved, was converted from an older version or was restored by Data Recovery, unless a recorded Save or Save As step writes a file first; a Save or Save As step that overrideSave points into destinationFolder makes each data set's file the document's own) | folder (save or export into destinationFolder and close), destinationFolder? (required when destination is folder; also the folder Override Save/Export write into), datasetFileNaming?: fileNumber | fileDataSetName (default) | dataSetName (used only for source datasets; ignored for folder), overrideOpen?: true (skip document.open steps: the batch opens each source file), overrideSave?: true (point document.save / file.saveAs at destinationFolder/{stem}.{ext}), overrideExport?: true (point document.export / document.exportSelection the same way, and give document.exportForScreens / assets.export the folder destinationFolder/{stem}, one for each source file or data set, in which the export names its files as it does outside Batch), stopOnError?: true, label?} play the commands on every readable file in folder (and its subfolders when includeSubdirs; {stem} is the file's name without its extension and without trailing periods and spaces, with `-2`, `-3`… added to a name an earlier file used or whose file or folder has the name of one an earlier file wrote or of another source file or a folder of source files in destinationFolder), or on every data set of the open document. Data set names use the document stem plus a three-digit ordinal, the document stem and an underscore plus the data set name, or the data set name alone. Invalid file name characters become `-` and trailing periods and spaces are dropped; a name already used in the batch or whose output file or folder already exists in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix before the format-derived extension. Caps: 500 files or data sets, 8 folder levels, 256 steps. A step without a command, with a command the engine doesn't have, with params its command refuses, or with command.batch, action.batch or prefs.import (batches cannot nest) is refused before any file is opened, named by its place in commands, from 1 (action step 2 (`select.al`) failed: unknown command `select.al`; did you mean `select.all`?). A switch (includeSubdirs, overrideOpen, overrideSave, overrideExport, stopOnError) that is not true or false, or a source, folder, destination, destinationFolder, datasetFileNaming or label that is not a string, is an error before any folder is made or file opened; null reads as left out. A step that fails as it runs is named the same way, counting the Open steps the batch skips (action step 3 (`object.align`) failed: …); the batch's own opening of a file, choosing of a data set and destination save, export or close give their errors without a step number. → {processed: [{path|dataset, result|error}…], count, failed, stopped, warning?} (warning: for source datasets, when Save and Close without such a step, or a Save, Save a Copy, Save as Template or export step (document.export, exportSelection, exportForScreens, exportPdf, exportEps, exportDxf, exportForWeb, exportForOffice) that writes a file and is not pointed into destinationFolder, saves every data set over the same file)",
|
||||
always,
|
||||
action_batch::action_batch
|
||||
),
|
||||
|
||||
@@ -226,9 +226,10 @@ pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option<bool>) ->
|
||||
vec![(Some(b), rect(b)?, false)]
|
||||
}
|
||||
};
|
||||
let regions: Vec<(Rect, bool)> = drawings.iter().map(|&(_, region, crop)| (region, crop)).collect();
|
||||
let outs = vectorcraft_cad::export_drawings(doc, &opts, ®ions).map_err(|e| bad(C, e))?;
|
||||
let mut enc = Encoded::default();
|
||||
for (board, region, crop) in drawings {
|
||||
let out = vectorcraft_cad::export(doc, &DxfOptions { region, crop, ..opts.clone() }).map_err(|e| bad(C, e))?;
|
||||
for ((board, _, _), out) in drawings.into_iter().zip(outs) {
|
||||
enc.files.push((board, out.bytes));
|
||||
for w in out.warnings {
|
||||
if !enc.warnings.contains(&w) {
|
||||
|
||||
@@ -280,8 +280,10 @@ fn thumbnail_of(preview: &Rendered, rect: Rect) -> Result<Raster> {
|
||||
}
|
||||
|
||||
/// What the file carries to reopen: `doc` (with only artboard `board` when the file is one of
|
||||
/// several artboards), with linked images whole when `include_linked`.
|
||||
/// several artboards), with linked images whole when `include_linked`, and without an Export for
|
||||
/// Screens folder outside the read roots ([`super::access::with_readable_settings_folder`]).
|
||||
fn native(doc: &Document, board: Option<usize>, include_linked: bool) -> Vec<u8> {
|
||||
let doc = &*super::access::with_readable_settings_folder(doc);
|
||||
let several = board.filter(|_| doc.artboards.len() > 1);
|
||||
if several.is_none() && !include_linked {
|
||||
return vectorcraft_format::save(doc, false);
|
||||
|
||||
@@ -838,13 +838,13 @@ fn other_open_filters() -> impl Iterator<Item = (&'static str, &'static [&'stati
|
||||
/// Open-dialog filters for Swatch Libraries and Graphic Style Libraries Other Library… and Locate
|
||||
/// Library…. The library formats come first so Linux file portals (which grey out files that don't
|
||||
/// match the default filter) still list `.ase` and the other library extensions; then the same
|
||||
/// filters as [`builtin_open_filters`], without a second copy of the library filter, so a document
|
||||
/// filters as [`builtin_open_filters`], without a second filter of that label, so a document
|
||||
/// can be picked for its swatches or graphic styles.
|
||||
pub fn library_open_filters(
|
||||
library_label: &'static str,
|
||||
library_exts: &'static [&'static str],
|
||||
) -> impl Iterator<Item = (&'static str, &'static [&'static str])> {
|
||||
std::iter::once((library_label, library_exts)).chain(builtin_open_filters().filter(move |f| *f != (library_label, library_exts)))
|
||||
std::iter::once((library_label, library_exts)).chain(builtin_open_filters().filter(move |f| f.0 != library_label))
|
||||
}
|
||||
|
||||
/// File → Place dialog filters: "All placeable files", then one per placeable format, then text,
|
||||
|
||||
@@ -231,6 +231,8 @@ pub(super) fn encode_to(cmd: &str, f: &Format, doc: &Document, p: &Value, w: imp
|
||||
}
|
||||
other => other,
|
||||
};
|
||||
// Without an Export for Screens folder outside the read roots.
|
||||
let native = super::access::with_readable_settings_folder(&native);
|
||||
so.pretty = so.pretty_fits(&native);
|
||||
vectorcraft_format::save_to(&native, &so, w).map_err(|e| bad(cmd, e.to_string()))
|
||||
}
|
||||
@@ -308,6 +310,8 @@ pub(super) fn ai_native(cmd: &str, doc: &Document, so: &SaveOptions) -> Result<V
|
||||
} else {
|
||||
Cow::Borrowed(doc)
|
||||
};
|
||||
// Without an Export for Screens folder outside the read roots.
|
||||
let native = super::access::with_readable_settings_folder(&native);
|
||||
vectorcraft_format::save_with(&native, so).map_err(|e| bad(cmd, e.to_string()))
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -222,6 +222,13 @@ 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() }
|
||||
}
|
||||
|
||||
/// Whether `document.open`'s `linkPages` takes the file `name` holding `bytes`: a PDF or a
|
||||
/// PDF-compatible `.ai` or `.ait` of at most [`document::MAX_FILE`] bytes. Its path, a password
|
||||
/// and `textAs` are checked apart ([`linked_pages`]).
|
||||
pub fn pages_can_link(name: &str, bytes: &[u8]) -> bool {
|
||||
bytes.len() <= document::MAX_FILE && document::is_pdf(name, bytes)
|
||||
}
|
||||
|
||||
/// `document.open` with `linkPages`: the pages `o` picks of the PDF (or PDF-compatible `.ai` or
|
||||
/// `.ait`) `name`, read from `path`, as a document holding one placed document per page, linked to
|
||||
/// that page of the file as File › Place with Link places one ([`document::source`]). Each page
|
||||
|
||||
@@ -896,7 +896,10 @@ fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option<i
|
||||
params.entry("hiddenLayers").or_insert(Value::Bool(true));
|
||||
}
|
||||
let params = Value::Object(params);
|
||||
super::check_linked_images(cmd, plan.format.id, st, &own, ¶ms)?;
|
||||
// Other formats are checked below, with the options the encoder reads.
|
||||
if is_svg(plan.format) {
|
||||
super::check_linked_images(cmd, plan.format.id, st, &own, ¶ms)?;
|
||||
}
|
||||
// The file the document is saved as (else its own) titles it if New's name is all it has.
|
||||
let file = plan.path.as_deref().filter(|_| plan.retargets()).or(st.path.as_deref());
|
||||
if let Some(d) = super::titled_for_export(&own, file, plan.format.id) {
|
||||
@@ -941,6 +944,7 @@ fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option<i
|
||||
_ => std::borrow::Cow::Borrowed(¶ms),
|
||||
};
|
||||
super::check_linked_scripts(cmd, plan.format.id, st, &checked)?;
|
||||
super::access::check_native_images(cmd, plan.format.id, &st.doc, crate::cmd::links::LinkBase::of(st), &checked)?;
|
||||
Ok(SaveJob { plan, doc, params, snapshot, source: st.doc.clone(), stamped, boards })
|
||||
}
|
||||
|
||||
|
||||
@@ -1129,6 +1129,28 @@ fn names_scripts(item: &Item, r: &Row, single: Option<&[usize]>) -> bool {
|
||||
super::access::names_linked_scripts(C, "pdf", &options, doc.artboards.len())
|
||||
}
|
||||
|
||||
/// The document the file of `item` that row `r` writes carries when it carries one
|
||||
/// ([`names_scripts`]): Full Document's PDF of every artboard, the item's artboard alone for a
|
||||
/// native, `.ai` or EPS row ([`board_document`]), else the item's document.
|
||||
fn carried_document<'a>(item: &'a Item, r: &Row, single: Option<&[usize]>) -> std::borrow::Cow<'a, Document> {
|
||||
match (&item.every_artboard, r.format.id, single) {
|
||||
(Some(all), "pdf", None) => std::borrow::Cow::Borrowed(&**all),
|
||||
_ if r.whole_document() && item.artboard.is_some() => std::borrow::Cow::Owned(board_document(item)),
|
||||
_ => std::borrow::Cow::Borrowed(&*item.doc),
|
||||
}
|
||||
}
|
||||
|
||||
/// The document a native, `.ai` or EPS row writes for `item`'s artboard: that artboard alone, with
|
||||
/// its background color and the art on it, as Save's separateArtboards writes it (#3868).
|
||||
fn board_document(item: &Item) -> Document {
|
||||
let mut d = single_artboard(&item.doc, item.region, &item.name);
|
||||
if let (Some(a), Some(from)) = (d.artboards.first_mut(), item.doc.artboards.get(item.artboard.unwrap_or(0))) {
|
||||
a.color = from.color;
|
||||
}
|
||||
super::save::keep_art_on(&mut d, item.region);
|
||||
d
|
||||
}
|
||||
|
||||
/// Every chosen artboard (asset, layer, selected object) in every format row, one file each (a PDF
|
||||
/// holds its artboard alone), or with `fullDocument` one file per row (a PDF of every artboard,
|
||||
/// else the bounds of all art). Items that share a name get `-2`, `-3`… instead of overwriting, and
|
||||
@@ -1177,6 +1199,23 @@ pub(crate) fn export(s: &mut Session, p: &Value, asked: &Value) -> Result<Value>
|
||||
super::check_images_in(C, r.format.id, &item.doc, base, &r.options_for(item.region, item.artboard)?)?;
|
||||
}
|
||||
}
|
||||
// The native document the files of the other rows carry, each document looked through once.
|
||||
if crate::file_access::current().is_some() {
|
||||
let mut looked: HashSet<(usize, bool, Option<usize>)> = HashSet::new();
|
||||
for r in rows.iter().filter(|r| !matches!(r.format.id, "svg" | "svgz")) {
|
||||
// A single-file PDF carries the first item's document alone, as the writer writes it.
|
||||
let carried = items.iter().enumerate().filter(|(index, _)| !(single.is_some() && r.format.id == "pdf" && *index > 0));
|
||||
for (_, item) in carried.filter(|(_, i)| names_scripts(i, r, single.as_deref())) {
|
||||
let all = item.every_artboard.is_some() && r.format.id == "pdf" && single.is_none();
|
||||
let board = item.artboard.filter(|_| !all && r.whole_document());
|
||||
if looked.insert((Arc::as_ptr(&item.doc) as usize, all, board))
|
||||
&& crate::cmd::links::names_hidden_file(&carried_document(item, r, single.as_deref()), base)
|
||||
{
|
||||
return Err(bad(C, super::access::IMAGE_OUTSIDE));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Appearance of Black › Printing / Exporting for RGB raster rows.
|
||||
// Include Artboard Fill off: the encoders leave the background colors out.
|
||||
let fill = if o.include_artboard_fill == Some(false) { json!({ "includeArtboardFill": false }) } else { json!({}) };
|
||||
@@ -1318,8 +1357,9 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) ->
|
||||
}
|
||||
Ok(bytes)
|
||||
};
|
||||
// A whole-document copy of an artboard, for the formats that write documents to edit.
|
||||
let mut board_docs: std::collections::HashMap<usize, Arc<Document>> = std::collections::HashMap::new();
|
||||
// A whole-document copy of an artboard of an item's document, for the formats that write
|
||||
// documents to edit.
|
||||
let mut board_docs: std::collections::HashMap<(usize, usize), Arc<Document>> = std::collections::HashMap::new();
|
||||
let mut files = 0u64;
|
||||
// One step per item and row, the files a name collision skips included.
|
||||
let steps = (items.len() * rows.len()) as u64;
|
||||
@@ -1358,19 +1398,7 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) ->
|
||||
write(pdf_doc.unwrap_or(all), "pdf", &options)?
|
||||
} else if r.whole_document() && item.artboard.is_some() {
|
||||
let b = item.artboard.unwrap_or(0);
|
||||
// That artboard alone, as Save's separateArtboards writes it: its art, not the others' (#3868).
|
||||
let d = board_docs
|
||||
.entry(b)
|
||||
.or_insert_with(|| {
|
||||
let mut d = single_artboard(&item.doc, item.region, &item.name);
|
||||
// It keeps its background color.
|
||||
if let (Some(a), Some(from)) = (d.artboards.first_mut(), item.doc.artboards.get(b)) {
|
||||
a.color = from.color;
|
||||
}
|
||||
super::save::keep_art_on(&mut d, item.region);
|
||||
Arc::new(d)
|
||||
})
|
||||
.clone();
|
||||
let d = board_docs.entry((Arc::as_ptr(&item.doc) as usize, b)).or_insert_with(|| Arc::new(board_document(item))).clone();
|
||||
let mut options = r.options_for(item.region, None)?;
|
||||
// An EPS page is the artboard, not its art's bounds: an artboard without art still writes.
|
||||
if r.format.id == "eps" {
|
||||
|
||||
@@ -183,13 +183,7 @@ pub(super) fn lost_artboards_warning(doc: &Document, p: &Value, label: &str) ->
|
||||
/// The native document Preserve Editing embeds: `doc`, without an Export for Screens `folder`
|
||||
/// outside the read roots of the request being served (the open document keeps it).
|
||||
fn native_attachment(doc: &Document) -> Vec<u8> {
|
||||
let settings = super::screens::leave_out_unreadable_settings_folder(doc.export_settings.clone());
|
||||
if settings.len() == doc.export_settings.len() {
|
||||
return vectorcraft_format::save(doc, false);
|
||||
}
|
||||
let mut kept = doc.clone();
|
||||
kept.export_settings = settings;
|
||||
vectorcraft_format::save(&kept, false)
|
||||
vectorcraft_format::save(&super::access::with_readable_settings_folder(doc), false)
|
||||
}
|
||||
|
||||
/// Encode `doc` as SVG (or gzipped, SVGZ): one file per chosen artboard, with the images they
|
||||
|
||||
@@ -492,6 +492,19 @@ fn library_open_filters_list_library_formats_first() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Other Library…'s Swatch Libraries filter lists the `.ai` and `.eps` documents whose swatches load
|
||||
/// as a library, and it is the only filter of that label.
|
||||
#[test]
|
||||
fn the_swatch_library_filter_lists_ai_and_eps_files() {
|
||||
let filters: Vec<_> = library_open_filters("Swatch libraries", crate::cmd::swatchlib::LIBRARY_PICK_EXTS).collect();
|
||||
for ext in ["ai", "ait", "eps", "epsf", "ase", "gpl", "acb", "vcswatches"] {
|
||||
assert!(filters[0].1.contains(&ext), "{ext}: {:?}", filters[0]);
|
||||
}
|
||||
assert_eq!(filters.iter().filter(|f| f.0 == "Swatch libraries").count(), 1, "{filters:?}");
|
||||
// File › Open still opens a `.ai` as a document, not as a swatch library.
|
||||
assert!(!crate::cmd::swatchlib::LIBRARY_EXTS.contains(&"ai") && !opens_as_other("ai"));
|
||||
}
|
||||
|
||||
/// The extensions usage texts list for export: one per writable format, each picking that format
|
||||
/// (`.png` picks PNG; PNG-8 is asked for by `format`).
|
||||
#[test]
|
||||
|
||||
@@ -413,6 +413,114 @@ fn a_swatch_library_in_a_ai_file_without_layers_loads_its_palette() {
|
||||
assert!(matches!(sky, Some(vectorcraft_color::Paint::Gradient(_))), "{sky:?}");
|
||||
}
|
||||
|
||||
/// A `.ai` swatch library (a palette and no layers) holding White, the gradient Sky and, in the
|
||||
/// color group Textures, the swatch Tiles of the 4 pt pattern Dots, whose square is painted with
|
||||
/// `square` (a color operator), a color the palette doesn't list.
|
||||
fn textures_library(square: &str) -> Vec<u8> {
|
||||
let dots = format!("%AI3_BeginPattern: (Dots)\n(Dots) 0 0 4 4\n%_{square}\n%_1 1 m\n%_3 1 L\n%_3 3 L\n%_1 3 L\n%_f\nE\n%AI3_EndPattern\n");
|
||||
let gradient =
|
||||
"%AI5_BeginGradient: (Sky)\n(Sky) 0 2 Bd\n[\n%_0 0 0 0 1 1 1 2 1 6 50 0 Bs\n%_0 0 0 1 0 0 0 2 0.5 6 50 100 Bs\nBD\n%AI5_EndGradient\n";
|
||||
let palette = "%AI5_BeginPalette\n0 0 Pb\n0 0 0 0 1 1 1 Xa\n(White)\nPc\nBb\n2 (Sky) 0 0 0 1 1 0 0 1 0 0 1 Bg\n0 BB\n(Sky)\nPc\n\
|
||||
1 (Textures) 1 Pg\n(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n(Tiles)\nPc\nPB\n%AI5_EndPalette\n";
|
||||
let data = ai::editing_data(200.0, 100.0, &format!("{dots}{gradient}{palette}"));
|
||||
ai::ai(&compressed(data.as_bytes()), "1 0 0 rg 10 50 30 40 re f")
|
||||
}
|
||||
|
||||
/// `swatch.library.load` of `file` named `name` → its library id.
|
||||
fn load_library(s: &mut Session, name: &str, file: &[u8]) -> Value {
|
||||
let p = json!({"dataBase64": vectorcraft_format::base64_encode(file), "name": name});
|
||||
s.execute("swatch.library.load", &p).unwrap()["library"].clone()
|
||||
}
|
||||
|
||||
/// Other Library… on a `.ai` swatch library lists its colors, gradients and pattern swatches in its
|
||||
/// order and color groups, and adding the pattern swatch makes a pattern swatch with the pattern's
|
||||
/// tile and art in the document, in the library's color group, not the pattern's colors.
|
||||
#[test]
|
||||
fn a_swatch_library_in_a_ai_file_lists_and_adds_its_pattern_swatches() {
|
||||
let mut s = Session::new();
|
||||
let id = load_library(&mut s, "textures.ai", &textures_library("0 0 0 1 k"));
|
||||
let lib = s.execute("swatch.library.get", &json!({"library": id})).unwrap();
|
||||
let kinds: Vec<(&str, &str, Option<&str>)> =
|
||||
lib["swatches"].as_array().unwrap().iter().map(|w| (w["name"].as_str().unwrap(), w["kind"].as_str().unwrap(), w["group"].as_str())).collect();
|
||||
assert_eq!(kinds, [("White", "color", None), ("Sky", "gradient", None), ("Tiles", "pattern", Some("Textures"))], "{lib}");
|
||||
assert_eq!(lib["swatches"][2]["pattern"], json!("Dots"), "{lib}");
|
||||
// The library panel draws the pattern from the file it came from; a copy of the swatch isn't its own.
|
||||
let (_, library) = crate::cmd::swatchlib::library(&s, id.as_str().unwrap()).unwrap();
|
||||
let tiles = library.iter().find(|w| w.name == "Tiles").unwrap();
|
||||
assert!(crate::cmd::swatchlib::pattern_source(&s, tiles).is_some_and(|d| d.pattern("Dots").is_some()));
|
||||
assert!(crate::cmd::swatchlib::pattern_source(&s, &tiles.clone()).is_none());
|
||||
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
let r = s.execute("swatch.library.add", &json!({"library": id, "names": ["Textures"]})).unwrap();
|
||||
assert_eq!(r["added"], json!(["Tiles"]), "{r}");
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let dots = doc.pattern("Dots").expect("the pattern comes with its swatch");
|
||||
assert_eq!((dots.tile.width(), dots.tile.height()), (4.0, 4.0));
|
||||
assert_eq!(dots.art.len(), 1, "{:?}", dots.art);
|
||||
let textures = doc.swatch_groups.iter().find(|g| g.name == "Textures").expect("the color group comes too");
|
||||
let tiles: Vec<_> = textures.swatches.iter().map(|w| (w.name.as_str(), &w.paint)).collect();
|
||||
assert!(matches!(tiles[..], [("Tiles", vectorcraft_color::Paint::Pattern { pattern, .. })] if pattern == "Dots"), "{tiles:?}");
|
||||
// Added again, the swatch the document has is used.
|
||||
let again = s.execute("swatch.library.add", &json!({"library": id, "names": ["Tiles"]})).unwrap();
|
||||
assert_eq!((again["added"].clone(), again["existing"].clone()), (json!([]), json!(["Tiles"])), "{again}");
|
||||
}
|
||||
|
||||
/// A pattern swatch of a `.ai` library whose pattern paints with a color the library doesn't list
|
||||
/// still comes in with that color in its art.
|
||||
#[test]
|
||||
fn a_pattern_from_a_ai_library_keeps_a_color_the_library_lacks() {
|
||||
let mut s = Session::new();
|
||||
let id = load_library(&mut s, "textures.ai", &textures_library("0 0.5 1 0 k"));
|
||||
let lib = s.execute("swatch.library.get", &json!({"library": id})).unwrap();
|
||||
let names: Vec<&str> = lib["swatches"].as_array().unwrap().iter().map(|w| w["name"].as_str().unwrap()).collect();
|
||||
assert_eq!(names, ["White", "Sky", "Tiles"], "the pattern's color isn't listed: {lib}");
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
s.execute("swatch.library.add", &json!({"library": id, "names": ["Tiles"]})).unwrap();
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let art = &doc.pattern("Dots").unwrap().art;
|
||||
let fill = art.first().and_then(|n| n.appearance.fill()).map(|f| f.paint.color());
|
||||
assert_eq!(fill, Some(Some(vectorcraft_color::Color::cmyk(0.0, 0.5, 1.0, 0.0))), "{art:?}");
|
||||
// Copy to User Defined would write a .vcswatches file, which can't hold the pattern swatch: it is
|
||||
// refused, writes nothing and leaves the library loaded.
|
||||
let dir = std::env::temp_dir().join(format!("vc-pattern-copy-{}", std::process::id()));
|
||||
s.swatch_libraries.set_user_dir(Some(dir.to_string_lossy().to_string()));
|
||||
let e = s.execute("swatch.library.copyToUser", &json!({"library": id})).unwrap_err().to_string();
|
||||
assert!(e.contains("`textures` has pattern swatches"), "{e}");
|
||||
assert!(!dir.exists() || std::fs::read_dir(&dir).unwrap().next().is_none(), "nothing written");
|
||||
assert!(s.execute("swatch.library.get", &json!({"library": id})).is_ok());
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
}
|
||||
|
||||
/// A `.ai` file without a palette of its own, and a document with no swatches, are refused as
|
||||
/// swatch libraries with a message, not listed as the default swatches or as an empty library. A
|
||||
/// damaged `.ai` is refused with the reader's error, and none of them is listed. A library file
|
||||
/// with no swatches loads as an empty library.
|
||||
#[test]
|
||||
fn swatch_library_documents_without_swatches_or_damaged_are_refused() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
s.edit("Clear", |d, _| {
|
||||
d.swatches.clear();
|
||||
d.swatch_groups.clear();
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let b64 = s.execute("document.serialize", &json!({})).unwrap()["dataBase64"].as_str().unwrap().to_string();
|
||||
let e = s.execute("swatch.library.load", &json!({"dataBase64": b64, "name": "Bare.vectorcraft"})).unwrap_err().to_string();
|
||||
assert!(e.contains("`Bare.vectorcraft` has no swatches of its own"), "{e}");
|
||||
let data = ai::editing_data(200.0, 100.0, &ai::layer("Art", &format!("0 0 0 1 k\n{}f\n", ai::rect(10.0, 50.0, 40.0, 90.0))));
|
||||
let p = json!({"dataBase64": vectorcraft_format::base64_encode(&ai::ai(&compressed(data.as_bytes()), "1 0 0 rg 10 50 30 40 re f")), "name": "art.ai"});
|
||||
let e = s.execute("swatch.library.load", &p).unwrap_err().to_string();
|
||||
assert!(e.contains("`art.ai` has no swatches of its own"), "{e}");
|
||||
let damaged = json!({"data": "%PDF-1.4\n%damaged\n", "name": "damaged.ai"});
|
||||
assert!(s.execute("swatch.library.load", &damaged).is_err());
|
||||
let list = s.execute("swatch.library.list", &json!({})).unwrap();
|
||||
assert!(list["libraries"].as_array().unwrap().iter().all(|l| l["category"] != "loaded"), "{list}");
|
||||
// A library file without swatches still loads, as an empty library.
|
||||
let r = s.execute("swatch.library.load", &json!({"data": "GIMP Palette\nName: Empty\n#\n", "name": "Empty.gpl"})).unwrap();
|
||||
assert_eq!(r["count"], json!(0), "{r}");
|
||||
}
|
||||
|
||||
/// Other Library… on a `.ai` graphic style library (art styles, their list and no layers) gives the
|
||||
/// library the styles of its list, in the list's order, not the default styles; the file opens with
|
||||
/// them too.
|
||||
|
||||
@@ -116,6 +116,24 @@ fn use_artboards_writes_one_drawing_per_artboard() {
|
||||
assert!(e.contains("useArtboards"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_artboard_s_drawing_is_the_drawing_of_that_artboard_alone() {
|
||||
let mut s = two_boards();
|
||||
// A second rectangle on the second artboard, so the two drawings differ.
|
||||
let second = s.doc().unwrap().doc.artboards[1].rect.x0;
|
||||
s.execute("shape.rectangle", &json!({"x": second + 50.0, "y": 50, "width": 20, "height": 20})).unwrap();
|
||||
let r = s.execute("document.export", &json!({"format": "dxf", "useArtboards": true, "unit": "pt"})).unwrap();
|
||||
let files = r["files"].as_array().unwrap();
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let o = dxf::options(&json!({"unit": "pt"})).unwrap();
|
||||
assert_eq!(files.len(), doc.artboards.len());
|
||||
assert_ne!(b64(&files[0]), b64(&files[1]));
|
||||
for (f, board) in files.iter().zip(&doc.artboards) {
|
||||
let alone = vectorcraft_cad::export(doc, &vectorcraft_cad::DxfOptions { region: board.rect, crop: true, ..o.clone() }).unwrap();
|
||||
assert_eq!(b64(f), alone.bytes, "{}", f["name"]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selected_only_exports_the_selection_in_its_layers() {
|
||||
let mut s = two_boards();
|
||||
|
||||
@@ -410,3 +410,16 @@ fn a_placeholder_only_pdf_part_is_detected() {
|
||||
assert!(open(&mut s, &two, json!({"pages": "1"})).is_err());
|
||||
open(&mut s, &two, json!({})).unwrap();
|
||||
}
|
||||
|
||||
/// `linkPages` takes a PDF up to the largest file placed, and nothing else.
|
||||
#[test]
|
||||
fn pages_can_link_a_pdf_up_to_the_largest_file_placed() {
|
||||
let small = three_pages();
|
||||
assert!(pages_can_link("pages.pdf", &small));
|
||||
assert!(!pages_can_link("pages.svg", b"<svg xmlns=\"http://www.w3.org/2000/svg\"/>"));
|
||||
let mut big = vec![0u8; crate::cmd::place::document::MAX_FILE + 1];
|
||||
big[..small.len()].copy_from_slice(&small);
|
||||
assert!(!pages_can_link("pages.pdf", &big), "over the limit");
|
||||
big.pop();
|
||||
assert!(pages_can_link("pages.pdf", &big), "at the limit");
|
||||
}
|
||||
|
||||
@@ -1461,3 +1461,25 @@ fn an_export_preset_adds_no_notes() {
|
||||
let r = export(&mut s, json!({"exportPreset": "Mixed"}));
|
||||
assert!(unused(&r).is_empty(), "{r}");
|
||||
}
|
||||
|
||||
/// Assets, layers and selected objects each write a native, `.ai` or EPS file of their own art:
|
||||
/// every piece's file holds its own artboard, named after it, not the first piece's.
|
||||
#[test]
|
||||
fn each_piece_writes_its_own_native_document() {
|
||||
let mut s = session(1);
|
||||
s.execute("shape.ellipse", &json!({"x": 2, "y": 2, "width": 10, "height": 10})).unwrap();
|
||||
let ids: Vec<u64> = s.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id.0).collect();
|
||||
let mut assets = vec![];
|
||||
for (id, name) in ids.iter().zip(["Square", "Circle"]) {
|
||||
assets.push(s.execute("assets.add", &json!({"ids": [id], "name": name})).unwrap()["assets"][0].as_u64().unwrap());
|
||||
}
|
||||
let r = export(&mut s, json!({"assets": assets, "formats": [{"format": "vectorcraft"}, {"format": "eps"}]}));
|
||||
let written = files(&r);
|
||||
assert_eq!(written.len(), 4, "{r}");
|
||||
for (name, bytes) in written {
|
||||
let native = if name.ends_with(".eps") { vectorcraft_eps::native(&bytes).expect("native document") } else { bytes };
|
||||
let doc = vectorcraft_format::load(&native).unwrap();
|
||||
let board = doc.artboards[0].name.clone();
|
||||
assert!(name.contains(&board), "{name} holds the artboard {board}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -769,6 +769,7 @@ fn give_item(a: &AppearanceItem, b: &AppearanceItem, m: &AppearanceItem, n: &mut
|
||||
arrow_scale,
|
||||
profile,
|
||||
brush,
|
||||
brush_options,
|
||||
opacity,
|
||||
blend,
|
||||
visible,
|
||||
@@ -781,7 +782,11 @@ fn give_item(a: &AppearanceItem, b: &AppearanceItem, m: &AppearanceItem, n: &mut
|
||||
bearing: _,
|
||||
rotation: _,
|
||||
} = m;
|
||||
give_fields!(a, b, n: paint, width, cap, join, miter_limit, align, dash, start_arrow, end_arrow, arrow_scale, profile, brush, opacity, blend, visible, effects, arrow_align, overprint, gradient_mode);
|
||||
give_fields!(a, b, n: paint, width, cap, join, miter_limit, align, dash, start_arrow, end_arrow, arrow_scale, profile, brush, brush_options, opacity, blend, visible, effects, arrow_align, overprint, gradient_mode);
|
||||
// A stroke's own brush settings go with the brush they set: a new brush takes the model's.
|
||||
if a.brush != b.brush {
|
||||
n.brush_options = brush_options.clone();
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
@@ -37,7 +37,8 @@ use axis::{nice_axis, tick_values};
|
||||
#[cfg(test)]
|
||||
use columns::{fill_totals, total_text};
|
||||
pub use commands::specs;
|
||||
pub(crate) use data::{apply_csv, parse_csv};
|
||||
pub use data::{MAX_GRAPH_DATA_FILE, graph_cell_text, graph_data_from_grid, graph_data_text, graph_grid_from_text};
|
||||
pub(crate) use data::{apply_csv, graph_csv_from_file, parse_csv};
|
||||
#[cfg(test)]
|
||||
use data::{fmt_value, to_csv};
|
||||
pub use edit::{GraphTypeSubject, graph_type_subject};
|
||||
|
||||
@@ -91,6 +91,102 @@ pub(super) fn to_csv(g: &GraphSpec) -> String {
|
||||
g.to_csv()
|
||||
}
|
||||
|
||||
// ---------- graph data files ----------
|
||||
|
||||
/// The largest graph data file that Graph Data's Import Data and Import Data Sets' `%` columns
|
||||
/// read, 1 MB (1,048,576 bytes).
|
||||
pub const MAX_GRAPH_DATA_FILE: usize = 1 << 20;
|
||||
|
||||
/// A graph data sheet's size: a row of labels over a graph's categories, a column of labels
|
||||
/// before its series; a cell's longest text.
|
||||
const SHEET_ROWS: usize = vectorcraft_doc::MAX_GRAPH_CATEGORIES + 1;
|
||||
const SHEET_COLS: usize = vectorcraft_doc::MAX_GRAPH_SERIES + 1;
|
||||
const SHEET_CELL: usize = 256;
|
||||
|
||||
/// A graph data file's bytes as text: UTF-16 with its byte-order mark (spreadsheets' "Unicode
|
||||
/// Text"), else UTF-16 without one when the bytes hold NUL bytes and Import Data Sets' rule gives
|
||||
/// them a byte order ([`crate::cmd::utf16_order_without_mark`]), else UTF-8 with or without one.
|
||||
/// UTF-16 is read as it is after a byte-order mark: an odd last byte is left out, and an unpaired
|
||||
/// surrogate reads as U+FFFD.
|
||||
pub fn graph_data_text(bytes: &[u8]) -> String {
|
||||
let utf16 = |rest: &[u8], le: bool| {
|
||||
let units: Vec<u16> = rest.as_chunks::<2>().0.iter().map(|p| if le { u16::from_le_bytes(*p) } else { u16::from_be_bytes(*p) }).collect();
|
||||
String::from_utf16_lossy(&units)
|
||||
};
|
||||
match bytes {
|
||||
[0xFF, 0xFE, rest @ ..] => utf16(rest, true),
|
||||
[0xFE, 0xFF, rest @ ..] => utf16(rest, false),
|
||||
[0xEF, 0xBB, 0xBF, rest @ ..] => String::from_utf8_lossy(rest).into_owned(),
|
||||
_ => match bytes.contains(&0).then(|| crate::cmd::utf16_order_without_mark(bytes)).flatten() {
|
||||
Some(le) => utf16(bytes, le),
|
||||
None => String::from_utf8_lossy(bytes).into_owned(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// A graph data sheet cell's text: one line (tabs and line breaks become spaces), at most 256
|
||||
/// characters.
|
||||
pub fn graph_cell_text(s: &str) -> String {
|
||||
s.chars().map(|c| if matches!(c, '\t' | '\r' | '\n') { ' ' } else { c }).take(SHEET_CELL).collect()
|
||||
}
|
||||
|
||||
/// Text from a file or the clipboard as graph data sheet cells: tab-separated when any line holds
|
||||
/// a tab, else comma-separated (decided once, so a label with a comma in a tab-separated file
|
||||
/// stays whole), at most a graph's rows and columns.
|
||||
pub fn graph_grid_from_text(text: &str) -> Vec<Vec<String>> {
|
||||
let sep = if text.contains('\t') { '\t' } else { ',' };
|
||||
text.lines().take(SHEET_ROWS).map(|l| l.trim_end_matches('\r').split(sep).take(SHEET_COLS).map(|c| graph_cell_text(c.trim())).collect()).collect()
|
||||
}
|
||||
|
||||
/// A graph data sheet as `graph.setData` takes it: the first row holds the series labels, the
|
||||
/// first column the category labels (none when all are blank), and the other cells the values (a
|
||||
/// blank cell, or text that isn't a number, has none), without the empty rows and columns past
|
||||
/// the data.
|
||||
pub fn graph_data_from_grid(grid: &[Vec<String>]) -> Value {
|
||||
let cell = |r: usize, c: usize| grid.get(r).and_then(|row| row.get(c)).cloned().unwrap_or_default();
|
||||
let filled = |s: &String| !s.trim().is_empty();
|
||||
// At most a graph's rows and columns, as a file gives (`graph_grid_from_text`): a grid sent by
|
||||
// automation is any size, and the values are their product.
|
||||
let grid = &grid[..grid.len().min(SHEET_ROWS)];
|
||||
let rows = grid.iter().rposition(|r| r.iter().take(SHEET_COLS).any(filled)).map_or(1, |i| i + 1).max(1);
|
||||
let cols = grid.iter().take(rows).filter_map(|r| r.iter().take(SHEET_COLS).rposition(filled)).max().map_or(1, |i| i + 1).max(1);
|
||||
let label = |s: &str| {
|
||||
let s = s.trim();
|
||||
// A label typed in straight quotes (as the CSV form takes a number as a label) is the text inside.
|
||||
s.strip_prefix('"').and_then(|t| t.strip_suffix('"')).unwrap_or(s).to_string()
|
||||
};
|
||||
// Series labels up to the last one given (none when all are blank).
|
||||
let mut series: Vec<String> = (1..cols).map(|c| label(&cell(0, c))).collect();
|
||||
while series.last().is_some_and(String::is_empty) {
|
||||
series.pop();
|
||||
}
|
||||
let mut categories: Vec<String> = (1..rows).map(|r| label(&cell(r, 0))).collect();
|
||||
if categories.iter().all(String::is_empty) {
|
||||
categories.clear();
|
||||
}
|
||||
let values: Vec<Vec<Value>> = (1..rows)
|
||||
.map(|r| {
|
||||
(1..cols)
|
||||
.map(|c| {
|
||||
let t = cell(r, c);
|
||||
t.trim().parse::<f64>().ok().filter(|v| v.is_finite() && !t.trim().starts_with('"')).map_or(Value::Null, |v| json!(v))
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.collect();
|
||||
json!({ "series": series, "categories": categories, "rows": values })
|
||||
}
|
||||
|
||||
/// The graph value (the CSV form [`apply_csv`] reads) of a graph data file's bytes, read as Graph
|
||||
/// Data's Import Data reads the file into its sheet and Apply sends the sheet: so applying the
|
||||
/// value gives a graph the data that Import Data and Apply give it.
|
||||
pub(crate) fn graph_csv_from_file(bytes: &[u8]) -> Result<String> {
|
||||
let data = graph_data_from_grid(&graph_grid_from_text(&graph_data_text(bytes)));
|
||||
let mut spec = GraphSpec::default();
|
||||
apply_data(&mut spec, &data, "dataset.import")?;
|
||||
Ok(spec.to_csv())
|
||||
}
|
||||
|
||||
/// Apply CSV graph data to the graph root `id` and rebuild its art (Variables data merge), as `graph.setData` with
|
||||
/// `csv` does. Data the graph already holds leaves the graph as it is.
|
||||
pub(crate) fn apply_csv(d: &mut Document, id: NodeId, csv: &str) -> Result<()> {
|
||||
@@ -149,6 +245,11 @@ pub(super) fn apply_data(g: &mut GraphSpec, p: &Value, cmd: &str) -> Result<bool
|
||||
if let Some(csv) = csv {
|
||||
let (s, c, r) = parse_csv(csv);
|
||||
g.series = s;
|
||||
// Series labels up to the last one given, as Graph Data's sheet keeps them
|
||||
// ([`graph_data_from_grid`]): `to_csv` writes a blank label for each series without one.
|
||||
while g.series.last().is_some_and(String::is_empty) {
|
||||
g.series.pop();
|
||||
}
|
||||
g.categories = c;
|
||||
g.set_cells(r);
|
||||
changed = true;
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::text::INLINE_MAX_SCALE;
|
||||
use vectorcraft_doc::{Document, InlineArt, NodeId, NodeKind, TextRun};
|
||||
use vectorcraft_doc::{Document, InlineArt, InlineMeasured, NodeId, NodeKind, TextRun};
|
||||
use vectorcraft_text::edit;
|
||||
|
||||
use super::brushsym::current_symbol;
|
||||
@@ -25,12 +25,33 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
/// Inline graphics follow their symbols: after an edit of a document that has (or had) symbols,
|
||||
/// resolve the inline art of every text again, in the layers and in the art of symbols, graph
|
||||
/// designs, pattern tiles and opacity masks, and lay out again the texts whose art changed (a
|
||||
/// symbol's type before the type that shows that symbol inline).
|
||||
pub(crate) fn refresh(before: &Document, d: &mut Document) {
|
||||
/// symbol's type before the type that shows that symbol inline). `last` is the document the last
|
||||
/// refresh left resolved, with what it measured: when nothing the inline art depends on changed
|
||||
/// since, only the layer trees that differ from its own are checked
|
||||
/// ([`Document::resolve_inline_art_since`]). Returns what this refresh measured, or `None` when
|
||||
/// neither document has symbols and nothing was checked.
|
||||
pub(crate) fn refresh(last: Option<&Resolved>, before: &Document, d: &mut Document) -> Option<InlineMeasured> {
|
||||
if before.symbols.is_empty() && d.symbols.is_empty() {
|
||||
return;
|
||||
return None;
|
||||
}
|
||||
d.resolve_inline_art_with(&mut refresh_bounds);
|
||||
#[cfg(test)]
|
||||
let last = last.filter(|_| !FULL_PASS.get());
|
||||
let pass = d.resolve_inline_art_since(last.map(|(doc, m)| (&**doc, m)), &mut refresh_bounds);
|
||||
#[cfg(test)]
|
||||
PASSES.with(|p| p.borrow_mut().push((pass.partial, pass.changed.clone())));
|
||||
Some(pass.measured)
|
||||
}
|
||||
|
||||
/// A document a [`refresh`] left resolved, and what that refresh measured.
|
||||
pub(crate) type Resolved = (std::sync::Arc<Document>, InlineMeasured);
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// Each [`refresh`] on this thread that checked the document: whether it checked only the
|
||||
/// changed layer trees, and the ids of the texts in the layers that changed.
|
||||
pub(crate) static PASSES: std::cell::RefCell<Vec<(bool, Vec<NodeId>)>> = const { std::cell::RefCell::new(vec![]) };
|
||||
/// Set: every [`refresh`] on this thread takes the full pass.
|
||||
pub(crate) static FULL_PASS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
}
|
||||
|
||||
fn insert_inline(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -47,18 +68,22 @@ fn insert_inline(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
let len = edit::runs_len(&t.runs);
|
||||
let from_tool = editing == Some(id);
|
||||
let (a, b) = match p.get("at") {
|
||||
None | Some(Value::Null) if from_tool => {
|
||||
let g = |k: &str| tool.get(k).and_then(Value::as_u64).map_or(len, |v| (v as usize).min(len));
|
||||
let (x, y) = (g("start"), g("end"));
|
||||
(x.min(y), x.max(y))
|
||||
}
|
||||
None | Some(Value::Null) => (len, len),
|
||||
Some(v) => {
|
||||
let at = v.as_u64().ok_or_else(|| bad(C, "`at` must be a byte offset"))?.min(len as u64) as usize;
|
||||
(at, at)
|
||||
}
|
||||
// Where the graphic goes in text `len` bytes long.
|
||||
let range = |len: usize| -> Result<(usize, usize)> {
|
||||
Ok(match p.get("at") {
|
||||
None | Some(Value::Null) if from_tool => {
|
||||
let g = |k: &str| tool.get(k).and_then(Value::as_u64).map_or(len, |v| (v as usize).min(len));
|
||||
let (x, y) = (g("start"), g("end"));
|
||||
(x.min(y), x.max(y))
|
||||
}
|
||||
None | Some(Value::Null) => (len, len),
|
||||
Some(v) => {
|
||||
let at = v.as_u64().ok_or_else(|| bad(C, "`at` must be a byte offset"))?.min(len as u64) as usize;
|
||||
(at, at)
|
||||
}
|
||||
})
|
||||
};
|
||||
let (mut a, mut b) = range(len)?;
|
||||
let symbol = match str_param(p, "symbol") {
|
||||
Some(n) if doc.symbols.iter().any(|s| s.name == n) => n.to_string(),
|
||||
Some(n) => return Err(bad(C, format!("no symbol named `{n}`"))),
|
||||
@@ -76,11 +101,16 @@ fn insert_inline(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
None | Some(Value::Null) => 0.0,
|
||||
Some(v) => v.as_f64().filter(|k| k.is_finite() && k.abs() <= 1e5).ok_or_else(|| bad(C, "`shift` must be a number of points"))?,
|
||||
};
|
||||
// A typing session ends first: the insertion is a step of its own.
|
||||
// A typing session ends first: the insertion is a step of its own. Typing that Real-time
|
||||
// Drawing off left unapplied is applied first, and the caret is read in the typed text.
|
||||
let typing = tool.get("typing").and_then(Value::as_bool) == Some(true);
|
||||
if typing && from_tool {
|
||||
s.set_tool_option("commitTyping", &Value::Bool(true));
|
||||
s.commit_interaction()?;
|
||||
super::settle_interaction(s)?;
|
||||
let NodeKind::Text(t) = &s.doc()?.doc.node(id).ok_or(EngineError::NoNode(id))?.kind else {
|
||||
return Err(bad(C, format!("node {} is not text", id.0)));
|
||||
};
|
||||
(a, b) = range(edit::runs_len(&t.runs))?;
|
||||
}
|
||||
let caret = s.edit("Insert Inline Symbol", |d, _| {
|
||||
let mut art = InlineArt { scale, baseline_shift: shift, ..InlineArt::new(symbol.clone()) };
|
||||
|
||||
@@ -29,7 +29,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"New Layer…",
|
||||
["Window", "Layers"],
|
||||
Some("Cmd+L"),
|
||||
"{name?, top?: bool, below?: bool, color?, template?, locked?, visible?, printable?, preview?, dimImages?} a layer directly above the current layer, at its level (a sublayer beside a current sublayer); `top`: above all layers (Ctrl/Cmd-click the button); `below`: directly below the current layer, at its level (Ctrl/Cmd+Alt-click the button), not with `top`. Options as layer.setProps; refused while an opacity mask is edited (the Layers panel lists only the mask) → {id}",
|
||||
"{name?, top?: bool, below?: bool, color?, template?, locked?, visible?, printable?, preview?, dimImages?} a layer directly above the current layer, at its level (a sublayer beside a current sublayer), or directly below it in Draw Behind; `top`: above all layers (Ctrl/Cmd-click the button); `below`: directly below the current layer, at its level (Ctrl/Cmd+Alt-click the button), not with `top`. Options as layer.setProps; refused while an opacity mask is edited (the Layers panel lists only the mask) → {id}",
|
||||
super::maskedit::outside_mask_editing,
|
||||
new_layer
|
||||
),
|
||||
@@ -110,7 +110,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Rows",
|
||||
[],
|
||||
None,
|
||||
"{ids|id, target, place?: \"above\"|\"below\"|\"inside\" (default inside), copy?: bool} drag rows in the Layers panel: above or below the target row (beside it, in its layer or group), or inside a layer, group or Intertwine group (on top of its contents). Layers go only in layers or at the top level, objects in layers, groups and Intertwine groups; an object placed beside a top-level layer goes inside it. An object placed in an Intertwine group becomes a member drawn in its row's order, with no arranged areas, and one placed in a group that is a member becomes part of that member; one that is or holds an Intertwine group, a Repeat, a graph or a Live Paint group is refused. A member moved out of its Intertwine group drops its arranged areas, and a group left with one member is replaced by that member, or becomes a plain group of it when the group has an opacity, blending, appearance, mask, lock or hidden state of its own (with no member, it is removed). A row never goes into itself; a locked layer or group takes nothing. `copy` (Alt-drag) moves copies. Every selected object left hidden or locked, such as one moved into a hidden layer or group, is deselected (the key object too). One undo step → {ids}",
|
||||
"{ids|id, target, place?: \"above\"|\"below\"|\"inside\" (default inside), copy?: bool} drag rows in the Layers panel: above or below the target row (beside it, in its layer or group), or inside a layer, group or Intertwine group (on top of its contents). Layers go only in layers or at the top level, objects in layers, groups and Intertwine groups; an object placed beside a top-level layer goes inside it. An object placed in an Intertwine group becomes a member drawn in its row's order, with no arranged areas, and one placed in a group that is a member becomes part of that member; one that is or holds an Intertwine group, a Repeat, a graph or a Live Paint group is refused. A member moved out of its Intertwine group drops its arranged areas, and a group left with one member is replaced by that member, or becomes a plain group of it when the group has an opacity, blending, appearance, mask, lock or hidden state of its own (with no member, it is removed). A row never goes into itself; a locked layer or group takes nothing. `copy` (Alt-drag) moves copies, which may also go above or below a row they copy (the target among `ids`). Every selected object left hidden or locked, such as one moved into a hidden layer or group, is deselected (the key object too). One undo step → {ids}",
|
||||
has_doc,
|
||||
move_rows
|
||||
),
|
||||
@@ -526,12 +526,15 @@ fn add_layer(s: &mut Session, p: &Value, cmd: &str, label: &str, place: impl FnO
|
||||
fn new_layer(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "layer.new";
|
||||
let below = switch_or(p, "below", false, C)?;
|
||||
if below && bool_or(p, "top", false) {
|
||||
let top = bool_or(p, "top", false);
|
||||
if below && top {
|
||||
return Err(bad(C, "`top` and `below` can't both be true"));
|
||||
}
|
||||
// In Draw Behind a layer given neither `top` nor `below` goes below the current layer.
|
||||
let below = below || (!top && s.draw_mode == crate::DrawMode::Behind);
|
||||
let st = s.doc()?;
|
||||
// Above the current layer, at its level; below it with `below`; on top of everything with `top`.
|
||||
let cur = st.current_layer().filter(|_| !bool_or(p, "top", false));
|
||||
let cur = st.current_layer().filter(|_| !top);
|
||||
add_layer(s, p, C, "New Layer", |d| match cur.and_then(|c| d.position(c)) {
|
||||
Some((parent, i, _)) => Ok((parent, if below { i } else { i + 1 })),
|
||||
None => Ok((None, if below { 0 } else { usize::MAX })),
|
||||
@@ -723,19 +726,18 @@ fn select_art(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
} else {
|
||||
vec![id]
|
||||
};
|
||||
let all_selected = !ids.is_empty() && ids.iter().all(|i| st.selection.contains(*i));
|
||||
let all_selected = add && !ids.is_empty() && {
|
||||
let selected: HashSet<NodeId> = st.selection.objects.iter().copied().collect();
|
||||
ids.iter().all(|i| selected.contains(i))
|
||||
};
|
||||
let rows = st.layer_rows.clone();
|
||||
s.select(|_, sel| {
|
||||
if !add {
|
||||
sel.set(ids.iter().copied());
|
||||
} else if all_selected {
|
||||
for i in &ids {
|
||||
sel.remove(*i);
|
||||
}
|
||||
sel.remove_all(ids.iter().copied());
|
||||
} else {
|
||||
for i in &ids {
|
||||
sel.add(*i);
|
||||
}
|
||||
sel.add_all(ids.iter().copied());
|
||||
}
|
||||
})?;
|
||||
let st = s.doc_mut()?;
|
||||
@@ -774,9 +776,11 @@ fn move_rows(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if ids.is_empty() {
|
||||
return Err(bad(C, "no such rows"));
|
||||
}
|
||||
// Never into itself or a row inside it.
|
||||
// Never into itself or a row inside it. A copy may go above or below one of the rows it
|
||||
// copies, which a move there would leave where it is (#8237).
|
||||
let beside_itself = copy && place != Place::Inside && ids.contains(&target);
|
||||
let around = d.ancestry(target).unwrap_or_default();
|
||||
if ids.iter().any(|i| around.contains(i)) {
|
||||
if ids.iter().any(|i| around.contains(i) && !(beside_itself && *i == target)) {
|
||||
return Err(bad(C, "a row can't go into itself"));
|
||||
}
|
||||
let nodes: Vec<&Node> = ids.iter().filter_map(|i| d.node(*i)).collect();
|
||||
@@ -788,6 +792,11 @@ fn move_rows(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
parent => (parent, Some(target)),
|
||||
},
|
||||
};
|
||||
// A copy beside a top-level layer it copies, with objects among the rows, would go inside
|
||||
// that layer: into itself.
|
||||
if parent.is_some_and(|p| ids.contains(&p)) {
|
||||
return Err(bad(C, "a row can't go into itself"));
|
||||
}
|
||||
if let Some(n) = nodes.iter().find(|n| !accepts(d, parent, n)) {
|
||||
let into = parent.and_then(|p| d.node(p)).map_or("the top level", |p| if p.is_layer() { "a layer" } else { p.kind_label() });
|
||||
return Err(bad(C, format!("{} can't go into {into}", n.display_name())));
|
||||
|
||||
@@ -132,7 +132,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Locate Object",
|
||||
["Window", "Layers"],
|
||||
None,
|
||||
"{id?} (default: the last selected object) highlight the object's row; the Layers panel opens the layers around it and scrolls to it → {id, ancestry: [layer…, id]}",
|
||||
"{id?, layersOnly?} (default: the last selected object) highlight the object's row; the Layers panel opens the layers around it and scrolls to it, also when the row was already highlighted →{id, ancestry: [layer…, id]}. layersOnly (default false; the panel sends true while Show Layers Only is on, as Locate Layer) highlights the innermost layer or sublayer holding the object instead, or a layer id itself → {id: layer, objectId, ancestry: [layer…]}",
|
||||
has_doc,
|
||||
locate
|
||||
),
|
||||
@@ -435,10 +435,19 @@ fn reverse(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn locate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = object_param(p, "id", "layer.locate")?;
|
||||
let layers_only = switch_or(p, "layersOnly", false, "layer.locate")?;
|
||||
let st = s.doc_mut()?;
|
||||
let id = id.or_else(|| st.selection.objects.last().copied()).ok_or_else(|| bad("layer.locate", "nothing selected"))?;
|
||||
let ancestry = st.doc.ancestry(id).ok_or(EngineError::NoNode(id))?;
|
||||
st.layer_rows = vec![id];
|
||||
let mut ancestry = st.doc.ancestry(id).ok_or(EngineError::NoNode(id))?;
|
||||
if layers_only {
|
||||
// Locate Layer: the innermost layer or sublayer holding the object (a layer locates itself).
|
||||
let at = ancestry.iter().rposition(|a| st.doc.node(*a).is_some_and(Node::is_layer)).ok_or(EngineError::NoNode(id))?;
|
||||
ancestry.truncate(at + 1);
|
||||
}
|
||||
let row = ancestry.last().copied().ok_or(EngineError::NoNode(id))?;
|
||||
st.layer_rows = vec![row];
|
||||
st.locate_reveal = Some(row);
|
||||
st.revision += 1;
|
||||
Ok(json!({ "id": id.0, "ancestry": ancestry.iter().map(|i| i.0).collect::<Vec<_>>() }))
|
||||
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 }) })
|
||||
}
|
||||
|
||||
@@ -36,7 +36,7 @@ use vectorcraft_doc::{
|
||||
use vectorcraft_geom::{Affine, FillRule, PathData, Rect, shapes};
|
||||
|
||||
use super::fileio::{self, RasterImage, absolute_path, file_created, file_stamp, read_file, write_file};
|
||||
use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_doc, ids_param, object_param, str_param, switch_or};
|
||||
use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_doc, ids_param, object_param, str_param, switch_or, text_param};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
@@ -108,7 +108,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Unembed",
|
||||
[],
|
||||
None,
|
||||
"{id?: an embedded image (default: the one selected), path?} write the image's pixels to the file at path (PNG, JPEG, GIF or WebP as stored, other images as PNG; a path ending in .png/.jpg/.jpeg/.gif/.webp/.tif/.tiff/.bmp converts them) and link the image to it, keeping its bounds. One undo step → {id, path}; no path → {name, dataBase64} (nothing changes: there is no file to link to)",
|
||||
"{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 (PNG, JPEG, GIF or WebP as stored, other images as PNG; a path ending in .png/.jpg/.jpeg/.gif/.webp/.tif/.tiff/.bmp converts them) and link the image to it, keeping its bounds. 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. 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
|
||||
),
|
||||
@@ -2686,11 +2686,35 @@ fn convert_image(bytes: &[u8], ext: &str) -> std::result::Result<Vec<u8>, String
|
||||
craft_image_codecs::encode(&raw, format, &craft_image_codecs::EncodeOptions::default()).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// The extension of the format embedded image `blob` is stored in (PNG for one Unembed doesn't
|
||||
/// name).
|
||||
fn stored_extension(blob: &vectorcraft_doc::ImageBlob) -> &'static str {
|
||||
fileio::FORMATS.iter().find(|f| f.raster && f.mime == blob.mime).map_or("png", |f| f.extensions.first().copied().unwrap_or("png"))
|
||||
}
|
||||
|
||||
/// The bytes of embedded image `blob` in the format of extension `ext`: its own bytes when it is
|
||||
/// stored in that format, else converted.
|
||||
fn unembed_bytes(blob: &vectorcraft_doc::ImageBlob, ext: &str) -> std::result::Result<Vec<u8>, String> {
|
||||
let same = fileio::format(ext).is_some_and(|f| f.mime == blob.mime);
|
||||
if same { Ok(blob.bytes.to_vec()) } else { convert_image(&blob.bytes, ext) }
|
||||
}
|
||||
|
||||
fn unembed(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "links.unembed";
|
||||
let given = |k: &str| p.get(k).is_some_and(|v| !v.is_null());
|
||||
// `id` with `ids`, and `path` with `folder`, are refused, in a replayed step too.
|
||||
super::params::check_exclusive_keys(C, p)?;
|
||||
let ids = ids_param(p, "ids", C)?;
|
||||
if given("folder") || ids.as_ref().is_some_and(|ids| ids.len() != 1) {
|
||||
return unembed_to_folder(s, p, ids);
|
||||
}
|
||||
let st = s.doc()?;
|
||||
let doc = with_brush_art(&st.doc);
|
||||
let id = image_param(st, &doc, p, C)?;
|
||||
// `ids` of one image is `id`.
|
||||
let id = match ids.as_deref() {
|
||||
Some(&[id]) => id,
|
||||
_ => image_param(st, &doc, p, C)?,
|
||||
};
|
||||
let n = stored(&doc, id).ok_or(crate::EngineError::NoNode(id))?;
|
||||
let im = image_of(&doc, id).ok_or_else(|| bad(C, format!("object {} is not an image", id.0)))?;
|
||||
if im.link.is_some() {
|
||||
@@ -2698,15 +2722,14 @@ fn unembed(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let blob = st.doc.images.get(&im.key).filter(|b| !b.is_proxy()).ok_or_else(|| bad(C, "the image's pixels aren't in the document"))?;
|
||||
// As stored (PNG, JPEG, GIF, WebP), unless the path names another format.
|
||||
let stored = fileio::FORMATS.iter().find(|f| f.raster && f.mime == blob.mime).map_or("png", |f| f.extensions.first().copied().unwrap_or("png"));
|
||||
let stored = stored_extension(blob);
|
||||
let path = str_param(p, "path");
|
||||
let ext = match path.map(fileio::extension) {
|
||||
Some(e) if UNEMBED_EXTS.contains(&e.as_str()) => e,
|
||||
Some(e) if !e.is_empty() => return Err(bad(C, format!("can't write .{e} images: use .png, .jpg, .gif, .webp, .tif or .bmp"))),
|
||||
_ => stored.to_string(),
|
||||
};
|
||||
let same = fileio::format(&ext).is_some_and(|f| f.mime == blob.mime);
|
||||
let bytes = if same { blob.bytes.to_vec() } else { convert_image(&blob.bytes, &ext).map_err(|e| bad(C, e))? };
|
||||
let bytes = unembed_bytes(blob, &ext).map_err(|e| bad(C, e))?;
|
||||
let Some(path) = path else {
|
||||
let name = n.display_name();
|
||||
let stem = Path::new(&name).file_stem().map_or_else(|| name.clone(), |s| s.to_string_lossy().into_owned());
|
||||
@@ -2722,6 +2745,146 @@ fn unembed(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "id": id.0, "path": path }))
|
||||
}
|
||||
|
||||
/// `links.unembed {ids?, folder}`: each embedded image of `ids` (`id` as `ids` of one; default: the
|
||||
/// selected embedded images) written to a new file in `folder` as stored (as PNG when that format is not one of
|
||||
/// VectorCraft's raster file formats) and linked to it, in one undo step. Linked images are skipped. When any image fails, the files written before it
|
||||
/// are removed and the document does not change.
|
||||
fn unembed_to_folder(s: &mut Session, p: &Value, ids: Option<Vec<NodeId>>) -> Result<Value> {
|
||||
const C: &str = "links.unembed";
|
||||
let folder = text_param(p, "folder", C)?.filter(|f| !f.is_empty()).ok_or_else(|| bad(C, "missing `folder`"))?;
|
||||
let ids = match ids {
|
||||
Some(ids) => Some(ids),
|
||||
None => object_param(p, "id", C)?.map(|id| vec![id]),
|
||||
};
|
||||
let st = s.doc()?;
|
||||
let doc = with_brush_art(&st.doc);
|
||||
let ids = ids.unwrap_or_else(|| selected_images(st, |im| im.link.is_none()));
|
||||
let mut seen = BTreeSet::new();
|
||||
if !ids.iter().all(|id| seen.insert(id.0)) {
|
||||
return Err(bad(C, "`ids` names an object twice"));
|
||||
}
|
||||
let (mut embedded, mut skipped) = (vec![], vec![]);
|
||||
for &id in &ids {
|
||||
let n = stored(&doc, id).ok_or(crate::EngineError::NoNode(id))?;
|
||||
let im = image_of(&doc, id).ok_or_else(|| bad(C, format!("object {} is not an image", id.0)))?;
|
||||
if im.link.is_some() {
|
||||
skipped.push(id);
|
||||
continue;
|
||||
}
|
||||
let blob = st.doc.images.get(&im.key).filter(|b| !b.is_proxy()).ok_or_else(|| bad(C, "the image's pixels aren't in the document"))?;
|
||||
embedded.push((id, n.display_name(), blob));
|
||||
}
|
||||
match (embedded.is_empty(), skipped.first()) {
|
||||
(true, Some(id)) => return Err(bad(C, format!("image {} is linked already", id.0))),
|
||||
(true, None) => return Err(bad(C, "select an image")),
|
||||
_ => {}
|
||||
}
|
||||
let dir = absolute_path(folder);
|
||||
writable_folder(&dir)?;
|
||||
// One image at a time: its bytes are read before its file is written, so pixels that can't be
|
||||
// read leave no file behind.
|
||||
let mut written: Vec<String> = vec![];
|
||||
let mut reads = Vec::with_capacity(embedded.len());
|
||||
let wrote = embedded.iter().try_for_each(|(id, name, blob)| {
|
||||
vectorcraft_doc::cancel::check()?;
|
||||
let ext = stored_extension(blob);
|
||||
let bytes = unembed_bytes(blob, ext).map_err(|e| bad(C, e))?;
|
||||
let name = format!("{}.{ext}", unembed_stem(name));
|
||||
let img = linked_image(&bytes, Some(Path::new(&dir).join(&name).to_string_lossy().as_ref()))?;
|
||||
let path = write_numbered(&dir, &name, &bytes)?;
|
||||
written.push(path.clone());
|
||||
reads.push((*id, (link_info(&path, &bytes), img)));
|
||||
Ok(())
|
||||
});
|
||||
let remove_written = |written: &[String]| {
|
||||
for path in written {
|
||||
let _ = std::fs::remove_file(path);
|
||||
}
|
||||
};
|
||||
if let Err(e) = wrote {
|
||||
remove_written(&written);
|
||||
return Err(e);
|
||||
}
|
||||
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)))
|
||||
});
|
||||
if let Err(e) = edited {
|
||||
remove_written(&written);
|
||||
return Err(e);
|
||||
}
|
||||
Ok(json!({ "unembedded": done, "skipped": ids_json(&skipped) }))
|
||||
}
|
||||
|
||||
/// The name Unembed gives image `name`'s file in a folder, before its extension: the name without
|
||||
/// a folder part or extension, each character a file name can't hold on some system
|
||||
/// (`/ \ : * ? " < > |` and control characters) as `_`, without leading spaces or trailing dots and
|
||||
/// spaces, at most 150 bytes long, and `Image` when nothing is left. A name Windows keeps for a
|
||||
/// device (`CON`, `NUL`, `COM1` …) gets `_` after it.
|
||||
fn unembed_stem(name: &str) -> String {
|
||||
let base = name.rsplit(['/', '\\']).next().unwrap_or_default();
|
||||
let stem = match base.rfind('.') {
|
||||
Some(i) if i > 0 => &base[..i],
|
||||
_ => base,
|
||||
};
|
||||
let mut clean = String::new();
|
||||
for c in stem.chars().map(|c| if c.is_control() || "/\\:*?\"<>|".contains(c) { '_' } else { c }) {
|
||||
if clean.len() + c.len_utf8() > 150 {
|
||||
break;
|
||||
}
|
||||
clean.push(c);
|
||||
}
|
||||
let clean = clean.trim_start_matches(' ').trim_end_matches(['.', ' ']);
|
||||
if clean.is_empty() {
|
||||
return "Image".to_string();
|
||||
}
|
||||
let device = clean.split('.').next().unwrap_or_default().trim_end().to_ascii_uppercase();
|
||||
let numbered = |prefix: &str| device.strip_prefix(prefix).is_some_and(|d| d.len() == 1 && matches!(d.as_bytes().first(), Some(b'1'..=b'9')));
|
||||
if matches!(device.as_str(), "CON" | "PRN" | "AUX" | "NUL") || numbered("COM") || numbered("LPT") {
|
||||
format!("{clean}_")
|
||||
} else {
|
||||
clean.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// Folder `path` may take Unembed's files: inside the automation write roots, and a folder.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn writable_folder(path: &str) -> Result<()> {
|
||||
crate::file_access::check_write(path).map_err(EngineError::Other)?;
|
||||
if !std::fs::metadata(path).is_ok_and(|m| m.is_dir()) {
|
||||
return Err(EngineError::Other(format!("{path} is not a folder")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write `bytes` to a new file named `name` in folder `dir`, never replacing a file there: `Name.ext`,
|
||||
/// else `Name 2.ext` up to `Name 99.ext`, as [`fileio::copy_new`] names them → its path.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn write_numbered(dir: &str, name: &str, bytes: &[u8]) -> Result<String> {
|
||||
use std::io::Write as _;
|
||||
let create = |to: &Path| {
|
||||
crate::file_access::check_write(&to.to_string_lossy()).map_err(|e| std::io::Error::new(std::io::ErrorKind::PermissionDenied, e))?;
|
||||
vectorcraft_format::write_new_with(to, |f| f.write_all(bytes))
|
||||
};
|
||||
match fileio::copy_new(Path::new(name), Path::new(dir), create, |_, _| false) {
|
||||
Ok(Some(fileio::Placed::Copied(to) | fileio::Placed::Kept(to))) => Ok(to.to_string_lossy().into_owned()),
|
||||
Ok(None) => Err(EngineError::Other(format!("every numbered name for {name} is taken in that folder"))),
|
||||
Err(e) => Err(EngineError::Other(format!("{dir}: {e}"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The web has no folders to write to.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn writable_folder(_: &str) -> Result<()> {
|
||||
Err(EngineError::Other("no file system here".into()))
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn write_numbered(_: &str, _: &str, _: &[u8]) -> Result<String> {
|
||||
Err(EngineError::Other("no file system here".into()))
|
||||
}
|
||||
|
||||
/// Placement Options as `{preserve, align, clip}`.
|
||||
fn placement_json(o: PlacementOptions) -> Value {
|
||||
json!({ "preserve": o.preserve.id(), "align": o.align.id(), "clip": o.clip })
|
||||
@@ -2901,4 +3064,28 @@ mod tests {
|
||||
let c = read();
|
||||
assert!(!Arc::ptr_eq(&a.blob.bytes, &c.blob.bytes));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unembed_names_a_file_after_the_image_with_only_characters_a_file_name_holds() {
|
||||
for (name, stem) in [
|
||||
("photo.png", "photo"),
|
||||
("Image", "Image"),
|
||||
("../../etc/passwd", "passwd"),
|
||||
("C:\\art\\logo.tif", "logo"),
|
||||
("a:b*c?d\"e<f>g|h", "a_b_c_d_e_f_g_h"),
|
||||
("tab\there", "tab_here"),
|
||||
(" name. .png", "name"),
|
||||
("..", "Image"),
|
||||
("", "Image"),
|
||||
(".hidden", ".hidden"),
|
||||
("CON.png", "CON_"),
|
||||
("lpt1", "lpt1_"),
|
||||
("COM0", "COM0"),
|
||||
("console", "console"),
|
||||
] {
|
||||
assert_eq!(unembed_stem(name), stem, "{name:?}");
|
||||
}
|
||||
let long = unembed_stem(&"é".repeat(200));
|
||||
assert!(long.len() <= 150 && long.chars().all(|c| c == 'é'), "{}", long.len());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,6 +29,8 @@ mod commands;
|
||||
mod common;
|
||||
mod envelope;
|
||||
mod mesh;
|
||||
#[cfg(test)]
|
||||
mod selected_tests;
|
||||
|
||||
pub(crate) use blend::expand_blends;
|
||||
pub use commands::specs;
|
||||
|
||||
@@ -657,9 +657,8 @@ pub(super) fn blend_replace_spine(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
/// Is any selected blend one made without a spine?
|
||||
fn any_without_spine(s: &Session) -> bool {
|
||||
let Ok(st) = s.doc() else { return false };
|
||||
selected_of(s, is_blend).iter().any(|b| matches!(st.doc.node(*b).map(|n| &n.kind), Some(NodeKind::Blend { spec, .. }) if spec.no_spine))
|
||||
pub(super) fn any_without_spine(s: &Session) -> bool {
|
||||
super::common::any_selected_of(s, is_blend, |n| matches!(&n.kind, NodeKind::Blend { spec, .. } if spec.no_spine))
|
||||
}
|
||||
|
||||
pub(super) fn blend_reverse_spine(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
use std::collections::HashSet;
|
||||
|
||||
use super::mesh::whole;
|
||||
use super::{
|
||||
Arc, BlendEase, BlendEaseType, BlendOrientation, BlendSpacing, Document, EngineError, Node, NodeId, NodeKind, Result, Selection, Session, Value,
|
||||
@@ -20,13 +22,14 @@ pub(super) fn roots_param(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
let mut sel = Selection::default();
|
||||
sel.set(ids.iter().copied().filter(|id| st.doc.node(*id).is_some_and(|n| !n.is_layer())));
|
||||
let ordered = sel.in_paint_order(&st.doc);
|
||||
let given: HashSet<NodeId> = ordered.iter().copied().collect();
|
||||
// Drop ids nested inside other given ids.
|
||||
return Ok(ordered
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|id| {
|
||||
let anc = st.doc.ancestry(*id).unwrap_or_default();
|
||||
!anc[..anc.len().saturating_sub(1)].iter().any(|a| ordered.contains(a))
|
||||
!anc[..anc.len().saturating_sub(1)].iter().any(|a| given.contains(a))
|
||||
})
|
||||
.collect());
|
||||
}
|
||||
@@ -37,20 +40,27 @@ pub(super) fn roots_param(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
/// dynamic symbol instance's art is selected.
|
||||
pub(super) fn selected_of(s: &Session, pred: fn(&Node) -> bool) -> Vec<NodeId> {
|
||||
let Some(st) = s.active().filter(|st| st.selection.symbol_part.is_none()) else { return vec![] };
|
||||
let mut find = st.doc.nearest_finder();
|
||||
let mut seen = HashSet::new();
|
||||
let mut out = vec![];
|
||||
for id in &st.selection.objects {
|
||||
for a in st.doc.ancestry(*id).unwrap_or_default().into_iter().rev() {
|
||||
if st.doc.node(a).is_some_and(pred) {
|
||||
if !out.contains(&a) {
|
||||
out.push(a);
|
||||
}
|
||||
break;
|
||||
}
|
||||
if let Some(n) = find.nearest(*id, pred)
|
||||
&& seen.insert(n.id)
|
||||
{
|
||||
out.push(n.id);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether some selected object's node of a kind ([`selected_of`]) passes `test`; stops at the
|
||||
/// first one that does.
|
||||
pub(super) fn any_selected_of(s: &Session, pred: fn(&Node) -> bool, test: impl Fn(&Node) -> bool) -> bool {
|
||||
let Some(st) = s.active().filter(|st| st.selection.symbol_part.is_none()) else { return false };
|
||||
let mut find = st.doc.nearest_finder();
|
||||
st.selection.objects.iter().any(|id| find.nearest(*id, pred).is_some_and(&test))
|
||||
}
|
||||
|
||||
pub(super) fn is_blend(n: &Node) -> bool {
|
||||
matches!(n.kind, NodeKind::Blend { .. })
|
||||
}
|
||||
@@ -66,19 +76,19 @@ pub(super) fn is_mesh(n: &Node) -> bool {
|
||||
pub(super) fn has_blend(s: &Session) -> std::result::Result<(), String> {
|
||||
has_selection(s)?;
|
||||
crate::cmd::edit::no_symbol_part(s)?;
|
||||
if selected_of(s, is_blend).is_empty() { Err("select a blend".into()) } else { Ok(()) }
|
||||
if any_selected_of(s, is_blend, |_| true) { Ok(()) } else { Err("select a blend".into()) }
|
||||
}
|
||||
|
||||
pub(super) fn has_envelope(s: &Session) -> std::result::Result<(), String> {
|
||||
has_selection(s)?;
|
||||
crate::cmd::edit::no_symbol_part(s)?;
|
||||
if selected_of(s, is_envelope).is_empty() { Err("select an envelope".into()) } else { Ok(()) }
|
||||
if any_selected_of(s, is_envelope, |_| true) { Ok(()) } else { Err("select an envelope".into()) }
|
||||
}
|
||||
|
||||
pub(super) fn has_mesh(s: &Session) -> std::result::Result<(), String> {
|
||||
has_selection(s)?;
|
||||
crate::cmd::edit::no_symbol_part(s)?;
|
||||
if selected_of(s, is_mesh).is_empty() { Err("select a gradient mesh".into()) } else { Ok(()) }
|
||||
if any_selected_of(s, is_mesh, |_| true) { Ok(()) } else { Err("select a gradient mesh".into()) }
|
||||
}
|
||||
|
||||
/// Wrap `roots` (paint order) into a new node built by `make`, placed where the topmost root was.
|
||||
|
||||
@@ -0,0 +1,324 @@
|
||||
//! The selected blend, envelope and mesh ([`selected_of`] and the checks built on it) are the ones
|
||||
//! the lookup of every ancestor by id found: the same ids in the same order, the same availability
|
||||
//! and errors, on selections with keys, nested blends, stale and repeated ids and a damaged tree.
|
||||
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_doc::{Node, NodeId, NodeKind, SymbolPart};
|
||||
|
||||
use super::Session;
|
||||
use super::blend::any_without_spine;
|
||||
use super::common::{any_selected_of, has_blend, has_envelope, has_mesh, is_blend, is_envelope, is_mesh, selected_of};
|
||||
|
||||
/// [`selected_of`] as each ancestor was looked up by id: `ancestry`, then `node` for each id from
|
||||
/// the object up, repeats dropped by a scan of the list.
|
||||
fn selected_of_by_ids(s: &Session, pred: fn(&Node) -> bool) -> Vec<NodeId> {
|
||||
let Some(st) = s.active().filter(|st| st.selection.symbol_part.is_none()) else { return vec![] };
|
||||
let mut out = vec![];
|
||||
for id in &st.selection.objects {
|
||||
for a in st.doc.ancestry(*id).unwrap_or_default().into_iter().rev() {
|
||||
if st.doc.node(a).is_some_and(pred) {
|
||||
if !out.contains(&a) {
|
||||
out.push(a);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The availability [`has_blend`] and the others gave, from [`selected_of_by_ids`].
|
||||
fn has_by_ids(s: &Session, pred: fn(&Node) -> bool, msg: &str) -> std::result::Result<(), String> {
|
||||
super::has_selection(s)?;
|
||||
crate::cmd::edit::no_symbol_part(s)?;
|
||||
if selected_of_by_ids(s, pred).is_empty() { Err(msg.into()) } else { Ok(()) }
|
||||
}
|
||||
|
||||
/// The no-spine check [`any_without_spine`] made, from [`selected_of_by_ids`].
|
||||
fn without_spine_by_ids(s: &Session) -> bool {
|
||||
let Ok(st) = s.doc() else { return false };
|
||||
selected_of_by_ids(s, is_blend).iter().any(|b| matches!(st.doc.node(*b).map(|n| &n.kind), Some(NodeKind::Blend { spec, .. }) if spec.no_spine))
|
||||
}
|
||||
|
||||
/// Every check on the current selection gives what the lookups by id gave.
|
||||
fn agree(s: &Session, what: &str) {
|
||||
type Has = fn(&Session) -> std::result::Result<(), String>;
|
||||
for (name, pred, has, msg) in [
|
||||
("blend", is_blend as fn(&Node) -> bool, has_blend as Has, "select a blend"),
|
||||
("envelope", is_envelope, has_envelope, "select an envelope"),
|
||||
("mesh", is_mesh, has_mesh, "select a gradient mesh"),
|
||||
] {
|
||||
let want = selected_of_by_ids(s, pred);
|
||||
assert_eq!(selected_of(s, pred), want, "{what}: selected {name}s");
|
||||
assert_eq!(any_selected_of(s, pred, |_| true), !want.is_empty(), "{what}: any {name}");
|
||||
assert_eq!(has(s), has_by_ids(s, pred, msg), "{what}: has {name}");
|
||||
}
|
||||
assert_eq!(any_without_spine(s), without_spine_by_ids(s), "{what}: a blend without a spine");
|
||||
}
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn id_of(v: &serde_json::Value) -> NodeId {
|
||||
NodeId(v["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
fn rect(s: &mut Session, x: f64) -> NodeId {
|
||||
id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 20, "height": 20})).unwrap())
|
||||
}
|
||||
|
||||
fn select(s: &mut Session, ids: &[NodeId]) {
|
||||
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
|
||||
}
|
||||
|
||||
fn run(s: &mut Session, cmd: &str, ids: &[NodeId], p: serde_json::Value) -> NodeId {
|
||||
select(s, ids);
|
||||
id_of(&s.execute(cmd, &p).unwrap())
|
||||
}
|
||||
|
||||
/// Every node id under the layers, parents before children (as Direct Selection can pick them).
|
||||
fn all_ids(s: &Session) -> Vec<NodeId> {
|
||||
fn walk(nodes: &[std::sync::Arc<Node>], out: &mut Vec<NodeId>) {
|
||||
for n in nodes {
|
||||
out.push(n.id);
|
||||
if let Some(ch) = n.children() {
|
||||
walk(ch, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = vec![];
|
||||
for l in &s.doc().unwrap().doc.layers {
|
||||
walk(l.children().map_or(&[][..], |c| c.as_slice()), &mut out);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The active document, to change in place.
|
||||
fn doc_mut(s: &mut Session) -> &mut vectorcraft_doc::Document {
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc)
|
||||
}
|
||||
|
||||
/// Set the selection's objects as given, stale and repeated ids included.
|
||||
fn set_objects(s: &mut Session, ids: Vec<NodeId>) {
|
||||
s.doc_mut().unwrap().selection.objects = ids;
|
||||
}
|
||||
|
||||
/// Two blends, a blend in a key group of a third, an envelope and a mesh; one blend has no spine.
|
||||
/// Returns the blends `a`, `b` and `c`, the group `g` of `c` that holds `a`, the envelope, and a key
|
||||
/// of `a`.
|
||||
fn document() -> (Session, [NodeId; 6]) {
|
||||
let mut s = session();
|
||||
let r: Vec<NodeId> = (0..10).map(|i| rect(&mut s, 40.0 * i as f64)).collect();
|
||||
let a = run(&mut s, "object.blend.make", &[r[0], r[1]], json!({}));
|
||||
let b = run(&mut s, "object.blend.make", &[r[2], r[3]], json!({}));
|
||||
let g = run(&mut s, "object.group", &[a, r[4]], json!({}));
|
||||
let c = run(&mut s, "object.blend.make", &[g, r[5]], json!({}));
|
||||
let e = run(&mut s, "object.envelope.makeWithWarp", &[r[6]], json!({"style": "arch", "bend": 50}));
|
||||
select(&mut s, &[r[7]]);
|
||||
s.execute("object.mesh.create", &json!({"ids": [r[7].0], "rows": 1, "cols": 1})).unwrap();
|
||||
if let Some(NodeKind::Blend { spec, .. }) = doc_mut(&mut s).node_mut(b).map(|n| &mut n.kind) {
|
||||
spec.no_spine = true;
|
||||
}
|
||||
(s, [a, b, c, g, e, r[0]])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selected_blends_envelopes_and_meshes_match_the_lookups_by_id() {
|
||||
let (mut s, [a, b, c, g, e, inner_key]) = document();
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
agree(&s, "select all");
|
||||
let all = all_ids(&s);
|
||||
let keys: Vec<NodeId> = all.iter().copied().filter(|id| ![a, b, c, g, e].contains(id)).collect();
|
||||
set_objects(&mut s, keys.clone());
|
||||
agree(&s, "keys, as Direct Selection picks them");
|
||||
set_objects(&mut s, all.iter().rev().copied().collect());
|
||||
agree(&s, "every node, children first");
|
||||
set_objects(&mut s, vec![a, keys[0], b, keys[1], keys[0], NodeId(999_999), a]);
|
||||
agree(&s, "repeated and stale ids, in first-seen order");
|
||||
assert_eq!(selected_of(&s, is_blend), vec![a, b], "the blend with no spine is listed once, in order");
|
||||
set_objects(&mut s, vec![NodeId(999_999)]);
|
||||
agree(&s, "only a stale id");
|
||||
set_objects(&mut s, vec![]);
|
||||
agree(&s, "nothing");
|
||||
// A blend in another blend's key group: the inner one.
|
||||
set_objects(&mut s, vec![inner_key]);
|
||||
agree(&s, "a key of a blend nested in another's key group");
|
||||
assert_eq!(selected_of(&s, is_blend), vec![a]);
|
||||
// An object of a dynamic symbol instance's art: nothing.
|
||||
set_objects(&mut s, all.clone());
|
||||
s.doc_mut().unwrap().selection.symbol_part = Some(SymbolPart { instance: a, path: vec![0] });
|
||||
agree(&s, "a symbol part");
|
||||
assert!(selected_of(&s, is_blend).is_empty());
|
||||
}
|
||||
|
||||
/// A damaged tree: an earlier node of another kind with the id of a blend on the selected key's
|
||||
/// path. `node` gives the earlier node, so that blend does not count, before and after the cache is
|
||||
/// built again.
|
||||
#[test]
|
||||
fn a_repeated_id_counts_as_its_first_node() {
|
||||
let (mut s, [a, _, c, _, _, inner_key]) = document();
|
||||
let all = all_ids(&s);
|
||||
s.doc().unwrap().doc.node(a);
|
||||
let doc = doc_mut(&mut s);
|
||||
if let Some(ch) = std::sync::Arc::make_mut(&mut doc.layers[0]).children_mut() {
|
||||
ch.insert(0, std::sync::Arc::new(Node::group(a, vec![])));
|
||||
}
|
||||
set_objects(&mut s, all.clone());
|
||||
agree(&s, "a repeated id, the cache older than the tree");
|
||||
s.doc().unwrap().doc.drop_lookup_cache();
|
||||
agree(&s, "a repeated id, no cache");
|
||||
s.doc().unwrap().doc.node(a);
|
||||
agree(&s, "a repeated id, cached afresh");
|
||||
set_objects(&mut s, vec![inner_key]);
|
||||
assert_eq!(selected_of(&s, is_blend), vec![c], "the nested blend's id is the group's, so the outer blend counts");
|
||||
}
|
||||
|
||||
/// Large selections: with the lookup cache built, finding the selected blends looks no id up, and
|
||||
/// the checks stop at the first selected object that has one.
|
||||
#[test]
|
||||
fn selected_blends_take_no_lookups_by_id() {
|
||||
let mut s = session();
|
||||
let mut keys = vec![];
|
||||
for i in 0..300 {
|
||||
let (x, y) = (rect(&mut s, i as f64), rect(&mut s, i as f64 + 30.0));
|
||||
run(&mut s, "object.blend.make", &[x, y], json!({}));
|
||||
keys.extend([x, y]);
|
||||
}
|
||||
for i in 0..1_000 {
|
||||
rect(&mut s, i as f64);
|
||||
}
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
s.doc().unwrap().doc.drop_lookup_cache();
|
||||
s.doc().unwrap().doc.node(keys[0]);
|
||||
let before = vectorcraft_doc::path_lookups();
|
||||
assert_eq!(selected_of(&s, is_blend).len(), 300);
|
||||
assert!(!any_selected_of(&s, is_mesh, |_| true));
|
||||
set_objects(&mut s, keys.clone());
|
||||
assert_eq!(selected_of(&s, is_blend).len(), 300, "each blend once from its two keys");
|
||||
assert_eq!(vectorcraft_doc::path_lookups() - before, 0, "lookups by id");
|
||||
// The first key is in a blend: the check tests that key and its blend only.
|
||||
static TESTED: AtomicUsize = AtomicUsize::new(0);
|
||||
fn counted(n: &Node) -> bool {
|
||||
TESTED.fetch_add(1, Ordering::Relaxed);
|
||||
is_blend(n)
|
||||
}
|
||||
assert!(any_selected_of(&s, counted, |_| true));
|
||||
assert_eq!(TESTED.load(Ordering::Relaxed), 2, "nodes tested");
|
||||
}
|
||||
|
||||
/// `n` and everything under it with new ids.
|
||||
fn renumber(d: &mut vectorcraft_doc::Document, n: &Node) -> Node {
|
||||
let mut n = n.clone();
|
||||
n.id = d.alloc_id();
|
||||
if let Some(ch) = n.children_mut() {
|
||||
for c in ch.iter_mut() {
|
||||
*c = std::sync::Arc::new(renumber(d, c));
|
||||
}
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
/// This thread's CPU time in nanoseconds, where the system reports it (Linux).
|
||||
fn cpu_ns() -> Option<u64> {
|
||||
std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok()
|
||||
}
|
||||
|
||||
/// Milliseconds one call of `f` takes over `calls` calls, in CPU time where the system reports it,
|
||||
/// otherwise in wall-clock time.
|
||||
fn ms_per_call(calls: u32, f: &dyn Fn()) -> f64 {
|
||||
let (cpu, wall) = (cpu_ns(), std::time::Instant::now());
|
||||
for _ in 0..calls {
|
||||
f();
|
||||
}
|
||||
let ms = match (cpu, cpu_ns()) {
|
||||
(Some(a), Some(b)) => b.saturating_sub(a) as f64 / 1e6,
|
||||
_ => wall.elapsed().as_secs_f64() * 1e3,
|
||||
};
|
||||
ms / f64::from(calls)
|
||||
}
|
||||
|
||||
/// The medians of 7 runs of `a` and of `b`, the runs taking turns.
|
||||
fn medians(calls: u32, a: &dyn Fn(), b: &dyn Fn()) -> (f64, f64) {
|
||||
let (mut ta, mut tb) = (vec![], vec![]);
|
||||
for _ in 0..7 {
|
||||
ta.push(ms_per_call(calls, a));
|
||||
tb.push(ms_per_call(calls, b));
|
||||
}
|
||||
ta.sort_by(f64::total_cmp);
|
||||
tb.sort_by(f64::total_cmp);
|
||||
(ta[3], tb[3])
|
||||
}
|
||||
|
||||
/// Timings of the lookups by id and of the one-path lookup on 100,000 rectangles in 10 layers,
|
||||
/// 2,000 two-key blends (every fourth one in a group) and 200 envelopes, all selected. Run with
|
||||
/// `cargo test --release -p vectorcraft-engine --lib selected_tests::timing -- --ignored --nocapture`.
|
||||
#[test]
|
||||
#[ignore = "timing; run by hand"]
|
||||
fn timing_of_the_selected_blend_checks() {
|
||||
let mut s = session();
|
||||
let (a, b, c) = (rect(&mut s, 0.0), rect(&mut s, 40.0), rect(&mut s, 80.0));
|
||||
let square = rect(&mut s, 120.0);
|
||||
let blend = run(&mut s, "object.blend.make", &[a, b], json!({}));
|
||||
let envelope = run(&mut s, "object.envelope.makeWithWarp", &[c], json!({"style": "arch", "bend": 50}));
|
||||
let doc = doc_mut(&mut s);
|
||||
let templates: Vec<Node> = [square, blend, envelope].iter().map(|id| doc.node(*id).cloned().unwrap()).collect();
|
||||
let mut layers = vec![];
|
||||
for l in 0..10 {
|
||||
let mut layer = Node::layer(doc.alloc_id(), &format!("Layer {l}"), vectorcraft_doc::LayerColor::Preset(0));
|
||||
let mut kids = vec![];
|
||||
for _ in 0..10_000 {
|
||||
kids.push(std::sync::Arc::new(renumber(doc, &templates[0])));
|
||||
}
|
||||
for i in 0..200 {
|
||||
let b = renumber(doc, &templates[1]);
|
||||
let b = if i % 4 == 0 { Node::group(doc.alloc_id(), vec![std::sync::Arc::new(b)]) } else { b };
|
||||
kids.push(std::sync::Arc::new(b));
|
||||
}
|
||||
for _ in 0..20 {
|
||||
kids.push(std::sync::Arc::new(renumber(doc, &templates[2])));
|
||||
}
|
||||
if let Some(ch) = layer.children_mut() {
|
||||
*ch = kids;
|
||||
}
|
||||
layers.push(std::sync::Arc::new(layer));
|
||||
}
|
||||
doc.layers = layers;
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
let first = s.doc().unwrap().selection.objects[0];
|
||||
s.doc().unwrap().doc.drop_lookup_cache();
|
||||
s.doc().unwrap().doc.node(first);
|
||||
println!("{} objects selected", s.doc().unwrap().selection.objects.len());
|
||||
type Check = fn(&Session) -> bool;
|
||||
let checks: [(&str, Check, Check); 5] = [
|
||||
("has_blend", |s| has_by_ids(s, is_blend, "").is_ok(), |s| has_blend(s).is_ok()),
|
||||
("has_envelope", |s| has_by_ids(s, is_envelope, "").is_ok(), |s| has_envelope(s).is_ok()),
|
||||
("has_mesh", |s| has_by_ids(s, is_mesh, "").is_ok(), |s| has_mesh(s).is_ok()),
|
||||
(
|
||||
"selected blends (object.blend.info and the Blend commands)",
|
||||
|s| !selected_of_by_ids(s, is_blend).is_empty(),
|
||||
|s| !selected_of(s, is_blend).is_empty(),
|
||||
),
|
||||
("a blend without a spine (Reverse Spine, the Blend panel)", without_spine_by_ids, any_without_spine),
|
||||
];
|
||||
assert_eq!(selected_of(&s, is_blend), selected_of_by_ids(&s, is_blend));
|
||||
println!("| Check | Lookups by id (ms) | One path (ms) |");
|
||||
println!("|---|---:|---:|");
|
||||
for (name, by_ids, one_path) in checks {
|
||||
assert_eq!(by_ids(&s), one_path(&s), "{name}");
|
||||
let (old, new) = medians(
|
||||
15,
|
||||
&|| {
|
||||
std::hint::black_box(by_ids(&s));
|
||||
},
|
||||
&|| {
|
||||
std::hint::black_box(one_path(&s));
|
||||
},
|
||||
);
|
||||
println!("| {name} | {old:.3} | {new:.3} |");
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Object menu long tail: Lock/Hide All Artwork Above & Other Layers, Transform Each, Reset
|
||||
//! Bounding Box, Rasterize, Crop Image, Mask (an image), Create Trim Marks, Convert to Shape and
|
||||
//! Artboards → Convert / Rearrange. (Live blends are in `live.rs`.)
|
||||
//! Bounding Box, Rotate Bounding Box, Rasterize, Crop Image, Mask (an image), Create Trim Marks,
|
||||
//! Convert to Shape and Artboards → Convert / Rearrange. (Live blends are in `live.rs`.)
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet, HashSet};
|
||||
use std::sync::Arc;
|
||||
@@ -15,8 +15,8 @@ use vectorcraft_render::encode::{RasterExportOptions, RasterFormat};
|
||||
|
||||
use super::edit::{duplicate_in, selected_roots, selected_roots_to_transform};
|
||||
use super::{
|
||||
CommandSpec, EngineError, Result, Session, bad, check_numbers, check_switches, cmd, f64_or, fileio, find_command, has_doc, has_selected_member,
|
||||
has_selection, switch_or,
|
||||
CommandSpec, EngineError, Result, Session, bad, check_numbers, check_switches, cmd, f64_or, f64_req, fileio, find_command, has_doc,
|
||||
has_selected_member, has_selection, switch_or,
|
||||
};
|
||||
|
||||
/// Session-level (not saved) state owned by the menu commands.
|
||||
@@ -110,6 +110,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_selection,
|
||||
reset_bounding_box
|
||||
),
|
||||
cmd!(
|
||||
"object.rotateBoundingBox",
|
||||
"Rotate Bounding Box…",
|
||||
["Object", "Transform"],
|
||||
None,
|
||||
"{angle: degrees (counter-clockwise), absolute?: bool (true: turn the box to angle; default false: turn it by angle from the angle the selected objects share, 0 when theirs differ)} turn the bounding box of the selected objects to one angle without moving their art; the objects inside them (the children of groups, compound paths, clip groups, blends, envelopes, repeats and intertwines, and the art of linked opacity masks) turn with them and keep their angle relative to them; a path of a compound path selected on its own turns only its own box; one undo step, none when every box is already at the angle; object.resetBoundingBox squares the boxes again; a missing or non-numeric angle is an error → {angle: the new angle of the boxes, in (-180, 180], changed: objects whose box turned, the objects inside the selected ones included}",
|
||||
has_selection,
|
||||
rotate_bounding_box
|
||||
),
|
||||
cmd!(
|
||||
"object.rasterize",
|
||||
"Rasterize…",
|
||||
@@ -225,9 +234,10 @@ pub(crate) fn squash(s: &mut Session, from: usize, label: &str) {
|
||||
// ---------- Reset Bounding Box ----------
|
||||
|
||||
/// Squares each selected object and every object inside it: the children of groups, compound paths,
|
||||
/// clip groups, blends, envelopes, repeats and intertwines, and the art of linked opacity masks.
|
||||
/// clip groups, blends, envelopes, repeats and intertwines, and the art of linked opacity masks. A
|
||||
/// path of a compound path selected on its own is squared alone, as the transforms move it alone.
|
||||
fn reset_bounding_box(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let ids = selected_roots(s)?;
|
||||
let ids = selected_roots_to_transform(s)?;
|
||||
let d = &s.doc()?.doc;
|
||||
let mut changed = 0;
|
||||
let squared: Vec<(NodeId, Node)> = ids
|
||||
@@ -251,6 +261,69 @@ fn reset_bounding_box(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
Ok(json!({ "changed": changed }))
|
||||
}
|
||||
|
||||
// ---------- Rotate Bounding Box ----------
|
||||
|
||||
/// Turns the bounding box of the selected objects to one angle without moving their art: by `angle`
|
||||
/// from the angle they share (0 when it differs), or to `angle` with `absolute`. Each object's box
|
||||
/// turns by what takes it there, and so do the boxes of the objects inside it (the children of
|
||||
/// groups and the art of linked opacity masks), which keep their angle relative to it.
|
||||
fn rotate_bounding_box(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "object.rotateBoundingBox";
|
||||
// A JSON number is always finite.
|
||||
let angle = f64_req(p, "angle", C)?;
|
||||
let absolute = switch_or(p, "absolute", false, C)?;
|
||||
// The same objects the transforms move: a path of a compound path selected on its own turns
|
||||
// its own box. Layers are left out, as they have no box.
|
||||
let owners = selected_roots_to_transform(s)?;
|
||||
let d = &s.doc()?.doc;
|
||||
let start = if absolute { 0.0 } else { d.bbox_angle(&owners) };
|
||||
// An angle within the tolerance of 0 is stored as 0, as `Node::turn_boxes` stores it.
|
||||
let target = match vectorcraft_geom::normalize_deg(start + angle) {
|
||||
a if a.abs() <= BOX_EPS_DEG => 0.0,
|
||||
a => a,
|
||||
};
|
||||
let mut changed = 0;
|
||||
let turned: Vec<(NodeId, Node)> = owners
|
||||
.iter()
|
||||
.filter_map(|id| {
|
||||
let n = d.node(*id)?;
|
||||
let by = vectorcraft_geom::normalize_deg(target - n.bbox_angle);
|
||||
(by.abs() > BOX_EPS_DEG).then(|| {
|
||||
let mut c = n.clone();
|
||||
c.turn_boxes(by);
|
||||
// The selected object's box is set to the target itself, so repeated turns add no
|
||||
// rounding error to it.
|
||||
c.bbox_angle = target;
|
||||
changed += boxes(&c);
|
||||
(*id, c)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
if !turned.is_empty() {
|
||||
s.edit("Rotate Bounding Box", |d, _| {
|
||||
for (id, n) in turned {
|
||||
if let Some(slot) = d.node_mut(id) {
|
||||
*slot = n;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
Ok(json!({ "angle": target, "changed": changed }))
|
||||
}
|
||||
|
||||
/// Angles closer than this (degrees) are the same, as `vectorcraft_doc::orient` compares them.
|
||||
const BOX_EPS_DEG: f64 = 1e-6;
|
||||
|
||||
/// The number of objects in `n`'s subtree whose box [`Node::turn_boxes`] turns: `n`, its children
|
||||
/// and the art of a linked opacity mask, layers left out.
|
||||
fn boxes(n: &Node) -> usize {
|
||||
let own = usize::from(!n.is_layer());
|
||||
let children: usize = n.children().into_iter().flatten().map(|c| boxes(c)).sum();
|
||||
let mask = n.extras().mask.as_ref().filter(|m| m.linked).map_or(0, |m| boxes(&m.art));
|
||||
own + children + mask
|
||||
}
|
||||
|
||||
/// A copy of `n` with the angle of every object in its subtree set to 0, or `None` when no box in
|
||||
/// it stands at an angle, and the number of objects squared. The subtree takes in children and the
|
||||
/// art of linked opacity masks (an unlinked mask's art turns on its own); layers have no box. Only
|
||||
|
||||
@@ -7,12 +7,16 @@
|
||||
//! panel's New Art Has Basic Appearance off, the whole appearance of the last selection. With the
|
||||
//! option on (the default) an inherited appearance gives new art its top stroke's options only,
|
||||
//! and a change of selection loads only the proxies. `paint.default` resets it.
|
||||
//!
|
||||
//! A document whose Default Graphic Style no longer has the shipped look (a New Document profile
|
||||
//! redefined it) gives the reset that style's fills, strokes and effects instead, and `file.new`
|
||||
//! resets new art when it opens such a document.
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{BlendMode, Paint};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, FillLayer, GraphicStyle, Node, NodeKind, StrokeLayer};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, ColorMode, DEFAULT_GRAPHIC_STYLE, Document, FillLayer, GraphicStyle, Node, NodeKind, StrokeLayer};
|
||||
use vectorcraft_tools::PaintDefaults;
|
||||
|
||||
use super::gradient::unplaced;
|
||||
@@ -263,7 +267,35 @@ fn describe(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
}))
|
||||
}
|
||||
|
||||
/// The defaults for new art reset (`paint.default`): white fill, 1 pt black stroke, no template.
|
||||
/// The defaults for new art reset (`paint.default`): white fill, 1 pt black stroke, no template;
|
||||
/// in a document whose Default Graphic Style was redefined, that style's fills, strokes and effects
|
||||
/// at full opacity, not linked to the style.
|
||||
pub(crate) fn reset(s: &mut Session) {
|
||||
s.paint = PaintDefaults::default();
|
||||
let style = s.doc().ok().and_then(|st| redefined_default_style(&st.doc)).cloned();
|
||||
if let Some(g) = style {
|
||||
let ap = if g.unit_box { g.appearance } else { unplace_all(g.appearance) };
|
||||
s.take_new_art(ap, 1.0, BlendMode::Normal, None, false);
|
||||
}
|
||||
}
|
||||
|
||||
/// `d`'s Default Graphic Style when its fills, strokes, effects or transparency differ from the
|
||||
/// shipped style's (white fill, 1 pt black stroke), the shipped colors converted to `d`'s color mode
|
||||
/// as a New Document profile's are.
|
||||
pub(crate) fn redefined_default_style(d: &Document) -> Option<&GraphicStyle> {
|
||||
let g = d.graphic_styles.iter().find(|g| g.name == DEFAULT_GRAPHIC_STYLE)?;
|
||||
let same =
|
||||
|o: &GraphicStyle| (&o.appearance, o.opacity, o.blend, o.isolate, o.knockout) == (&g.appearance, g.opacity, g.blend, g.isolate, g.knockout);
|
||||
if same(&GraphicStyle::new(DEFAULT_GRAPHIC_STYLE, Appearance::default_art())) {
|
||||
return None;
|
||||
}
|
||||
if d.color_mode != ColorMode::Rgb {
|
||||
let mut shipped = Document::new_with_mode(1.0, 1.0, ColorMode::Rgb);
|
||||
shipped.graphic_styles.retain(|o| o.name == DEFAULT_GRAPHIC_STYLE);
|
||||
super::colormgmt::set_color_mode(&mut shipped, d.color_mode, true, None, super::colormgmt::Grays::Profile);
|
||||
if shipped.graphic_styles.first().is_some_and(same) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
Some(g)
|
||||
}
|
||||
|
||||
@@ -814,6 +814,10 @@ pub(crate) fn file_new(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// The profile's links keep their relative paths, which name places from the profile's file, as
|
||||
// a new document from a history state keeps its source's.
|
||||
s.doc_mut()?.links_from = links_from;
|
||||
// A profile whose Default Graphic Style was redefined gives new art in the document that style.
|
||||
if super::newart::redefined_default_style(&s.doc()?.doc).is_some() {
|
||||
super::newart::reset(s);
|
||||
}
|
||||
// Overprint Preview is the engine's (the UI turns Pixel Preview on from `previewMode`). Both
|
||||
// are views of the whole app, so Default leaves them as they are.
|
||||
if settings.preview_mode == PreviewMode::Overprint {
|
||||
|
||||
@@ -384,6 +384,11 @@ fn add_drawn_live_paint(s: &mut Session, isolated: NodeId, next: Option<NodeId>)
|
||||
}
|
||||
|
||||
pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let key = "all";
|
||||
let all = match p.get(key) {
|
||||
None => false,
|
||||
Some(v) => v.as_bool().ok_or_else(|| bad("object.exitIsolation", format!("`{key}` must be true or false")))?,
|
||||
};
|
||||
// Opacity mask editing, pattern editing and symbol editing isolate their editing layer. Leaving
|
||||
// isolation mode then leaves that mode, as Stop Editing Opacity Mask and the isolation bar's
|
||||
// Done do. A group isolated inside the symbol's art goes back to the symbol's layer.
|
||||
@@ -419,12 +424,18 @@ pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return ok();
|
||||
}
|
||||
let menu = s.menu.clone();
|
||||
let prev = s.active().and_then(|d| d.isolation);
|
||||
let prev = st.isolation;
|
||||
// An isolated sublayer goes up to its parent layer, which stays isolated, unless `all` is true or
|
||||
// that layer is hidden or locked; anything else leaves isolation mode.
|
||||
let up = prev
|
||||
.filter(|i| !all && st.doc.node(*i).is_some_and(Node::is_layer))
|
||||
.and_then(|i| st.doc.parent_of(i))
|
||||
.filter(|parent| st.doc.is_editable(*parent));
|
||||
if let Some(i) = prev {
|
||||
crate::cmd::settle_interaction(s)?;
|
||||
let left = add_drawn_live_paint(s, i, None)?.unwrap_or(i);
|
||||
let left = add_drawn_live_paint(s, i, up)?.unwrap_or(i);
|
||||
let st = s.doc_mut()?;
|
||||
st.isolation = None;
|
||||
st.isolation = up;
|
||||
crate::cmd::distortcmds::finish_edit_text(st, i);
|
||||
let target = st.doc.parent_of(left).filter(|p| st.doc.node(*p).is_some_and(|n| n.extras().shaper.is_some())).unwrap_or(left);
|
||||
st.selection.set([target]);
|
||||
|
||||
@@ -59,7 +59,7 @@ fn bounds_transform(s: &Session, p: &Value, ids: Vec<NodeId>, least: f64, anchor
|
||||
let refi = reference_index(p)?;
|
||||
let st = s.doc()?;
|
||||
check_switches(p, &TRANSFORM_SWITCHES, "object.setBounds")?;
|
||||
check_switches(p, &["proportional"], "object.setBounds")?;
|
||||
check_switches(p, &["proportional", "interpolate"], "object.setBounds")?;
|
||||
let how = s.bounds_measure();
|
||||
if anchors
|
||||
&& transforms_objects(p)
|
||||
|
||||
@@ -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} 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)} 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
|
||||
),
|
||||
@@ -25,7 +25,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move…",
|
||||
["Object", "Transform"],
|
||||
Some("Cmd+Shift+M"),
|
||||
"{ids?: [id…] (selected first; default: the selection), dx, dy, copy?, 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), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.",
|
||||
"{ids?: [id…] (selected first; default: the selection), dx, dy, copy?, 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), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), interpolate?: bool (as path.moveAnchors's; default: prefs interpolateControlPoints)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.",
|
||||
has_selection_or_guides,
|
||||
move_cmd
|
||||
),
|
||||
@@ -61,7 +61,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Shear…",
|
||||
["Object", "Transform"],
|
||||
None,
|
||||
"{ids?: [id…] (selected first; default: the selection), angle: deg (positive turns the vertical edges clockwise with the horizontal axis, the top to the right; the horizontal edges clockwise with the vertical axis, the right side down), axis?: \"horizontal\"|\"vertical\", origin?, copy?, 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), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.",
|
||||
"{ids?: [id…] (selected first; default: the selection), angle: deg (positive turns the vertical edges clockwise with the horizontal axis, the top to the right; the horizontal edges clockwise with the vertical axis, the right side down), axis?: \"horizontal\"|\"vertical\"|deg (the line the art slides along, counter-clockwise from horizontal on the page, -359 to 359; 0: horizontal, 90: vertical; omitted: horizontal), origin?, copy?, 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), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.",
|
||||
has_selection,
|
||||
shear
|
||||
),
|
||||
@@ -70,7 +70,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Transform Again",
|
||||
["Object", "Transform"],
|
||||
Some("Cmd+D"),
|
||||
"{copy?, strokes?, corners?, patterns?, typeAreas?: bool (as object.transform's; default: the value the transform it repeats used, else object.transform's default)} the last transform's matrix on the selection (after a perspective move or scale: that plane-space transform, without these params)",
|
||||
"{copy?, strokes?, corners?, patterns?, typeAreas?, interpolate?: bool (as object.transform's; default: the value the transform it repeats used, else object.transform's default)} the last transform's matrix on the selection (after a perspective move or scale: that plane-space transform, without these params)",
|
||||
has_selection,
|
||||
transform_again
|
||||
),
|
||||
@@ -79,7 +79,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Nudge",
|
||||
[],
|
||||
None,
|
||||
"{dx: -1|0|1, dy: -1|0|1, big?: bool (×10), copy?: bool, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move)} arrow-key nudge by the keyboard increment (the selected anchors, else objects, along the x and y axes turned by the constrainAngle preference; else ruler guides, along the page axes)",
|
||||
"{dx: -1|0|1, dy: -1|0|1, big?: bool (×10), copy?: bool, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move), interpolate?: bool (as path.moveAnchors's; default: prefs interpolateControlPoints)} arrow-key nudge by the keyboard increment (the selected anchors, else objects, along the x and y axes turned by the constrainAngle preference; else ruler guides, along the page axes)",
|
||||
has_selection_or_guides,
|
||||
nudge
|
||||
),
|
||||
@@ -250,7 +250,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Exit Isolation Mode",
|
||||
[],
|
||||
None,
|
||||
"{} leave isolation mode; leaving an isolated Live Paint group adds the paths, compound paths and groups of them drawn in it (shown and unlocked with everything in them) to the group as livePaint.merge does, in one undo step, and leaves type, images and other objects in it as they are; object.isolate on a level outside the group does the same",
|
||||
"{all?: bool (default false)} leave isolation mode; from an isolated sublayer, go up one level to its parent layer instead (the next call goes up again), unless all is true or the parent layer is hidden or locked; no undo step for the move up; while a symbol is edited, a group isolated in its art goes back to the symbol's layer first, with or without all; leaving an isolated Live Paint group adds the paths, compound paths and groups of them drawn in it (shown and unlocked with everything in them) to the group as livePaint.merge does, in one undo step, and leaves type, images and other objects in it as they are; object.isolate on a level outside the group does the same",
|
||||
has_doc,
|
||||
exit_isolation
|
||||
),
|
||||
@@ -295,7 +295,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Set Bounds",
|
||||
[],
|
||||
None,
|
||||
"{x?, y?, width?, height?, reference?: whole number >= 0 (9-point grid 0..8; 0.0 equals 0; a whole number past 8 is read as 8; omitted/null: center, 4), proportional?, strokes?, corners?, copy?: bool, patterns?: bool (Transform Patterns), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move)} (Transform panel; width/height and the reference point follow the bounding box, rotated with rotated objects; x, y are page coordinates; with Use Preview Bounds the values measure the visual bounds; with the typeGlyphBounds preference, each point type object selected as an object (not inside a selected group) is measured by its glyphs' ink (underline and strikethrough included), which the scale gives the size asked for; strokes/corners as object.scale; with anchor points selected (Direct Selection) and no copy, the values are the box around those points, square to the page, and only they move or scale, as with object.move (#1824))",
|
||||
"{x?, y?, width?, height?, reference?: whole number >= 0 (9-point grid 0..8; 0.0 equals 0; a whole number past 8 is read as 8; omitted/null: center, 4), proportional?, strokes?, corners?, copy?: bool, patterns?: bool (Transform Patterns), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move), interpolate?: bool (with anchor points selected and only x or y changed: as path.moveAnchors's; default: prefs interpolateControlPoints)} (Transform panel; width/height and the reference point follow the bounding box, rotated with rotated objects; x, y are page coordinates; with Use Preview Bounds the values measure the visual bounds; with the typeGlyphBounds preference, each point type object selected as an object (not inside a selected group) is measured by its glyphs' ink (underline and strikethrough included), which the scale gives the size asked for; strokes/corners as object.scale; with anchor points selected (Direct Selection) and no copy, the values are the box around those points, square to the page, and only they move or scale, as with object.move (#1824))",
|
||||
has_selection,
|
||||
set_bounds
|
||||
),
|
||||
@@ -305,7 +305,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Live Shape Properties",
|
||||
[],
|
||||
None,
|
||||
"{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding, as in the reference app: store radii as fractions of each corner's maximum so they scale with the shape), corners?: [i…], items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse)} (Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius)",
|
||||
"{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding, as in the reference app: store radii as fractions of each corner's maximum so they scale with the shape), corners?: [i…], items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint)} (Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)",
|
||||
has_selection,
|
||||
set_live_shape
|
||||
),
|
||||
|
||||
@@ -6,6 +6,7 @@ use super::{
|
||||
BTreeSet, CornerKind, EngineError, LiveCorners, LiveShape, NodeId, NodeKind, Result, Session, Value, bad, check_numbers, check_switches,
|
||||
convert_radii_relative, ok, selected_roots, set_corners, targets,
|
||||
};
|
||||
use crate::MAX_COORD;
|
||||
|
||||
/// The largest scale of 0 or more at which `spans`, with the margins that scale grown by `k`,
|
||||
/// reach across `size` together. Returns 1 when their geometric boxes reach 1e-9 or less across
|
||||
@@ -98,8 +99,32 @@ fn corners_param(p: &Value) -> Result<Option<BTreeSet<usize>>> {
|
||||
list.iter().map(|k| k.as_u64().and_then(|k| usize::try_from(k).ok()).ok_or_else(err)).collect::<Result<_>>().map(Some)
|
||||
}
|
||||
|
||||
/// Live line `l` with Line Length `len` (its first end stays) and then Line Angle `angle` (about
|
||||
/// its midpoint; a line whose ends meet has none to turn), or None when neither changes it.
|
||||
fn line_edit(l: &LiveShape, len: Option<f64>, angle: Option<f64>) -> Option<LiveShape> {
|
||||
let now = l.line_length()?;
|
||||
let mut new = l.clone();
|
||||
let mut changed = false;
|
||||
if let Some(len) = len
|
||||
&& (len - now).abs() > 1e-9 * len.max(now)
|
||||
{
|
||||
new.set_line_length(len);
|
||||
changed = true;
|
||||
}
|
||||
if let Some(a) = angle
|
||||
&& new.line_length().is_some_and(|n| n > 0.0)
|
||||
&& let Some(turn) = new.line_angle().map(|now| (a - now).rem_euclid(360.0))
|
||||
&& turn > 1e-9
|
||||
&& turn < 360.0 - 1e-9
|
||||
{
|
||||
new.set_line_angle(a);
|
||||
changed = true;
|
||||
}
|
||||
(changed && new != *l).then_some(new)
|
||||
}
|
||||
|
||||
pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
check_switches(p, &["invertPie", "makeSidesEqual", "relativeRadii"], "object.setLiveShape")?;
|
||||
check_switches(p, &["constrainPie", "invertPie", "makeSidesEqual", "relativeRadii"], "object.setLiveShape")?;
|
||||
check_numbers(p, &["radius", "sides"], "object.setLiveShape")?;
|
||||
// `items`: objects each with its own `corners`; else `ids` (or the selection) sharing them.
|
||||
let items = match p.get("items").filter(|v| !v.is_null()) {
|
||||
@@ -148,7 +173,7 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
};
|
||||
let angle = |k: &str| Ok::<_, EngineError>(number(k, |_| true, "an angle in degrees")?.map(|a| a.rem_euclid(360.0)));
|
||||
let length = |k: &str| number(k, |x| x > 0.0 && x <= crate::MAX_COORD, "a length in points above 0");
|
||||
let length = |k: &str| number(k, |x| x > 0.0 && x <= MAX_COORD, "a length in points above 0");
|
||||
// Saved steps ([`Session::replay`]) can hold values a direct call refuses, recorded before these
|
||||
// checks: a negative radius is 0, a whole side count of 0 or more is brought into 3 to 1000, and
|
||||
// a fractional or negative one is ignored. A whole number written as 5.0 counts as 5, as in a
|
||||
@@ -168,21 +193,58 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// An ellipse's pie (Ellipse Properties: Pie Start and End Angle, degrees; Invert Pie swaps them).
|
||||
let (pie_start, pie_end) = (angle("pieStart")?, angle("pieEnd")?);
|
||||
let invert = p.get("invertPie").and_then(Value::as_bool) == Some(true);
|
||||
// Constrain Pie Angle: the one angle given moves the other by as much, so each ellipse keeps
|
||||
// its span (its end angle less its start angle, counterclockwise).
|
||||
let constrain = p.get("constrainPie").and_then(Value::as_bool) == Some(true);
|
||||
if constrain && (invert || pie_start.is_some() == pie_end.is_some()) {
|
||||
return Err(bad("object.setLiveShape", "`constrainPie` needs one of `pieStart` and `pieEnd`, without `invertPie`"));
|
||||
}
|
||||
// A polygon's Polygon Properties: its angle, radius or side length, Make Sides Equal.
|
||||
let (polygon_angle, polygon_radius, side) = (angle("polygonAngle")?, length("polygonRadius")?, length("sideLength")?);
|
||||
let equal = p.get("makeSidesEqual").and_then(Value::as_bool) == Some(true);
|
||||
// A line's Line Properties: its length (its first end stays) and its angle (about its midpoint).
|
||||
// A line's length can reach across the whole canvas, past `MAX_COORD`: its ends are checked below.
|
||||
let line_length = number("lineLength", |x| x > 0.0, "a length in points above 0")?;
|
||||
let line_angle = angle("lineAngle")?;
|
||||
// An ellipse's pie becomes `pie_of(pie)`. An end of 0 is a full turn (Illustrator shows a whole
|
||||
// ellipse as 0° to 360°).
|
||||
let end_of = |a: f64| if a == 0.0 { 360.0 } else { a };
|
||||
let pie_of = |pie: (f64, f64)| {
|
||||
let pie = (pie_start.unwrap_or(pie.0), pie_end.map_or(pie.1, end_of));
|
||||
let span = (pie.1 - pie.0).rem_euclid(360.0);
|
||||
let pie = match (constrain, pie_start, pie_end) {
|
||||
// The angle it already has: nothing moves.
|
||||
(true, Some(a), _) if a == pie.0 => pie,
|
||||
(true, _, Some(a)) if end_of(a) == pie.1 => pie,
|
||||
// A whole ellipse (a span of 0) stays whole.
|
||||
(true, Some(a), _) => (a, end_of((a + span).rem_euclid(360.0))),
|
||||
(true, _, Some(a)) => ((a - span).rem_euclid(360.0), end_of(a)),
|
||||
_ => (pie_start.unwrap_or(pie.0), pie_end.map_or(pie.1, end_of)),
|
||||
};
|
||||
if invert { (pie.1.rem_euclid(360.0), end_of(pie.0)) } else { pie }
|
||||
};
|
||||
// When every value given is the current one, the document and its undo history stay as they
|
||||
// are.
|
||||
let st = s.doc()?;
|
||||
// The lines that Line Length or Line Angle changes, as they become. A line that would reach
|
||||
// past the document's coordinate limit is an error before anything changes.
|
||||
let mut lines = std::collections::BTreeMap::new();
|
||||
if line_length.is_some() || line_angle.is_some() {
|
||||
for id in &ids {
|
||||
let Some(NodeKind::Path { live: Some(l), .. }) = st.doc.node(*id).map(|n| &n.kind) else { continue };
|
||||
if let Some(new) = line_edit(l, line_length, line_angle) {
|
||||
let LiveShape::Line { a, b } = &new else { continue };
|
||||
if ![a.x, a.y, b.x, b.y].iter().all(|c| c.abs() <= MAX_COORD) {
|
||||
return Err(bad("object.setLiveShape", format!("coordinate out of range (limit ±{MAX_COORD} pt)")));
|
||||
}
|
||||
lines.insert(*id, new);
|
||||
}
|
||||
}
|
||||
}
|
||||
let has_values = |id: &NodeId| {
|
||||
let Some(NodeKind::Path { path, live, .. }) = st.doc.node(*id).map(|n| &n.kind) else { return true };
|
||||
if lines.contains_key(id) {
|
||||
return false;
|
||||
}
|
||||
match live.as_deref() {
|
||||
Some(l @ LiveShape::Polygon { sides: now, .. })
|
||||
if !(sides.is_none_or(|n| n.clamp(3, 1000) == u64::from(*now))
|
||||
@@ -244,6 +306,12 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
*path = l.to_path();
|
||||
}
|
||||
if let Some(new) = lines.get(id)
|
||||
&& let Some(l) = live.as_deref_mut()
|
||||
{
|
||||
*l = new.clone();
|
||||
*path = l.to_path();
|
||||
}
|
||||
if let Some(on) = relative_radii
|
||||
&& let Some(l) = live.as_deref_mut()
|
||||
{
|
||||
|
||||
@@ -125,9 +125,14 @@ fn apply_transform_moving_guides(
|
||||
let d = &s.doc()?.doc;
|
||||
let paths = d.index_paths(ids.iter().copied());
|
||||
let none = paths.is_empty() && !has_guides;
|
||||
// A move of direct-selected anchors may re-map the handles beside them (`interpolate`).
|
||||
let mut interpolate = None;
|
||||
let ids = if anchors && objects && !copy && !s.doc()?.selection.anchors.is_empty() {
|
||||
if c[..4] == [1.0, 0.0, 0.0, 1.0] {
|
||||
interpolate = Some(crate::cmd::path::interpolates_handles(s, p, label)?);
|
||||
}
|
||||
if xf != Affine::IDENTITY {
|
||||
crate::cmd::path::transform_anchors(s, label, xf, sc)?;
|
||||
crate::cmd::path::transform_anchors(s, label, xf, sc, interpolate.unwrap_or(false))?;
|
||||
}
|
||||
ids
|
||||
} else if none || (!copy && xf == Affine::IDENTITY) {
|
||||
@@ -195,6 +200,9 @@ fn apply_transform_moving_guides(
|
||||
options["strokes"] = json!(sc.strokes);
|
||||
options["corners"] = json!(!sc.keep_corners);
|
||||
}
|
||||
if let Some(on) = interpolate {
|
||||
options["interpolate"] = json!(on);
|
||||
}
|
||||
st.last_transform = Some(LastTransform::Matrix(xf, options));
|
||||
st.last_perspective = None;
|
||||
}
|
||||
@@ -248,7 +256,7 @@ 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"], "object.transform")?;
|
||||
check_switches(p, &["anchors", "releaseOutside", "interpolate"], "object.transform")?;
|
||||
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.
|
||||
@@ -292,6 +300,7 @@ pub(super) fn transform(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
pub(super) fn move_cmd(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
check_numbers(p, &["dx", "dy"], "object.move")?;
|
||||
check_switches(p, &TRANSFORM_SWITCHES, "object.move")?;
|
||||
check_switches(p, &["interpolate"], "object.move")?;
|
||||
let ids = selected_roots_to_transform(s)?;
|
||||
apply_transform(s, "Move", ids, Affine::translate((f64_or(p, "dx", 0.0), f64_or(p, "dy", 0.0))), p, true)
|
||||
}
|
||||
@@ -311,7 +320,7 @@ pub(crate) fn along_constrain_angle(dx: f64, dy: f64, deg: f64) -> (f64, f64) {
|
||||
pub(super) fn nudge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
check_numbers(p, &["dx", "dy"], "object.nudge")?;
|
||||
check_switches(p, &TRANSFORM_SWITCHES, "object.nudge")?;
|
||||
check_switches(p, &["big"], "object.nudge")?;
|
||||
check_switches(p, &["big", "interpolate"], "object.nudge")?;
|
||||
let k = s.prefs.keyboard_increment * if bool_or(p, "big", false) { 10.0 } else { 1.0 };
|
||||
let (dx, dy) = (f64_or(p, "dx", 0.0) * k, f64_or(p, "dy", 0.0) * k);
|
||||
// Guides keep to the page's axes; art and anchors move along the constrain angle's.
|
||||
@@ -322,7 +331,7 @@ pub(super) fn nudge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if dx == 0.0 && dy == 0.0 {
|
||||
return ok();
|
||||
}
|
||||
return crate::cmd::path::move_anchors(s, &json!({ "dx": dx, "dy": dy, "patterns": p.get("patterns") }));
|
||||
return crate::cmd::path::move_anchors(s, &json!({ "dx": dx, "dy": dy, "patterns": p.get("patterns"), "interpolate": p.get("interpolate") }));
|
||||
}
|
||||
if s.doc()?.selection.is_empty() {
|
||||
let copy = bool_or(p, "copy", false);
|
||||
@@ -420,16 +429,35 @@ pub(super) fn shear(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = selected_roots_to_transform(s)?;
|
||||
let o = origin_of(s, p, &ids)?;
|
||||
let t = f64_or(p, "angle", 0.0).clamp(-89.0, 89.0).to_radians().tan();
|
||||
let vertical = choice(p, "object.shear", "axis", &["horizontal", "vertical"])? == Some("vertical");
|
||||
let m = if vertical { Affine::new([1.0, t, 0.0, 1.0, 0.0, 0.0]) } else { Affine::new([1.0, 0.0, -t, 1.0, 0.0, 0.0]) };
|
||||
let horizontal = Affine::new([1.0, 0.0, -t, 1.0, 0.0, 0.0]);
|
||||
// A named axis, or a line on the page at an angle in degrees, counter-clockwise from horizontal.
|
||||
let m = match p.get("axis") {
|
||||
None | Some(Value::Null) => horizontal,
|
||||
Some(Value::String(a)) if a == "horizontal" => horizontal,
|
||||
Some(Value::String(a)) if a == "vertical" => Affine::new([1.0, t, 0.0, 1.0, 0.0, 0.0]),
|
||||
Some(Value::Number(n)) if n.as_f64().is_some_and(|a| (-SHEAR_AXIS_MAX..=SHEAR_AXIS_MAX).contains(&a)) => {
|
||||
// y is down, so the page's counter-clockwise angle turns the other way on screen.
|
||||
let r = -n.as_f64().unwrap_or(0.0).to_radians();
|
||||
Affine::rotate(r) * horizontal * Affine::rotate(-r)
|
||||
}
|
||||
Some(v) => {
|
||||
let given = v.as_str().map_or_else(|| v.to_string(), str::to_string);
|
||||
let range = format!("from -{SHEAR_AXIS_MAX} to {SHEAR_AXIS_MAX}");
|
||||
return Err(bad("object.shear", format!("axis must be \"horizontal\", \"vertical\" or an angle in degrees {range}, not `{given}`")));
|
||||
}
|
||||
};
|
||||
apply_transform(s, "Shear", ids, about(o, m), p, true)
|
||||
}
|
||||
|
||||
/// The largest angle, either way from horizontal, of the axis `object.shear` takes in degrees.
|
||||
const SHEAR_AXIS_MAX: f64 = 359.0;
|
||||
|
||||
/// The last transform on the selection, with the options `last_transform` keeps for it; an option
|
||||
/// that `p` sets to true or false (a recorded Transform Again's) takes precedence. A Transform
|
||||
/// Each is repeated by running it again (its transform is per object, about each one's bounds).
|
||||
pub(super) fn transform_again(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
check_switches(p, &TRANSFORM_SWITCHES, "object.transformAgain")?;
|
||||
check_switches(p, &["interpolate"], "object.transformAgain")?;
|
||||
if let Some(again) = s.doc()?.last_perspective.clone() {
|
||||
return crate::cmd::distortcmds::transform_again(s, &again);
|
||||
}
|
||||
|
||||
@@ -137,6 +137,24 @@ fn check_carried_scripts(name: &str, bytes: &[u8], path: &str) -> Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The error for a linked file the package would copy with an Export for Screens folder outside
|
||||
/// the read roots in the native document it is or carries.
|
||||
const FOLDER_OUTSIDE: &str = "a linked file's export folder is outside the read roots";
|
||||
|
||||
/// Under read roots, the linked file `name` (`bytes`, as the package writes it) is copied only when
|
||||
/// the native document it is or carries ([`carried_document`]) keeps no Export for Screens folder
|
||||
/// outside them: a file copied as it is, a PDF, `.ai` or EPS file or a native document not
|
||||
/// rewritten, would name it. The error names no file or folder.
|
||||
fn check_carried_folder(name: &str, bytes: &[u8]) -> Result<()> {
|
||||
if crate::file_access::current().is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
match carried_document(name, bytes) {
|
||||
Some(carried) if matches!(super::fileio::with_readable_settings_folder(&carried), std::borrow::Cow::Owned(_)) => Err(bad(C, FOLDER_OUTSIDE)),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The fonts of the type on `pages` of the PDF or `.ai` file `name` (`bytes`, found at `path`);
|
||||
/// none for other files.
|
||||
fn page_fonts(name: &str, bytes: &[u8], path: &str, pages: &PlacedPages) -> BTreeSet<super::fonts::UsedFont> {
|
||||
@@ -363,6 +381,7 @@ impl<'a> Collector<'a> {
|
||||
options.profiles = saved.profiles;
|
||||
options.compress = compressed;
|
||||
options.include_linked = include_linked;
|
||||
let nested = super::fileio::with_readable_settings_folder(&nested);
|
||||
match vectorcraft_format::save_with(&nested, &options) {
|
||||
Ok(rewritten) => bytes = rewritten,
|
||||
Err(e) => self.warn(
|
||||
@@ -381,6 +400,7 @@ impl<'a> Collector<'a> {
|
||||
}
|
||||
}
|
||||
}
|
||||
check_carried_folder(&file.name, &bytes)?;
|
||||
let copy = Copied { name: destination_file.clone(), size: Some(bytes.len() as u64), hash: Some(hash_bytes(&bytes)) };
|
||||
self.copies.insert(found_path.to_string(), copy.clone());
|
||||
local.insert(file.path.clone(), copy);
|
||||
@@ -520,7 +540,9 @@ fn prepare(s: &mut Session, p: &Value) -> Result<Package> {
|
||||
}
|
||||
let root = folder.map(|f| Path::new(f).join(&name));
|
||||
let info = if o.report { Some(super::docinfo::report(s, false)?) } else { None };
|
||||
// The package's document leaves out an Export for Screens folder outside the read roots.
|
||||
let doc = s.doc()?.doc.clone();
|
||||
let doc = if let std::borrow::Cow::Owned(kept) = super::fileio::with_readable_settings_folder(&doc) { std::sync::Arc::new(kept) } else { doc };
|
||||
let links_from = s.doc()?.links_from.clone().unwrap_or_else(|| doc_path.clone());
|
||||
Ok(Package { o, doc_path, links_from, stem, name, root, info, doc })
|
||||
}
|
||||
|
||||
@@ -48,7 +48,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; type gets black fill and no stroke. 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)",
|
||||
"{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. 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)",
|
||||
has_doc,
|
||||
default_paint
|
||||
),
|
||||
@@ -1035,6 +1035,8 @@ fn default_paint(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if !ids.is_empty() {
|
||||
// When every object comes out as it was, the document and its undo history stay as they are.
|
||||
let before = s.doc()?.doc.clone();
|
||||
// A redefined Default Graphic Style gives other art its fills, strokes and effects, placed on each object.
|
||||
let style = super::newart::redefined_default_style(&before).cloned();
|
||||
super::overprint::edit_counted(s, "Default Fill and Stroke", |d| {
|
||||
for id in &ids {
|
||||
let Some(n) = d.node_mut(*id) else { continue };
|
||||
@@ -1045,7 +1047,12 @@ fn default_paint(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
r.style.stroke = Paint::None;
|
||||
}
|
||||
}
|
||||
_ => n.appearance = Appearance::default_art().into(),
|
||||
_ => {
|
||||
n.appearance = match &style {
|
||||
Some(g) => g.appearance_on(n).into_owned().into(),
|
||||
None => Appearance::default_art().into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let kept = super::appearance::capture_series_writes(&before, d, &ids, (true, true), (true, true), false, false);
|
||||
|
||||
File diff suppressed because one or more lines are too long
+144
-13
@@ -36,6 +36,9 @@
|
||||
//! `channel` that the effect doesn't have are refused by `effect.apply` and `effect.setParams`
|
||||
//! themselves ([`check_effect_color`], [`check_effect_channel`]).
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use serde_json::Value;
|
||||
use vectorcraft_apischema::shown_key;
|
||||
|
||||
@@ -43,7 +46,7 @@ use super::{bad, command_specs, find_command};
|
||||
use crate::Result;
|
||||
|
||||
/// What a params description says about the keys of the params object.
|
||||
#[derive(Debug, Default, PartialEq)]
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct ParamKeys<'a> {
|
||||
/// The keys it names.
|
||||
pub keys: Vec<&'a str>,
|
||||
@@ -107,6 +110,8 @@ pub(crate) fn is_key(s: &str) -> bool {
|
||||
|
||||
/// The keys a params description names, or what in it doesn't read as one.
|
||||
pub fn doc_keys(doc: &str) -> std::result::Result<ParamKeys<'_>, String> {
|
||||
#[cfg(test)]
|
||||
PARSES.with(|n| n.set(n.get() + 1));
|
||||
let mut out = ParamKeys::default();
|
||||
let (mut body, mut rest) = object_body(doc)?;
|
||||
let mut entries = split_top(body, ',');
|
||||
@@ -155,7 +160,12 @@ fn named_commands(more: &str) -> impl Iterator<Item = &'static super::CommandSpe
|
||||
/// `None`: any key (a `…` entry naming no command, or a description that doesn't parse, which
|
||||
/// the tests rule out).
|
||||
fn accepted(doc: &'static str, depth: usize) -> Option<Vec<&'static str>> {
|
||||
let parsed = doc_keys(doc).ok()?;
|
||||
resolve(doc, depth, &mut |doc| doc_keys(doc).ok())
|
||||
}
|
||||
|
||||
/// [`accepted`], with `parse` reading each description it reaches.
|
||||
fn resolve(doc: &'static str, depth: usize, parse: &mut dyn FnMut(&'static str) -> Option<ParamKeys<'static>>) -> Option<Vec<&'static str>> {
|
||||
let parsed = parse(doc)?;
|
||||
let mut keys = parsed.keys;
|
||||
for more in parsed.more {
|
||||
let mut named = named_commands(more).peekable();
|
||||
@@ -168,22 +178,120 @@ fn accepted(doc: &'static str, depth: usize) -> Option<Vec<&'static str>> {
|
||||
if UNCHECKED.contains(&spec.id) {
|
||||
return None;
|
||||
}
|
||||
keys.extend(accepted(spec.params, depth + 1)?);
|
||||
keys.extend(resolve(spec.params, depth + 1, parse)?);
|
||||
}
|
||||
}
|
||||
Some(keys)
|
||||
}
|
||||
|
||||
/// What the params description of a built-in command says about its keys, read once per process
|
||||
/// ([`known`]).
|
||||
#[derive(Debug)]
|
||||
struct Known {
|
||||
/// The keys it names itself; none when it doesn't parse.
|
||||
own: Vec<&'static str>,
|
||||
/// [`accepted`] of it.
|
||||
accepted: Option<Vec<&'static str>>,
|
||||
/// [`id_stands_for_ids`] of it.
|
||||
id_stands_for_ids: bool,
|
||||
}
|
||||
|
||||
impl Known {
|
||||
/// [`takes_key`] of the description.
|
||||
fn takes(&self, key: &str) -> bool {
|
||||
self.own.contains(&key) || self.accepted.as_ref().is_some_and(|keys| keys.contains(&key))
|
||||
}
|
||||
}
|
||||
|
||||
/// The place and length of `doc`'s text: a description with the same words elsewhere (a plug-in's)
|
||||
/// has another place.
|
||||
fn text_key(doc: &str) -> (usize, usize) {
|
||||
(doc.as_ptr().addr(), doc.len())
|
||||
}
|
||||
|
||||
/// [`Known`] of each description in `docs`, each one and each one its `…` entries name parsed once.
|
||||
/// A description is left out when one it reaches has a `…` entry naming a plug-in command, whose
|
||||
/// keys change as plug-ins are installed and removed.
|
||||
fn read_descriptions(docs: impl IntoIterator<Item = &'static str>) -> HashMap<(usize, usize), Known> {
|
||||
let names_plugin =
|
||||
|more: &str| more.split_whitespace().any(|w| w.trim_matches(|c: char| !c.is_ascii_alphanumeric()).starts_with(vectorcraft_plugins::PREFIX));
|
||||
let mut parsed: HashMap<(usize, usize), (Option<ParamKeys<'static>>, bool)> = HashMap::new();
|
||||
let mut table = HashMap::new();
|
||||
for doc in docs {
|
||||
if table.contains_key(&text_key(doc)) {
|
||||
continue;
|
||||
}
|
||||
let mut live = false;
|
||||
let mut parse = |doc: &'static str| {
|
||||
let (keys, plugin) = parsed.entry(text_key(doc)).or_insert_with(|| {
|
||||
let keys = doc_keys(doc).ok();
|
||||
let plugin = keys.as_ref().is_some_and(|k| k.more.iter().any(|m| names_plugin(m)));
|
||||
(keys, plugin)
|
||||
});
|
||||
live |= *plugin;
|
||||
keys.clone()
|
||||
};
|
||||
let own = parse(doc).map(|p| p.keys).unwrap_or_default();
|
||||
let accepted = resolve(doc, 0, &mut parse);
|
||||
if live {
|
||||
continue;
|
||||
}
|
||||
let mut known = Known { own, accepted, id_stands_for_ids: false };
|
||||
known.id_stands_for_ids = known.takes("ids") && known.takes("id") && no_required_id_beside_ids(doc);
|
||||
table.insert(text_key(doc), known);
|
||||
}
|
||||
table
|
||||
}
|
||||
|
||||
/// [`Known`] of `doc` when it is the params description of a built-in command.
|
||||
fn known(doc: &str) -> Option<&'static Known> {
|
||||
#[cfg(test)]
|
||||
if UNCACHED.get() {
|
||||
return None;
|
||||
}
|
||||
static TABLE: OnceLock<HashMap<(usize, usize), Known>> = OnceLock::new();
|
||||
TABLE.get_or_init(|| read_descriptions(command_specs().iter().map(|c| c.params))).get(&text_key(doc))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// The times [`doc_keys`] parsed a description on this thread.
|
||||
pub(crate) static PARSES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
/// Whether [`known`] is skipped on this thread ([`uncached`]).
|
||||
static UNCACHED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
}
|
||||
|
||||
/// Whether [`read_descriptions`] keeps what `doc` says.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn read_once(doc: &'static str) -> bool {
|
||||
read_descriptions([doc]).contains_key(&text_key(doc))
|
||||
}
|
||||
|
||||
/// `f`'s result with every description parsed again where it is used, as without [`known`].
|
||||
#[cfg(test)]
|
||||
pub(crate) fn uncached<T>(f: impl FnOnce() -> T) -> T {
|
||||
let before = UNCACHED.replace(true);
|
||||
let out = f();
|
||||
UNCACHED.set(before);
|
||||
out
|
||||
}
|
||||
|
||||
/// Every key the description `doc` takes, those of the commands its `…` entries name included, or
|
||||
/// `None` when that isn't known: it doesn't parse, a `…` entry names no command, or one names a
|
||||
/// command in [`UNCHECKED`].
|
||||
pub(crate) fn accepted_keys(doc: &'static str) -> Option<Vec<&'static str>> {
|
||||
accepted(doc, 0)
|
||||
match known(doc) {
|
||||
Some(known) => known.accepted.clone(),
|
||||
None => accepted(doc, 0),
|
||||
}
|
||||
}
|
||||
|
||||
/// Does the description `doc` name `key` as a parameter (its own keys, and those of the commands
|
||||
/// its `…` entries name)?
|
||||
pub fn takes_key(doc: &'static str, key: &str) -> bool {
|
||||
if let Some(known) = known(doc) {
|
||||
return known.takes(key);
|
||||
}
|
||||
doc_keys(doc).is_ok_and(|parsed| parsed.keys.contains(&key)) || accepted(doc, 0).is_some_and(|keys| keys.contains(&key))
|
||||
}
|
||||
|
||||
@@ -191,12 +299,17 @@ pub fn takes_key(doc: &'static str, key: &str) -> bool {
|
||||
/// (instead of id)}`, `{id} or {ids: […]}`): it names both keys, and no params object of it names
|
||||
/// `ids` beside a required `id`, which is something else (`plugin.run {id, ids?}`: the plug-in's)?
|
||||
pub(crate) fn id_stands_for_ids(doc: &'static str) -> bool {
|
||||
if let Some(known) = known(doc) {
|
||||
return known.id_stands_for_ids;
|
||||
}
|
||||
takes_key(doc, "ids") && takes_key(doc, "id") && no_required_id_beside_ids(doc)
|
||||
}
|
||||
|
||||
/// No params object of `doc` names `ids` beside a required `id`.
|
||||
fn no_required_id_beside_ids(doc: &str) -> bool {
|
||||
fn head(alternative: &str) -> &str {
|
||||
alternative.split([':', '=', '(']).next().unwrap_or_default().trim()
|
||||
}
|
||||
if !takes_key(doc, "ids") || !takes_key(doc, "id") {
|
||||
return false;
|
||||
}
|
||||
let mut rest = doc;
|
||||
while let Ok((body, after)) = object_body(rest) {
|
||||
let entries = split_top(body, ',');
|
||||
@@ -249,20 +362,33 @@ pub fn check_keys(id: &str, doc: &'static str, params: &Value) -> Result<()> {
|
||||
if given.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let Some(keys) = accepted(doc, 0) else { return Ok(()) };
|
||||
let live;
|
||||
let keys = match known(doc) {
|
||||
Some(known) => known.accepted.as_deref(),
|
||||
None => {
|
||||
live = accepted(doc, 0);
|
||||
live.as_deref()
|
||||
}
|
||||
};
|
||||
let Some(keys) = keys else { return Ok(()) };
|
||||
match given.keys().find(|k| !keys.contains(&k.as_str())) {
|
||||
Some(key) => Err(unknown(id, key, &keys)),
|
||||
Some(key) => Err(unknown(id, key, keys)),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Parameters a command takes instead of one another: (command, key, other key). Giving both,
|
||||
/// neither null, is a parameter error ([`check_exclusive_keys`]).
|
||||
const EXCLUSIVE_KEYS: &[(&str, &str, &str)] = &[("addon.pathtools.cornerSet", "items", "ids"), ("addon.pathtools.cornerRemove", "items", "ids")];
|
||||
const EXCLUSIVE_KEYS: &[(&str, &str, &str)] = &[
|
||||
("addon.pathtools.cornerSet", "items", "ids"),
|
||||
("addon.pathtools.cornerRemove", "items", "ids"),
|
||||
("links.unembed", "id", "ids"),
|
||||
("links.unembed", "path", "folder"),
|
||||
];
|
||||
|
||||
/// `params` of command `id` give at most one of each pair in [`EXCLUSIVE_KEYS`], or the parameter
|
||||
/// error naming the pair.
|
||||
fn check_exclusive_keys(id: &str, params: &Value) -> Result<()> {
|
||||
pub(crate) fn check_exclusive_keys(id: &str, params: &Value) -> Result<()> {
|
||||
let given = |key: &str| params.get(key).filter(|v| !v.is_null());
|
||||
for (_, key, other) in EXCLUSIVE_KEYS.iter().filter(|(c, ..)| *c == id) {
|
||||
if given(key).is_some() && given(other).is_some() {
|
||||
@@ -928,9 +1054,14 @@ fn check_params_in(id: &str, params: &Value, in_batch: bool) -> Result<()> {
|
||||
crate::schemas::check(spec, params, false)?;
|
||||
}
|
||||
if matches!(id, "command.batch" | "action.batch") && !in_batch {
|
||||
for step in params.get("commands").and_then(Value::as_array).into_iter().flatten() {
|
||||
for (i, step) in params.get("commands").and_then(Value::as_array).into_iter().flatten().enumerate() {
|
||||
if let Some(step_id) = step.get("command").and_then(Value::as_str) {
|
||||
check_params_in(step_id, step.get("params").unwrap_or(&Value::Null), true)?;
|
||||
let checked = check_params_in(step_id, step.get("params").unwrap_or(&Value::Null), true);
|
||||
// An `action.batch` names the step it refuses by its place, from 1, as its own checks and its steps' errors do.
|
||||
match checked {
|
||||
Err(e) if id == "action.batch" => return Err(bad(id, super::fileio::action_step(i, step_id, &e.to_string()))),
|
||||
checked => checked?,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+154
-10
@@ -1,10 +1,10 @@
|
||||
//! Path editing commands (used by the Pen and Direct Selection tools and Object → Path).
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind, Scaling, Selection};
|
||||
use vectorcraft_doc::{AnchorRef, Document, Node, NodeId, NodeKind, Scaling, Selection};
|
||||
use vectorcraft_geom::{Anchor, AnchorKind, Anchors, PathData, Point, SubPath, Vec2};
|
||||
|
||||
use super::create::anchor_from_json;
|
||||
@@ -41,7 +41,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Anchors",
|
||||
[],
|
||||
None,
|
||||
"{dx, dy, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles)} move direct-selected anchors (whole paths if fully selected); refused while an object of a symbol instance's art is selected",
|
||||
"{dx, dy, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), interpolate?: bool (Interpolate Control Points: the handles of each segment with one moved end are re-mapped by the turn, scale and move that take its old ends to its new ends; default: prefs interpolateControlPoints)} move direct-selected anchors (whole paths if fully selected); refused while an object of a symbol instance's art is selected",
|
||||
has_selection,
|
||||
move_anchors
|
||||
),
|
||||
@@ -245,28 +245,43 @@ fn close(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
pub(crate) fn move_anchors(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let d = Vec2::new(number_or(p, "dx", 0.0, "path.moveAnchors")?, number_or(p, "dy", 0.0, "path.moveAnchors")?);
|
||||
check_switches(p, &["patterns"], "path.moveAnchors")?;
|
||||
check_switches(p, &["patterns", "interpolate"], "path.moveAnchors")?;
|
||||
// An object selected in a symbol instance's art stays where the symbol puts it.
|
||||
super::edit::refuse_symbol_part(s)?;
|
||||
// Objects selected whole move as objects, and their pattern tiles move with them when
|
||||
// `patterns` (default: General › Transform Pattern Tiles) is on.
|
||||
let whole = s.doc()?.selection.whole();
|
||||
let sc = Scaling { patterns: super::object::transform_patterns(s, p, &whole)?, ..Scaling::default() };
|
||||
transform_anchors(s, "Move", vectorcraft_geom::Affine::translate(d), sc)?;
|
||||
let interpolate = interpolates_handles(s, p, "path.moveAnchors")?;
|
||||
transform_anchors(s, "Move", vectorcraft_geom::Affine::translate(d), sc, interpolate)?;
|
||||
// Transform Again repeats a move that moved something; a drag records it when it commits.
|
||||
let st = s.doc_mut()?;
|
||||
if st.interaction.is_none() && (d.x != 0.0 || d.y != 0.0) {
|
||||
let options = json!({ "copy": false, "patterns": sc.patterns });
|
||||
let options = json!({ "copy": false, "patterns": sc.patterns, "interpolate": interpolate });
|
||||
st.last_transform = Some(crate::LastTransform::Matrix(vectorcraft_geom::Affine::translate(d), options));
|
||||
st.last_perspective = None;
|
||||
}
|
||||
ok()
|
||||
}
|
||||
|
||||
/// Interpolate Control Points: does a move of direct-selected anchors re-map the handles of the
|
||||
/// segments beside them (`interpolate` param, else General › Interpolate Control Points When
|
||||
/// Moving Anchors)? Noted in the journal, so a replay re-maps them alike whatever the preference
|
||||
/// is then. A saved step without `interpolate` ([`Session::replay`]) was recorded before the
|
||||
/// preference existed, so it moves the handles as it did then, without re-mapping them.
|
||||
pub(crate) fn interpolates_handles(s: &mut Session, p: &Value, cmd: &str) -> Result<bool> {
|
||||
let default = s.prefs.interpolate_control_points && !s.replaying();
|
||||
let on = switch_or(p, "interpolate", default, cmd)?;
|
||||
s.note_journal("interpolate", json!(on));
|
||||
Ok(on)
|
||||
}
|
||||
|
||||
/// Apply `xf` to the direct-selected anchors, their handles with them, and (with `sc`) to the
|
||||
/// objects selected whole (those with no entry in the selection's `anchors`). An object inside
|
||||
/// another selected object, such as a path in a selected group, moves once, with that object.
|
||||
pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_geom::Affine, sc: Scaling) -> Result<()> {
|
||||
/// When `xf` is a move and `interpolate` is on, the handles of each segment with one moved end
|
||||
/// are re-mapped ([`move_interpolating_handles`]).
|
||||
pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_geom::Affine, sc: Scaling, interpolate: bool) -> Result<()> {
|
||||
let sel = s.doc()?.selection.clone();
|
||||
let ids = super::edit::outermost(&s.doc()?.doc, sel.objects.clone());
|
||||
let c = xf.as_coeffs();
|
||||
@@ -277,9 +292,15 @@ pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_ge
|
||||
match sel.anchors.get(id) {
|
||||
Some(set) => {
|
||||
let path = path_mut(doc, *id)?;
|
||||
for &(si, ai) in set {
|
||||
if let Some(a) = path.anchor_mut(si, ai) {
|
||||
*a = a.transform(xf);
|
||||
// Only an exact move takes the interpolating path: a near-identity scale or
|
||||
// turn still transforms the anchors as asked.
|
||||
if interpolate && c[..4] == [1.0, 0.0, 0.0, 1.0] {
|
||||
move_interpolating_handles(path, set, delta);
|
||||
} else {
|
||||
for &(si, ai) in set {
|
||||
if let Some(a) = path.anchor_mut(si, ai) {
|
||||
*a = a.transform(xf);
|
||||
}
|
||||
}
|
||||
}
|
||||
// A pixel-aligned path, or the pixel-aligned compound path that holds it, snaps
|
||||
@@ -307,6 +328,129 @@ pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_ge
|
||||
})
|
||||
}
|
||||
|
||||
/// Move the anchors `set` of `path` by `d`, their handles with them, then re-map the two handles
|
||||
/// of each segment with exactly one moved end by the map that takes the segment's old ends to its
|
||||
/// new ends: a turn, a uniform scale and a move. Between two corner anchors the segment keeps its
|
||||
/// shape relative to its ends. A segment with both ends moved, or with its ends at the same place
|
||||
/// before or after the move, moves as it does without the preference. A smooth anchor keeps its
|
||||
/// two handles in line ([`line_up_handles`]).
|
||||
fn move_interpolating_handles(path: &mut PathData, set: &BTreeSet<AnchorRef>, d: Vec2) {
|
||||
// (subpath, anchor, outgoing handle?, new position)
|
||||
let mut placed: Vec<(usize, usize, bool, Point)> = Vec::new();
|
||||
if d != Vec2::ZERO {
|
||||
// Only the segments beside a moved anchor can have one moved end: (subpath, first anchor).
|
||||
let mut segments: BTreeSet<AnchorRef> = BTreeSet::new();
|
||||
for &(si, ai) in set {
|
||||
let Some(sp) = path.subpaths.get(si) else { continue };
|
||||
let n = sp.anchors.len();
|
||||
if ai >= n || n < 2 {
|
||||
continue;
|
||||
}
|
||||
if ai > 0 || sp.closed {
|
||||
segments.insert((si, (ai + n - 1) % n));
|
||||
}
|
||||
if ai + 1 < n || sp.closed {
|
||||
segments.insert((si, ai));
|
||||
}
|
||||
}
|
||||
for (si, from) in segments {
|
||||
let Some(sp) = path.subpaths.get(si) else { continue };
|
||||
let to = (from + 1) % sp.anchors.len().max(1);
|
||||
let (moved_from, moved_to) = (set.contains(&(si, from)), set.contains(&(si, to)));
|
||||
if moved_from == moved_to {
|
||||
continue;
|
||||
}
|
||||
let (Some(a), Some(b)) = (sp.anchors.get(from), sp.anchors.get(to)) else { continue };
|
||||
let old = b.p - a.p;
|
||||
let len2 = old.hypot2();
|
||||
if len2 <= 1e-12 || !len2.is_finite() {
|
||||
continue;
|
||||
}
|
||||
let start = if moved_from { a.p + d } else { a.p };
|
||||
let end = if moved_to { b.p + d } else { b.p };
|
||||
let new = end - start;
|
||||
// A move that puts the two ends at the same place would collapse both handles onto
|
||||
// them, past recovering by moving back.
|
||||
if new.hypot2() <= 1e-12 {
|
||||
continue;
|
||||
}
|
||||
// `new / old` as complex numbers: the turn and scale between the two chords.
|
||||
let (re, im) = ((new.x * old.x + new.y * old.y) / len2, (new.y * old.x - new.x * old.y) / len2);
|
||||
let map = |h: Point| {
|
||||
let v = h - a.p;
|
||||
start + Vec2::new(v.x * re - v.y * im, v.x * im + v.y * re)
|
||||
};
|
||||
// A retracted handle goes to its anchor's new place exactly: mapped, it could land a
|
||||
// rounding error away, which `line_up_handles` would read as a direction.
|
||||
let h_out = if a.h_out == a.p { start } else { map(a.h_out) };
|
||||
let h_in = if b.h_in == b.p { end } else { map(b.h_in) };
|
||||
if h_out.is_finite() && h_in.is_finite() {
|
||||
placed.push((si, from, true, h_out));
|
||||
placed.push((si, to, false, h_in));
|
||||
}
|
||||
}
|
||||
}
|
||||
for &(si, ai) in set {
|
||||
if let Some(a) = path.anchor_mut(si, ai) {
|
||||
a.translate(d);
|
||||
}
|
||||
}
|
||||
// For each anchor with a re-mapped handle: its handles as the plain move left them, and which
|
||||
// of them (outgoing, incoming) were re-mapped.
|
||||
let mut touched: BTreeMap<AnchorRef, (Point, Point, bool, bool)> = BTreeMap::new();
|
||||
for &(si, ai, out, pos) in &placed {
|
||||
if let Some(a) = path.anchor_mut(si, ai) {
|
||||
let e = touched.entry((si, ai)).or_insert((a.h_out, a.h_in, false, false));
|
||||
if out {
|
||||
a.h_out = pos;
|
||||
e.2 = true;
|
||||
} else {
|
||||
a.h_in = pos;
|
||||
e.3 = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
for ((si, ai), (rigid_out, rigid_in, out, inn)) in touched {
|
||||
let Some(a) = path.anchor_mut(si, ai) else { continue };
|
||||
if a.kind == AnchorKind::Smooth && !line_up_handles(a, out, inn) {
|
||||
a.h_out = rigid_out;
|
||||
a.h_in = rigid_in;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Put the handles of the smooth anchor `a` back in line after [`move_interpolating_handles`]
|
||||
/// re-mapped its outgoing handle (`out`), its incoming handle (`inn`) or both. A re-mapped handle
|
||||
/// turns to point away from the other handle, at its own new length; when both were re-mapped,
|
||||
/// both point along the mean of their directions. A retracted handle is left as it is. False when
|
||||
/// both were re-mapped to point the same way, which has no mean direction: the caller then moves
|
||||
/// both handles with the anchor.
|
||||
fn line_up_handles(a: &mut Anchor, out: bool, inn: bool) -> bool {
|
||||
let (v_out, v_in) = (a.h_out - a.p, a.h_in - a.p);
|
||||
let (l_out, l_in) = (v_out.hypot(), v_in.hypot());
|
||||
if l_out <= 0.0 || l_in <= 0.0 || !l_out.is_finite() || !l_in.is_finite() {
|
||||
return true;
|
||||
}
|
||||
let dir = match (out, inn) {
|
||||
(true, true) => v_out / l_out - v_in / l_in,
|
||||
(true, false) => -v_in / l_in,
|
||||
(false, true) => v_out / l_out,
|
||||
(false, false) => return true,
|
||||
};
|
||||
let l = dir.hypot();
|
||||
if l <= 1e-12 || !l.is_finite() {
|
||||
return false;
|
||||
}
|
||||
let dir = dir / l;
|
||||
if out {
|
||||
a.h_out = a.p + dir * l_out;
|
||||
}
|
||||
if inn {
|
||||
a.h_in = a.p - dir * l_in;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn set_handle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = object_param(p, "id", "path.setHandle")?.ok_or_else(|| bad("path.setHandle", "missing id"))?;
|
||||
let si = usize_opt(p, "subpath", "path.setHandle")?.unwrap_or(0);
|
||||
|
||||
@@ -27,7 +27,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Unite",
|
||||
["Window", "Pathfinder"],
|
||||
None,
|
||||
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}",
|
||||
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids, warning?: when a selected object is or holds a line or another open path that encloses no area once closed, and so does not change the result's shape (when such a path leaves the result empty, as in Intersect, the error says so)}",
|
||||
has_selection,
|
||||
|s, p| run_pf(s, p, PathfinderOp::Unite)
|
||||
),
|
||||
@@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Minus Front",
|
||||
["Window", "Pathfinder"],
|
||||
None,
|
||||
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}",
|
||||
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids, warning?: when a selected object is or holds a line or another open path that encloses no area once closed, and so does not change the result's shape (when such a path leaves the result empty, as in Intersect, the error says so)}",
|
||||
has_selection,
|
||||
|s, p| run_pf(s, p, PathfinderOp::MinusFront)
|
||||
),
|
||||
@@ -45,7 +45,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Intersect",
|
||||
["Window", "Pathfinder"],
|
||||
None,
|
||||
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}",
|
||||
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids, warning?: when a selected object is or holds a line or another open path that encloses no area once closed, and so does not change the result's shape (when such a path leaves the result empty, as in Intersect, the error says so)}",
|
||||
has_selection,
|
||||
|s, p| run_pf(s, p, PathfinderOp::Intersect)
|
||||
),
|
||||
@@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Exclude",
|
||||
["Window", "Pathfinder"],
|
||||
None,
|
||||
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}",
|
||||
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids, warning?: when a selected object is or holds a line or another open path that encloses no area once closed, and so does not change the result's shape (when such a path leaves the result empty, as in Intersect, the error says so)}",
|
||||
has_selection,
|
||||
|s, p| run_pf(s, p, PathfinderOp::Exclude)
|
||||
),
|
||||
@@ -108,7 +108,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Minus Back",
|
||||
["Window", "Pathfinder"],
|
||||
None,
|
||||
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}",
|
||||
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids, warning?: when a selected object is or holds a line or another open path that encloses no area once closed, and so does not change the result's shape (when such a path leaves the result empty, as in Intersect, the error says so)}",
|
||||
has_selection,
|
||||
|s, p| run_pf(s, p, PathfinderOp::MinusBack)
|
||||
),
|
||||
@@ -285,6 +285,37 @@ impl Style {
|
||||
}
|
||||
}
|
||||
|
||||
/// The Shape Mode commands' warning, which the status bar shows, when a selected object is or holds
|
||||
/// a line or another open path that encloses no area once closed, and so does not change the result's
|
||||
/// shape (the result still takes its paint from the frontmost object, as without the warning).
|
||||
pub const SHAPE_MODE_OPEN_PATH_NO_AREA: &str = "a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first";
|
||||
|
||||
/// `path` has an open subpath that encloses no area once closed (a straight line, or an evenodd
|
||||
/// contour traced twice), by the area its fill rule gives, so a self-crossing path whose signed
|
||||
/// area is zero (a bow tie) still counts as enclosing area, as Divide measures it.
|
||||
fn has_open_subpath_without_area(path: &PathData, rule: FillRule) -> bool {
|
||||
path.subpaths.iter().filter(|sp| !sp.closed).any(|sp| {
|
||||
// A point or a straight two-anchor line needs no area measurement.
|
||||
if sp.anchors.len() < 2 || (sp.anchors.len() == 2 && sp.anchors.iter().all(|a| a.h_in == a.p && a.h_out == a.p)) {
|
||||
return true;
|
||||
}
|
||||
let mut closed = sp.clone();
|
||||
closed.closed = true;
|
||||
// The signed-area test alone only holds for nonzero: evenodd can fill nothing where the
|
||||
// signed area is not zero (a contour traced twice).
|
||||
!(rule == FillRule::NonZero && po::encloses_area(sp)) && po::area(&PathData::single(closed), rule) <= 0.0
|
||||
})
|
||||
}
|
||||
|
||||
/// The area `path` fills with its open subpaths closed, as the Shape Modes fill it.
|
||||
fn closed_area(path: &PathData, rule: FillRule) -> f64 {
|
||||
let mut closed = path.clone();
|
||||
for sp in &mut closed.subpaths {
|
||||
sp.closed = true;
|
||||
}
|
||||
po::area(&closed, rule)
|
||||
}
|
||||
|
||||
/// All subpaths of a path or compound path node, in document coordinates, with its fill rule.
|
||||
pub(crate) fn node_path(n: &Node) -> Option<(PathData, FillRule)> {
|
||||
match &n.kind {
|
||||
@@ -685,8 +716,9 @@ fn run_pf(s: &mut Session, p: &Value, op: PathfinderOp) -> Result<Value> {
|
||||
let keeps_hidden = matches!(op, PathfinderOp::Intersect | PathfinderOp::MinusFront | PathfinderOp::MinusBack | PathfinderOp::Crop);
|
||||
let label = pf_label(op);
|
||||
let options = pf_options(s, p, &format!("object.pathfinder.{}", pf_id(op)))?;
|
||||
let ids = s.edit(label, |d, sel| {
|
||||
let (ids, no_area) = s.edit(label, |d, sel| {
|
||||
// Build the stack (back → front); names are separate from paint/style identity.
|
||||
let mut no_area = false;
|
||||
let mut styles: Vec<Style> = vec![];
|
||||
let mut shapes: Vec<po::Shape> = vec![];
|
||||
let mut names: Vec<Option<String>> = vec![];
|
||||
@@ -759,6 +791,7 @@ fn run_pf(s: &mut Session, p: &Value, op: PathfinderOp) -> Result<Value> {
|
||||
continue;
|
||||
};
|
||||
let top = *top;
|
||||
no_area = no_area || parts.iter().any(|(_, p, r)| has_open_subpath_without_area(p, *r));
|
||||
let refs: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, p, r)| (p, *r)).collect();
|
||||
push(
|
||||
po::try_unite_all_with(&refs, options.precision).map_err(|e| EngineError::Other(e.to_string()))?,
|
||||
@@ -771,6 +804,7 @@ fn run_pf(s: &mut Session, p: &Value, op: PathfinderOp) -> Result<Value> {
|
||||
} else {
|
||||
for (l, clip) in &lv {
|
||||
if let Some((p, r)) = node_path(l) {
|
||||
no_area = no_area || (shape_mode && has_open_subpath_without_area(&p, r));
|
||||
push(p, r, style_of(l), n.name.clone().or_else(|| l.name.clone()), clip.as_deref(), clip.is_some())?;
|
||||
}
|
||||
}
|
||||
@@ -798,6 +832,21 @@ fn run_pf(s: &mut Session, p: &Value, op: PathfinderOp) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
if results.iter().all(|r| r.path.is_empty()) {
|
||||
// The lines left the result empty when the other shapes give a result without them, or
|
||||
// when nothing else is selected. A closed shape without area stays among the others.
|
||||
let lines_emptied = no_area && {
|
||||
let kept: Vec<po::Shape> = shapes
|
||||
.iter()
|
||||
.filter(|s| closed_area(&s.path, s.rule) > 0.0 || !has_open_subpath_without_area(&s.path, s.rule))
|
||||
.cloned()
|
||||
.collect();
|
||||
kept.is_empty() || po::pathfinder_with(op, &kept, options.precision).iter().any(|r| !r.path.is_empty())
|
||||
};
|
||||
if lines_emptied {
|
||||
return Err(EngineError::Other(format!(
|
||||
"{label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first"
|
||||
)));
|
||||
}
|
||||
return Err(EngineError::Other(format!("{label} produced an empty result")));
|
||||
}
|
||||
let new_node = if shape_mode {
|
||||
@@ -833,9 +882,13 @@ fn run_pf(s: &mut Session, p: &Value, op: PathfinderOp) -> Result<Value> {
|
||||
};
|
||||
let nid = d.wrap(&roots, |_| new_node)?;
|
||||
sel.set([nid]);
|
||||
Ok(vec![nid])
|
||||
Ok((vec![nid], no_area))
|
||||
})?;
|
||||
Ok(ids_json(&ids))
|
||||
let mut out = ids_json(&ids);
|
||||
if no_area {
|
||||
out["warning"] = json!(SHAPE_MODE_OPEN_PATH_NO_AREA);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
// ---------- Trap ----------
|
||||
|
||||
@@ -12,7 +12,7 @@ use vectorcraft_geom::{PathData, Point, Rect, SubPath, shapes};
|
||||
|
||||
use super::Result;
|
||||
use super::clipboard::Clipboard;
|
||||
use super::clipboard::resources::SwatchChoices;
|
||||
use super::clipboard::resources::{Imported, SwatchChoices};
|
||||
use super::swatchlib::LibraryInfo;
|
||||
|
||||
/// A built-in pattern library: a stable id, its menu name and the function that adds its patterns.
|
||||
@@ -87,12 +87,67 @@ pub fn swatch_source(w: &Swatch) -> Option<Arc<Document>> {
|
||||
|
||||
/// 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`.
|
||||
pub(crate) fn import(d: &mut Document, lib: &Document, name: &str) -> Result<String> {
|
||||
/// 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.
|
||||
/// 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)>)> {
|
||||
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)?;
|
||||
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()
|
||||
};
|
||||
let added = d
|
||||
.swatches_iter()
|
||||
.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))
|
||||
}
|
||||
|
||||
/// Pattern `name` of `lib` with the resources its art uses, as an object painted with it is copied.
|
||||
fn gather(lib: &Document, name: &str) -> Clipboard {
|
||||
let user = Node::path(NodeId(0), shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)), Appearance::basic(pattern_paint(name), Paint::None, 0.0));
|
||||
let imported = Clipboard::gather(lib, vec![user]).import_into(d, &SwatchChoices::default(), false)?;
|
||||
Clipboard::gather(lib, vec![user])
|
||||
}
|
||||
|
||||
/// The name pattern `name` has in the document `imported` went into.
|
||||
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());
|
||||
Ok(renamed.unwrap_or(name).to_string())
|
||||
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> {
|
||||
let gathered = gather(lib, name);
|
||||
let only_pattern = gathered.patterns.len() == 1
|
||||
&& gathered.symbols.is_empty()
|
||||
&& gathered.swatches.is_empty()
|
||||
&& gathered.graphic_styles.is_empty()
|
||||
&& gathered.char_styles.is_empty()
|
||||
&& gathered.para_styles.is_empty()
|
||||
&& gathered.brushes.is_empty()
|
||||
&& gathered.images.is_empty();
|
||||
if only_pattern {
|
||||
return existing_pattern(d, lib, name);
|
||||
}
|
||||
// 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)?;
|
||||
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;
|
||||
}
|
||||
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))
|
||||
}
|
||||
|
||||
/// The pattern of `d` that is pattern `name` of library `lib`: the same tile options and art under
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -3,8 +3,8 @@
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
use super::super::utf16_order_without_mark;
|
||||
use super::{Point, Rect, Result, bad, bool_or, fileio, shapes, str_param};
|
||||
use super::super::{text_param, utf16_order_without_mark};
|
||||
use super::{Point, Rect, Result, bad, fileio, shapes, switch_or};
|
||||
|
||||
/// Text files as `file.place` reports them (not a format `document.open` reads).
|
||||
pub(super) const FORMAT: fileio::Format = fileio::Format {
|
||||
@@ -22,13 +22,68 @@ pub(super) const FORMAT: fileio::Format = fileio::Format {
|
||||
/// document may give.
|
||||
pub(super) const MAX_TEXT: usize = 4 << 20;
|
||||
|
||||
/// A character set of Text Import Options (`text.characterSet`).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
enum CharacterSet {
|
||||
/// UTF-8, or UTF-16 with or without a byte-order mark ([`decode`]).
|
||||
#[default]
|
||||
Unicode,
|
||||
/// The platform's 8-bit character set: Windows-1252, or Mac Roman on a Mac.
|
||||
Ansi,
|
||||
ShiftJis,
|
||||
Gb2312,
|
||||
ChineseBig5,
|
||||
Cyrillic,
|
||||
Gb18030,
|
||||
Greek,
|
||||
Turkish,
|
||||
Baltic,
|
||||
CentralEuropean,
|
||||
}
|
||||
|
||||
/// Each character set by its `text.characterSet` value.
|
||||
const CHARACTER_SETS: [(&str, CharacterSet); 11] = [
|
||||
("unicode", CharacterSet::Unicode),
|
||||
("ansi", CharacterSet::Ansi),
|
||||
("shiftJis", CharacterSet::ShiftJis),
|
||||
("gb2312", CharacterSet::Gb2312),
|
||||
("chineseBig5", CharacterSet::ChineseBig5),
|
||||
("cyrillic", CharacterSet::Cyrillic),
|
||||
("gb18030", CharacterSet::Gb18030),
|
||||
("greek", CharacterSet::Greek),
|
||||
("turkish", CharacterSet::Turkish),
|
||||
("baltic", CharacterSet::Baltic),
|
||||
("centralEuropean", CharacterSet::CentralEuropean),
|
||||
];
|
||||
|
||||
impl CharacterSet {
|
||||
/// The Encoding Standard decoder of a set other than Unicode and ANSI, for a file from a Mac
|
||||
/// when `mac`: GB2312 reads as GBK, Cyrillic as windows-1251 (x-mac-cyrillic on a Mac), and
|
||||
/// Greek, Turkish, Baltic and Central European as windows-1253, 1254, 1257 and 1250 on both
|
||||
/// platforms.
|
||||
fn encoding(self, mac: bool) -> Option<&'static encoding_rs::Encoding> {
|
||||
Some(match self {
|
||||
Self::Unicode | Self::Ansi => return None,
|
||||
Self::ShiftJis => encoding_rs::SHIFT_JIS,
|
||||
Self::Gb2312 => encoding_rs::GBK,
|
||||
Self::ChineseBig5 => encoding_rs::BIG5,
|
||||
Self::Cyrillic if mac => encoding_rs::X_MAC_CYRILLIC,
|
||||
Self::Cyrillic => encoding_rs::WINDOWS_1251,
|
||||
Self::Gb18030 => encoding_rs::GB18030,
|
||||
Self::Greek => encoding_rs::WINDOWS_1253,
|
||||
Self::Turkish => encoding_rs::WINDOWS_1254,
|
||||
Self::Baltic => encoding_rs::WINDOWS_1257,
|
||||
Self::CentralEuropean => encoding_rs::WINDOWS_1250,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Text Import Options (`file.place`'s `text` param).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub(super) struct TextOptions {
|
||||
/// Decode as the platform's 8-bit character set (Windows-1252 or Mac Roman) instead of
|
||||
/// Unicode.
|
||||
ansi: bool,
|
||||
/// The file comes from a Mac (its 8-bit character set is Mac Roman).
|
||||
/// The character set the file's bytes are decoded as.
|
||||
character_set: CharacterSet,
|
||||
/// The file comes from a Mac (its ANSI set is Mac Roman, its Cyrillic set x-mac-cyrillic).
|
||||
mac: bool,
|
||||
/// Join the lines of each block of text (blank lines end paragraphs).
|
||||
remove_line_returns: bool,
|
||||
@@ -45,11 +100,13 @@ impl TextOptions {
|
||||
if !t.is_object() {
|
||||
return Err(bad(cmd, "text must be {characterSet?, platform?, removeLineReturns?, removeParagraphReturns?, replaceSpaces?}"));
|
||||
}
|
||||
let choice = |key: &str, values: [&str; 2]| match str_param(t, key) {
|
||||
None => Ok(false),
|
||||
Some(v) if v == values[0] => Ok(false),
|
||||
Some(v) if v == values[1] => Ok(true),
|
||||
Some(v) => Err(bad(cmd, format!("text.{key} `{v}`: use \"{}\" or \"{}\"", values[0], values[1]))),
|
||||
// The index of `text[key]` in `values`; 0 when it is omitted or null.
|
||||
let choice = |key: &str, values: &[&str]| -> Result<usize> {
|
||||
let Some(v) = text_param(t, key, cmd)? else { return Ok(0) };
|
||||
values.iter().position(|x| *x == v).ok_or_else(|| {
|
||||
let (last, rest) = values.split_last().map_or(("", &[][..]), |(last, rest)| (*last, rest));
|
||||
bad(cmd, format!("text.{key} `{v}`: use \"{}\" or \"{}\"", rest.join("\", \""), last))
|
||||
})
|
||||
};
|
||||
let spaces_to_tab = match t.get("replaceSpaces") {
|
||||
None | Some(Value::Null) => None,
|
||||
@@ -58,11 +115,12 @@ impl TextOptions {
|
||||
as usize,
|
||||
),
|
||||
};
|
||||
let set = choice("characterSet", &CHARACTER_SETS.map(|(name, _)| name))?;
|
||||
Ok(Self {
|
||||
ansi: choice("characterSet", ["unicode", "ansi"])?,
|
||||
mac: choice("platform", ["windows", "mac"])?,
|
||||
remove_line_returns: bool_or(t, "removeLineReturns", false),
|
||||
remove_paragraph_returns: bool_or(t, "removeParagraphReturns", false),
|
||||
character_set: CHARACTER_SETS.get(set).map_or(CharacterSet::Unicode, |(_, s)| *s),
|
||||
mac: choice("platform", &["windows", "mac"])? == 1,
|
||||
remove_line_returns: switch_or(t, "removeLineReturns", false, cmd)?,
|
||||
remove_paragraph_returns: switch_or(t, "removeParagraphReturns", false, cmd)?,
|
||||
spaces_to_tab,
|
||||
})
|
||||
}
|
||||
@@ -80,10 +138,15 @@ pub(super) fn import(bytes: &[u8], o: TextOptions, cmd: &str) -> Result<String>
|
||||
/// `bytes` as text: Unicode (UTF-8, or UTF-16 with a byte-order mark, or without one when the
|
||||
/// file has an even length, reads as valid UTF-16 with no NUL character in the byte order
|
||||
/// [`utf16_order_without_mark`] gives; bytes that aren't UTF-8 are read as the platform's 8-bit
|
||||
/// set), or the platform's 8-bit character set.
|
||||
/// set), the platform's 8-bit character set, or another set's decoder
|
||||
/// ([`CharacterSet::encoding`]), which reads a byte-order mark as ordinary bytes and a malformed
|
||||
/// sequence as U+FFFD.
|
||||
fn decode(bytes: &[u8], o: TextOptions) -> String {
|
||||
if let Some(encoding) = o.character_set.encoding(o.mac) {
|
||||
return encoding.decode_without_bom_handling(bytes).0.into_owned();
|
||||
}
|
||||
let eight_bit = |b: &[u8]| -> String { b.iter().map(|&c| if o.mac { mac_roman(c) } else { windows_1252(c) }).collect() };
|
||||
if o.ansi {
|
||||
if o.character_set == CharacterSet::Ansi {
|
||||
return eight_bit(bytes);
|
||||
}
|
||||
let utf16 = |rest: &[u8], le: bool| {
|
||||
@@ -278,22 +341,76 @@ mod tests {
|
||||
assert_eq!(decode(&[0xFF, 0xFE, b'h', 0, 0xE9, 0], unicode), "hé", "UTF-16 LE");
|
||||
assert_eq!(decode(&[0xFE, 0xFF, 0, b'h', 0x20, 0xAC], unicode), "h€", "UTF-16 BE");
|
||||
assert_eq!(decode(&[b'c', b'a', b'f', 0xE9, 0x80], unicode), "café€", "not UTF-8: Windows-1252");
|
||||
let ansi = TextOptions { ansi: true, ..TextOptions::default() };
|
||||
let ansi = TextOptions { character_set: CharacterSet::Ansi, ..TextOptions::default() };
|
||||
assert_eq!(decode(&[0x93, b'q', 0x94, 0xE9], ansi), "“q”é");
|
||||
let mac = TextOptions { ansi: true, mac: true, ..TextOptions::default() };
|
||||
let mac = TextOptions { character_set: CharacterSet::Ansi, mac: true, ..TextOptions::default() };
|
||||
assert_eq!(decode(&[0xD2, b'q', 0xD3, 0x8E, 0xA5, 0xDB], mac), "“q”é•€");
|
||||
}
|
||||
|
||||
/// The other character sets decode by their Encoding Standard decoders: the platform matters
|
||||
/// for Cyrillic alone, a byte-order mark is read as ordinary bytes, and a malformed sequence
|
||||
/// reads as U+FFFD.
|
||||
#[test]
|
||||
fn decodes_the_other_character_sets() {
|
||||
let cases: [(CharacterSet, &[u8], &str); 9] = [
|
||||
(CharacterSet::ShiftJis, &[0x93, 0xFA, 0x96, 0x7B], "日本"),
|
||||
(CharacterSet::Gb2312, &[0xD6, 0xD0, 0xCE, 0xC4], "中文"),
|
||||
(CharacterSet::ChineseBig5, &[0xA4, 0xA4, 0xA4, 0xE5], "中文"),
|
||||
(CharacterSet::Cyrillic, &[0xCF, 0xF0, 0xE8, 0xE2, 0xE5, 0xF2], "Привет"),
|
||||
(CharacterSet::Gb18030, &[0x95, 0x32, 0x82, 0x36], "\u{20000}"),
|
||||
(CharacterSet::Greek, &[0xC5, 0xEB, 0xEB, 0xDC, 0xE4, 0xE1], "Ελλάδα"),
|
||||
(CharacterSet::Turkish, &[0xDD, 0x73, 0x74], "İst"),
|
||||
(CharacterSet::Baltic, &[0x52, 0xEE, 0x67, 0x61], "Rīga"),
|
||||
(CharacterSet::CentralEuropean, &[0xA3, 0xF3, 0x64, 0x9F], "Łódź"),
|
||||
];
|
||||
for (set, bytes, text) in cases {
|
||||
let windows = TextOptions { character_set: set, ..TextOptions::default() };
|
||||
assert_eq!(decode(bytes, windows), text, "{set:?}");
|
||||
if set != CharacterSet::Cyrillic {
|
||||
assert_eq!(decode(bytes, TextOptions { mac: true, ..windows }), text, "{set:?} from a Mac");
|
||||
}
|
||||
}
|
||||
let mac_cyrillic = TextOptions { character_set: CharacterSet::Cyrillic, mac: true, ..TextOptions::default() };
|
||||
assert_eq!(decode(&[0x8F, 0xF0, 0xE8, 0xE2, 0xE5, 0xF2], mac_cyrillic), "Привет");
|
||||
let shift_jis = TextOptions { character_set: CharacterSet::ShiftJis, ..TextOptions::default() };
|
||||
assert_eq!(decode(&[0x82, 0x22], shift_jis), "\u{FFFD}\"", "a lead byte before ASCII");
|
||||
assert_eq!(decode(&[b'a', 0x82], shift_jis), "a\u{FFFD}", "a lead byte at the end");
|
||||
let central = TextOptions { character_set: CharacterSet::CentralEuropean, ..TextOptions::default() };
|
||||
assert_eq!(decode(&[0xEF, 0xBB, 0xBF, b'A'], central), "A", "a UTF-8 byte-order mark is read as windows-1250");
|
||||
assert_eq!(decode(&[0xFF, 0xFE, b'A', 0], shift_jis), "\u{FFFD}\u{FFFD}A\0", "a UTF-16 byte-order mark is read as Shift JIS");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn options_parse_and_reject_bad_values() {
|
||||
let p = serde_json::json!({"text": {"characterSet": "ansi", "platform": "mac", "removeLineReturns": true, "replaceSpaces": 4}});
|
||||
let o = TextOptions::parse(&p, "file.place").unwrap();
|
||||
assert_eq!(o, TextOptions { ansi: true, mac: true, remove_line_returns: true, remove_paragraph_returns: false, spaces_to_tab: Some(4) });
|
||||
assert_eq!(
|
||||
o,
|
||||
TextOptions {
|
||||
character_set: CharacterSet::Ansi,
|
||||
mac: true,
|
||||
remove_line_returns: true,
|
||||
remove_paragraph_returns: false,
|
||||
spaces_to_tab: Some(4)
|
||||
}
|
||||
);
|
||||
for (name, set) in CHARACTER_SETS {
|
||||
let o = TextOptions::parse(&serde_json::json!({"text": {"characterSet": name}}), "file.place").unwrap();
|
||||
assert_eq!(o.character_set, set, "{name}");
|
||||
}
|
||||
assert_eq!(TextOptions::parse(&serde_json::json!({}), "file.place").unwrap(), TextOptions::default());
|
||||
for bad in
|
||||
[serde_json::json!({"text": 3}), serde_json::json!({"text": {"platform": "amiga"}}), serde_json::json!({"text": {"replaceSpaces": 1}})]
|
||||
{
|
||||
for bad in [
|
||||
serde_json::json!({"text": 3}),
|
||||
serde_json::json!({"text": {"platform": "amiga"}}),
|
||||
serde_json::json!({"text": {"replaceSpaces": 1}}),
|
||||
serde_json::json!({"text": {"characterSet": 3}}),
|
||||
serde_json::json!({"text": {"platform": true}}),
|
||||
serde_json::json!({"text": {"removeLineReturns": "yes"}}),
|
||||
serde_json::json!({"text": {"removeParagraphReturns": 1}}),
|
||||
] {
|
||||
assert!(TextOptions::parse(&bad, "file.place").is_err(), "{bad}");
|
||||
}
|
||||
let null = serde_json::json!({"text": {"characterSet": null, "platform": null, "removeLineReturns": null}});
|
||||
assert_eq!(TextOptions::parse(&null, "file.place").unwrap(), TextOptions::default(), "null leaves the default");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -64,6 +64,7 @@ const DENIED_PREFIXES: &[&str] = &[
|
||||
"edit.newDocument",
|
||||
"edit.colorSettings",
|
||||
"edit.dropSelection",
|
||||
"symbol.placeFromDocument",
|
||||
"artboard.copy",
|
||||
"artboard.cut",
|
||||
"text.rescanFonts",
|
||||
|
||||
@@ -41,10 +41,12 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"addon.image.removeBackground",
|
||||
"addon.image.removeColorMask",
|
||||
"addon.packaging.check",
|
||||
"addon.packaging.fold",
|
||||
"addon.packaging.roles",
|
||||
"addon.packaging.setRole",
|
||||
"addon.packaging.setRoleSwatch",
|
||||
"addon.pathtools.addPoints",
|
||||
"addon.pathtools.bridge",
|
||||
"addon.pathtools.close",
|
||||
"addon.pathtools.commonTangents",
|
||||
"addon.pathtools.corner",
|
||||
@@ -84,6 +86,8 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"addon.shapes.star",
|
||||
"addon.type.releasePath",
|
||||
"addon.type.textTweaker",
|
||||
"addon.units.convert",
|
||||
"addon.units.selectionSize",
|
||||
"appearance.addEffect",
|
||||
"appearance.addFill",
|
||||
"appearance.addStroke",
|
||||
@@ -124,6 +128,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"brush.list",
|
||||
"brush.move",
|
||||
"brush.new",
|
||||
"brush.objectOptions",
|
||||
"brush.options",
|
||||
"brush.placeArt",
|
||||
"brush.remove",
|
||||
@@ -366,6 +371,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"object.repeat.release",
|
||||
"object.resetBoundingBox",
|
||||
"object.rotate",
|
||||
"object.rotateBoundingBox",
|
||||
"object.scale",
|
||||
"object.setBounds",
|
||||
"object.setLiveShape",
|
||||
|
||||
@@ -139,6 +139,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[
|
||||
p!("cornerRadius", "General", "", "Corner Radius", len(0.0, 1296.0, General)),
|
||||
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!("usePreciseCursors", "General", "Options", "Use Precise Cursors", bool),
|
||||
p!("showToolTips", "General", "Options", "Show Tool Tips", bool),
|
||||
p!("showExternalScriptWarning", "General", "Options", "Show External Script Warning", bool),
|
||||
@@ -368,6 +369,8 @@ pub const PREF_SPECS: &[PrefSpec] = &[
|
||||
p!("gpuPerformance", "Performance", "GPU Performance", "GPU Performance", bool),
|
||||
p!("animatedZoom", "Performance", "GPU Performance", "Animated Zoom", bool),
|
||||
p!("gpuPreference", "Performance", "GPU Performance", "Graphics Processor", choice(GPU_PREFERENCES)),
|
||||
// Read by the desktop app at startup: the window presents without vsync, capped at 240 fps (#6013).
|
||||
p!("lowLatencyDrawing", "Performance", "GPU Performance", "Low-Latency Drawing", bool),
|
||||
p!("historyStates", "Performance", "", "History States", int(5, 1000)),
|
||||
p!("realTimeDrawing", "Performance", "", "Real-time Drawing and Editing", bool),
|
||||
p!("renderThreads", "Performance", "", "Render Threads (-1 = Automatic)", int(-1, 64)),
|
||||
|
||||
@@ -34,7 +34,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Recolor Artwork",
|
||||
["Edit", "Edit Colors"],
|
||||
None,
|
||||
"{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex); may be empty: an empty row recolours nothing, adds no library swatch and gives `group` no colour unless `added`], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint), added?: false (an empty row's new color is a color added to `group`)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour | null] (what `group` is rewritten with, a null removing the group's swatch at its place; default: the new colors of the rows with current colors, in order, then those of the empty rows with `added`, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and 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, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model), notChanged: {locked, hidden} (as edit.colors.invert), warning?: set when notChanged counts any object}",
|
||||
"{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex); may be empty: an empty row recolours nothing, adds no library swatch and gives `group` no colour unless `added`], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint), added?: false (an empty row's new color is a color added to `group`)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour | null | \"keep\"] (what `group` is rewritten with, a null removing the group's swatch at its place and \"keep\" leaving that swatch its colour, without the Global Adjust (past the swatches it adds nothing; refused for a swatch that is not a colour); default: the new colors of the rows with current colors, in order, then those of the empty rows with `added`, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and 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, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model), notChanged: {locked, hidden} (as edit.colors.invert), warning?: set when notChanged counts any object}",
|
||||
has_doc,
|
||||
apply
|
||||
),
|
||||
@@ -1680,12 +1680,26 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(Value::Array(cs)) => Some(cs),
|
||||
Some(_) => return Err(bad(C, "`groupColors` must be an array")),
|
||||
};
|
||||
// A null in groupColors removes the group's swatch at its place.
|
||||
// A null in groupColors removes the group's swatch at its place, and "keep" leaves the swatch
|
||||
// at its place its color, without the Global Adjust.
|
||||
let own: Vec<Option<Color>> = match group {
|
||||
Some(g) => {
|
||||
s.doc()?.doc.swatch_groups.iter().find(|x| x.name == g).map(|g| g.swatches.iter().map(|w| w.paint.color()).collect()).unwrap_or_default()
|
||||
}
|
||||
None => vec![],
|
||||
};
|
||||
let new: Vec<Option<Color>> = match group_colors {
|
||||
Some(cs) => cs
|
||||
.iter()
|
||||
.map(|v| match v {
|
||||
.enumerate()
|
||||
.map(|(i, v)| match v {
|
||||
Value::Null => Ok(None),
|
||||
// Past the group's swatches it adds nothing.
|
||||
Value::String(k) if k == "keep" => match own.get(i) {
|
||||
Some(Some(c)) => Ok(Some(*c)),
|
||||
Some(None) => Err(bad(C, format!("the swatch at place {i} of groupColors is not a colour to keep"))),
|
||||
None => Ok(None),
|
||||
},
|
||||
v => color_value(v)
|
||||
.map(|c| adjust.apply(c))
|
||||
.map(|c| Some(in_doc_model(palette.as_ref().map_or(c, |pl| pl.nearest(c)))))
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -375,6 +375,59 @@ fn is_selectable_within(d: &Document, iso: Option<NodeId>, locks: Option<&Locked
|
||||
}
|
||||
}
|
||||
|
||||
/// The object Next Object Above (`dir` > 0) or Next Object Below selects from `cur`: the nearest
|
||||
/// sibling of `cur` in that direction that [`walk_selectable`] visits. Hidden and locked objects
|
||||
/// and sublayers are passed over. Only the siblings are read, not the rest of the document.
|
||||
fn step_target(d: &Document, iso: Option<NodeId>, cur: NodeId, dir: i64) -> Option<NodeId> {
|
||||
let path = d.index_path(cur)?;
|
||||
let (&idx, up) = path.split_last()?;
|
||||
// The objects that hold `cur` and its siblings, from the top-level layer down.
|
||||
let mut holders = Vec::with_capacity(up.len());
|
||||
let mut siblings = &d.layers;
|
||||
for &i in up {
|
||||
let n = siblings.get(i)?;
|
||||
holders.push(n.as_ref());
|
||||
siblings = n.children()?;
|
||||
}
|
||||
let iso = iso.and_then(|i| d.node(i));
|
||||
let locks = d.locked_artboards();
|
||||
let visits = |n: &Node| walk_visits(&holders, n, iso, &locks);
|
||||
let next = if dir > 0 { siblings.iter().skip(idx + 1).find(|n| visits(n)) } else { siblings.iter().take(idx).rev().find(|n| visits(n)) };
|
||||
next.map(|n| n.id)
|
||||
}
|
||||
|
||||
/// Whether [`walk_selectable`] visits `n`, read from the objects that hold it: `holders` are its
|
||||
/// layer and the sublayers, groups and other containers inside it that hold `n`, outermost first
|
||||
/// (its [`Document::ancestry`] without `n`). `iso` is the isolated object. Unlike
|
||||
/// [`is_selectable`], it passes over sublayers and the ruler guides of a layer, which the walk
|
||||
/// looks through or leaves out.
|
||||
fn walk_visits(holders: &[&Node], n: &Node, iso: Option<&Node>, locks: &LockedArtboards) -> bool {
|
||||
let len = holders.len() + 1;
|
||||
let at = |i: usize| holders.get(i).copied().unwrap_or(n);
|
||||
let open = |i: usize| at(i).visible && !at(i).locked;
|
||||
let start = match iso {
|
||||
Some(c) => {
|
||||
let Some(p) = (0..len).find(|&i| at(i).id == c.id) else { return false };
|
||||
if !(0..=p).all(|i| open(i) && !at(i).is_template()) {
|
||||
return false;
|
||||
}
|
||||
// A single object isolated is all there is to select.
|
||||
if !c.is_container() {
|
||||
return p + 1 == len;
|
||||
}
|
||||
p + 1
|
||||
}
|
||||
None => 0,
|
||||
};
|
||||
// The object Select All takes: the first one that is not a layer, inside visible, unlocked
|
||||
// layers and sublayers that are not template layers.
|
||||
let Some(top) = (start..len).find(|&i| !at(i).is_layer()) else { return false };
|
||||
(start..top).all(|i| open(i) && !at(i).is_template())
|
||||
&& !at(top).is_ruler_guide()
|
||||
&& (top..len).all(open)
|
||||
&& (iso.is_some() || locks.is_empty() || !locks.holds(at(top)))
|
||||
}
|
||||
|
||||
/// The first selected object, in selection order, that [`is_selectable`] accepts.
|
||||
pub(crate) fn first_selectable(st: &DocState) -> Option<&Node> {
|
||||
let locks = st.doc.locked_artboards();
|
||||
@@ -475,17 +528,7 @@ fn inverse(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
fn step(s: &mut Session, dir: i64) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let Some(cur) = st.selection.objects.first().copied() else { return ok() };
|
||||
let Some((par, idx, _)) = st.doc.position(cur) else { return ok() };
|
||||
let Some(siblings) = st.doc.children(par) else { return ok() };
|
||||
// The nearest sibling in that direction that `walk_selectable` visits: hidden and locked
|
||||
// objects and sublayers are passed over.
|
||||
let can = selectable_ids(&st.doc, st.isolation);
|
||||
let next = if dir > 0 {
|
||||
siblings.iter().skip(idx + 1).find(|n| can.contains(&n.id))
|
||||
} else {
|
||||
siblings.iter().take(idx).rev().find(|n| can.contains(&n.id))
|
||||
};
|
||||
let Some(id) = next.map(|n| n.id) else { return ok() };
|
||||
let Some(id) = step_target(&st.doc, st.isolation, cur, dir) else { return ok() };
|
||||
s.select(|_, sel| sel.set([id]))?;
|
||||
ok()
|
||||
}
|
||||
@@ -1399,5 +1442,8 @@ fn not_pixel_aligned(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
#[cfg(test)]
|
||||
mod same_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod step_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -0,0 +1,347 @@
|
||||
//! Select > Next Object Above and Below through [`step_target`], which reads only the siblings of
|
||||
//! the selected object, against a copy of the search that collected every object
|
||||
//! [`walk_selectable`] visits on each step.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_doc::{Appearance, Document, LayerColor, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{Rect, shapes};
|
||||
|
||||
use super::{selectable_ids, step_target, walk_visits};
|
||||
use crate::Session;
|
||||
|
||||
/// The search as it was before it read only the siblings: the nearest sibling in that direction
|
||||
/// that `walk_selectable` visits, from the set of every object it visits.
|
||||
fn step_base(d: &Document, iso: Option<NodeId>, cur: NodeId, dir: i64) -> Option<NodeId> {
|
||||
let (par, idx, _) = d.position(cur)?;
|
||||
let siblings = d.children(par)?;
|
||||
let can = selectable_ids(d, iso);
|
||||
let next = if dir > 0 {
|
||||
siblings.iter().skip(idx + 1).find(|n| can.contains(&n.id))
|
||||
} else {
|
||||
siblings.iter().take(idx).rev().find(|n| can.contains(&n.id))
|
||||
};
|
||||
next.map(|n| n.id)
|
||||
}
|
||||
|
||||
/// A small xorshift generator, so that each seed gives the same document every run.
|
||||
struct Rng(u64);
|
||||
|
||||
impl Rng {
|
||||
fn next(&mut self) -> u64 {
|
||||
self.0 ^= self.0 << 13;
|
||||
self.0 ^= self.0 >> 7;
|
||||
self.0 ^= self.0 << 17;
|
||||
self.0
|
||||
}
|
||||
|
||||
fn below(&mut self, n: u64) -> u64 {
|
||||
self.next() % n
|
||||
}
|
||||
|
||||
/// True `pct` times in 100.
|
||||
fn chance(&mut self, pct: u64) -> bool {
|
||||
self.below(100) < pct
|
||||
}
|
||||
}
|
||||
|
||||
fn rect_node(d: &mut Document, x: f64, y: f64) -> Node {
|
||||
Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, y, x + 40.0, y + 40.0)), Appearance::default())
|
||||
}
|
||||
|
||||
fn layer_node(d: &mut Document, children: Vec<Node>) -> Node {
|
||||
let mut l = Node::layer(d.alloc_id(), "Layer", LayerColor::Preset(0));
|
||||
if let Some(ch) = l.children_mut() {
|
||||
ch.extend(children.into_iter().map(Arc::new));
|
||||
}
|
||||
l
|
||||
}
|
||||
|
||||
fn ruler_guide(d: &mut Document, pos: f64) -> Node {
|
||||
Node::new(d.alloc_id(), NodeKind::RulerGuide { vertical: pos > 300.0, pos, artboard: None })
|
||||
}
|
||||
|
||||
/// Up to six objects: rectangles on and off the artboard, guides made from paths, ruler guides,
|
||||
/// groups, and sublayers, some hidden, locked or template layers. Groups and sublayers hold more
|
||||
/// below `depth`. Sublayers and ruler guides also go inside groups, which the app does not make,
|
||||
/// so that every shape of tree is compared.
|
||||
fn objects(r: &mut Rng, d: &mut Document, depth: u32) -> Vec<Node> {
|
||||
(0..r.below(7))
|
||||
.map(|_| {
|
||||
let (x, y) = (r.below(1400) as f64 - 300.0, r.below(1000) as f64 - 200.0);
|
||||
let mut n = match r.below(if depth == 0 { 6 } else { 10 }) {
|
||||
0..=3 => rect_node(d, x, y),
|
||||
4 => {
|
||||
let mut n = rect_node(d, x, y);
|
||||
if let NodeKind::Path { guide, .. } = &mut n.kind {
|
||||
*guide = true;
|
||||
}
|
||||
n
|
||||
}
|
||||
5 => ruler_guide(d, x),
|
||||
6 | 7 => {
|
||||
let kids = objects(r, d, depth - 1);
|
||||
Node::group(d.alloc_id(), kids.into_iter().map(Arc::new).collect())
|
||||
}
|
||||
_ => {
|
||||
let kids = objects(r, d, depth - 1);
|
||||
layer_node(d, kids)
|
||||
}
|
||||
};
|
||||
n.visible = !r.chance(10);
|
||||
n.locked = r.chance(10);
|
||||
if let NodeKind::Layer { template, .. } = &mut n.kind {
|
||||
*template = r.chance(15);
|
||||
}
|
||||
n
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A document of one to three layers, some hidden, locked or template layers, holding
|
||||
/// [`objects`], with its artboard locked in some seeds.
|
||||
fn random_document(seed: u64) -> Document {
|
||||
let mut r = Rng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1);
|
||||
let mut d = Document::new(800.0, 600.0);
|
||||
let layers = (0..1 + r.below(3))
|
||||
.map(|_| {
|
||||
let kids = objects(&mut r, &mut d, 3);
|
||||
let mut l = layer_node(&mut d, kids);
|
||||
l.visible = !r.chance(10);
|
||||
l.locked = r.chance(10);
|
||||
if let NodeKind::Layer { template, .. } = &mut l.kind {
|
||||
*template = r.chance(10);
|
||||
}
|
||||
Arc::new(l)
|
||||
})
|
||||
.collect();
|
||||
d.layers = layers;
|
||||
if let Some(a) = d.artboards.first_mut() {
|
||||
a.locked = r.chance(40);
|
||||
}
|
||||
d
|
||||
}
|
||||
|
||||
/// Every node of `d`, layers included, in tree order.
|
||||
fn all_ids(d: &Document) -> Vec<NodeId> {
|
||||
let mut ids = vec![];
|
||||
d.walk(|n| ids.push(n.id));
|
||||
ids
|
||||
}
|
||||
|
||||
/// The objects that hold `id`, outermost first, and the node itself.
|
||||
fn holders(d: &Document, id: NodeId) -> (Vec<&Node>, &Node) {
|
||||
let a = d.ancestry(id).unwrap();
|
||||
let (last, up) = a.split_last().unwrap();
|
||||
(up.iter().map(|i| d.node(*i).unwrap()).collect(), d.node(*last).unwrap())
|
||||
}
|
||||
|
||||
/// For every node of random documents, outside isolation mode and with each of several nodes
|
||||
/// isolated, `walk_visits` says what the set of the objects `walk_selectable` visits says, and
|
||||
/// Next Object Above and Below from it give what the search over that set gave.
|
||||
#[test]
|
||||
fn next_object_gives_what_the_search_over_every_selectable_object_gave() {
|
||||
let (mut steps, mut moved, mut isolated) = (0, 0, 0);
|
||||
for seed in 0..300 {
|
||||
let d = random_document(seed);
|
||||
let ids = all_ids(&d);
|
||||
let mut r = Rng(seed + 7);
|
||||
let mut isos = vec![None];
|
||||
isos.extend((0..10).map(|_| Some(ids[r.below(ids.len() as u64) as usize])));
|
||||
let locks = d.locked_artboards();
|
||||
for iso in isos {
|
||||
let can = selectable_ids(&d, iso);
|
||||
let iso_node = iso.and_then(|i| d.node(i));
|
||||
for &id in &ids {
|
||||
let (up, n) = holders(&d, id);
|
||||
assert_eq!(walk_visits(&up, n, iso_node, &locks), can.contains(&id), "seed {seed}, isolating {iso:?}, node {id:?}");
|
||||
}
|
||||
for &cur in &ids {
|
||||
for dir in [1, -1] {
|
||||
let want = step_base(&d, iso, cur, dir);
|
||||
assert_eq!(step_target(&d, iso, cur, dir), want, "seed {seed}, isolating {iso:?}, from {cur:?}, direction {dir}");
|
||||
steps += 1;
|
||||
moved += usize::from(want.is_some());
|
||||
isolated += usize::from(want.is_some() && iso.is_some());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// The documents give many steps that select something, inside isolation mode too.
|
||||
eprintln!("{moved} of {steps} steps select an object, {isolated} of them in isolation mode");
|
||||
assert!(moved > 5_000, "{moved} of {steps} steps select an object");
|
||||
assert!(isolated > 500, "{isolated} steps select an object in isolation mode");
|
||||
}
|
||||
|
||||
/// A session holding `d`, with `iso` isolated and `cur` selected.
|
||||
fn session(d: Document, iso: Option<NodeId>, cur: NodeId) -> Session {
|
||||
let mut s = Session::new();
|
||||
s.add_document(d, None);
|
||||
let st = s.doc_mut().unwrap();
|
||||
st.isolation = iso;
|
||||
st.selection.set([cur]);
|
||||
s
|
||||
}
|
||||
|
||||
fn selected(s: &Session) -> Vec<NodeId> {
|
||||
s.doc().unwrap().selection.objects.to_vec()
|
||||
}
|
||||
|
||||
/// In an isolated layer, Next Object Above and Below pass over a sublayer beside the selected object,
|
||||
/// as the walk looks through it.
|
||||
#[test]
|
||||
fn next_object_passes_over_a_sublayer_in_an_isolated_layer() {
|
||||
let mut d = Document::new(800.0, 600.0);
|
||||
let a = rect_node(&mut d, 0.0, 0.0);
|
||||
let inner = rect_node(&mut d, 100.0, 0.0);
|
||||
let b = rect_node(&mut d, 200.0, 0.0);
|
||||
let sub = layer_node(&mut d, vec![inner]);
|
||||
let (a_id, b_id) = (a.id, b.id);
|
||||
let l = layer_node(&mut d, vec![a, sub, b]);
|
||||
let layer = l.id;
|
||||
d.layers = vec![Arc::new(l)];
|
||||
assert_eq!(step_base(&d, Some(layer), a_id, 1), Some(b_id));
|
||||
let mut s = session(d, Some(layer), a_id);
|
||||
s.execute("select.nextAbove", &json!({})).unwrap();
|
||||
assert_eq!(selected(&s), vec![b_id]);
|
||||
s.execute("select.nextBelow", &json!({})).unwrap();
|
||||
assert_eq!(selected(&s), vec![a_id]);
|
||||
}
|
||||
|
||||
/// Next Object Above passes over a ruler guide of the layer, which the walk leaves out, unless the
|
||||
/// guide is the object isolated.
|
||||
#[test]
|
||||
fn next_object_passes_over_a_ruler_guide_of_the_layer() {
|
||||
let mut d = Document::new(800.0, 600.0);
|
||||
let a = rect_node(&mut d, 0.0, 0.0);
|
||||
let b = rect_node(&mut d, 200.0, 0.0);
|
||||
let guide = ruler_guide(&mut d, 100.0);
|
||||
let (a_id, b_id, guide_id) = (a.id, b.id, guide.id);
|
||||
let l = layer_node(&mut d, vec![a, b, guide]);
|
||||
d.layers = vec![Arc::new(l)];
|
||||
// Nothing above the rectangle but the guide: the selection stays.
|
||||
assert_eq!(step_base(&d, None, b_id, 1), None);
|
||||
let mut s = session(d.clone(), None, b_id);
|
||||
s.execute("select.nextAbove", &json!({})).unwrap();
|
||||
assert_eq!(selected(&s), vec![b_id]);
|
||||
s.execute("select.nextBelow", &json!({})).unwrap();
|
||||
assert_eq!(selected(&s), vec![a_id]);
|
||||
// The guide isolated on its own is what there is to select.
|
||||
assert_eq!(step_base(&d, Some(guide_id), b_id, 1), Some(guide_id));
|
||||
assert_eq!(step_target(&d, Some(guide_id), b_id, 1), Some(guide_id));
|
||||
}
|
||||
|
||||
/// The first selected object anchors the search even when it can no longer be selected itself.
|
||||
#[test]
|
||||
fn next_object_steps_from_a_hidden_first_selected_object() {
|
||||
let mut d = Document::new(800.0, 600.0);
|
||||
let mut a = rect_node(&mut d, 0.0, 0.0);
|
||||
a.visible = false;
|
||||
let b = rect_node(&mut d, 200.0, 0.0);
|
||||
let (a_id, b_id) = (a.id, b.id);
|
||||
let l = layer_node(&mut d, vec![a, b]);
|
||||
d.layers = vec![Arc::new(l)];
|
||||
assert_eq!(step_base(&d, None, a_id, 1), Some(b_id));
|
||||
let mut s = session(d, None, a_id);
|
||||
s.execute("select.nextAbove", &json!({})).unwrap();
|
||||
assert_eq!(selected(&s), vec![b_id]);
|
||||
}
|
||||
|
||||
/// The CPU time this thread has used, from Linux's scheduler statistics; `None` elsewhere.
|
||||
fn thread_cpu() -> Option<Duration> {
|
||||
let stat = std::fs::read_to_string("/proc/thread-self/schedstat").ok()?;
|
||||
stat.split_whitespace().next()?.parse().ok().map(Duration::from_nanos)
|
||||
}
|
||||
|
||||
/// The time `f` takes: this thread's CPU time where Linux reports it, otherwise the wall clock.
|
||||
fn time(f: impl FnOnce()) -> Duration {
|
||||
match thread_cpu() {
|
||||
Some(before) => {
|
||||
f();
|
||||
thread_cpu().map_or(Duration::ZERO, |after| after.saturating_sub(before))
|
||||
}
|
||||
None => {
|
||||
let start = Instant::now();
|
||||
f();
|
||||
start.elapsed()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A document of `groups` groups of `per` rectangles on one layer, or of `per` rectangles when
|
||||
/// `groups` is 0 → the document and the object in the middle of the layer.
|
||||
fn wide(groups: usize, per: usize) -> (Document, NodeId) {
|
||||
let mut d = Document::new(800.0, 600.0);
|
||||
let mut top = vec![];
|
||||
if groups == 0 {
|
||||
top.extend((0..per).map(|i| rect_node(&mut d, (i % 200) as f64 * 4.0, (i / 200 % 150) as f64 * 4.0)));
|
||||
} else {
|
||||
for g in 0..groups {
|
||||
let kids: Vec<Arc<Node>> = (0..per).map(|i| Arc::new(rect_node(&mut d, (i % 20) as f64 * 4.0, (g % 150) as f64 * 4.0))).collect();
|
||||
top.push(Node::group(d.alloc_id(), kids));
|
||||
}
|
||||
}
|
||||
let mid = top[top.len() / 2].id;
|
||||
let l = layer_node(&mut d, top);
|
||||
d.layers = vec![Arc::new(l)];
|
||||
(d, mid)
|
||||
}
|
||||
|
||||
/// A search for the object Next Object Above or Below selects: [`step_base`] or [`step_target`].
|
||||
type Step = fn(&Document, Option<NodeId>, NodeId, i64) -> Option<NodeId>;
|
||||
|
||||
/// Timings of Next Object Above and Below, stepping up and down from the object in the middle of
|
||||
/// the layer, by the search over every selectable object (200 steps a run) and by the siblings
|
||||
/// alone (200,000 steps a run, as one step takes too little time to measure), on 100,000
|
||||
/// rectangles and on 1,000 groups of 100, run in turn on the same document, 7 runs each. Ignored by
|
||||
/// default; it prints the median, fastest and slowest time per step and sets no bound on them:
|
||||
/// `cargo test --release -p vectorcraft-engine --lib next_object_perf -- --ignored --nocapture`.
|
||||
#[test]
|
||||
#[ignore = "a benchmark: run with --ignored --nocapture"]
|
||||
fn next_object_perf() {
|
||||
const RUNS: usize = 7;
|
||||
const OLD_STEPS: usize = 200;
|
||||
const NEW_STEPS: usize = 200_000;
|
||||
let per_step = |d: Duration, steps: usize| d.as_secs_f64() * 1e6 / steps as f64;
|
||||
eprintln!("next_object_perf: {}", if thread_cpu().is_some() { "thread CPU time" } else { "wall clock" });
|
||||
eprintln!("next_object_perf: {:<26} {:>32} {:>32}", "document", "every object µs/step (min-max)", "siblings µs/step (min-max)");
|
||||
for (name, groups, per) in [("100,000 rectangles", 0, 100_000), ("1,000 groups of 100", 1_000, 100)] {
|
||||
let (d, mid) = wide(groups, per);
|
||||
let walk = |f: Step, steps: usize| {
|
||||
let mut cur = mid;
|
||||
let mut seen = Vec::with_capacity(steps);
|
||||
for i in 0..steps {
|
||||
cur = f(&d, None, cur, if i % 2 == 0 { 1 } else { -1 }).unwrap_or(cur);
|
||||
seen.push(cur);
|
||||
}
|
||||
std::hint::black_box(seen)
|
||||
};
|
||||
let (mut old, mut new) = (Vec::new(), Vec::new());
|
||||
let (mut a, mut b) = (vec![], vec![]);
|
||||
for run in 0..RUNS {
|
||||
// The two take turns going first.
|
||||
if run % 2 == 0 {
|
||||
old.push(time(|| a = walk(step_base, OLD_STEPS)));
|
||||
new.push(time(|| b = walk(step_target, NEW_STEPS)));
|
||||
} else {
|
||||
new.push(time(|| b = walk(step_target, NEW_STEPS)));
|
||||
old.push(time(|| a = walk(step_base, OLD_STEPS)));
|
||||
}
|
||||
assert_eq!(a[..], b[..OLD_STEPS], "{name}");
|
||||
assert_ne!(a[0], mid, "{name}: the first step selects another object");
|
||||
}
|
||||
old.sort();
|
||||
new.sort();
|
||||
eprintln!(
|
||||
"next_object_perf: {name:<26} {:>12.3} ({:>8.3}-{:>9.3}) {:>12.3} ({:>8.3}-{:>9.3})",
|
||||
per_step(old[RUNS / 2], OLD_STEPS),
|
||||
per_step(old[0], OLD_STEPS),
|
||||
per_step(old[RUNS - 1], OLD_STEPS),
|
||||
per_step(new[RUNS / 2], NEW_STEPS),
|
||||
per_step(new[0], NEW_STEPS),
|
||||
per_step(new[RUNS - 1], NEW_STEPS),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -220,8 +220,10 @@ fn own_stroke_or_leaves(s: &Session, p: &Value) -> Result<Vec<vectorcraft_doc::N
|
||||
})
|
||||
};
|
||||
let (mut out, rest): (Vec<_>, Vec<_>) = picked.into_iter().partition(own);
|
||||
// A leaf already listed is skipped; a set keeps this linear in the number of leaves.
|
||||
let mut seen: std::collections::HashSet<vectorcraft_doc::NodeId> = out.iter().copied().collect();
|
||||
for id in super::leaf_targets(s, &rest)? {
|
||||
if !out.contains(&id) {
|
||||
if seen.insert(id) {
|
||||
out.push(id);
|
||||
}
|
||||
}
|
||||
@@ -429,6 +431,52 @@ impl Session {
|
||||
painted(first, true, &mut nodes);
|
||||
node_stroke(nodes.first()?)
|
||||
}
|
||||
|
||||
/// Do all the strokes that `stroke.set` edits without `ids` or `item` draw with a brush
|
||||
/// ([`vectorcraft_brush::keeps_brush_size`])? If they do, a width profile changes none of
|
||||
/// them, and the result is `Some`, holding whether any of them has a width profile. The result
|
||||
/// is `None` when a profile changes at least one of them.
|
||||
///
|
||||
/// The strokes are the ones `stroke.set` edits:
|
||||
/// - the Appearance panel's active stroke row in each target that has an equal row
|
||||
/// ([`ItemTarget::per_target`]), and the top stroke in the others;
|
||||
/// - else a selected group's own stroke;
|
||||
/// - else the top strokes of the objects it paints ([`own_stroke_or_leaves`]).
|
||||
///
|
||||
/// The art of graph designs is left out, and so are images and symbol instances without an
|
||||
/// active row. The result is also `None` with nothing selected, with an object inside a symbol
|
||||
/// instance selected, with type among the targets while no Appearance row is active for it,
|
||||
/// and with a target that has no stroke row, since `stroke.set` gives such a target a plain
|
||||
/// stroke.
|
||||
pub fn brushed_strokes_profiled(&self) -> Option<bool> {
|
||||
const C: &str = "stroke.set";
|
||||
let st = self.active()?;
|
||||
if st.selected_symbol_part().is_some() {
|
||||
return None;
|
||||
}
|
||||
let p = json!({});
|
||||
let item = item_target(self, &p, C).ok()?.of_kind(self, false);
|
||||
let ids = if item == ItemTarget::Top { own_stroke_or_leaves(self, &p).ok()? } else { item.targets(self, &p).ok()? };
|
||||
let mut ids = super::appearance::drop_design_art_rows(self, ids, item, false, C).ok()?;
|
||||
if item == ItemTarget::Top {
|
||||
ids.retain(|id| !matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::Image(_) | NodeKind::SymbolInstance { .. })));
|
||||
}
|
||||
let mut strokes = vec![];
|
||||
for (id, each) in ids.iter().zip(item.per_target(self, &ids)) {
|
||||
let n = st.doc.node(*id)?;
|
||||
let row = each?.resolve(&n.appearance, false, C).ok()?;
|
||||
if row.is_none() && matches!(n.kind, NodeKind::Text(_)) {
|
||||
return None;
|
||||
}
|
||||
strokes.push(n.appearance.stroke_at(row).filter(|s| s.brush.is_some())?);
|
||||
}
|
||||
if strokes.is_empty() {
|
||||
return None;
|
||||
}
|
||||
// The library is read only when every stroke names a brush.
|
||||
let lib = vectorcraft_brush::library(&st.doc);
|
||||
strokes.iter().all(|s| vectorcraft_brush::keeps_brush_size(&lib, s)).then(|| strokes.iter().any(|s| s.profile.is_some()))
|
||||
}
|
||||
}
|
||||
|
||||
impl DocState {
|
||||
@@ -549,6 +597,10 @@ fn stroke_advanced(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let Some(st) = n.appearance.stroke_at_mut(index) else { return Ok(()) };
|
||||
arrows_and_profile(st);
|
||||
if let Some(b) = &brush {
|
||||
// The path's own brush settings (Options of Selected Object) go with the brush they set.
|
||||
if st.brush != *b {
|
||||
st.brush_options.clear();
|
||||
}
|
||||
st.brush = b.clone();
|
||||
}
|
||||
Ok(())
|
||||
@@ -674,6 +726,7 @@ fn profile_list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use vectorcraft_doc::NodeId;
|
||||
|
||||
#[test]
|
||||
fn weight_steps_follow_units_and_stop_at_their_bounds() {
|
||||
@@ -689,4 +742,93 @@ mod tests {
|
||||
assert!((step_weight(mm, Unit::Millimeters, true) - 2.0 * mm).abs() < 1e-9);
|
||||
assert!((step_weight(mm, Unit::Millimeters, false) - 0.75 * mm).abs() < 1e-9);
|
||||
}
|
||||
|
||||
fn run(s: &mut Session, id: &str, p: Value) -> Value {
|
||||
s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"))
|
||||
}
|
||||
|
||||
fn made(v: Value) -> NodeId {
|
||||
NodeId(v["id"].as_u64().unwrap_or_else(|| panic!("no id in {v}")))
|
||||
}
|
||||
|
||||
/// The targets of [`own_stroke_or_leaves`] merged by a linear search of the growing list.
|
||||
fn listed_merge(s: &Session, p: &Value) -> Vec<NodeId> {
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let own = |id: &NodeId| {
|
||||
d.node(*id).is_some_and(|n| {
|
||||
matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) && !n.is_compound_shape() && n.appearance.stroke().is_some()
|
||||
})
|
||||
};
|
||||
let (mut out, rest): (Vec<_>, Vec<_>) = super::super::targets(s, p).unwrap().into_iter().partition(own);
|
||||
for id in super::super::leaf_targets(s, &rest).unwrap() {
|
||||
if !out.contains(&id) {
|
||||
out.push(id);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `stroke.set` with no `item` lists the same targets in the same order as a linear merge:
|
||||
/// groups and layers with a stroke of their own (repeats kept), the leaves of plain groups and
|
||||
/// layers, compound paths and compound shapes for their members, and each leaf once, also
|
||||
/// when it is named both directly and through its group.
|
||||
#[test]
|
||||
fn stroke_targets_match_the_listed_merge() {
|
||||
let mut s = Session::new();
|
||||
run(&mut s, "file.new", json!({"width": 2000, "height": 400}));
|
||||
let base = s.doc().unwrap().doc.layers[0].id;
|
||||
let mut x = 0.0;
|
||||
let mut rect = |s: &mut Session| {
|
||||
x += 120.0;
|
||||
made(run(s, "shape.rectangle", json!({"x": x, "y": 100, "width": 100, "height": 100})))
|
||||
};
|
||||
let (a, b) = (rect(&mut s), rect(&mut s));
|
||||
let plain = made(run(&mut s, "object.group", json!({"ids": [a.0, b.0]})));
|
||||
let (c, d) = (rect(&mut s), rect(&mut s));
|
||||
let owned = made(run(&mut s, "object.group", json!({"ids": [c.0, d.0]})));
|
||||
run(&mut s, "appearance.addStroke", json!({"ids": [owned.0]}));
|
||||
let (e, f) = (rect(&mut s), rect(&mut s));
|
||||
run(&mut s, "select.set", json!({"ids": [e.0, f.0]}));
|
||||
let compound = made(run(&mut s, "object.compoundPath.make", json!({})));
|
||||
let (g, h) = (rect(&mut s), rect(&mut s));
|
||||
run(&mut s, "select.set", json!({"ids": [g.0, h.0]}));
|
||||
let shape = made(run(&mut s, "object.compoundShape.make", json!({})));
|
||||
let lone = rect(&mut s);
|
||||
let layer = made(run(&mut s, "layer.new", json!({})));
|
||||
let (j, k) = (rect(&mut s), rect(&mut s));
|
||||
run(&mut s, "appearance.addStroke", json!({"ids": [layer.0]}));
|
||||
{
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
assert_eq!((doc.parent_of(j), doc.parent_of(k)), (Some(layer), Some(layer)), "the new layer holds the last two");
|
||||
assert_eq!((doc.parent_of(e), doc.parent_of(g)), (Some(compound), Some(shape)));
|
||||
assert!(doc.node(owned).unwrap().appearance.stroke().is_some() && doc.node(layer).unwrap().appearance.stroke().is_some());
|
||||
}
|
||||
let named = json!({"ids": [plain.0, a.0, owned.0, owned.0, c.0, e.0, compound.0, g.0, lone.0, layer.0, j.0]});
|
||||
let cases = [
|
||||
named.clone(),
|
||||
json!({"ids": [j.0, h.0, f.0, b.0, plain.0, layer.0, owned.0, k.0, shape.0]}),
|
||||
json!({"ids": [base.0, layer.0, base.0]}),
|
||||
json!({"ids": [d.0, owned.0, base.0]}),
|
||||
json!({"ids": []}),
|
||||
];
|
||||
for p in &cases {
|
||||
assert_eq!(own_stroke_or_leaves(&s, p).unwrap(), listed_merge(&s, p), "{p}");
|
||||
}
|
||||
run(&mut s, "select.set", json!({"ids": [lone.0, owned.0, f.0, plain.0, b.0, layer.0]}));
|
||||
assert_eq!(own_stroke_or_leaves(&s, &json!({})).unwrap(), listed_merge(&s, &json!({})), "the selection");
|
||||
|
||||
// The edit reaches every listed target, counting a repeated one once, and leaves the other
|
||||
// member of the group with its own stroke alone.
|
||||
let want = listed_merge(&s, &named);
|
||||
assert_eq!(want.iter().filter(|id| **id == owned).count(), 2, "{want:?}");
|
||||
let distinct: std::collections::HashSet<_> = want.iter().collect();
|
||||
let before = s.doc().unwrap().doc.node(d).unwrap().clone();
|
||||
let r = run(&mut s, "stroke.set", json!({"ids": named["ids"], "weight": 3}));
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
assert_eq!(r["objects"], distinct.len(), "{r} {want:?}");
|
||||
for id in &want {
|
||||
assert_eq!(doc.node(*id).unwrap().appearance.stroke().map(|st| st.width), Some(3.0), "{id:?}");
|
||||
}
|
||||
assert_eq!(doc.node(d), Some(&before), "a member reached only through its group's own stroke is left alone");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -318,8 +318,14 @@ impl Session {
|
||||
/// it is still linked (still has that style's look). A graph series group that holds nothing of its own stands
|
||||
/// for the topmost path directly inside it, which a style applied to the group links.
|
||||
pub fn selection_graphic_style(&self) -> Option<(&GraphicStyle, bool)> {
|
||||
self.graphic_style_of(*self.active()?.selection.subjects().first()?)
|
||||
}
|
||||
|
||||
/// The graphic style of object `id` of the active document, as [`Self::selection_graphic_style`]
|
||||
/// gives it for the first selected object.
|
||||
pub fn graphic_style_of(&self, id: NodeId) -> Option<(&GraphicStyle, bool)> {
|
||||
let st = self.active()?;
|
||||
let n = super::appearance::look_holder(&st.doc, st.doc.node(*st.selection.subjects().first()?)?);
|
||||
let n = super::appearance::look_holder(&st.doc, st.doc.node(id)?);
|
||||
let g = st.doc.graphic_style_by_id(n.extras().graphic_style?)?;
|
||||
Some((g, in_sync(n, g)))
|
||||
}
|
||||
|
||||
@@ -129,7 +129,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Edit Color Group",
|
||||
["Window", "Swatches"],
|
||||
None,
|
||||
"{group: colour group, colors: [colour] (hex, key, {c,m,y,k} or {l,a,b}; #rrggbbaa and #rgba are refused; the group's swatches take them in order, extra colours become new swatches, swatches past the end are removed; built-in swatches can't change; a color the swatch already has keeps its model), keepModel?: bool (as paint.setFill), rename?: new group name} rewrite a colour group as one undo step; art linked to its global swatches takes their new colours (and keeps its colour, unlinked, when its swatch goes) → {name, swatches: [names], relinked}",
|
||||
"{group: colour group, colors: [colour] (hex, key, {c,m,y,k} or {l,a,b}; #rrggbbaa and #rgba are refused; the group's swatches take them in order, extra colours become new swatches, swatches past the end are removed; a null removes the swatch at that place; built-in swatches can't change; a color the swatch already has keeps its model, and a key that names the swatch's color, rounded to the key's steps, keeps the swatch's color unrounded), keepModel?: bool (as paint.setFill), rename?: new group name} rewrite a colour group as one undo step; art linked to its global swatches takes their new colours (and keeps its colour, unlinked, when its swatch goes) → {name, swatches: [names], relinked}",
|
||||
has_doc,
|
||||
swatch_edit_group
|
||||
),
|
||||
@@ -1340,21 +1340,45 @@ pub(super) fn rewrite_group(d: &mut Document, group: &str, colors: &[Option<Colo
|
||||
fn swatch_edit_group(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "swatch.editGroup";
|
||||
let group = str_param(p, "group").ok_or_else(|| bad(C, "missing `group`"))?;
|
||||
let colors: Vec<Color> = p
|
||||
// A null removes the swatch at that place.
|
||||
let colors: Vec<Option<Color>> = p
|
||||
.get("colors")
|
||||
.and_then(Value::as_array)
|
||||
.ok_or_else(|| bad(C, "missing `colors`"))?
|
||||
.iter()
|
||||
.map(|v| color_value(v).ok_or_else(|| bad(C, format!("bad colour {v}"))))
|
||||
.map(|v| if v.is_null() { Ok(None) } else { color_value(v).map(Some).ok_or_else(|| bad(C, format!("bad colour {v}"))) })
|
||||
.collect::<Result<_>>()?;
|
||||
super::paint::check_keep_model(p, C)?;
|
||||
// A color its swatch already has keeps its model. The others take the document's.
|
||||
// A color its swatch already has keeps its model. The others take the document's. A color key
|
||||
// (`recolor.colors`) names a color rounded to its steps, so a key of the swatch's own color
|
||||
// gives the swatch that color, unrounded.
|
||||
let old: Vec<Option<Color>> =
|
||||
s.doc()?.doc.swatch_groups.iter().find(|g| g.name == group).map(|g| g.swatches.iter().map(|w| w.paint.color()).collect()).unwrap_or_default();
|
||||
let colors: Vec<Color> =
|
||||
colors.into_iter().enumerate().map(|(i, c)| if old.get(i) == Some(&Some(c)) { c } else { super::paint::new_color(s, p, c) }).collect();
|
||||
let entries = p.get("colors").and_then(Value::as_array);
|
||||
let is_key = |i: usize| entries.and_then(|a| a.get(i)).and_then(Value::as_str).and_then(vectorcraft_color::recolor::ColorKey::parse);
|
||||
let mut colors: Vec<Option<Color>> = colors
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(i, c)| {
|
||||
c.map(|c| match old.get(i).copied().flatten() {
|
||||
Some(o) if o == c || is_key(i).is_some_and(|k| k == vectorcraft_color::recolor::ColorKey::of(&o)) => o,
|
||||
_ => super::paint::new_color(s, p, c),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
// A null past the group's swatches removes nothing.
|
||||
while colors.len() > old.len() && colors.last() == Some(&None) {
|
||||
colors.pop();
|
||||
}
|
||||
let rename = str_param(p, "rename");
|
||||
let colors: Vec<Option<Color>> = colors.into_iter().map(Some).collect();
|
||||
// The group's own colors, in order, under its own name change nothing: no undo step.
|
||||
if let Some(g) = s.doc()?.doc.swatch_groups.iter().find(|g| g.name == group)
|
||||
&& rename.map(str::trim).is_none_or(|n| n.is_empty() || n == group)
|
||||
&& old.len() == colors.len()
|
||||
&& old.iter().zip(&colors).all(|(o, c)| c.is_some() && o == c)
|
||||
{
|
||||
return Ok(json!({"name": group, "swatches": g.swatches.iter().map(|w| w.name.clone()).collect::<Vec<_>>(), "relinked": 0}));
|
||||
}
|
||||
let e = s.edit("Edit Color Group", |d, _| rewrite_group(d, group, &colors, rename, C))?;
|
||||
e.defaults(s)?;
|
||||
Ok(json!({"name": e.name, "swatches": e.swatches, "relinked": e.relinked}))
|
||||
|
||||
@@ -49,7 +49,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 → {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)} 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}",
|
||||
has_doc,
|
||||
add
|
||||
),
|
||||
@@ -76,7 +76,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Other Library…",
|
||||
["Window", "Swatch Libraries"],
|
||||
None,
|
||||
"{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} load a .vcswatches, .gpl, .ase (swatch exchange) or .acb (color book, read only) library, or the swatches of any document VectorCraft opens (see document.formats), for the library panel (Window → Swatch Libraries lists it until the app quits; a file of the user library folder, or a file with the same extension and bytes as one there, opens as that User Defined library) → {library: id, name, count}",
|
||||
"{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} load a .vcswatches, .gpl, .ase (swatch exchange) or .acb (color book, read only) library, or the swatches of any document VectorCraft opens (see document.formats), such as a .ai or .eps swatch library, for the library panel (Window → Swatch Libraries lists it until the app quits; a file of the user library folder, or a file with the same extension and bytes as one there, opens as that User Defined library). A document's colors, tints, gradients and pattern swatches come in, in its order and color groups; swatch.library.add brings a pattern swatch's pattern with it. A document with no swatches is an error, and so is a .ai, .eps or PostScript file whose swatches are only the default ones (it has no palette of its own) → {library: id, name, count}",
|
||||
always,
|
||||
load
|
||||
),
|
||||
@@ -85,7 +85,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Copy to User Defined",
|
||||
["Window", "Swatch Libraries"],
|
||||
None,
|
||||
"{library: id or name of a loaded library (category \"loaded\", swatch.library.load)} copy it into the user library folder of the desktop app, whose libraries VectorCraft lists as User Defined every time it starts (a loaded library is listed until the app quits): a library file as it is, the swatches of a document or a library loaded from data as a .vcswatches file. A name the folder already has gets a number (\"Brand 2.ase\") and no file is replaced; when the folder already holds the same file, that file is used. The library is then listed as User Defined only, and until the app quits commands given its loaded id use the copy; a User Defined library comes back as it is → {library: its User Defined id, name, count, path (left out when it is outside the read roots), copied: false when nothing was written}",
|
||||
"{library: id or name of a loaded library (category \"loaded\", swatch.library.load)} copy it into the user library folder of the desktop app, whose libraries VectorCraft lists as User Defined every time it starts (a loaded library is listed until the app quits): a library file as it is, the swatches of a document or a library loaded from data as a .vcswatches file (a library with pattern swatches is refused). A name the folder already has gets a number (\"Brand 2.ase\") and no file is replaced; when the folder already holds the same file, that file is used. The library is then listed as User Defined only, and until the app quits commands given its loaded id use the copy; a User Defined library comes back as it is → {library: its User Defined id, name, count, path (left out when it is outside the read roots), copied: false when nothing was written}",
|
||||
has_user_folder,
|
||||
copy_to_user
|
||||
),
|
||||
@@ -109,6 +109,9 @@ pub struct Libraries<L = SwatchLibrary> {
|
||||
/// the file name instead. [`Libraries::rescan`] drops an entry whose file no longer holds those
|
||||
/// bytes, and keeps one whose file is missing so a file put back can be checked.
|
||||
saved_as: HashMap<String, SavedAs>,
|
||||
/// The documents loaded swatch libraries were read from, by library id, for those with pattern
|
||||
/// swatches: the patterns live there ([`Libraries::pattern_doc`]).
|
||||
pattern_docs: HashMap<String, Arc<vectorcraft_doc::Document>>,
|
||||
}
|
||||
|
||||
/// A User Defined file this session wrote: the library's name, and [`vectorcraft_doc::links::hash_bytes`]
|
||||
@@ -149,6 +152,38 @@ impl LibraryFile for SwatchLibrary {
|
||||
/// The extensions of library files [`palette_io::read_bytes`] reads.
|
||||
pub const LIBRARY_EXTS: &[&str] = &["vcswatches", "gpl", "ase", "acb"];
|
||||
|
||||
/// The extensions the Swatch Libraries filter of Other Library… lists: the library files, and the
|
||||
/// `.ai`, `.ait` and `.eps` (`.epsf`) documents whose swatches load as a library (`swatch.library.load`).
|
||||
pub const LIBRARY_PICK_EXTS: &[&str] = &["vcswatches", "gpl", "ase", "acb", "ai", "ait", "eps", "epsf"];
|
||||
|
||||
impl Libraries<SwatchLibrary> {
|
||||
/// Keep `doc`, the document loaded library `id` was read from, for its pattern swatches; `None`
|
||||
/// forgets the one kept for `id`.
|
||||
fn set_pattern_doc(&mut self, id: &str, doc: Option<Arc<vectorcraft_doc::Document>>) {
|
||||
match doc {
|
||||
Some(doc) => self.pattern_docs.insert(id.to_string(), doc),
|
||||
None => self.pattern_docs.remove(id),
|
||||
};
|
||||
}
|
||||
|
||||
/// The document holding the patterns of loaded library `id`'s pattern swatches.
|
||||
pub fn pattern_doc(&self, id: &str) -> Option<Arc<vectorcraft_doc::Document>> {
|
||||
self.pattern_docs.get(id).cloned()
|
||||
}
|
||||
|
||||
/// The document holding the pattern of swatch `w`, when `w` is one of a loaded library's own
|
||||
/// pattern swatches (a library panel draws them from it). Only the libraries that have pattern
|
||||
/// swatches are looked at, each by the address ranges of its swatch lists.
|
||||
pub fn pattern_source(&self, w: &Swatch) -> Option<Arc<vectorcraft_doc::Document>> {
|
||||
let Paint::Pattern { pattern, .. } = &w.paint else { return None };
|
||||
let at = std::ptr::from_ref(w);
|
||||
let holds = |v: &[Swatch]| v.as_ptr_range().contains(&at);
|
||||
let own = |lib: &SwatchLibrary| holds(&lib.swatches) || lib.groups.iter().any(|g| holds(&g.swatches));
|
||||
let (_, doc) = self.pattern_docs.iter().find(|(id, _)| self.extra.iter().any(|e| e.info.id == **id && own(&e.lib)))?;
|
||||
Some(doc.clone()).filter(|d| d.pattern(pattern).is_some())
|
||||
}
|
||||
}
|
||||
|
||||
/// A library file the save commands write ([`Libraries::write`]).
|
||||
pub(crate) enum FileData {
|
||||
/// Text (`.vcswatches`, `.gpl`, CSS, `.vcstyles`), returned as `data`.
|
||||
@@ -646,6 +681,12 @@ pub fn library_swatches(s: &Session, key: &str) -> Option<Vec<Swatch>> {
|
||||
Some(library(s, key)?.1.iter().filter(own).cloned().collect())
|
||||
}
|
||||
|
||||
/// The document holding the pattern of library swatch `w`: a built-in pattern library's or a loaded
|
||||
/// library's own pattern swatch (a library panel draws them from it).
|
||||
pub fn pattern_source(s: &Session, w: &Swatch) -> Option<Arc<vectorcraft_doc::Document>> {
|
||||
patternlib::swatch_source(w).or_else(|| s.swatch_libraries.pattern_source(w))
|
||||
}
|
||||
|
||||
/// The `limitTo` parameter's palette ([`limit_palette`]); `None` without one (or for "" or null).
|
||||
/// A `limitTo` that is not a string, such as `5`, names no library.
|
||||
pub(crate) fn limit_param(s: &Session, p: &Value, cmd: &str) -> Result<Option<Palette>> {
|
||||
@@ -694,13 +735,17 @@ fn list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
/// The document's swatches `names` (swatches or colour groups; empty: all) as a library named
|
||||
/// `name`, without None and patterns.
|
||||
fn document_library(d: &vectorcraft_doc::Document, names: &[String], name: String, cmd: &str) -> Result<SwatchLibrary> {
|
||||
/// `name`, without None, and without pattern swatches unless `patterns`.
|
||||
fn document_library(d: &vectorcraft_doc::Document, names: &[String], name: String, patterns: bool, cmd: &str) -> Result<SwatchLibrary> {
|
||||
if let Some(n) = names.iter().find(|n| !d.swatch_name_taken(n)) {
|
||||
return Err(bad(cmd, format!("no swatch or colour group `{n}`")));
|
||||
}
|
||||
let want = |n: &str| names.is_empty() || names.iter().any(|x| x == n);
|
||||
let savable = |w: &&Swatch| matches!(w.paint, Paint::Solid { .. } | Paint::Gradient(_));
|
||||
let savable = |w: &&Swatch| match w.paint {
|
||||
Paint::Solid { .. } | Paint::Gradient(_) => true,
|
||||
Paint::Pattern { .. } => patterns,
|
||||
_ => false,
|
||||
};
|
||||
let swatches = d.swatches.iter().filter(savable).filter(|w| want(&w.name)).cloned().collect();
|
||||
let groups = d
|
||||
.swatch_groups
|
||||
@@ -724,7 +769,7 @@ fn save(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let names = names_param(p, C)?;
|
||||
let st = s.doc()?;
|
||||
let name = text_param(p, "name", C)?.map(str::trim).filter(|n| !n.is_empty()).map_or_else(|| stem(&st.title()).to_string(), str::to_string);
|
||||
let lib = document_library(&st.doc, &names, name, C)?;
|
||||
let lib = document_library(&st.doc, &names, name, false, C)?;
|
||||
let bytes = palette_io::write(&lib, format).map_err(|e| bad(C, e))?;
|
||||
let data = if format.binary() { FileData::Binary(bytes) } else { FileData::Text(String::from_utf8_lossy(&bytes).into_owned()) };
|
||||
let mut out = json!({"format": format.id(), "count": lib.iter().filter(|w| format.holds(&w.paint)).count()});
|
||||
@@ -734,21 +779,44 @@ fn save(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn load(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "swatch.library.load";
|
||||
// The document a library with pattern swatches was read from, which holds their patterns.
|
||||
let mut patterns = None;
|
||||
let (info, lib) = s.swatch_libraries.load(p, C, |bytes, file| {
|
||||
// A library file, or a document whose swatches become the library.
|
||||
if palette_io::sniff_bytes(bytes) {
|
||||
palette_io::read_bytes(bytes, stem(file)).map_err(|e| bad(C, e))
|
||||
} else {
|
||||
let loaded = super::fileio::load(file, bytes).map_err(|e| bad(C, e.to_string()))?;
|
||||
if loaded.preview_only {
|
||||
return Err(bad(C, "only this Affinity file's embedded preview could be read; use File › Open to see it with its warning"));
|
||||
}
|
||||
document_library(&loaded.doc, &[], stem(file).to_string(), C)
|
||||
return palette_io::read_bytes(bytes, stem(file)).map_err(|e| bad(C, e));
|
||||
}
|
||||
let loaded = super::fileio::load(file, bytes).map_err(|e| bad(C, e.to_string()))?;
|
||||
if loaded.preview_only {
|
||||
return Err(bad(C, "only this Affinity file's embedded preview could be read; use File › Open to see it with its warning"));
|
||||
}
|
||||
// A `.ai`, EPS or PostScript file without a palette of its own opens with the default swatches.
|
||||
let defaults = matches!(loaded.format.id, "ai" | "ait" | "eps" | "ps") && has_only_default_swatches(&loaded.doc);
|
||||
let lib = document_library(&loaded.doc, &[], stem(file).to_string(), true, C)?;
|
||||
if defaults || lib.is_empty() {
|
||||
return Err(bad(C, format!("`{file}` has no swatches of its own")));
|
||||
}
|
||||
if lib.iter().any(|w| matches!(w.paint, Paint::Pattern { .. })) {
|
||||
patterns = Some(Arc::new(loaded.doc));
|
||||
}
|
||||
Ok(lib)
|
||||
})?;
|
||||
if info.category == "loaded" {
|
||||
s.swatch_libraries.set_pattern_doc(&info.id, patterns);
|
||||
}
|
||||
Ok(json!({"library": shown_library_id(s, &info.id), "name": info.name, "count": lib.len()}))
|
||||
}
|
||||
|
||||
/// `d`'s swatches and color groups are exactly the default ones of a color mode, as a new
|
||||
/// document's are.
|
||||
fn has_only_default_swatches(d: &vectorcraft_doc::Document) -> bool {
|
||||
use vectorcraft_color::cms::Model;
|
||||
[Model::Rgb, Model::Cmyk].into_iter().any(|model| {
|
||||
let (swatches, groups) = default_swatches(model);
|
||||
d.swatches[..] == swatches[..] && d.swatch_groups[..] == groups[..]
|
||||
})
|
||||
}
|
||||
|
||||
fn get(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (info, lib) = library_param(s, p, "swatch.library.get")?;
|
||||
let ungrouped = lib.swatches.iter().map(|w| swatch_json(w, None));
|
||||
@@ -772,6 +840,9 @@ fn copy_to_user(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "swatch.library.copyToUser";
|
||||
let (info, lib) = library_param(s, p, C)?;
|
||||
let (info, lib, copied) = match info.category {
|
||||
"loaded" if lib.iter().any(|w| matches!(w.paint, Paint::Pattern { .. })) => {
|
||||
return Err(bad(C, format!("`{}` has pattern swatches, which a .vcswatches file can't hold", info.name)));
|
||||
}
|
||||
"loaded" => {
|
||||
let native = |lib: &SwatchLibrary| palette_io::write(lib, PaletteFormat::Native).map_err(|e| bad(C, e));
|
||||
s.swatch_libraries.copy_to_user(&info.id, PaletteFormat::Native.id(), native, C)?
|
||||
@@ -811,6 +882,22 @@ fn picked<'a>(lib: &'a SwatchLibrary, names: &[String], cmd: &str) -> Result<Vec
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The swatch of `d` that library pattern swatch `w` stands for once its pattern is `target` in `d`:
|
||||
/// one that paints `target` placed as `w` places its pattern, named as `w` or a numbered copy of
|
||||
/// that name ("Tiles 2"); for a swatch named after its pattern, under any name.
|
||||
fn library_pattern_swatch(d: &vectorcraft_doc::Document, w: &Swatch, target: &str) -> Option<String> {
|
||||
let Paint::Pattern { pattern, xf } = &w.paint else { return None };
|
||||
let paint = Paint::Pattern { pattern: target.to_string(), xf: *xf };
|
||||
let named = |n: &str| {
|
||||
w.name == *pattern
|
||||
|| n == w.name
|
||||
|| n.strip_prefix(w.name.as_str())
|
||||
.and_then(|r| r.strip_prefix(' '))
|
||||
.is_some_and(|r| !r.is_empty() && r.bytes().all(|b| b.is_ascii_digit()))
|
||||
};
|
||||
d.swatches_iter().find(|x| x.paint == paint && named(&x.name)).map(|x| x.name.clone())
|
||||
}
|
||||
|
||||
/// Every name a swatch or colour group of `d` uses (they share one namespace, with the registration swatch).
|
||||
fn taken_names(d: &vectorcraft_doc::Document) -> HashSet<String> {
|
||||
let names = d.swatches_iter().map(|w| &w.name).chain(d.swatch_groups.iter().map(|g| &g.name));
|
||||
@@ -840,8 +927,9 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let focus = switch_or(p, "focus", true, 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.
|
||||
let patterns = patternlib::library_doc(&info.id);
|
||||
// same pattern) are reused, not added again. The patterns are in a built-in pattern library's
|
||||
// document, or in the document a loaded library was read from.
|
||||
let patterns = patternlib::library_doc(&info.id).or_else(|| s.swatch_libraries.pattern_doc(&info.id));
|
||||
let d = &s.doc()?.doc;
|
||||
// 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.
|
||||
@@ -851,7 +939,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let there = |w: &Swatch| match (&w.paint, &patterns) {
|
||||
(Paint::Pattern { pattern, .. }, Some(src)) => {
|
||||
patternlib::existing_pattern(d, src, pattern).and_then(|target| patternlib::pattern_swatch(d, &target))
|
||||
patternlib::present_pattern(d, src, pattern).and_then(|target| library_pattern_swatch(d, w, &target))
|
||||
}
|
||||
_ => match by_name.get(w.name.as_str()) {
|
||||
Some(x) => x.paint == w.paint,
|
||||
@@ -873,32 +961,64 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let added: Vec<(String, String)> = if fresh.is_empty() {
|
||||
vec![]
|
||||
} else {
|
||||
s.edit("Add to Swatches", |d, _| {
|
||||
let (added, reused) = 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![];
|
||||
// Each library group goes into one document group: the group of that name the document
|
||||
// already had, or one made here.
|
||||
let before = d.swatch_groups.len();
|
||||
let mut placed: Vec<(&str, usize)> = vec![];
|
||||
let mut taken = taken_names(d);
|
||||
// The swatches the patterns imported in this call brought with their art: (library
|
||||
// name, document name).
|
||||
let mut brought: Vec<(String, String)> = vec![];
|
||||
for (group, w) in fresh {
|
||||
if let (Paint::Pattern { pattern, .. }, Some(src)) = (&w.paint, &patterns) {
|
||||
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.
|
||||
let target = patternlib::import(d, src, pattern)?;
|
||||
let name = match patternlib::pattern_swatch(d, &target) {
|
||||
Some(name) => name,
|
||||
None => {
|
||||
let name = d.free_swatch_name(&target);
|
||||
d.swatches.push(Swatch { name: name.clone(), paint: pattern_paint(&target), global: false, spot: false });
|
||||
name
|
||||
}
|
||||
};
|
||||
out.push((w.name.clone(), name));
|
||||
// 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.
|
||||
let had = taken_names(d);
|
||||
let (target, colors) = patternlib::import(d, src, pattern)?;
|
||||
brought.extend(colors);
|
||||
if let Some(name) = library_pattern_swatch(d, w, &target).filter(|n| had.contains(n)) {
|
||||
reused.push((w.name.clone(), name));
|
||||
taken = taken_names(d);
|
||||
continue;
|
||||
}
|
||||
let made = patternlib::pattern_swatch(d, &target).filter(|n| !had.contains(n));
|
||||
if let Some(made) = &made {
|
||||
d.swatches.retain(|x| x.name != *made);
|
||||
}
|
||||
taken = taken_names(d);
|
||||
continue;
|
||||
}
|
||||
let name = free_in(&mut taken, &w.name);
|
||||
let sw = Swatch { name: name.clone(), ..(*w).clone() };
|
||||
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),
|
||||
};
|
||||
taken.insert(name.clone());
|
||||
// The library swatch's placement of its pattern is kept.
|
||||
let paint = match &w.paint {
|
||||
Paint::Pattern { xf, .. } => Paint::Pattern { pattern: target, xf: *xf },
|
||||
_ => pattern_paint(&target),
|
||||
};
|
||||
(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);
|
||||
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))
|
||||
});
|
||||
match moved {
|
||||
Some(sw) => (sw.name.clone(), sw),
|
||||
None => {
|
||||
let name = free_in(&mut taken, &w.name);
|
||||
(name.clone(), Swatch { name, ..(*w).clone() })
|
||||
}
|
||||
}
|
||||
};
|
||||
match group {
|
||||
Some(g) => {
|
||||
let found = placed.iter().find(|(n, _)| *n == g).map(|&(_, i)| i);
|
||||
@@ -919,8 +1039,10 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
out.push((w.name.clone(), name));
|
||||
}
|
||||
Ok(out)
|
||||
})?
|
||||
Ok((out, reused))
|
||||
})?;
|
||||
existing.extend(reused);
|
||||
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)});
|
||||
|
||||
@@ -314,12 +314,12 @@ pub(crate) fn follow_history(st: &mut crate::DocState, was: Option<&SymbolEdit>)
|
||||
}
|
||||
}
|
||||
|
||||
/// Does `n` hold an instance of symbol `name`, directly or through the art of the symbols it holds
|
||||
/// instances of?
|
||||
fn holds_symbol(d: &Document, n: &Node, name: &str, seen: &mut HashSet<String>) -> bool {
|
||||
/// Does `n` hold an instance of symbol `name` (opacity masks included), directly or through the art
|
||||
/// of the symbols it holds instances of?
|
||||
pub(crate) fn holds_symbol(d: &Document, n: &Node, name: &str, seen: &mut HashSet<String>) -> bool {
|
||||
let mut found = false;
|
||||
let mut nested = vec![];
|
||||
n.walk(&mut |c| {
|
||||
vectorcraft_doc::swatches::walk_with_masks(n, &mut |c| {
|
||||
if let NodeKind::SymbolInstance { symbol, .. } = &c.kind {
|
||||
if symbol == name {
|
||||
found = true;
|
||||
|
||||
@@ -20,7 +20,7 @@ use super::clipboard::Clipboard;
|
||||
use super::clipboard::resources::SwatchChoices;
|
||||
use super::swatch::str_list;
|
||||
use super::swatchlib::{FileData, LibraryFile, LibraryInfo, concealed_library_id, concealed_library_ids, shown_id, shown_library_id, stem};
|
||||
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, number_or, str_param};
|
||||
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, number_or, str_param, u64_req};
|
||||
|
||||
/// The extension of saved symbol libraries: native documents.
|
||||
pub const SYMBOLS_EXT: &str = vectorcraft_format::EXTENSION;
|
||||
@@ -54,6 +54,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
add
|
||||
),
|
||||
cmd!(
|
||||
"symbol.placeFromDocument",
|
||||
"Place Symbol Instance",
|
||||
[],
|
||||
None,
|
||||
"{sourceDocument: uid, name: a symbol of that document, x?, y?} place an instance of a symbol of another open document so its registration point is at (x, y) (default: the first artboard's center), as a symbol dragged from that document's Symbols panel onto the canvas is placed. The symbol, the symbols it nests and the resources they use are added as a drop of art from that document adds them, in the same undo step as the instance: a symbol the active document already has with the same name, art and Symbol Options is used, and one with the same name but other art or Symbol Options gets a number (\"Leaf 2\"); each symbol added takes its Symbol Options along. When sourceDocument is the active document, its own symbol is placed, as symbol.place places it. An error, with no edit, when that document is no longer open or has no symbol `name` → {id, name: the symbol's name in the active document}",
|
||||
has_doc,
|
||||
place_from_document
|
||||
),
|
||||
cmd!(
|
||||
"symbol.saveLibrary",
|
||||
"Save Symbol Library…",
|
||||
@@ -630,6 +639,46 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// `symbol.placeFromDocument`: an instance of symbol `name` of the open document `sourceDocument`
|
||||
/// placed in the active document, with the symbol and the resources it uses added as a drop of
|
||||
/// art from that document adds them, in one undo step. The source document is not changed.
|
||||
fn place_from_document(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "symbol.placeFromDocument";
|
||||
let uid = u64_req(p, "sourceDocument", C)?;
|
||||
let name = str_param(p, "name").ok_or_else(|| bad(C, "missing `name`"))?;
|
||||
let st = s.doc()?;
|
||||
let centre = st.doc.artboards.first().map(|a| a.rect.center()).unwrap_or(Point::ZERO);
|
||||
let at = Point::new(number_or(p, "x", centre.x, C)?, number_or(p, "y", centre.y, C)?);
|
||||
let parent = st.target_parent()?;
|
||||
let same = uid == st.uid;
|
||||
let src = s.documents().iter().find(|d| d.uid == uid).map(|d| Arc::clone(&d.doc));
|
||||
let src = src.ok_or_else(|| bad(C, "the document the symbol came from is no longer open"))?;
|
||||
if !src.symbols.iter().any(|sym| sym.name == name) {
|
||||
return Err(bad(C, format!("no symbol named `{name}` in the document it came from")));
|
||||
}
|
||||
// A symbol of the active document itself is placed as it is.
|
||||
let clip = (!same).then(|| Clipboard::gather(&src, vec![instance(name)]));
|
||||
// The source's colors are kept even where the active document has swatches of the same names.
|
||||
let choices = SwatchChoices::parse(C, &json!({"swatchConflict": "add"}))?;
|
||||
let (id, placed) = s.edit("Place Symbol Instance", |d, sel| {
|
||||
let placed = match &clip {
|
||||
// Each symbol added takes its Symbol Options along.
|
||||
Some(clip) => {
|
||||
let imported = clip.import_into(d, &choices, false)?;
|
||||
let renamed = imported.renamed.iter().find(|r| r["kind"] == "symbol" && r["from"] == name).and_then(|r| r["to"].as_str());
|
||||
renamed.unwrap_or(name).to_string()
|
||||
}
|
||||
None => name.to_string(),
|
||||
};
|
||||
let xf = place_xf(at, natural_size(d, &placed), d.symbol_registration(&placed));
|
||||
let id = d.alloc_id();
|
||||
d.insert(parent, usize::MAX, Node::new(id, NodeKind::SymbolInstance { symbol: placed.clone(), xf }))?;
|
||||
sel.set([id]);
|
||||
Ok((id, placed))
|
||||
})?;
|
||||
Ok(json!({ "id": id.0, "name": placed }))
|
||||
}
|
||||
|
||||
fn save(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "symbol.saveLibrary";
|
||||
let st = s.doc()?;
|
||||
|
||||
@@ -1883,13 +1883,14 @@ enum Step {
|
||||
BaselineShift,
|
||||
}
|
||||
|
||||
/// The Type tool's selected text while it edits (its typing session ends first: one undo 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) };
|
||||
if super::edit::typing_in_progress(s) {
|
||||
s.set_tool_option("commitTyping", &Value::Bool(true));
|
||||
s.commit_interaction()?;
|
||||
super::edit::settle_interaction(s)?;
|
||||
}
|
||||
let at = |k: &str| byte_param(&o, k).unwrap_or(0);
|
||||
Ok(Some((id, at("start"), at("end"))))
|
||||
|
||||
@@ -488,8 +488,14 @@ fn selection_attrs(s: &Session, p: &Value, kind: Kind, verb: &str) -> Result<Opt
|
||||
};
|
||||
char_attrs(&style)
|
||||
}
|
||||
// The paragraph at `start`.
|
||||
Kind::Para => para_attrs(t.para_at(t.paragraphs_in(at, at).start)),
|
||||
// The paragraph at `start`, without the number its list gives that paragraph alone.
|
||||
Kind::Para => {
|
||||
let mut para = t.para_at(t.paragraphs_in(at, at).start).clone();
|
||||
if let Some(l) = para.list.as_mut() {
|
||||
l.start = None;
|
||||
}
|
||||
para_attrs(¶)
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -516,14 +522,16 @@ pub(crate) fn style_attrs(d: &Document, para: bool, name: &str) -> Option<Map<St
|
||||
if para { Kind::Para } else { Kind::Char }.attrs(d, name)
|
||||
}
|
||||
|
||||
/// The fill of `[Normal Character Style]` in `d`: black, or the fill a redefinition gave it. New
|
||||
/// type starts in that style ([Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html):
|
||||
/// every character is in it by default; [FAQs on fonts](https://helpx.adobe.com/illustrator/using/fonts-faq.html):
|
||||
/// new type's defaults are changed by editing it), so it takes this fill, not the current fill
|
||||
/// left from the last shape (#7975).
|
||||
pub(crate) fn normal_char_fill(d: &Document) -> vectorcraft_color::Paint {
|
||||
/// `[Normal Character Style]` in `d`: the defaults, with whatever a redefinition gave it (font,
|
||||
/// size, fill…). New type starts in that style ([Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html):
|
||||
/// every character is in it by default; [FAQs on fonts](https://helpx.adobe.com/illustrator/using/fonts-faq.html)
|
||||
/// and [Change the default font](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/change-the-default-font-in-illustrator.html):
|
||||
/// new type's defaults, its font included, are changed by editing it), so it takes this style's
|
||||
/// font and fill, not the current fill left from the last shape (#7975). Attributes that don't
|
||||
/// pass its checks leave the defaults.
|
||||
pub(crate) fn normal_char_style(d: &Document) -> CharStyle {
|
||||
let normal = Kind::Char.attrs(d, NORMAL_CHAR).unwrap_or_default();
|
||||
with_attrs(&CharStyle::default(), &normal, "text.create").map_or_else(|_| CharStyle::default().fill, |st| st.fill)
|
||||
with_attrs(&CharStyle::default(), &normal, "text.create").unwrap_or_default()
|
||||
}
|
||||
|
||||
/// `attrs` in the form `charStyle.new` (`para`: `paraStyle.new`) stores them in `d`, or `None`
|
||||
@@ -639,6 +647,11 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma
|
||||
}
|
||||
Kind::Para => {
|
||||
let mut st = with_attrs(&ParaStyle::default(), m, &c)?;
|
||||
// A list's number belongs to one paragraph, not to a style.
|
||||
if st.list.is_some_and(|l| l.start.is_some()) {
|
||||
let k = "list.start";
|
||||
return Err(bad(&c, format!("unknown attribute `{k}`")));
|
||||
}
|
||||
para_ranges(&st, m, kept, &c)?;
|
||||
sort_tabs(&mut st, m, kept);
|
||||
para_attrs(&st)
|
||||
|
||||
@@ -95,7 +95,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Area Type Options…",
|
||||
["Type"],
|
||||
None,
|
||||
"{ids?|id?, width?: pt, height?: pt, rows?, columns?, gutter?: pt (between rows and columns), rowGutter?: pt|null (between rows when it differs from gutter, which is then between columns; gutter given alone sets both; the reply gives the rows' gutter either way), inset?: pt, firstBaseline?: ascent|capHeight|xHeight|leading|fixed, firstBaselineMin?: pt, verticalAlign?: top|center|bottom|justify, flow?: columns|rows (Text Flow: down each column's rows, then across, the default; or across each row's columns, then down), fit?: none|autoHeight|shrinkText|block, fitMinPercent?: 10..100, wordGap?: % 0..1000, lineGap?: pt -1296..1296, …the keys of its own reply (it can be passed back; the values it only reports are ignored)} set the selected area type's options (each frame takes the options given over its own and keeps the rest; fit resolves against each frame's own; options that change nothing add no undo step); width and height size the type area from its top-left corner, along the type's own axes, and the text reflows at its size (with fit autoHeight, Auto Size, the frame's height follows the text after every edit and height is ignored; setting the height by hand turns it off); fit shrinkText scales overflowing text down (size, leading, baseline shift) by the largest factor down to fitMinPercent % (default 50) that makes it fit; fit block is Dynamic Text's Block, as type.dynamicText sets it (in place of Auto Size and Shrink Text to Fit; threaded frames are refused; another fit turns it off, keeping the sizes it wrote), and wordGap and lineGap set its gaps (kept while Block is off; out of range is an error) (none given: query) → the first object's options, plus wordGap and lineGap, overflow (the text doesn't fit its frame) and fitScale (Shrink Text's factor, 1 unshrunk)",
|
||||
"{ids?|id?, width?: pt, height?: pt, rows?, columns?, gutter?: pt (between rows and columns), rowGutter?: pt|null (between rows when it differs from gutter, which is then between columns; gutter given alone sets both; the reply gives the rows' gutter either way), inset?: pt, firstBaseline?: ascent|capHeight|xHeight|leading|emBoxHeight|fixed (emBoxHeight: the top of the first line's ideographic em box, the largest on the line, touches the top of the type area inside the inset), firstBaselineMin?: pt (the least distance from that top to the first baseline; with fixed, the distance), verticalAlign?: top|center|bottom|justify, flow?: columns|rows (Text Flow: down each column's rows, then across, the default; or across each row's columns, then down), fit?: none|autoHeight|shrinkText|block, fitMinPercent?: 10..100, wordGap?: % 0..1000, lineGap?: pt -1296..1296, …the keys of its own reply (it can be passed back; the values it only reports are ignored)} set the selected area type's options (each frame takes the options given over its own and keeps the rest; fit resolves against each frame's own; options that change nothing add no undo step); width and height size the type area from its top-left corner, along the type's own axes, and the text reflows at its size (with fit autoHeight, Auto Size, the frame's height follows the text after every edit and height is ignored; setting the height by hand turns it off); fit shrinkText scales overflowing text down (size, leading, baseline shift) by the largest factor down to fitMinPercent % (default 50) that makes it fit; fit block is Dynamic Text's Block, as type.dynamicText sets it (in place of Auto Size and Shrink Text to Fit; threaded frames are refused; another fit turns it off, keeping the sizes it wrote), and wordGap and lineGap set its gaps (kept while Block is off; out of range is an error) (none given: query) → the first object's options, plus wordGap and lineGap, overflow (the text doesn't fit its frame) and fitScale (Shrink Text's factor, 1 unshrunk)",
|
||||
has_selection,
|
||||
area_options
|
||||
),
|
||||
|
||||
@@ -736,6 +736,189 @@ fn numbered_lists_are_set_per_paragraph_saved_and_styled() {
|
||||
assert_eq!((list(&s, 0), list(&s, 1), list(&s, 2)), (None, None, None));
|
||||
}
|
||||
|
||||
/// `text.setFormat {startNumber}` gives the first numbered paragraph it touches a number, and the
|
||||
/// paragraphs after it count on from it; `restartNumbering` true gives it 1 and false takes the
|
||||
/// numbers away. Each change is one undo step, a call that changes nothing records none, and a
|
||||
/// bad value or both keys change nothing. The file keeps the number, Return and paragraph styles
|
||||
/// do not take it, a bulleted paragraph keeps none, and Convert to Text writes the numbers shown.
|
||||
#[test]
|
||||
fn a_numbered_paragraph_starts_at_a_given_number_or_restarts() {
|
||||
use vectorcraft_doc::text::{Bullet, ParaList};
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
let id = s
|
||||
.execute("text.create", &json!({"x": 10, "y": 10, "text": "Intro\nOne\nTwo\nThree\nFour", "area": {"width": 300, "height": 200}}))
|
||||
.unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
let text = |s: &Session| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind {
|
||||
NodeKind::Text(t) => (**t).clone(),
|
||||
_ => panic!("text"),
|
||||
};
|
||||
let starts = |s: &Session| text(s).paragraph_styles().iter().map(|p| p.list.and_then(|l| l.start)).collect::<Vec<_>>();
|
||||
let numbers = |s: &Session| {
|
||||
vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &text(s)).markers.iter().map(|m| m.text.clone()).collect::<Vec<_>>()
|
||||
};
|
||||
let undo = |s: &Session| s.active().unwrap().history.undo.len();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
// A call over all the text gives the number to the first paragraph the same call numbers.
|
||||
s.execute("text.setFormat", &json!({"start": 6, "end": 24, "number": "arabic", "startNumber": 5})).unwrap();
|
||||
assert_eq!(starts(&s), [None, Some(5), None, None, None]);
|
||||
assert_eq!(numbers(&s), ["5.", "6.", "7.", "8."]);
|
||||
// On "Three": `restartNumbering` gives it 1, and "Four" counts on from it.
|
||||
let steps = undo(&s);
|
||||
s.execute("text.setFormat", &json!({"start": 14, "end": 14, "restartNumbering": true})).unwrap();
|
||||
assert_eq!((numbers(&s), undo(&s)), (vec!["5.".to_string(), "6.".into(), "1.".into(), "2.".into()], steps + 1));
|
||||
// The same number again, or a call on a paragraph in no list, changes nothing.
|
||||
s.execute("text.setFormat", &json!({"start": 14, "end": 14, "startNumber": 1.0})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"start": 0, "end": 0, "startNumber": 3})).unwrap();
|
||||
assert_eq!((starts(&s), undo(&s)), (vec![None, Some(5), None, Some(1), None], steps + 1));
|
||||
// Bad values and both keys at once are errors and change nothing.
|
||||
for bad in [
|
||||
json!({"startNumber": 0}),
|
||||
json!({"startNumber": -2}),
|
||||
json!({"startNumber": 2.5}),
|
||||
json!({"startNumber": 1_000_000_000}),
|
||||
json!({"startNumber": "5"}),
|
||||
json!({"restartNumbering": "yes"}),
|
||||
json!({"startNumber": 3, "restartNumbering": true}),
|
||||
] {
|
||||
assert!(s.execute("text.setFormat", &bad).is_err(), "{bad}");
|
||||
}
|
||||
assert_eq!((starts(&s), undo(&s)), (vec![None, Some(5), None, Some(1), None], steps + 1));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(numbers(&s), ["5.", "6.", "7.", "8."], "one Undo takes the restart back");
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
// The file keeps the numbers.
|
||||
assert_eq!(serde_json::to_value(text(&s).para_at(1)).unwrap()["list"], json!({"bullet": "dot", "number": "arabic", "start": 5}));
|
||||
let reopened = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap();
|
||||
let Some(NodeKind::Text(back)) = reopened.node(NodeId(id)).map(|n| &n.kind) else { panic!("text") };
|
||||
assert_eq!(back.paragraph_styles(), text(&s).paragraph_styles());
|
||||
// Return at the end of "One" makes an item that counts on, without a number of its own.
|
||||
s.execute("text.editRange", &json!({"id": id, "start": 9, "end": 9, "insert": "\nOne and a half"})).unwrap();
|
||||
assert_eq!(numbers(&s), ["5.", "6.", "7.", "1.", "2."]);
|
||||
assert_eq!(starts(&s), [None, Some(5), None, None, Some(1), None]);
|
||||
// A paragraph style made from the paragraph does not keep its number, and a style's list
|
||||
// with a number is an error.
|
||||
s.execute("paraStyle.new", &json!({"name": "Item", "id": id, "start": 6, "end": 6})).unwrap();
|
||||
s.execute("paraStyle.apply", &json!({"name": "Item", "id": id})).unwrap();
|
||||
assert_eq!(starts(&s), [None; 6]);
|
||||
assert_eq!(numbers(&s), ["1.", "2.", "3.", "4.", "5.", "6."]);
|
||||
let given = json!({"name": "Given", "attrs": {"list": {"number": "arabic", "start": 4}}});
|
||||
assert!(s.execute("paraStyle.new", &given).is_err());
|
||||
// `restartNumbering` false takes every number the call touches away; a paragraph made bulleted
|
||||
// keeps none.
|
||||
s.execute("text.setFormat", &json!({"start": 0, "end": 0, "startNumber": 7})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"start": 6, "end": 6, "startNumber": 3})).unwrap();
|
||||
assert_eq!(starts(&s)[..2], [Some(7), Some(3)]);
|
||||
s.execute("text.setFormat", &json!({"restartNumbering": false})).unwrap();
|
||||
assert_eq!(starts(&s), [None; 6]);
|
||||
s.execute("text.setFormat", &json!({"start": 0, "end": 0, "startNumber": 7})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"start": 0, "end": 0, "bullet": "dot"})).unwrap();
|
||||
assert_eq!(text(&s).para_at(0).list, Some(ParaList::bulleted(Bullet::Dot)));
|
||||
s.execute("text.setFormat", &json!({"start": 0, "end": 0, "number": "upperRoman"})).unwrap();
|
||||
assert_eq!(text(&s).para_at(0).list.and_then(|l| l.start), None, "numbered again, it counts on");
|
||||
// Convert to Text writes the numbers the paragraphs showed.
|
||||
s.execute("text.setFormat", &json!({"start": 0, "end": 0, "number": "arabic", "startNumber": 10})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"start": 30, "end": 30, "restartNumbering": true})).unwrap();
|
||||
let shown = numbers(&s);
|
||||
assert_eq!(shown, ["10.", "11.", "12.", "13.", "1.", "2."]);
|
||||
s.execute("text.convertListToText", &json!({})).unwrap();
|
||||
let written: Vec<String> = text(&s).plain_text().split('\n').map(|p| p.split('\t').next().unwrap_or("").to_string()).collect();
|
||||
assert_eq!(written, shown);
|
||||
assert_eq!(starts(&s), [None; 6]);
|
||||
assert!(text(&s).paragraph_styles().iter().all(|p| p.list.is_none()));
|
||||
}
|
||||
|
||||
/// In threaded type, a paragraph given a number in the first frame carries its count on through
|
||||
/// the later frames, and a paragraph given 1 in a later frame starts the count again there.
|
||||
#[test]
|
||||
fn a_given_number_carries_through_threaded_frames() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 300})).unwrap();
|
||||
let numbers = |s: &Session, id: u64| {
|
||||
let Some(NodeKind::Text(t)) = s.doc().unwrap().doc.node(NodeId(id)).map(|n| &n.kind) else { panic!("text") };
|
||||
vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).markers.iter().map(|m| m.text.clone()).collect::<Vec<_>>()
|
||||
};
|
||||
let story = (1..=10).map(|i| format!("Item {i}")).collect::<Vec<_>>().join("\n");
|
||||
let a =
|
||||
s.execute("text.create", &json!({"x": 10, "y": 10, "text": story, "area": {"width": 150, "height": 60}})).unwrap()["id"].as_u64().unwrap();
|
||||
let b = s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 150, "height": 200})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
|
||||
s.execute("text.thread.create", &json!({})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"ids": [a, b], "list": "number"})).unwrap();
|
||||
let first = numbers(&s, a).len();
|
||||
assert!((2..10).contains(&first), "both frames hold items: {first}");
|
||||
s.execute("text.setFormat", &json!({"ids": [a], "start": 0, "end": 0, "startNumber": 20})).unwrap();
|
||||
let want: Vec<String> = (20..30).map(|n| format!("{n}.")).collect();
|
||||
assert_eq!([numbers(&s, a), numbers(&s, b)].concat(), want);
|
||||
// The first paragraph of the second frame given 1: the second frame counts from 1.
|
||||
s.execute("text.setFormat", &json!({"ids": [b], "start": 0, "end": 0, "restartNumbering": true})).unwrap();
|
||||
let want: Vec<String> = (20..20 + first).chain(1..=10 - first).map(|n| format!("{n}.")).collect();
|
||||
assert_eq!([numbers(&s, a), numbers(&s, b)].concat(), want);
|
||||
// Editing the first frame's number moves every later number on with it.
|
||||
s.execute("text.setFormat", &json!({"ids": [a], "start": 0, "end": 0, "startNumber": 2})).unwrap();
|
||||
let want: Vec<String> = (2..2 + first).chain(1..=10 - first).map(|n| format!("{n}.")).collect();
|
||||
assert_eq!([numbers(&s, a), numbers(&s, b)].concat(), want);
|
||||
}
|
||||
|
||||
/// A number given in a threaded frame whose first paragraph continues from the frame before goes
|
||||
/// to the next numbered paragraph that begins in that frame, not to the item the earlier frame shows,
|
||||
/// and `restartNumbering` false there leaves that item's number alone.
|
||||
#[test]
|
||||
fn a_given_number_skips_the_paragraph_continued_from_the_frame_before() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 300})).unwrap();
|
||||
let text = |s: &Session, id: u64| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind {
|
||||
NodeKind::Text(t) => (**t).clone(),
|
||||
_ => panic!("text"),
|
||||
};
|
||||
let numbers = |s: &Session, id: u64| {
|
||||
vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &text(s, id)).markers.iter().map(|m| m.text.clone()).collect::<Vec<_>>()
|
||||
};
|
||||
let long = (1..=40).map(|i| format!("word{i}")).collect::<Vec<_>>().join(" ");
|
||||
let story = format!("One\n{long}\nThree");
|
||||
let a =
|
||||
s.execute("text.create", &json!({"x": 10, "y": 10, "text": story, "area": {"width": 150, "height": 60}})).unwrap()["id"].as_u64().unwrap();
|
||||
let b = s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 150, "height": 250})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
|
||||
s.execute("text.thread.create", &json!({})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"ids": [a, b], "list": "number"})).unwrap();
|
||||
assert!(text(&s, b).first_para_continues, "the second frame starts inside the long paragraph");
|
||||
assert_eq!((numbers(&s, a), numbers(&s, b)), (vec!["1.".to_string(), "2.".into()], vec!["3.".to_string()]));
|
||||
s.execute("text.setFormat", &json!({"ids": [b], "startNumber": 5})).unwrap();
|
||||
assert_eq!((numbers(&s, a), numbers(&s, b)), (vec!["1.".to_string(), "2.".into()], vec!["5.".to_string()]));
|
||||
// The long item, numbered in the first frame, keeps its number when the second frame's are taken away.
|
||||
s.execute("text.setFormat", &json!({"ids": [a], "start": 4, "end": 4, "startNumber": 8})).unwrap();
|
||||
assert_eq!((numbers(&s, a), numbers(&s, b)), (vec!["1.".to_string(), "8.".into()], vec!["5.".to_string()]));
|
||||
s.execute("text.setFormat", &json!({"ids": [b], "restartNumbering": false})).unwrap();
|
||||
assert_eq!((numbers(&s, a), numbers(&s, b)), (vec!["1.".to_string(), "8.".into()], vec!["9.".to_string()]));
|
||||
}
|
||||
|
||||
/// `startNumber` over several type objects goes to the first numbered paragraph with text among
|
||||
/// all of them, past an empty numbered object listed first; with no text anywhere it goes to the
|
||||
/// first numbered paragraph.
|
||||
#[test]
|
||||
fn a_given_number_goes_to_the_first_numbered_text_across_objects() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
let make =
|
||||
|s: &mut Session, y: u32, text: &str| s.execute("text.create", &json!({"x": 10, "y": y, "text": text})).unwrap()["id"].as_u64().unwrap();
|
||||
let empty = make(&mut s, 10, "");
|
||||
let full = make(&mut s, 60, "One\nTwo");
|
||||
let start = |s: &Session, id: u64| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind {
|
||||
NodeKind::Text(t) => t.para_at(0).list.and_then(|l| l.start),
|
||||
_ => panic!("text"),
|
||||
};
|
||||
s.execute("text.setFormat", &json!({"ids": [empty, full], "number": "arabic"})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"ids": [empty, full], "startNumber": 4})).unwrap();
|
||||
assert_eq!((start(&s, empty), start(&s, full)), (None, Some(4)));
|
||||
let other = make(&mut s, 120, "");
|
||||
s.execute("text.setFormat", &json!({"ids": [other, empty], "number": "arabic"})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"ids": [other, empty], "startNumber": 6})).unwrap();
|
||||
assert_eq!((start(&s, other), start(&s, empty)), (Some(6), None));
|
||||
}
|
||||
|
||||
/// Bullets and Numbering… › Alignment: `text.setFormat {listAlign}` sets where the marker
|
||||
/// stands in the list paragraphs it touches, in one undo step, and refuses unknown values;
|
||||
/// a paragraph in no list gets no list from it. A list keeps its alignment when it changes
|
||||
@@ -2613,6 +2796,44 @@ fn area_options_columns_change_layout() {
|
||||
assert!(s.execute("text.areaOptions", &json!({"firstBaseline": "nope"})).is_err());
|
||||
}
|
||||
|
||||
/// First Baseline Em Box Height: set, reported and undone like the other kinds, with Min as the
|
||||
/// least distance; setting it again adds no undo step, and the refusal of an unknown kind lists it.
|
||||
#[test]
|
||||
fn area_options_set_the_em_box_height_first_baseline() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
let id = s.execute("text.create", &json!({"x": 10, "y": 10, "text": "word ".repeat(20), "area": {"width": 300, "height": 120}})).unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
let first = |s: &Session| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind {
|
||||
NodeKind::Text(t) => vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).lines[0].first_baseline,
|
||||
_ => panic!("area type"),
|
||||
};
|
||||
let ascent = first(&s);
|
||||
let r = s.execute("text.areaOptions", &json!({"firstBaseline": "emBoxHeight"})).unwrap();
|
||||
assert_eq!((r["firstBaseline"].as_str(), r["firstBaselineMin"].as_f64()), (Some("emBoxHeight"), Some(0.0)));
|
||||
let em_box = first(&s);
|
||||
assert!(em_box > 0.0 && (em_box - ascent).abs() > 0.1, "{em_box} {ascent}");
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
s.execute("text.areaOptions", &json!({"firstBaseline": "emBoxHeight"})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "no change, no undo step");
|
||||
// A Min nearer the top keeps the em box; one further down is the distance.
|
||||
s.execute("text.areaOptions", &json!({"firstBaselineMin": em_box / 2.0})).unwrap();
|
||||
assert!((first(&s) - em_box).abs() < 1e-9);
|
||||
let r = s.execute("text.areaOptions", &json!({"firstBaselineMin": 30})).unwrap();
|
||||
assert_eq!((r["firstBaseline"].as_str(), r["firstBaselineMin"].as_f64()), (Some("emBoxHeight"), Some(30.0)));
|
||||
assert!((first(&s) - 30.0).abs() < 1e-9);
|
||||
for _ in 0..3 {
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
}
|
||||
assert_eq!(s.execute("text.areaOptions", &json!({})).unwrap()["firstBaseline"], "ascent");
|
||||
assert!((first(&s) - ascent).abs() < 1e-9);
|
||||
let e = s.execute("text.areaOptions", &json!({"firstBaseline": "emBox"})).unwrap_err().to_string();
|
||||
assert!(e.contains("emBoxHeight"), "{e}");
|
||||
assert_eq!(s.execute("text.areaOptions", &json!({})).unwrap()["firstBaseline"], "ascent");
|
||||
}
|
||||
|
||||
/// `rowGutter` sets a gutter between rows of its own, the reply passes it back, and a gutter
|
||||
/// given alone is the rows' and the columns' again.
|
||||
#[test]
|
||||
|
||||
@@ -8,7 +8,8 @@
|
||||
//! variable name per column, which export writes with `#` before a visibility variable and `@`
|
||||
//! before an image variable); import replaces the datasets, names the rows Data Set 1, 2…,
|
||||
//! also reads tab-separated files, and reads header cells that define new variables (`#` for
|
||||
//! visibility, `@` for image, no prefix for text). `variable.loadLibrary` replaces the variables and data sets with the
|
||||
//! visibility, `@` for image, `%` for graph, whose cells name graph data files, no prefix for
|
||||
//! text). `variable.loadLibrary` replaces the variables and data sets with the
|
||||
//! variables and data sets of a variable library, the XML file of the reference app's Save
|
||||
//! Variable Library, and `variable.saveLibrary` writes the variables and data sets as one.
|
||||
//! `variable.import` (the panel's Import…) runs one of the two readers by the file's extension.
|
||||
@@ -1070,7 +1071,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Import Data Sets…",
|
||||
["Window", "Variables"],
|
||||
None,
|
||||
"{path? | data? | dataBase64? | csv?} replace every dataset with the rows of a CSV, comma- or tab-separated, in UTF-16 (with a byte-order mark, or without one when at least half of its two-byte units hold a NUL byte and only one byte order reads a line break; any other file with NUL bytes is refused), UTF-8 or else Windows-1252 (header: one variable name per column, whatever its case; one row per dataset, named Data Set 1, 2… in file order). The document's variables and their bindings stay. A header that names no variable defines one, unbound: `#Name` defines a visibility variable, `@Name` defines an image variable, and a header without a prefix defines a text variable. A prefixed header whose name is a variable of another kind, and a `%` header that isn't a variable's exact name (graph data files), are refused, and so are two headers that name one variable and a header that would define a variable while the variables are locked. An import that leaves the variables and data sets as they were adds no undo step → {imported, names, defined, deletedDataSets}",
|
||||
"{path? | data? | dataBase64? | csv?, base?: folder} replace every dataset with the rows of a CSV, comma- or tab-separated, in UTF-16 (with a byte-order mark, or without one when at least half of its two-byte units hold a NUL byte and only one byte order reads a line break; any other file with NUL bytes is refused), UTF-8 or else Windows-1252 (header: one variable name per column, whatever its case; one row per dataset, named Data Set 1, 2… in file order). The document's variables and their bindings stay. A header that names no variable defines one, unbound: `#Name` defines a visibility variable, `@Name` defines an image variable, `%Name` defines a graph variable, and a header without a prefix defines a text variable. A `%Name` column's cells are paths of graph data files, each read as Graph Data's Import Data reads one (at most 1 MB; tab-separated when a line holds a tab, else comma-separated; UTF-16 by dataset.import's rule, else UTF-8, with bytes that aren't UTF-8 read as replacement characters; the first row holds the series labels and the first column the category labels) and kept as the data set's graph value, which applies as graph.setData applies it. The files are read at import. A relative path is taken from `base`, else from the folder of the CSV file at `path`; with neither, it is refused (an `@Name` column's relative paths are kept as they are and taken from the document's folder when a data set is selected). A path on another computer, or on a network share other than the one `base` or the CSV is on, a device and a URL other than a `file:` URL without a host are refused, as image variables' paths are, before anything is read. A file that is missing, can't be read or is larger than 1 MB, a file that gives a graph value longer than 256 KB, and `%` columns whose files and graph values hold more than 256 MB in all (each file counted once, each cell's value every time) refuse the import, naming the line and the column. A prefixed header whose name is a variable of another kind is refused, and so are two headers that name one variable and a header that would define a variable while the variables are locked. An import that leaves the variables and data sets as they were adds no undo step → {imported, names, defined, deletedDataSets}",
|
||||
has_doc,
|
||||
dataset_import
|
||||
),
|
||||
|
||||
@@ -3,6 +3,7 @@ use super::{
|
||||
json, read_file_head, str_param, variables_unlocked, write_file,
|
||||
};
|
||||
use crate::cmd::place::text::windows_1252;
|
||||
use crate::cmd::{MAX_GRAPH_DATA_FILE, text_param};
|
||||
|
||||
/// Cap on a graph variable's CSV (MCP and files are untrusted).
|
||||
pub(super) const MAX_GRAPH_CSV: usize = 256 * 1024;
|
||||
@@ -268,10 +269,11 @@ fn export_header(v: &Variable) -> String {
|
||||
|
||||
/// What [`dataset_import`] does with each variable's column of the CSV that [`datasets_to_csv`]
|
||||
/// writes, in a document without the variables: the first list names the variables whose header
|
||||
/// or values it refuses, so it doesn't import the file (a `%` header, a `#` header whose values
|
||||
/// aren't true or false, a header that names a variable an earlier column named), and the second
|
||||
/// the variables it reads as another variable (a text variable whose name starts with `#` or `@`,
|
||||
/// and a graph variable, which no header cell defines).
|
||||
/// or values it refuses, so it doesn't import the file (a `%` header over values, which it reads as
|
||||
/// paths of graph data files, a `#` header whose values aren't true or false, a header that names
|
||||
/// a variable an earlier column named), and the second the variables it reads as another variable
|
||||
/// (a variable whose name starts with `#`, `@` or `%` and isn't of that prefix's kind, and a graph
|
||||
/// variable, which the export writes without `%`).
|
||||
fn kinds_a_new_document_loses(vars: &Variables) -> (Vec<&str>, Vec<&str>) {
|
||||
const C: &str = "dataset.import";
|
||||
let none = BTreeMap::new();
|
||||
@@ -287,9 +289,11 @@ fn kinds_a_new_document_loses(vars: &Variables) -> (Vec<&str>, Vec<&str>) {
|
||||
refused.push(v.name.as_str());
|
||||
continue;
|
||||
};
|
||||
// A `%` header's cells are paths of graph data files, which the values the export writes aren't.
|
||||
let files = kind == VariableKind::Graph && name != cell;
|
||||
let cells_read = vars.datasets.iter().filter_map(|d| d.values.get(&v.name)).all(|val| {
|
||||
let cell = value_to_cell(val);
|
||||
cell_to_value(kind, &cell, cell.is_empty(), &name, 2, C).is_ok()
|
||||
if files { cell.trim().is_empty() } else { cell_to_value(kind, &cell, cell.is_empty(), &name, 2, C).is_ok() }
|
||||
});
|
||||
if !cells_read {
|
||||
refused.push(v.name.as_str());
|
||||
@@ -340,7 +344,9 @@ fn datasets_to_csv(vars: &Variables, cmd: &str) -> Result<String> {
|
||||
/// that earlier columns define) names that variable. Otherwise `#` before the name makes it a
|
||||
/// visibility variable, `@` makes it an image variable, and a cell without a prefix names a text
|
||||
/// variable. A prefixed name that is already a variable must be one of the prefix's kind; a new
|
||||
/// name is added to `defined`. A `%` cell that names no variable (graph data files) is refused.
|
||||
/// name is added to `defined`. `%` before a name makes it a graph variable whose column holds the
|
||||
/// paths of graph data files ([`graph_file_value`]); [`dataset_import`] tells such a column apart
|
||||
/// by a returned name that is not the cell.
|
||||
fn header_variable(
|
||||
cell: &str,
|
||||
column: usize,
|
||||
@@ -356,8 +362,8 @@ fn header_variable(
|
||||
(rest.trim(), VariableKind::Visibility)
|
||||
} else if let Some(rest) = cell.strip_prefix('@') {
|
||||
(rest.trim(), VariableKind::Image)
|
||||
} else if cell.starts_with('%') {
|
||||
return Err(bad(cmd, format!("column {column}: `{cell}` is a `%` column of graph data files, which are not read")));
|
||||
} else if let Some(rest) = cell.strip_prefix('%') {
|
||||
(rest.trim(), VariableKind::Graph)
|
||||
} else {
|
||||
(cell, VariableKind::Text)
|
||||
};
|
||||
@@ -375,13 +381,94 @@ fn header_variable(
|
||||
}
|
||||
}
|
||||
|
||||
/// The most bytes the `%` columns of one import read from graph data files and keep as graph
|
||||
/// values, counted together: each file's bytes once (it is read once, however many cells name it),
|
||||
/// and the graph value of every cell, which each data set holds a copy of.
|
||||
const MAX_GRAPH_FILES_TOTAL: usize = 256 * 1_048_576;
|
||||
|
||||
/// The graph data files the `%` columns of one import have read, by path, and the bytes counted
|
||||
/// against [`MAX_GRAPH_FILES_TOTAL`] so far.
|
||||
#[derive(Default)]
|
||||
struct GraphFiles {
|
||||
read: BTreeMap<String, String>,
|
||||
total: usize,
|
||||
}
|
||||
|
||||
/// The graph value of a `%` column's cell `path` on file line `line`, in 1-based `column`, for the
|
||||
/// graph variable `var`: the graph data file at `path` (taken from the folder `base` when
|
||||
/// relative), read as Graph Data's Import Data reads one ([`crate::cmd::graph::graph_csv_from_file`]),
|
||||
/// or no value for an empty cell. The path is followed as an image variable's path is
|
||||
/// ([`crate::cmd::fileio::document_path`]): only files on this computer, or on the network share
|
||||
/// `base` is on, are read. A relative path without `base`, a path on another computer or share, a
|
||||
/// device or a URL, a file that can't be read or is larger than 1 MB, a file that gives a graph
|
||||
/// value longer than [`MAX_GRAPH_CSV`] bytes and more than [`MAX_GRAPH_FILES_TOTAL`] bytes in all
|
||||
/// are refused, with the line and the column.
|
||||
fn graph_file_value(files: &mut GraphFiles, path: &str, base: Option<&str>, var: &str, (line, column): (usize, usize)) -> Result<Option<DataValue>> {
|
||||
const C: &str = "dataset.import";
|
||||
let path = path.trim();
|
||||
if path.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
// Without `base`, a path that stays relative once a `file:` URL is read is refused here, so the
|
||||
// error says what to give.
|
||||
if base.is_none() && craft_docpath::resolve(path, None).is_ok_and(|p| !p.is_absolute()) {
|
||||
return Err(bad(
|
||||
C,
|
||||
format!("line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path"),
|
||||
));
|
||||
}
|
||||
// `document_path` takes a relative path from the folder of a document; any file name in `base`
|
||||
// stands for the CSV there.
|
||||
let document = base.map(|base| std::path::Path::new(base).join("data sets.csv").to_string_lossy().into_owned());
|
||||
let full = crate::cmd::fileio::document_path(path, document.as_deref())
|
||||
.map_err(|r| bad(C, format!("line {line}, column {column}: the graph data file `{path}` for `{var}` isn't followed: {r}")))?;
|
||||
let csv = match files.read.get(&full) {
|
||||
Some(csv) => csv.clone(),
|
||||
None => {
|
||||
// One byte past the limit is enough to refuse the file.
|
||||
let bytes = read_file_head(&full, MAX_GRAPH_DATA_FILE + 1)
|
||||
.map_err(|e| bad(C, format!("line {line}, column {column}: the graph data file for `{var}` can't be read: {e}")))?;
|
||||
if bytes.len() > MAX_GRAPH_DATA_FILE {
|
||||
return Err(bad(
|
||||
C,
|
||||
format!("line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes"),
|
||||
));
|
||||
}
|
||||
let csv = crate::cmd::graph::graph_csv_from_file(&bytes)?;
|
||||
if csv.len() > MAX_GRAPH_CSV {
|
||||
return Err(bad(
|
||||
C,
|
||||
format!(
|
||||
"line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes"
|
||||
),
|
||||
));
|
||||
}
|
||||
files.total += bytes.len();
|
||||
files.read.insert(full, csv.clone());
|
||||
csv
|
||||
}
|
||||
};
|
||||
files.total += csv.len();
|
||||
if files.total > MAX_GRAPH_FILES_TOTAL {
|
||||
return Err(bad(C, format!("line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all")));
|
||||
}
|
||||
Ok(Some(DataValue::Graph(csv)))
|
||||
}
|
||||
|
||||
/// Import datasets from CSV. Every header cell names a variable, as [`header_variable`] reads it,
|
||||
/// and the variables the document doesn't define yet are defined, unbound. Two headers that name
|
||||
/// one variable are refused. The rows replace every dataset of the document and are named "Data
|
||||
/// Set 1", "Data Set 2" and so on, in file order. The document's variables and their bindings
|
||||
/// one variable are refused. The cells of a `%` column are paths of graph data files
|
||||
/// ([`graph_file_value`]); a relative one is taken from the folder `base` gives, else from the
|
||||
/// folder of the file `path` names. The rows replace every dataset of the document and are named
|
||||
/// "Data Set 1", "Data Set 2" and so on, in file order. The document's variables and their bindings
|
||||
/// stay. One undo step, and none when the variables and datasets stay as they were.
|
||||
pub(super) fn dataset_import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "dataset.import";
|
||||
let base = match text_param(p, "base", C)? {
|
||||
Some("") => return Err(bad(C, "`base` is empty")),
|
||||
Some(base) => Some(absolute_path(base)),
|
||||
None => str_param(p, "path").and_then(|path| std::path::Path::new(&absolute_path(path)).parent().map(|d| d.to_string_lossy().into_owned())),
|
||||
};
|
||||
let (bytes, given_as_text) = datasets_csv_bytes(p, C)?;
|
||||
// `data` and `csv` are already text, NUL characters included (`dataset.export` writes them).
|
||||
let text = if given_as_text { String::from_utf8(bytes).map_err(|_| bad(C, "CSV is not UTF-8"))? } else { datasets_csv_text(&bytes, C)? };
|
||||
@@ -390,7 +477,8 @@ pub(super) fn dataset_import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(C, "CSV is empty"));
|
||||
};
|
||||
let kinds: BTreeMap<String, VariableKind> = s.doc()?.doc.variables.variables.iter().map(|v| (v.name.clone(), v.kind)).collect();
|
||||
let mut columns: Vec<(usize, String, VariableKind)> = Vec::new();
|
||||
// Each column: its index, its variable and kind, and whether its cells are graph data files.
|
||||
let mut columns: Vec<(usize, String, VariableKind, bool)> = Vec::new();
|
||||
let mut defined: Vec<Variable> = Vec::new();
|
||||
for (i, h) in header.iter().enumerate() {
|
||||
let cell = h.trim();
|
||||
@@ -398,11 +486,12 @@ pub(super) fn dataset_import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(C, format!("empty header in column {}", i + 1)));
|
||||
}
|
||||
let (name, kind) = header_variable(cell, i + 1, &kinds, &mut defined, C)?;
|
||||
if let Some(&(first, ..)) = columns.iter().find(|(_, n, _)| *n == name) {
|
||||
if let Some(&(first, ..)) = columns.iter().find(|(_, n, ..)| *n == name) {
|
||||
let (first, column) = (first + 1, i + 1);
|
||||
return Err(bad(C, format!("columns {first} and {column} both name the variable `{name}`")));
|
||||
}
|
||||
columns.push((i, name, kind));
|
||||
let files = kind == VariableKind::Graph && name != cell;
|
||||
columns.push((i, name, kind, files));
|
||||
}
|
||||
// Lock Variables refuses New Variable, so the import is refused when a header would define one.
|
||||
if !defined.is_empty() {
|
||||
@@ -412,13 +501,19 @@ pub(super) fn dataset_import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(C, "CSV has a header but no data rows"));
|
||||
}
|
||||
let mut parsed: Vec<DataSet> = Vec::new();
|
||||
let mut files = GraphFiles::default();
|
||||
for (n, &(line, ref row, ref quoted)) in rows.iter().skip(1).enumerate() {
|
||||
let name = format!("Data Set {}", n + 1);
|
||||
let mut values = BTreeMap::new();
|
||||
for &(col, ref var, kind) in &columns {
|
||||
for &(col, ref var, kind, from_files) in &columns {
|
||||
let cell = row.get(col).map(String::as_str).unwrap_or("");
|
||||
let was_quoted = quoted.get(col).copied().unwrap_or(false);
|
||||
if let Some(v) = cell_to_value(kind, cell, was_quoted, var, line, C)? {
|
||||
let value = if from_files {
|
||||
graph_file_value(&mut files, cell, base.as_deref(), var, (line, col + 1))?
|
||||
} else {
|
||||
cell_to_value(kind, cell, was_quoted, var, line, C)?
|
||||
};
|
||||
if let Some(v) = value {
|
||||
values.insert(var.clone(), v);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -619,7 +619,21 @@ pub(crate) fn give_svg_library(doc: &mut Document, lib: Library, found: &HashMap
|
||||
}
|
||||
}
|
||||
doc.variables = vars.into();
|
||||
left_out_warning(other.iter().map(|v| v.trait_name.as_deref().unwrap_or_else(|| v.kind.label())))
|
||||
left_out_warning(other.iter().map(|v| left_out_kind(v.kind, v.trait_name.as_deref())))
|
||||
}
|
||||
|
||||
/// How the warning about variables that aren't text names the kind of one: Visibility, Linked File
|
||||
/// or Graph Data for a `trait` VectorCraft reads, Unknown for a variable without a `trait`, and any
|
||||
/// other `trait` as the file writes it, in backticks, each backtick in it doubled, so that a `trait`
|
||||
/// such as `Unknown` or `a (1), b` reads as one kind the file names.
|
||||
fn left_out_kind(kind: VariableKind, trait_name: Option<&str>) -> String {
|
||||
match (kind, trait_name) {
|
||||
(VariableKind::Visibility, _) => "Visibility".into(),
|
||||
(VariableKind::Image, _) => "Linked File".into(),
|
||||
(VariableKind::Graph, _) => "Graph Data".into(),
|
||||
(_, None) => "Unknown".into(),
|
||||
(_, Some(t)) => format!("`{}`", t.replace('`', "``")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Load Variable Library: replace the document's variables and data sets with a variable library's
|
||||
@@ -668,10 +682,11 @@ pub(super) fn load_library(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({"variables": declared, "deleted": deleted, "deletedDataSets": deleted_sets, "names": names}))
|
||||
}
|
||||
|
||||
/// The warning about variables that aren't text and were left out, given the kind of each: every
|
||||
/// kind once, in the order it first comes, with how many variables have it. `None` without any.
|
||||
fn left_out_warning<'a>(kinds: impl Iterator<Item = &'a str>) -> Option<String> {
|
||||
let mut counted: Vec<(&str, usize)> = Vec::new();
|
||||
/// The warning about variables that aren't text and were left out, given the kind of each
|
||||
/// ([`left_out_kind`]): every kind once, in the order it first comes, with how many variables have
|
||||
/// it. `None` without any.
|
||||
fn left_out_warning(kinds: impl Iterator<Item = String>) -> Option<String> {
|
||||
let mut counted: Vec<(String, usize)> = Vec::new();
|
||||
for t in kinds {
|
||||
match counted.iter_mut().find(|(k, _)| *k == t) {
|
||||
Some((_, n)) => *n += 1,
|
||||
|
||||
@@ -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} (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; a new reduction without colorTable clears it and deleted)} (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
|
||||
),
|
||||
@@ -325,27 +325,39 @@ pub struct ColorTable {
|
||||
pub web_shift: Vec<String>,
|
||||
#[serde(serialize_with = "ser_key", deserialize_with = "de_key")]
|
||||
pub sort: ColorSort,
|
||||
/// Taken out of the table: their pixels take the nearest color left. A deleted color is no
|
||||
/// longer locked, transparent or web-shifted.
|
||||
pub deleted: Vec<String>,
|
||||
/// A fixed palette (a Custom table) used instead of the reduction's own: the colors of the
|
||||
/// table when the first color was deleted. Empty: the reduction makes the palette.
|
||||
pub custom_palette: Vec<String>,
|
||||
}
|
||||
|
||||
/// The most colours a colour table list holds.
|
||||
const MAX_TABLE: usize = 256;
|
||||
|
||||
/// The error for a deletion that would leave the color table no color for the pixels.
|
||||
pub const KEEP_ONE: &str = "colorTable.deleted: at least one color has to stay in the color table";
|
||||
|
||||
impl ColorTable {
|
||||
/// Whether the table is a Custom one: a color was deleted or the palette is fixed.
|
||||
pub fn is_custom(&self) -> bool {
|
||||
!self.deleted.is_empty() || !self.custom_palette.is_empty()
|
||||
}
|
||||
|
||||
fn colors(list: &[String], what: &str) -> std::result::Result<Vec<[u8; 3]>, String> {
|
||||
if list.len() > MAX_TABLE {
|
||||
return Err(format!("colorTable.{what}: at most {MAX_TABLE} colours"));
|
||||
}
|
||||
list.iter()
|
||||
.map(|h| {
|
||||
vectorcraft_color::Color::from_hex(h)
|
||||
.filter(|_| !super::hex_with_alpha(h))
|
||||
.map(|c| {
|
||||
let [r, g, b, _] = c.to_rgba8(1.0);
|
||||
[r, g, b]
|
||||
})
|
||||
.ok_or_else(|| format!("colorTable.{what}: `{h}` is not a colour such as \"#ff8800\""))
|
||||
})
|
||||
.collect()
|
||||
list.iter().map(|h| Self::rgb(h).ok_or_else(|| format!("colorTable.{what}: `{h}` is not a colour such as \"#ff8800\""))).collect()
|
||||
}
|
||||
|
||||
/// `h` as RGB; `None` when it is not a color such as `#ff8800`.
|
||||
fn rgb(h: &str) -> Option<[u8; 3]> {
|
||||
vectorcraft_color::Color::from_hex(h).filter(|_| !super::hex_with_alpha(h)).map(|c| {
|
||||
let [r, g, b, _] = c.to_rgba8(1.0);
|
||||
[r, g, b]
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -445,7 +457,13 @@ impl WebSettings {
|
||||
}
|
||||
}
|
||||
}
|
||||
let s: WebSettings = serde_json::from_value(v).map_err(|e| format!("Save for Web settings: {e}"))?;
|
||||
let mut s: WebSettings = serde_json::from_value(v).map_err(|e| format!("Save for Web settings: {e}"))?;
|
||||
// Another reduction makes a new palette: the deletions and the fixed palette go, unless
|
||||
// the params give the color table too.
|
||||
if p.get("reduction").is_some() && p.get("colorTable").is_none() && s.reduction != self.reduction {
|
||||
s.color_table.deleted.clear();
|
||||
s.color_table.custom_palette.clear();
|
||||
}
|
||||
s.checked()
|
||||
}
|
||||
|
||||
@@ -463,11 +481,19 @@ impl WebSettings {
|
||||
return Err("width and height are at least 1 pixel".into());
|
||||
}
|
||||
self.matte_rgb()?;
|
||||
let table = &mut self.color_table;
|
||||
for (list, what) in
|
||||
[(&self.color_table.locked, "locked"), (&self.color_table.transparent, "transparent"), (&self.color_table.web_shift, "webShift")]
|
||||
[(&table.locked, "locked"), (&table.transparent, "transparent"), (&table.web_shift, "webShift"), (&table.custom_palette, "customPalette")]
|
||||
{
|
||||
ColorTable::colors(list, what)?;
|
||||
}
|
||||
// A deleted color is no longer locked, transparent or web-shifted.
|
||||
let deleted = ColorTable::colors(&table.deleted, "deleted")?;
|
||||
if !deleted.is_empty() {
|
||||
for list in [&mut table.locked, &mut table.transparent, &mut table.web_shift] {
|
||||
list.retain(|h| ColorTable::rgb(h).is_none_or(|c| !deleted.contains(&c)));
|
||||
}
|
||||
}
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
@@ -741,7 +767,7 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8
|
||||
transparency: s.transparency,
|
||||
matte,
|
||||
};
|
||||
let mut ix = quantize::quantize_locked(rgba, w, h, &o, &locked);
|
||||
let mut ix = reduced(rgba, w, h, s, &o, &locked)?;
|
||||
// Map to transparent works on the colours the reduction made.
|
||||
let before = ix.palette.clone();
|
||||
let clear = ix.transparent.map(usize::from);
|
||||
@@ -789,6 +815,45 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8
|
||||
Ok(PaletteImage { ix, colors, mapped })
|
||||
}
|
||||
|
||||
/// The pixels reduced to the palette `s` gives: the reduction's own (`locked` kept), or the
|
||||
/// 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.
|
||||
fn reduced(rgba: &[u8], w: u32, h: u32, s: &WebSettings, o: &PaletteOptions, locked: &[[u8; 3]]) -> std::result::Result<Indexed, String> {
|
||||
let table = &s.color_table;
|
||||
let deleted = ColorTable::colors(&table.deleted, "deleted")?;
|
||||
let custom = ColorTable::colors(&table.custom_palette, "customPalette")?;
|
||||
let to_clear = ColorTable::colors(&table.transparent, "transparent")?;
|
||||
let opaque_left = |left: &[[u8; 3]]| left.iter().any(|c| !to_clear.contains(c));
|
||||
if custom.is_empty() {
|
||||
let ix = quantize::quantize_locked(rgba, w, h, o, locked);
|
||||
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);
|
||||
}
|
||||
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));
|
||||
}
|
||||
// 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);
|
||||
let removed = custom.iter().any(|c| deleted.contains(c));
|
||||
let mut left: Vec<[u8; 3]> = vec![];
|
||||
for c in custom {
|
||||
if !deleted.contains(&c) && !left.contains(&c) {
|
||||
left.push(c);
|
||||
}
|
||||
}
|
||||
left.truncate(usize::from(s.colors.clamp(2, 256)) - usize::from(has_clear));
|
||||
if left.is_empty() || (removed && !opaque_left(&left)) {
|
||||
return Err(KEEP_ONE.into());
|
||||
}
|
||||
Ok(quantize::quantize_to(rgba, w, h, o, &left))
|
||||
}
|
||||
|
||||
/// An optimised image as straight RGBA → `(pixels, width, height)` (the dialog's preview).
|
||||
pub fn decode(o: &Optimized) -> std::result::Result<(Vec<u8>, u32, u32), String> {
|
||||
let img = craft_image_codecs::decode(o.display()).map_err(|e| format!("the optimised image can't be read back: {e}"))?;
|
||||
|
||||
@@ -25,6 +25,10 @@ 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>,
|
||||
/// 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.
|
||||
@@ -136,6 +140,10 @@ pub struct DocState {
|
||||
/// same document comes to the front, its type set in them is not measured again. While this
|
||||
/// reference lasts, its allocation holds no other document. Not saved.
|
||||
pub(crate) measured_in_own: Option<(std::sync::Weak<Document>, std::collections::HashSet<String>)>,
|
||||
/// The document as the last edit's refresh of inline graphics left it, and what that refresh
|
||||
/// 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>,
|
||||
}
|
||||
|
||||
/// Whether a document has an artboard for Delete Empty Artboards to delete, with the document that
|
||||
@@ -318,6 +326,7 @@ impl DocState {
|
||||
revision: 1,
|
||||
active_layer,
|
||||
layer_rows: vec![],
|
||||
locate_reveal: None,
|
||||
variables_highlight: None,
|
||||
variables_sort: Default::default(),
|
||||
isolation: None,
|
||||
@@ -355,6 +364,7 @@ impl DocState {
|
||||
plugin_effects: Default::default(),
|
||||
art_to_fit: Default::default(),
|
||||
measured_in_own: None,
|
||||
inline_resolved: None,
|
||||
}
|
||||
}
|
||||
/// `measure`'s answer for the document now. `measure` runs once for each version of the document,
|
||||
|
||||
@@ -25,7 +25,9 @@
|
||||
//! guard against other programs on the computer.
|
||||
//!
|
||||
//! [`ScriptScope`] holds the folders a running script's own files (its includes and `$.evalFile`)
|
||||
//! are read from, inside the roots.
|
||||
//! 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.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::ffi::OsString;
|
||||
@@ -174,7 +176,7 @@ fn with_scope<T>(scope: Option<Scope>, f: impl FnOnce() -> T) -> T {
|
||||
/// Run `f` with `roots` in force on this thread (`None`: as things stand).
|
||||
pub fn confine<T>(roots: Option<&Arc<AutomationRoots>>, f: impl FnOnce() -> T) -> T {
|
||||
match roots {
|
||||
Some(r) => with_scope(Some(Scope::Confined(r.clone())), f),
|
||||
Some(r) => with_gate_reads_exempt(false, || with_scope(Some(Scope::Confined(r.clone())), f)),
|
||||
None => f(),
|
||||
}
|
||||
}
|
||||
@@ -182,25 +184,111 @@ pub fn confine<T>(roots: Option<&Arc<AutomationRoots>>, f: impl FnOnce() -> T) -
|
||||
/// Run `f` with no roots in force on this thread: what the person at the keyboard does, and the
|
||||
/// app's own folders.
|
||||
pub fn unconfined<T>(f: impl FnOnce() -> T) -> T {
|
||||
with_scope(Some(Scope::Unconfined), f)
|
||||
with_gate_reads_exempt(true, || with_scope(Some(Scope::Unconfined), f))
|
||||
}
|
||||
|
||||
/// This thread's scope, to carry to work it hands to another thread ([`ScopeHandle::run`]).
|
||||
thread_local! {
|
||||
/// Are reads on this thread exempt from the gate of the script command it runs? Only inside an
|
||||
/// [`unconfined`] entered after the gate was put in force ([`with_script_gate`]).
|
||||
static GATE_READS_EXEMPT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
}
|
||||
|
||||
/// Puts the exemption it replaced back when dropped (also when `f` panics).
|
||||
struct RestoreExempt(bool);
|
||||
|
||||
impl Drop for RestoreExempt {
|
||||
fn drop(&mut self) {
|
||||
GATE_READS_EXEMPT.with(|e| e.set(self.0));
|
||||
}
|
||||
}
|
||||
|
||||
fn with_gate_reads_exempt<T>(exempt: bool, f: impl FnOnce() -> T) -> T {
|
||||
let _restore = RestoreExempt(GATE_READS_EXEMPT.with(|e| e.replace(exempt)));
|
||||
f()
|
||||
}
|
||||
|
||||
/// This thread's scope, with the gate of the script command it runs, to carry to work it hands to
|
||||
/// another thread ([`ScopeHandle::run`]).
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ScopeHandle(Option<Scope>);
|
||||
pub struct ScopeHandle(Option<Scope>, Option<Arc<ScriptGate>>, bool);
|
||||
|
||||
impl ScopeHandle {
|
||||
/// The scope of the calling thread.
|
||||
pub fn capture() -> Self {
|
||||
Self(SCOPE.with(|s| s.borrow().clone()))
|
||||
Self(SCOPE.with(|s| s.borrow().clone()), GATE.with(|g| g.borrow().clone()), GATE_READS_EXEMPT.with(std::cell::Cell::get))
|
||||
}
|
||||
|
||||
/// Run `f` in the captured scope.
|
||||
pub fn run<T>(self, f: impl FnOnce() -> T) -> T {
|
||||
with_scope(self.0, f)
|
||||
let Self(scope, gate, exempt) = self;
|
||||
with_gate(gate, || with_gate_reads_exempt(exempt, || with_scope(scope, f)))
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.
|
||||
#[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.
|
||||
pub(crate) documents: Vec<String>,
|
||||
}
|
||||
|
||||
impl ScriptGate {
|
||||
fn check(&self, path: &str, access: Access) -> Result<(), String> {
|
||||
let real = if ScriptScope::refused_by_name(Path::new(path)) { None } else { resolve(path).ok() };
|
||||
let allowed = real.is_some_and(|real| {
|
||||
let scoped = match access {
|
||||
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))
|
||||
});
|
||||
if allowed { Ok(()) } else { Err(format!("Script file access denied: {path}")) }
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// The gate of the script command this thread runs ([`with_script_gate`]).
|
||||
static GATE: RefCell<Option<Arc<ScriptGate>>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// Puts the gate it replaced back when dropped (also when `f` panics).
|
||||
struct RestoreGate(Option<Arc<ScriptGate>>);
|
||||
|
||||
impl Drop for RestoreGate {
|
||||
fn drop(&mut self) {
|
||||
let previous = self.0.take();
|
||||
GATE.with(|g| *g.borrow_mut() = previous);
|
||||
}
|
||||
}
|
||||
|
||||
fn with_gate<T>(gate: Option<Arc<ScriptGate>>, f: impl FnOnce() -> T) -> T {
|
||||
let _restore = RestoreGate(GATE.with(|g| g.replace(gate)));
|
||||
f()
|
||||
}
|
||||
|
||||
/// Runs `f`, a command a script runs, with `gate` in force on this thread: every path it reads or
|
||||
/// writes must pass the gate as well as the automation roots, also when the run itself is
|
||||
/// [`unconfined`] (one the person started). Reads of the app's own folders, inside an
|
||||
/// [`unconfined`] the command enters, are not checked; writes there are, so a script's command
|
||||
/// does not save into the app's libraries.
|
||||
pub(crate) fn with_script_gate<T>(gate: ScriptGate, f: impl FnOnce() -> T) -> T {
|
||||
with_gate(Some(Arc::new(gate)), || with_gate_reads_exempt(false, f))
|
||||
}
|
||||
|
||||
/// May `path` be read (or written) by the script command this thread runs? Always outside one,
|
||||
/// and for a read inside an [`unconfined`] the command entered.
|
||||
fn check_gate(path: &str, access: Access) -> Result<(), String> {
|
||||
if matches!(access, Access::Read) && GATE_READS_EXEMPT.with(std::cell::Cell::get) {
|
||||
return Ok(());
|
||||
}
|
||||
GATE.with(|g| g.borrow().clone()).map_or(Ok(()), |g| g.check(path, access))
|
||||
}
|
||||
|
||||
/// The roots in force on this thread, if any.
|
||||
pub fn current() -> Option<Arc<AutomationRoots>> {
|
||||
match SCOPE.with(|s| s.borrow().clone()) {
|
||||
@@ -210,9 +298,11 @@ pub fn current() -> Option<Arc<AutomationRoots>> {
|
||||
}
|
||||
}
|
||||
|
||||
/// May `path` be read here? Always, without roots in force.
|
||||
/// May `path` be read here? Always, without roots in force and outside a script's command
|
||||
/// ([`with_script_gate`]).
|
||||
pub fn check_read(path: &str) -> Result<(), String> {
|
||||
current().map_or(Ok(()), |r| r.check(path, Access::Read))
|
||||
current().map_or(Ok(()), |r| r.check(path, Access::Read))?;
|
||||
check_gate(path, Access::Read)
|
||||
}
|
||||
|
||||
/// Is `path`, under a read root, written as an absolute path of another platform: outside Windows, one
|
||||
@@ -229,9 +319,11 @@ pub fn is_path_key(key: &str) -> bool {
|
||||
crate::cmd::key_location(key).is_some()
|
||||
}
|
||||
|
||||
/// May `path` be written here? Always, without roots in force.
|
||||
/// May `path` be written here? Always, without roots in force and outside a script's command
|
||||
/// ([`with_script_gate`]).
|
||||
pub fn check_write(path: &str) -> Result<(), String> {
|
||||
current().map_or(Ok(()), |r| r.check(path, Access::Write))?;
|
||||
check_gate(path, Access::Write)?;
|
||||
WRITES.with(|w| {
|
||||
if let Some(paths) = w.borrow_mut().as_mut()
|
||||
&& !paths.iter().any(|(p, _)| p == path)
|
||||
@@ -323,6 +415,12 @@ fn inside(path: &Path, root: &Path) -> bool {
|
||||
root.components().all(|r| path.next().is_some_and(|p| same_component(p, r)))
|
||||
}
|
||||
|
||||
/// Is `path` `root` or inside it, both with their links followed, compared as [`AutomationRoots`]
|
||||
/// compares them?
|
||||
pub(crate) fn path_inside(path: &Path, root: &Path) -> bool {
|
||||
inside(path, root)
|
||||
}
|
||||
|
||||
fn same_component(a: Component, b: Component) -> bool {
|
||||
if a == b {
|
||||
return true;
|
||||
@@ -374,10 +472,21 @@ fn windows_name_refusal(path: &str) -> Option<&'static str> {
|
||||
/// The file opened is the path with its links followed, and after reading, the path is followed
|
||||
/// again and must still lead to the same place: a process that changes the folders twice in between
|
||||
/// can still win that race.
|
||||
///
|
||||
/// A scope can also be given more folders ([`ScriptScope::add`]) and single files
|
||||
/// ([`ScriptScope::add_file`]), and folders it keeps out even inside a granted folder
|
||||
/// ([`ScriptScope::fence`]), each but the places inside it that stay open. A granted file grants its
|
||||
/// own path only, also when a folder later takes its place.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(crate) struct ScriptScope {
|
||||
/// The granted folders, made absolute with their links followed.
|
||||
roots: Vec<PathBuf>,
|
||||
/// The granted files, made absolute with their links followed.
|
||||
files: Vec<PathBuf>,
|
||||
/// The folders kept out, with their links followed.
|
||||
fenced: Vec<PathBuf>,
|
||||
/// The places inside a fenced folder that are not kept out.
|
||||
open: Vec<PathBuf>,
|
||||
}
|
||||
|
||||
/// Why a script's file was not read.
|
||||
@@ -396,18 +505,68 @@ pub(crate) enum ScriptRead {
|
||||
impl ScriptScope {
|
||||
/// The scope of a script run from a file in folder `dir`: that folder.
|
||||
pub(crate) fn of_folder(dir: &Path) -> Self {
|
||||
Self { roots: std::fs::canonicalize(dir).ok().into_iter().collect() }
|
||||
Self { roots: std::fs::canonicalize(dir).ok().into_iter().collect(), ..Self::default() }
|
||||
}
|
||||
|
||||
/// Grants the folder `real`, a path with its links followed, with everything inside it.
|
||||
pub(crate) fn add(&mut self, real: PathBuf) {
|
||||
if !self.roots.contains(&real) {
|
||||
self.roots.push(real);
|
||||
}
|
||||
}
|
||||
|
||||
/// Grants the file `real`, a path with its links followed: that path and nothing below it.
|
||||
pub(crate) fn add_file(&mut self, real: PathBuf) {
|
||||
if !self.files.contains(&real) {
|
||||
self.files.push(real);
|
||||
}
|
||||
}
|
||||
|
||||
/// Takes back the grant of the folder (`folder`) or file `real` that [`ScriptScope::add`] or
|
||||
/// [`ScriptScope::add_file`] gave.
|
||||
pub(crate) fn remove(&mut self, real: &Path, folder: bool) {
|
||||
if folder { self.roots.retain(|r| r != real) } else { self.files.retain(|r| r != real) }
|
||||
}
|
||||
|
||||
/// Is nothing granted?
|
||||
fn is_empty(&self) -> bool {
|
||||
self.roots.is_empty() && self.files.is_empty()
|
||||
}
|
||||
|
||||
/// Keeps the folder `real` (links followed) and everything in it out, but for `open` and the
|
||||
/// places inside it.
|
||||
pub(crate) fn fence(&mut self, real: PathBuf, open: &[PathBuf]) {
|
||||
self.fenced.push(real);
|
||||
self.open.extend(open.iter().cloned());
|
||||
}
|
||||
|
||||
/// Leaves the place `real` (links followed) and everything in it open inside a fenced folder.
|
||||
pub(crate) fn fence_open(&mut self, real: PathBuf) {
|
||||
self.open.push(real);
|
||||
}
|
||||
|
||||
/// The granted folders, with their links followed.
|
||||
pub(crate) fn roots(&self) -> &[PathBuf] {
|
||||
&self.roots
|
||||
}
|
||||
|
||||
/// Is the real path `real` a granted file or inside a granted folder, and not kept out? A place
|
||||
/// left open counts only inside the fenced folder: one that holds the fenced folder opens none of it.
|
||||
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)))
|
||||
}
|
||||
|
||||
/// The scope of a script run from a file in the folder whose real path, with its links already
|
||||
/// followed, is `real`: that folder, which is not looked up again.
|
||||
pub(crate) fn of_real_folder(real: PathBuf) -> Self {
|
||||
Self { roots: vec![real] }
|
||||
Self { roots: vec![real], ..Self::default() }
|
||||
}
|
||||
|
||||
/// Is `path` refused by its name alone: a `..` component, a NUL, a Windows device name or
|
||||
/// stream, or a computer on the network?
|
||||
fn refused_by_name(path: &Path) -> bool {
|
||||
pub(crate) fn refused_by_name(path: &Path) -> bool {
|
||||
let text = path.to_string_lossy();
|
||||
text.contains('\0')
|
||||
|| path.components().any(|c| c == Component::ParentDir)
|
||||
@@ -417,7 +576,7 @@ impl ScriptScope {
|
||||
/// The real path of the file at `path` and its first `max` bytes, at most.
|
||||
pub(crate) fn read(&self, path: &Path, max: usize) -> Result<(PathBuf, Vec<u8>), ScriptRead> {
|
||||
use std::io::Read;
|
||||
if self.roots.is_empty() || Self::refused_by_name(path) || check_read(&path.to_string_lossy()).is_err() {
|
||||
if self.is_empty() || Self::refused_by_name(path) || check_read(&path.to_string_lossy()).is_err() {
|
||||
return Err(ScriptRead::Refused);
|
||||
}
|
||||
let real = match std::fs::canonicalize(path) {
|
||||
@@ -428,7 +587,7 @@ impl ScriptScope {
|
||||
}
|
||||
Err(e) => return Err(ScriptRead::Failed(e.to_string())),
|
||||
};
|
||||
if !self.roots.iter().any(|r| inside(&real, r)) {
|
||||
if !self.allows(&real) {
|
||||
return Err(ScriptRead::Refused);
|
||||
}
|
||||
let file = std::fs::File::open(&real).map_err(|e| ScriptRead::Failed(e.to_string()))?;
|
||||
@@ -456,24 +615,24 @@ impl ScriptScope {
|
||||
self.roots.first().map(|r| crate::cmd::findfiles::plain(r.clone()))
|
||||
}
|
||||
|
||||
/// Does the absolute path `path` name a granted folder or a place inside one, by its names
|
||||
/// alone, without regard to case? A path that does not is refused before the file system is
|
||||
/// asked anything about it.
|
||||
/// Does the absolute path `path` name a granted file, a granted folder or a place inside one,
|
||||
/// by its names alone, without regard to case? A path that does not is refused before the file
|
||||
/// system is asked anything about it.
|
||||
fn names_inside(&self, path: &Path) -> bool {
|
||||
let lower = |c: Component| c.as_os_str().to_string_lossy().to_lowercase();
|
||||
path.is_absolute()
|
||||
&& self.roots.iter().any(|r| {
|
||||
let root = crate::cmd::findfiles::plain(r.clone());
|
||||
let mut names = path.components();
|
||||
root.components().all(|c| names.next().is_some_and(|n| lower(n) == lower(c)))
|
||||
})
|
||||
let names_under = |r: &PathBuf| {
|
||||
let root = crate::cmd::findfiles::plain(r.clone());
|
||||
let mut names = path.components();
|
||||
root.components().all(|c| names.next().is_some_and(|n| lower(n) == lower(c)))
|
||||
};
|
||||
path.is_absolute() && (self.roots.iter().any(names_under) || self.files.iter().any(names_under))
|
||||
}
|
||||
|
||||
/// The real path of the file or folder at `path`, which must be absolute: refused as
|
||||
/// [`ScriptScope::read`] refuses a path, and also when its names alone place it outside every
|
||||
/// granted folder, in which case the file system is not asked about it.
|
||||
pub(crate) fn locate(&self, path: &Path) -> Result<PathBuf, ScriptRead> {
|
||||
if self.roots.is_empty() || Self::refused_by_name(path) || !self.names_inside(path) {
|
||||
if self.is_empty() || Self::refused_by_name(path) || !self.names_inside(path) {
|
||||
return Err(ScriptRead::Refused);
|
||||
}
|
||||
probed();
|
||||
@@ -490,22 +649,72 @@ impl ScriptScope {
|
||||
}
|
||||
Err(e) => return Err(ScriptRead::Failed(e.to_string())),
|
||||
};
|
||||
if !self.roots.iter().any(|r| inside(&real, r)) {
|
||||
if !self.allows(&real) {
|
||||
return Err(ScriptRead::Refused);
|
||||
}
|
||||
Ok(real)
|
||||
}
|
||||
|
||||
/// Is the missing `path` inside a granted folder: does the nearest folder above it that exists
|
||||
/// lie inside one? On a file system where case matters, `MAIN/x` beside the granted `main` is
|
||||
/// outside, whether `MAIN` exists or not. A link above it that leads to nothing is outside too,
|
||||
/// so a script cannot tell whether the folder a link leads to exists.
|
||||
/// The real path that writing to `path` writes: `path` with its links followed (the last
|
||||
/// name's too only when `follow`), and for a path that does not exist yet, its nearest existing
|
||||
/// folder's links followed and the rest appended. Refused as [`ScriptScope::locate`] refuses a
|
||||
/// path, also when a link on the way leads nowhere, and when the automation write roots in force
|
||||
/// ([`check_write`]) do not take it.
|
||||
pub(crate) fn target(&self, path: &Path, follow: bool) -> Result<PathBuf, ScriptRead> {
|
||||
if self.is_empty() || Self::refused_by_name(path) || !self.names_inside(path) {
|
||||
return Err(ScriptRead::Refused);
|
||||
}
|
||||
probed();
|
||||
if check_write(&path.to_string_lossy()).is_err() {
|
||||
return Err(ScriptRead::Refused);
|
||||
}
|
||||
let (Some(parent), Some(name)) = (path.parent(), path.file_name()) else { return Err(ScriptRead::Refused) };
|
||||
let real = match std::fs::symlink_metadata(path) {
|
||||
Ok(_) if follow => std::fs::canonicalize(path).map_err(|_| ScriptRead::Refused)?,
|
||||
Ok(m) => {
|
||||
// Where case does not matter, the name given can differ in case from the name the
|
||||
// file system keeps, so a file or folder that is not a link is checked under the
|
||||
// kept name too.
|
||||
if !m.file_type().is_symlink() && !std::fs::canonicalize(path).is_ok_and(|kept| self.allows(&kept)) {
|
||||
return Err(ScriptRead::Refused);
|
||||
}
|
||||
std::fs::canonicalize(parent).map_err(|_| ScriptRead::Refused)?.join(name)
|
||||
}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
|
||||
let mut missing = vec![name.to_os_string()];
|
||||
let mut at = parent;
|
||||
loop {
|
||||
match std::fs::symlink_metadata(at) {
|
||||
Ok(_) => break,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
|
||||
missing.push(at.file_name().ok_or(ScriptRead::Refused)?.to_os_string());
|
||||
at = at.parent().ok_or(ScriptRead::Refused)?;
|
||||
}
|
||||
Err(e) => return Err(ScriptRead::Failed(e.to_string())),
|
||||
}
|
||||
}
|
||||
let mut real = std::fs::canonicalize(at).map_err(|_| ScriptRead::Refused)?;
|
||||
real.extend(missing.iter().rev());
|
||||
real
|
||||
}
|
||||
Err(e) => return Err(ScriptRead::Failed(e.to_string())),
|
||||
};
|
||||
// The automation write roots take the place written as well as the path named.
|
||||
if !self.allows(&real) || check_write(&crate::cmd::findfiles::plain(real.clone()).to_string_lossy()).is_err() {
|
||||
return Err(ScriptRead::Refused);
|
||||
}
|
||||
Ok(real)
|
||||
}
|
||||
|
||||
/// Is the missing `path` inside a granted place: with the links of the nearest folder above it
|
||||
/// that exists followed, and the rest of its names appended, is it granted? On a file system
|
||||
/// where case matters, `MAIN/x` beside the granted `main` is outside, whether `MAIN` exists or
|
||||
/// not. A link above it that leads to nothing is outside too, so a script cannot tell whether
|
||||
/// the folder a link leads to exists.
|
||||
fn missing_inside(&self, path: &Path) -> bool {
|
||||
path.ancestors()
|
||||
.skip(1)
|
||||
.find(|a| std::fs::symlink_metadata(a).is_ok())
|
||||
.and_then(|a| std::fs::canonicalize(a).ok())
|
||||
.is_some_and(|real| self.roots.iter().any(|r| inside(&real, r)))
|
||||
let Some(found) = path.ancestors().skip(1).find(|a| std::fs::symlink_metadata(a).is_ok()) else { return false };
|
||||
let (Ok(real), Ok(rest)) = (std::fs::canonicalize(found), path.strip_prefix(found)) else { return false };
|
||||
self.allows(&real.join(rest))
|
||||
}
|
||||
|
||||
/// What the file or folder at `path` is, located as [`ScriptScope::locate`] locates it.
|
||||
@@ -548,7 +757,7 @@ impl ScriptScope {
|
||||
continue;
|
||||
}
|
||||
let Ok(target) = std::fs::canonicalize(entry.path()) else { continue };
|
||||
if !self.roots.iter().any(|r| inside(&target, r)) || check_read(&entry.path().to_string_lossy()).is_err() {
|
||||
if !self.allows(&target) || check_read(&entry.path().to_string_lossy()).is_err() {
|
||||
continue;
|
||||
}
|
||||
if out.len() >= max {
|
||||
|
||||
@@ -32,6 +32,9 @@ pub struct HistoryEntry {
|
||||
pub(crate) color_mode_paints: Option<(vectorcraft_tools::PaintDefaults, vectorcraft_tools::PaintDefaults)>,
|
||||
/// Owned new-art snapshots included in both directional estimates.
|
||||
color_mode_bytes: usize,
|
||||
/// The state that changes without an undo step as the next state had it: undo and redo compare
|
||||
/// it with `doc` to tell what the step changed.
|
||||
pub(crate) unrecorded: Arc<crate::cmd::Unrecorded>,
|
||||
}
|
||||
|
||||
impl Clone for HistoryEntry {
|
||||
@@ -49,6 +52,7 @@ impl Clone for HistoryEntry {
|
||||
serial: self.serial,
|
||||
color_mode_paints: self.color_mode_paints.clone(),
|
||||
color_mode_bytes: self.color_mode_bytes,
|
||||
unrecorded: self.unrecorded.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -94,6 +98,7 @@ impl HistoryEntry {
|
||||
serial: next_serial(),
|
||||
color_mode_paints: None,
|
||||
color_mode_bytes: 0,
|
||||
unrecorded: Arc::new(crate::cmd::Unrecorded::of(next)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -126,6 +131,7 @@ impl HistoryEntry {
|
||||
serial: next_serial(),
|
||||
color_mode_paints: None,
|
||||
color_mode_bytes: 0,
|
||||
unrecorded: Arc::new(crate::cmd::Unrecorded::of(now)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -337,6 +343,7 @@ impl History {
|
||||
e.next_bytes = after.saturating_add(e.color_mode_bytes);
|
||||
e.next = std::ptr::from_ref(now) as usize;
|
||||
e.serial = next_serial();
|
||||
e.unrecorded = Arc::new(crate::cmd::Unrecorded::of(now));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@ use vectorcraft_tools::{PaintDefaults, Tool};
|
||||
|
||||
pub use cmd::clipboard::{Clipboard, SourceLayer};
|
||||
pub use cmd::create::constrain_click;
|
||||
pub use cmd::distortcmds::perspective_click;
|
||||
pub use cmd::distortcmds::{perspective_click, width_point_pair};
|
||||
pub use cmd::graph::{GraphTypeSubject, calculated_axes as graph_calculated_axes, graph_type_subject};
|
||||
pub use cmd::params::{check_keys, check_params};
|
||||
pub use cmd::pathops::auto_simplify_level;
|
||||
@@ -185,6 +185,10 @@ pub struct Session {
|
||||
/// The folder of the New Document profiles `file.new` starts documents from; `None`: none,
|
||||
/// every document starts with the defaults ([`Session::attach_new_doc_profiles`]).
|
||||
new_doc_profile_dir: Option<std::path::PathBuf>,
|
||||
/// The folder of each script's data folder (`Folder.userData`), beside which the grants file
|
||||
/// keeps the file access people allowed scripts; `None`: no folder
|
||||
/// ([`Session::attach_script_data`]).
|
||||
script_data_dir: Option<std::path::PathBuf>,
|
||||
/// A filter's output that a run made in the background handed in for `plugin.run` to apply
|
||||
/// ([`cmd::plugin::FilterRun::hand_in`]); the next `plugin.run` takes it.
|
||||
plugin_output: Option<cmd::plugin::HandedIn>,
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user