mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-01 10:51:11 +01:00
Merge main into fix/smooth-bridge-says-why
This commit is contained in:
commit
dcf99ad998
71 files changed
+2281
-164
No files matched your search
@@ -111,6 +111,7 @@ mod textedit;
|
||||
|
||||
pub use textedit::effective_kerning;
|
||||
mod retype;
|
||||
mod stepandrepeat;
|
||||
pub mod textstyles;
|
||||
pub(crate) mod textwrap;
|
||||
pub(crate) mod threads;
|
||||
@@ -327,6 +328,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(layerpanel::specs());
|
||||
v.extend(draw2::specs());
|
||||
v.extend(xform::specs());
|
||||
v.extend(stepandrepeat::specs());
|
||||
v.extend(effectcmd::specs());
|
||||
v.extend(bevels::specs());
|
||||
v.extend(wireframe::specs());
|
||||
@@ -874,6 +876,9 @@ pub(crate) use vectorcraft_doc::range::parse_range;
|
||||
/// What the fill and stroke proxies read from the selected objects, kept with the selection
|
||||
/// ([`crate::doc_state::SelectionRecord`]).
|
||||
pub(crate) use paint::SelectionPaints;
|
||||
/// The faces and edges of Live Paint groups among objects that count with their group
|
||||
/// ([`crate::DocState::live_paint_covered_kept`] keeps an empty answer).
|
||||
pub(crate) use paint::live_paint_covered;
|
||||
#[cfg(test)]
|
||||
pub(crate) use paint::{PAINTS_READ, WEIGHTS_READ};
|
||||
|
||||
|
||||
@@ -98,7 +98,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Apply Brush",
|
||||
[],
|
||||
None,
|
||||
"{name, ids?|id?} apply a brush to the strokes of the selected paths (adds a stroke if missing) and make it current → {ids}",
|
||||
"{name, ids?|id?} apply a brush to the strokes of the selected paths (adds a stroke if missing) and make it current; the brush settings of each path's top stroke (brush.objectOptions) are cleared, and clearing them is one undo step; when the brush is already current and applying it leaves every path as it was (its top stroke already has the brush, paint, a width above 0 and no settings of its own), nothing changes and no undo step is recorded → {ids}",
|
||||
has_doc,
|
||||
brush_apply
|
||||
),
|
||||
@@ -170,7 +170,7 @@ 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|stylusWheel 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°; stylusWheel from value − variation at one end of an airbrush pen's finger wheel to value + variation at the other; 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|stylusWheel 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°; stylusWheel: a at one end of an airbrush pen's finger wheel to b at the other), 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), saturation_jitter 0..100% (each copy moves the saturation of its solid colors, after the colorization and the hue jitter, by its own amount up to this many points either way, keeping their hue and brightness, the same on every redraw; colors without a hue stay; 0: off), brightness_jitter 0..100% (each copy moves the brightness of its solid colors, after the colorization and the hue and saturation jitter, by its own amount up to this many points either way, keeping their hue and saturation, the same on every redraw; white, black and grays move too; 0: off). art: width 1..1000%, width_mode: null (fixed)|pressure|tilt|bearing|rotation|stylusWheel, 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°; stylusWheel: width at one end of the finger wheel to width_max at the other; 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%, scale_mode: null (fixed)|pressure|tilt|bearing|rotation|stylusWheel, scale_max 1..10000% (the tiles go from scale to scale_max over the same pen ranges as an art brush's width; half way on a stroke drawn without that input; each tile's height follows the stroke, its length and the gap after it take the scale at its middle, and a corner tile takes the scale at its corner), 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|stylusWheel 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°; stylusWheel from value − variation at one end of an airbrush pen's finger wheel to value + variation at the other; 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|stylusWheel 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°; stylusWheel: a at one end of an airbrush pen's finger wheel to b at the other), 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), saturation_jitter 0..100% (each copy moves the saturation of its solid colors, after the colorization and the hue jitter, by its own amount up to this many points either way, keeping their hue and brightness, the same on every redraw; colors without a hue stay; 0: off), brightness_jitter 0..100% (each copy moves the brightness of its solid colors, after the colorization and the hue and saturation jitter, by its own amount up to this many points either way, keeping their hue and saturation, the same on every redraw; white, black and grays move too; 0: off). art: width 1..1000%, width_mode: null (fixed)|pressure|tilt|bearing|rotation|stylusWheel, 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°; stylusWheel: width at one end of the finger wheel to width_max at the other; 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%, scale_mode: null (fixed)|pressure|tilt|bearing|rotation|stylusWheel, scale_max 1..10000% (the tiles go from scale to scale_max over the same pen ranges as an art brush's width; half way on a stroke drawn without that input; each tile's height follows the stroke, its length and the gap after it take the scale at its middle, and a corner tile takes the scale at its corner), 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); params and a newName that leave the brush as it is change nothing and record no undo step → {name}",
|
||||
has_doc,
|
||||
brush_options
|
||||
),
|
||||
|
||||
@@ -80,10 +80,11 @@ pub(super) fn brush_apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let ids = brush_targets(&s.doc()?.doc, &roots(s, p)?);
|
||||
let stroke = stroke_paint(s);
|
||||
s.edit("Apply Brush", |d, _| {
|
||||
crate::cmd::colorcmds::edit_if_changed(s, "Apply Brush", |before, d| {
|
||||
d.unknown.insert(brush::CURRENT_KEY.into(), json!(name));
|
||||
apply_brush(d, &ids, &name, &stroke);
|
||||
Ok(())
|
||||
let changed = brush::current(before).as_deref() != Some(name.as_str()) || ids.iter().any(|id| before.node(*id) != d.node(*id));
|
||||
Ok(((), changed))
|
||||
})?;
|
||||
Ok(json!({ "ids": ids_json(&ids) }))
|
||||
}
|
||||
@@ -213,6 +214,7 @@ fn rename_brush_strokes(d: &mut Document, lib: &mut [Brush], from: &str, to: Opt
|
||||
}
|
||||
}
|
||||
|
||||
/// Stores `lib` and applies `renames` as one undo step named `label`.
|
||||
fn save_library(s: &mut Session, label: &str, mut lib: Vec<Brush>, renames: &[(String, Option<String>)]) -> Result<()> {
|
||||
s.edit(label, |d, _| {
|
||||
for (from, to) in renames {
|
||||
@@ -503,8 +505,13 @@ pub(super) fn brush_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
v["name"] = json!(name);
|
||||
}
|
||||
v["type"] = json!(lib[i].kind.type_id());
|
||||
lib[i] = parse_brush(C, v)?;
|
||||
let out = lib[i].name.clone();
|
||||
let edited = parse_brush(C, v)?;
|
||||
let out = edited.name.clone();
|
||||
// Options that leave the brush as it is change nothing and add no undo step.
|
||||
if new_name.is_none() && edited == lib[i] {
|
||||
return Ok(json!({ "name": out }));
|
||||
}
|
||||
lib[i] = edited;
|
||||
let rename = new_name.map(|nn| (name, Some(nn)));
|
||||
save_library(s, "Brush Options", lib, rename.as_slice())?;
|
||||
Ok(json!({ "name": out }))
|
||||
|
||||
@@ -1045,11 +1045,13 @@ impl Session {
|
||||
match std::fs::symlink_metadata(&path) {
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||
// A link is refused: the script's gate does not check where it leads.
|
||||
Ok(m) if !m.file_type().is_file() => return Err("not a plain file".to_string()),
|
||||
Ok(m) if !m.file_type().is_file() => return Err(crate::store::NOT_PLAIN.to_string()),
|
||||
_ => {}
|
||||
}
|
||||
crate::file_access::check_read(&file).map_err(denied)?;
|
||||
crate::store::read_capped(&path, MAX_PROFILE_BYTES).map(Some)
|
||||
// Read without following a link, so a link put in the file's place since the check
|
||||
// above is refused too.
|
||||
crate::store::read_capped_plain(&path, MAX_PROFILE_BYTES).map(Some)
|
||||
})?;
|
||||
let Some(bytes) = read else { return Ok(None) };
|
||||
// The color profiles the file carries are installed where missing, as opening it installs
|
||||
|
||||
@@ -1470,12 +1470,13 @@ fn in_live_paint(d: &Document, id: NodeId) -> bool {
|
||||
|
||||
impl DocState {
|
||||
/// [`live_paint_covered`] for `ids`, the selected objects or the selection's subjects: none
|
||||
/// when the [`SelectionPaints`] of the selection say no selected object is in a Live Paint group.
|
||||
/// when the [`SelectionPaints`] of the selection say no selected object is in a Live Paint group,
|
||||
/// else as [`DocState::live_paint_covered_kept`] keeps it for this version of the document.
|
||||
pub(crate) fn selection_live_paint_covered(&self, ids: &[NodeId]) -> std::collections::HashSet<NodeId> {
|
||||
if self.selection_paints().is_some_and(|p| !p.in_live_paint()) {
|
||||
return std::collections::HashSet::new();
|
||||
}
|
||||
live_paint_covered(&self.doc, ids)
|
||||
self.live_paint_covered_kept(ids)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -242,6 +242,58 @@ fn the_question_marks_read_only_the_selected_objects() {
|
||||
assert!(vectorcraft_doc::tree_walks() - walks <= 1, "one walk for a large selection");
|
||||
}
|
||||
|
||||
/// How many times this thread read the groups around selected objects for their Live Paint faces
|
||||
/// and edges ([`DocState::live_paint_covered_kept`]).
|
||||
fn cover_reads() -> usize {
|
||||
crate::doc_state::LIVE_PAINT_COVER_READS.with(Cell::get)
|
||||
}
|
||||
|
||||
/// After an edit the selection keeps no record of what it holds, and the proxies, the Stroke panel
|
||||
/// and the "?" ask on every frame whether its objects lie in a Live Paint group. They read the
|
||||
/// objects' groups once for each version of the document and selection, not once for each question.
|
||||
/// A Live Paint group selected with one of its faces still counts the face with its group.
|
||||
#[test]
|
||||
fn live_paint_faces_are_looked_for_once_per_document_version() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
|
||||
let ids: Vec<NodeId> = (0..20).map(|i| rect(&mut s, 10.0 + 30.0 * f64::from(i), "#ff0000", "#000000")).collect();
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
s.execute("object.move", &json!({"dx": 5, "dy": 0})).unwrap();
|
||||
assert!(s.active().unwrap().selection_paints().is_none(), "the edit leaves the selection without a record");
|
||||
let ask = |s: &Session| {
|
||||
for _ in 0..3 {
|
||||
s.proxy_paints();
|
||||
s.shown_stroke();
|
||||
s.proxy_mixed();
|
||||
s.active().unwrap().stroke_mixed();
|
||||
}
|
||||
};
|
||||
let before = cover_reads();
|
||||
ask(&s);
|
||||
assert_eq!(cover_reads() - before, 1, "one read for this version of the document");
|
||||
s.execute("object.move", &json!({"dx": 5, "dy": 0})).unwrap();
|
||||
let before = cover_reads();
|
||||
ask(&s);
|
||||
assert_eq!(cover_reads() - before, 1, "an edit reads them again, once");
|
||||
s.execute("select.set", &json!({"ids": [ids[0].0, ids[1].0]})).unwrap();
|
||||
s.execute("object.move", &json!({"dx": 5, "dy": 0})).unwrap();
|
||||
let before = cover_reads();
|
||||
ask(&s);
|
||||
assert_eq!(cover_reads() - before, 1, "another selection reads them again, once");
|
||||
|
||||
// A Live Paint group with one of its edges selected too: the edge counts with its group on every ask.
|
||||
s.execute("livePaint.make", &json!({"ids": [ids[2].0, ids[3].0]})).unwrap();
|
||||
let group = s.active().unwrap().selection.objects[0];
|
||||
let edge = vectorcraft_tools::builder::edges(s.active().unwrap().doc.node(group).unwrap())[0].id;
|
||||
s.execute("select.set", &json!({"ids": [group.0, edge.0]})).unwrap();
|
||||
let st = s.active().unwrap();
|
||||
let covered = live_paint_covered(&st.doc, &st.selection.objects);
|
||||
assert!(covered.contains(&edge));
|
||||
for _ in 0..2 {
|
||||
assert_eq!(st.selection_live_paint_covered(&st.selection.objects), covered);
|
||||
}
|
||||
}
|
||||
|
||||
/// Random selections of a document with nested groups answer as a walk does.
|
||||
#[test]
|
||||
fn random_selections_match_a_walk_of_the_document() {
|
||||
|
||||
@@ -409,6 +409,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"object.slice.release",
|
||||
"object.slice.select",
|
||||
"object.slice.setRect",
|
||||
"object.stepAndRepeat",
|
||||
"object.tag.add",
|
||||
"object.tag.remove",
|
||||
"object.tag.removeAll",
|
||||
|
||||
@@ -725,6 +725,8 @@ impl Session {
|
||||
for e in self.prefs.keep_folders(&mut p) {
|
||||
log::warn!("{e}");
|
||||
}
|
||||
// Tool settings saved by an earlier version are updated once.
|
||||
p.migrate_tool_settings();
|
||||
// Saved gradient presets get names no built-in preset or other saved one has.
|
||||
for (old, new) in super::gradpresets::rename_clashing_presets(&mut p.gradient_presets) {
|
||||
log::warn!("saved gradient preset {old} is listed as {new}: another preset has its name");
|
||||
|
||||
@@ -1027,6 +1027,84 @@ fn used_colors(d: &Document, ids: &[NodeId], only: Option<&BTreeSet<NodeId>>) ->
|
||||
used.into_iter().map(|(_, u)| u).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// Tests: how many objects [`several_colors`] read on this thread.
|
||||
static SEVERAL_COLORS_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Whether [`used_colors`] lists more than one color for the objects `ids`. The objects are read
|
||||
/// until a second color turns up.
|
||||
fn several_colors(d: &Document, ids: &[NodeId], only: Option<&BTreeSet<NodeId>>) -> bool {
|
||||
struct Seen<'a> {
|
||||
first: Option<ColorKey>,
|
||||
several: bool,
|
||||
patterns: Vec<&'a str>,
|
||||
}
|
||||
impl<'a> Seen<'a> {
|
||||
fn read(&mut self, m: &'a Node) {
|
||||
#[cfg(test)]
|
||||
SEVERAL_COLORS_READS.with(|c| c.set(c.get() + 1));
|
||||
let (first, several) = (&mut self.first, &mut self.several);
|
||||
paints(
|
||||
m,
|
||||
&mut |c, _, _, _| {
|
||||
let k = ColorKey::of(c);
|
||||
match first {
|
||||
None => *first = Some(k),
|
||||
Some(f) => *several |= *f != k,
|
||||
}
|
||||
},
|
||||
&mut self.patterns,
|
||||
);
|
||||
}
|
||||
fn read_tree(&mut self, n: &'a Node, only: Option<&BTreeSet<NodeId>>) {
|
||||
if self.several || only.is_some_and(|o| !o.contains(&n.id)) {
|
||||
return;
|
||||
}
|
||||
self.read(n);
|
||||
for c in n.children().into_iter().flatten() {
|
||||
self.read_tree(c, only);
|
||||
if self.several {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut seen = Seen { first: None, several: false, patterns: vec![] };
|
||||
for n in ids.iter().filter_map(|id| d.node(*id)) {
|
||||
seen.read_tree(n, only);
|
||||
if seen.several {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
let mut next = 0;
|
||||
while !seen.several
|
||||
&& let Some(&name) = seen.patterns.get(next)
|
||||
{
|
||||
next += 1;
|
||||
for a in d.pattern(name).map(|def| def.art.as_slice()).unwrap_or_default() {
|
||||
let _ = a.try_walk(&mut |m| {
|
||||
seen.read(m);
|
||||
if seen.several { std::ops::ControlFlow::Break(()) } else { std::ops::ControlFlow::Continue(()) }
|
||||
});
|
||||
if seen.several {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
seen.several
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Whether the objects `recolor.colors` reads without `ids` use more than one color: the
|
||||
/// selection, or with nothing selected the objects Select All takes. False without a document.
|
||||
pub fn several_colors_used(&self) -> bool {
|
||||
let Ok((ids, only)) = scope_ids(self, &Value::Null, "recolor.colors") else { return false };
|
||||
self.doc().is_ok_and(|st| several_colors(&st.doc, &ids, only.as_ref()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Count the colors `m` holds itself with `count` (the color, its swatch, the tint the paint
|
||||
/// stores, and whether it is a gradient stop that mixes the swatch's ink with process inks), and
|
||||
/// add the patterns it is painted with to `patterns`.
|
||||
@@ -2050,6 +2128,69 @@ mod tests {
|
||||
assert!(has(&t, RED), "P100 read again at the top");
|
||||
}
|
||||
|
||||
/// How many objects [`several_colors`] read on this thread.
|
||||
fn several_reads() -> usize {
|
||||
SEVERAL_COLORS_READS.with(std::cell::Cell::get)
|
||||
}
|
||||
|
||||
/// Whether more than one color is used ([`Session::several_colors_used`]), checked against the
|
||||
/// length of `recolor.colors`'s list, with how many objects the answer read.
|
||||
fn several(s: &mut Session, what: &str) -> (bool, usize) {
|
||||
let before = several_reads();
|
||||
let several = s.several_colors_used();
|
||||
let reads = several_reads() - before;
|
||||
let listed = s.execute("recolor.colors", &json!({})).unwrap()["colors"].as_array().map_or(0, Vec::len);
|
||||
assert_eq!(several, listed > 1, "{what}: {listed} colors listed");
|
||||
(several, reads)
|
||||
}
|
||||
|
||||
/// The Recolor quick action asks on every change whether the selection uses more than one
|
||||
/// color. The answer matches `recolor.colors`, pattern tiles and Select All's objects included,
|
||||
/// and the objects are read only until a second color turns up.
|
||||
#[test]
|
||||
fn several_colors_stop_at_the_second_color() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
|
||||
let ids: Vec<u64> = (0..30)
|
||||
.map(|i| {
|
||||
let id =
|
||||
s.execute("shape.rectangle", &json!({"x": 10 + 20 * i, "y": 10, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("paint.setFill", &json!({"ids": [id], "color": "#ff0000"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [id], "none": true})).unwrap();
|
||||
id
|
||||
})
|
||||
.collect();
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
assert_eq!(several(&mut s, "one red"), (false, 30), "one color: every object is read");
|
||||
// A blue object in the middle: the objects are read up to it, from either end.
|
||||
s.execute("paint.setFill", &json!({"ids": [ids[15]], "color": "#0000ff"})).unwrap();
|
||||
let (found, reads) = several(&mut s, "a blue in the middle");
|
||||
assert!(found && matches!(reads, 15 | 16), "{reads} objects read");
|
||||
s.execute("paint.setFill", &json!({"ids": [ids[0], ids[29]], "color": "#00ff00"})).unwrap();
|
||||
assert_eq!(several(&mut s, "green at both ends"), (true, 2), "the second object holds the second color");
|
||||
s.execute("select.set", &json!({"ids": &ids[1..15]})).unwrap();
|
||||
assert!(!several(&mut s, "the red ones").0);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert!(several(&mut s, "Select All's objects").0);
|
||||
|
||||
// A red object filled with a pattern too: its tile's color counts.
|
||||
for (tile, expect) in [(BLUE, true), (RED, false)] {
|
||||
let filled = NodeId(ids[1]);
|
||||
s.edit("t", |d, _| {
|
||||
let art = square(d, 0.0, Paint::solid(tile));
|
||||
d.patterns.retain(|p| p.name != "Tile");
|
||||
d.patterns.push(PatternDef::new("Tile", vec![art]));
|
||||
if let Some(n) = d.node_mut(filled) {
|
||||
n.appearance.set_fill(Paint::Pattern { pattern: "Tile".into(), xf: Affine::IDENTITY });
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [ids[1], ids[2]]})).unwrap();
|
||||
assert_eq!(several(&mut s, "a pattern tile").0, expect, "a tile of {tile:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A pattern tile's symbol instances charge the same limit as the art around it.
|
||||
#[test]
|
||||
fn pattern_tiles_charge_the_symbol_limit() {
|
||||
|
||||
@@ -0,0 +1,214 @@
|
||||
//! Object › Step and Repeat: lays out copies of the selection on a grid or fills a sheet, for
|
||||
//! print-and-cut work (stickers, labels).
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_geom::{Rect, Vec2, rotate_deg};
|
||||
|
||||
use super::edit::{copy_above, selected_roots};
|
||||
use super::object::group_nodes;
|
||||
use super::{Affine, CommandSpec, NodeId, Result, Session, bad, check_numbers, check_switches, cmd, has_selection, switch_or};
|
||||
use crate::EngineError;
|
||||
use vectorcraft_doc::Scaling;
|
||||
|
||||
const CMD: &str = "object.stepAndRepeat";
|
||||
const MAX_CELLS: usize = 10_000;
|
||||
const EPS: f64 = 1e-9;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"object.stepAndRepeat",
|
||||
"Step and Repeat…",
|
||||
["Object", "Transform"],
|
||||
None,
|
||||
"{rows?: n (default 1), columns?: n (default 1), fill?: bool (rows and columns are as many as fit the sheet, ignoring `rows` and `columns`; the first copy goes to the sheet's top-left corner plus `margin`), sheet?: {x, y, width, height} (pt; default the artboard that holds the selection's center, else the first), margin?: pt (fill only, default 0), gap?: pt (between neighbors, both axes), gapX?: pt, gapY?: pt (default `gap`, default 0; measured between the bounds of `cutId`, else of the selection, not between centers), cutId?: id (a selected object whose geometric bounds measure the spacing and the 180° turn; default the selection), rotate?: \"none\"|\"columns\"|\"rows\" (turn every other column or row by 180° about its cell's center, the same clockwise or counter-clockwise; default none), patterns?: bool} copy the selection into a grid of cells, left to right and top to bottom, the first cell being the selection itself (moved to the sheet's corner with fill); copies of pixel-aligned objects stay on the pixel grid, so a fractional gap between them is rounded to it, and gaps of other objects are exact; a selection of several objects is grouped first, so that a cut contour stays with its artwork in every copy; one undo step; the copies are selected → {ids: [id…], rows, columns, count}",
|
||||
has_selection,
|
||||
step_and_repeat
|
||||
)]
|
||||
}
|
||||
|
||||
/// Which cells of the grid are turned by 180°.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
pub enum Alternate {
|
||||
None,
|
||||
Columns,
|
||||
Rows,
|
||||
}
|
||||
|
||||
/// One cell of a layout: its place in the grid, the offset of its top-left corner from the first
|
||||
/// cell's, and whether its copy is turned by 180° about the cell's center.
|
||||
#[derive(Clone, Copy, PartialEq, Debug)]
|
||||
pub struct Cell {
|
||||
pub row: usize,
|
||||
pub col: usize,
|
||||
pub dx: f64,
|
||||
pub dy: f64,
|
||||
pub turned: bool,
|
||||
}
|
||||
|
||||
/// How many items of `size` with `gap` between them fit in `room` (all at least 0).
|
||||
pub fn fit_count(room: f64, size: f64, gap: f64) -> usize {
|
||||
if !(room.is_finite() && size.is_finite() && gap.is_finite()) || size <= 0.0 || room < size - EPS {
|
||||
return 0;
|
||||
}
|
||||
(((room + gap) / (size + gap)) + EPS).floor().max(0.0) as usize
|
||||
}
|
||||
|
||||
/// The `(rows, columns)` of items `w` × `h` with gaps `gx`, `gy` that fit a sheet `sw` × `sh`
|
||||
/// inside `margin` on every side.
|
||||
pub fn fill_counts(sw: f64, sh: f64, margin: f64, w: f64, h: f64, gx: f64, gy: f64) -> (usize, usize) {
|
||||
let m = margin.max(0.0);
|
||||
(fit_count(sh - 2.0 * m, h, gy), fit_count(sw - 2.0 * m, w, gx))
|
||||
}
|
||||
|
||||
/// The cells of a `rows` × `cols` grid of items `w` × `h` with gaps `gx` between columns and `gy`
|
||||
/// between rows, in reading order.
|
||||
pub fn layout(w: f64, h: f64, gx: f64, gy: f64, rows: usize, cols: usize, alt: Alternate) -> Vec<Cell> {
|
||||
(0..rows)
|
||||
.flat_map(|row| (0..cols).map(move |col| (row, col)))
|
||||
.map(|(row, col)| Cell {
|
||||
row,
|
||||
col,
|
||||
dx: col as f64 * (w + gx),
|
||||
dy: row as f64 * (h + gy),
|
||||
turned: match alt {
|
||||
Alternate::None => false,
|
||||
Alternate::Columns => col % 2 == 1,
|
||||
Alternate::Rows => row % 2 == 1,
|
||||
},
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn count_param(p: &Value, key: &str) -> Result<usize> {
|
||||
match p.get(key).filter(|v| !v.is_null()) {
|
||||
None => Ok(1),
|
||||
Some(v) => v
|
||||
.as_u64()
|
||||
.filter(|n| (1..=MAX_CELLS as u64).contains(n))
|
||||
.map(|n| n as usize)
|
||||
.ok_or_else(|| bad(CMD, format!("`{key}` must be a whole number from 1 to {MAX_CELLS}"))),
|
||||
}
|
||||
}
|
||||
|
||||
fn sheet_param(p: &Value) -> Result<Option<Rect>> {
|
||||
let Some(v) = p.get("sheet").filter(|v| !v.is_null()) else { return Ok(None) };
|
||||
let n = |k: &str| v.get(k).and_then(Value::as_f64).filter(|x| x.is_finite()).ok_or_else(|| bad(CMD, format!("`sheet.{k}` must be a number")));
|
||||
let (x, y, w, h) = (n("x")?, n("y")?, n("width")?, n("height")?);
|
||||
if w <= 0.0 || h <= 0.0 {
|
||||
return Err(bad(CMD, "`sheet` needs a positive width and height"));
|
||||
}
|
||||
Ok(Some(Rect::new(x, y, x + w, y + h)))
|
||||
}
|
||||
|
||||
fn step_and_repeat(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
check_numbers(p, &["gap", "gapX", "gapY", "margin"], CMD)?;
|
||||
check_switches(p, &["patterns"], CMD)?;
|
||||
let fill = switch_or(p, "fill", false, CMD)?;
|
||||
let alt = match p.get("rotate").filter(|v| !v.is_null()) {
|
||||
None => Alternate::None,
|
||||
Some(v) => match v.as_str() {
|
||||
Some("none") => Alternate::None,
|
||||
Some("columns") => Alternate::Columns,
|
||||
Some("rows") => Alternate::Rows,
|
||||
_ => return Err(bad(CMD, "`rotate` must be \"none\", \"columns\" or \"rows\"")),
|
||||
},
|
||||
};
|
||||
let gap = super::f64_or(p, "gap", 0.0);
|
||||
let (gx, gy) = (super::f64_or(p, "gapX", gap), super::f64_or(p, "gapY", gap));
|
||||
let margin = super::f64_or(p, "margin", 0.0);
|
||||
if !(gx.is_finite() && gy.is_finite() && margin.is_finite()) {
|
||||
return Err(bad(CMD, "gaps and margin must be finite"));
|
||||
}
|
||||
let (rows, cols) = if fill { (1, 1) } else { (count_param(p, "rows")?, count_param(p, "columns")?) };
|
||||
let sheet = sheet_param(p)?;
|
||||
let mut roots = selected_roots(s)?;
|
||||
if roots.is_empty() {
|
||||
return Err(EngineError::Other("nothing selected".into()));
|
||||
}
|
||||
let d = &s.doc()?.doc;
|
||||
let cut = match p.get("cutId").filter(|v| !v.is_null()) {
|
||||
None => None,
|
||||
Some(v) => {
|
||||
let id = NodeId(v.as_u64().ok_or_else(|| bad(CMD, "`cutId` must be an object id"))?);
|
||||
let held = roots.iter().filter_map(|r| d.node(*r)).any(|n| {
|
||||
let mut found = false;
|
||||
n.walk(&mut |c| found |= c.id == id);
|
||||
found
|
||||
});
|
||||
if !held {
|
||||
return Err(bad(CMD, "`cutId` must be part of the selection"));
|
||||
}
|
||||
Some(id)
|
||||
}
|
||||
};
|
||||
let measured = cut.map_or_else(|| roots.clone(), |id| vec![id]);
|
||||
let b = d.bounds_of(&measured, false);
|
||||
let b = b.ok_or_else(|| EngineError::Other("the selection has no bounds".into()))?;
|
||||
let (w, h) = (b.width(), b.height());
|
||||
if !(w.is_finite() && h.is_finite()) || w <= 0.0 || h <= 0.0 {
|
||||
return Err(EngineError::Other("the selection has no area to repeat".into()));
|
||||
}
|
||||
let anchor = if fill {
|
||||
let sheet = sheet.or_else(|| {
|
||||
let c = d.bounds_of(&roots, false).unwrap_or(b).center();
|
||||
d.artboards.iter().find(|a| a.rect.contains(c)).or_else(|| d.artboards.first()).map(|a| a.rect)
|
||||
});
|
||||
let sheet = sheet.ok_or_else(|| EngineError::Other("no sheet to fill".into()))?;
|
||||
Some((sheet, margin.max(0.0)))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let (rows, cols) = match anchor {
|
||||
Some((sh, m)) => fill_counts(sh.width(), sh.height(), m, w, h, gx, gy),
|
||||
None => (rows, cols),
|
||||
};
|
||||
if rows == 0 || cols == 0 {
|
||||
return Err(EngineError::Other("the selection does not fit the sheet".into()));
|
||||
}
|
||||
if rows.saturating_mul(cols) > MAX_CELLS {
|
||||
return Err(bad(CMD, format!("more than {MAX_CELLS} copies")));
|
||||
}
|
||||
let origin = anchor.map_or(Vec2::ZERO, |(sh, m)| Vec2::new(sh.x0 + m - b.x0, sh.y0 + m - b.y0));
|
||||
let cells = layout(w, h, gx, gy, rows, cols, alt);
|
||||
let center = b.center().to_vec2();
|
||||
let place = |c: &Cell| -> Affine {
|
||||
let t = Affine::translate(origin + Vec2::new(c.dx, c.dy));
|
||||
if c.turned { t * Affine::translate(center) * rotate_deg(180.0) * Affine::translate(-center) } else { t }
|
||||
};
|
||||
let sc = Scaling { patterns: super::object::transform_patterns(s, p, &roots)?, ..Scaling::default() };
|
||||
let ids = s.edit("Step and Repeat", |d, sel| {
|
||||
if roots.len() > 1 {
|
||||
roots = vec![group_nodes(d, &roots)?];
|
||||
}
|
||||
let mut copied: Vec<NodeId> = vec![];
|
||||
let mut first = Affine::IDENTITY;
|
||||
for c in &cells {
|
||||
let m = place(c);
|
||||
if c.row == 0 && c.col == 0 {
|
||||
first = m;
|
||||
continue;
|
||||
}
|
||||
let copies = copy_above(d, &roots, |_, _, n| {
|
||||
n.transform(m, sc);
|
||||
super::object::keep_pixel_aligned(n, sc);
|
||||
})?;
|
||||
copied.extend(copies);
|
||||
}
|
||||
if first != Affine::IDENTITY {
|
||||
for id in &roots {
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
n.transform(first, sc);
|
||||
super::object::keep_pixel_aligned(n, sc);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out: Vec<NodeId> = roots.clone();
|
||||
out.extend(copied);
|
||||
sel.set(out.iter().copied());
|
||||
Ok(out)
|
||||
})?;
|
||||
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "rows": rows, "columns": cols, "count": ids.len() }))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,178 @@
|
||||
use serde_json::json;
|
||||
|
||||
use super::*;
|
||||
|
||||
const A4: (f64, f64) = (210.0, 297.0);
|
||||
|
||||
#[test]
|
||||
fn fills_a4_with_50_by_30_items_and_3_gap() {
|
||||
assert_eq!(fill_counts(A4.0, A4.1, 0.0, 50.0, 30.0, 3.0, 3.0), (9, 4));
|
||||
assert_eq!(fill_counts(A4.0, A4.1, 5.0, 50.0, 30.0, 3.0, 3.0), (8, 3));
|
||||
assert_eq!(fill_counts(40.0, 297.0, 0.0, 50.0, 30.0, 3.0, 3.0), (9, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layout_places_cells_at_the_pitch_and_alternates_rotation() {
|
||||
let c = layout(50.0, 30.0, 3.0, 3.0, 9, 4, Alternate::Columns);
|
||||
assert_eq!(c.len(), 36);
|
||||
let at = |r: usize, k: usize| c[r * 4 + k];
|
||||
assert_eq!((at(0, 0).dx, at(0, 0).dy), (0.0, 0.0));
|
||||
assert_eq!((at(2, 3).dx, at(2, 3).dy), (159.0, 66.0));
|
||||
assert_eq!(c.iter().filter(|c| c.turned).count(), 18);
|
||||
assert!(at(4, 1).turned && at(4, 3).turned && !at(4, 0).turned && !at(4, 2).turned);
|
||||
let rows = layout(50.0, 30.0, 3.0, 3.0, 3, 2, Alternate::Rows);
|
||||
assert_eq!(rows.iter().map(|c| c.turned).collect::<Vec<_>>(), [false, false, true, true, false, false]);
|
||||
assert!(layout(50.0, 30.0, 3.0, 3.0, 3, 2, Alternate::None).iter().all(|c| !c.turned));
|
||||
}
|
||||
|
||||
fn setup() -> (Session, u64) {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 210, "height": 297})).unwrap();
|
||||
let id = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 30})).unwrap()["id"].as_u64().unwrap();
|
||||
(s, id)
|
||||
}
|
||||
|
||||
fn bounds(s: &Session, id: u64) -> (f64, f64, f64, f64) {
|
||||
let b = s.doc().unwrap().doc.node(NodeId(id)).unwrap().geometric_bounds().unwrap();
|
||||
(b.x0, b.y0, b.x1, b.y1)
|
||||
}
|
||||
|
||||
fn undo_steps(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn creates_the_grid_in_one_undo_step_and_undoes_cleanly() {
|
||||
let (mut s, _) = setup();
|
||||
let (before, steps) = (s.doc().unwrap().doc.clone(), undo_steps(&s));
|
||||
let r = s.execute(CMD, &json!({"rows": 2, "columns": 3, "gap": 3})).unwrap();
|
||||
assert_eq!((r["count"].clone(), r["rows"].clone(), r["columns"].clone()), (json!(6), json!(2), json!(3)));
|
||||
assert_eq!(undo_steps(&s), steps + 1);
|
||||
let ids: Vec<u64> = r["ids"].as_array().unwrap().iter().map(|i| i.as_u64().unwrap()).collect();
|
||||
assert_eq!(bounds(&s, ids[0]), (0.0, 0.0, 50.0, 30.0));
|
||||
assert_eq!(bounds(&s, ids[4]), (53.0, 33.0, 103.0, 63.0));
|
||||
assert_eq!(bounds(&s, ids[5]), (106.0, 33.0, 156.0, 63.0));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.artboards.len(), before.artboards.len());
|
||||
assert!(d.node(NodeId(ids[0])).is_some());
|
||||
assert!(ids[1..].iter().all(|i| d.node(NodeId(*i)).is_none()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fill_sheet_with_margin_moves_the_first_copy_to_the_corner() {
|
||||
let (mut s, _) = setup();
|
||||
let r = s.execute(CMD, &json!({"fill": true, "gap": 3, "margin": 0})).unwrap();
|
||||
assert_eq!((r["rows"].clone(), r["columns"].clone(), r["count"].clone()), (json!(9), json!(4), json!(36)));
|
||||
let (mut s, _) = setup();
|
||||
let r = s.execute(CMD, &json!({"fill": true, "gap": 3, "margin": 5})).unwrap();
|
||||
assert_eq!(r["count"], json!(24));
|
||||
let first = r["ids"][0].as_u64().unwrap();
|
||||
assert_eq!(bounds(&s, first), (5.0, 5.0, 55.0, 35.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fill_places_every_cell_from_the_original_when_it_starts_away_from_the_margin() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 210, "height": 297})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 20, "y": 40, "width": 50, "height": 30})).unwrap();
|
||||
let r = s.execute(CMD, &json!({"fill": true, "gap": 3, "margin": 5, "rotate": "columns"})).unwrap();
|
||||
let ids: Vec<u64> = r["ids"].as_array().unwrap().iter().map(|i| i.as_u64().unwrap()).collect();
|
||||
assert_eq!((r["rows"].clone(), r["columns"].clone()), (json!(8), json!(3)));
|
||||
assert_eq!(bounds(&s, ids[0]), (5.0, 5.0, 55.0, 35.0));
|
||||
assert_eq!(bounds(&s, ids[1]), (58.0, 5.0, 108.0, 35.0));
|
||||
assert_eq!(bounds(&s, ids[2]), (111.0, 5.0, 161.0, 35.0));
|
||||
assert_eq!(bounds(&s, ids[3]), (5.0, 38.0, 55.0, 68.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn alternate_columns_turn_by_180_degrees_about_the_cell_center() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 210, "height": 297})).unwrap();
|
||||
let id = s.execute("shape.polygon", &json!({"cx": 25, "cy": 15, "radius": 10, "sides": 3})).unwrap()["id"].as_u64().unwrap();
|
||||
let b0 = bounds(&s, id);
|
||||
let r = s.execute(CMD, &json!({"rows": 1, "columns": 2, "gap": 4, "rotate": "columns"})).unwrap();
|
||||
let ids: Vec<u64> = r["ids"].as_array().unwrap().iter().map(|i| i.as_u64().unwrap()).collect();
|
||||
let (w, b1) = (b0.2 - b0.0, bounds(&s, ids[1]));
|
||||
assert!((b1.0 - (b0.0 + w + 4.0)).abs() < 1e-6 && ((b1.2 - b1.0) - w).abs() < 1e-6);
|
||||
assert!((b1.1 - b0.1).abs() < 1e-6 && (b1.3 - b0.3).abs() < 1e-6);
|
||||
let tri = |s: &Session, id: u64| format!("{:?}", s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind);
|
||||
assert_ne!(tri(&s, ids[0]), tri(&s, ids[1]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cut_contour_stays_grouped_with_its_artwork_in_every_copy() {
|
||||
let (mut s, art) = setup();
|
||||
let cut = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 30})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [art, cut]})).unwrap();
|
||||
let r = s.execute(CMD, &json!({"rows": 1, "columns": 3, "gap": 2, "cutId": cut})).unwrap();
|
||||
assert_eq!(r["count"], json!(3));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
for id in r["ids"].as_array().unwrap() {
|
||||
let n = d.node(NodeId(id.as_u64().unwrap())).unwrap();
|
||||
assert!(matches!(n.kind, vectorcraft_doc::NodeKind::Group { .. }));
|
||||
let mut paths = 0;
|
||||
n.walk(&mut |c| paths += usize::from(matches!(c.kind, vectorcraft_doc::NodeKind::Path { .. })));
|
||||
assert_eq!(paths, 2);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_bad_params_and_a_selection_that_does_not_fit() {
|
||||
let (mut s, _) = setup();
|
||||
assert!(s.execute(CMD, &json!({"rows": 0})).is_err());
|
||||
assert!(s.execute(CMD, &json!({"rows": 1000, "columns": 1000})).is_err());
|
||||
assert!(s.execute(CMD, &json!({"rotate": "diagonal"})).is_err());
|
||||
assert!(s.execute(CMD, &json!({"cutId": 999999})).is_err());
|
||||
assert!(s.execute(CMD, &json!({"fill": true, "sheet": {"x": 0, "y": 0, "width": 40, "height": 40}})).is_err());
|
||||
let mut e = Session::new();
|
||||
e.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
assert!(e.execute(CMD, &json!({})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fill_ignores_explicit_counts() {
|
||||
let (mut s, _) = setup();
|
||||
let r = s.execute(CMD, &json!({"fill": true, "rows": 0, "columns": 0, "gap": 3})).unwrap();
|
||||
assert_eq!((r["rows"].clone(), r["columns"].clone()), (json!(9), json!(4)));
|
||||
assert!(s.execute(CMD, &json!({"rows": 0})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fractional_gaps_are_exact_except_for_pixel_aligned_objects_which_stay_on_the_grid() {
|
||||
let gap = |aligned: bool| {
|
||||
let (mut s, id) = setup();
|
||||
if aligned {
|
||||
s.execute("object.setPixelAligned", &json!({"ids": [id], "on": true})).unwrap();
|
||||
}
|
||||
let r = s.execute(CMD, &json!({"rows": 1, "columns": 2, "gapX": 0.5})).unwrap();
|
||||
let ids: Vec<u64> = r["ids"].as_array().unwrap().iter().map(|i| i.as_u64().unwrap()).collect();
|
||||
let (a, c) = (bounds(&s, ids[0]), bounds(&s, ids[1]));
|
||||
(c.0 - a.2, c.0 - a.0)
|
||||
};
|
||||
assert!((gap(false).0 - 0.5).abs() < 1e-9);
|
||||
let pitch = gap(true).1;
|
||||
assert!((pitch - pitch.round()).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fill_picks_the_artboard_of_the_selection_not_of_the_cut_contour() {
|
||||
let first_x = |sheet: Option<Value>| {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
s.execute("artboard.new", &json!({"x": 100, "y": 0, "width": 100, "height": 100})).unwrap();
|
||||
let art = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 60, "height": 20})).unwrap()["id"].as_u64().unwrap();
|
||||
let cut = s.execute("shape.rectangle", &json!({"x": 105, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [art, cut]})).unwrap();
|
||||
let mut p = json!({"fill": true, "cutId": cut});
|
||||
if let Some(sh) = sheet {
|
||||
p["sheet"] = sh;
|
||||
}
|
||||
let r = s.execute(CMD, &p).unwrap();
|
||||
bounds(&s, r["ids"][0].as_u64().unwrap()).0
|
||||
};
|
||||
let default = first_x(None);
|
||||
let explicit = first_x(Some(json!({"x": 100, "y": 0, "width": 100, "height": 100})));
|
||||
assert!((explicit - default - 100.0).abs() < 1e-9);
|
||||
}
|
||||
@@ -4,6 +4,8 @@
|
||||
//! resolves, for each area text object, the outlines of the wrap objects above it into
|
||||
//! `TextObject::wrap` (text space); the layout engine subtracts them from each line's span.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, NodeId, NodeKind, TextWrap};
|
||||
|
||||
@@ -17,7 +19,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Make",
|
||||
["Object", "Text Wrap"],
|
||||
None,
|
||||
"{offset?: pt (6), invert?: bool, ids?} area type below the selected objects (same layer) wraps around them; offset -1000 to 1000 (a negative one lets the text that far into them); an offset outside that range or not a number, or an invert that is not true or false, is an error → {ids}",
|
||||
"{offset?: pt (6), invert?: bool, ids?} area type below the selected objects (same layer) wraps around them; a selected type object with another selected object above it in its layer is the text to wrap, not a wrap object, and loses a wrap it had; offset -1000 to 1000 (a negative one lets the text that far into them); an offset outside that range or not a number, or an invert that is not true or false, is an error → {ids (the wrap objects), warning? (no area type lies below any of them)}",
|
||||
has_selection,
|
||||
make
|
||||
),
|
||||
@@ -27,13 +29,16 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Text Wrap Options…",
|
||||
["Object", "Text Wrap"],
|
||||
None,
|
||||
"{offset?: pt, invert?: bool, ids?} set the options of the selected wrap objects (offset -1000 to 1000; a negative one lets text into the objects); an offset outside that range or not a number, or an invert that is not true or false, is an error; no options (or null ones) → the current {offset, invert}",
|
||||
"{offset?: pt, invert?: bool, ids?} set the options of the selected wrap objects, leaving out the type selected below them as Make does (offset -1000 to 1000; a negative one lets text into the objects); an offset outside that range or not a number, or an invert that is not true or false, is an error; no options (or null ones) → the current {offset, invert}",
|
||||
has_selection,
|
||||
options
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// The warning Make gives when no area type lies below any of its wrap objects in their layer.
|
||||
pub const NO_AREA_TYPE_BELOW: &str = "Text Wrap: no area type lies below these objects in their layer, so no text wraps around them. Move the objects above the area type with Object › Arrange › Bring to Front. Point type does not wrap.";
|
||||
|
||||
/// The Offset a wrap object takes, in points.
|
||||
pub const TEXT_WRAP_OFFSET_RANGE: std::ops::RangeInclusive<f64> = -1000.0..=1000.0;
|
||||
|
||||
@@ -51,20 +56,70 @@ fn wrap_param(p: &Value, base: TextWrap, cmd: &str) -> Result<TextWrap> {
|
||||
Ok(TextWrap { offset, invert: switch_or(p, "invert", base.invert, cmd)? })
|
||||
}
|
||||
|
||||
/// The type objects of `ids` that lie below another of `ids` in their layer: the text Make wraps
|
||||
/// when the wrap objects and the type are selected together. Make leaves them out of the wrap
|
||||
/// objects, and takes the wrap off any of them that has one.
|
||||
fn type_to_wrap(d: &Document, ids: &[NodeId]) -> HashSet<NodeId> {
|
||||
let wanted: HashSet<NodeId> = ids.iter().copied().collect();
|
||||
// One pass in paint order: each selected type object with its layer and place, and the place of
|
||||
// the topmost selected object other than a layer in each layer.
|
||||
let mut texts = vec![];
|
||||
let mut top: HashMap<usize, usize> = HashMap::new();
|
||||
let mut at = 0usize;
|
||||
for (layer, l) in d.layers.iter().enumerate() {
|
||||
l.walk(&mut |n| {
|
||||
if wanted.contains(&n.id) {
|
||||
match n.kind {
|
||||
NodeKind::Layer { .. } => {}
|
||||
NodeKind::Text(_) => {
|
||||
texts.push((n.id, layer, at));
|
||||
top.insert(layer, at);
|
||||
}
|
||||
_ => {
|
||||
top.insert(layer, at);
|
||||
}
|
||||
}
|
||||
}
|
||||
at += 1;
|
||||
});
|
||||
}
|
||||
texts.into_iter().filter(|(_, layer, at)| top.get(layer).is_some_and(|t| t > at)).map(|(id, _, _)| id).collect()
|
||||
}
|
||||
|
||||
fn make(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = checked_ids_or_selection(s, p, "object.textWrap.make")?;
|
||||
let w = wrap_param(p, TextWrap::default(), "object.textWrap.make")?;
|
||||
s.edit("Make Text Wrap", |d, _| {
|
||||
for id in &ids {
|
||||
let n = d.node_mut(*id).ok_or(EngineError::NoNode(*id))?;
|
||||
if matches!(n.kind, NodeKind::Layer { .. }) {
|
||||
let (objects, text, changed) = {
|
||||
let d = &s.doc()?.doc;
|
||||
let text = type_to_wrap(d, &ids);
|
||||
let objects: Vec<NodeId> = ids.iter().copied().filter(|i| !text.contains(i)).collect();
|
||||
for id in &objects {
|
||||
if d.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. })) {
|
||||
return Err(EngineError::Other("layers can't be wrap objects".into()));
|
||||
}
|
||||
n.extras_mut().wrap = Some(w);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() }))
|
||||
let changed = objects.iter().any(|i| d.node(*i).is_some_and(|n| n.extras().wrap != Some(w)))
|
||||
|| text.iter().any(|i| d.node(*i).is_some_and(|n| n.extras().wrap.is_some()));
|
||||
(objects, text, changed)
|
||||
};
|
||||
if changed {
|
||||
s.edit("Make Text Wrap", |d, _| {
|
||||
for id in &objects {
|
||||
d.node_mut(*id).ok_or(EngineError::NoNode(*id))?.extras_mut().wrap = Some(w);
|
||||
}
|
||||
for id in &text {
|
||||
d.node_mut(*id).ok_or(EngineError::NoNode(*id))?.extras_mut().wrap = None;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
let mut out = json!({ "ids": objects.iter().map(|i| i.0).collect::<Vec<_>>() });
|
||||
let mut wraps = false;
|
||||
vectorcraft_doc::text::wrap_sources(&s.doc()?.doc, |_, sources, _| wraps |= sources.iter().any(|n| objects.contains(&n.id)));
|
||||
if !wraps {
|
||||
out["warning"] = json!(NO_AREA_TYPE_BELOW);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn release(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -91,14 +146,25 @@ fn release(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = checked_ids_or_selection(s, p, "object.textWrap.options")?;
|
||||
let current = {
|
||||
// The type selected below the wrap objects is the text they wrap, as in Make.
|
||||
let (ids, current) = {
|
||||
let d = &s.doc()?.doc;
|
||||
ids.iter().find_map(|i| d.node(*i).and_then(|n| n.extras().wrap)).unwrap_or_default()
|
||||
let text = type_to_wrap(d, &ids);
|
||||
let ids: Vec<NodeId> = ids.into_iter().filter(|i| !text.contains(i)).collect();
|
||||
let current = ids.iter().find_map(|i| d.node(*i).and_then(|n| n.extras().wrap)).unwrap_or_default();
|
||||
(ids, current)
|
||||
};
|
||||
if ["offset", "invert"].iter().all(|k| p.get(k).is_none_or(Value::is_null)) {
|
||||
return Ok(json!({ "offset": current.offset, "invert": current.invert }));
|
||||
}
|
||||
let w = wrap_param(p, current, "object.textWrap.options")?;
|
||||
let changed = {
|
||||
let d = &s.doc()?.doc;
|
||||
ids.iter().any(|i| d.node(*i).is_some_and(|n| !matches!(n.kind, NodeKind::Layer { .. }) && n.extras().wrap != Some(w)))
|
||||
};
|
||||
if !changed {
|
||||
return Ok(json!({ "offset": w.offset, "invert": w.invert }));
|
||||
}
|
||||
s.edit("Text Wrap Options", |d, _| {
|
||||
for id in &ids {
|
||||
if let Some(n) = d.node_mut(*id)
|
||||
@@ -287,6 +353,95 @@ mod tests {
|
||||
assert_eq!(s.execute("object.textWrap.options", &json!({"invert": true})).unwrap(), json!({"offset": 5000.0, "invert": true}));
|
||||
}
|
||||
|
||||
fn wrap_of(s: &Session, id: u64) -> Option<vectorcraft_doc::TextWrap> {
|
||||
s.doc().unwrap().doc.node(NodeId(id)).unwrap().extras().wrap
|
||||
}
|
||||
|
||||
fn area_type(s: &mut Session) -> u64 {
|
||||
s.execute("text.create", &json!({"x": 0, "y": 0, "text": "word ".repeat(300), "size": 12, "area": {"width": 400, "height": 400}}))
|
||||
.unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn ellipse(s: &mut Session) -> u64 {
|
||||
s.execute("shape.ellipse", &json!({"x": 150, "y": 100, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap()
|
||||
}
|
||||
|
||||
/// Make with the wrap object and the area type below it selected together wraps the type: the
|
||||
/// type is the text to wrap, not another wrap object (#3211).
|
||||
#[test]
|
||||
fn make_with_the_area_type_selected_wraps_it() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap();
|
||||
let t = area_type(&mut s);
|
||||
let plain = lines(&s, t);
|
||||
let c = ellipse(&mut s);
|
||||
s.execute("select.set", &json!({"ids": [c, t]})).unwrap();
|
||||
let r = s.execute("object.textWrap.make", &json!({})).unwrap();
|
||||
assert_eq!(r, json!({"ids": [c]}), "{r}");
|
||||
assert!(wrap_of(&s, c).is_some());
|
||||
assert!(wrap_of(&s, t).is_none(), "the area type became a wrap object");
|
||||
assert_ne!(lines(&s, t), plain, "the area type did not wrap");
|
||||
// Make again with the same options changes nothing and records no undo step.
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
assert_eq!(s.execute("object.textWrap.make", &json!({})).unwrap(), json!({"ids": [c]}));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps);
|
||||
// Text Wrap Options with both still selected sets the wrap object's options only, and the
|
||||
// type keeps wrapping; the same options again record no undo step.
|
||||
let wrapped = lines(&s, t);
|
||||
assert_eq!(s.execute("object.textWrap.options", &json!({"offset": 30})).unwrap()["offset"], json!(30.0));
|
||||
assert_eq!(wrap_of(&s, c).map(|w| w.offset), Some(30.0));
|
||||
assert!(wrap_of(&s, t).is_none(), "Options made the area type a wrap object");
|
||||
assert_ne!(lines(&s, t), wrapped, "the type did not follow the new offset");
|
||||
assert_ne!(lines(&s, t), plain);
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
s.execute("object.textWrap.options", &json!({"offset": 30})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
// One undo takes the wrap off again.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(wrap_of(&s, c).is_none());
|
||||
assert_eq!(lines(&s, t), plain);
|
||||
}
|
||||
|
||||
/// Make with the object below the area type warns that no text wraps. After Bring to Front,
|
||||
/// Make with both selected wraps the type, and the type that the first Make made a wrap object
|
||||
/// is the text to wrap again (#3211).
|
||||
#[test]
|
||||
fn make_warns_when_the_object_is_below_the_type_and_wraps_after_bring_to_front() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap();
|
||||
let c = ellipse(&mut s);
|
||||
let t = area_type(&mut s);
|
||||
let plain = lines(&s, t);
|
||||
s.execute("select.set", &json!({"ids": [c, t]})).unwrap();
|
||||
let r = s.execute("object.textWrap.make", &json!({})).unwrap();
|
||||
assert_eq!(r["warning"], json!(super::NO_AREA_TYPE_BELOW), "{r}");
|
||||
assert_eq!(lines(&s, t), plain);
|
||||
s.execute("select.set", &json!({"ids": [c]})).unwrap();
|
||||
s.execute("object.arrange.bringToFront", &json!({})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [c, t]})).unwrap();
|
||||
let r = s.execute("object.textWrap.make", &json!({})).unwrap();
|
||||
assert!(r.get("warning").is_none(), "{r}");
|
||||
assert!(wrap_of(&s, t).is_none(), "the area type is still a wrap object");
|
||||
assert_ne!(lines(&s, t), plain, "the area type did not wrap");
|
||||
}
|
||||
|
||||
/// Point type below a wrap object does not wrap, so Make warns.
|
||||
#[test]
|
||||
fn make_warns_over_point_type() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap();
|
||||
let p = s.execute("text.create", &json!({"x": 0, "y": 100, "text": "point type", "size": 12})).unwrap()["id"].as_u64().unwrap();
|
||||
let r = s.execute("shape.rectangle", &json!({"x": 0, "y": 80, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [r, p]})).unwrap();
|
||||
let out = s.execute("object.textWrap.make", &json!({})).unwrap();
|
||||
assert_eq!(out["warning"], json!(super::NO_AREA_TYPE_BELOW), "{out}");
|
||||
assert!(wrap_of(&s, r).is_some());
|
||||
assert!(wrap_of(&s, p).is_none(), "the point type became a wrap object");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_flows_on_both_sides_of_a_centred_object() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -203,11 +203,23 @@ pub struct DocState {
|
||||
/// The selected objects as [`crate::Session::select`] last checked them or the proxies last
|
||||
/// read them, with the document they were checked in ([`SelectionRecord`]). Not saved.
|
||||
pub(crate) selection_record: Option<SelectionRecord>,
|
||||
/// The objects that [`DocState::live_paint_covered_kept`] last found no face or edge of a Live
|
||||
/// Paint group among, with the document it read. Not saved.
|
||||
outside_live_paint: std::cell::RefCell<Option<OutsideLivePaint>>,
|
||||
/// The last move of the selected objects that changed nothing else they show ([`Moved`]).
|
||||
/// Not saved.
|
||||
pub moved: Option<Moved>,
|
||||
}
|
||||
|
||||
/// Objects that hold no face or edge of a Live Paint group that counts with its group
|
||||
/// ([`cmd::live_paint_covered`] is empty for them), with the document they were read in, held as
|
||||
/// [`EmptyArtboards::doc`] holds it.
|
||||
#[derive(Clone, Debug)]
|
||||
struct OutsideLivePaint {
|
||||
doc: std::sync::Weak<Document>,
|
||||
ids: Vec<NodeId>,
|
||||
}
|
||||
|
||||
/// A move of whole objects that took document `from` to document `to`: each object the selection
|
||||
/// shows, the key object and the key anchor included, is the one in `from` moved by `by`, and
|
||||
/// nothing else they are drawn from changed (no member snapped to the pixel grid, no blend spine
|
||||
@@ -320,6 +332,8 @@ thread_local! {
|
||||
pub(crate) static EMPTY_ARTBOARD_MEASURES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
/// Tests: how many times [`DocState::any_art_to_fit`] measured a document on this thread.
|
||||
pub(crate) static ART_TO_FIT_MEASURES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
/// Tests: how many times [`DocState::live_paint_covered_kept`] read the objects' groups on this thread.
|
||||
pub(crate) static LIVE_PAINT_COVER_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
static NEXT_DOC_UID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
|
||||
@@ -540,6 +554,7 @@ impl DocState {
|
||||
measured_in_own: None,
|
||||
inline_resolved: None,
|
||||
selection_record: None,
|
||||
outside_live_paint: Default::default(),
|
||||
moved: None,
|
||||
}
|
||||
}
|
||||
@@ -558,6 +573,25 @@ impl DocState {
|
||||
pub(crate) fn selection_paints(&self) -> Option<&cmd::SelectionPaints> {
|
||||
self.selection_record().and_then(|r| r.paints.as_ref())
|
||||
}
|
||||
/// The faces and edges of Live Paint groups among `ids` that count with their group
|
||||
/// ([`cmd::live_paint_covered`]). An empty answer is kept for this version of the document and
|
||||
/// these objects, so the proxies and the Stroke panel, which ask on every frame, read the
|
||||
/// objects' groups once after an edit.
|
||||
pub(crate) fn live_paint_covered_kept(&self, ids: &[NodeId]) -> std::collections::HashSet<NodeId> {
|
||||
let kept = |k: &OutsideLivePaint| std::ptr::eq(k.doc.as_ptr(), Arc::as_ptr(&self.doc)) && k.ids == ids;
|
||||
if self.outside_live_paint.try_borrow().is_ok_and(|k| k.as_ref().is_some_and(kept)) {
|
||||
return std::collections::HashSet::new();
|
||||
}
|
||||
#[cfg(test)]
|
||||
LIVE_PAINT_COVER_READS.with(|c| c.set(c.get() + 1));
|
||||
let covered = cmd::live_paint_covered(&self.doc, ids);
|
||||
if covered.is_empty()
|
||||
&& let Ok(mut k) = self.outside_live_paint.try_borrow_mut()
|
||||
{
|
||||
*k = Some(OutsideLivePaint { doc: Arc::downgrade(&self.doc), ids: ids.to_vec() });
|
||||
}
|
||||
covered
|
||||
}
|
||||
/// Keep the [`SelectionRecord`] of the selection that [`crate::Session::select`] left, with
|
||||
/// Lock Guides `guides_locked`. `record` is the record of the selection before, in the same
|
||||
/// document: the objects that leave the selection are taken out of its paints and the objects
|
||||
|
||||
@@ -438,6 +438,12 @@ pub struct Prefs {
|
||||
/// resetting the preferences keeps them; `tool.setOption` edits them.
|
||||
#[serde(skip_serializing_if = "std::collections::BTreeMap::is_empty")]
|
||||
pub tool_settings: std::collections::BTreeMap<String, serde_json::Map<String, Value>>,
|
||||
/// The version of [`Self::tool_settings`]: [`TOOL_SETTINGS_VERSION`] once this version stores
|
||||
/// or updates a tool setting, 0 while none is stored and in preferences saved without one.
|
||||
/// [`Prefs::migrate_tool_settings`] updates older tool settings once. Not a Preferences dialog
|
||||
/// field: resetting the preferences keeps it.
|
||||
#[serde(default, skip_serializing_if = "is_zero")]
|
||||
pub tool_settings_version: u32,
|
||||
/// View → Perspective Grid presets: the user's (the built-in ones aren't stored). A local
|
||||
/// library, not a Preferences dialog field: resetting the preferences keeps it;
|
||||
/// `perspective.presets.*` edit it.
|
||||
@@ -464,7 +470,36 @@ pub const KEY_HOLD_DELAY: f64 = 0.35;
|
||||
/// The range of the Hold Shortcut Delay, in seconds.
|
||||
pub const KEY_HOLD_DELAY_RANGE: (f64, f64) = (0.2, 1.0);
|
||||
|
||||
/// The version of the tool settings these preferences write ([`Prefs::tool_settings_version`]).
|
||||
/// Version 1 makes Color Swatches the Shape Builder's Pick Color From.
|
||||
pub const TOOL_SETTINGS_VERSION: u32 = 1;
|
||||
|
||||
fn is_zero(v: &u32) -> bool {
|
||||
*v == 0
|
||||
}
|
||||
|
||||
impl Prefs {
|
||||
/// Update tool settings saved by an earlier version to [`TOOL_SETTINGS_VERSION`], once. Before
|
||||
/// version 1, leaving the Shape Builder saved its `pickColorFrom` whether or not it was
|
||||
/// changed, so a saved `artwork` becomes `swatches`. Without tool settings, nothing changes; a
|
||||
/// version newer than this one is kept.
|
||||
pub fn migrate_tool_settings(&mut self) {
|
||||
if self.tool_settings_version < 1
|
||||
&& let Some(saved) = self.tool_settings.get_mut("shapeBuilder")
|
||||
&& saved.get("pickColorFrom").and_then(Value::as_str) == Some("artwork")
|
||||
{
|
||||
saved.insert("pickColorFrom".into(), Value::from("swatches"));
|
||||
}
|
||||
self.mark_tool_settings_current();
|
||||
}
|
||||
|
||||
/// Record that [`Self::tool_settings`], when any is stored, is in this version's form.
|
||||
pub(crate) fn mark_tool_settings_current(&mut self) {
|
||||
if !self.tool_settings.is_empty() {
|
||||
self.tool_settings_version = self.tool_settings_version.max(TOOL_SETTINGS_VERSION);
|
||||
}
|
||||
}
|
||||
|
||||
/// The `document.open` / place params `p` with `embeddedFonts: false` added when Preferences
|
||||
/// › File Handling › Use fonts embedded in imported PDFs is off and `p` gives no choice of its own.
|
||||
pub fn with_pdf_font_choice(&self, p: &serde_json::Value) -> serde_json::Value {
|
||||
@@ -672,6 +707,7 @@ impl Default for Prefs {
|
||||
use_registration_point_for_symbol: false,
|
||||
show_on_shape_creation: false,
|
||||
tool_settings: Default::default(),
|
||||
tool_settings_version: 0,
|
||||
perspective_presets: vec![],
|
||||
blend_options: None,
|
||||
perspective_widget: Default::default(),
|
||||
|
||||
@@ -49,6 +49,9 @@
|
||||
//! `No active document`.
|
||||
//! - Assigning `Document.selection` takes one object, a list of them, `null` or `[]`; every object
|
||||
//! must be one of that document's that can be selected, or nothing changes. `undefined` throws.
|
||||
//! - `app.selectTool(name)` takes a tool's id, its label, or a name of the list cited at
|
||||
//! [`TOOL_NAME_PREFIX`], and the tool becomes the current tool when the run ends without an
|
||||
//! error. A run that fails leaves the tool as it was.
|
||||
//! - `controlBounds` is the visible bounds, widened to take in the direction points of every path
|
||||
//! in the object.
|
||||
//! - `Document.views` holds the document's drawn windows ([`crate::Session::window_views`]),
|
||||
@@ -172,7 +175,8 @@ const ARTBOARD_COORDS: &str = "CoordinateSystem.ARTBOARDCOORDINATESYSTEM";
|
||||
/// written yet, how many times each path's points went stale and each path as the run last saw its
|
||||
/// points, whether a call's own savepoint ([`atomically`]) is open, the settings of each
|
||||
/// `DocumentPreset` the run made, with the size of the values they hold now and the most they may
|
||||
/// hold (the run's heap), and the `Variable` and `Dataset` objects it gave out.
|
||||
/// hold (the run's heap), the `Variable` and `Dataset` objects it gave out, and the tool
|
||||
/// `app.selectTool` chose last.
|
||||
#[derive(Default)]
|
||||
pub(super) struct State {
|
||||
coords: Cell<Coords>,
|
||||
@@ -207,6 +211,7 @@ pub(super) struct State {
|
||||
preset_bytes: Cell<u64>,
|
||||
preset_limit: u64,
|
||||
vars: variables::Handles,
|
||||
tool: Cell<Option<&'static str>>,
|
||||
}
|
||||
|
||||
impl State {
|
||||
@@ -219,6 +224,12 @@ impl State {
|
||||
pub(super) fn saving(&self) -> bool {
|
||||
self.saving.get()
|
||||
}
|
||||
|
||||
/// The id of the tool `app.selectTool` chose last in the run, which becomes the current tool
|
||||
/// when the run ends without an error.
|
||||
pub(super) fn chosen_tool(&self) -> Option<&'static str> {
|
||||
self.tool.get()
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `f`, whose commands are kept together or put back together: when `f` fails, every
|
||||
@@ -844,12 +855,24 @@ fn restore_layer(h: &Host, uid: u64, layer: Option<NodeId>, rows: &[NodeId]) ->
|
||||
/// commands changed it (commands given ids select them first), direct-selected anchors, segments,
|
||||
/// ruler guides, slices, the key, a Layers panel target and an object chosen inside a dynamic
|
||||
/// symbol instance or an Objects on Path group included, less the objects that are now deleted,
|
||||
/// hidden or locked.
|
||||
/// hidden or locked. `f`'s commands and the steps that put things back succeed or fail together
|
||||
/// ([`atomically`]): when putting back the selection, the layer or the active document fails, `f`'s
|
||||
/// changes are undone as well.
|
||||
fn on_doc<T>(
|
||||
h: &Host,
|
||||
uid: u64,
|
||||
keep_selection: bool,
|
||||
f: impl FnOnce(&Host) -> std::result::Result<T, HostError>,
|
||||
) -> std::result::Result<T, HostError> {
|
||||
atomically(h, |h| on_doc_steps(h, uid, keep_selection, f))
|
||||
}
|
||||
|
||||
/// The steps of [`on_doc`].
|
||||
fn on_doc_steps<T>(
|
||||
h: &Host,
|
||||
uid: u64,
|
||||
keep_selection: bool,
|
||||
f: impl FnOnce(&Host) -> std::result::Result<T, HostError>,
|
||||
) -> std::result::Result<T, HostError> {
|
||||
let (index, active, before, layer, activated) = {
|
||||
let s = h.session.borrow();
|
||||
@@ -1021,6 +1044,69 @@ fn app_is_open(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(Data::Bool(open))
|
||||
}
|
||||
|
||||
/// The start of the tool names that scripts pass to `app.selectTool`, as the list at
|
||||
/// <https://community.adobe.com/questions-652/what-s-new-in-illustrator-scripting-cc2020-769942> gives them.
|
||||
const TOOL_NAME_PREFIX: &str = "Adobe "; // brand-ok: the start of the tool names scripts pass
|
||||
|
||||
/// The names on that list, without [`TOOL_NAME_PREFIX`], whose words differ from the label of the
|
||||
/// VectorCraft tool they choose, with that tool's id. Names whose words are a VectorCraft tool's
|
||||
/// label (`Pen Tool`) choose that tool without a row here. The pairs are VectorCraft's own.
|
||||
const TOOL_NAMES: &[(&str, &str)] = &[
|
||||
("Select Tool", "selection"),
|
||||
("Direct Select Tool", "directSelection"),
|
||||
("Direct Object Select Tool", "groupSelection"),
|
||||
("Direct Lasso Tool", "lasso"),
|
||||
("Path Type Tool", "typeOnPath"),
|
||||
("Vertical Path Type Tool", "verticalTypeOnPath"),
|
||||
("Line Tool", "lineSegment"),
|
||||
("Shape Construction Regular Polygon Tool", "polygon"),
|
||||
("Shape Construction Star Tool", "star"),
|
||||
("Shape Construction Spiral Tool", "spiral"),
|
||||
("Brush Tool", "paintbrush"),
|
||||
("Freehand Tool", "pencil"),
|
||||
("Freehand Smooth Tool", "smooth"),
|
||||
("Freehand Erase Tool", "pathEraser"),
|
||||
("Corner Join Tool", "join"),
|
||||
("Knife Tool", "knife"),
|
||||
("New Twirl Tool", "twirl"),
|
||||
("Cyrstallize Tool", "crystallize"),
|
||||
("Planar Paintbucket Tool", "livePaintBucket"),
|
||||
("Planar Face Select Tool", "livePaintSelection"),
|
||||
("Mesh Editing Tool", "mesh"),
|
||||
("Gradient Vector Tool", "gradient"),
|
||||
("Crop Tool", "artboard"),
|
||||
("Slice Select Tool", "sliceSelection"),
|
||||
("Scroll Tool", "hand"),
|
||||
("Page Tool", "printTiling"),
|
||||
];
|
||||
|
||||
/// The id of the tool `name` names: a tool's id (`pen`), its label (`Pen Tool`), or a name of the
|
||||
/// list [`TOOL_NAME_PREFIX`] cites.
|
||||
fn tool_named(name: &str) -> Option<&'static str> {
|
||||
let tools = || vectorcraft_tools::catalog::all_tools();
|
||||
if let Some(t) = tools().find(|t| t.id == name || t.label == name) {
|
||||
return Some(t.id);
|
||||
}
|
||||
let rest = name.strip_prefix(TOOL_NAME_PREFIX)?;
|
||||
if let Some((_, id)) = TOOL_NAMES.iter().find(|(n, _)| *n == rest) {
|
||||
return vectorcraft_tools::tool_info(id).map(|t| t.id);
|
||||
}
|
||||
tools().find(|t| t.label == rest).map(|t| t.id)
|
||||
}
|
||||
|
||||
/// `app.selectTool(name)`: chooses the tool `name` names ([`tool_named`]) and gives `true`. The
|
||||
/// tool becomes the current tool when the run ends without an error, as a choice on the toolbar
|
||||
/// does; the tool chosen last in a run is the one that counts. A name no tool has throws.
|
||||
fn app_select_tool(h: &Host, a: &[Data]) -> Answer {
|
||||
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("selectTool needs a tool name, as a string".into())) };
|
||||
if name.len() > MAX_TEXT_BYTES {
|
||||
return Err(HostError::Range("the tool name is too long".into()));
|
||||
}
|
||||
let id = tool_named(name).ok_or_else(|| HostError::Error(format!("No tool is named \"{name}\"")))?;
|
||||
h.dom.tool.set(Some(id));
|
||||
Ok(Data::Bool(true))
|
||||
}
|
||||
|
||||
/// The menu command strings `app.executeMenuCommand` takes, each with the command it runs. The
|
||||
/// strings are the ones
|
||||
/// <https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510>
|
||||
@@ -2224,9 +2310,9 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer {
|
||||
if !(0.0..=100.0).contains(&v) {
|
||||
return Err(HostError::Range("opacity must be from 0 to 100".into()));
|
||||
}
|
||||
// A value the getter reports for the item's opacity sends the opacity it has, and
|
||||
// `object.setProps` finds the no-op itself: an opacity a graph mark or label already has still
|
||||
// replaces the one the graph keeps for its series or kind.
|
||||
// A value the getter reports for the item's opacity runs no command, unless the item is a graph
|
||||
// mark or label whose graph keeps another opacity for its series or kind: then the opacity the
|
||||
// item has is sent, and replaces the one the graph keeps.
|
||||
// The opacity the item already has may be assigned while its layer is hidden or locked, unless
|
||||
// it would still replace the opacity a graph keeps for the item's series or kind.
|
||||
let (now, keeps_other) = with_doc(h, item.doc, |_, st| {
|
||||
@@ -2240,7 +2326,7 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer {
|
||||
if now.is_none() || keeps_other {
|
||||
refuse_protected_edit(h, item)?;
|
||||
}
|
||||
set_props(h, a, |_| false, json!({"opacity": now.unwrap_or(v)}))
|
||||
set_props(h, a, |_| now.is_some() && !keeps_other, json!({"opacity": now.unwrap_or(v)}))
|
||||
}
|
||||
|
||||
/// The members of `BlendModes` with the blend mode each one names.
|
||||
@@ -2842,6 +2928,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
("coordinateSystem", property(l, app_coords, app_set_coords), typed("CoordinateSystem")),
|
||||
("getIsFileOpen", method(l, app_is_open), returns("boolean", &[("filePath", "string")])),
|
||||
("redraw", method(l, app_redraw), returns("undefined", &[])),
|
||||
("selectTool", method(l, app_select_tool), returns("boolean", &[("toolName", "string")])),
|
||||
("undo", method(l, app_undo), returns("undefined", &[])),
|
||||
("redo", method(l, app_redo), returns("undefined", &[])),
|
||||
("executeMenuCommand", method(l, app_menu_command), returns("undefined", &[("menuCommandString", "string")])),
|
||||
|
||||
@@ -2647,7 +2647,15 @@ impl Session {
|
||||
o.insert("unhandledRejectionCount".into(), json!(job.realm.unhandled_rejection_count()));
|
||||
}
|
||||
close_run(self, host, &mut report, console::Ending::Finished);
|
||||
let tool = host.dom.chosen_tool();
|
||||
self.end_job(job, false);
|
||||
// The tool `app.selectTool` chose last becomes the current tool, as a choice on the
|
||||
// toolbar makes it; the run's changes are kept when the tool cannot be chosen.
|
||||
if let Some(id) = tool
|
||||
&& let Err(e) = self.select_tool(id, self.last_view)
|
||||
{
|
||||
report["toolError"] = json!(e.to_string());
|
||||
}
|
||||
self.script_report = Some(report.clone());
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
@@ -219,6 +219,52 @@ fn read_past_cap(path: &Path, max: u64) -> std::io::Result<Vec<u8>> {
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
/// What [`read_capped_plain`] tells a path that is not a plain file.
|
||||
pub(crate) const NOT_PLAIN: &str = "not a plain file";
|
||||
|
||||
/// The content of `path` when it is a plain file of at most `max` bytes. The file is opened without
|
||||
/// following a link at `path` (on Windows a junction or other reparse point is opened itself), and
|
||||
/// its kind and bytes are read from that open file, so a link put at `path` after an earlier check
|
||||
/// is refused with [`NOT_PLAIN`] rather than read.
|
||||
pub(crate) fn read_capped_plain(path: &Path, max: u64) -> Result<Vec<u8>, String> {
|
||||
let file = open_no_link(path).map_err(|e| match std::fs::symlink_metadata(path) {
|
||||
Ok(m) if !m.file_type().is_file() || reparse_point(&m) => NOT_PLAIN.to_string(),
|
||||
_ => e.to_string(),
|
||||
})?;
|
||||
let m = file.metadata().map_err(|e| e.to_string())?;
|
||||
if !m.file_type().is_file() || reparse_point(&m) {
|
||||
return Err(NOT_PLAIN.to_string());
|
||||
}
|
||||
let mut bytes = vec![];
|
||||
file.take(max + 1).read_to_end(&mut bytes).map_err(|e| e.to_string())?;
|
||||
if bytes.len() as u64 > max {
|
||||
return Err(too_large(max));
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
/// `path` opened for reading, without following a link there. A pipe put in its place does not hold
|
||||
/// the open up.
|
||||
#[cfg(unix)]
|
||||
fn open_no_link(path: &Path) -> std::io::Result<std::fs::File> {
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
let flags = rustix::fs::OFlags::NOFOLLOW | rustix::fs::OFlags::NONBLOCK;
|
||||
std::fs::OpenOptions::new().read(true).custom_flags(flags.bits() as i32).open(path)
|
||||
}
|
||||
|
||||
/// `path` opened for reading; a link or junction there is opened itself, not its target.
|
||||
#[cfg(windows)]
|
||||
fn open_no_link(path: &Path) -> std::io::Result<std::fs::File> {
|
||||
use std::os::windows::fs::OpenOptionsExt;
|
||||
const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x0020_0000;
|
||||
std::fs::OpenOptions::new().read(true).custom_flags(FILE_FLAG_OPEN_REPARSE_POINT).open(path)
|
||||
}
|
||||
|
||||
#[cfg(not(any(unix, windows)))]
|
||||
fn open_no_link(path: &Path) -> std::io::Result<std::fs::File> {
|
||||
std::fs::File::open(path)
|
||||
}
|
||||
|
||||
/// Plug-ins loading on worker threads, which [`Session::poll_plugin_loads`] and
|
||||
/// [`Session::finish_plugin_loads`] install.
|
||||
pub(crate) enum PluginLoad {
|
||||
|
||||
@@ -913,6 +913,77 @@ fn brush_options_rename_duplicate_and_delete_update_strokes() {
|
||||
assert!(s.execute("brush.delete", &json!({"name": "5 pt. Round"})).is_err());
|
||||
}
|
||||
|
||||
/// `brush.options` that leaves the brush as it is changes neither the document nor its revision,
|
||||
/// and records no undo step, whether the library is stored or still the defaults.
|
||||
#[test]
|
||||
fn brush_options_that_change_nothing_record_no_undo_step() {
|
||||
let mut s = session();
|
||||
let state = |s: &Session| {
|
||||
let st = s.doc().unwrap();
|
||||
(st.doc.clone(), st.revision, st.history.undo.len())
|
||||
};
|
||||
let before = state(&s);
|
||||
s.execute("brush.options", &json!({"name": "Arrow", "params": {}})).unwrap();
|
||||
assert_eq!(state(&s), before, "unchanged options of a default library change nothing");
|
||||
s.execute("brush.options", &json!({"name": "Arrow", "params": {"width": 110.25}})).unwrap();
|
||||
assert_eq!(undo_steps(&s), before.2 + 1, "a changed option is one undo step");
|
||||
let before = state(&s);
|
||||
for p in [
|
||||
json!({"name": "Arrow"}),
|
||||
json!({"name": "Arrow", "params": {}}),
|
||||
json!({"name": "Arrow", "params": {"width": 110.25}}),
|
||||
json!({"name": "Arrow", "newName": " Arrow "}),
|
||||
json!({"name": "Arrow", "newName": ""}),
|
||||
] {
|
||||
assert_eq!(s.execute("brush.options", &p).unwrap()["name"], "Arrow");
|
||||
assert_eq!(state(&s), before, "{p} changes nothing");
|
||||
}
|
||||
s.execute("brush.options", &json!({"name": "Arrow", "newName": "Arrow 2"})).unwrap();
|
||||
assert_eq!(undo_steps(&s), before.2 + 1, "a rename is one undo step");
|
||||
}
|
||||
|
||||
/// `brush.apply` of the brush that the strokes and the current brush already have changes neither
|
||||
/// the document nor its revision, and records no undo step.
|
||||
#[test]
|
||||
fn brush_apply_that_changes_nothing_records_no_undo_step() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 10.0, 10.0, 50.0, 50.0);
|
||||
let state = |s: &Session| {
|
||||
let st = s.doc().unwrap();
|
||||
(st.doc.clone(), st.revision, st.history.undo.len())
|
||||
};
|
||||
let before = state(&s);
|
||||
s.execute("brush.apply", &json!({"name": "Charcoal", "ids": [a.0]})).unwrap();
|
||||
assert_eq!(undo_steps(&s), before.2 + 1);
|
||||
let before = state(&s);
|
||||
s.execute("brush.apply", &json!({"name": "Charcoal", "ids": [a.0]})).unwrap();
|
||||
assert_eq!(state(&s), before, "applying the brush again changes nothing");
|
||||
s.execute("brush.setCurrent", &json!({"name": "Arrow"})).unwrap();
|
||||
s.execute("brush.apply", &json!({"name": "Charcoal", "ids": [a.0]})).unwrap();
|
||||
assert_eq!(undo_steps(&s), before.2 + 1, "making the brush current again is one undo step");
|
||||
assert_eq!(s.execute("brush.list", &json!({})).unwrap()["current"], "Charcoal");
|
||||
let b = rect(&mut s, 80.0, 10.0, 50.0, 50.0);
|
||||
let steps = undo_steps(&s);
|
||||
s.execute("brush.apply", &json!({"name": "Charcoal", "ids": [a.0, b.0]})).unwrap();
|
||||
assert_eq!((brush_of(&s, a).as_deref(), brush_of(&s, b).as_deref()), (Some("Charcoal"), Some("Charcoal")));
|
||||
assert_eq!(undo_steps(&s), steps + 1, "a new stroke to paint is one undo step");
|
||||
}
|
||||
|
||||
/// Applying the current brush again to a stroke with settings of its own clears them as one undo step.
|
||||
#[test]
|
||||
fn brush_apply_clears_object_options_as_one_undo_step() {
|
||||
let mut s = session();
|
||||
let a = line(&mut s);
|
||||
select(&mut s, &[a]);
|
||||
s.execute("brush.apply", &json!({"name": "Arrow"})).unwrap();
|
||||
s.execute("brush.objectOptions", &json!({"params": {"width": 50}})).unwrap();
|
||||
assert_eq!(own_options(&s, a), json!({"width": 50.0}));
|
||||
let steps = undo_steps(&s);
|
||||
s.execute("brush.apply", &json!({"name": "Arrow"})).unwrap();
|
||||
assert_eq!(own_options(&s, a), json!({}), "applying the brush clears the stroke's own settings");
|
||||
assert_eq!(undo_steps(&s), steps + 1, "clearing the settings is one undo step");
|
||||
}
|
||||
|
||||
/// A document whose brushes repeat a name opens with the later brush numbered: strokes of the name
|
||||
/// keep the first brush, and renaming or deleting one brush leaves the other and its strokes alone.
|
||||
#[test]
|
||||
|
||||
@@ -1753,7 +1753,8 @@ fn shape_builder_swatches_keep_the_current_fill_and_the_first_covered_objects_lo
|
||||
}
|
||||
|
||||
/// The Shape Builder tool sends the point where the drag started first and the point where it
|
||||
/// ended last, so a drag from the hole into the square takes the square's look.
|
||||
/// ended last, so with Pick Color From Artwork a drag from the hole into the square takes the
|
||||
/// square's look.
|
||||
#[test]
|
||||
fn shape_builder_tool_drag_from_the_hole_takes_the_look_where_it_ends() {
|
||||
let mut s = session();
|
||||
@@ -1762,6 +1763,7 @@ fn shape_builder_tool_drag_from_the_hole_takes_the_look_where_it_ends() {
|
||||
select_ids(&mut s, &bars.iter().copied().chain([red]).collect::<Vec<_>>());
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool("shapeBuilder", v).unwrap();
|
||||
s.set_tool_option_cmd(&json!({"tool": "shapeBuilder", "values": {"pickColorFrom": "artwork"}})).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 50.0, 50.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 85.0, 50.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 120.0, 50.0), v).unwrap();
|
||||
@@ -1853,6 +1855,7 @@ fn shape_builder_arrow_keys_step_the_current_fill_through_the_swatches() {
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool("shapeBuilder", v).unwrap();
|
||||
let chips = |s: &mut Session| s.overlays(v).iter().filter(|o| matches!(o, vectorcraft_tools::Overlay::Swatch { .. })).count();
|
||||
s.set_tool_option_cmd(&json!({"tool": "shapeBuilder", "values": {"pickColorFrom": "artwork"}})).unwrap();
|
||||
assert!(!s.tool_claims_key(ToolKey::Right, v), "Artwork leaves the arrows to nudging");
|
||||
let values = json!({"pickColorFrom": "swatches", "cursorSwatchPreview": true});
|
||||
s.set_tool_option_cmd(&json!({"tool": "shapeBuilder", "values": values})).unwrap();
|
||||
@@ -2071,6 +2074,31 @@ fn shape_builder_fill_preview_is_put_back_by_a_cancel() {
|
||||
assert_eq!(s.paint.fill, before, "the cancel puts the fill back");
|
||||
}
|
||||
|
||||
/// With the Shape Builder's default options, a fill picked while it is active (a swatch or a
|
||||
/// color) fills the next merge: the tool sends `pickColorFrom: "swatches"`, and the merged shape
|
||||
/// is not the red or blue of the art.
|
||||
#[test]
|
||||
fn shape_builder_default_merge_fills_with_the_picked_fill() {
|
||||
let v = ViewInfo::default();
|
||||
for pick in [json!({"swatch": "Leaf"}), json!({"color": "#ff8800"})] {
|
||||
let mut s = session();
|
||||
two(&mut s);
|
||||
s.execute("swatch.new", &json!({"name": "Leaf", "color": "#00ff00"})).unwrap();
|
||||
s.select_tool("shapeBuilder", v).unwrap();
|
||||
s.execute("paint.setFill", &pick).unwrap();
|
||||
let picked = s.paint.fill.clone();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 25.0, 50.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 75.0, 50.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 125.0, 50.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 125.0, 50.0), v).unwrap();
|
||||
let (cmd, params) = s.journal.last().unwrap().clone();
|
||||
assert_eq!((cmd.as_str(), ¶ms["pickColorFrom"]), ("shapeBuilder.merge", &json!("swatches")), "{pick}");
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let fills: Vec<Paint> = d.children(d.default_layer()).into_iter().flatten().map(|n| n.appearance.fill_paint()).collect();
|
||||
assert_eq!(fills, vec![picked], "{pick}: the two squares merged into one shape with the picked fill");
|
||||
}
|
||||
}
|
||||
|
||||
/// With Pick Color From Color Swatches, a merge fills with the fill chosen while the Shape Builder
|
||||
/// is active, and the Gradient panel's eyedropper samples into a stop of that fill's gradient.
|
||||
#[test]
|
||||
|
||||
@@ -155,6 +155,27 @@ fn page_item_size_setters_on_a_rotated_object_give_the_page_aligned_size() {
|
||||
assert_eq!(format!("{:?}", s.active().unwrap().doc.node(b)), other, "the other object stays as it was");
|
||||
}
|
||||
|
||||
/// `controlBounds` holds a curve's handles, which reach past the curve; for a rectangle it is the
|
||||
/// visible bounds.
|
||||
#[test]
|
||||
fn control_bounds_hold_the_handles_of_a_curve() {
|
||||
let (mut s, _, _) = doc();
|
||||
s.execute("path.create", &json!({"d": "M100 200 C100 100 200 100 200 200"})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var p = app.activeDocument.pageItems, c = p[0], r = p[1];\
|
||||
function h(b) { return b[1] - b[3]; }\
|
||||
vc.log([h(c.visibleBounds), h(c.controlBounds), c.controlBounds[0] <= c.visibleBounds[0]]);\
|
||||
vc.log(String(r.controlBounds) === String(r.visibleBounds));",
|
||||
);
|
||||
let heights = out[0].as_array().unwrap();
|
||||
let (visible, control) = (heights[0].as_f64().unwrap(), heights[1].as_f64().unwrap());
|
||||
// The curve rises 75 pt and its handles 100 pt; half the stroke's weight reaches above the curve.
|
||||
assert!(control - visible > 20.0 && control - visible <= 25.0 + 1e-6, "{out:?}");
|
||||
assert_eq!(heights[2], json!(true), "{out:?}");
|
||||
assert_eq!(out[1], json!(true), "{out:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convert_coordinate_pair_is_inverse_and_y_up() {
|
||||
let mut s = Session::new();
|
||||
@@ -500,6 +521,7 @@ fn assigning_the_reported_opacity_changes_nothing() {
|
||||
assert_eq!(out, vec![json!(33.3333)]);
|
||||
assert_eq!(s.active().unwrap().doc.node(a).unwrap().opacity, before);
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
assert_eq!(s.script_report().unwrap()["slowestCommands"], json!([]), "the assignment runs no command");
|
||||
// A value close to the reported one but not equal to it is still applied.
|
||||
s.execute("object.setProps", &json!({"id": a.0, "opacity": 50})).unwrap();
|
||||
let (before, steps) = (s.active().unwrap().doc.node(a).unwrap().opacity, undo_steps(&s));
|
||||
@@ -560,6 +582,14 @@ fn selection_assignment_is_atomic_across_invalid_items() {
|
||||
let e = failure(&mut s, "var p = app.activeDocument.pageItems; app.activeDocument.selection = [p[0], p[1]];");
|
||||
assert!(e.contains("Cannot select PathItem"), "{e}");
|
||||
assert!(s.active().unwrap().selection.objects.is_empty());
|
||||
// With the valid item first and the error caught, the run sees the selection unchanged.
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, p = d.pageItems; try { d.selection = [p[1], p[0]]; vc.log('assigned'); }\
|
||||
catch (e) { vc.log(String(e).indexOf('Cannot select PathItem') >= 0); } vc.log(d.selection.length);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(true), json!(0)]);
|
||||
assert!(s.active().unwrap().selection.objects.is_empty());
|
||||
s.execute("object.setProps", &json!({"ids": [b.0], "locked": false})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
@@ -2116,6 +2146,35 @@ fn prototype_changes_cannot_forge_a_page_item() {
|
||||
assert_eq!(s.active().unwrap().doc.node(a).unwrap().name, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn select_tool_makes_the_named_tool_current_when_the_run_ends() {
|
||||
let (mut s, _, _) = doc();
|
||||
assert_eq!(s.tool_id(), "selection");
|
||||
// A tool's id, its label and a name in the form scripts pass all choose it; the last one counts.
|
||||
assert_eq!(log(&mut s, "vc.log(app.selectTool('pen'));"), vec![json!(true)]);
|
||||
assert_eq!(s.tool_id(), "pen");
|
||||
log(&mut s, "app.selectTool('Rectangle Tool');");
|
||||
assert_eq!(s.tool_id(), "rectangle");
|
||||
log(&mut s, "app.selectTool('Adobe Ellipse Tool'); app.selectTool('Adobe Direct Select Tool');");
|
||||
assert_eq!(s.tool_id(), "directSelection");
|
||||
log(&mut s, "app.selectTool('Adobe Select Tool');");
|
||||
assert_eq!(s.tool_id(), "selection");
|
||||
// An unknown name throws, a caught error chooses nothing, and a run that fails leaves the tool.
|
||||
assert!(failure(&mut s, "app.selectTool('No Such Tool');").contains("No tool is named \"No Such Tool\""));
|
||||
assert!(failure(&mut s, "app.selectTool('Adobe ');").contains("No tool is named"));
|
||||
let out = log(&mut s, "try { app.selectTool('pencil tool'); } catch (e) { vc.log(e.message); }");
|
||||
assert_eq!(out, vec![json!("No tool is named \"pencil tool\"")]);
|
||||
assert!(failure(&mut s, "app.selectTool('pen'); throw new Error('stop');").contains("stop"));
|
||||
let out = log(&mut s, "try { app.selectTool(5); } catch (e) { vc.log(e.name); }");
|
||||
assert_eq!(out, vec![json!("TypeError")]);
|
||||
assert!(failure(&mut s, "app.selectTool(new Array(5000).join('a'));").contains("too long"));
|
||||
assert_eq!(s.tool_id(), "selection");
|
||||
// With no document open the tool is chosen too.
|
||||
let mut empty = Session::new();
|
||||
log(&mut empty, "app.selectTool('Adobe Freehand Tool');");
|
||||
assert_eq!(empty.tool_id(), "pencil");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_members_say_so() {
|
||||
let (mut s, _, _) = doc();
|
||||
@@ -2340,6 +2399,9 @@ fn a_collection_read_with_a_name_gives_the_named_object() {
|
||||
vc.log(m);",
|
||||
);
|
||||
assert_eq!(out, vec![json!([true, "n", true, false, true]), json!([true, true, false]), json!(["Not found", "Not found"])]);
|
||||
// A name the collection inherits is not looked up as an object's name when it is assigned.
|
||||
let out = log(&mut s, "Object.prototype.tag = 1; var p = app.activeDocument.pageItems; p.tag = 2; vc.log(p.tag);");
|
||||
assert_eq!(out, vec![json!(1)]);
|
||||
}
|
||||
|
||||
/// A collection read with a name that is the text of a number but not an array index, such as `-1`
|
||||
|
||||
@@ -157,6 +157,24 @@ fn a_write_reads_the_file_it_replaces_only_one_byte_past_the_new_length() {
|
||||
assert!(holds(&[][..], &[]));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_plain_capped_read_refuses_a_link_and_reads_a_plain_file() {
|
||||
use crate::store::{NOT_PLAIN, read_capped_plain};
|
||||
let root = fresh_dir("plain-read");
|
||||
let target = root.join("target.bin");
|
||||
std::fs::write(&target, b"outside").unwrap();
|
||||
let link = root.join("profile.vectorcraft");
|
||||
std::os::unix::fs::symlink(&target, &link).unwrap();
|
||||
assert_eq!(read_capped_plain(&link, 100), Err(NOT_PLAIN.to_string()));
|
||||
let folder = root.join("folder");
|
||||
std::fs::create_dir(&folder).unwrap();
|
||||
assert_eq!(read_capped_plain(&folder, 100), Err(NOT_PLAIN.to_string()));
|
||||
assert_eq!(read_capped_plain(&target, 100), Ok(b"outside".to_vec()));
|
||||
assert_eq!(read_capped_plain(&target, 7), Ok(b"outside".to_vec()));
|
||||
assert!(read_capped_plain(&target, 6).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_saved_preset_replaces_an_oversized_file_in_its_place() {
|
||||
let root = fresh_dir("oversized-put");
|
||||
|
||||
@@ -698,3 +698,55 @@ fn a_parametric_shape_kind_and_its_values_set_together() {
|
||||
assert_eq!(s.tool_options_of("parametricShape")["kind"], json!("star"), "a refused call sets nothing");
|
||||
}
|
||||
}
|
||||
|
||||
/// The Shape Builder picks colors from the color swatches by default: a fresh session, and saved
|
||||
/// preferences that hold other Shape Builder options but no `pickColorFrom`, give `swatches`.
|
||||
/// Preferences saved without `toolSettingsVersion` read a saved `artwork` as `swatches` once and
|
||||
/// are then written with the version, so a later `artwork` is kept. A saved `swatches` is kept.
|
||||
#[test]
|
||||
fn shape_builder_pick_color_from_defaults_to_swatches_and_migrates_a_saved_artwork_once() {
|
||||
let mut s = session();
|
||||
select(&mut s, "shapeBuilder");
|
||||
assert_eq!(s.tool_options()["pickColorFrom"], json!("swatches"), "a fresh session");
|
||||
select(&mut s, "selection");
|
||||
assert_eq!(s.prefs.to_json()["toolSettingsVersion"], json!(1), "stored settings are written with the version");
|
||||
let load = |version: Option<u32>, saved: &Value| {
|
||||
let mut prefs = Prefs::default().to_json();
|
||||
prefs["toolSettings"] = json!({ "shapeBuilder": saved });
|
||||
let fields = prefs.as_object_mut().unwrap();
|
||||
match version {
|
||||
Some(v) => fields.insert("toolSettingsVersion".into(), json!(v)),
|
||||
None => fields.remove("toolSettingsVersion"),
|
||||
};
|
||||
let mut next = session();
|
||||
next.apply_prefs(serde_json::from_str(&prefs.to_string()).unwrap());
|
||||
next
|
||||
};
|
||||
for (version, saved, want) in [
|
||||
(None, json!({"highlightFill": false}), "swatches"),
|
||||
(None, json!({"pickColorFrom": "artwork"}), "swatches"),
|
||||
(None, json!({"pickColorFrom": "swatches"}), "swatches"),
|
||||
(Some(1), json!({"pickColorFrom": "artwork"}), "artwork"),
|
||||
(Some(1), json!({"pickColorFrom": "swatches"}), "swatches"),
|
||||
(Some(1), json!({"highlightFill": false}), "swatches"),
|
||||
] {
|
||||
let mut next = load(version, &saved);
|
||||
assert_eq!(next.prefs.tool_settings_version, 1, "the version is written: {version:?} {saved}");
|
||||
select(&mut next, "shapeBuilder");
|
||||
assert_eq!(next.tool_options()["pickColorFrom"], json!(want), "saved {version:?} {saved}");
|
||||
select(&mut next, "selection");
|
||||
assert_eq!(next.prefs.tool_settings["shapeBuilder"]["pickColorFrom"], json!(want), "stored again: {version:?} {saved}");
|
||||
}
|
||||
// Artwork picked after the update, or in a session that started without saved settings, is
|
||||
// kept at the next launch.
|
||||
for mut next in [load(None, &json!({"pickColorFrom": "artwork"})), session()] {
|
||||
select(&mut next, "shapeBuilder");
|
||||
next.set_tool_option("pickColorFrom", &json!("artwork"));
|
||||
select(&mut next, "selection");
|
||||
let saved_text = serde_json::to_string(&next.prefs).unwrap();
|
||||
let mut later = session();
|
||||
later.apply_prefs(serde_json::from_str(&saved_text).unwrap());
|
||||
select(&mut later, "shapeBuilder");
|
||||
assert_eq!(later.tool_options()["pickColorFrom"], json!("artwork"), "picked after the update: {saved_text}");
|
||||
}
|
||||
}
|
||||
@@ -581,6 +581,7 @@ impl Session {
|
||||
}
|
||||
}
|
||||
}
|
||||
prefs.mark_tool_settings_current();
|
||||
}
|
||||
|
||||
/// Keep the active tool's persistent options for the next time it, or a tool sharing them, is
|
||||
|
||||
Reference in new issue
Block a user